fix: replace DELETE+INSERT with INSERT OR REPLACE and wrap game loop in try-except to prevent unique key crashes on duplicate nicknames

This commit is contained in:
retoor 2025-10-04 19:15:02 +00:00
parent f52cc992be
commit 8441695d0a
2 changed files with 16 additions and 14 deletions

View File

@ -50,12 +50,10 @@ class Database:
def save_game_state(self, game_state):
"""Save complete game state to database"""
with self._get_connection() as conn:
# Save players
conn.execute('DELETE FROM players')
# Save players using INSERT OR REPLACE to handle existing nicknames
for player in game_state.players.values():
conn.execute('''
INSERT INTO players (player_id, nickname, money, population, color, last_online)
INSERT OR REPLACE INTO players (player_id, nickname, money, population, color, last_online)
VALUES (?, ?, ?, ?, ?, ?)
''', (
player.player_id,

View File

@ -20,16 +20,20 @@ database = Database()
async def game_loop():
"""Main game loop: economy ticks every 10 seconds, DB save every 10 seconds"""
while True:
await asyncio.sleep(10)
# Economy tick
economy_engine.tick()
# Save to database
database.save_game_state(game_state)
# Broadcast state to all players
await ws_manager.broadcast_game_state(game_state.get_state())
try:
await asyncio.sleep(10)
# Economy tick
economy_engine.tick()
# Save to database
database.save_game_state(game_state)
# Broadcast state to all players
await ws_manager.broadcast_game_state(game_state.get_state())
except Exception as e:
print(f"Error in game loop: {e}")
# Continue running even if there's an error
@asynccontextmanager
async def lifespan(app: FastAPI):