如何修复“xcor()缺少1个必需的位置参数:Python中的'self'错误

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

我只是想从我创建的海龟类中引用海龟的位置。我觉得我所做的事情在理论上是不正确的,但它看起来好像可行。也许这个错误超出了我的范围,但我不确定。

我尝试过其他方法来放置海龟,但它们变得非常复杂和无法使用。

class Maze_wall(Turtle):

    def __init__(self, x_loc, y_loc):
       super().__init__()
       self.color("#ffffff")
       self.penup()
       self.speed(0)
       self.shape("square")
       self.shapesize(stretch_wid=0.95, stretch_len=0.95)
       self.goto(x_loc, y_loc)
       self.showturtle()

上面是我的乌龟类,下面我尝试引用海龟x和y坐标。

def wall_right():
    Maze_wall(Maze_wall.xcor(), Maze_wall.ycor())
def wall_left():
    Maze_wall(Maze_wall.xcor(), Maze_wall.ycor())
def wall_up():
    Maze_wall(Maze_wall.xcor(), Maze_wall.ycor())
def wall_down():
    Maze_wall(Maze_wall.xcor(), Maze_wall.ycor())

我的目标是每个功能根据海龟的当前位置放置一只乌龟。

python class turtle-graphics superclass
1个回答
0
投票

简短的回答:你在一个乌龟子类而不是一个乌龟实例上调用.xcor()

更长的答案:你似乎正在混淆你正在使用的乌龟,将迷宫与将成为迷宫墙壁的海龟展开。在它存在之前你不能问墙的位置。我期望的是代码更像:

from turtle import Screen, Turtle

class Maze_wall(Turtle):

    def __init__(self, x_loc, y_loc):
        super().__init__(visible=False)

        self.shape('square')
        self.speed('fastest')
        self.color('black')
        self.penup()
        self.shapesize(stretch_wid=0.95, stretch_len=0.95)
        self.goto(x_loc, y_loc)
        self.showturtle()

def wall_right(turtle):
        return Maze_wall(turtle.xcor(), turtle.ycor())

builder = Turtle(visible=False)
builder.penup()

walls = []

for _ in range(4):
    builder.forward(100)
    wall = wall_right(builder)
    walls.append(wall)
    builder.left(90)

screen = Screen()
screen.exitonclick()
© www.soinside.com 2019 - 2024. All rights reserved.