Go Rogue! - Chapter 2
The Generic Entity, the Render Functions, and the Map

If you prefer to jump straight to the working Chapter 2 state instead of setting up the files by hand, and you have previously cloned the repository, checkout the
chapter-2branch or thev0.2.0tag:git checkout v0.2.0 go run ./cmd/go-rogue/This checks out the exact “Chapter 2” project state and runs the project.
In the last chapter, “Drawing the ‘@’ Symbol and Moving It Around”, we followed the original Python tutorial at rogueliketutorials.com pretty closely. The result was essentially a literal translation of Python into Go.
Starting with this chapter, we are breaking away from that approach. We will restructure the project to reflect standard Go conventions and focus on solving problems the “Go way” rather than mirroring Python idioms. While I am still refining my own idiomatic Go, writing this project with Go-first patterns will result in cleaner, more maintainable code as the game grows. At various points in this chapter, as we are making these changes, the code will not compile. If you are using an editor like VS Code that highlights errors, these broken lines of code will show up immediately. All of these will be resolved by the end of the chapter, but our program will be in a broken state while we perform this refactor and create the needed new functionality.
To begin, create a new folder in your project root called internal/.
In Go, internal/ is a special directory name. Packages inside this folder can only be imported by code rooted in the same parent directory, meaning external projects or modules cannot import them. Unlike Python’s underscore-prefixed privacy conventions, this boundary is strictly enforced by the Go compiler. Using internal as the default home for supporting code keeps your implementation details private until you explicitly choose to expose a package publicly.
Inside internal/, create another folder named engine/. This is where the core mechanics of our game engine will live. If this code ever matures into a standalone, reusable roguelike engine, it can be promoted out of internal later; for now, keeping it internal suits our single-game focus.
Finally, inside internal/engine/, create a new file named entity.go. Here we will define the data structures and behaviors for entities like the players, monsters, and items that inhabit the game world.
The first thing every game entity needs is a location. Entities exist somewhere within the game world. In the previous chapter, we presented the game world as having x and y coordinates on a grid and we kept track of what grid location the player was at. We will start with that. In the entity.go file, we need to specify that this code is part of the engine package and then begin defining our data structure:
package engine
type Entity struct {
X, Y int
}
This tells the compiler that this file is part of our new engine package and defines a basic data structure to hold a location. However, right away I see an improvement that might be useful. The two fields in our Entity data structure represent a point in our game world. Why don’t we define a data structure for this? In the internal/engine/ folder, create another file named point.go and let’s define a data structure to represent a Point. We will also define a few methods for Point operations.
package engine
type Point struct {
X, Y int
}
type Vector = Point
func (p Point) Add(direction Vector) Point {
return Point{p.X + direction.X, p.Y + direction.Y}
}
func (p Point) Sub(point Point) Vector {
return Vector{p.X - point.X, p.Y - point.Y}
}
func (v Vector) Mul(scalar int) Vector {
return Vector{v.X * scalar, v.Y * scalar}
}
This gives us a data structure to represent a location in the game world. We also create an aliased type, Vector and some operations. We can add a Vector to a Point to obtain a new Point. We can subtract one Point from another to determine the Vector between them. Finally, we can multiply a Vector by an integer scalar. Because we are defining Vector as an alias for Point, the compiler treats these types as completely interchangeable. The reason for this is twofold. First, it removes the need to perform any type conversion when doing math with both Point and Vector operands. Second, the reason for creating this alias is semantic clarity. While a Point and a Vector both just contain integers X and Y, mathematically, it doesn’t make sense to add two points and get a third point, nor does it make sense to subtract two points and get a third point. But it makes perfect sense to add a vector to a point to obtain a new point and likewise, the difference between two points is a vector, not a new point.
Now, we can modify our definition for Entity to use our Point type for the location. Remove the X and Y int fields from the Entity definition and replace it with a Point.
type Entity struct {
Loc Point
}
Now, every entity has a location of type Point. There are a few other things that we can assume most, if not all, entities will need. They will have a name (Player, Orc, Goblin, Sword, Healing Potion, etc.) They will have a visual representation within the game (we used ‘@’ for the Player in the last chapter). They will also have things that they can do (for example move). Let’s add a few more fields to the Entity struct. This will initially show an error for undefined types Graphic and Behavior, but we’ll correct that shortly.
type Entity struct {
Loc Point
Name string
Graphic Graphic
Behavior Behavior
}
Location and Name should be intuitive, but what are the fields Graphic of type Graphic and Behavior of type Behavior? Let’s tackle Behavior first. Entities do things within the game. The player and monsters move around, fight, etc. A healing potion heals, a sword does damage. Everything does something. The things that an Entity can do are its behaviors. Behavior will be an interface. We will define the interface as follows:
type Behavior interface {
GetAction(g *Game, e *Entity) Action
}
This interface definition involves three different types. It takes as arguments a pointer to the Game data structure and a pointer to an Entity data structure. We started setting up our Game struct and Action interface in the last chapter, and we are building our Entity struct now. What should our first Behavior be? We know that the Player needs to be able to move around the game world in response to input, so that is a behavior. Let’s start implementing it. In the last chapter, we built some logic to read the keyboard and determine if a movement key or the escape key was pressed. Generically, we will call this PlayerControl. This change is also going to show an error. The field, input on the Game struct is not yet defined, but this will also be fixed in this chapter.
type PlayerControl struct {}
func (p *PlayerControl) GetAction(g *Game, e *Entity) Action {
if g.input.WantsToQuit() {
return &EscapeAction{}
}
direction := g.input.WantsToMove()
if direction.X != 0 || direction.Y != 0 {
return &MovementAction{Direction: direction}
}
return nil
}
// Interface Guard
var _ Behavior = (*PlayerControl)(nil)
Let’s break this down to follow what’s happening. First, we create an empty struct, PlayerControl. This struct might need to store some data later, but for right now, it doesn’t have any state.
Then, we define the GetAction(g *Game, e *Entity) Action method to satisfy the interface. This method has two parameters, a pointer to the Game struct and a pointer to the Entity struct, and it returns something that implements the Action interface. This matches the required method signature for the Behavior interface, so PlayerControl is a Behavior.
What does the PlayerControl do? We see right up front that it does something with an input to see if the player wants to quit. Our Game doesn’t currently have an input field. For right now, input is a way to read and interpret commands (in this case, key presses). It has two methods it supports, WantsToQuit() and WantsToMove(). We first test for an input indicating the player wants to quit. If so, we return a pointer to an EscapeAction, which we defined in the last chapter. If the player hasn’t pressed the escape key, we check if the player has indicated that they want to move. Calling the WantsToMove() method returns a Vector. We test if the Vector is non-zero, and if so, we return a pointer to a MovementAction with the Vector that we read. If the player hasn’t hit the escape key or a movement key, we return nil to indicate there is no Action currently. Finally, we have an interface guard to test that PlayerControl implements the Behavior interface.
In the last chapter, we updated the player’s location directly within the game state, but now we have an Entity data structure that tracks its own location, so let’s create a method for an entity to move:
func (e *Entity) Move(direction Vector) {
e.Loc = e.Loc.Add(direction)
}
Now, we can call an Entity’s Move() method and pass it a directional Vector. The entity adds the vector to its location and sets the result as its new location.
Our Entity is complete for now and the code should look like this:
package engine
type Entity struct {
Loc Point
Name string
Graphic Graphic
Behavior Behavior
}
func (e *Entity) Move(direction Vector) {
e.Loc = e.Loc.Add(direction)
}
type Behavior interface {
GetAction(g *Game, e *Entity) Action
}
type PlayerControl struct{}
func (p *PlayerControl) GetAction(g *Game, e *Entity) Action {
if g.input.WantsToQuit() {
return &EscapeAction{}
}
direction := g.input.WantsToMove()
if direction.X != 0 || direction.Y != 0 {
return &MovementAction{Direction: direction}
}
return nil
}
// Interface Guard
var _ Behavior = (*PlayerControl)(nil)
We still need to handle our new data structure for entity graphics, but first, let’s move actions.go out of the root directory of the project workspace and into the internal/engine directory we created above. There are a few changes we are going to make in this section. We need to change the package declaration from main to engine. We are going to remove the two helper functions from last chapter, as they aren’t really necessary, and we are going to add a method, Perform() to the Action interface. Below is the new actions.go contents:
package engine
type Action interface {
Perform(g *Game, e *Entity) error
}
type EscapeAction struct{}
func (ea *EscapeAction) Perform(g *Game, e *Entity) error {
return ErrQuit
}
// Interface Guard
var _ Action = (*EscapeAction)(nil)
type MovementAction struct{ Direction Vector }
func (ma *MovementAction) Perform(g *Game, e *Entity) error {
destination := e.Loc.Add(ma.Direction)
if !g.gameMap.InBounds(destination) {
return &ImpossibleActionError{
Reason: "A magical force prevents you from moving outside the " +
"bounds of the map.",
}
}
if !g.gameMap.IsWalkable(destination) {
return &ImpossibleActionError{Reason: "You walk into the wall. Ouch!"}
}
e.Move(ma.Direction)
return nil
}
// Interface Guard
var _ Action = (*MovementAction)(nil)
The Action interface now requires a method, Perform(g *Game, e *Entity) error. The implementations of this method for both the EscapeAction type and the MovementAction type are defined.
The implementation for EscapeAction is very simple, we just return ErrQuit. This error will be defined later when we get to the coverage of the source in game.go.
The implementation for MovementAction is a little more involved. First, we determine the destination that the entity wants to move to by adding the direction vector to the entity’s current location and then verify that this location is within the boundary of the game map and is considered a walkable location. If either of these tests fail, we return an ImpossibleActionError (which will also be defined when we cover game.go) with an appropriate message set.
With actions.go completed, we will still have some errors in entity.go because Graphic is undefined, but this should clear up errors related to Action being undefined.
Next, let’s tackle updating our Game struct from last chapter. At the end of Chapter 1, our Game struct was defined in main.go as the following:
type Game struct {
gridCols int
gridRows int
charWidth int
charHeight int
playerX int
playerY int
}
The game state is storing how big the game map is (gridCols, gridRows), how big the glyphs are (charWidth, charHeight), and where the player entity is located (playerX, playerY).
Let’s make a new Go source file in our internal/engine/ directory, game.go. We want to start separating out concerns as we restructure the project, so let’s examine what things we really want to store as part of game state. We definitely need to keep track of the player entity and any other entities. We need to know about the game world, and we need a way for the player to give commands to the game. Let’s start out defining the Game state like this:
package engine
type Game struct {
player *Entity
entities []*Entity
gameMap *GameMap
input Input
}
This is a little different from the definition in Chapter 1, so let’s go over what has changed. First, we are specifying that this structure is part of the engine package.
Next, within the Game struct, we no longer are tracking the player’s location directly as X and Y coordinates. Above we defined an Entity type that tracks its own location, so we have a slice (a dynamically sized array) of pointers to type Entity to track the game’s entities. The player is a particularly important entity, so we will have a field with a pointer to type Entity specifically for the player. When we built our Entity struct, we gave it a field to hold graphical information. Perhaps we don’t need to track the size of a glyph within the game state, and instead we can leverage the Graphic field that every entity has.
We do need to keep track of the game world, but our game world is more than just a width and a height defining the area that the player can move around in. Instead of storing gridCols and gridRows, we will store a pointer to a GameMap that we will define shortly.
Finally, we are adding a field to handle the input mechanism. This will be very similar to the EventHandler() method of the Game structure from last chapter, but provides a layer of abstraction. One of the goals of this organization for the code is to remove any dependencies on Ebitengine from the game state. The new engine package will be self-contained and not rely on any knowledge of the mechanisms for input or rendering provided by Ebitengine.
Next, we define a helper function to construct the Game data structure:
func NewGame(
mapWidth, mapHeight int,
player *Entity,
npcs []*Entity,
input Input,
) (*Game, error) {
game := &Game{
player: player,
entities: append([]*Entity{player}, npcs...),
gameMap: NewGameMap(mapWidth, mapHeight),
input: input,
}
return game, nil
}
This function takes arguments for the map size (mapWidth and mapHeight), a pointer to the player Entity, a slice of pointers to any NPC entities, and the input interface. The player, entities, and input fields of the Game structure are set - note that the Game’s entities slice includes the player as the first entity in the slice. We also call a helper function to create the GameMap structure based on the size parameters that were passed. This helper function, NewGameMap() will be defined when we cover the GameMap data structure later in this chapter.
Next, we define the game’s Update() method. This will get called from main() via the GameRunner wrapper we’ll create shortly. Here we update the game state each “tick” of the game’s internal clock:
func (g *Game) Update() error {
action := g.player.Behavior.GetAction(g, g.player)
if action == nil {
return nil
}
err := action.Perform(g, g.player)
if err != nil {
var impErr *ImpossibleActionError
if errors.As(err, &impErr) {
fmt.Println(impErr.Reason)
return nil
}
return err
}
return nil
}
This method is pretty simple at this point. We use the Behavior from the player Entity structure to get an action from the Player. This is going to check the keyboard for any input from the Player, similar to how we did it in the last chapter, but we will look at it in detail momentarily. If there was no input from the Player, we return nil, meaning there was no error and the update is complete for this tick. If we did get an Action for the player, we call the Action’s Perform() method and check for errors. If the Perform() method did return an error, we see if it was an ImpossibleActionError. An ImpossibleActionError isn’t a real error, it just means the desired Action wasn’t performed for some reason that we can deal with. For right now, that is going to be because the player couldn’t move to the desired location. It was either outside the boundary of the map or the location is inside the map but not valid for movement. We print the reason the Action was impossible and return nil to indicate this update completed with no errors. If it was actually an error, we return the error.
Next, we will define another helper function:
func (g *Game) Map() MapViewer {
return g.gameMap
}
We will need this method when we get to the Renderer structure. The Renderer needs to be able to read the map, but we want to protect it from modification, so we provide a way to obtain a MapViewer from the Game. MapViewer is an interface that allows game map locations to be examined, but not modified. We will define this interface and its methods when we get to the section on the GameMap type later in this chapter.
Similarly, we are going to provide a helper function for examining Entity instances, but we don’t want code outside of this package to be able to modify them:
func (g *Game) Entities() []Entity {
copies := make([]Entity, len(g.entities))
for i, e := range g.entities {
copies[i] = *e
}
return copies
}
This method copies the Game’s slice of Entities and returns it.
Next, we define the Game struct’s Input interface:
type Input interface {
WantsToMove() (direction Vector)
WantsToQuit() bool
}
The Player can only provide two kinds of commands at the moment, an intention to move and an intention to quit. More methods will be added to this interface eventually when we build logic for the Player to issue more kinds of commands.
Finally, we define our special errors:
var ErrQuit = errors.New("player requested quit")
type ImpossibleActionError struct {
Reason string
}
func (e *ImpossibleActionError) Error() string {
return e.Reason
}
Here is the game.go file in entirety:
package engine
import (
"errors"
"fmt"
)
type Game struct {
player *Entity
entities []*Entity
gameMap *GameMap
input Input
}
func NewGame(
mapWidth, mapHeight int,
player *Entity,
npcs []*Entity,
input Input,
) (*Game, error) {
game := &Game{
player: player,
entities: append([]*Entity{player}, npcs...),
gameMap: NewGameMap(mapWidth, mapHeight),
input: input,
}
return game, nil
}
func (g *Game) Update() error {
action := g.player.Behavior.GetAction(g, g.player)
if action == nil {
return nil
}
err := action.Perform(g, g.player)
if err != nil {
var impErr *ImpossibleActionError
if errors.As(err, &impErr) {
fmt.Println(impErr.Reason)
return nil
}
return err
}
return nil
}
func (g *Game) Map() MapViewer {
return g.gameMap
}
func (g *Game) Entities() []Entity {
copies := make([]Entity, len(g.entities))
for i, e := range g.entities {
copies[i] = *e
}
return copies
}
type Input interface {
WantsToMove() (direction Vector)
WantsToQuit() bool
}
var ErrQuit = errors.New("player requested quit")
type ImpossibleActionError struct {
Reason string
}
func (e *ImpossibleActionError) Error() string {
return e.Reason
}
In the last chapter, game state was contained in the main package and the Game data structure directly implemented the methods required by Ebitengine for Ebitengine’s Game interface, but we have now moved game state out into its own package. We are going to make another organizational change here. Create a new directory, cmd, in the root of the project. Inside of this directory, create another directory, go-rogue. In this directory, create two new files, main.go and ebitenInput.go.
It is a common convention in Go projects to have a top level directory named cmd in the project workspace. Under this directory, there is another directory named for the project. Inside of this directory is where the main package is placed.
We can delete the main.go and inputHandlers.go in the project root, as they will not be needed any more.
The first file we’ll work on is ebitenInput.go. This file is pretty short and simple and will be needed for main.go, so we may as well create it first. Here is the contents of that file and then after will be an explanation.
package main
import (
"github.com/FooWho/go-rogue/internal/engine"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/inpututil"
)
type EbitenInput struct{}
func (i *EbitenInput) WantsToMove() engine.Vector {
if inpututil.IsKeyJustPressed(ebiten.KeyUp) ||
inpututil.IsKeyJustPressed(ebiten.KeyW) ||
inpututil.IsKeyJustPressed(ebiten.KeyNumpad8) {
return engine.Vector{X: 0, Y: -1}
}
if inpututil.IsKeyJustPressed(ebiten.KeyDown) ||
inpututil.IsKeyJustPressed(ebiten.KeyS) ||
inpututil.IsKeyJustPressed(ebiten.KeyNumpad2) {
return engine.Vector{X: 0, Y: 1}
}
if inpututil.IsKeyJustPressed(ebiten.KeyLeft) ||
inpututil.IsKeyJustPressed(ebiten.KeyA) ||
inpututil.IsKeyJustPressed(ebiten.KeyNumpad4) {
return engine.Vector{X: -1, Y: 0}
}
if inpututil.IsKeyJustPressed(ebiten.KeyRight) ||
inpututil.IsKeyJustPressed(ebiten.KeyD) ||
inpututil.IsKeyJustPressed(ebiten.KeyNumpad6) {
return engine.Vector{X: 1, Y: 0}
}
if inpututil.IsKeyJustPressed(ebiten.KeyNumpad7) {
return engine.Vector{X: -1, Y: -1}
}
if inpututil.IsKeyJustPressed(ebiten.KeyNumpad9) {
return engine.Vector{X: 1, Y: -1}
}
if inpututil.IsKeyJustPressed(ebiten.KeyNumpad1) {
return engine.Vector{X: -1, Y: 1}
}
if inpututil.IsKeyJustPressed(ebiten.KeyNumpad3) {
return engine.Vector{X: 1, Y: 1}
}
return engine.Vector{X: 0, Y: 0}
}
func (i *EbitenInput) WantsToQuit() bool {
return inpututil.IsKeyJustPressed(ebiten.KeyEscape)
}
// Interface Guard
var _ engine.Input = (*EbitenInput)(nil)
First, we declare that this file is part of package main. This is followed by our imports. We need to import our engine package and the ebiten and inpututil packages.
Next, we define a struct to represent the input handler. We will call it EbitenInput. It’s going to be an empty struct, but we need something to attach to the game state to get input from.
If you recall from when we created the Entity struct, we said that we needed input to handle WantsToQuit() and WantsToMove(), so we define those methods.
WantsToQuit() is the easier of the two. It checks if the escape key was pressed and if so, returns true. Otherwise, it returns false.
WantsToMove() is a little more complicated, but not much. It checks if the up arrow, the w key, or the numpad 8 key was pressed and if so, returns Vector{X: 0, Y: -1} to indicate the player’s intent to move up one unit. If none of those keys were pressed, it checks for the down arrow, the s key or the numpad 2 key and if so returns Vector{X: 0, Y: 1} to indicate the player’s intent to move down one unit. If none of these keys were pressed, it checks the left arrow, the a key, or the numpad 4 key, returning Vector{X: -1, Y: 0} if one was pressed. It then checks if the right arrow, d key, or numpad 6 key were pressed, returning Vector{X: 1, Y: 0} if one of them was. It then checks the numpad 7, 9, 1, or 3 keys were pressed for diagonal movement and returns Vector{X: -1, Y: -1}, Vector{X: 1, Y: -1}, Vector{X: -1, Y: 1}, or Vector{X: 1, Y: 1} respectively. If none of these keys were pressed, the player has not indicated an intent to move, so the method returns Vector{X: 0, Y: 0}.
Now let’s work on main.go. First I will show the new version of the code and then I will explain the changes. There are going to be some errors initially, don’t worry, we will resolve them shortly.
package main
import (
"errors"
"fmt"
"image/color"
"log"
"github.com/FooWho/go-rogue/internal/engine"
"github.com/FooWho/go-rogue/internal/renderer"
"github.com/hajimehoshi/ebiten/v2"
)
type GameRunner struct {
gameState *engine.Game
renderer *renderer.Renderer
}
func (g *GameRunner) Update() error {
err := g.gameState.Update()
if errors.Is(err, engine.ErrQuit) {
fmt.Println("Good bye!")
return ebiten.Termination
}
return err
}
func (g *GameRunner) Draw(screen *ebiten.Image) {
g.renderer.Draw(screen, g.gameState)
}
func (g *GameRunner) Layout(outsideWidth, outsideHeight int) (int, int) {
return g.renderer.Layout(outsideWidth, outsideHeight)
}
// Interface Guard
var _ ebiten.Game = (*GameRunner)(nil)
const (
gameCols = 80
gameRows = 50
tileWidth = 10
tileHeight = 10
playerX = (gameCols / 2)
playerY = (gameRows / 2)
)
func main() {
input := &EbitenInput{}
renderer, err :=
renderer.NewRenderer("dejavu10x10_gs_tc_transparent.png",
tileWidth,
tileHeight,
gameCols,
gameRows,
)
if err != nil {
log.Fatal(err)
}
player := &engine.Entity{Loc: engine.Point{X: playerX, Y: playerY},
Name: "player",
Graphic: engine.Graphic{
Name: "@",
FG: color.NRGBA{R: 255, G: 255, B: 255, A: 255},
BG: color.NRGBA{R: 0, G: 0, B: 0, A: 0},
},
Behavior: &engine.PlayerControl{},
}
npc := &engine.Entity{Loc: engine.Point{X: gameCols/2 - 5, Y: gameRows / 2},
Name: "monster",
Graphic: engine.Graphic{
Name: "@",
FG: color.NRGBA{R: 255, G: 255, B: 0, A: 255},
BG: color.NRGBA{R: 0, G: 0, B: 0, A: 0},
},
Behavior: nil,
}
npcs := []*engine.Entity{npc}
game, err := engine.NewGame(gameCols,
gameRows,
player,
npcs,
input)
if err != nil {
log.Fatal(err)
}
gameRunner := &GameRunner{gameState: game, renderer: renderer}
err = ebiten.RunGame(gameRunner)
if err != nil && err != ebiten.Termination {
log.Fatal(err)
}
}
We still need to declare that this file is part of package main, so that is unchanged. We are adding some new imports and one of these is going to be an error because we haven’t created the renderer package yet, so github.com/FooWho/go-rogue/internal/renderer will complain that there isn’t such a module. Remember for your project, replace the github.com/FooWho/go-rogue part with your project name. We will be creating that package before the end of the chapter.
In the next piece, we have a new data structure:
type GameRunner struct {
gameState *engine.Game
renderer *renderer.Renderer
}
The reason for this data structure is to provide a wrapper for our game engine code so that we can implement the ebiten.Game interface in our main package. Doing this means that our engine package doesn’t need to interact with Ebitengine or even be aware of it in any way. Our game logic can be completely decoupled from Ebitengine. We could potentially swap it out for some other library with minimal (or perhaps no) changes to our engine code.
The next bit of code is where we implement the three required methods for ebiten.Game:
func (g *GameRunner) Update() error {
err := g.gameState.Update()
if errors.Is(err, engine.ErrQuit) {
fmt.Println("Good bye!")
return ebiten.Termination
}
return err
}
func (g *GameRunner) Draw(screen *ebiten.Image) {
g.renderer.Draw(screen, g.gameState)
}
func (g *GameRunner) Layout(outsideWidth, outsideHeight int) (int, int) {
return g.renderer.Layout(outsideWidth, outsideHeight)
}
// Interface Guard
var _ ebiten.Game = (*GameRunner)(nil)
First, we provide a wrapper for the Update() method, passing the call through to the Game structure and checking any error that is returned. If the error is our special ErrQuit error we defined in game.go, that will be the signal that the user wants to quit the game, so we will replace it with the ebiten.Termination error and return that. Otherwise, we return whatever error we got from our game engine, which will hopefully be nil.
Next, we have a wrapper for the Draw() method. This is passed through to the renderer package to update the screen. We will define the Renderer later in this chapter.
Then, we have the wrapper for the Layout() method which is passed to the renderer and returns the size of our game window.
Finally, we have an interface guard just to double check that our GameRunner structure correctly implements the ebiten.Game interface.
The next section of the code defines a few constants for us:
const (
gameCols = 80
gameRows = 50
tileWidth = 10
tileHeight = 10
playerX = (gameCols / 2)
playerY = (gameRows / 2)
)
Our game map is 80 columns wide by 50 rows high. The bitmap font we are using for the graphics in the chapter is 10 pixels wide by 10 pixels high. The last pair of constants are because we want to place the player’s graphic in the center location.
Now we define the main entry point for the program, main(). Once again, there will be some errors here for references to things that are not yet defined. The main() function first creates a reference to our input handler:
input := &EbitenInput{}
It then calls a helper function to set up the renderer and checks for any errors:
renderer, err :=
renderer.NewRenderer("dejavu10x10_gs_tc_transparent.png",
tileWidth,
tileHeight,
gameCols,
gameRows,
)
if err != nil {
log.Fatal(err)
}
dejavu10x10_gs_tc_transparent.png is the bitmap font that we use for graphics in this chapter. If you have not cloned my repository and are working from scratch, you can download the image here:
Create a directory in the root of the project workspace named assets and place the file in this directory. This file is used by the renderer for the graphical sprites. The renderer also needs to know the size of our tiles or sprites (tileWidth and tileHeight) and the size of our game map (gameCols and gameRows). If there was an error in creating the renderer, log it and exit with an error state.
Next, we will create two entities, one for the player and one for a monster.
player := &engine.Entity{Loc: engine.Point{X: playerX, Y: playerY},
Name: "player",
Graphic: engine.Graphic{
Name: "@",
FG: color.NRGBA{R: 255, G: 255, B: 255, A: 255},
BG: color.NRGBA{R: 0, G: 0, B: 0, A: 0},
},
Behavior: &engine.PlayerControl{},
}
npc := &engine.Entity{Loc: engine.Point{X: gameCols/2 - 5, Y: gameRows / 2},
Name: "monster",
Graphic: engine.Graphic{
Name: "@",
FG: color.NRGBA{R: 255, G: 255, B: 0, A: 255},
BG: color.NRGBA{R: 0, G: 0, B: 0, A: 0},
},
Behavior: nil,
}
The player entity is created at the location we calculated as the center of the map. We name it “player” and we then create a Graphic data structure for it. This will be an error, as this data structure is still not defined, but here we see an example of what a Graphic structure looks like. A Graphic consists of a name, which we will use to load the correct sprite, and then a foreground and background color in standard color.NRGBA format. Finally, we set the entity’s Behavior. In the case of the player entity, its behavior is controlled by the Player, so we set it to a PlayerControl. The NPC entity is set up similarly. For now, we will use the same sprite for the monster as we are using for the player (the ‘@’ glyph). We set a foreground and background color. For the monster’s Behavior, this is set to nil for now, as we have not yet designed any kind of monster AI yet. This will come in a later chapter.
In the next section of the code:
npcs := []*engine.Entity{npc}
game, err := engine.NewGame(gameCols,
gameRows,
player,
npcs,
input)
if err != nil {
log.Fatal(err)
}
The monster is placed into a slice named npcs and we then create an instance of our Game structure using a helper function (which we defined earlier in the chapter). This function takes the size of the game map (gameCols and gameRows), the data structure for the player, the list of NPC data structures, and then our input data structure. We check if an error occurred, we log it and exit with an error state.
Our main() function then launches the game loop:
gameRunner := &GameRunner{gameState: game, renderer: renderer}
err = ebiten.RunGame(gameRunner)
if err != nil && err != ebiten.Termination {
log.Fatal(err)
}
We create an instance of our GameRunner structure that has a pointer to the game state and rendering structures we created. This is passed to the Ebitengine’s RunGame() method. This method will execute until an error occurs. When the method returns, we check if there was an actual error (and if so log it and exit with an error). If there was not an actual error and the application is just exiting, we terminate normally.
Next, we will define our GameMap data structure. Create a new Go source file, gameMap.go in the internal/engine/ directory. Below is the content of this file, followed by the explanation:
package engine
import (
"image/color"
)
type Graphic struct {
Name string
FG color.NRGBA
BG color.NRGBA
}
type Tile struct {
Walkable bool
Transparent bool
DarkGraphic *Graphic
}
type GameMap struct {
cols, rows int
tiles []*Tile
}
func NewGameMap(cols, rows int) *GameMap {
gm := &GameMap{cols: cols, rows: rows}
gm.tiles = make([]*Tile, cols*rows)
for y := 0; y < gm.rows; y++ {
for x := 0; x < gm.cols; x++ {
gm.tiles[gm.GetIndex(Point{x, y})] = floor
}
}
gm.tiles[gm.GetIndex(Point{X: 30, Y: 22})] = wall
gm.tiles[gm.GetIndex(Point{X: 31, Y: 22})] = wall
gm.tiles[gm.GetIndex(Point{X: 32, Y: 22})] = wall
return gm
}
func (gm *GameMap) GetIndex(p Point) int {
return p.Y*gm.cols + p.X
}
func (gm *GameMap) InBounds(p Point) bool {
return 0 <= p.X && p.X < gm.cols && 0 <= p.Y && p.Y < gm.rows
}
func (gm *GameMap) IsWalkable(p Point) bool {
return gm.tiles[gm.GetIndex(p)].Walkable
}
type MapViewer interface {
Width() int
Height() int
GetTileAt(p Point) Tile
}
func (gm *GameMap) Width() int {
return gm.cols
}
func (gm *GameMap) Height() int {
return gm.rows
}
func (gm *GameMap) GetTileAt(p Point) Tile {
return *gm.tiles[gm.GetIndex(p)]
}
var floor = &Tile{Walkable: true,
Transparent: true,
DarkGraphic: &Graphic{Name: " ",
FG: color.NRGBA{R: 0, G: 0, B: 0, A: 0},
BG: color.NRGBA{R: 50, G: 50, B: 150, A: 255},
}}
var wall = &Tile{Walkable: false,
Transparent: false,
DarkGraphic: &Graphic{Name: " ",
FG: color.NRGBA{R: 0, G: 0, B: 0, A: 0},
BG: color.NRGBA{R: 0, G: 0, B: 100, A: 255}}}
At the start of this file, we declare it to be part of the engine package and we import image/color:
package engine
import (
"image/color"
)
Next, we define the Graphic type:
type Graphic struct {
Name string
FG color.NRGBA
BG color.NRGBA
}
The Graphic data structure has a field Name which is a string to reference the sprite that is needed and a foreground and background color in color.NRGBA format.
Next up is the Tile struct:
type Tile struct {
Walkable bool
Transparent bool
DarkGraphic *Graphic
}
A tile is a location within the GameMap. It has two boolean fields, Walkable and Transparent, and a pointer to a Graphic. The Walkable field indicates if entities can walk over this location and the Transparent field indicates if the location blocks field of view. The field DarkGraphic is a pointer to a Graphic structure. I kept the name DarkGraphic from the Python tutorial. Eventually, tiles will have a DarkGraphic and a LitGraphic.
Next up is the definition for the actual GameMap type:
type GameMap struct {
cols, rows int
tiles []*Tile
}
It has two integer fields, cols and rows telling us its size and a slice of pointers to instances of Tile. This is a one dimensional slice, but we can think of a GameMap as a 2D matrix of Tiles, where each Tile has a graphical representation, and flags to indicate if entities can see through and walk through it.
Next is the definition of the helper function to initialize the GameMap:
func NewGameMap(cols, rows int) *GameMap {
gm := &GameMap{cols: cols, rows: rows}
gm.tiles = make([]*Tile, cols*rows)
for y := 0; y < gm.rows; y++ {
for x := 0; x < gm.cols; x++ {
gm.tiles[gm.GetIndex(Point{x, y})] = floor
}
}
gm.tiles[gm.GetIndex(Point{X: 30, Y: 22})] = wall
gm.tiles[gm.GetIndex(Point{X: 31, Y: 22})] = wall
gm.tiles[gm.GetIndex(Point{X: 32, Y: 22})] = wall
return gm
}
Our map is very simple for now. We fill the map up with floor tiles, and then place three wall tiles running horizontally from columns 30 - 32 in row 22. This will allow us to test that we can move through some tiles (instances of floor) but are blocked by others (instances of wall). In the next chapter, we will generate a proper dungeon.
This is followed by three helper functions:
func (gm *GameMap) GetIndex(p Point) int {
return p.Y*gm.cols + p.X
}
func (gm *GameMap) InBounds(p Point) bool {
return 0 <= p.X && p.X < gm.cols && 0 <= p.Y && p.Y < gm.rows
}
func (gm *GameMap) IsWalkable(p Point) bool {
return gm.tiles[gm.GetIndex(p)].Walkable
}
The first helper, GetIndex() takes a point as an argument and translates the (x, y) coordinate into an index into the slice holding the tiles. InBounds() is similar, taking a Point returning a boolean to indicate if that (x, y) coordinate is inside the map. Finally, IsWalkable() tests a Point to see if the Walkable flag is set for that Tile. Later, we will probably add a similar helper for Transparent, but we aren’t handling visibility yet.
Following this, we define the MapViewer interface and implement the required methods:
type MapViewer interface {
Width() int
Height() int
GetTileAt(p Point) Tile
}
func (gm *GameMap) Width() int {
return gm.cols
}
func (gm *GameMap) Height() int {
return gm.rows
}
func (gm *GameMap) GetTileAt(p Point) Tile {
return *gm.tiles[gm.GetIndex(p)]
}
A MapViewer must implement Width() int, Height() int, and GetTileAt(p Point) Tile. These three methods are all pretty intuitive, with one possible exception. In the last section, I explained that we wanted a MapViewer interface to allow other packages to look at the map but not modify it, but the Game structure’s Map() function returns the actual GameMap and the GameMap’s GetTileAt() method returns the Tile for the requested location. Then, how does the protection work?
Two things are happening here. First, the GameMap holds pointers to Tiles, but GetTileAt() returns a Tile. When the Tile pointer is dereferenced in GetTileAt(), the Tile that is returned is a copy of the Tile being referenced, not the Tile itself. The Tile can be modified, but that doesn’t change the data inside the Tile that is referenced by the pointer in the GameMap’s tiles slice. And because the Game structure’s Map() method returns a MapViewer and not a Map it doesn’t matter that this instance of MapViewer is actually a real GameMap. It is an error to try to reference the underlying tiles directly.
This will let us access Tiles outside of the engine package (for example in the Renderer) while still protecting them and costs us almost nothing in terms of overhead.
Finally, this source file ends by defining two kinds of Tiles for us: a floor and a wall. These are used in the NewGameMap() method for making the simple map used in this chapter.
This has been a long chapter, but we are getting close to the finish line! We know that we still need to define the Renderer type, but let’s cover one more thing quickly first. You should have an assets/ directory in the top level of the project workspace with a file named dejavu10x10_gs_tc_transparent.png in it. If you haven’t created this directory yet or downloaded the image file linked earlier in this chapter, do that now and then create a new source file in the assets/ directory called assets.go. Go provides a nice little feature to embed files within our program and we are going to use that to store our graphics (and a few more things in later chapters). The assets.go file is really simple:
package assets
import (
"embed"
)
//go:embed *.png
var AssetsFS embed.FS
This file is declared to be part of the assets package and we import the embed package. We declare a package level variable, AssetsFS of type embed.FS and it has a funny little comment right before the declaration, //go:embed *.png. This comment tells the compiler that any PNG file in this directory should be embedded inside of our program and that we are going to access it via a virtual, read-only file system. We are going to use this within our Renderer type, which we will implement next.
Now for the Renderer, the final type needed for this chapter. Create a new directory in the internal/ directory called renderer. Inside of this directory, create a new source file, renderer.go. We will walk through making this file together.
package renderer
import (
"bytes"
"image"
"image/color"
_ "image/png"
"github.com/FooWho/go-rogue/assets"
"github.com/FooWho/go-rogue/internal/engine"
"github.com/hajimehoshi/ebiten/v2"
)
First, we declare this file to be part of the renderer package. Then, we have several other packages that we need to import. The assets package from our project is going to let us work with the virtual filesystem we set up in the last bit and we will also need the engine package from our project. We need the ebiten package so we can render our game onto the screen. We also need a few packages from the Go library, bytes, image, and image/color. The package image/png is also imported, but the _ before its name means that we aren’t going to be using it directly.
We will start out defining a couple of new types we will need:
type SpriteSheet map[string]*ebiten.Image
type Renderer struct {
spriteSheet SpriteSheet
whitePixel *ebiten.Image
tileWidth, tileHeight int
viewportCols, viewportRows int
}
SpriteSheet is a map that lets us use a string as the key to look up a pointer to an ebiten.Image. We are going to use this to hold our sprites.
Our Renderer type has a field spriteSheet of type SpriteSheet for the sprites. It has a field whitePixel which is a pointer to an ebiten.Image. Finally, we have two integers, tileWidth and tileHeight to store the size of our sprites/tiles and two more integers, viewportCols and viewportRows to store how many tiles we can see in our game window. Currently, our map and our window are the same size, but we will be ambitious and allow support in the future for maps to be larger than the game window and just show pieces of the map at a time.
Next, we define our helper function to initialize the renderer:
func NewRenderer(
spriteSheetName string,
tileWidth, tileHeight int,
viewportCols, viewportRows int,
) (*Renderer, error) {
spriteSheet, err := loadTileset(spriteSheetName, tileWidth, tileHeight)
if err != nil {
return nil, err
}
ebiten.SetWindowSize(viewportCols*tileWidth, viewportRows*tileHeight)
ebiten.SetWindowTitle("Go Rogue!")
whitePixel := ebiten.NewImage(1, 1)
whitePixel.Fill(color.White)
return &Renderer{spriteSheet: spriteSheet,
whitePixel: whitePixel,
tileWidth: tileWidth,
tileHeight: tileHeight,
viewportCols: viewportCols,
viewportRows: viewportRows,
},
nil
}
This function takes a string, spriteSheetName telling us what graphic file to load, two integers for the width and height of each of our sprites/tiles, and the width and height of the window. It will return a pointer to a Renderer and an error (which will hopefully be nil). We attempt to initialize the spriteSheet by calling a function we will cover in a second, loadTileset(). We check if we got an error and if so, return the error and nil for the pointer to Renderer. If the SpriteSheet loaded correctly, we set the window size and window title. Then we create the whitePixel, a 1x1 white image. This will be scaled up and tinted to draw solid background colors for our tiles. We then return the initialized Renderer and nil for the error.
Next is the Renderer’s Draw() method. This method is a bit long, I will present the whole method, and then explain it:
func (r *Renderer) Draw(screen *ebiten.Image, gameEngine *engine.Game) {
opFG := &ebiten.DrawImageOptions{}
opBG := &ebiten.DrawImageOptions{}
for y := 0; y < r.viewportRows; y++ {
for x := 0; x < r.viewportCols; x++ {
tile := gameEngine.Map().GetTileAt(engine.Point{X: x, Y: y})
visual := tile.DarkGraphic
if visual.BG.A > 0 {
opBG.GeoM.Reset()
opBG.GeoM.Scale(float64(r.tileWidth), float64(r.tileHeight))
opBG.GeoM.Translate(
float64(x*r.tileWidth),
float64(y*r.tileHeight),
)
opBG.ColorScale.Reset()
opBG.ColorScale.Scale(
float32(visual.BG.R)/255.0,
float32(visual.BG.G)/255.0,
float32(visual.BG.B)/255.0,
float32(visual.BG.A)/255.0,
)
screen.DrawImage(r.whitePixel, opBG)
}
}
}
for y := 0; y < r.viewportRows; y++ {
for x := 0; x < r.viewportCols; x++ {
tile := gameEngine.Map().GetTileAt(engine.Point{X: x, Y: y})
visual := tile.DarkGraphic
opFG.GeoM.Reset()
opFG.GeoM.Translate(
float64(x*r.tileWidth),
float64(y*r.tileHeight),
)
opFG.ColorScale.Reset()
opFG.ColorScale.Scale(
float32(visual.FG.R)/255.0,
float32(visual.FG.G)/255.0,
float32(visual.FG.B)/255.0,
float32(visual.FG.A)/255.0,
)
screen.DrawImage(r.spriteSheet[visual.Name], opFG)
}
}
for _, entity := range gameEngine.Entities() {
visual := entity.Graphic
if visual.BG.A > 0 {
opBG.GeoM.Reset()
opBG.GeoM.Scale(float64(r.tileWidth), float64(r.tileHeight))
opBG.GeoM.Translate(float64(entity.Loc.X*r.tileWidth),
float64(entity.Loc.Y*r.tileHeight))
opBG.ColorScale.Reset()
opBG.ColorScale.Scale(
float32(visual.BG.R)/255.0,
float32(visual.BG.G)/255.0,
float32(visual.BG.B)/255.0,
float32(visual.BG.A)/255.0,
)
screen.DrawImage(r.whitePixel, opBG)
}
}
for _, entity := range gameEngine.Entities() {
visual := entity.Graphic
opFG.GeoM.Reset()
opFG.GeoM.Translate(float64(entity.Loc.X*r.tileWidth),
float64(entity.Loc.Y*r.tileHeight))
opFG.ColorScale.Reset()
opFG.ColorScale.Scale(
float32(visual.FG.R)/255.0,
float32(visual.FG.G)/255.0,
float32(visual.FG.B)/255.0,
float32(visual.FG.A)/255.0,
)
screen.DrawImage(r.spriteSheet[visual.Name], opFG)
}
}
We start by creating two empty ebiten.DrawImageOptions structures, opFG, and opBG. These will be used for drawing the foreground and the background.
Next, we go into the actual rendering loop.
The renderer starts by looping over the tiles in the game map. We get each tile in turn by calling the GetTileAt() method from the MapViewer interface we request from our Game instance. We store that Tile’s graphic in a variable named visual.
If visual has a background color with a non-zero Alpha channel, meaning it isn’t completely transparent, then we set up our opBG struct and draw that image:
for y := 0; y < r.viewportRows; y++ {
for x := 0; x < r.viewportCols; x++ {
tile := gameEngine.Map().GetTileAt(engine.Point{X: x, Y: y})
visual := tile.DarkGraphic
if visual.BG.A > 0 {
opBG.GeoM.Reset()
opBG.GeoM.Scale(float64(r.tileWidth), float64(r.tileHeight))
opBG.GeoM.Translate(
float64(x*r.tileWidth),
float64(y*r.tileHeight),
)
opBG.ColorScale.Reset()
opBG.ColorScale.Scale(
float32(visual.BG.R)/255.0,
float32(visual.BG.G)/255.0,
float32(visual.BG.B)/255.0,
float32(visual.BG.A)/255.0,
)
screen.DrawImage(r.whitePixel, opBG)
}
}
}
First, reset the geometry matrix, scale the matrix to the size of a tile, and place the origin of the matrix at the correct location within the window. Then, reset the color and then scale the color according to RGBA values for the Graphic’s background. We then draw the 1x1 white pixel (r.whitePixel), with the correctly applied geometry and color.
This loop runs through the entire game map, laying down all of the background.
Next up we are going to do something very similar for the foreground:
for y := 0; y < r.viewportRows; y++ {
for x := 0; x < r.viewportCols; x++ {
tile := gameEngine.Map().GetTileAt(engine.Point{X: x, Y: y})
visual := tile.DarkGraphic
opFG.GeoM.Reset()
opFG.GeoM.Translate(
float64(x*r.tileWidth),
float64(y*r.tileHeight),
)
opFG.ColorScale.Reset()
opFG.ColorScale.Scale(
float32(visual.FG.R)/255.0,
float32(visual.FG.G)/255.0,
float32(visual.FG.B)/255.0,
float32(visual.FG.A)/255.0,
)
screen.DrawImage(r.spriteSheet[visual.Name], opFG)
}
}
We loop through the game map, getting each Tile in turn and storing its Graphic in visual. Now, working with the image options for the foreground, we reset the geometry matrix and place the origin of the matrix at the correct location within the window. We don’t need to scale the foreground image, as it is already the correct size. Then we reset the color scale and apply the scaled color based on the RGBA values for the Graphic’s foreground. We then draw the sprite (r.spriteSheet[visual.Name]) with the correctly applied geometry and color.
Now, we do this process again for each of the entities:
for _, entity := range gameEngine.Entities() {
visual := entity.Graphic
if visual.BG.A > 0 {
opBG.GeoM.Reset()
opBG.GeoM.Scale(float64(r.tileWidth), float64(r.tileHeight))
opBG.GeoM.Translate(float64(entity.Loc.X*r.tileWidth),
float64(entity.Loc.Y*r.tileHeight))
opBG.ColorScale.Reset()
opBG.ColorScale.Scale(
float32(visual.BG.R)/255.0,
float32(visual.BG.G)/255.0,
float32(visual.BG.B)/255.0,
float32(visual.BG.A)/255.0,
)
screen.DrawImage(r.whitePixel, opBG)
}
}
for _, entity := range gameEngine.Entities() {
visual := entity.Graphic
opFG.GeoM.Reset()
opFG.GeoM.Translate(float64(entity.Loc.X*r.tileWidth),
float64(entity.Loc.Y*r.tileHeight))
opFG.ColorScale.Reset()
opFG.ColorScale.Scale(
float32(visual.FG.R)/255.0,
float32(visual.FG.G)/255.0,
float32(visual.FG.B)/255.0,
float32(visual.FG.A)/255.0,
)
screen.DrawImage(r.spriteSheet[visual.Name], opFG)
}
The process in these two passes is identical to the above two passes except that instead of running through all 80x50 tiles in the map, we are just running these two loops over the entities (currently the player and one monster).
Next, we have an implementation of the Layout() method that is used by the GameRunner wrapper from main():
func (r *Renderer) Layout(
outsideWidth, outsideHeight int,
) (screenWidth, screenHeight int) {
screenWidth = r.viewportCols * r.tileWidth
screenHeight = r.viewportRows * r.tileHeight
return screenWidth, screenHeight
}
Here, we are just doing the calculation of window size based on the sprite/tile size for our graphics.
Finally, we have the loadTileset() function:
func loadTileset(
spriteSheetName string,
tileWidth, tileHeight int,
) (SpriteSheet, error) {
tileset := make(map[string]*ebiten.Image)
spriteSheetFile, err := assets.AssetsFS.ReadFile(spriteSheetName)
if err != nil {
return nil, err
}
img, _, err := image.Decode(bytes.NewReader(spriteSheetFile))
if err != nil {
return nil, err
}
baseImage := ebiten.NewImageFromImage(img)
rect := image.Rect(
0*tileWidth,
1*tileHeight,
0*tileWidth+tileWidth,
1*tileHeight+tileHeight,
)
tileset["@"] = baseImage.SubImage(rect).(*ebiten.Image)
rect = image.Rect(
0*tileWidth,
0*tileHeight,
0*tileWidth+tileWidth,
0*tileHeight+tileHeight,
)
tileset[" "] = baseImage.SubImage(rect).(*ebiten.Image)
rect = image.Rect(
3*tileWidth,
0*tileHeight,
3*tileWidth+tileWidth,
0*tileHeight+tileHeight,
)
tileset["#"] = baseImage.SubImage(rect).(*ebiten.Image)
return tileset, nil
}
In this function, we create the map of sprite names to images. We then load the graphic file from our virtual filesystem and check for any errors. If there was an error, we return an empty SpriteSheet and the error.
Next, we decode what we read into an image and check for any errors. As above, we either return an empty SpriteSheet and the error or we continue processing.
The graphic file read from the virtual filesystem (a PNG) is then converted into an ebiten.Image.
Finally, we create a few sprites from the sprite sheet, one for the ‘@’, one for ’ ‘, and one for ‘#’, though we aren’t currently using ‘#’. If you look at dejavu10x10_gs_tc_transparent.png, you should be able to see that the ‘@’ glyph is in column 0, row 1, so we read a rectangle at (0 * tileWidth, 1 * tileHeight) to (0 * tileWidth + tileWidth, 1 * tileHeight + tileHeight). This is the bounding rectangle for the ‘@’ glyph. The same thing is done for the other two glyphs.
We then return the SpriteSheet and nil to indicate no error occurred.
You should now be able to run the program! At your command prompt, enter:
go run ./cmd/go-rogue/
and you should see this:

