我正在使用乌龟试图移动我的雪碧并使其向左或向右旋转或加速或减速。但是我的编码不起作用。它只会向一个方向移动,然后在屏幕上消失。不确定我在哪里做错了。
import turtle
turtle.fd(0)
turtle.speed(0)
turtle.bgcolor("black")
turtle.hideturtle()
turtle.setundobuffer(1)
turtle.tracer(1)
class Sprite(turtle.Turtle):
def __init__(self, spriteshape, color, startx, starty):
turtle.Turtle.__init__(self, shape=spriteshape)
self.speed(0)
self.penup()
self.color(color)
self.fd(0)
self.goto(startx, starty)
self.speed = 1
def move(self):
self.fd(self.speed)
class Player(Sprite):
def __init__(self, spriteshape, color, startx, starty):
Sprite.__init__(self, spriteshape, color, startx, starty)
self.speed = 4
self.lives = 3
def turn_left(self):
self.lt(45)
def turn_right(self):
self.rt(45)
def accelerate(self):
self.speed += 1
def decelerate(self):
self.speed -= 1
# Create my sprite
player = Player("triangle", "white", 0, 0)
turtle.onkey(player.turn_left, "Left")
turtle.onkey(player.turn_right, "Right")
turtle.onkey(player.accelerate, "Up")
turtle.onkey(player.decelerate, "Down")
turtle.listen()
# Main game loop
while True:
player.move()
答案 0 :(得分:2)
您的代码基本上可以正常工作-它的启动速度如此之快,以至于在屏幕上运行之前很难控制它。我在代码中看到的主要问题是,在尝试同时使用原始定义和新定义时,您都重新定义了turtle.speed
。您应该为“速度”实例变量命名一个不同的名称。
下一个问题是,您使用while True:
在像乌龟这样的事件驱动世界中没有地位。您应该改为使用计时器事件。以下返工解决了上述两个问题,并调整了一些其他细节:
from turtle import Screen, Turtle
class Sprite(Turtle):
def __init__(self, spriteshape, color, startx, starty):
super().__init__(shape=spriteshape)
self.my_speed = 1
self.speed('fastest')
self.color(color)
self.penup()
self.goto(startx, starty)
def move(self):
self.forward(self.my_speed)
class Player(Sprite):
def __init__(self, spriteshape, color, startx, starty):
super().__init__(spriteshape, color, startx, starty)
self.my_speed = 4
def turn_left(self):
self.left(45)
def turn_right(self):
self.right(45)
def accelerate(self):
self.my_speed += 1
def decelerate(self):
self.my_speed -= 1
# Main game loop
def run():
player.move()
screen.ontimer(run, 50)
screen = Screen()
screen.bgcolor("black")
# Create my sprite
player = Player("triangle", "white", 0, 0)
screen.onkey(player.turn_left, "Left")
screen.onkey(player.turn_right, "Right")
screen.onkey(player.accelerate, "Up")
screen.onkey(player.decelerate, "Down")
screen.listen()
run()
screen.mainloop()