您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch |

自学教程:Python贪吃蛇小游戏实例分享

51自学网 2021-10-30 22:13:52
  python
这篇教程Python贪吃蛇小游戏实例分享写得很实用,希望能帮到您。

本文实例为大家分享了Python实现贪吃蛇小游戏的具体代码,供大家参考,具体内容如下

使用的库

pygame 、random 、pyautogui

流程简述

1.设置初始参数

设置每个网格大小为 20 px ,size可以随意修改但最好为20的倍数,设置初始方向向右,初始蛇长为 3 。

# 初始化参数size = 320screen = pygame.display.set_mode([size,size],0 , 32)pygame.display.set_caption("贪吃蛇")cell_size = 20cell_num = int(size/20)x , y = [60,0]# 初始方向向右dir_snake = 'R'body_snake = [[0,0],[20,0],[40,0],[60,0]]# 初始蛇长为3len_snake = 3# 初始食物坐标food_coor = [random.randint(0, cell_num - 1) * 20, random.randint(0, cell_num - 1) * 20, 20, 20]# 蛇移动速度clock = pygame.time.Clock()

2.键盘控制

键盘上下左右控制蛇方向,禁止反向。

3.食物

蛇头吃到食物后,蛇长加一 ,random 一个随机坐标,如果坐标再蛇身上则继续 random。

if [x,y] == food_coor[:2]:    food_coor = [random.randint(0, cell_num - 1) * 20, random.randint(0, cell_num - 1) * 20, 20, 20]    if food_coor[:2] in body_snake[-2:-len_snake -1 :-1]:        food_coor = [random.randint(0, cell_num - 1) * 20, random.randint(0, cell_num - 1) * 20, 20, 20]    len_snake +=1

4. 胜负判断

蛇头与蛇身碰撞判输,弹出游戏结束窗口,说明最终蛇长为多长。

if body_snake[-1] in body_snake[-2:-len_snake -1 :-1]:    pyautogui.alert(text='游戏结束,最终蛇长为{}'.format(len_snake))    exit()

代码及结果

代码

import pygame , random ,pyautoguifrom pygame.locals import *# 初始化参数size = 500screen = pygame.display.set_mode([size,size],0 , 32)pygame.display.set_caption("贪吃蛇")cell_size = 20cell_num = int(size/20)x , y = [60,0]# 初始方向向右dir_snake = 'R'body_snake = [[0,0],[20,0],[40,0],[60,0]]# 初始蛇长为3len_snake = 3# 初始食物坐标food_coor = [random.randint(0, cell_num - 1) * 20, random.randint(0, cell_num - 1) * 20, 20, 20]# 蛇移动速度clock = pygame.time.Clock()# bgdef bg():    for i in range(0, size , int(cell_size)):        pygame.draw.line(screen,[72,72,72],[i,0],[i,size])    for i in range(0, size, int(cell_size)):        pygame.draw.line(screen, [72, 72, 72], [0, i], [size,i])# 蛇def snake(K):    for x,y in K[:-len_snake - 1:-1]:        pygame.draw.rect(screen,[255,255,255],[x,y,20,20],0)# 食物def food():    pygame.draw.rect(screen,[255,0,0],food_coor,0)# 主循环def running():    global x ,y , dir_snake ,food_coor , len_snake    while True:        for event in pygame.event.get():            if event.type == QUIT:                exit()        screen.fill((40, 43, 46))        # 方向规则        if dir_snake == 'U':            y -= 20        elif dir_snake == 'R':            x += 20        elif dir_snake == 'D':            y += 20        elif dir_snake == 'L':            x -= 20        # 键盘方向控制        if event.type == KEYDOWN:            if event.key == K_LEFT and dir_snake != 'R':                dir_snake = 'L'            elif event.key == K_DOWN and dir_snake != 'U':                dir_snake = 'D'            elif event.key == K_RIGHT and dir_snake != 'L':                dir_snake = 'R'            elif event.key == K_UP and dir_snake != 'D':                dir_snake = 'U'        # 撞墙之后        if x < 0:            x += size        elif x >= size:            x -= size        elif y < 0:            y += size        elif y >= size:            y -= size        # draw蛇体        body_snake.append([x,y])        snake(body_snake)        food()        # 吃到食物后food换位置        if [x,y] == food_coor[:2]:            food_coor = [random.randint(0, cell_num - 1) * 20, random.randint(0, cell_num - 1) * 20, 20, 20]            if food_coor[:2] in body_snake[-2:-len_snake -1 :-1]:                food_coor = [random.randint(0, cell_num - 1) * 20, random.randint(0, cell_num - 1) * 20, 20, 20]            len_snake +=1        # 游戏结束        if body_snake[-1] in body_snake[-2:-len_snake -1 :-1]:            pyautogui.alert(text='游戏结束,最终蛇长为{}'.format(len_snake))            exit()        # 格线        bg()        # 右下角显示蛇长        font = pygame.font.SysFont("simsunnsimsun", 40)        text_surface = font.render("{}".format(len_snake), True, (255,255, 255))        screen.blit(text_surface , (size-40,size-40))        pygame.display.update()        # 蛇的移动速度随着蛇的长度而越来越快        clock.tick(len_snake * 2)if __name__ == '__main__':    pygame.init()    running()

输出结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持51zixue.net。


python入门课程第一讲之安装与优缺点介绍
Python爬虫分析汇总
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1