我正在做一个制作“太空侵略者”的教程,以学习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()


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

最佳答案

问题在于这两行代码:

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

关于python - 使按键绑定(bind)适用于“太空侵略者”游戏,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56464830/

10-12 18:16