我正在制作一个冒险/棋盘游戏,如果玩家踩到它,它就可以收集它。所以我做了函数check_item()
来检查:
def check_item(x, y):
global pick_armor
global pick_key
global pick_sword
global player_attack
global player_defense
if x == -400 and y == 275 and pick_armor == False:
armor.hideturtle()
pick_armor = True
elif x == 400 and y == 275 and pick_sword == False:
sword.hideturtle()
pick_sword = True
elif x == 400 and y == -325 and pick_key == False:
key.goto(400, 300)
pick_key = True
def move(x, y):
player.forward(-100)
if player.xcor() > 450 or player.xcor() < -450 or player.ycor() > 325 or player.ycor() < -375:
player.forward(100)
return
tx, ty = player.pos()
check_item(tx, ty)
def movePlayer():
player.onclick(move, 1)
事实是,有时它有用,有时却没有。我在测试游戏时,有时成功隐藏了armor
乌龟,有时却没有。同样,sword
对象通常不会被隐藏,key
只是不起作用。我尝试摆脱布尔参数,但没有任何效果。知道在move()
函数内部调用该函数也很有用,该函数是从onclick()
事件调用的。基本上,每当我单击播放器对象时,它都会移动,然后检查位置。
首先,海龟在浮点平面上爬行,因此像这样的测试有时会起作用,有时会失败:
x == -400 and y == 275
因为x
可能会返回为-400.0001
。您可以将点强制为整数:
int(x) == -400 and int(y) == 245
或测试位置是否在值的范围内。
第二,您的move()
函数中的此代码可疑:
player.forward(100)
return
tx, ty = player.pos()
check_item(tx, ty)
return
后不应有相同的缩进级别的代码-它将永远不会执行。我本来希望您的代码更像:
def check_item(x, y):
global pick_armor, pick_key, pick_sword
x = int(x)
y = int(y)
if not pick_armor and x == -400 and y == 275:
armor.hideturtle()
pick_armor = True
elif not pick_sword and x == 400 and y == 275:
sword.hideturtle()
pick_sword = True
elif not pick_key and x == 400 and y == -325:
key.goto(400, 300)
pick_key = True
def move(x, y):
player.forward(-100)
tx, ty = player.pos()
if not -450 <= tx <= 450 or not -375 <= ty <= 325:
player.backward(-100)
return
check_item(tx, ty)
def movePlayer():
player.onclick(move, 1)
如果没有更多的代码可以使用,我将无法进行以上测试,但希望您能理解。