我正在创建游戏,但是当我按向上或向下箭头键时,什么也没有发生。当我运行这些代码时,乌龟已经移动了,而不是在我按下这些键时移动了。这是代码:
turtle_race.py:
from turtle import Screen
import elements
win = Screen()
win.setup(800, 600)
win.bgcolor("cyan")
win.title("Turtle Race")
win.tracer(0)
obj = elements.Objects()
win.onkeypress(obj.player_one_move(), "Up")
win.onkeypress(obj.player_two_move(), "Down")
win.listen()
while True:
win.update()
这是 elements.py:
from turtle import Turtle
class Objects:
def __init__(self):
self.player_one = Turtle("turtle")
self.player_one_init()
self.x1 = 0
self.x2 = 0
self.player_two = Turtle("turtle")
self.player_two_init()
def player_one_init(self):
self.x1 = -200
self.player_one.speed(5)
self.player_one.color("red")
self.player_one.penup()
self.player_one.setx(self.x1)
self.player_one.sety(150)
def player_two_init(self):
self.x2 = -200
self.player_two.speed(5)
self.player_two.color("green")
self.player_two.penup()
self.player_two.setx(self.x2)
self.player_two.sety(-150)
def player_one_move(self):
x = self.player_one.xcor() + 35
self.player_one.setx(x)
def player_two_move(self):
x = self.player_two.xcor() + 35
self.player_two.setx(x)
答案 0 :(得分:3)
快速答案是您要传递这些方法,而不是调用它们:
win.onkeypress(obj.player_one_move(), "Up")
win.onkeypress(obj.player_two_move(), "Down")
因此,请这样做:
win.onkeypress(obj.player_one_move, "Up")
win.onkeypress(obj.player_two_move, "Down")
这些方法将在以后的某个时间由其他人调用。
更长的答案是您完全误解了面向对象的编程。您应该创建两个Objects
类的实例,而不是操纵两个玩家的Player
类实例。
turtle_race.py:
from turtle import Screen, mainloop
import elements
screen = Screen()
screen.setup(800, 600)
screen.bgcolor('cyan')
screen.title("Turtle Race")
player_1 = elements.Player('red', (-200, 150))
player_2 = elements.Player('green', (-200, -150))
screen.onkey(player_1.move, 'Up')
screen.onkey(player_2.move, 'Down')
screen.listen()
mainloop()
elements.py:
from turtle import Turtle
class Player:
def __init__(self, color, position):
self.player = Turtle('turtle')
self.player.color(color)
self.player.penup()
self.player.setposition(position)
def move(self):
x = self.player.xcor() + 35
self.player.setx(x)