Continuously update values on server-side


#1

I would like to make a simple game that allows player to build some buildings which provides resources continuously. Let’s say I have resource ‘Wood’ and several kinds of buildings like ‘Sawmill’, ‘Woodcutter’s tent’ and so on, each level of these buildings increase a rate of wood incoming, like +5 wood/sec, +10 wood/sec, etc. Player is allowed to build several buldings in a time. And, of course, I would like to display ‘live’ amount of resources to player and building time as well.
I have created collections Buildings with fields (player_id, building_id, level, income_rate, build_started_at, build_finished_at) and Resources with fields (player_id, wood_amount). Every second I would like to do

wood_amount += sum of each buildings income_rate

And here is a question: what is the best way to update the amount of resources on the server side?
On the client side I can create a couple of intervals and update these values according to income_rate and to reduce client-server traffic check only once per minute with the server for correctness. But for the server I have no idea. If I create a separate timer interval for each player it will lead to numerous DB updates every second, like updating current amount of resources which is not good idea. Of course, I can create a separate function and update those income_rates only by request from methods like I would do with old-fashion app for each http-request but in this way I loose reactivity. Or I do not need the reactivity in this case and should stay with updating by request from methods?

Thanks.


#2

I would update it only as a reaction to that minute scheduled check from client.


#3

So try to think of rates / minute instead of hard-coding in an actual interval. You could save the time your wood count was last retrieved (using a method, for example), and then multiply your wood/minute rate by the time difference between now and last retrieval.

This way, the server is state-less and the wood count is only updated when the client looks at it, which is optimal.

The client would still have to implement an interval of these updates, and simulate the effect on the server. Since you can share code between them, they should stay fairly well in sync.


#4

Thanks you guys, your answers make sense for me.

I’m pretty new with Meteor that’s why I thought there is some cool magic trick for such task.


#5

Just make sure you keep your “local/simulated” values in a reactiveDict, so that they update reactively when you add resources :wink: