Roguelike Tutorial 7
Roguelike in Go - Part 7 (Turn Based)
All of the code for this tutorial can be found here.
If you have tried to move about, you will discover it’s not easy. The player really zips across the screen. A while back, we added states to make this turn-based. Let’s put that to use now.
In main.go add this to the GameState object.
Turn TurnState
TurnCounter int
In the constructor method for GameState, you will need to add these two lines right above the return:
g.Turn = PlayerTurn
g.TurnCounter = 0
This sets the game to start at the player turn and initializes the counter.
Next we need to edit the Update function:
func (g *Game) Update() error {
g.TurnCounter++
if g.Turn == PlayerTurn && g.TurnCounter > 20 {
TryMovePlayer(g)
}
//Obviously just for now
g.Turn = PlayerTurn
return nil
}
This will only allow the player to make an action once per 20 iterations. Update is called 60 times a second, so where this isn’t using a delta and absolutely perfect, it’s good enough for a turn-based game. This just adds a small delay making it much easier to work with. Tweak this number as you see fit. We move things back to player turn here simply because we don’t have any world actions, so we need to move the state machine further along manually. Doing this here leaves us one place to fix when we add monsters or any other system actions.
Now in player_move_system.go we need to edit the TryMovePlayer system function and add the following to the very bottom.
if x != 0 || y != 0 {
g.Turn = GetNextState(g.Turn)
g.TurnCounter = 0
}
This resets that counter when the player moves and pushes to the next state. When we add monsters, we will not need to edit this function in the future, since it properly works with the state machine as is.
That’s it. You now have a turn based application and moving the player is a lot easier now.
If you have any questions on this tutorial, feel free to contact me at fatoldyeti@gmail.com or @idiotcoder on the gophers slack.