Site icon Golang Libraries, Apps, Golang Jobs and Go Tutorials

Tutorial – Code a Simple Game In Golang

This article will explore how to code a character sprite that can walk around on an image background using Golang, the Image package, and the Fyne GUI toolkit

Some time ago, I followed some exciting tutorials by Frank’s Laboratory on how to code games in JavaScript. I have decided to code one of his simple games in Golang using the Fyne GUI toolkit for this article instead of JavaScript.

The structure of the code I present to you here will also be somewhat different from the original by Frank’s Laboratory, given that Golang works differently from JavaScript.

As in his video tutorial, we won’t be building a complete game. You’ll be able to move a character around on a background image using the arrow keys on your keyboard. Nevertheless, this could be the start of an actual game.

The Game Assets

Below, you can see the two-game elements used in this project.

We’ll use a Starwars background and a sprite sheet featuring Chewbacca. “Chewie.” The original links to these assets can be found on the YouTube page of the tutorial by Frank’s Laboratory.

The background image (left) and the character sprite sheet (right)

Once you have downloaded them, these PNG image game assets should be placed in a folder called ./assets below the folder in which the Go code is run.

The Golang Packages That We’ll Be Using

An Overview Of The Golang Code

The Player and Game models

In lines 1–16, we define the Player struct.

The xand y fields refer to the position of the player in the game.

The width and height are the size of each sprite on the sprite sheet.

The variables frameX and frameY refer to the sprite position on the sprite sheet in the x and y directions, respectively.

The field cyclesX counts the number of sprites in the X direction on the sprite sheet. When the player walks, these sprites will repeatedly be cycled from beginning to end.

The variables upYdownYleftYrightY refer to the specific rows of sprites that correspond to the orientation of the player character.

The “chewie” sprite sheet with 16 individual sprites

The variable speed is the amount added to the player’s x or y position.

Exit mobile version