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:
import turtle import turtle as trtl color = input("Please select color of turtle: ") # classes class enemy(turtle.Turtle): def __init__(self): turtle.Turtle.__init__(self, shape='square') self.color('white') self.turtlesize(2) self.penup() self.goto(0, 240) class player(turtle.Turtle): def __init__(self, x=True): turtle.Turtle.__init__(self, shape='turtle') self.x = x self.color(color) self.turtlesize(2) self.hideturtle() self.penup() self.goto(4.440892098500626e-14, -180.0) self.setheading(90) self.showturtle() while self.x: self.forward(10) self.speed('slowest') def turning_left(self): self.x = False self.left(30) self.x = True def turning_right(self): self.x = False self.right(30) self.x = True enemy1 = enemy() shooter = player() # controls wn = trtl.Screen() wn.onkeypress(shooter.turning_right, 'Right') wn.onkeypress(shooter.turning_left, 'Left') wn.onkeypress(shooter.turning_right, 'd') wn.onkeypress(shooter.turning_left, 'a') wn.listen() wn.bgpic('backround.gif') turtle.done()
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:
from turtle import Screen, Turtle screen = Screen() class player(Turtle): def __init__(self): super().__init__(shape='turtle') self.hideturtle() self.turtlesize(2) self.setheading(90) self.penup() self.backward(180.0) self.showturtle() self.move() def move(self): self.forward(1) screen.ontimer(self.move) def turn_left(self): self.left(15) def turn_right(self): self.right(15) shooter = player() screen.onkeypress(shooter.turn_right, 'Right') screen.onkeypress(shooter.turn_left, 'Left') screen.listen() screen.mainloop()