Snake game implementation in Go using a 2-dimensional array.
download the package
git clone https://github.com/twiny/snakycd snaky/
run the game directly using the Go command
go run cmd/launcher/main.go -x 30 -y 15 -s slow
or build it
go build -o snaky -v cmd/launcher/main.gochmod +x ./snaky
./snaky -hprint help message.-xgame grid width-ygame grid height-sgame speed (string default: medium) - slow|medium|fast
keyboard arrow keychanges Snake direction.SKey starts the game.PKey pauses the game.Rrestart the game.ESCorCtrl+Cexit the game.
The snake game logic:
-
The snake keeps on moving in a straight line unless the direction is changed.
-
If the snake ate the food it grows. then a new food will be placed on the grid. the new position must not be on the snake body nor the same as the previous one.
-
If the snake bites itself or hits the wall, the game ends.
The snaky game consist of two main structures:
Game struct that represents the current game. it contains Snake, Food & Board structs
Boardholds the current game information:Gridis a 2d array. where snake body and food will be marked/mapped for renderingCellis the coordinate of a point on the gridIconused to paint the Cell when rendering board.
A Renderer is an interface that renders the game Board, and it consists of two methods.
Listen(chan Event) error: this listens to user inputs and sends them to a channel ofEvent.Render(b *Board) error: this renders a gameBoardand prints it to the user. This way,renderercan be easily replaced.
The renderer range the grid Cell by Cell and depends on its value (Icon) it either print Head, Body, or Food.
- fix case food is generated on snake body.
- snake auto move forward.
- fix snake moving direction.
- change food icon.
- fix when snake hit itself or borders.
- show a message to the user when the game ends/restarts.
- initially the snake is stopped. disable auto-start.
- add more test cases.
