2

我正在创建游戏,但是当我按下向上或向下箭头键时,什么也没有发生。当我按下这些键时,乌龟并没有移动,而是在我运行代码时已经移动了。这是代码:

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)
4

1 回答 1

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()

元素.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)
于 2020-05-21T18:26:02.637 回答