我得到了这个错误,它说“NameError:global name‘Sheep’未定义”

2024-04-16 05:16:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我写的代码在处理草图,我得到了这个错误,我试图修复它,但它仍然不工作,所以我需要一些帮助来修复它,请帮助我。错误在这一行“sheepList.append(Sheep(random(width))”

class Grass:
    def __init__(self,x,y,sz):
        self.x = x
        self.y = y
        self.energy = 5 #energy from eating this patch
        self.eaten = False #hasn't been eaten yet
        self.sz = sz
    def update(self):
        fill(GREEN)
        rect(self.x,self.y,self.sz,self.sz)
sheepList = [] #list to store sheep
grassList = [] #list to store grass
patchSize = 10 #size of each patch of grass
def setup():
    global patchSize
    size(600,600)
    #create the sheep
    for i in range(3):
        sheepList.append(Sheep(random(width),
                          random(height)))
        #create the grass:
    for x in range(0,width,patchSize):
        for y in range(0,height,patchSize):
            grassList.append(Grass(x,y,patchSize))
def draw():
    background(255)
    #update the grass first
    for grass in grassList:
        grass.update()
    #then the sheep
    for sheep in sheepList:
        sheep.update()