Skip to content

How I wrote Minesweeper in Go in under 200 lines of code

Published: at 12:00 AM

Source code: github.com/katistix/gosweeper

In the past days I found myself wanting to upgrade my skillset as a developer. After about a year stuck in the Javascript, React, Next.js bubble I wanted something new.

Part of the reason why I chose Go and Minesweeper is the Youtuber and Twitch streamer ThePrimeagen, he recently made a minesweeper game in Go that his Twitch Chat could play collectively, while he was livestreaming.

My goal

So what was my goal? Well… For starters, I just wanted to familiarize myself with the Go language (how to declare a variable, how functions work, how arrays/slices work, conditional statements, loops, etc.). So I decided that implementing a simple minesweeper game in the terminal using this language would help me a lot, and it did.

So how did I do it?

Step 1. Create a new Go project

I started by creating a new directory with the name of the project. I went with gosweeper

mkdir gosweeper
cd gosweeper #navigate to the directory

Then, I initialized the go project:

go mod init github.com/katistix/gosweeper

In this command I used go mod init <module_name> to initialise a new go module, the github.com/katistix/gosweeper is the location where the code will be hosted, in this case, on my github, this makes easier to download the module using the go get github.com/katistix/gosweeper command. But this is not necessary and you should be able to name this whatever you want and then simply clone the github repo as usual with git clone.

Step 2. Declare global variables for the size of the board and the number of bombs, and read them

All of the code is in the main.go file.

package main // Declare this file as part of the main package

// import the fmt standard lib,
// used for printing to the console and reading used input
import 'fmt'

// Declare the global variables

var BOMB_COUNT, x, y int // Here, x and y represent the size of the board

func main(){

	fmt.Print("Enter the number of rows (1-9): ")
	fmt.Scanf("%d", &x) // Read the value of x

	fmt.Print("Enter the number of columns (1-9): ")
	fmt.Scanf("%d", &y) // Read the value of y

	fmt.Print("Enter the number of bombs (no more than rows*cols): ")
	fmt.Scanf("%d", &BOMB_COUNT) // Read the value of BOMB_COUNT
}

The Go compiler looks for a main function declared inside of the files. This is how it knows where the program starts.

Declaring a variable is done like this

var x int // Here we declare a new x variable of type int

Reading user input

fmt.Scanf("%d", &x)
// %d - the input is an integer
// &x get a reference to the x variable

Step 3. …

This post is still “Work In Progress” and will be updated soon