Go Rogue! - Chapter 3
Generating a dungeon

If you prefer to jump straight to the working Chapter 3 state instead of setting up the files by hand, and you have previously cloned the repository, checkout the
chapter-3branch or thev0.3.0tag:git checkout v0.3.0 go run ./cmd/go-rogue/This checks out the exact “Chapter 3” project end state and runs the project.
At the end of the last chapter, “The Generic Entity, the Render Functions, and the Map”, we had a very basic “dungeon”. It was mostly floor with a small wall that we could use to test that we can’t walk through it. We had a representation for the player and for a monster, both of which were data structures of type Entity. Finally, we got our project structured in a standard Go style.
Similar to the last chapter, a lot of things are going to be temporarily broken in this chapter as we work through it. Don’t worry, when we get to the end, everything will be back to working. I will try to be sure and point it out when it’s happening. At the end of this chapter, we will be able to create random dungeon levels. Not only that, we will take advantage of some of our structural work last chapter to do some neat things, like being able to choose for the game to be rendered using old-school ASCII style art, or simple sprites. In fact, we will have an extensible system that lets us swap in different sprite packs to change the look of the game.
First things first, your project should have an assets/ folder with a Go source file, assets.go, and a graphic file, dejavu10x10_gs_tc_transparent.png. If you are working from my repository, you may have some other files in there as well. If for some reason you don’t have the dejavu10x10_gs_tc_transparent.png file, download it here:
For this chapter, we are also going to need the sprite pack. I am using a 1-bit monochrome sprite pack from kenney.itch.io. You can download it here:
Make sure your files are the same as mine. I have added an extra “character” to the dejavu10x10_gs_tc_transparent.png file and I have made a color change in the monochrome-transparent_packed.png file.
We are going to add two new files to our assets/ folder. The first one is configuration.json. Here is the content for this file:
{
"tileset": "graphic",
"viewportCols": 80,
"viewportRows": 50,
"roomsMax": 100,
"roomsMin": 3,
"roomsWidthMin": 5,
"roomsWidthMax": 15,
"roomsHeightMin": 5,
"roomsHeightMax": 15
}
This file provides some configurable options for the game. The most important one is the tileset parameter. This can be set to either "ascii" or "graphic", depending on your preference of ascii display or sprite graphics. I will be using the "graphic" option, but feel free to use "ascii" if you prefer.
The next file we need to add is assets.json. This file provides the definitions for our art assets. You might want to just copy the contents because it is a bit long. This file will allow us to provide standard definitions for the art. It gives a name to the art pack, currently "ascii" and "graphics", specifies the file that holds the art, the size of the tiles, where in the file a particular sprite is located, what color we want it to be, and if it is rotated from from its orientation in the file. We will get into all of this a bit later in the chapter.
{
"graphic": {
"file": "monochrome-transparent_packed.png",
"tileWidth": 16,
"tileHeight": 16,
"sprites": {
"player": {
"imageLoc": {"x": 25, "y": 0},
"color": {"R": 255, "G": 255, "B": 255, "A": 255},
"rotation": 0
},
"monster": {
"imageLoc": {"x": 28, "y": 6},
"color": {"R": 255, "G": 255, "B": 0, "A": 255},
"rotation": 0
},
"wallVert": {
"imageLoc": {"x": 8, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallHoriz": {
"imageLoc": {"x": 8, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0.5
},
"wallTL": {
"imageLoc": {"x": 9, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallTR": {
"imageLoc": {"x": 9, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0.5
},
"wallBL": {
"imageLoc": {"x": 9, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 1.5
},
"wallBR": {
"imageLoc": {"x": 9, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 1
},
"wallTRight": {
"imageLoc": {"x": 10, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallTDown": {
"imageLoc": {"x": 10, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0.5
},
"wallTLeft": {
"imageLoc": {"x": 10, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 1.0
},
"wallTUp": {
"imageLoc": {"x": 10, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 1.5
},
"wall4Way": {
"imageLoc": {"x": 11, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallCapUp": {
"imageLoc": {"x": 12, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallCapRight": {
"imageLoc": {"x": 12, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0.5
},
"wallCapDown": {
"imageLoc": {"x": 12, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 1.0
},
"wallCapLeft": {
"imageLoc": {"x": 12, "y": 4},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 1.5
},
"floor": {
"imageLoc": {"x": 16, "y": 0},
"color": {"R": 100, "G": 100, "B": 100, "A": 255},
"rotation": 0
},
"bedrock": {
"imageLoc": {"x": 8, "y": 5},
"color": {"R": 0, "G": 0, "B": 0, "A": 255},
"rotation": 0
},
"whiteTile": {
"imageLoc": {"x": 8, "y": 5},
"color": {"R": 255, "G": 255, "B": 255, "A": 255},
"rotation": 0
}
}
},
"ascii": {
"file": "dejavu10x10_gs_tc_transparent.png",
"tileWidth": 10,
"tileHeight": 10,
"sprites": {
"player": {
"imageLoc": {"x": 0, "y": 1},
"color": {"R": 255, "G": 255, "B": 255, "A": 255},
"rotation": 0
},
"monster": {
"imageLoc": {"x": 6, "y": 4},
"color": {"R": 255, "G": 255, "B": 0, "A": 255},
"rotation": 0
},
"wallVert": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallHoriz": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallTL": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallTR": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallBL": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallBR": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallTUp": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallTDown": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallTLeft": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallTRight": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wall4Way": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallCapUp": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallCapDown": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallCapLeft": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"wallCapRight": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 50, "G": 50, "B": 50, "A": 255},
"rotation": 0
},
"floor": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 100, "G": 100, "B": 100, "A": 255},
"rotation": 0
},
"bedrock": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 0, "G": 0, "B": 0, "A": 255},
"rotation": 0
},
"whiteTile": {
"imageLoc": {"x": 25, "y": 2},
"color": {"R": 255, "G": 255, "B": 255, "A": 255},
"rotation": 0
}
}
}
}
Next, we need to make a slight change in assets/assets.go:
package assets
import (
"embed"
)
//go:embed *.png *.json
var AssetsFS embed.FS
Here we are telling the build system to embed all of the png files and json files into the embedded filesystem.
Now, let’s start building!
First, open up internal/engine/gameMap.go. At the end of Chapter 2, we had defined our GameMap structure as:
type GameMap struct {
cols, rows int
tiles []*Tile
}
And our NewGameMap() function was defined as:
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
}
We looped through all the tiles in our map, set them to floor, and then changed three of those tiles into a wall.
In this chapter we want to be able to make random dungeons, so we are going to start by making a change to the definition of the GameMap:
type GameMap struct {
cols, rows int
tiles []*Tile
rooms []RectangularRoom
}
We have added a new field to the GameMap, a slice of type RectangularRoom called rooms. This will be an error because we haven’t defined RectangularRoom yet, but we will get there shortly. We are also going to change our NewGameMap() function:
func NewGameMap(cols, rows int, roomsConfig RoomConfiguration) *GameMap {
gm := &GameMap{cols: cols, rows: rows}
gm.tiles = make([]*Tile, cols*rows)
for y := range rows {
for x := range cols {
gm.tiles[gm.GetIndex(Point{X: x, Y: y})] = bedrock
}
}
gm.rooms = make([]RectangularRoom, 0, roomsConfig.RoomsMax)
gm.GenerateDungeon(roomsConfig)
return gm
}
There are some more errors, here, but they will be fixed soon. The differences between our original and this version are that we have a new argument of type RoomConfiguration, we are filling the map with bedrock instead of floor, initializing the rooms slice to be empty, but reserving sufficient space for the maximum number of rooms, and then calling a new method, func(GameMap *) GenerateDungeon(roomsConfig RoomConfiguration) which we will be defining in a moment.
Earlier, we created configuration.json and you may have noticed that most of its fields were “room” things. We provided definitions for a maximum number of rooms, a minimum number of rooms, and minimum and maximum widths and heights for rooms. These values our going to be used for our RoomConfiguration structure. Let’s go ahead and define this structure in our gameMap.go file:
type RoomConfiguration struct {
RoomsMax int
RoomsMin int
RoomsWidthMin int
RoomsWidthMax int
RoomsHeightMin int
RoomsHeightMax int
}
A few more changes, and our new version of gameMap.go will be complete.
As I worked through writing the code for this chapter, I learned a few things about Ebitengine which lead me to making a few changes to the way we draw the screen. Because of these changes, we don’t need the Graphic struct that we had originally defined in Chapter 2. Go ahead and locate this definition in the gameMap.go file and remove it:
type Graphic struct {
Name string
FG color.NRGBA
BG color.NRGBA
}
We can also remove the declarations for the floor and wall variables. Find these two in gameMap.go and delete them:
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}}}
We also are going to need to change our definition of the Tile data structure because it used to have a field for a Graphic. Locate this definition in the gameMap.go file:
type Tile struct {
Walkable bool
Transparent bool
DarkGraphic *Graphic
}
Change the definition for this data structure to be:
type Tile struct {
Walkable bool
Transparent bool
SpriteName string
SpriteID int
}
We removed the DarkGraphic field and have added two new fields, SpriteName and SpriteID.
We are going to add two new method for GameMap, IsTransparent() and IsWall(). The IsWall() method will cause some errors for now, but they will be fixed by the end. Here are their definitions:
func (gm *GameMap) IsTransparent(p Point) bool {
return gm.tiles[gm.GetIndex(p)].Transparent
}
func (gm *GameMap) IsWall(p Point) bool {
if !gm.InBounds(p) {
return false
}
t := gm.tiles[gm.GetIndex(p)]
return (t == wallTL ||
t == wallTR ||
t == wallBR ||
t == wallBL ||
t == wallHoriz ||
t == wallVert ||
t == wallTRight ||
t == wallTDown ||
t == wallTLeft ||
t == wallTUp ||
t == wall4Way ||
t == wallCapUp ||
t == wallCapRight ||
t == wallCapDown ||
t == wallCapLeft)
}
The IsTransparent() method takes a Point as the argument and returns a boolean telling us if the tile at that coordinate is transparent.
The IsWall() method gets takes a Point and tests if it is located inside the bounds of the GameMap, returning false if it is not, and then obtaining the *Tile for that Point and testing if it is one of the wall-type tiles, returning true if it is and false if it isn’t.
With this change complete, we can go ahead and create the tiles. Create a new file, tiles.go in internal/engine/. This file is part of the engine package and will hold the definitions for all of the tiles in the game:
package engine
var (
floor = &Tile{
Walkable: true,
Transparent: true,
SpriteName: "floor",
}
wallTL = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallTL",
}
wallTR = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallTR",
}
wallBR = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallBR",
}
wallBL = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallBL",
}
wallHoriz = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallHoriz",
}
wallVert = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallVert",
}
wallTRight = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallTRight",
}
wallTDown = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallTDown",
}
wallTLeft = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallTLeft",
}
wallTUp = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallTUp",
}
wall4Way = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wall4Way",
}
wallCapUp = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallCapUp",
}
wallCapRight = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallCapRight",
}
wallCapDown = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallCapDown",
}
wallCapLeft = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "wallCapLeft",
}
bedrock = &Tile{
Walkable: false,
Transparent: false,
SpriteName: "bedrock",
}
whiteTile = &Tile{
SpriteName: "whiteTile",
}
)
The names for the tiles match the definitions we provided in assets.json and provide the Walkable and Transparent values. The last tile, whiteTile doesn’t provide values for Walkable and Transparent (which means they will be false, since that’s the default for a bool in Go). This is a special tile that isn’t actually displayed in the map and is used for applying color to other tiles.
Next, we are going to create a slice that holds pointers to all of these tiles:
var allTiles = []*Tile{
floor,
wallTL,
wallTR,
wallBR,
wallBL,
wallHoriz,
wallVert,
wallTRight,
wallTDown,
wallTLeft,
wallTUp,
wall4Way,
wallCapUp,
wallCapRight,
wallCapDown,
wallCapLeft,
bedrock,
whiteTile,
}
And finally, we are going to create a helper function that will bind the the tile’s name (the string value) to an int for faster lookup.
func BindTileSpriteIDs(nameToID map[string]int) {
for _, t := range allTiles {
if id, ok := nameToID[t.SpriteName]; ok {
t.SpriteID = id
}
}
}
Now we can do the work of actually generating the dungeon. Here is the basic algorithm we will use:
- Iterate through all the tiles of the map, setting them to bedrock.
- Select a random width, height, and location for a room candidate based on the values from the configuration file.
- Check if the room candidate overlaps any existing rooms. If it does, discard it. If it does not, it is now a room: set all the tiles in the inner area of this room to floor and add it to the list of rooms.
- The inner area of a room excludes the outermost ring of tiles bounded by the rectangle’s corners.
- Repeat this process until it has been attempted the maximum number of times specified by the configuration.
- Check if at least the minimum number of rooms were successfully created. If not, reset the map and start over.
- Iterate through the list of rooms, calculating the distance between the center of the current room and the center of each room that comes after it in the list. Identify which of these subsequent rooms is the closest neighbor.
- Because the second-to-last room only has the final room after it in the list, the final room is guaranteed to be connected without needing to search for its own neighbor.
- At the end of this process, if there are n rooms, we will have n - 1 room pairings.
- For each room pairing, build an L-shaped hallway between the two room centers:
- Starting at the center of the first room in the pair, randomly decide whether to tunnel along the vertical or horizontal axis first. Set each tile along the selected axis to a floor tile until reaching the coordinate of the second room’s center on that axis.
- Turn 90 degrees and set each tile along the remaining axis to a floor tile until reaching the center of the second room.
We now have a dungeon level with a list of rooms and hallways connecting them. The next stage is to lay down the wall tiles. If we had stuck to simple ascii graphics, this would be simple. We would just set every tile that touches a floor tile to a wall. However, because we could be using the graphical tile set, we have to think about whether a wall is running horizontally or vertically or if it is a corner, how the corner is oriented. Luckily, there is a fairly straightforward algorithm we can use for this:
- Scan each tile in the map. For any tile that is bedrock, if one of it’s 8 neighbors is a floor tile, set the current tile to a wall (it doesn’t matter what kind, I used a horizontal wall).
- We have now identified every tile that will be a wall, we just need to figure out what kind of wall tile it is.
- Scan each tile in the map again. For any tile that is a wall, calculate a bitmask for that tile based on its cardinal neighbors (the tiles directly above, below, to the left, and to the right).
- If this wall tile is connected to a wall tile directly above it and at least one of the two tiles being considered has a floor tile to its immediate left or right, set the zero bit (one’s place) to 1.
- If this wall tile is connected to a wall tile directly to the right and at least one of the two tiles being considered has a floor tile immediately above or below it, set the first bit (two’s place) to 1.
- If this wall tile is connected to a wall tile directly below it and at least one of the two tiles being considered has a floor tile to its immediate left or right, set the second bit (four’s place) to 1.
- If this wall tile is connected to a wall tile directly to the left and at least one of the two tiles being considered has a floor tile immediately above or below it, set the third bit (eight’s place) to 1.
- Using a lookup, determine the tile type for this bitmask and set the tile to the correct wall type.
Here is the lookup table we will use to determine the correct type of wall tile:
| Wall Glyph | BitMask | Tile Name | Description |
|---|---|---|---|
| 0000 | wall4Way | A 4-way intersection of walls or a pillar | |
| 0001 | wallCapDown | A wall end cap pointing down | |
| 0010 | wallCapLeft | A wall end cap pointing left | |
| 0011 | wallBL | Bottom left corner wall | |
| 0100 | wallCapUp | A wall end cap point up | |
| 0101 | wallVert | A vertical wall section | |
| 0110 | wallTL | Top left corner wall | |
| 0111 | wallTRight | A T-intersection wall pointing right | |
| 1000 | wallCapRight | A wall end cap pointing right | |
| 1001 | wallBR | A bottom right corner wall | |
| 1010 | wallHoriz | A horizontal wall section | |
| 1011 | wallTUp | A T-intersection wall pointing up | |
| 1100 | wallTR | Top right corner wall | |
| 1101 | wallTLeft | A T-intersection wall pointing left | |
| 1110 | WallTDown | A T-intersection wall pointing down | |
| 1111 | wall4Way | A 4-way intersection of walls or a pillar |
This algorithm may be a bit confusing at first, so here is a visual explanation:
A horizontal wallConsider the wall tile in the center of this grid. We first test if it is connected to a wall tile directly above it and it is not, so we leave the 20 bit as zero. Next we check if it is connected to a wall tile directly to the right and it is. We then check if at least one of these two tiles has a floor tile directly above or below. In this case, both tiles have a floor below them. We set the 21 bit to 1. We then check if it is connected to a wall tile directly below it and it is not, so we leave the 22 bit as a zero. Finally, we check if it is connected to a wall tile directly to the left and it is. We then check if either of these walls has a floor directly above or below and they do, so we set the 23 bit to 1. The bitmask for this tile is 1010, or 10.
Here is one more example of the bitmask calculation and tile type selection:
Top left cornerIn this example, we are setting the bits for the immediate right neighbor (21) and the below neighbor (22). The bits for immediate left neighbor (23) and the above neighbor (20) are left unset. The bitmask for this tile is 0110, or 6. According to the lookup table, this tile should be a top left corner tile and we see that it is.
Ok, so we have our algorithm for creating a dungeon level with rooms that have a random size and a random location. We have an algorithm for connecting the rooms with hallways. Finally, we have an algorithm figuring out what shape a particular wall tile needs to be. Let’s dig into the implementation! Create a new source file in the internal/engine/ directory named procGen.go. This file is part of the engine package and since we know we are going to be doing some random selections and distance calculations, we will import the math and random packages. So put at the start of the file:
package engine
import (
"math"
"math/rand/v2"
)
First thing we need is a room. We changed the definition of the GameMap struct in this chapter to include a slice of of type RectangularRoom, so we need to define that. A rectangle can be defined very simply by the top left and bottom right corner locations, so we will use that:
type RectangularRoom struct {
topLeft Point
bottomRight Point
}
We are also going to create a method for GameMap to create a room once we have decided the size and where it belongs. We will define that method like this:
func (gm *GameMap) NewRectangularRoom(topLeft, bottomRight Point) {
rr := RectangularRoom{topLeft, bottomRight}
floorTopLeft, floorBottomRight := rr.InnerArea()
for y := floorTopLeft.Y; y < floorBottomRight.Y; y++ {
for x := floorTopLeft.X; x < floorBottomRight.X; x++ {
gm.tiles[gm.GetIndex(Point{x, y})] = floor
}
}
gm.rooms = append(gm.rooms, rr)
}
This method creates a new RectangularRoom structure, given the two bounding points. We then call a method on the RectangularRoom to give us the InnerArea(). When we decide the size and location of a room, the “outer ring” of that room is where we are going to place the walls. Remember from our map creation algorithm, once all the rooms are placed, we change every bedrock tile that touches a floor tile into a wall. InnerArea() tells us the bounding box for the floor. We iterate through the room’s inner area and set all of those tiles to floor. Finally, we put the newly created room in the GameMaps slice of rooms.
Let’s define that InnerArea() method for RectangularRoom next:
func (rr RectangularRoom) InnerArea() (Point, Point) {
return Point{X: rr.topLeft.X + 1, Y: rr.topLeft.Y + 1},
Point{X: rr.bottomRight.X, Y: rr.bottomRight.Y}
}
If you are wondering why we moved the topLeft.X and topLeft.Y in and down one point, but left the bottomRight.X and bottomRight.Y where they were, this is because we run our loops on a inclusive interval for the start point but an exclusive interval for the end point:
Carving out the floorWe will also need a method to obtain the center point for a room, so let’s define that:
func (rr RectangularRoom) Center() Point {
centerX := (rr.topLeft.X + rr.bottomRight.X) / 2
centerY := (rr.topLeft.Y + rr.bottomRight.Y) / 2
return Point{X: centerX, Y: centerY}
}
Finally, we need a method to determine if one room overlaps another:
func (rr RectangularRoom) Overlap(room RectangularRoom) bool {
return rr.topLeft.X <= room.bottomRight.X &&
rr.bottomRight.X >= room.topLeft.X &&
rr.topLeft.Y <= room.bottomRight.Y &&
rr.bottomRight.Y >= room.topLeft.Y
}
Here, we check if the X coordinate of the top left corner of the room calling the method is to the left of the X coordinate of the bottom right corner of the room passed in the argument. Then, we check if the X coordinate of the bottom right corner of the calling room is to the right of the X coordinate of the top left corner of the argument room. Next, we check if the Y coordinate of the top left corner of the calling room is above the Y coordinate of the bottom right corner of the argument room. Finally we check if the Y coordinate of the bottom right corner of the calling room is below the Y coordinate of the top left corner of the argument room. If all of these conditions are true, then the rooms overlap. As long as one of the conditions is not true, the rooms do not overlap.
We are now ready to define the GenerateDungeon() method:
func (gm *GameMap) GenerateDungeon(roomConfig RoomConfiguration) {
var overlap = false
for range roomConfig.RoomsMax {
roomWidth := rand.N(roomConfig.RoomsWidthMax-roomConfig.RoomsWidthMin+1) +
roomConfig.RoomsWidthMin
roomHeight := rand.N(roomConfig.RoomsHeightMax-roomConfig.RoomsHeightMin+1) +
roomConfig.RoomsHeightMin
x := rand.N(gm.cols - roomWidth - 1)
y := rand.N(gm.rows - roomHeight - 1)
candidateRoom := RectangularRoom{
topLeft: Point{X: x, Y: y},
bottomRight: Point{X: x + roomWidth, Y: y + roomHeight},
}
for i := range gm.rooms {
if gm.rooms[i].Overlap(candidateRoom) {
overlap = true
break
}
}
if !overlap {
gm.NewRectangularRoom(candidateRoom.topLeft, candidateRoom.bottomRight)
}
overlap = false
}
if len(gm.rooms) < roomConfig.RoomsMin {
gm.rooms = make([]RectangularRoom, 0, roomConfig.RoomsMax)
for y := range gm.rows {
for x := range gm.cols {
gm.tiles[gm.GetIndex(Point{X: x, Y: y})] = bedrock
}
}
gm.GenerateDungeon(roomConfig)
return
}
gm.MakeHalls()
gm.MakeWalls()
}
We begin by assuming there is no overlap between rooms (this is certainly true, because there are no rooms yet). we then begin a loop that will iterate roomConfig.RoomsMax times. We have defined this to be the maximum number of rooms we will attempt to create. We generate a room width in the range [roomsConfig.RoomsWidthMin, roomsConfig.RoomsWidthMax] and a height in the range [roomsConfig.RoomsHeighthMin, roomsConfig.RoomsHeightMax]. We then randomly select an X and Y coordinate to be the top left corner of the room, leaving enough space that the room will fit in the map. We then iterate over any existing rooms, checking if there is overlap with this new candidate room. If we find that it does overlap an existing room, we discard it and start the next attempt at placing a candidate room. If there is no overlap, we call the GameMap’s NewRectangularRoom() method. This sets the inner area of the room to floor tiles and adds the room to the map’s room slice. Once the we have completed roomConfig.RoomsMax attempts to place a room, we check if at least roomConfig.RoomsMin rooms were successfully created. If not, we reset the slice of rooms and reset all the tiles in the map to bedrock. We then kick off another attempt to generate the map. Once we have completed a room creation run that resulted in enough rooms, we call the GameMap’s MakeHalls() and MakeWalls() methods.
First, I’ll show the code for this method, and then we will go over it:
func (gm *GameMap) MakeHalls() {
type LeastDistance struct {
Room1, Room2 int
Distance float64
}
distances := make([]LeastDistance, len(gm.rooms)-1)
for i := range len(gm.rooms) - 1 {
leastDistance := LeastDistance{Distance: math.Inf(1)}
center1 := gm.rooms[i].Center()
for j := i + 1; j < len(gm.rooms); j++ {
center2 := gm.rooms[j].Center()
distance := math.Sqrt(
float64(
((center1.X - center2.X) * (center1.X - center2.X)) +
((center1.Y - center2.Y) * (center1.Y - center2.Y)),
),
)
if distance < leastDistance.Distance {
leastDistance.Distance = distance
leastDistance.Room1 = i
leastDistance.Room2 = j
}
}
distances[i] = leastDistance
}
for i := range len(gm.rooms) - 1 {
start := gm.rooms[distances[i].Room1].Center()
end := gm.rooms[distances[i].Room2].Center()
current := start
if rand.N(2) == 0 {
for current.Y < end.Y {
current.Y++
gm.tiles[gm.GetIndex(current)] = floor
}
for current.Y > end.Y {
current.Y--
gm.tiles[gm.GetIndex(current)] = floor
}
for current.X < end.X {
current.X++
gm.tiles[gm.GetIndex(current)] = floor
}
for current.X > end.X {
current.X--
gm.tiles[gm.GetIndex(current)] = floor
}
} else {
for current.X < end.X {
current.X++
gm.tiles[gm.GetIndex(current)] = floor
}
for current.X > end.X {
current.X--
gm.tiles[gm.GetIndex(current)] = floor
}
for current.Y < end.Y {
current.Y++
gm.tiles[gm.GetIndex(current)] = floor
}
for current.Y > end.Y {
current.Y--
gm.tiles[gm.GetIndex(current)] = floor
}
}
}
}
In MakeHalls(), we define a data structure to store two integers which will be the IDs for a pair of rooms and a floating point value to store the distance between the two rooms. Starting with room 0, we calculate the distance between the center of this room and the center of each of the rooms that come after it in the map’s slice of rooms. We keep track of the shortest distance and when we get to the end, we have identified a nearest neighbor for room 0. This process then repeats for the remaining rooms. We calculate the distance between the center of room 1 and the center of all of the rooms that come after it in map’s slice of rooms. When this process is done, for a set of n rooms, we will have n-1 pairings. Because we restricted the search for the closest neighbor to only consider rooms that come after the current room in the list, we are guaranteed that all of the rooms are connected and no rooms are orphaned from the remainder of the map. Next, we randomly select between two options. We will either begin our L-shaped corridor by traversing the X-axis or by traversing the Y-axis. We move along the selected axis, setting each of the tiles to a floor. When we intercept the center line of the paired room on the opposite axis, we traverse that axis and once again set all of the tiles to a floor.
Now, we have carved out rooms and hallways from the bedrock of our dungeon map. It’s time to put up the walls. This is handled by the GameMap’s MakeWalls() method:
func (gm *GameMap) MakeWalls() {
for y := range gm.rows {
for x := range gm.cols {
p := Point{X: x, Y: y}
i := gm.GetIndex(p)
if gm.tiles[i] == bedrock && gm.touchesFloor(p) {
gm.tiles[i] = wallHoriz
}
}
}
for y := range gm.rows {
for x := range gm.cols {
pt := Point{X: x, Y: y}
if gm.IsWall(pt) {
mask := gm.getWallBitmask(pt)
gm.tiles[gm.GetIndex(pt)] = gm.getWallTileForMask(mask)
}
}
}
}
It is done in two passes. In the first pass, we scan the map and set any bedrock tile that has a floor tile as one of its eight neighbors to a wall. Here is the touchesFloor() method definition:
func (gm *GameMap) touchesFloor(p Point) bool {
for dy := -1; dy <= 1; dy++ {
for dx := -1; dx <= 1; dx++ {
if dx == 0 && dy == 0 {
continue
}
neighbor := Point{X: p.X + dx, Y: p.Y + dy}
if gm.isFloor(neighbor) {
return true
}
}
}
return false
}
func (gm *GameMap) isFloor(p Point) bool {
if !gm.InBounds(p) {
return false
}
return gm.tiles[gm.GetIndex(p)] == floor
}
In the second pass, we scan the map and for every wall tile, we calculate a bitmask based if/how it connects to any other wall tiles. Here is the getWallBitmask() method and the helper functions it uses:
func (gm *GameMap) getWallBitmask(p Point) int {
mask := 0
if gm.connectsVertically(p, Point{X: p.X, Y: p.Y - 1}) {
mask |= 1
}
if gm.connectsHorizontally(p, Point{X: p.X + 1, Y: p.Y}) {
mask |= 2
}
if gm.connectsVertically(p, Point{X: p.X, Y: p.Y + 1}) {
mask |= 4
}
if gm.connectsHorizontally(p, Point{X: p.X - 1, Y: p.Y}) {
mask |= 8
}
return mask
}
func (gm *GameMap) connectsVertically(p1, p2 Point) bool {
dy := p1.Y - p2.Y
if p1.X != p2.X || (dy != 1 && dy != -1) {
return false
}
if !gm.IsWall(p1) || !gm.IsWall(p2) {
return false
}
return gm.isFloor(Point{X: p1.X - 1, Y: p1.Y}) ||
gm.isFloor(Point{X: p1.X + 1, Y: p1.Y}) ||
gm.isFloor(Point{X: p2.X - 1, Y: p2.Y}) ||
gm.isFloor(Point{X: p2.X + 1, Y: p2.Y})
}
func (gm *GameMap) connectsHorizontally(p1, p2 Point) bool {
dx := p1.X - p2.X
if p1.Y != p2.Y || (dx != 1 && dx != -1) {
return false
}
if !gm.IsWall(p1) || !gm.IsWall(p2) {
return false
}
return gm.isFloor(Point{X: p1.X, Y: p1.Y - 1}) ||
gm.isFloor(Point{X: p1.X, Y: p1.Y + 1}) ||
gm.isFloor(Point{X: p2.X, Y: p2.Y - 1}) ||
gm.isFloor(Point{X: p2.X, Y: p2.Y + 1})
}
We start by clearing the mask and then check if the tile we are considering at Point p is considered vertically connected to a wall directly above it on the map. The connectsVertically() method first verifies that the two points are vertically adjacent. Then it checks if both tiles are walls. Finally, it verifies that at least one of the two tiles has a floor tile to the left or the right. Next, we check if the tile at Point p is horizontally connected to wall directly to the right. The connectsHorizontally() method is essentially the same as connectsVertically() with the exception that in the last step, we verify that at least one of the two wall tiles has a floor tall directly above or below it.
We have a total of 15 types of wall tiles. Two of the bitmasks, 0000 (0) and 1111 (15), map to wall4Way (a wall surrounded by walls or completely by itself). A wall with walls to the left and to the right will map to 1010 (10), which is a horizontal wall. A wall with a wall to the left, but not to the right, will map to 1000 (8), which is a wallCapRight. A wall with a wall below it and a wall to the right of it will map to 0110 (6), which is a wallTL (a top left corner piece). A wall with a wall below it, to the left of it and to the right of it but not above it will map to 1110 (14), which is a wallTDown (a T-intersection with the wall continuing below). The bit ordering is LDRU, meaning the most significant bit is set if there is a connected wall to the left and the second most significant bit is set if there is a connected wall below, etc.
We can use this to look up the correct wall tile with the getWallTileForMask() method:
func (gm *GameMap) getWallTileForMask(mask int) *Tile {
switch mask {
case 1:
return wallCapDown
case 2:
return wallCapLeft
case 4:
return wallCapUp
case 8:
return wallCapRight
case 5:
return wallVert
case 10:
return wallHoriz
case 3:
return wallBL
case 6:
return wallTL
case 9:
return wallBR
case 12:
return wallTR
case 7:
return wallTRight
case 11:
return wallTUp
case 13:
return wallTLeft
case 14:
return wallTDown
case 0, 15:
return wall4Way
default:
return wall4Way
}
}
Next up, we are going to make some optimizations in our renderer. Open internal/renderer/renderer.go.
We will need to add a couple of imports at the top of the file:
package renderer
import (
"bytes"
"encoding/json"
"image"
"image/color"
_ "image/png"
"math"
"github.com/FooWho/go-rogue/assets"
"github.com/FooWho/go-rogue/internal/engine"
"github.com/hajimehoshi/ebiten/v2"
)
Next, we are going to make a change to the definition of the SpriteSheet. In Chapter 2, it was a map[string]*ebiten.Image. This let us lookup sprites by name, but has a cost of having to hash the string every time we lookup a sprite. Instead, we are going to define it like this:
type SpriteSheet []*Sprite
Next, we need to add a definition for our new Sprite type:
type Sprite struct {
Img *ebiten.Image
ColorScale ebiten.ColorScale
GeoM ebiten.GeoM
}
Now, we are going to add a SpriteConfig type that we will use when we read in the sprite definitions from the assets.json file:
type spriteConfig struct {
ImageLoc engine.Point `json:"imageLoc"`
Color color.NRGBA `json:"color"`
Rotation float64 `json:"rotation"`
}
Next, we will change the definition for our Renderer structure. In chapter 2, it was defined as:
type Renderer struct {
spriteSheet SpriteSheet
whitePixel *ebiten.Image
tileWidth, tileHeight int
viewportCols, viewportRows int
}
However, we are not going to need the whitePixel field anymore, so we can remove that and define the Renderer as:
type Renderer struct {
spriteSheet SpriteSheet
tileWidth, tileHeight int
viewportCols, viewportRows int
}
We need some helpers to handle reading in the assets.json file and building our sprite atlas. Let’s define a couple of types first:
type AssetConfigurationSet map[string]AssetConfiguration
type AssetConfiguration struct {
FileName string `json:"file"`
TileWidth int `json:"tileWidth"`
TileHeight int `json:"tileHeight"`
AssetTilesMap map[string]spriteConfig `json:"sprites"`
}
An AssetConfigurationSet is the set of all AssetConfigurations defined in assets.json. This type maps the name of the AssetConfiguration to its definition. The AssetConfiguration type knows the name of the file that the sprites are stored in, the size of our sprites/tiles, and then has a map of sprite names to sprite configurations.
Here is the function to read and process assets.json:
func loadAssetConfigurationSet() (AssetConfigurationSet, error) {
assetConfigurationFile, err := assets.AssetsFS.ReadFile("assets.json")
if err != nil {
return nil, err
}
var assetConfigurationSet AssetConfigurationSet
err = json.Unmarshal(assetConfigurationFile, &assetConfigurationSet)
if err != nil {
return nil, err
}
return assetConfigurationSet, nil
}
This function reads assets.json from the embedded file system. It then parses the file to build asset configurations and returns that mapping, or an error if something went wrong.
Next, we need to make some changes to the loadTileset() function. Locate that function definition and replace it with:
func loadTileset(
assetConfiguration AssetConfiguration) (SpriteSheet, map[string]int, error) {
tileset := make([]*Sprite, len(assetConfiguration.AssetTilesMap))
namesToIDs := make(map[string]int, len(assetConfiguration.AssetTilesMap))
spriteSheetFile, err := assets.AssetsFS.ReadFile(
assetConfiguration.FileName,
)
if err != nil {
return nil, nil, err
}
img, _, err := image.Decode(bytes.NewReader(spriteSheetFile))
if err != nil {
return nil, nil, err
}
baseImage := ebiten.NewImageFromImage(img)
i := 0
halfW := float64(assetConfiguration.TileWidth) / 2
halfH := float64(assetConfiguration.TileHeight) / 2
for k, v := range assetConfiguration.AssetTilesMap {
tmpSpriteConfig := v
x0 := tmpSpriteConfig.ImageLoc.X * assetConfiguration.TileWidth
y0 := tmpSpriteConfig.ImageLoc.Y * assetConfiguration.TileHeight
x1 := tmpSpriteConfig.ImageLoc.X*assetConfiguration.TileWidth + assetConfiguration.TileWidth
y1 := tmpSpriteConfig.ImageLoc.Y*assetConfiguration.TileHeight + assetConfiguration.TileHeight
rect := image.Rect(x0, y0, x1, y1)
tmpSprite := Sprite{}
tmpSprite.Img = baseImage.SubImage(rect).(*ebiten.Image)
if tmpSpriteConfig.Rotation != 0 {
tmpSprite.GeoM.Translate(-halfW, -halfH)
tmpSprite.GeoM.Rotate(math.Pi * tmpSpriteConfig.Rotation)
tmpSprite.GeoM.Translate(halfW, halfH)
}
tmpSprite.ColorScale.ScaleWithColor(tmpSpriteConfig.Color)
tileset[i] = &tmpSprite
namesToIDs[k] = i
i++
}
return tileset, namesToIDs, nil
}
We pass the function an AssetConfiguration. A slice is created to the correct number of *Sprite instances based on the size of the AssetTilesMap field of the argument. We also create a map of appropriate size to hold the mapping from sprite names to sprite IDs. We then read in the graphic file specified by the AssetConfiguration and decode it to an Image. This is used to create a pointer to an ebiten.Image. Before entering the main loop, we precalculate half of the width and height for rotations. We then iterate over the key, value pairs of the AssetTilesMap. The key is the sprite name and the value is the SpriteConfig. We obtain the sub-image of the sprite from the larger image and if needed, we rotate it. Since the origin of the sub-image is the top left corner, we need to shift it to the left and up by half of the width and height. This places the origin at the center of the image, which is then rotated, and finally shifted back to the original origin. Any color tinting is performed and the final image is stored tileset slice at the current index. We then store that index in the map, using the sprite name as the key and increment the index. When we have iterated through all of the sprite definitions, we return the tileset slice, the mapping of names to IDs, and nil to indicate there were no errors (if there had been an error, we would have previously returned the error, with the slice and map set to nil).
We are going to change the definition of NewRenderer() to handle loading the AssetConfigurationSet and selecting the correct AssetConfiguration. Here is the new function definition:
func NewRenderer(
viewportCols, viewportRows int, tilesetName string,
) (*Renderer, map[string]int, error) {
assetConfigurationSet, err := loadAssetConfigurationSet()
if err != nil {
return nil, nil, err
}
assetConfiguration := assetConfigurationSet[tilesetName]
spriteSheet, namesToIDs, err := loadTileset(assetConfiguration)
if err != nil {
return nil, nil, err
}
engine.BindTileSpriteIDs(namesToIDs)
ebiten.SetWindowSize(1280, 800)
ebiten.SetWindowTitle("Go Rogue!")
return &Renderer{spriteSheet: spriteSheet,
tileWidth: assetConfiguration.TileWidth,
tileHeight: assetConfiguration.TileHeight,
viewportCols: viewportCols,
viewportRows: viewportRows,
},
namesToIDs,
nil
}
We pass in the number columns and rows in the view port and the name of the tileset that we want to load. We return a pointer to the configured Renderer and the mapping from sprite names to sprite IDs, or an error.
First, the AssetConfigurationSet is loaded and the correct AssetConfiguration is selected. Then sprite sheet and the sprite name to sprite ID map are created. The BindTileSpriteIDs() function that we defined earlier is called to set the SpriteID field for all of the Tile structures. We set the window size and title, then assign the fields to the Renderer struct and return it along with the mapping of sprite names to sprite IDs. This map will be needed later by the game engine for instantiation of entities.
The last change we need to make in the Renderer is the Draw() method. In chapter 2, our Draw() method iterated over the map to draw the background and then did it again to draw the foreground. We used the whitePixel field to apply color tints. The new Draw() method is a lot cleaner:
func (r *Renderer) Draw(screen *ebiten.Image, gameEngine *engine.Game) {
op := &ebiten.DrawImageOptions{}
tileWidth := float64(r.tileWidth)
tileHeight := float64(r.tileHeight)
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 := r.spriteSheet[tile.SpriteID]
op.GeoM = visual.GeoM
op.GeoM.Translate(
float64(x)*tileWidth,
float64(y)*tileHeight,
)
op.ColorScale = visual.ColorScale
screen.DrawImage(visual.Img, op)
}
}
for _, entity := range gameEngine.Entities() {
visual := r.spriteSheet[entity.SpriteID]
op.GeoM = visual.GeoM
op.GeoM.Translate(
float64(entity.Loc.X)*tileWidth,
float64(entity.Loc.Y)*tileHeight,
)
op.ColorScale = visual.ColorScale
screen.DrawImage(visual.Img, op)
}
}
Color tinting and rotation of sprites was already performed when the sprite was loaded. We don’t have a separate background and foreground. We no longer need the map lookup to locate the sprite. Now, the Draw() method loops over the map, gets the tile sprite by ID, loads its precalculated geometry and color scaling and applies them, then draws the sprite to the screen. Because all of our sprites are coming from one sprite sheet, our calls to DrawImage() should be able to be batched by Ebitengine. Once the map has been drawn, we iterate over the entities, load their sprites and apply the precalculated geometry and color tint and draw them to the screen as well.
With the Renderer complete, we need to make a change in the definition of the Entity type. Open internal/engine/entity.go.
In chapter 2, we defined Entity as:
type Entity struct {
Loc Point
Name string
Graphic Graphic
Behavior Behavior
}
Since we no longer have the Graphic type, we need to replace that with a SpriteName and SpriteID:
type Entity struct {
Loc Point
Name string
SpriteName string
SpriteID int
Behavior Behavior
}
That is the only change needed in this file.
We have one last file to modify our internal packages. Open internal/engine/game.go.
In the last chapter, our Game struct was define as:
type Game struct {
player *Entity
entities []*Entity
gameMap *GameMap
input Input
}
We are going to change that to:
type Game struct {
player *Entity
entities []*Entity
namesToIDs map[string]int
gameMap *GameMap
roomConfiguration RoomConfiguration
input Input
}
We also need to make some changes to the helper function we use to construct the Game. Locate the definition for NewGame() and change it like so:
func NewGame(
mapWidth, mapHeight int,
player *Entity,
npcs []*Entity,
input Input,
roomsConfig RoomConfiguration,
namesToIDs map[string]int,
) (*Game, error) {
game := &Game{
player: player,
entities: append([]*Entity{player}, npcs...),
namesToIDs: namesToIDs,
gameMap: NewGameMap(mapWidth, mapHeight, roomsConfig),
roomConfiguration: roomsConfig,
input: input,
}
player.Loc = game.gameMap.rooms[0].Center()
game.entities[1].Loc = game.gameMap.rooms[len(game.gameMap.rooms)-1].Center()
return game, nil
}
The change is pretty minor, we are now passing in the roomsConfig data structure and the namesToIDs map and storing those inside the Game. We are also placing the player in the center of the first room and the monster in the center of the last room. This is so they don’t end up in bedrock.
Finally, there are some changes we need to make in cmd/go-rouge/main.go to glue everything together, so go ahead and open that file now.
We need to make a few changes to the imports:
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"github.com/FooWho/go-rogue/assets"
"github.com/FooWho/go-rogue/internal/engine"
"github.com/FooWho/go-rogue/internal/renderer"
"github.com/hajimehoshi/ebiten/v2"
)
We need to define a type for the configuration information we will read in from configuration.json:
type ConfigurationFile struct {
Tileset string `json:"tileset"`
ViewPortCols int `json:"viewPortCols"`
ViewPortRows int `json:"viewPortRows"`
RoomsMax int `json:"roomsMax"`
RoomsMin int `json:"roomsMin"`
RoomsWidthMin int `json:"roomsWidthMin"`
RoomsWidthMax int `json:"roomsWidthMax"`
RoomsHeightMin int `json:"roomsHeightMin"`
RoomsHeightMax int `json:"roomsHeightMax"`
}
We can now eliminate the constants that we were using in Chapter 2, as these are contained in our configuration file. In that chapter we had this definition:
const (
gameCols = 80
gameRows = 50
tileWidth = 10
tileHeight = 10
playerX = (gameCols / 2)
playerY = (gameRows / 2)
)
It is no longer needed and can be removed.
Finally, here is our new main() function:
func main() {
configurationFile, err := assets.AssetsFS.ReadFile("configuration.json")
if err != nil {
log.Fatal(err)
}
var config ConfigurationFile
err = json.Unmarshal(configurationFile, &config)
if err != nil {
log.Fatal(err)
}
input := &EbitenInput{}
renderer, namesToIDs, err :=
renderer.NewRenderer(
config.ViewPortCols,
config.ViewPortRows,
config.Tileset,
)
if err != nil {
log.Fatal(err)
}
player := &engine.Entity{
Name: "player",
SpriteName: "player",
SpriteID: namesToIDs["player"],
Behavior: &engine.PlayerControl{},
}
npc := &engine.Entity{
Name: "monster",
SpriteName: "monster",
SpriteID: namesToIDs["monster"],
Behavior: nil,
}
npcs := []*engine.Entity{npc}
roomsConfig := engine.RoomConfiguration{
RoomsMax: config.RoomsMax,
RoomsMin: config.RoomsMin,
RoomsWidthMin: config.RoomsWidthMin,
RoomsWidthMax: config.RoomsWidthMax,
RoomsHeightMin: config.RoomsHeightMin,
RoomsHeightMax: config.RoomsHeightMax,
}
game, err := engine.NewGame(
config.ViewPortCols,
config.ViewPortRows,
player,
npcs,
input,
roomsConfig,
namesToIDs,
)
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 read in the configuration file from the embedded file system and unmarshal it into the data structure that we defined above. We set up the input handler. Then, we configure a new Renderer structure. This also provides us with the namesToIDs map that we will need for the engine. We construct our initial player and monster entities and create a slice for holding npcs. We then configure a RoomConfiguration structure with the room parameters we read from the configuration file. Now, we can construct the GameRunner wrapper and pass it in to ebiten.RunGame(). The game will run until we encounter a fatal error or signal termination from the game loop.
And that’s it for Chapter 3! Congratulations!
The full code base to this point in the repository is available here to view:
In the next chapter, we will be working on Field of View!














