使按键绑定适用于“太空侵略者”游戏

时间:2019-06-05 16:49:03

标签: python turtle-graphics python-3.7

我正在做一个制作“太空侵略者”的教程,以学习Python,但是绑定键时遇到了问题。无论我将move_leftmove_right函数更改为什么键,太空飞船都不会移动,并且没有错误可追溯到任何一个。

我曾尝试查看处理类似问题的论坛和YouTube,但这些论坛都没有。

#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()

我希望当按“向左”和“向右”箭头键时,乌龟会左右移动。

1 个答案:

答案 0 :(得分:1)

问题在于这两行代码:

wn.onkey(move_left(), "Left")
wn.onkey(move_right(),"Right")

您不想调用move_left(),而是想在按下键时传递move_left以便由事件处理程序调用:

wn.onkey(move_left, 'Left')
wn.onkey(move_right, 'Right')

通过加上括号,您传递了move_left()的返回值None,从而有效地禁用了该事件,而不是启用了该事件!

以下是使用上述修复程序对代码的重做:

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()