我正在使用海龟为Python制作一种保险杠汽车游戏的开始阶段。到目前为止,我已经创建了以下代码,这些代码只是为了创建“保险杠”海龟。我试图让这些海龟在屏幕上随机产卵(它们都出现在中间,我不知道为什么),我试着让它们随机移动,停留在我列出的边界内(如果不是,返回到0,0)。然而,它们不移动,它们在中间产卵。这是迄今为止我创建的唯一代码,我也不确定如何创建障碍类型代码,以便当它们遇到主海龟时,用户能够控制(尚未实现或尝试),它们从屏幕上消失。任何对我当前问题的帮助或对我的目标的提示都将不胜感激!但是,当我运行此代码时,会收到错误消息:
TypeError:check_boundary()接受0个位置参数,但给出了1个
无论如何,这是我目前的代码:
import turtle
import random
from random import randint
class BumperTurtles():
def __init__(bumper, name, color):
bumper.color = color
bumper.turtle = turtle.Turtle()
bumper.turtle.shape("classic")
bumper.turtle.color(bumper.color)
bumper.turtle.speed(100)
bumper.turtle.pd()
#Having them spawn within the desired range:
x = random.randint (-150, 150)
y = random.randint (-150, 150)
#Making sure they don't move out of bounds
def check_boundary():
if (-300 <= prey.xcor() <= 300 and -300 <= prey.ycor() <=300):
return
prey.goto(0, 0)
def move(bumper):
bumper.turtle.penup()
turn = randint(0,2)
if turn == 1:
bumper.turtle.lt(45)
elif turn == 2:
bumper.turtle.rt(45)
bumper.turtle.forward(5)
#Creating my bumper turtles
turtles = []
turtles.append(BumperTurtles('bump1', 'blue'))
turtles.append(BumperTurtles('bump2', 'blue'))
turtles.append(BumperTurtles('bump3', 'blue'))
turtles.append(BumperTurtles('bump4', 'blue'))
turtles.append(BumperTurtles('bump5', 'blue'))
turtles.append(BumperTurtles('bump6', 'blue'))
turtles.append(BumperTurtles('bump7', 'blue'))
turtles.append(BumperTurtles('bump8', 'blue'))
#Calling for them to move
ok = True
while ok:
for t in turtles:
t.move()
if t.check_boundary():
t.goto(0,0)
ok = False
你的代码永远不会像你现在这样工作。测试不返回任何内容的
check_boundary()
的结果;您引用了一个不存在的prey
变量(即使将其作为参数,它在xcor()
调用中也会失败);将随机值传递给speed()
方法;您计算了保险杠海龟的x和y位置,但没有使用它们;等等让我们把你的程序拆开,重新组合起来,让你可以实际运行,并观看你的海龟们的随机进程:
注意,我已经将
BumperTurtle
从包含一个海龟改为一个海龟子类。我用适当的计时器事件替换了while True:
循环。对于您的方法,我切换到了传统的self
参数。我关闭了跟踪功能并添加了update()
以提高图形性能,这样它就有了真正的碰碰车感觉。您可以通过将第二个参数调整为ontimer()
来调整速度,这是以毫秒为单位的两次调用之间的时间相关问题 更多 >
编程相关推荐