A real-time updating turtle graphics system for the golang programming language
11/01/2024
A bit ago, I looked online to find a turtle graphics system for golang to help teach golang to a student, but found that none of the existing options had real time updating of the canvas. There is one that is online only, but... So, I endeavored to create it myself. I built it on top of the Ebitengine 2D game engine for golang.
Some of the cool features are:
I am of the opinion that teaching golang to high school age students actually makes a lot of sense. Most people immediately will reach for python, but I don't agree. Python has multiple issues. What I will mention here is that there is far too much magic in python. between decorators and overloading, python is doing a huge amount of hidden work to massage the data types. If you step out of the invisible field-of-play though, boom, it blows up. Also, python is not a complete stack, and you will eventually need to learn another programming language.
If you don't know how to setup a golang project, first make a new directory.
Then, inside the directory run the console command:
1 2 |
|
Finally, we need to get this turtle package. Again in the console run the following command:
1 2 |
|
Now you are ready.
The most basic thing you can do is just open up a turtle window with nothing in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
It is just a blank white screen that is 500 pixels wide by 500 pixels high.
To add the turtle sprite we need 2 more lines of code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
The turtle can move in a bunch of different ways, but let's just start with moving forward and turning. Similar to the python turtle graphics system, this turtle will move at a set speed.
Lets have the turtle draw a box. So, we need to move forward, then turn left 4 times a make a box.
I am also only going show the drawFunc code now since it is all that is changing
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
But where is the line? Ah, well we didn't put the "Pen" down.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
And there we have it!
Now we can easily make this into a sort of spirograph by putting it into a loop. We can also randomize the colors for a more interesting picture. I also increased the turtle speed to 8000 pixels per second.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
Thanks for reading! Subscribe for free and receive updates and support my work.