awacke1 commited on
Commit
43f31cf
·
verified ·
1 Parent(s): a8b86a3

Create gamestate.py

Browse files
Files changed (1) hide show
  1. gamestate.py +64 -0
gamestate.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Ensure the save directory exists
11
+ os.makedirs(save_dir, exist_ok=True)
12
+ self.csv_path = os.path.join(save_dir, csv_filename)
13
+ self.lock = threading.Lock()
14
+ self.world_state = [] # List of dicts representing game objects
15
+ self.last_update_time = time.time()
16
+ self.load_state() # Optionally load state from CSV on startup
17
+
18
+ def load_state(self):
19
+ """Load world state from CSV if available."""
20
+ if os.path.exists(self.csv_path):
21
+ try:
22
+ df = pd.read_csv(self.csv_path)
23
+ # Convert DataFrame rows to a list of dictionaries
24
+ self.world_state = df.to_dict(orient='records')
25
+ except Exception as e:
26
+ print(f"Error loading state from {self.csv_path}: {e}")
27
+ else:
28
+ self.world_state = []
29
+
30
+ def save_state(self):
31
+ """Persist the current world state to CSV."""
32
+ with self.lock:
33
+ try:
34
+ df = pd.DataFrame(self.world_state)
35
+ df.to_csv(self.csv_path, index=False)
36
+ except Exception as e:
37
+ print(f"Error saving state to {self.csv_path}: {e}")
38
+
39
+ def get_state(self):
40
+ """Return a deep copy of the current world state."""
41
+ with self.lock:
42
+ # Use JSON serialization to create a deep copy.
43
+ return json.loads(json.dumps(self.world_state))
44
+
45
+ def update_state(self, new_objects):
46
+ """
47
+ Merge new or updated objects into the world state.
48
+ Each object must have a unique 'obj_id'.
49
+ """
50
+ with self.lock:
51
+ for obj in new_objects:
52
+ found = False
53
+ for existing in self.world_state:
54
+ if existing.get('obj_id') == obj.get('obj_id'):
55
+ # Update the existing object's properties
56
+ existing.update(obj)
57
+ found = True
58
+ break
59
+ if not found:
60
+ # Add new object if it doesn't exist already
61
+ self.world_state.append(obj)
62
+ self.last_update_time = time.time()
63
+ # Optionally, persist the state to CSV after each update.
64
+ self.save_state()