如何在 OOP 中让乌龟移动?

问题描述 投票:0回答:2

我正在制作一个简单的乒乓球游戏,并尝试使用 OOP 来制作它。我正在尝试使用 ycor 让海龟移动。它的目的是调用“objects_up”方法将它们向上移动,然后对 x 和 y 执行相同的操作。 我尝试了各种缩进,不使用方法并将 wn.listen 移到类之外。我究竟做错了什么?我不断收到错误:

编辑1:使桨成为乌龟的子类。我收到一个新的、不同的错误:

Edit2:遵循@OneCricketeer 的建议,我现在正在使用 lambda。程序运行良好,但按键不起作用,并且出现大量错误:例如

````
File "C:\Users\okpla\AppData\Local\Programs\Python\Python311\Lib\turtle.py", line 1294, in _incrementudc
    raise Terminator
````

这是代码:

````
from turtle import Screen,Turtle

wn = Screen()
wn.title("Pong by CGGamer")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)

class Paddles(Turtle):  
    def __init__(self,position,size):
        super().__init__()
        self.position = position
        self.size = size
        self.speed(0)
        self.shape("square")
        self.shape("square")
        self.color("white")
        self.shapesize(size,1)
        self.penup()
        self.setposition(position)
        wn.listen()
        wn.onkeypress(lambda self:self.sety(self.ycor() + 20),"w")

paddle_a = Paddles((-350,0),5)


paddle_b = Paddles((350,0),5)


ball = Paddles((0,0),1)


````
python class python-turtle
2个回答
0
投票

谢谢大家!解决了问题,比我想象的要容易得多。 这是新代码:

from turtle import Screen,Turtle

wn = Screen()
wn.title("Pong by CGGamer")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)

class Paddles(Turtle):  
    def __init__(self,position,size):
        super().__init__()
        self.position = position
        self.size = size
        self.speed(0)
        self.shape("square")
        self.shape("square")
        self.color("white")
        self.y = 20
        self.x = 20
        self.shapesize(size,1)
        self.penup()
        self.setposition(position)
    
    def moving_on_y_up(self):
          newy = self.ycor() + self.y
          self.goto(self.xcor(),newy)
   
    def moving_on_x_right(self):
        newx = self.xcor() + self.x
        self.goto(newx,self.ycor())

    def moving_on_y_down(self):
        newy = self.ycor() - self.y
        self.goto(self.xcor(),newy)
    
    def moving_on_x_left(self):
        newx = self.xcor() - self.x
        self.goto(newx,self.ycor())


paddle_a = Paddles((-350,0),5)
wn.listen()
wn.onkeypress(paddle_a.moving_on_y_up, "w")
wn.onkeypress(paddle_a.moving_on_x_right, "d")
wn.onkeypress(paddle_a.moving_on_y_down, "s")
wn.onkeypress(paddle_a.moving_on_x_left, "a")


paddle_b = Paddles((350,0),5)
wn.listen()
wn.onkeypress(paddle_a.moving_on_y_up, "w")
wn.onkeypress(paddle_a.moving_on_x_right, "d")
wn.onkeypress(paddle_a.moving_on_y_down, "s")
wn.onkeypress(paddle_a.moving_on_x_left, "a")



ball = Paddles((0,0),1)



while True:
    wn.update()

0
投票

创建一只会动的乌龟真的很容易。 这段代码将使你的乌龟前进。

import turtle
turtle.goto(100,0)   
© www.soinside.com 2019 - 2024. All rights reserved.