I am implementing a game server in python. The GameServer class holds multiple game instances, which each hold multiple players. I am trying to figure out the most optimal data structures to use. There is a single function that receives all incoming data, and it needs to find the player within the games, and update the info.

Currently, GameServer has a set of GameInstances, and GameInstance has a set of players. This requires me to iterate through every game and player to find the correct game, and I don't think this is the best way to do it, because it will have to be run hundreds of times per second.

The incoming data has a connection (from which the data was received), and the message. This means I store a connection for every player within their class, so that I can send messages back to a specific player. I can't keep a dict of every player connection, because they have to be grouped by game instance. Please help me understand the most efficient way to structure this.

有帮助吗?

解决方案

Currently, GameServer has a set of GameInstances, and GameInstance has a set of players. This requires me to iterate through every game and player to find the correct game, and I don't think this is the best way to do it, because it will have to be run hundreds of times per second.

You're right! And while I will answer your specific question, what you should do is read about datastructures. It's essential that every working programmer have at least a basic understanding of the most common datastructures, and their performance characteristics.

Based on your description of your problem, you need to maintain a mapping, probably using a hashtable, between a key which identifies each game, and the object which describes it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top