在尝试向我的蛇游戏添加图像时出错



我的代码中有一个错误,错误消息是:

第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)

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

self.image = img

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

最新更新