Objective
Turtle Graphics is a fun and engaging way to learn programming concepts. It involves controlling a “turtle” to draw various shapes and patterns on the screen. In this tutorial, we will use the Go programming language to implement Turtle Graphics and draw simple shapes such as squares, triangles, and circles.
The objective of this program is to demonstrate how we can use the Turtle Graphics library in Go to visually create patterns and gain insight into basic programming concepts like loops, functions, and coordinates.
Go Code to Draw Shapes Using Turtle Graphics
package main
import (
"fmt"
"github.com/cheusov/go-turtle"
)
func drawSquare(t *turtle.Turtle, size float64) {
for i := 0; i < 4; i++ {
t.Forward(size)
t.Left(90)
}
}
func drawTriangle(t *turtle.Turtle, size float64) {
for i := 0; i < 3; i++ {
t.Forward(size)
t.Left(120)
}
}
func drawCircle(t *turtle.Turtle, radius float64) {
t.SetHeading(0)
for i := 0; i < 360; i++ {
t.Forward(2 * 3.1415 * radius / 360)
t.Left(1)
}
}
func main() {
// Create a new turtle window
t := turtle.NewTurtle()
// Set speed of the turtle
t.Speed(10)
// Draw a square
fmt.Println("Drawing a Square")
drawSquare(t, 100)
t.Clear()
// Draw a triangle
fmt.Println("Drawing a Triangle")
drawTriangle(t, 100)
t.Clear()
// Draw a circle
fmt.Println("Drawing a Circle")
drawCircle(t, 100)
// Keep the window open
turtle.MainLoop()
}
Program Structure and Explanation
This Go program uses the Turtle Graphics library to draw different shapes: a square, a triangle, and a circle. Let’s break down the structure and functions:
- Imports: We import the necessary package
github.com/cheusov/go-turtle
, which provides the Turtle Graphics functionality in Go. - Functions: We define three functions to draw specific shapes:
drawSquare(t *turtle.Turtle, size float64)
: Draws a square by moving the turtle forward and rotating it by 90 degrees four times.drawTriangle(t *turtle.Turtle, size float64)
: Draws an equilateral triangle by moving the turtle forward and rotating it by 120 degrees three times.drawCircle(t *turtle.Turtle, radius float64)
: Draws a circle by moving the turtle forward in small increments and rotating it slightly after each step.
- Main function: The
main
function initializes the turtle and draws a square, a triangle, and a circle in sequence. The window remains open usingturtle.MainLoop()
until the user closes it manually.
How to Run the Program
- Make sure you have Go installed on your system. You can download it from here.
- Install the required Turtle Graphics package using the following command in your terminal:
go get github.com/cheusov/go-turtle
- Create a new Go file (e.g.,
turtle.go
) and paste the code provided above. - Run the Go program by executing the following command in your terminal:
go run turtle.go
- You should now see a window open where the turtle draws the shapes!