/* jquery */ /* jquery accordion style*/ /* jquery init */
Showing posts with label Python Turtle Graphics. Show all posts
Showing posts with label Python Turtle Graphics. Show all posts

Game of Life in Python Turtle Graphics

In the September 2020 issue of the Linux Format magazine (LXF) you'll find a Calvin Robinson article on how to code the classic Game of Life simulation, as invented by mathematician John Horton Conway.

The source code examples for this article are in the Python language and use its Turtle Graphics capabilties.

Creating a Turtle Graphics program is fun. But if you'd prefer a more efficient Game of Life then consider recoding the simulation to use the PyGame or PyGame Zero modules - as described in the YouTube coding tutorial video below.

Back issues of the Linux Format magazine are available from the LXF Archive webpage.
And you can download article source code listings from the LXF website.

Try My Free Python Coding Tutorials

Learn Python - Tom And Tim Stomp

Creating turtle called Tom was fun. But why stick with just one turtle?

Let's write a program that creates a pair of turtles, Tom and Tim, and control them both at the same time. Here's what you'll see...

Let's get coding. Open a new file in your editor and save it as turtle-pair.py, then type in the code below:

from turtle import *

# create Tom
tom = Turtle()
tom.shape("turtle")
tom.color("red")
tom.pencolor("red")
tom.penup()

# create Tim
tim = Turtle()
tim.shape("turtle")
tim.color("blue")
tom.pencolor("blue")
tim.penup()

# starting positions
tom.forward(150)
tim.backward(150)

# stomp around
dist = 8
for i in range(30):
  tom.stamp()
  tim.stamp()
  dist += 2
  tom.forward(dist)
  tom.right(24)
  tim.forward(dist)
  tim.right(24)

exitonclick()

After the import statement we have two code blocks that create Tom and Tim. These turtles have different body and pen colours.

Next we send the turtles to their respective starting positions. Notice that while Tim moves forwards, Tom moves backwards. This gives each turtle their own space to move around in. Once again we'll use the penup command to stop the turtles drawing.

Now we come to the main movement loop.

Inside the loop we've used the stamp command to leave a coloured impression of our turtles on the screen. The 'stamping' loop moves the turtles in a circular motion. The every increasing step distance is specified by the dist variable. We add two to this value every time the loop repeats.

Save the code, run the program and watch Tim and Tom perform some synchronised stomping!

A post from my Learn Python on the Raspberry Pi tutorial.

Python Turtle Graphics for 3D Printing

As we've seen in previous posts on Turtle Patterns and Turtle Shapes moving your turtle around the screen is done by simple dictional commands and angled turns.

A similar process happens in 3D printing with DIY plastic extrusion hardware, such as Rep Rap, RepRap Pro and Makerbot.

Here the 3D printing extrusion nozzle is moved in a particular direction and for a specific length, before it halts and waits for a new instructions.

So, we could use Python Turtle code to simulate a 3D printing layer. Then put it into a repeating loop to create multiple layers. This loop could subtly change the direction and length commands to build quite complex and intricate shapes.

Here's a video of a Turtle code driven 3D printer in action.

The video was part of this 3D Printing presentation at the IPSJ Summer Programming Symposium in 2014.

The presentation also included a 3D Printer Turtle Graphics Python module and a code example of the module in use.

More Raspberry Pi Python Coding Tutorials

Learn Python - Tom The Turtle

Up to now we've drawn some patterns and shapes, but we've seen nothing that looks much like a turtle. Let's put that right.

Before starting to issue move commands we can create a turtle object. We can give this object a name, and define a turtle-like shape.

It's done like this:

tom = turtle()
tom.shape("turtle")
tom.color("red")

These three lines will create a turtle called Tom, with a real turtle shape, filled with a bright red colour.

We can command Tom to move around the around the screen just as before, like this:

tom.circle(100)
tom.right(45)

Next time I'll show you how to control two turtles at once for some synchronised stomping.

A post from my Learn Python on the Raspberry Pi tutorial.

Learn Python - Turtle Shapes

This time, rather than drawing patterns with lines we'll use shapes filled with colour, like this...

Let's get started. Open an new file in your editor and save it as 'turtle-shapes.py'.
Now type in the code below:

from turtle import *

# set a shape and colour
shape("circle")
shapesize(5,1,2)
fillcolor("red")
pencolor("darkred")

penup() # no drawing
goto(0, -100)

# main draw loop
for i in range(72):
  forward(10)
  left(5)
  tilt(7.5)
  stamp()

exitonclick()

