Python贪吃蛇游戏详细代码和注释

在写Python游戏项目时,最重要的时python中的pygame库。安装pygame库和用法在我CSDN博客另一篇文章上。这里就不详细说了。下边时运行游戏界面。

下边是详细的代码和注释

import pygame,sys,random,time
from pygame.locals import *   #从pygame模块导入常用的函数和常量
#定义颜色变量
black_colour = pygame.Color(0,0,0)
white_colour = pygame.Color(255,255,255)
red_colour = pygame.Color(255,0,0)
grey_colour = pygame.Color(150,150,150)
#定义游戏结束函数
def GameOver(gamesurface):
    #设置提示字体的格式
    GameOver_font = pygame.font.SysFont("MicrosoftYaHei", 16)
    #设置提示字体的颜色
    GameOver_colour = GameOver_font.render('Game Over',True,grey_colour)
    #设置提示位置
    GameOver_location = GameOver_colour.get_rect()
    GameOver_location.midtop = (320,10)
    #绑定以上设置到句柄
    gamesurface.blit(GameOver_colour,GameOver_location)
    #提示运行信息
    pygame.display.flip()
    #休眠5秒
    time.sleep(5)
    #退出游戏
    pygame.quit()
    #退出程序
    sys.exit()
#定义主函数
def main():
    #初始化pygame,为使用硬件做准备
    pygame.init()
    pygame.time.Clock()
    ftpsClock = pygame.time.Clock()
    #创建一个窗口
    gamesurface = pygame.display.set_mode((640,480))
    #设置窗口的标题
    pygame.display.set_caption('tanchishe snake')
    #初始化变量
    #初始化贪吃蛇的起始位置
    snakeposition = [100,100]
    #初始化贪吃蛇的长度
    snakelength = [[100,100],[80,100],[60,100]]
    #初始化目标方块的位置
    square_purpose = [300,300]
    #初始化一个数来判断目标方块是否存在
    square_position = 1
    #初始化方向,用来使贪吃蛇移动
    derection = "right"
    change_derection = derection
    #进行游戏主循环
    while True:
        #检测按键等pygame事件
        for event in pygame.event.get():
            if event.type==QUIT:
                #接收到退出事件后,退出程序
                pygame.quit()
                sys.exit()
            elif event.type==KEYDOWN:
                #判断键盘事件,用w,s,a,d来表示上下左右
                if event.key==K_RIGHT or event.key==ord('d'):
                    change_derection = "right"
                if event.key==K_LEFT or event.key==ord('a'):
                    change_derection = "left"
                if event.key==K_UP or event.key==ord('w'):
                    change_derection = "up"
                if event.key==K_DOWN or event.key==ord('s'):
                    change_derection = "down"
                if event.key==K_ESCAPE:
                    pygame.event.post(pygame.event.Event(QUIT))
        #判断移动的方向是否相反
        if change_derection =='left'and not derection =='right':
            derection = change_derection
        if change_derection =='right'and not derection =='left':
            derection = change_derection
        if change_derection == 'up' and not derection =='down':
            derection = change_derection
        if change_derection == 'down' and not derection == 'up':
            derection = change_derection
        #根据方向,改变坐标
        if derection == 'left':
            snakeposition[0] -= 20
        if derection == 'right':
            snakeposition[0] += 20
        if derection == 'up':
            snakeposition[1] -= 20
        if derection == 'down':
            snakeposition[1] += 20
        #增加蛇的长度
        snakelength.insert(0,list(snakeposition))
        #判断是否吃掉目标方块
        if snakeposition[0]==square_purpose[0] and snakeposition[1]==square_purpose[1]:
            square_position = 0
        else:
            snakelength.pop()
        #重新生成目标方块
        if square_position ==0:
            #随机生成x,y,扩大二十倍,在窗口范围内
            x = random.randrange(1,32)
            y = random.randrange(1,24)
            square_purpose = [int(x*20),int(y*20)]
            square_position = 1
        #绘制pygame显示层
        gamesurface.fill(black_colour)
        for position in snakelength:
            pygame.draw.rect(gamesurface,white_colour,Rect(position[0],position[1],20,20))
            pygame.draw.rect(gamesurface,red_colour,Rect(square_purpose[0],square_purpose[1],20,20))
        #刷新pygame显示层
        pygame.display.flip()
        #判断是否死亡
        if snakeposition[0]<0 or snakeposition[0]>620:
            GameOver(gamesurface)
        if snakeposition[1]<0 or snakeposition[1]>460:
            GameOver(gamesurface)
        for snakebody in snakelength[1:]:
            if snakeposition[0]==snakebody[0] and snakeposition[1]==snakebody[1]:
                GameOver(gamesurface)
        #控制游戏速度
        ftpsClock.tick(5)

