开发者

node.js storing gamestate, how?

开发者 https://www.devze.com 2023-02-04 17:42 出处:网络
I\'m writing a game in javascript, and to prevent cheating, i\'m having the game be played on the server (it\'s a board game like a more complicated checkers). Since the game is fairly complex, I need

I'm writing a game in javascript, and to prevent cheating, i'm having the game be played on the server (it's a board game like a more complicated checkers). Since the game is fairly complex, I need to store the gamestate in order to validate client actions.

Is it possible to store the gamestate 开发者_JS百科in memory? Is that smart? Should I do that? If so, how? I don't know how that would work.

I can also store in redis. And that sort of thing is pretty familiar to me and requires no explanation. But if I do store in redis, the problem is that on every single move, the game would need to get the data from redis and interpret and parse that data in order to recreate the gamestate from scratch. But since moves happen very frequently this seems very stupid to me.

What should I do?


If you really, really don't want the overhead of I/O then just store the game state in a global object keyed by the game id:

var global_gamesate = {}

Then on each connection check what the game id is to retrieve he game state:

var gamestate = global_gamestate[game_id];

Presumably you already have a mechanism to map client sessions to game id.

Usually, game state is small and would hardly take up much RAM. Let's be pessimistic and assume each game state takes up 500K. Then you can serve two million thousand games (four million thousand users if we assume two users per game) for each gigabyte of RAM on your server.


However, I would like to point out that databases like MySQL already implement caching (which is configurable) so loading the most frequently used data basically loads from RAM with a minor socket I/O overhead. The advantages of databases is that you can have much more data than you have RAM because they store the rest on disk.

If your program ever reaches the load where you start thinking of writing your own disk-serialization algorithm to implement a swap file then you're basically re-inventing the wheel. In which case I'd say go with databases.

0

精彩评论

暂无评论...
验证码 换一张
取 消