I have a fairly simple board game i've been building in C++. Currently, players are assigned a player number (1, 2, 3...N) depending on the number of players in the game. Pretty standard. The players and their stats are kept in a file which include their name and their number. I then process turns via reading a directory with turn files. The turns are submitted by the players and contain only their player name and their task/turn. In the future, I plan to have player numbers change so to mix up the order of the game.
(if you're a board gamer, think Caylus or Agricola)
Players are read in at the start of the application. I then give a command and turns are processed. Basically, I simply read the directory of turns, 1 by 1, and match that turn to a player name. As it stands, there is no order in turn processing. Player 3 can go before player 2.
I figured this wasn't a great design so I came up with the following solution:
- As I'm comparing which turn goes with which player, insert that turn into a
std::map<int, Turn>
, the key being the player number. - After I gather all the turns, search for player N, starting with 1, within the map and process his tur开发者_如何学运维n.
- I'm iterating through the list of players again here because I need to match the player with the player number in order to process the turn.
- Do this until I've processed all players.
Is there a better way to do this? This seems kludgey and a lot of overhead.
Thanks!
Note: My turn processing method takes in a Player class
(which represents the player stats file) and a struct
representing the turn read from the turn file.
So as I understand it, your problem is you have thee bits of linked data: Turn
s, PlayerID
s and PlayerTurnPosition
s (OK the latter 2 are ints but I'll assume you've typedef-ed them to something like that to avoid confusion). And you want to maintain a lookup from the PlayerID and PlayerTurnPosition values to the corresponding Turn, and also maintain a bidirectional relation between the Player info.
This is just screaming out to use a boost::bimap with some extra info attached to each pair relation; something like
boost::bimaps::bimap<
boost::bimaps::vector_of<PlayerID>,
boost::bimaps::vector_of<PlayerTurnPosition>,
boost::bimaps::with_info<boost::shared_ptr<Turn> >
>
should do the job nicely (although there are other options for the left/right view container types; set_of
probably makes more sense given playerIDs and positions are presumably unique).
Example of this sort of with_info
usage in the docs.
You might think of defining an Action class for a player acting in his turn, which is defined by a player number and a turn number, and define a comparison on this class. Read all Actions from the files, insert them into an ordered list, and then process these actions.
精彩评论