Reputation: 21
I'm doing a tutorial to make "Space Invaders" in order to learn Python but I'm encountering an issue in binding my keys. No matter what keys I change the move_left
and move_right
functions to, the spaceship doesn't move at all, and there is no error to trace it to either.
I have tried looking at forums that dealt with a similar issue, and YouTube, but none of them have worked at all.
#Modules
import turtle
#Screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Space invaders")
# Border
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("white")
border_pen.penup()
border_pen.setposition(-300, -300)
border_pen.pendown()
border_pen.pensize(3)
for sides in range(4):
border_pen.fd(600)
border_pen.lt(90)
border_pen.hideturtle()
# Create the player turtle
player = turtle.Turtle()
player.color("blue")
player.shape("triangle")
player.penup()
player.speed(0)
player.setposition(0, -250)
player.setheading(90)
playerspeed = 15
# move player left and right
def move_left():
x = player.xcor()
x -= playerspeed
player.setx(x)
def move_right():
x = player.xcor()
x+=playerspeed
player.setx(x)
# keyboard bindings
wn.onkey(move_left(), "Left")
wn.onkey(move_right(),"Right")
wn.listen()
turtle.mainloop()
I expect the player turtle to move left and right when I press the "Left" and "Right" arrow keys.
Upvotes: 1
Views: 187
Reputation: 41905
The problem is with these two lines of code:
wn.onkey(move_left(), "Left")
wn.onkey(move_right(),"Right")
You don't want to call move_left()
, you want to pass move_left
to be called by the event handler when the key is pressed:
wn.onkey(move_left, 'Left')
wn.onkey(move_right, 'Right')
By including the parentheses, you pass the return value of move_left()
which is None
, effectively disabling the event instead of enabling it!
Here's a rework of your code with the above fix:
from turtle import Screen, Turtle
screen = Screen()
screen.bgcolor('black')
screen.title("Space invaders")
# Border
border_pen = Turtle()
border_pen.hideturtle()
border_pen.pensize(3)
border_pen.speed('fastest')
border_pen.color('white')
border_pen.penup()
border_pen.setposition(-300, -300)
border_pen.pendown()
for _ in range(4):
border_pen.forward(600)
border_pen.left(90)
# Create the player turtle
player = Turtle()
player.shape('triangle')
player.speed('fastest')
player.color('blue')
player.penup()
player.setposition(0, -250)
player.setheading(90)
playerspeed = 15
# Move player left and right
def move_left():
x = player.xcor() - playerspeed
player.setx(x)
def move_right():
x = player.xcor() + playerspeed
player.setx(x)
# Keyboard bindings
screen.onkey(move_left, 'Left')
screen.onkey(move_right, 'Right')
screen.listen()
screen.mainloop()
Upvotes: 1