我目前正在设计蛇类游戏,但是难以检测到精灵之间的碰撞并不断出现错误-AttributeError:类型对象'head'没有属性'rect'。
我正在使用
eat = pygame.sprite.collide_rect(head, apple)
检测碰撞的功能。
这是我的完整代码
import pygame
import random
BLACK = (0, 0, 0)
GREEN = (0, 250, 0)
RED = (250, 0, 0)
Width = 15
Space = 3
Xspeed = 18
Yspeed = 0
Factor = 18
clock = pygame.time.Clock()
segments = 10
class head(pygame.sprite.Sprite):
def __init__(self, x, y, colour = GREEN):
super().__init__()
self.image = pygame.Surface([Width, Width])
self.image.fill(colour)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
class apple(pygame.sprite.Sprite):
def __init__(self, z, q):
super().__init__()
self.image = pygame.Surface([Width, Width])
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = z
self.rect.y = q
for i in range(0,20):
z = random.randint(1,800)
q = random.randint(1,800)
c = apple(z,q)
pygame.init()
screen = pygame.display.set_mode([800, 800])
pygame.display.set_caption('Snake')
allspriteslist = pygame.sprite.Group()
SnakeSegments = []
for i in range(segments):
x = 250 - (Width + Space) * i
y = 30
h = head(x, y)
SnakeSegments.append(h)
allspriteslist.add(h)
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if Xspeed == -Factor:
Xspeed = 0
if Xspeed == Factor:
Xspeed = Factor
else:
Xspeed = Xspeed - Factor
Yspeed = 0
elif event.key == pygame.K_RIGHT:
if Xspeed == Factor:
Xspeed = 0
if Xspeed == -Factor:
Xspeed = -Factor
else:
Xspeed = Xspeed + Factor
Yspeed = 0
elif event.key == pygame.K_UP:
if Yspeed == -Factor:
Yspeed = 0
if Yspeed == Factor:
Yspeed = Factor
else:
Yspeed = Yspeed - Factor
Xspeed = 0
elif event.key == pygame.K_DOWN:
if Yspeed == Factor:
Yspeed = 0
if Yspeed == -Factor:
Yspeed = -Factor
else:
Yspeed = Yspeed + Factor
Xspeed = 0
clock.tick(10)
OldSegment = SnakeSegments.pop()
allspriteslist.remove(OldSegment)
x = SnakeSegments[0].rect.x + Xspeed
y = SnakeSegments[0].rect.y + Yspeed
h = head(x, y)
SnakeSegments.insert(0, h)
allspriteslist.add(h,c)
allspriteslist.update()
print(x,y)
print(z,q)
eat = pygame.sprite.collide_rect(head, apple)
screen.fill(BLACK)
#game walls
pygame.draw.rect(screen, GREEN, [0, 0, 800, 10])
pygame.draw.rect(screen, GREEN, [0, 0, 10, 800])
pygame.draw.rect(screen, GREEN, [0, 790, 800, 10])
pygame.draw.rect(screen, GREEN, [790, 0, 10, 800])
if x <= 10:
done = True
if x >= 785:
done = True
if y <= 10:
done = True
if y >= 785:
done = True
allspriteslist.draw(screen)
pygame.display.flip()