2

so im creating a snake game using Python turtle module. currently im drawing the head of the snake, using this code:

# Snake head
head = turtle.Turtle()                      # create an instance of the class turtle called 'head'
head.speed(0)                               # call the speed method
head.shape("square")                        # defines the shape of the snakes head
head.color("black")                         # defines the colour of the snakes head
head.penup()                                # stop the snake from drawing when moving
head.goto(0,0)                              # moves the snakes head to the coordinates 0,0 on the screen.
head.direction = "stop"                     # stops the turtles head from moving strait away

Instead of drawing, i would like to import an image and use it as the snakes head. here is the code so far

image1 = "D:\Desktop\computing\Python\snake game\img\snake_head.png"
head = turtle.Turtle()
head.speed(0)
head.addshape(image1)
head.goto(0,0)
head.direction = "stop"

after doing some research i found here, you could use a method called "addshape" to import the image. however when i run the code i get the error:

AttributeError: 'Turtle' object has no attribute 'addshape'
  • I'm not too familiar with `turtle` but seems from the docs they use [`register_shape`](https://docs.python.org/2/library/turtle.html#turtle.addshape) – Jab Mar 02 '19 at 21:13
  • just tried it, getting `AttributeError: 'Turtle' object has no attribute 'register_shape'` now. –  Mar 02 '19 at 21:17
  • I'm not familiar with the module either, but having just glanced through the [docs](https://docs.python.org/3.7/library/turtle.html#turtle.addshape) (those are the Python 3.7 ones, those linked to above are for Python 2), it appears that `addshape` and `register_shape` are only methods of the `TurtleScreen` class, which is different from the `Turtle` class. – Robin Zigmond Mar 02 '19 at 21:32

1 Answers1

0

The addshape and register_shape methods are synonyms, you can use either. But they are methods of the screen, not the turtle. And most importantly, the image has to be in GIF format, nothing else (like *.png) will work:

from turtle import Screen, Turtle

IMAGE = "D:\Desktop\computing\Python\snake game\img\snake_head.gif"

screen = Screen()
screen.addshape(IMAGE)

head = Turtle(IMAGE)
head.speed('fastest')
head.penup()
# ...
cdlane
  • 40,441
  • 5
  • 32
  • 81