The first thing this program does is define the turtle shape with the shape function call. Here we are going to use a circle, but it could also be a triangle or a square.

On the next line we have a shapesize function call with three parameters. These specify the shape length, width and outline thickness respectively. Here the parameter values 5,1,2 will stretch our circle to create a thin ellipse.

We fill the ellipse shape with colour using the fill function. Here we've set it to red. We've also set the pen colour, to provide a contrasting shape outline colour. So, now our turtle is solid red ellipse with a dark red outline.

The next line issues a penup command. This raises the turtle's pen and stops it from drawing a line as it moves. It will become clear why we do this shortly.

By default our turtle is positioned at the centre of the window. However, for this program we need to move it a little first, to create room for our pattern. Although we could use the standard turn and movement commands, this time we'll use the goto function call because it can be done in a single command.

The goto command instructs the turtle to move to a new position relative to its current location. The move is specified as X and Y axis movements. The first X parameter is zero, so we won't move left or right. But, the Y value is -100. This moves the turtle down the screen by 100 steps.

Now we have the main draw loop, which repeats 72 times. Each time it will move forward 10 steps, turn left 5 degrees, tilt our ellipse shape by 7.5 degrees and do a stamp. What does stamp do? Stamp will leave an impression of our turtle, namely our red ellipse, on the screen.

Save the code and run the program, to see the stamped red ellipses gradually build up a pattern. Yet there's loads of ways to modify this program.

Try different values for forward, left and tilt in the loop and discover what sort of patterns are generated. You might be surprised at the results.

The shape of the ellipse can be altered by using different parameter values in the shapesize function call. And, of course, you're free to use any colour, or colours, you like.

A post from my Learn Python on the Raspberry Pi tutorial.

Learn Python - Turtle Patterns

Now let's draw some circles to create a pretty pattern, like this...

Does it look somewhat familiar? For those who remember, it's strikingly similar to the designs generated by the classic Denys Fisher Spirograph game.

To start use the Geany 'File->Save As' menu option save the square drawing program as 'turtle-circles.py'.

We only need to do a minor code change, namely replace the 'forward(200)' line with 'circle(100)'. The new listing will look like this:

from turtle import *

pencolor("blue")
pensize(5)

for i in range(4):
  circle(100)
  right(90)

exitonclick()

Save your changes and run the program. We now have four circles arranged in a pattern.

Let's make a few more changes. Modify the code to look like the listing below:

from turtle import *

pensize(5)

for i in range(4):
  for c in ["red","green","blue"]:
    pencolor(c)
    circle(100)
    right(30)

exitonclick()

Save your changes and run it again.

As you can see we now have two loops, one inside the other. This will draw a circle a total of twelve times (4 x 3). And by changing the pen colour in the inner loop, we've generated a multi-coloured pattern.

Are you starting to see the possibilities turtle graphics can offer? Next time we'll move onto creating solid-colour shapes.

A post from my Learn Python on the Raspberry Pi tutorial.

Learn Python - Move That Turtle

Let's dive in and draw squares with the turtle graphics module and a sequence of turtle movement commands.

In the Geany editor and create a new file called 'turtle-square.py', and enter the following code:

from turtle import *

forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)

exitonclick()

Save your typing and run the program using the Geany 'Build->Execute' menu option, or F5 key. You should see a new window appear and a square being drawn.

So, what's actually going on here?

First there's the import statement. As we saw earlier with TKinter GUI module using this style of import means we don't need to use a 'turtle.' prefix for every function call.

Now for our turtle move commands. Imagine you are drawing a square on a piece of paper using a pencil and a ruler. We can imitate the motion of the pencil with a series of directional and turn commands sent to our turtle.

The first command is the 'forward(100)' function call. This will move 100 steps in the direction the turtle is already pointing, drawing a line as it goes. Next we need to turn the turtle. The command 'right(90)' turns the turtle by a specified angle, in this case it's 90 degrees.

Now we simply repeat the 'forward' and 'right' commands another three times, to finish drawing our square.

The last line just ensures we can see what the turtle has drawn before the window closes. The program waits until we click somewhere inside the window - or the window's close button is clicked.

And there you have it, your first turtle graphics program.

A post from my Learn Python on the Raspberry Pi tutorial.

Learn Python - The Turtle Module

So, how do we access all this fun with Python? Well, it's all down to a module called turtle, which has a collection of Logo-like commands, implemented as functions - plus some useful window and event management features.

The turtle module's functionality is split into a number of categories. In broad terms these are:

• turtle movement
• pen control
• colour and fill settings
• special shapes
• window management
• event handling

