My turtle won’t move with my key press. When you remove the self.forward part, it turns just fine, but when it moves it doesn’t work. How can I make it so that turtle turns while it is moving. Also, what was it that didn’t work in my code before. Also, the image labeled backround isn’t loading. How do I fix that? Thanks. Code:
JavaScript
x
60
60
1
import turtle
2
import turtle as trtl
3
4
color = input("Please select color of turtle: ")
5
6
7
# classes
8
class enemy(turtle.Turtle):
9
def __init__(self):
10
turtle.Turtle.__init__(self, shape='square')
11
self.color('white')
12
self.turtlesize(2)
13
self.penup()
14
self.goto(0, 240)
15
16
17
class player(turtle.Turtle):
18
19
def __init__(self, x=True):
20
turtle.Turtle.__init__(self, shape='turtle')
21
self.x = x
22
self.color(color)
23
self.turtlesize(2)
24
self.hideturtle()
25
self.penup()
26
self.goto(4.440892098500626e-14, -180.0)
27
self.setheading(90)
28
self.showturtle()
29
while self.x:
30
self.forward(10)
31
self.speed('slowest')
32
33
def turning_left(self):
34
self.x = False
35
self.left(30)
36
self.x = True
37
38
def turning_right(self):
39
self.x = False
40
self.right(30)
41
self.x = True
42
43
44
enemy1 = enemy()
45
shooter = player()
46
47
# controls
48
49
50
wn = trtl.Screen()
51
52
wn.onkeypress(shooter.turning_right, 'Right')
53
wn.onkeypress(shooter.turning_left, 'Left')
54
wn.onkeypress(shooter.turning_right, 'd')
55
wn.onkeypress(shooter.turning_left, 'a')
56
57
wn.listen()
58
wn.bgpic('backround.gif')
59
turtle.done()
60
Advertisement
Answer
Below is a simplification of your code that’s further modified such that the turtle constantly moves forward but you can cause it to turn via the keyboard:
JavaScript
1
35
35
1
from turtle import Screen, Turtle
2
3
screen = Screen()
4
5
class player(Turtle):
6
7
def __init__(self):
8
super().__init__(shape='turtle')
9
self.hideturtle()
10
self.turtlesize(2)
11
self.setheading(90)
12
self.penup()
13
self.backward(180.0)
14
self.showturtle()
15
16
self.move()
17
18
def move(self):
19
self.forward(1)
20
screen.ontimer(self.move)
21
22
def turn_left(self):
23
self.left(15)
24
25
def turn_right(self):
26
self.right(15)
27
28
shooter = player()
29
30
screen.onkeypress(shooter.turn_right, 'Right')
31
screen.onkeypress(shooter.turn_left, 'Left')
32
screen.listen()
33
34
screen.mainloop()
35