作者 | 周萝卜

来源 | 萝卜大杂烩

相信我们大家都玩过贪吃蛇游戏,今天我们就从头一起来写一个贪吃蛇小游戏,只需要100多行的代码就完成了。

用到的 Pygame 函数

贪吃蛇小游戏用到的函数

功能 描述
init() 初始化 pygame
display.set_mode() 以元组或列表为参数创建窗口
update() 更新屏幕
quit() 用于取消初始化的 pygame
set_caption() 在屏幕的顶部设置文字
event.get() 返回所有事件的列表
Surface.fill() 使用纯色填充屏幕
time.Clock() 追踪时间
font.Font() 设置字体

创建屏幕

我们使用函数 display.set_mode() 来创建 pygame 窗口,同时我们还要在程序的开始和结尾处进行 init()quit() 函数,以保证程序可以正确开始和结束。

import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))
pygame.display.update()
pygame.quit()
quit()

这要我们运行程序,就可以得到如下:

但是这要的代码,我们的程序创建只会一闪而过,下面我们增加一些代码,来保持住程序窗口

import pygame
pygame.init()
dis=pygame.display.set_mode((400,300))
pygame.display.update()
pygame.display.set_caption('Snake game by Edureka')
game_over=False
while not game_over:for event in pygame.event.get():print(event)   # 打印出所有事件pygame.quit()
quit()

我们增加了游戏窗口的名称,同时还可以在 Python 控制台中看到我们在 pygame 窗口上操作时的所有事件

下面我们来增加关闭响应事件

pygame.init()
dis = pygame.display.set_mode((400, 300))
pygame.display.update()
pygame.display.set_caption('贪吃蛇')
game_over = False
while not game_over:for event in pygame.event.get():if event.type==pygame.QUIT:game_over=Truepygame.quit()
quit()

至此我们的游戏窗口就设置好了,下面就可以来画 snake 了

创建 snake

我们首先创建一些颜色变量,用来表示 snake,food,screen 等

pygame.init()
dis = pygame.display.set_mode((400, 300))
pygame.display.update()
pygame.display.set_caption('贪吃蛇')blue=(0,0,255)
red=(255,0,0)game_over = False
while not game_over:for event in pygame.event.get():if event.type==pygame.QUIT:game_over=Truepygame.draw.rect(dis, blue, [200, 150, 10, 10])pygame.display.update()pygame.quit()
quit()

这样,一只(条)贪吃蛇就创建完成了,就是那个小蓝点儿

使 snake 动起来

为了实现 snake 的移动,我们需要用到的关键事件是 KEYDOWN,它包含四个 key 值,K_UP, K_DOWN, K_LEFT, 和 K_RIGHT,分别表示向上、向下、向左和向右

pygame.init()
pygame.display.set_caption('贪吃蛇')
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)dis = pygame.display.set_mode((800, 600))game_over = Falsex1 = 300
y1 = 300x1_change = 0
y1_change = 0clock = pygame.time.Clock()while not game_over:for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -10y1_change = 0elif event.key == pygame.K_RIGHT:x1_change = 10y1_change = 0elif event.key == pygame.K_UP:y1_change = -10x1_change = 0elif event.key == pygame.K_DOWN:y1_change = 10x1_change = 0x1 += x1_changey1 += y1_changedis.fill(white)pygame.draw.rect(dis, black, [x1, y1, 10, 10])pygame.display.update()clock.tick(30)pygame.quit()
quit()

我这里创建了 x1_changey1_change 变量来更新 x 和 y 坐标,使得我们的 snake 可以移动起来

处理 Game Over

对于贪吃蛇游戏来说,如果 snake 移动出了游戏屏幕,那么游戏就已经失败了,下面我们就来处理这部分逻辑

