我一直在按照教程向初学者展示如何制作太空侵略者"游戏。我大多只想要一种方法来玩龟图形或类似的东西。一切都进展顺利,直到我注意到我的if语句,我在我定义我的move_left函数时创建,不起作用。然而问题不在于if语句本身。我试图在它下面做的任何数学运算都被程序完全忽略,没有错误信息或任何东西。我甚至试图在if语句下做一个print语句,只是为了看到实际的语句是否有响应,并且确实看到了我按计划打印的语句。什么给出了什么?为什么我不能在这两个函数下做任何数学方程式或类似的东西?
所以,这是我在下面遵循的代码:
import turtle
import os
def main():
#Set up the screen
wn = turtle.Screen()
wn.bgcolor("black")
wn.title("Space Invaders")
#Draw 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 side 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)
#Player controls
playerspeed = 15
def move_left():
x = player.xcor()
x -= playerspeed
player.setx(x)
print(x)
if x < -280:
print("Reached") #It is here I tested rather or not the if statement
#above works, which it does
x = -280 #The following code here will not take effect. I tried all
#of different signs to use. Nothing happens. Not even an
#error
def move_right(): #I did not put the if statement here since I noticed the
#problem with the left side first
x = player.xcor()
x += playerspeed
player.setx(x)
if x > 280:
x = 280
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.mainloop()
main()
答案 0 :(得分:0)
代码没有影响的原因是因为你修改了x
的值,一个局部变量到函数范围,而不是玩家位置。更新本地变量player.setx(x)
后,调用x
实际更新玩家位置。如果您想绑定您的位置,您还可以使用内置的min
/ max
方法:
def move_left():
x = player.xcor()
x -= playerspeed
player.setx(max(x, -280))
def move_right():
x = player.xcor()
x += playerspeed
player.setx(min(x, 280))