Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 蛇类游戏:蛇与自身碰撞_Python_Pygame - Fatal编程技术网

Python 蛇类游戏:蛇与自身碰撞

Python 蛇类游戏:蛇与自身碰撞,python,pygame,Python,Pygame,您好,我目前正在编写一个蛇游戏代码,我快写完了,但是我很难编写一个代码,如果蛇的头部与身体发生碰撞,就会导致游戏结束,我想我可以创建一个类似于蛇和苹果碰撞功能的碰撞功能: pygame.sprite.collide_rect(h, a) 然而,蛇的所有独立部分都以相同的方式活动,因此蛇总是不断地与自己碰撞。有没有办法解决这个问题 以下是我的完整snake代码: import pygame import random BLACK = (0, 0, 0) GREEN = (0, 250, 0)

您好,我目前正在编写一个蛇游戏代码,我快写完了,但是我很难编写一个代码,如果蛇的头部与身体发生碰撞,就会导致游戏结束,我想我可以创建一个类似于蛇和苹果碰撞功能的碰撞功能:

pygame.sprite.collide_rect(h, a)
然而,蛇的所有独立部分都以相同的方式活动,因此蛇总是不断地与自己碰撞。有没有办法解决这个问题

以下是我的完整snake代码:

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()
导入pygame
随机输入
黑色=(0,0,0)
绿色=(0,250,0)
红色=(250,0,0)
宽度=15
空间=3
X速度=18
Y速度=0
系数=18
clock=pygame.time.clock()
分段=2
HitLoop=0
屏幕宽度=800
AppleCount=1
#创建初始snake
班长(pygame.sprite.sprite):
定义初始值(自、x、y、颜色=绿色):
super()。\uuuu init\uuuuu()
self.image=pygame.Surface([Width,Width])
自映像填充(彩色)
self.rect=self.image.get_rect()
self.rect.x=x
自校正y=y
苹果类(pygame.sprite.sprite):
定义初始(self,z,q):
super()。\uuuu init\uuuuu()
self.image=pygame.Surface([Width,Width])
self.image.fill(红色)
self.rect=self.image.get_rect()
self.rect.x=z
自校正y=q
pygame.init()
screen=pygame.display.set_模式([ScreenWidth,ScreenWidth])
pygame.display.set_标题('Snake'))
allspriteslist=pygame.sprite.Group()
蛇节=[]
对于范围内的i(段):
x=250-(宽度+空间)*i
y=30
h=头部(x,y)
蛇段。附加(h)
所有精灵列表。添加(h)
AppleList=[]
对于范围内的i(0,AppleCount):
z=random.randint(10,屏幕宽度-25)
q=random.randint(10,屏幕宽度-25)
a=苹果(z,q)
appelist.append(a)
所有精灵列表。添加(a)
#主回路
完成=错误
虽然没有这样做:
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
完成=正确
如果event.type==pygame.KEYDOWN:
如果event.key==pygame.K_左:
如果Xspeed==-因子:
Xspeed=0
如果Xspeed==系数:
X速度=系数
其他:
Xspeed=Xspeed-系数
Y速度=0
elif event.key==pygame.K_RIGHT:
如果Xspeed==系数:
Xspeed=0
如果Xspeed==-因子:
Xspeed=-因子
其他:
Xspeed=Xspeed+系数
Y速度=0
elif event.key==pygame.K_UP:
如果Y速度==-系数:
Y速度=0
如果Yspeed==系数:
Y速度=系数
其他:
Y速度=Y速度-系数
Xspeed=0
elif event.key==pygame.K_向下:
如果Yspeed==系数:
Y速度=0
如果Y速度==-系数:
Y速度=-因子
其他:
Y速度=Y速度+系数
Xspeed=0
时钟滴答(10)
#造蛇者
OldSegment=SnakeSegments.pop(-1)
allspriteslist.remove(旧段)
x=蛇段[0]。矩形x+x速度
y=蛇段[0]。矩形y+y速度
h=头部(x,y)
蛇段.插入(0,h)
allspriteslist.add(h,a)
allspriteslist.update()
#collision必须为respawn创建自己的列表
如果pygame.sprite.collide_rect(h,a)=True且HitLoop==0:
蛇段。附加(h)
appelist.append(a)
HitLoop=HitLoop+1
z=random.randint(10,屏幕宽度-25)
q=random.randint(10,屏幕宽度-25)
OldApple=AppleList.pop()
allspriteslist.remove(旧苹果)
a=苹果(z,q)
allspriteslist.update()
#碰撞必须创建一个新类
如果pygame.sprite.collide_rect(h,h)=True:
通过
#命中计时器
如果HitLoop>0:
HitLoop+=1
如果HitLoop>4:
HitLoop=0
屏幕填充(黑色)
#游戏墙
pygame.draw.rect(屏幕,绿色,[0,0,屏幕宽度,10])
pygame.draw.rect(屏幕,绿色,[0,0,10,屏幕宽度])
pygame.draw.rect(屏幕,绿色,[0,屏幕宽度-10,屏幕宽度,10])
pygame.draw.rect(屏幕,绿色,[ScreenWidth-10,0,10,ScreenWidth])
如果x=屏幕宽度-宽度:
完成=正确
如果y=屏幕宽度-宽度:
完成=正确
allspriteslist.draw(屏幕)
pygame.display.flip()

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

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

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

请不要随意添加内容来规避编辑限制。事实上,一个字一个字地重复同一个问题;标题稍有不同。westgarthw这是一个巨大的帮助谢谢你,但是如果蛇也吃了苹果,这也是真的吗?