我曾尝试使用python的pygame进行蛇游戏 . 我所做的是在一个特定的距离开始创建2个片段,这将是我的蛇,当它吃掉更多的物体时它会生长 . 但是当蛇头与任何其他部分发生碰撞时,我希望我的游戏结束 . 我使用sprite collide方法来检测蛇头(这里是snake_segment [0])和段组之间的碰撞 . 这是与我的问题相关的代码
class Segment(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([segment_width,segment_height])
self.image.fill(black)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# we create the apple object here
class Apple(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.transform.scale(apple1,(25,25))
self.image.set_colorkey(white)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(30,screen_width-30)
self.rect.y = random.randrange(30,screen_height-30)
# we create the function for sprites so that we can manage all the sprites
all_sprites = pygame.sprite.Group()
segment_group = pygame.sprite.Group()
snake_segment = [] # we create this list to store all thhe segments
for i in range(0,2):
x = 250 - (segment_width+ segement_margin)*i
y= 30
segments =Segment(x,y)
snake_segment.append(segments)
all_sprites.add(segments)
segment_group.add(segments)
apple_group = pygame.sprite.Group()
apple =Apple()
apple_group.add(apple)
all_sprites.add(apple)
running = True
while running:
# we tweak the fps here
clock.tick(fps)
# we keep track of all the events here
for event in pygame.event.get():
# if the user wishes to quit
if event.type == pygame.QUIT:
running = False
# we set the movement of the segments
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = (segment_height + segement_margin)*-1
x_change=0
if event.key == pygame.K_DOWN:
y_change = (segment_height + segement_margin)
x_change= 0
if event.key == pygame.K_LEFT:
x_change = (segment_width + segement_margin)*-1
y_change = 0
if event.key == pygame.K_RIGHT:
x_change = (segment_width + segement_margin)
y_change = 0
# we remove the last element of the snake segment
old_segment = snake_segment.pop()
all_sprites.remove(old_segment)
# we add the new element on the top of the snake
x = snake_segment[0].rect.x + x_change
y = snake_segment[0].rect.y + y_change
segment = Segment(x,y)
snake_segment.insert(0,segment)
all_sprites.add(segment)
# here we detect collison between apple group and snake sprite and make changes
eat_coll = pygame.sprite.spritecollide(snake_segment[0],apple_group,True)
if eat_coll:
x = snake_segment[-1].rect.x - x_change
y = snake_segment[-1].rect.y - y_change
segment = Segment(x,y)
snake_segment.insert(-1,segment)
segment_group.add(segment)
apple = Apple()
apple_group.add(apple)
all_sprites.add(apple)
bite_sound.play()
snake_coll = pygame.sprite.spritecollide(snake_segment[0],segment_group,False)
if snake_coll:
running = False
# update each sprite
all_sprites.add(segment)
# here we fill the background
screen.blit(background_image,background_rect)
all_sprites.draw(screen)
# we will update the screen
pygame.display.update()