if __name__ == "__main__":
    main()








 

 

 

  • 32
    点赞
  • 191
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
下面是一个简单的 Python 贪吃蛇游戏代码: ```python import pygame import random # 定义颜色 BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # 设置屏幕宽高 SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 # 设置蛇的大小和速度 SNAKE_BLOCK_SIZE = 10 SNAKE_SPEED = 15 # 初始化 pygame pygame.init() # 创建屏幕 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("贪吃蛇") # 定义字体 font = pygame.font.SysFont(None, 25) # 定义蛇的函数 def snake(block_size, snake_list): for x in snake_list: pygame.draw.rect(screen, GREEN, [x[0], x[1], block_size, block_size]) # 定义消息显示函数 def message(msg, color): text = font.render(msg, True, color) screen.blit(text, [SCREEN_WIDTH / 6, SCREEN_HEIGHT / 3]) # 游戏循环 def gameLoop(): gameExit = False gameOver = False # 定义蛇的初始位置 lead_x = SCREEN_WIDTH / 2 lead_y = SCREEN_HEIGHT / 2 # 定义蛇的移动方向 lead_x_change = 0 lead_y_change = 0 # 定义蛇身体的初始位置 snake_List = [] Length_of_snake = 1 # 定义食物的位置 foodx = round(random.randrange(0, SCREEN_WIDTH - SNAKE_BLOCK_SIZE) / 10.0) * 10.0 foody = round(random.randrange(0, SCREEN_HEIGHT - SNAKE_BLOCK_SIZE) / 10.0) * 10.0 while not gameExit: while gameOver == True: screen.fill(WHITE) message("Game Over, press Q to quit or C to continue", RED) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: gameExit = True gameOver = False if event.key == pygame.K_c: gameLoop() # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: lead_x_change = -SNAKE_BLOCK_SIZE lead_y_change = 0 elif event.key == pygame.K_RIGHT: lead_x_change = SNAKE_BLOCK_SIZE lead_y_change = 0 elif event.key == pygame.K_UP: lead_y_change = -SNAKE_BLOCK_SIZE lead_x_change = 0 elif event.key == pygame.K_DOWN: lead_y_change = SNAKE_BLOCK_SIZE lead_x_change = 0 # 判断是否撞墙 if lead_x >= SCREEN_WIDTH or lead_x < 0 or lead_y >= SCREEN_HEIGHT or lead_y < 0: gameOver = True # 移动蛇 lead_x += lead_x_change lead_y += lead_y_change # 画出食物 pygame.draw.rect(screen, RED, [foodx, foody, SNAKE_BLOCK_SIZE, SNAKE_BLOCK_SIZE]) # 画出蛇 snake_Head = [] snake_Head.append(lead_x) snake_Head.append(lead_y) snake_List.append(snake_Head) if len(snake_List) > Length_of_snake: del snake_List[0] for eachSegment in snake_List[:-1]: if eachSegment == snake_Head: gameOver = True snake(SNAKE_BLOCK_SIZE, snake_List) pygame.display.update() # 判断是否吃到食物 if lead_x == foodx and lead_y == foody: foodx = round(random.randrange(0, SCREEN_WIDTH - SNAKE_BLOCK_SIZE) / 10.0) * 10.0 foody = round(random.randrange(0, SCREEN_HEIGHT - SNAKE_BLOCK_SIZE) / 10.0) * 10.0 Length_of_snake += 1 # 设置游戏帧率 clock = pygame.time.Clock() clock.tick(SNAKE_SPEED) # 退出 pygame pygame.quit() quit() # 开始游戏 gameLoop() ``` 这段代码使用了 Pygame 模块,需要先安装。安装方式可以使用 pip: ``` pip install pygame ``` 代码中的注释会帮助你理解它的结构和用法。可以试着运行代码,体验一下贪吃蛇游戏的乐趣。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值