import pygame
import timepygame.init()
pygame.display.set_caption('贪吃蛇')
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)dis_width = 600
dis_height = 400
dis = pygame.display.set_mode((dis_width, dis_width))game_over = Falsex1 = dis_width / 2
y1 = dis_height / 2snake_block = 10x1_change = 0
y1_change = 0clock = pygame.time.Clock()
snake_speed = 30font_style = pygame.font.Font("C:/Windows/Fonts/STFANGSO.TTF", 20)def message(msg, color):mesg = font_style.render(msg, True, color)dis.blit(mesg, [dis_width / 2, dis_height / 2])while not game_over:for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -snake_blocky1_change = 0elif event.key == pygame.K_RIGHT:x1_change = snake_blocky1_change = 0elif event.key == pygame.K_UP:y1_change = -snake_blockx1_change = 0elif event.key == pygame.K_DOWN:y1_change = snake_blockx1_change = 0if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:game_over = Truex1 += x1_changey1 += y1_changedis.fill(white)pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])pygame.display.update()clock.tick(snake_speed)message("你失败了,请重新开始游戏!", red)
pygame.display.update()
time.sleep(2)pygame.quit()
quit()

增加食物

既然是贪吃蛇,当然要投食了,下面我们就来处理食物

import pygame
import time
import randompygame.init()
pygame.display.set_caption('贪吃蛇')white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)dis_width = 800
dis_height = 600dis = pygame.display.set_mode((dis_width, dis_height))clock = pygame.time.Clock()snake_block = 10
snake_speed = 30font_style = pygame.font.Font("C:/Windows/Fonts/STFANGSO.TTF", 20)def message(msg, color):mesg = font_style.render(msg, True, color)dis.blit(mesg, [dis_width / 3, dis_height / 3])def gameLoop():  # creating a functiongame_over = Falsegame_close = Falsex1 = dis_width / 2y1 = dis_height / 2x1_change = 0y1_change = 0foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0while not game_over:while game_close == True:dis.fill(white)message("你失败了,请重新开始游戏!", red)pygame.display.update()for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseif event.key == pygame.K_c:gameLoop()for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -snake_blocky1_change = 0elif event.key == pygame.K_RIGHT:x1_change = snake_blocky1_change = 0elif event.key == pygame.K_UP:y1_change = -snake_blockx1_change = 0elif event.key == pygame.K_DOWN:y1_change = snake_blockx1_change = 0if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:game_close = Truex1 += x1_changey1 += y1_changedis.fill(white)pygame.draw.rect(dis, blue, [foodx, foody, snake_block, snake_block])pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])pygame.display.update()if x1 == foodx and y1 == foody:print("Good!")clock.tick(snake_speed)pygame.quit()quit()gameLoop()

我这里创建了一个函数 gameLoop 作为我们的主函数,同时还初始化了 snake 的食物,还同时增加了键盘 cq 关键字,来重新开始游戏和退出游戏

snake 的成长

下面我们就开始在 snake 吃掉食物之后,增加 snake 的长度,这也是游戏的基本规则

import pygame
import time
import randompygame.init()
pygame.display.set_caption('贪吃蛇')
font_style = pygame.font.Font("C:/Windows/Fonts/STFANGSO.TTF", 20)
score_font = pygame.font.Font("C:/Windows/Fonts/STCAIYUN.TTF", 30)white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)dis_width = 600
dis_height = 400dis = pygame.display.set_mode((dis_width, dis_height))clock = pygame.time.Clock()snake_block = 10
snake_speed = 15def our_snake(snake_block, snake_list):for x in snake_list:pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])def message(msg, color):mesg = font_style.render(msg, True, color)dis.blit(mesg, [dis_width / 6, dis_height / 3])def gameLoop():game_over = Falsegame_close = Falsex1 = dis_width / 2y1 = dis_height / 2x1_change = 0y1_change = 0snake_List = []Length_of_snake = 1foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0while not game_over:while game_close == True:dis.fill(blue)message("你失败了,请重新开始游戏!", red)pygame.display.update()for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseif event.key == pygame.K_c:gameLoop()for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -snake_blocky1_change = 0elif event.key == pygame.K_RIGHT:x1_change = snake_blocky1_change = 0elif event.key == pygame.K_UP:y1_change = -snake_blockx1_change = 0elif event.key == pygame.K_DOWN:y1_change = snake_blockx1_change = 0if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:game_close = Truex1 += x1_changey1 += y1_changedis.fill(blue)pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])snake_Head = []snake_Head.append(x1)snake_Head.append(y1)snake_List.append(snake_Head)if len(snake_List) > Length_of_snake:del snake_List[0]for x in snake_List[:-1]:if x == snake_Head:game_close = Trueour_snake(snake_block, snake_List)pygame.display.update()if x1 == foodx and y1 == foody:foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0Length_of_snake += 1clock.tick(snake_speed)pygame.quit()quit()gameLoop()

