An implementation of game leaderboards
I am a game company small ape One, do game server development. Recently the company is ready to recruit new C + + programmers, I usually ask a common function, 10,000 people leaderboard how to achieve.
There are many answers, such as "1. Read directly from the database; 2. Use a hash table; 3. Use a ring array; 4. I have to think about this question carefully. ”
I am not satisfied with these answers, because people engaged in the development of game logic, the leaderboard function is a basic function, out of the "excellent" C + + Programmer's instinct, should carefully think how to achieve it. I might not be willing to work with colleagues who would presumably speculate on what data structures to use for this function if they just stay on the surface, and on key issues. I'm not a bunch of guys. Anyone who cannot give a good answer in 10 minutes, but wants a "right instinctive response", is right in the direction of consideration.
Give me an implementation method that I think is feasible and has good performance.
Leaderboard This feature, the base container is definitely an array of vectors. Because the leaderboard to support a feature is "find people by rank". Other containers do not support such a feature.
The vector holds the Player pointer, and the key used in the ranking (such as the Rank leaderboard key is the "level", "0xFFFFFFFF-timestamp" combination).
Leaderboards are saved in the Player structure.
排行榜 玩家数据 第一名 key1, Player * p1 p1 {myrank : 1, ...} 第二名 key2, Player * p2 p2 {myrank : 2, ...} 第三名 key3, Player * p3 p3 {myrank : 3, ...} 第四名 key4, Player * p4 p4 {myrank : 4, ...}
When the server starts up, the top 10,000 is sorted out, regardless of whether you use quick sort, heap sorting, insert sort, or bubble sort.
In the game, the player data changes need to update the leaderboard, according to Myrank find the player corresponding to the position of the table, in turn to do bubble comparison, move the player data, while updating the player Myrank can be moved. This gives you a new leaderboard.
Extreme circumstances are unlikely to exist, the last player can not jump to the first place, but gradually moving upward, so the use of bubbles does not affect performance.
An implementation of game leaderboards