蛇类游戏:蛇与它的身体相撞

2024-09-28 22:36:03 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我目前正在编写一个蛇游戏代码,我几乎完成了,但我有困难写一个代码,将导致游戏结束,如果蛇的头部与它的身体碰撞,我想我可以创建一个碰撞功能类似的碰撞功能的蛇和苹果:

pygame.sprite.collide_rect(h, a)

然而,蛇的所有独立部分都以相同的方式活动,因此蛇总是不断地与自己发生碰撞。有什么办法可以解决这个问题吗。你知道吗

以下是我的完整蛇代码:

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 = 2
HitLoop = 0
ScreenWidth = 800
AppleCount = 1

#creating initial snake
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

pygame.init()
screen = pygame.display.set_mode([ScreenWidth, ScreenWidth])
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)

AppleList = []
for i in range(0,AppleCount):
    z = random.randint(10,ScreenWidth-25)
    q = random.randint(10,ScreenWidth-25)
    a = APPLE(z, q)
    AppleList.append(a)
    allspriteslist.add(a)

#main loop
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)
    #snake builder
    OldSegment = SnakeSegments.pop(-1)
    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,a)
    allspriteslist.update()

    # collision had to create apples own list for respawn
    if pygame.sprite.collide_rect(h, a) == True and HitLoop == 0:
        SnakeSegments.append(h)
        AppleList.append(a)
        HitLoop = HitLoop + 1
        z = random.randint(10, ScreenWidth - 25)
        q = random.randint(10, ScreenWidth - 25)
        OldApple = AppleList.pop()
        allspriteslist.remove(OldApple)
        a = APPLE(z, q)
        allspriteslist.update()

# collision had to create a new class
    if pygame.sprite.collide_rect(h, h) == True:
        pass


    # hit timer
    if HitLoop > 0:
        HitLoop += 1
    if HitLoop > 4:
        HitLoop = 0

    screen.fill(BLACK)

    #game walls
    pygame.draw.rect(screen, GREEN, [0, 0, ScreenWidth, 10])
    pygame.draw.rect(screen, GREEN, [0, 0, 10, ScreenWidth])
    pygame.draw.rect(screen, GREEN, [0, ScreenWidth - 10, ScreenWidth, 10])
    pygame.draw.rect(screen, GREEN, [ScreenWidth - 10, 0, 10, ScreenWidth])
    if x <= 10:
        done = True
    if x >= ScreenWidth - Width:
        done = True
    if y <= 10:
        done = True
    if y >= ScreenWidth - Width:
        done = True


    allspriteslist.draw(screen)
    pygame.display.flip()

Tags: rectselfeventifwidthscreenpygamefactor
1条回答
网友
1楼 · 发布于 2024-09-28 22:36:03

在您的代码中,似乎您正在检查蛇头是否与自身发生碰撞,这将始终返回True。您需要单独检查蛇头是否与其尾部的任何部分发生碰撞:

for segment in SnakeSegments[2:]:
    if pygame.sprite.collide_rect(h, segment):
        pass # collision detected, game-over

蛇的头部预计会与它后面的部分直接碰撞,这就是为什么我们需要从列表中的第3个元素开始。你知道吗

相关问题 更多 >