If you try to move the player through the wall, you should see the You walk into the wall. Ouch! message and if you try to move off of the map, you should see the A magical force prevents you from moving outside the bounds of the map. message.
Congratulations! That’s the end of Chapter 2! The complete state of the codebase at this point is available here:
In the next chapter, we will be generating a proper dungeon and we will add the ability to change between ASCII graphics and simple sprites!
If you have cloned my repository, You will notice that the source files from there have comments for every function/method and type declaration in a particular format, like the example here:
// GetAction for the player uses the [Game] struct's input field to read the // player's intention. First check if the player wants to quit, indicated by // having pushed the escape key. If not, check if the player wants to move, // indicated by having pushed one of the arrow keys, wasd or numpad keys. // If so, return the a [MovementAction] with the correct directional [Vector]. func (p *PlayerControl) GetAction(g *Game, e *Entity) Action {In Go, placing a comment like this directly above a top-level declaration is used for automatic generation of documentation. If you are using a smart editor like VS Code, the interface will use these comments to display information about the type of function. Identifiers in brackets,
[], act as links to that type or function. These comments must be directly above the declaration with no intervening blank. By convention, the first word should be the name of the identifier being documented.The github repository also has one additional source file in each of the packages called
doc.goThese files are a documentation comment for the package as a whole and look like this:// Package engine holds all of the logic and data for handling the game state. // It is decoupled from both rendering logic and knowledge of the Ebitengine. // If we want to use other renderers in the future, say a true terminal-based // renderer, or to use a game engine other than Ebitengine, this should make // it less painful. package engineIt’s not required to add these kinds of comments, but it’s defintely a good habit. I have never gone back to a piece of code I wrote a few months back and read it again thinking, “Gee, I put way too many comments in here.” But I have read some old code that left me scratching my head and wondering why I did something a particular way.