Snake game in Go using Ebiten
Ebiten is an open source game library in Go for building 2D games that can be ran across multiple platforms. Ebiten games work on desktop, web browsers (through WebAssembly), as well as on Mobile and even on Nintendo Switch.
I wanted to make a video building this game on my package main Youtube channel, but it would be too long, therefore I’m presenting you a text version of it.
We’ll give it a try and create a Snake game in Go, which we’ll run in the browser using WebAssembly.
The full code of this game can be found here.
Ebiten API
To create a new game we have to implement an ebiten.Game
interface which consist of the following functions as it shown on the image above:
Update()
- update the logical stateDraw(screen *ebiten.Image)
- render the screenLayout(outsideWidth, outsideHeight int)
- define the size of the screen
Let’s create our Snake
struct to implement these methods. For now it will do nothing, except setting the size of the screen and filling it with a background. We want to confirm that we can compile it and see the results in the browser.
snake/game.go
|
|
main.go
|
|
Compiling into WebAssembly
As I mentioned before we’ll run this game in a browser, as it’s easy to compile it in WebAssembly. There are 2 options running this game in the browser.
- We can just compile it manually and create our own HTML file
- We can use wasmserve project that will compile a code and run it in the browser for us
For simplicity I’ll use the second option.
|
|
Then if we open http://localhost:8080/ we should see a gray-ish square.
Snake Logic
Now we can write a snake logic that we’ll be using later in functions Update
and Draw
.
Food
Food
struct simply describes the point on the board that snake should eat.
snake/food.go
|
|
Input
struct is using inpututil
Ebiten’s package to check the latest key pressed.
snake/input.go
|
|
Snake
has logic on how to move a snake and has few functions to check for collisions.
snake/snake.go
|
|
Now we can combine these types in our new Board
struct that will define a game board.
Board
has an Update
function that will be called from our Game.Update()
method. Ebiten runs Update()
aroudn 60/s that’s why we need some intervals logic there to prevent snake moving too fast. For example we start with snake moving at move/200ms, and when it grows it will speed up to move/100s.
Board
struct also holds information such as points
and gameOver
so in case snake hits the wall or itself, we can later just render a message.
snake/board.go
|
|
What’s left is to make few updates to our game.go
file to initialize the Board
and render the snake/food at each current state .
snake/game.go
|
|
Playing the game
Repeat wasmserve .
or just refresh the page and you’ll be able to play the game.
Source code
github.com/plutov/packagemain/tree/master/drafts/ebiten-snake