贪吃蛇的代码: 

import pygame,sys,time,random
from pygame.locals import *
# 定义颜色变量,颜色范围在0-255之间,由红、绿、蓝三个颜色组成的
redColour = pygame.Color(255,0,0)
blackColour = pygame.Color(0,0,0)
Colour=pygame.Color(0,200,200)
whiteColour = pygame.Color(255,255,255)
greyColour = pygame.Color(160,160,160)
gColour = pygame.Color(100,100,100)
bgColour=pygame.Color(200, 200, 200)#设置全局变量的颜色,便于修改
width,height=800,640
#定义暂停函数,暂停3秒钟
def gamepause(playSurface,score,flag):
    if flag==0:
        pFont = pygame.font.SysFont('simhei', 45)
        pSurf = pFont.render('吃了'+str(score)+'个,歇会儿!', True, greyColour)
        pRect = pSurf.get_rect()
        pRect.midtop = (400, 40)  # 设置得分的位置
        playSurface.blit(pSurf, pRect)
        pygame.display.flip()
        time.sleep(3)  # 推迟调用线程的运行,表示进程挂起的时间
    else:
        if __name__ == "__main__":
            main()

def gameOver(playSurface,score):#定义游戏结束

    #设置游戏结束的悬挂字体、样式、颜色、位置等
    gameOverFont = pygame.font.SysFont('kaiti',40)#设置字体样式以及大小
    gameOverSurf = gameOverFont.render('干饭生涯结束~', True, blackColour)#渲染游戏结束显示文本,字体颜色以及背景色
    gameOverRect = gameOverSurf.get_rect()#rect()用来描述、控制可见对象在python中的位置
    gameOverRect.midtop = (300, 40)#设置文本出现的的位置
    playSurface.blit(gameOverSurf, gameOverRect)#bilt()可以实现图像绘制

    scoreFont = pygame.font.SysFont('kaiti',40)#可设置加粗斜体之类的
    scoreSurf = scoreFont.render('干饭量:'+str(score), True, blackColour)
    scoreRect = scoreSurf.get_rect()
    scoreRect.midtop = (300, 90)#设置得分的位置
    playSurface.blit(scoreSurf, scoreRect)

    #游戏结束,音乐结束
    pygame.mixer.music.pause()#游戏结束音乐停止

   # 重新游戏
    fFont = pygame.font.SysFont('kaiti', 35)
    blockRect=pygame.Rect(600,400,160,60)
    tSurf = fFont.render('重新游戏', True, redColour,greyColour)
    tRect = tSurf.get_rect()
    tRect.x = blockRect.x + 10#控制字体的x位置
    tRect.y = blockRect.y + 15#控制字体的y位置
    playSurface.blit(tSurf, tRect)
    pygame.display.update()

   # 退出游戏
    baseRect = pygame.Rect(600,450,160,60)
    qSurf = fFont.render('退出游戏', True, blackColour, greyColour)
    qRect = qSurf.get_rect()
    qRect.x = blockRect.x + 10
    qRect.y = blockRect.y + 70
    playSurface.blit(qSurf, qRect)
    pygame.display.flip()#刷新

    while 1:
        # 检测例如按键等pygame事件
        for event in pygame.event.get():#在for循环里面实现移动
            if event.type == QUIT:#游戏退出
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:#电了键盘被按下来的情况
                # 判断键盘事件,用DAWS或者上下左右键都可以
                if event.key == K_SPACE or event.key == ord('r'):
                    if __name__ == "__main__":
                        main()
                if event.key == ord('q'):
                    pygame.quit()
                    sys.exit()#标准系统退出
            elif event.type ==MOUSEBUTTONDOWN:
                if blockRect.collidepoint(event.pos):
                    if __name__ == "__main__":
                        main()
                elif baseRect.collidepoint(event.pos):
                    pygame.quit()
                    sys.exit()

    pygame.quit()
    sys.exit()
 # 初始化pygame