展示得分

最后我们来显示得分,毕竟对于游戏来说,玩家的得分还是很重要的

import pygame
import time
import randompygame.init()
pygame.display.set_caption('贪吃蛇')
font_style = pygame.font.Font("C:/Windows/Fonts/STFANGSO.TTF", 20)
score_font = pygame.font.Font("C:/Windows/Fonts/STCAIYUN.TTF", 30)white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)dis_width = 600
dis_height = 400dis = pygame.display.set_mode((dis_width, dis_height))clock = pygame.time.Clock()snake_block = 10
snake_speed = 15def Your_score(score):value = score_font.render("Your Score: " + str(score), True, yellow)dis.blit(value, [0, 0])def our_snake(snake_block, snake_list):for x in snake_list:pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])def message(msg, color):mesg = font_style.render(msg, True, color)dis.blit(mesg, [dis_width / 6, dis_height / 3])def gameLoop():game_over = Falsegame_close = Falsex1 = dis_width / 2y1 = dis_height / 2x1_change = 0y1_change = 0snake_List = []Length_of_snake = 1foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0while not game_over:while game_close == True:dis.fill(blue)message("你失败了,请重新开始游戏!", red)Your_score(Length_of_snake - 1)pygame.display.update()for event in pygame.event.get():if event.type == pygame.KEYDOWN:if event.key == pygame.K_q:game_over = Truegame_close = Falseif event.key == pygame.K_c:gameLoop()for event in pygame.event.get():if event.type == pygame.QUIT:game_over = Trueif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:x1_change = -snake_blocky1_change = 0elif event.key == pygame.K_RIGHT:x1_change = snake_blocky1_change = 0elif event.key == pygame.K_UP:y1_change = -snake_blockx1_change = 0elif event.key == pygame.K_DOWN:y1_change = snake_blockx1_change = 0if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:game_close = Truex1 += x1_changey1 += y1_changedis.fill(blue)pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])snake_Head = []snake_Head.append(x1)snake_Head.append(y1)snake_List.append(snake_Head)if len(snake_List) > Length_of_snake:del snake_List[0]for x in snake_List[:-1]:if x == snake_Head:game_close = Trueour_snake(snake_block, snake_List)Your_score(Length_of_snake - 1)pygame.display.update()if x1 == foodx and y1 == foody:foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0Length_of_snake += 1clock.tick(snake_speed)pygame.quit()quit()gameLoop()

这里创建了一个 Your_score 函数来记录玩家得分

这样,我们就完成了一个简易的贪吃蛇小游戏了

最后的最后,我们再给游戏添加音乐背景,让游戏的时光更加惬意吧

# 播放音乐
pygame.init()
pygame.mixer.music.load(r"Game.mp3")
pygame.mixer.music.play()

资讯

AI天气预测准确度高于气象台

资讯

AI 生成的代码可信吗?

资讯

机器人越像人越好?

资讯

机器人能帮助缝制T恤吗?

分享

点收藏

点点赞

点在看

