Learn to Code via Tutorials on Repl.it

← Back to all posts
5
Graphics with Go
Lord_Poseidon (109)

Getting started with graphics development in Golang on repl.it

Introduction

Who doesn't love golang? some people, maybe.But no can resist the cuteness of the gopher. Fact.

What I want to say is... I've found a way to do graphics in Go on repl.it. This post teaches you how to make a sample gopher screensaver using a framework called pixel.

Please note that much of the code is from the original tutorials. It strongly recommended to go through them if you do want to make a game in go. To be honest, this is more of a half-baked amalgamation of @eankeen 's original pygame tutorial and the tutorials

The final result will look like this:

A bit glitchy.Don't know why

Getting started

First, start by making a polygott repl here. Or even better, fork my repl at https://repl.it/@Lord_Poseidon/NarrowCrookedExternalcommand. You would see a makefile. Paste this there and make a folder called src

.PHONY: dependencies run clean

deppaths := github.com/faiface/pixel github.com/faiface/pixel/pixelgl golang.org/x/image/colornames

gopath   := /tmp/gopath

run: dependencies
	cd src && GOPATH=$(gopath) go build -o /tmp/main-go
	TERM=xterm /tmp/main-go

clean:
	rm -rf /tmp/main-go /tmp/gopath

dependencies:
	GOPATH=$(gopath) go get $(deppaths)

Thanks to @superwhiskers for this code. The reason we are doing this is because repl does not have a Go package manager yet .That makefile gets our dependencies, then runs the code in the folder src .

create a file main.go in src folder and code away!!

my code is mostly from the original tutorials here but these are the changes:

Code changes:

    pos:=pixel.V(100,300)
    horizadder,vertadder:=1.0,1.0

	for !win.Closed() {

        pos=pos.Add(pixel.V(horizadder,vertadder))
        mat:=pixel.IM
        win.Clear(colornames.Black)
        sprite.Draw(win, mat.Moved(pos))
        if pos.X < 0 || pos.X > 800{
            horizadder = -horizadder
        }
        if pos.Y < 0 || pos.Y > 600{
            vertadder = -vertadder
        }
		win.Update()
        time.Sleep(16666666)
	}

just standard edge detection, speed changing, movement and delay.

Path:

the tutorials assume that the source directory is the working directory. This is not the case with us. You have to do src/hiking.png even if you already are in src directory.
Also, I had to resize the original image to make it smaller

Size of the window:

the tutorials assume 1074 by 768 pixels. We at repl.it have only 800 by 600


Thanks again to @superwhiskers and @eankeen. If you do decide to make a game in go,let me know in the comments