chess
chess copied to clipboard
Persist games into a DB
trafficstars
Let's create a simple postgres table + Prisma for ORM which stores all the game information
- Whenever a new game is started, create an entry in the
gametable - As the users make moves, store it in a
movestable which has a foreign key to thegametable - Add
idsto every created game and add a new event that let's users re-join a game with a given id if their wifi went down/ws conn reset - If a user wants to join a game and there is no
in memoryGame object for it, recover the game from the DB and put it back in memory
On this
INSERT INTO game_table (game_name, start_date, players) VALUES ('New Game', CURRENT_DATE, 'Player 1, Player 2, Player 3');
class Game: def init(self, game_id, name, start_date, players): self.game_id = game_id self.name = name self.start_date = start_date self.players = players
def join_game(game_id, user): # Retrieve game data from the database game_data = database_library.retrieve_game_data(game_id)
if game_data:
# Create a new Game object using the retrieved data
game = Game(game_data['id'], game_data['name'], game_data['start_date'], game_data['players'])
# Add the user to the list of players
game.players.append(user)
# Store the Game object in memory or a data structure
# accessible to your application (e.g., a dictionary)
games[game_id] = game
else:
print("Game not found in the database.")
Example usage
games = {}
join_game(123, "Player 1")