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
gui.go
01 package main 02 03 import ( 04 "fyne.io/fyne/v2" 05 "fyne.io/fyne/v2/canvas" 06 "fyne.io/fyne/v2/container" 07 "fyne.io/fyne/v2/widget" 08 "math/rand" 09 "os" 10 "time" 11 ) 12 13 type clickImage struct { 14 widget.BaseWidget 15 image *canvas.Image 16 cb func() 17 } 18 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 } 26 27 func (t *clickImage) CreateRenderer() fyne.WidgetRenderer { 28 return widget.NewSimpleRenderer(t.image) 29 } 30 31 func (t *clickImage) Tapped(_ *fyne.PointEvent) { 32 t.cb() 33 } 34 35 func makeUI(w fyne.Window, p fyne.Preferences) { 36 rand.Seed(time.Now().UnixNano()) 37 38 var leftCard *widget.Card 39 var rightCard *widget.Card 40 41 quit := widget.NewButton("Quit", func() { 42 os.Exit(0) 43 }) 44 45 var restart *widget.Button 46 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 } 56 57 restart = widget.NewButton("New Game", func() { 58 reload() 59 }) 60 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
schnitzle.go
01 package main 02 03 import ( 04 "fmt" 05 "fyne.io/fyne/v2" 06 "fyne.io/fyne/v2/app" 07 "fyne.io/fyne/v2/canvas" 08 "fyne.io/fyne/v2/container" 09 "fyne.io/fyne/v2/widget" 10 "math/rand" 11 ) 12 13 func makeGame(p fyne.Preferences) (*widget.Card, *widget.Card) { 14 pickCh := make(chan int) 15 done := false 16 17 photos, err := photoSet() 18 panicOnErr(err) 19 20 photosRight := make([]Photo, len(photos)) 21 copy(photosRight, photos) 22 23 pool := []fyne.CanvasObject{} 24 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 }) 34 35 pool = append(pool, clkimg) 36 showImage(img, photo.Path) 37 } 38 39 solutionIdx := rand.Intn(len(photos)) 40 solution := photos[solutionIdx] 41 42 left := container.NewVBox() 43 right := container.NewVBox(pool...) 44 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) 52 53 if photo.Path == solution.Path { 54 done = true 55 } 56 57 subText := "" 58 if done == true { 59 subText = " * WINNER *" 60 } 61 62 card := widget.NewCard(fmt.Sprintf("%.1fkm %s", dist, bearing), subText, pool[i]) 63 left.Add(card) 64 canvas.Refresh(left) 65 66 pool[i] = widget.NewLabel("") 67 pool[i].Hide() 68 69 if done == true { 70 return 71 } 72 } 73 } 74 }() 75 76 first := randPickExcept(photos, solutionIdx) 77 pickCh <- first 78 return widget.NewCard("Picked", "", left), 79 widget.NewCard("Pick next", "", right) 80 } 81 82 func panicOnErr(err error) { 83 if err != nil { 84 panic(err) 85 } 86 } 87 88 func main() { 89 a := app.NewWithID("com.example.schnitzle") 90 w := a.NewWindow("Schnitzle Geo Worlde") 91 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
« Previous 1 2 3 4 Next »
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
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.
News
-
Gnome 48 Debuts New Audio Player
To date, the audio player found within the Gnome desktop has been meh at best, but with the upcoming release that all changes.
-
Plasma 6.3 Ready for Public Beta Testing
Plasma 6.3 will ship with KDE Gear 24.12.1 and KDE Frameworks 6.10, along with some new and exciting features.
-
Budgie 10.10 Scheduled for Q1 2025 with a Surprising Desktop Update
If Budgie is your desktop environment of choice, 2025 is going to be a great year for you.
-
Firefox 134 Offers Improvements for Linux Version
Fans of Linux and Firefox rejoice, as there's a new version available that includes some handy updates.
-
Serpent OS Arrives with a New Alpha Release
After months of silence, Ikey Doherty has released a new alpha for his Serpent OS.
-
HashiCorp Cofounder Unveils Ghostty, a Linux Terminal App
Ghostty is a new Linux terminal app that's fast, feature-rich, and offers a platform-native GUI while remaining cross-platform.
-
Fedora Asahi Remix 41 Available for Apple Silicon
If you have an Apple Silicon Mac and you're hoping to install Fedora, you're in luck because the latest release supports the M1 and M2 chips.
-
Systemd Fixes Bug While Facing New Challenger in GNU Shepherd
The systemd developers have fixed a really nasty bug amid the release of the new GNU Shepherd init system.
-
AlmaLinux 10.0 Beta Released
The AlmaLinux OS Foundation has announced the availability of AlmaLinux 10.0 Beta ("Purple Lion") for all supported devices with significant changes.
-
Gnome 47.2 Now Available
Gnome 47.2 is now available for general use but don't expect much in the way of newness, as this is all about improvements and bug fixes.