100行代码,使用 Pygame 制作一个贪吃蛇小游戏!相关推荐

  1. python的pygame库使用方法_python基础教程使用Python第三方库pygame写个贪吃蛇小游戏...

    今天看到几个关于pygame模块的博客和视频,感觉非常有趣,这里照猫画虎写了一个贪吃蛇小游戏,目前还有待完善,但是基本游戏功能已经实现,下面是代码: # 导入模块 import pygame impo ...

  2. Easyx图形库+C++做一个贪吃蛇小游戏 数据结构课程设计

    Easyx图形库+C++做一个贪吃蛇小游戏 数据结构课程设计 程序界面 ① 游戏开始界面(如下图): 显示游戏标题,提供"开始游戏"."游戏模式"和" ...

  3. 用 typescript 做一个贪吃蛇小游戏

    typescript 做一个贪吃蛇小游戏 搭建环境 创建 tscofig.json 文件 配置如下 {"compilerOptions": {"target": ...

  4. python小游戏编程实例-10分钟教你用Python写一个贪吃蛇小游戏,适合练手项目

    另外要注意:光理论是不够的.这里顺便总大家一套2020最新python入门到高级项目实战视频教程,可以去小编的Python交流.裙 :七衣衣九七七巴而五(数字的谐音)转换下可以找到了,还可以跟老司机交 ...

  5. 教你用十分钟编写一个贪吃蛇小游戏

    贪吃蛇,大家应该都玩过.当初第一次接触贪吃蛇的时候 ,还是能砸核桃的诺基亚上,当时玩的不亦乐乎.今天,我们用Python编程一个贪吃蛇游戏,下面我们先看看效果: 好了,先介绍一个思路 所有的游戏最主要 ...

  6. 10分钟用Python编写一个贪吃蛇小游戏

    贪吃蛇,大家应该都玩过.当初第一次接触贪吃蛇的时候 ,还是能砸核桃的诺基亚上,当时玩的不亦乐乎.今天,我们用Python编程一个贪吃蛇游戏,下面我们先看看效果: 好了,先介绍一个思路 所有的游戏最主要 ...

  7. python编程小游戏-10分钟用Python编写一个贪吃蛇小游戏,简单

    贪吃蛇,大家应该都玩过.小编当初第一次接触贪吃蛇的时候 ,还是能砸核桃的诺基亚上,当时玩的不亦乐乎.今天,我们用Python编程一个贪吃蛇游戏,下面我们先看看效果: 好了,先介绍一个思路 所有的游戏最 ...

  8. 10分钟用python编写贪吃蛇小游戏_牛得一批!10分钟用Python编写一个贪吃蛇小游戏...

    贪吃蛇,大家应该都玩过.当初第一次接触贪吃蛇的时候 ,还是能砸核桃的诺基亚上,当时玩的不亦乐乎.今天,我们用Python编程一个贪吃蛇游戏,下面我们先看看效果: 好了,先介绍一个思路 所有的游戏最主要 ...

  9. 10分钟python游戏_牛得一批!10分钟用Python编写一个贪吃蛇小游戏

    贪吃蛇,大家应该都玩过.当初第一次接触贪吃蛇的时候 ,还是能砸核桃的诺基亚上,当时玩的不亦乐乎.今天,我们用Python编程一个贪吃蛇游戏,下面我们先看看效果: 好了,先介绍一个思路 所有的游戏最主要 ...

最新文章

  1. yolov5检测完不显示框和标注
  2. [react] 有在项目中使用过Antd吗?说说它的好处
  3. 进一步理解VC中的句柄
  4. 第08课:GDB 实用调试技巧( 上)
  5. java 数据库题,JAVA数据库笔试习题(答案在最后
  6. 关于使用keil5软件进行stm32的简单嵌入编程
  7. php 单词替换,单词替换 - Shiyin's note
  8. 三种局域网扫描工具比较
  9. 第三方支付(服务商模式)
  10. 录屏鼠标光标圆圈如何实现_录屏鼠标光标圆圈如何实现
  11. 如何快速的开通公众号【原创】功能
  12. Python 数据科学入门教程:Matplotlib
  13. python汇率兑换双向_汇率兑换—python第一课
  14. matlab绘制动态图,Matlab绘制动态图的两种方式(参考)
  15. Redis与传统sql数据库的区别
  16. MPLAB 创建新项目
  17. 笔记本连接不上外接显示器_如何将多个外接显示器连接到笔记本电脑
  18. “梅西”式核心员工,正在摧毁你的团队
  19. HBase(一):概述
  20. explorer被微信企业版劫持一例

热门文章

  1. 女生做软件测试需要学习什么技术?
  2. linux下字符串处理工具二:awk(1)
  3. Servlet防止页面被客户端缓存
  4. Chameleon跨端框架——壹个理想主义团队的开源作品
  5. CSS布局之-水平垂直居中
  6. 互联网引发全面深刻产业变革
  7. Python fabric实现远程操作和部署
  8. 3、JPA一些常用的注解
  9. cheat engine lua
  10. [PHPUnit]自动生成PHPUnit测试骨架脚本-提供您的开发效率【2015升级版】