我正在尝试修改代码并使之面向对象,但是现在它无法正常工作。每当我打电话给if snake.rect.colliderect(food.rect)
时,它都会返回AttributeError: 'bool' object has no attribute 'rect'
。如果有帮助,这是我的其余代码。
import pygame,sys,random
from pygame.locals import *
pygame.init()
RES = (500,500)
rectangle_height = 20
rectangle_width = 20
GREEN = (0,255,0)
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
clock = pygame.time.Clock()
win = pygame.display.set_mode(RES)
pygame.display.set_caption("Snake")
class Snake():
def __init__(self, color, width, height):
self.image = pygame.Surface((rectangle_width,rectangle_height))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.speed = 20
self.move = (0,0)
class Food():
def __init__(self,color,width,height):
self.image = pygame.Surface((rectangle_width,rectangle_height))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(20,500,20)
self.rect.y = random.randrange(20,500,20)
self.state = True
def event_loop(snake,food):
while True:
win.fill(BLACK)
# for x in range(0,win_width,20):
# pygame.draw.line(win,WHITE,(x,0),(x,500))
# for y in range(0,win_height,20):
# pygame.draw.line(win,WHITE,(0,y),(500,y))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT:
snake.move = (snake.speed,0)
elif event.key == K_LEFT:
snake.move = (-snake.speed,0)
elif event.key == K_UP:
snake.move = (0,-snake.speed)
elif event.key == K_DOWN:
snake.move = (0,snake.speed)
if snake.rect.colliderect(food.rect):
food.state = False
if food.state:
win.blit(food.image,food.rect)
else:
food.rect.x = random.randrange(20,500,20)
food.rect.y = random.randrange(20,500,20)
win.blit(food.image,food.rect)
food = True
win.blit(snake.image,snake.rect)
snake.rect.move_ip(snake.move)
snake.rect.clamp_ip(win.get_rect())
pygame.display.update()
clock.tick(5)
snake = Snake(GREEN,rectangle_width,rectangle_height)
food = Food(RED,rectangle_width,rectangle_height)
event_loop(snake,food)
答案 0 :(得分:0)
这是因为您两次向food
分配了一个值。第一次是在文件级别:
food = Food(RED,rectangle_width,rectangle_height)
这很好,并且如果您不是第二次在food
中设置event_loop
,则您的代码可能会起作用:
food = True
在调用之后,food是布尔值,因此会出现错误,告诉您布尔变量没有rect
属性。
删除第二个任务,它应该可以解决问题。