Photo location guessing game in Go

Widget with Something Special on Top

The schnitzle GUI application relies on the Fyne framework to whip up a native-looking graphical application on the desktop with plain vanilla Go code. Previous articles in this column [9] have plumbed the depths of this excellent tool [10] many a time.

Fyne comes with a whole range of label, listbox, button, and other widgets out of the box, but it can't hope to cover every single special case conjured up by creative software engineers. For example, in the Schnitzle game, the guesser clicks on a photo in the right pane, to have the game move it to the left. Photos don't normally take clicks, but button widgets do. And they, in turn, define callbacks to perform the intended action in case of an alert.

With just a little code, you can quickly program extensions in Fyne to add the desired, albeit nonstandard, behavior. Listing 5 defines a new widget type named clickImage() starting in line 13. It is composed from a canvas object with a thumbnail image and takes a callback that it invokes when the user clicks on the photo with the mouse.

Listing 5


01 package main
03 import (
04   ""
05   ""
06   ""
07   ""
08   "math/rand"
09   "os"
10   "time"
11 )
13 type clickImage struct {
14   widget.BaseWidget
15   image *canvas.Image
16   cb    func()
17 }
19 func newClickImage(img *canvas.Image, cb func()) *clickImage {
20   ci := &clickImage{}
21   ci.ExtendBaseWidget(ci)
22   ci.image = img
23   ci.cb = cb
24   return ci
25 }
27 func (t *clickImage) CreateRenderer() fyne.WidgetRenderer {
28   return widget.NewSimpleRenderer(t.image)
29 }
31 func (t *clickImage) Tapped(_ *fyne.PointEvent) {
32   t.cb()
33 }
35 func makeUI(w fyne.Window, p fyne.Preferences) {
36   rand.Seed(time.Now().UnixNano())
38   var leftCard *widget.Card
39   var rightCard *widget.Card
41   quit := widget.NewButton("Quit", func() {
42     os.Exit(0)
43   })
45   var restart *widget.Button
47   reload := func() {
48     leftCard, rightCard = makeGame(p)
49     vbox := container.NewVBox(
50       container.NewGridWithColumns(2, quit, restart),
51       container.NewGridWithColumns(2, leftCard, rightCard),
52     )
53     w.SetContent(vbox)
54     canvas.Refresh(vbox)
55   }
57   restart = widget.NewButton("New Game", func() {
58     reload()
59   })
61   reload()
62 }

Thanks to Go's built-in inheritance mechanism for structures, widget.BaseWidget on line 14 derives the structure from Fyne's base widget, thus providing it with the display, shrink, or hide functions common to all widgets. In addition, the add-on widget needs to call the ExtendBaseWidget() function in the constructor later on in line 21 to use all of the GUI's features.

One more thing: The GUI still doesn't know how to display the new widget on the screen. This is why the CreateRenderer() function starting in line 27 returns an object of the NewSimpleRenderer type to the GUI, when the function is being called with the image as its only parameter.

In order for the photo widgets in Schnitzle to respond to mouse clicks, their newClickImage() constructor, defined in line 19, takes a callback that the widget later calls on mouse click events. Line 23 assigns this function to the cb instance variable. Later on, the Tapped() function (defined in line 31 and called by the GUI) simply triggers the previously defined callback in line 32, whenever the player clicks on the particular widget. There you have it: a new GUI element controlled by a clickable photo, which behaves in a similar way to a button widget.

Like the Quit button starting in line 41, which uses its callback to announce the end of the game when a button is pressed via os.Exit(0), Listing 6 can – thanks to the new extension – create a new clickable photo in line 29. In its callback, it sends the selected index to the pickCh channel. At the other end of the pipe, the game apparatus picks up the index and triggers the animation, which moves the photo from the right to the left pane.

Listing 6


01 package main
03 import (
04   "fmt"
05   ""
06   ""
07   ""
08   ""
09   ""
10   "math/rand"
11 )
13 func makeGame(p fyne.Preferences) (*widget.Card, *widget.Card) {
14   pickCh := make(chan int)
15   done := false
17   photos, err := photoSet()
18   panicOnErr(err)
20   photosRight := make([]Photo, len(photos))
21   copy(photosRight, photos)
23   pool := []fyne.CanvasObject{}
25   for i, photo := range photosRight {
26     idx := i
27     img := canvas.NewImageFromResource(nil)
28     img.SetMinSize(fyne.NewSize(DspWidth, DspHeight))
29     clkimg := newClickImage(img, func() {
30       if !done {
31         pickCh <- idx
32       }
33     })
35     pool = append(pool, clkimg)
36     showImage(img, photo.Path)
37   }
39   solutionIdx := rand.Intn(len(photos))
40   solution := photos[solutionIdx]
42   left := container.NewVBox()
43   right := container.NewVBox(pool...)
45   go func() {
46     for {
47       select {
48       case i := <-pickCh:
49         photo := photos[i]
50         dist, bearing, err := hike(photo.Lat, photo.Lng, solution.Lat, solution.Lng)
51         panicOnErr(err)
53         if photo.Path == solution.Path {
54           done = true
55         }
57         subText := ""
58         if done == true {
59           subText = " * WINNER  *"
60         }
62         card := widget.NewCard(fmt.Sprintf("%.1fkm %s", dist, bearing), subText, pool[i])
63         left.Add(card)
64         canvas.Refresh(left)
66         pool[i] = widget.NewLabel("")
67         pool[i].Hide()
69         if done == true {
70           return
71         }
72       }
73     }
74   }()
76   first := randPickExcept(photos, solutionIdx)
77   pickCh <- first
78   return widget.NewCard("Picked", "", left),
79     widget.NewCard("Pick next", "", right)
80 }
82 func panicOnErr(err error) {
83   if err != nil {
84     panic(err)
85   }
86 }
88 func main() {
89   a := app.NewWithID("com.example.schnitzle")
90   w := a.NewWindow("Schnitzle Geo Worlde")
92   pref := a.Preferences()
93   makeUI(w, pref)
94   w.ShowAndRun()
95 }

