python game of life 绘制函数(海龟)(调用实例方法?)

python game of life draw function (turtle) (invoking an instance method?)

我发现这个实现 Conway's Game of Life。我从来没有处理过 GUI,我正在尝试理解这段代码(并实现我自己的代码)

有一个特定的函数让我很烦。绘制每个 'organism' 的函数(黑色是活的,白色是死的)。

# import turtle (at the top)
def draw(self, x, y):
    "Update the cell (x,y) on the display."
    turtle.penup()
    key = (x, y)
    if key in self.state:
        turtle.setpos(x*CELL_SIZE, y*CELL_SIZE)
        turtle.color('black')
        turtle.pendown()
        turtle.setheading(0)
        turtle.begin_fill()
        for i in range(4):
            turtle.forward(CELL_SIZE-1)
            turtle.left(90)
        turtle.end_fill()

这是显示整个板的函数: 定义显示(自我):

"""Draw the whole board"""
turtle.clear()
for i in range(self.xsize):
    for j in range(self.ysize):
        self.draw(i, j)
turtle.update()

代码当然有效,但是 Intellij 说他找不到对所有这些函数的引用。 我认为这是因为它正在调用实例方法,作为 class 方法并且缺少 self。

  1. 我不明白它是如何工作的。
  2. 我该如何解决?我试图制作一个新的 Turtle,但它没有用(在我看来这不是一个好主意)。也许我应该将 Turtle 作为参数放入函数中?

已经坚持这个几个小时了。会喜欢一些帮助。

Intellij says that he can't find reference to ALL these functions

乌龟模块是一只奇怪的鸟。 (请原谅混合比喻。)它试图为不同的观众提供不同的东西,这会导致混淆:

1) 函数与方法

Turtle 是一个面向对象的模块,您可以在其中创建海龟和屏幕的实例并调用它们的方法:

screen = turtle.Screen()
screen.setworldcoordinates(0, 0, xsize, ysize)

yertle = turtle.Turtle()
yertle.forward(100)

但是,为了适应新手程序员and/or模拟其他 turtle 语言,它还提供了一个功能接口:

turtle.setworldcoordinates(0, 0, xsize, ysize)
turtle.forward(100)  # move the "default" turtle forward

为了防止混淆函数和方法,我建议以这种方式导入 turtle:

from turtle import Turtle, Screen

只允许对象接口而不允许函数接口。

之所以会出现 IntelliJ 警告,是因为 turtle 的功能接口是在加载时动态从对象方法接口派生的——文件中没有实际的函数可以返回引用。

2) 独立与嵌入式

turtle 模块旨在 运行 独立或嵌入到更大的 tkinter 项目中。您访问 turtles 的方式和屏幕会有所不同,具体取决于您在做什么。

就 Conway 的生命游戏的实现而言,它在可能应该使用对象一时使用了功能接口,并且将 turtle 模块视为独立模块,然后使用它打开其他基于 Tk 的面板:

from turtle import TK

应该反过来吧。没有快速修复来使这个模块符合要求,每个 turtle 和 tkinter 参考都需要检查和重新考虑。