我正在用Python 3.6.4开发游戏。
当玩家触摸红色圆圈时,玩家应该传送回起点。
问题1:如果乌龟撞到红色圆圈,如何将其移动到起点?
我的代码:
import turtle
wn = turtle.Screen()
wn.bgcolor("black")
player = turtle.Turtle()
player.color("white")
player.speed(0)
player.penup()
player.setposition(100, -110)
enemy = turtle.Turtle()
enemy.color("red")
enemy.shape("circle")
enemy.penup()
enemy.setposition(100, -100)
if player.pos(100, -100):
player.pos(100, -110)
我得到的错误是:
Traceback (most recent call last): File "C:\Users\ruffi\AppData\Local\Programs\Python\Python36-32\behg.p", line 18, in <module> if player.pos(100, -100):TypeError: pos() takes 1 positional argument but 3 were given
问题2:如何解决此错误?
最佳答案
我要解决这两个问题的方法是不要自己比较位置,而是使用turtle提供的distance()
方法:
if player.distance(enemy) < 10: # if the centers are within 10 pixels
这是一个完整的示例,可让您单击屏幕来移动玩家,但如果玩家离敌人的心太近,它将传送回到起点,您可以通过单击屏幕再次移动:
from turtle import Turtle, Screen
wn = Screen()
wn.setup(500, 500)
wn.bgcolor('black')
player = Turtle(visible=False)
player.speed('fastest')
player.shapesize(2)
player.color('white')
player.penup()
player.setposition(200, -200)
player.showturtle()
enemy = Turtle('circle', visible=False)
enemy.shapesize(2)
enemy.color('red')
enemy.penup()
enemy.setposition(-200, 200)
enemy.showturtle()
def click_handler(x, y):
wn.onclick(None) # disable handler while in handler
player.setheading(player.towards(x, y)) # head towards new location
player.setposition(x, y)
if player.distance(enemy) < 10:
player.hideturtle() # teleport
player.setposition(200, -200)
player.showturtle()
wn.onclick(click_handler)
wn.onclick(click_handler)
wn.mainloop()
关于python - 如何用Python传送 turtle ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48106441/