The rest of Listing 5 is devoted to arranging the widgets shown in the game with makeUI. The central function reload() loads a new game at the initial program start and whenever New Game is pressed.

Index Cards as a Model

The graphical elements in the game window are arranged as two horizontal buttons at the top, followed by two image columns each of the Card type – this relies on vertical stacking with NewVBox(). This standard Card widget from the Fyne collection displays a header (optionally a subhead) and an image to illustrate it. You can think of it as being something like an index card with a title and some media content.

Listing 6 defines the main() function of the game and defines the individual widgets of the left and right game columns in makeGame(). On top of this, you have the move mechanism that kicks in when the player clicks on a photo in the right column.

The elements in the pool array are the photos for the right column, each displayed as a CanvasObject. In contrast to this, the left-hand widget column contains the photos already selected over the course of the game. They are located in what is initially an empty left array. Each time a photo in the right widget column is clicked, the callback associated with that photo sends the index of the selection to the pickCh channel in line 31.

Then the Go routine defined in line 45, running concurrently, uses select to handle the event. It computes the distance to the target image by calling hike in line 50 and generates a Fyne card with the result in line 62. The Add() function appends the card at the bottom of the left column in line 63 and uses canvas.Refresh() to make sure the GUI displays the change.

To make the clicked photo disappear from the right column, line 66 puts an empty Label widget in its place and then immediately whisks it away by calling Hide().

At the start of the game, line 76 uses randPickExcept() to pick a random photo from the right column, but avoids disclosing the solution right away. Line 77 pushes the index position into the pickCh channel, very much like the callback of the photo widget selected by the user will do later on, setting off the same animation and moving it to the left column.

In Go, programmers have to check results, practically after each function call, to make sure an error hasn't crept in. It always comes back as an err variable. If it has a value of nil, no error occurred. Each time, the corresponding error handler requires three lines of code and takes up vast amounts of space in listings printed in magazines.

This is why line 82 simply defines a panicOnErr() function that executes this test in one line of code each time and, if an error occurs, aborts the program immediately by calling panic(). In production environments, errors are instead handled individually and often looped through further up the call stack, but page space in printed magazines is scarce and nobody wants to read monster-sized listings!

Off We Go

You can compile the whole kit and caboodle with the commands from Listing 7. The resulting schnitzle binary can be launched at the command line, which causes the GUI to pop up on screen.

On Linux, the Fyne GUI uses a C wrapper from Go to tap into the libx11-dev, libgl1-mesa-dev, libxcursor-dev, and xorg-dev libraries. To install the game on Ubuntu, for example, you can fetch these libraries with the command

sudo apt-get install

to ensure that go build in Listing 7 actually finds the required desktop underpinnings.

Listing 7

Compiling Schnitzle

$ go mod init schnitzle
$ go mod tidy
$ go build schnitzle.go gui.go photoset.go image.go gps.go

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Wheat and Chaff

    If you want to keep only the good photos from your digital collection, you have to find and delete the fails. Mike Schilli writes a graphical application with Go and the Fyne framework to help you cull your photo library.

  • Straight to the Point

    With the Fyne framework, Go offers an easy-to-use graphical interface for all popular platforms. As a sample application, Mike uses an algorithm to draw arrows onto images.

  • Chip Shot

    We all know that the Fyne framework for Go can be used to create GUIs for the desktop, but you can also write games with it. Mike Schilli takes on a classic from the soccer field.

  • GUI Apps with Fyne

    The Fyne toolkit offers a simple way to build native apps that work across multiple platforms. We show you how to build a to-do list app to demonstrate Fyne's power.

  • Digital Shoe Box

    In honor of the 25th anniversary of his Programming Snapshot column, Mike Schilli revisits an old problem and solves it with Go instead of Perl.

comments powered by Disqus
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters

Support Our Work

Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.

Learn More