所以我刚刚开始我的第一个项目,(做一个'蛇'游戏)。
但是我的一行(Line 65, in run_game, snakehead.update()'
)有一个名为'snakehead' object has no attribute 'update'
的错误,我尝试了一些但是我无法让它工作......
完整代码:
import pygame
from pygame.locals import *
class SnakeHead(object):
def __init__(self):
self.image = pygame.image.load('data/snake_head.png')
self.rect = self.image.get_rect()
self.rect.centerx = 320
self.rect.centery = 240
self.direction = (0,-1)
self.crashed = False
def render(self, screen):
screen.blit(self.image, self.rect)
def update(self):
self.rect.centerx += self.direction(0) * 2
self.rect.centery += self.direction(1) * 2
if self.rect.left < 0:
self.rect.left = 0
self.crashed = True
if self.rect.right > 639:
self.rect.right = 639
self.crashed = True
if self.rect.top < 0:
self.rect.top = 0
self.crashed = True
if self.rect.bottom > 479:
self.rect.bottom = 479
self.crashed = True
def run_game():
pygame.init()
screen = pygame.display.set_mode((640,480))
snakehead = SnakeHead()
clock = pygame.time.Clock()
while 1:
clock.tick(32)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
return
screen.fill((175,175,175))
snakehead.update()
snakehead.render(screen)
pygame.display.flip()
答案 0 :(得分:1)
检查缩进。 update被定义为render的子函数。
答案 1 :(得分:1)
如果您对更新方法的缩进稍作修改,它会起作用:
class SnakeHead(object):
def __init__(self):
self.image = pygame.image.load('data/snake_head.png')
self.rect = self.image.get_rect()
self.rect.centerx = 320
self.rect.centery = 240
self.direction = (0,-1)
self.crashed = False
def render(self, screen):
screen.blit(self.image, self.rect)
def update(self):
self.rect.centerx += self.direction(0) * 2
self.rect.centery += self.direction(1) * 2
if self.rect.left < 0:
self.rect.left = 0
self.crashed = True
if self.rect.right > 639:
self.rect.right = 639
self.crashed = True
if self.rect.top < 0:
self.rect.top = 0
self.crashed = True
if self.rect.bottom > 479:
self.rect.bottom = 479
self.crashed = True