awacke1 commited on
Commit
d564488
·
verified ·
1 Parent(s): 926eeea

Create gamestate.py

Browse files
Files changed (1) hide show
  1. gamestate.py +58 -0
gamestate.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gamestate.py
2
+ import threading
3
+ import time
4
+ import os
5
+ import json
6
+ import pandas as pd
7
+
8
+ class GameState:
9
+ def __init__(self, save_dir="saved_worlds", csv_filename="world_state.csv"):
10
+ os.makedirs(save_dir, exist_ok=True)
11
+ self.csv_path = os.path.join(save_dir, csv_filename)
12
+ self.lock = threading.Lock()
13
+ self.world_state = [] # List of dicts representing game objects
14
+ self.last_update_time = time.time()
15
+ self.load_state()
16
+
17
+ def load_state(self):
18
+ """Load world state from CSV if available."""
19
+ if os.path.exists(self.csv_path):
20
+ try:
21
+ df = pd.read_csv(self.csv_path)
22
+ self.world_state = df.to_dict(orient='records')
23
+ except Exception as e:
24
+ print(f"Error loading state from {self.csv_path}: {e}")
25
+ else:
26
+ self.world_state = []
27
+
28
+ def save_state(self):
29
+ """Persist the current world state to CSV."""
30
+ with self.lock:
31
+ try:
32
+ df = pd.DataFrame(self.world_state)
33
+ df.to_csv(self.csv_path, index=False)
34
+ except Exception as e:
35
+ print(f"Error saving state to {self.csv_path}: {e}")
36
+
37
+ def get_state(self):
38
+ """Return a deep copy of the current world state."""
39
+ with self.lock:
40
+ return json.loads(json.dumps(self.world_state))
41
+
42
+ def update_state(self, new_objects):
43
+ """
44
+ Merge new or updated objects into the world state.
45
+ Each object must have a unique 'obj_id'.
46
+ """
47
+ with self.lock:
48
+ for obj in new_objects:
49
+ found = False
50
+ for existing in self.world_state:
51
+ if existing.get('obj_id') == obj.get('obj_id'):
52
+ existing.update(obj)
53
+ found = True
54
+ break
55
+ if not found:
56
+ self.world_state.append(obj)
57
+ self.last_update_time = time.time()
58
+ self.save_state()