Before I start with any code, I want to ensure I have a code/algorithm design that will actually work. My question is how to design code so the following will work (performance wise) with, say, a 500x500 map and 8-10 players.
- My map is going to be split into squares, let’s imagine like a giant chess board for ease of visualization.
- Players’ actions in squares will affect the square where they take the action, and surrounding squares over time, and interact with the actions other players take in nearby squares.
- Each game tick (let’s say every second) I need to calculate / update the overall status of each square of the board (and potentially make a visual update in the client).
I’d assume that as far as player actions go, I’d just want to record the action as it happens. And then have an algorithm/function that runs once a second to update the ‘board’ and fire client events as necessary. Visual representations of square status I’ll do in the client.
For the function that runs every second, what’s an efficient design pattern to use? I’m guessing that traversing every square would be horrendous. I could instead look at each action, as there would be a lot less actions than squares, but challenges there would be actions interacting with each other, and also actions whose effects last multiple turns.
Best I can think of is as follows… would this work?
- Keep a list of actions to process each turn.
- Each time a player performs an action, it gets added to the list
- Each action in the list has the player, action, square, TTL
- The board will be a 2D array of squares. Each square will have status.
- Keep a list of squares that have been changed each turn, including their new status.
- Each tick we traverse the list of actions. For each action we calculate what squares it affects, update status of those squares, add the squares to the changed list (with their new status), and decrement the action’s TTL. If the action’s TTL is 0 we remove it from the list. Once all actions have been traversed, we send the changed list to the client.
I figure that means we only traverse what we need, and with 8 players. expecting that players do at most one action per second, if actions can last at most 10 seconds then we would have at most 80 actions to process each second, which hopefully would be manageable (certainly better than trying to traverse 250K squares). Actions interacting should be handled by the fact we do all actions before updating the clients… if a subsequent action changes status again, that will be OK because we’ll just update status in the existing entry in the changed list.
Any help much appreciated!