def main():
    #插入音乐,不插入的可删除这段代码
    pygame.mixer.init()#混音器初始化
    file = r'D:\PythonDemo\小旭音乐 - 贪吃蛇大作战-夺宝模式.mp3'#找到音乐所在文件
    track = pygame.mixer.music.load(file)#加载音乐
    pygame.mixer.music.play(-1)#播放音乐,设置-1为循环播放

    pygame.init()
    # 创建pygame显示层
    playSurface = pygame.display.set_mode((width,height))#设置显示层大小,宽和高可修改
    pygame.display.set_caption('干饭蛇🐍')
    # 初始化变量
    snakePosition = [100,100] #贪吃蛇 利用列表来创建
    snakeSegments = [[100,100]] #贪吃蛇 蛇的身体,初始为一个单位
    raspberryPosition = [300,300] #树莓的初始位置
    raspberrySpawned = 1 #树莓的个数为1
    direction = 'right' #初始方向为右
    changeDirection = direction
    score = 0 #初始得分

    while True:
        # 检测例如按键等pygame事件
        for event in pygame.event.get():#在for循环里面实现移动
            if event.type == QUIT:#游戏退出
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:#电了键盘被按下来的情况
                # 判断键盘事件,用DAWS或者上下左右键都可以
                if event.key == K_RIGHT or event.key == ord('d'):
                    changeDirection = 'right'
                if event.key == K_LEFT or event.key == ord('a'):
                    changeDirection = 'left'
                if event.key == K_UP or event.key == ord('w'):
                    changeDirection = 'up'
                if event.key == K_DOWN or event.key == ord('s'):
                    changeDirection = 'down'
                if event.key == K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))
                if event.key == K_SPACE or event.key == ord('p'):
                    gamepause(playSurface,score,0)
                if event.key == ord('r'):
                    gamepause(playSurface, score, 1)
            elif event.type ==MOUSEBUTTONDOWN:
                if mRect.collidepoint(event.pos):
                    pygame.mixer.music.pause()
                else:
                    pygame.mixer.music.play(-1)
        # 判断是否输入了反方向
        if changeDirection == 'right' and not direction == 'left':
            direction = changeDirection
        if changeDirection == 'left' and not direction == 'right':
            direction = changeDirection
        if changeDirection == 'up' and not direction == 'down':
            direction = changeDirection
        if changeDirection == 'down' and not direction == 'up':
            direction = changeDirection

        # 根据方向移动蛇头的坐标
        if direction == 'right':
            snakePosition[0] += 20
        if direction == 'left':
            snakePosition[0] -= 20
        if direction == 'up':
            snakePosition[1] -= 20
        if direction == 'down':
            snakePosition[1] += 20

        # 增加蛇的长度
        snakeSegments.insert(0,list(snakePosition))#insert()用于将指定对象插入列表的指定位置,索引位置,列表对象

        # 利用位置关系,判断是否吃掉了树莓
        if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
            raspberrySpawned = 0
        else:
            snakeSegments.pop()#默认删除最后一个

        # 如果吃掉树莓,则重新生成树莓
        if raspberrySpawned == 0:
            x = random.randrange(1,40)
            y = random.randrange(1,32)
            raspberryPosition = [int(x*20),int(y*20)]#随机生成树莓的位置
            raspberrySpawned = 1
            score += 1

        #游戏界面填充背景,不插入的可删除这段代码
        pygame.init()
        playSurface.fill(bgColour)
        img=pygame.image.load("D:\PythonDemo\蜡笔小新2.png")
        playSurface.blit(img,[0,0])#背景图片以及位置

        mFont = pygame.font.SysFont('kaiti', 25)
        musicRect = pygame.Rect(680, 0, 100, 60)
        mSurf = mFont.render('music', True, gColour, bgColour)
        mRect = mSurf.get_rect()  # 画矩形
        mRect.x = musicRect.x + 10
        mRect.y = musicRect.y + 70
        playSurface.blit(mSurf, mRect)
        pygame.display.update()

        for position in snakeSegments:
            #rect用于在指定区域绘制矩形,Rect用于描述控制可见文本
            pygame.draw.rect(playSurface,redColour,Rect(position[0],position[1],20,20))#画蛇的位置以及大小
            pygame.draw.rect(playSurface,Colour,Rect(raspberryPosition[0], raspberryPosition[1],20,20))#画随机生成树莓

        # 刷新pygame显示层
        pygame.display.flip()
        # 判断是否死亡
          #撞墙了
        if snakePosition[0] > width or snakePosition[0] < 0:
            gameOver(playSurface,score)#显示出死亡界面以及得分
        if snakePosition[1] > height or snakePosition[1] < 0:
            gameOver(playSurface,score)
          #吃到自己了
        for snakeBody in snakeSegments[1:]:
            if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
                gameOver(playSurface,score)
        # 控制游戏速度
        fpsClock = pygame.time.Clock()  # 创建clock对象
        fpsClock.tick(15)#为上面的clock设置帧频,可调节,里面的数字越大,速度越快

if __name__ == "__main__":
    main()

更多推荐