Installation

The turtle module is already installed with Python 3, but not always there with Python 2.7. To check start new a Python interactive session and enter this statement:

>>> import turtle

If you see an error message about a missing module, don't worry. Presuming you are running the standard Debian Linux image, make sure the Raspberry Pi is connected to the Internet, open a Terminal window and type the following command:

sudo apt-get install python-tk

If prompted enter the password you used to login in with, and reply y to any prompts.

Now we can write our first turtle graphics code.

A post from my Learn Python on the Raspberry Pi tutorial.

Learn Python - What is Logo?

Logo is an interesting computer language.

While its origins go back to the 1960s, in recent times Logo has been associated with something called turtle graphics. The idea is to draw pictures and generate patterns by issuing commands to a screen-based turtle.

Logo has a lot going for it. It's a language based on simple commands, using words that even the youngest primary school pupil will understand. Words such as 'forward', 'backward', 'left' and 'right'.

Despite being very easy to learn, Logo programs illustrate a number of very important concepts. Concepts that include geometry, graphical design, various computer programming techniques, and an introduction to artificial intelligence (AI) through Logo-controlled robots.

Unsurprisingly, these attributes caught the eye of educators. Educational establishments right across the board, from Primary Schools all the way to Universities, have incorporated Logo programming into their classrooms and lectures.

When combined with mechanical turtles - floor-traversing robotic devices drawing on large sheets of paper with coloured pens - it seldom fails to generate keen interest and attention-grabbing engagement with students of any age. One of the most successful turtle robots was the Valiant Turtle (see image). Design by Dave Catlin 1983 it won a Best of British Design award and was manufactured right up until 2011.

In future posts I'll demonstrate how we can use Python to emulate the Logo programming language, while showing just how simple and fun turtle graphics can be.

A post from my Learn Python on the Raspberry Pi tutorial.

Raspberry Pi Python: Turtle Shapes

Exploring the interactive world of Turtle Graphics on your Raspberry Pi is easy with Python's 'turtle' module.

Here's a short Python program to create a pattern using coloured shapes.

from turtle import *

# set a shape and colour
shape("circle")
shapesize(5,1,2)
fillcolor("red")
pencolor("darkred")

penup()  # no drawing
goto(0, -100)

for i in range(72):
   forward(10)
   left(5)
   tilt(7.5)
   stamp()

exitonclick()

Create a new Geany file, enter the Python code, save it as turtle-shapes.py and execute the program. After you've seen it run modify the code to experiment with different shapes, fill colours and pen colours.

Visit my Raspberry Pi page for news, reviews, advice and tutorials.

Raspberry Pi Python: Turtle Patterns

Exploring the interactive world of Turtle Graphics on your Raspberry Pi is easy with Python's 'turtle' module.

Here's a short Python program to create a pattern with coloured circles:

from turtle import *

pensize(5)

for i in range(4):
   for c in ["red","green","blue"]:
      pencolor(c)
      circle(100)
      right(30)

exitonclick()

Create a new Geany file, enter the Python code, save it as turtle-patterns.py and execute the program. After you've seen it run modify the code to experiment with different pen sizes, colour names and circle diameters.

Visit my Raspberry Pi page for news, reviews, advice and tutorials.

Learn Python on the Raspberry Pi: Turtle Fun

This week in my Learn Python on the Raspberry Pi series it's all about having fun with Turtle Graphics.

Using Python's 'turtle' module all it takes is a few lines of code to create engaging, colourful graphical patterns and designs.

If you don't have a Raspberry Pi you can still follow the series with these emulation instructions.

Here are a few extracts from Part 5:

Logo is an interesting computer language.

While its origins go back to the 1960s (see boxouts), in recent times Logo has been associated with something called 'turtle graphics'. The idea is to draw pictures and generate patterns by issuing commands to a screen-based 'turtle'.

Logo has a lot going for it. It's a language based on simple commands, using words that even the youngest primary school pupil will understand. Words such as 'forward', 'backward', 'left' and 'right'.

So, how do we access all this fun with Python? Well, it's all down to a module called 'turtle', which has a collection of Logo-like commands, implemented as functions - plus some useful window and event management features.

I hope you enjoyed this introduction to turtle graphics. Maybe you've been surprised at how easy it is to create quite complex patterns. There's so many ways to experiment, so have some fun creating your own little turtle programs. Visit the turtle module reference pages to discover more.

Next time I'll continue the visual theme by introducing game programming with the PyGame module.

Visit my Raspberry Pi page for news, reviews, advice and tutorials.