I know there are more questions like this around here (regarding websockets and Ajax requests) but I'm currently looking for the best solution in my specific case.
I'm currenly developing a game in Javascript. It's a Single Page Application so every change should be pulled from the server without page refresh. I'm currently wondering how I should handle the 'resources in stock' (like wood, food and gold).
Scenario
Resources are produced every second. So for example, every minute 100 resources are produced. This should be updated live. I know, in this case it's not necessary to really update them live. I mean, I can simply calculate how much resources are produced in the current time minus the last updated time.
So no problem here, but there are a lot of different factors regarding the production of resources:
- If a player is attacked, the enemy could have robbed some of his resources. So after an attack, the resources should be updated too.
- If a player is attacked, and one of his 'productionbuildings' are damaged, he, for example, doesn't produce 1000 resources a hour, but 800 resources instead. So after a building has been demolished, the application should know the new building level to calculate the right amount of new resources.
Possibilities
So, how should I update the resources for the user? These are the options I think could possibly work: * Ping a script on the server, which calculates and updates the resources, every 5 seconds. * Set up a websocket stream and trigger it after each activity (after an attack, demolished building, ...)
Are there any other options? What would be the best way? It's not really a problem if there is a delay of 5 seconds.