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