Whenever you're dealing with a game where multiple players on their own machine are playing the same game (i.e. the same game "session", if you will), the easiest approach is always to play the game on the server (i.e. the backend), and have the players' machine (i.e. the webpage they are on, the frontend) merely represent the state of the game on the server and decide the UI based on the server game's state.
Your situation is perfect for this approach.
Now I can't (and won't) write the whole thing for you, but I'll help you get started on the basics.
I strongly suggest adding an turnOrder
field to usersPlaying
, to keep track of whose turn it is next. If you're using a database, you're not always guaranteed to get the data with the same order, unless you specifically tell the database to order the data.
I would suggest rename userPlaying
in game
to currentTurnOrder
.
Assuming a player set like this:
UserId |
GameId |
TurnOrder |
Andy |
1 |
1 |
Bob |
1 |
2 |
Chris |
1 |
3 |
You can calculate the next turn, and whose turn it is, using the following formula:
$game.CurrentTurnOrder = (($game.CurrentTurnOrder + 1) % $number_of_players) + 1;
To walk you through the formula:
($game.CurrentTurnOrder + 1)
increases the turn counter
% $number_of_players
ensures that when the turn counter goes beyond the amount of players, it loops back to the beginning
- The final
+ 1
is added because %
returns a 0-indexed value, but we've made turnOrder
a 1-indexed value, so + 1 to fix it. If you store your turnOrder
as a 0-indexed value, you don't need to do this step.
If you run this method several times, you will see that $nextTurnOrder
changes value to 1,2,3,1,2,3,1,2,3,... and therefore creating a perfect match with each player's turnOrder
column.
For the sake of example, if you had a list of 5 players, , you will see that $nextTurnOrder
changes value to 1,2,3,4,5,1,2,3,4,5,1,2,..., so you can see that the same formula neatly cycles over all players for any arbitrary amount of players.
So, in order for a given webpage to check if it's their turn, you check the game's current turn order, and see if it matches the local player's TurnOrder
value.
The basic approach on the webpage is as follows:
- Load the initial game data, including this player's
TurnOrder
- Keep checking the game's
CurrentTurnOrder
value
- When the game's
CurrentTurnOrder
matches this player's TurnOrder
, it is this player's turn.