awacke1 commited on
Commit
ad3f401
·
verified ·
1 Parent(s): 2e2f5fb

Update gamestate.py

Browse files
Files changed (1) hide show
  1. gamestate.py +30 -38
gamestate.py CHANGED
@@ -1,64 +1,56 @@
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()
 
1
  # gamestate.py
2
  import threading
 
3
  import os
4
  import json
5
+ import time
6
 
7
  class GameState:
8
+ def __init__(self, state_file="global_state.json"):
9
+ self.state_file = state_file
 
 
10
  self.lock = threading.Lock()
11
+ # The state dictionary holds all game objects.
12
+ # You could later add other keys (for example, player positions per session).
13
+ self.state = {"objects": []}
14
+ self.load_state()
15
 
16
  def load_state(self):
17
+ """Load the global state from a JSON file if it exists."""
18
+ if os.path.exists(self.state_file):
19
  try:
20
+ with open(self.state_file, "r", encoding="utf-8") as f:
21
+ self.state = json.load(f)
 
22
  except Exception as e:
23
+ print(f"Error loading global state: {e}")
24
  else:
25
+ self.state = {"objects": []}
26
 
27
  def save_state(self):
28
+ """Persist the global state to a JSON file."""
29
  with self.lock:
30
  try:
31
+ with open(self.state_file, "w", encoding="utf-8") as f:
32
+ json.dump(self.state, f, indent=2)
33
  except Exception as e:
34
+ print(f"Error saving global state: {e}")
35
 
36
  def get_state(self):
37
+ """Return a copy of the current state."""
38
  with self.lock:
39
+ return self.state.copy()
 
40
 
41
  def update_state(self, new_objects):
42
  """
43
+ Merge a list of new object records into the state.
44
+ Uniqueness is determined by the 'obj_id' field.
45
  """
46
  with self.lock:
47
+ # Create a dict of existing objects by obj_id.
48
+ existing = {obj["obj_id"]: obj for obj in self.state.get("objects", []) if "obj_id" in obj}
49
  for obj in new_objects:
50
+ # If no obj_id, generate one.
51
+ if "obj_id" not in obj or not obj["obj_id"]:
52
+ obj["obj_id"] = str(time.time()) + "_" + str(len(existing))
53
+ existing[obj["obj_id"]] = obj
54
+ self.state["objects"] = list(existing.values())
55
+ self.state["last_updated"] = time.strftime("%Y-%m-%d %H:%M:%S")
56
+ self.save_state()