I have a game I’m writing using PHP. For the purposes of my question we can compare my game to “Words with Friends” on the iPhone, for those unfamiliar with the game it is an online/mobile scrabble game. The game consists of 3 major steps:
- 1st two users decide to start a game.
- 2nd, a new row is created within the database table “DATA” which
holds the game data for the two users. - 3rd, and finally, the two are relocated to a new page where they play
the game. When the game is over the row in the “DATA” table is
deleted and wins/losses are saved and reflected in the “USER” table.
Like Words with Friends, a user can have multiple ‘open games’ at any
moment. Meaning they don’t have to finish one game before another is
started.
Background: in the MySQL database I’ll have at least two tables one for generic player data labeled: USER and another to keep the stats of games currently in progress called: DATA. Each user will be given a unique 9-digit ID primary-key when they create an account.
I need some advice on best practices used to accomplish something like this. I had some ideas, fairly primitive in my opinion, they would work but I would like to use something more professional.
One of my ideas was to take the lower number of the two user’s IDs and concatenating it to the beginning of the larger one and save that in the database. An example. We have 2 users: adam and alan. Their IDs are 123456789 and 223456789 respectively. These two start a game which makes a new row in the DATA table where the GAMEID is equal to 123456789223456789. They play halfway through the game and sign out. The next day they try to start a new game. The database checks which user has a smaller ID and concatenates them together to check if a record of a game already exists. It notices the 123456789223456789 game already started and instead of creating a brand new game it brings them back to their game already in progress.
I feel this is certainly over kill and there should be a much easier way around this issue. Please I appreciate and suggestions or tips.
A simple
user_gamestable where you associate games with users would suffice. You can even add a flag for active or a datetime for last active at.Don’t over-complicate this by making up keys that can’t be indexed properly. Indexes are what prevent your table from becoming an unqueryable mess. This table can be queried by
user_idto find their list of games, bygame_idto find the users in a game, or both to find out if a user is present in a game.