【问题标题】:Getting error when trying to add a image to my snake game尝试将图像添加到我的蛇游戏时出错
【发布时间】:2021-07-26 19:53:59
【问题描述】:

我的代码有错误,错误信息是:

第 195 行第 127 行“str”对象没有属性“get_rect”

但我看不出有什么问题。


img = 'banana-hi.png'

class Snake():
    def __init__(self):
        self.alive = True
        self.length = 1
        self.tail = []
        self.x = 0
        self.y = 0
        self.xV = 0
        self.yV = 1
        self.tick = 0
    
    def draw(self):
        for section in self.tail:
            pygame.draw.rect(screen,WHITE,(((section[0]) * scale),((section[1]) * scale) + 100,scale,scale))
    
    def update(self):
        if self.alive == True:
            if self.tick == 10:
                self.x += self.xV
                self.y += self.yV
                for segment in self.tail:
                    if segment[0] == self.x and segment[1] == self.y:
                        self.alive = False
                self.tick = 0
                self.tail.append((self.x,self.y))
            else:
                self.tick += 1
            while len(self.tail) > self.length:
                self.tail.pop(0)
        if self.x == -1:
            self.alive = False
            self.x = 0
        if self.x == (size[0] / scale):
            self.alive = False
            self.x = (size[0] / scale) - 1
        if self.y == -1:
            self.alive = False
            self.y = 0
        if self.y == (size[1] - 100) / scale:
            self.alive = False
            self.y = ((size[1] - 100) / scale) - 1
    
    def reset(self):
        self.alive = True
        self.length = 1
        self.tail.clear()
        self.x = 0
        self.y = 0
        self.xV = 0
        self.yV = 1
        self.tick = 0

class Food(pygame.sprite.Sprite):
    def __init__(self,img):
        pygame.sprite.Sprite.__init__(self)
        self.image = img
        self.rect = self.image.get_rect()
        self.x = random.randrange((size[0] / scale) - 1)
        self.y = random.randrange(((size[1] - 100) / scale) - 1)
        
    
    def draw(self):
        pygame.draw.self.rect(screen,GREEN,((self.x * scale),(self.y * scale) + 100,scale,scale))
    
    def update(self):
        if snake.x == self.x and snake.y == self.y:
            self.reset()
            snake.length += 1
    
    def reset(self):
        self.x = random.randrange((size[0] / scale) - 1)
        self.y = random.randrange(((size[1] - 100) / scale) - 1)

【问题讨论】:

  • 有一个错字:pygame.draw.rect 而不是pygame.draw.self.rect
  • 哦,我没有注意到,但即使在修复后它仍然给我同样的错误
  • 这不是问题的答案。我刚刚提到有一个错字。

标签: python image pygame attributes attributeerror


【解决方案1】:

img 是图像文件的名称。加载文件并使用pygame.image.load 创建一个pygame.Surface 对象:

self.image = img

self.image = pygame.image.load(img)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多