200行python代码实现贪吃蛇游戏


Posted in Python onApril 24, 2020

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

这次我们来写一个贪吃蛇游戏

下面贴出具体代码

import pygame
import time
import numpy as np
# 此模块包含游戏所需的常量
from pygame.locals import *

# 设置棋盘的长宽
BOARDWIDTH = 48
BOARDHEIGHT = 28
# 分数
score = 0



class Food(object):
 def __init__(self):
 self.item = (4, 5)

 # 画出食物
 def _draw(self, screen, i, j):
 color = 255, 0, 255
 radius = 10
 width = 10
 # i:1---34 j:1---25
 position = 10 + 20 * i, 10 + 20 * j
 # 画出半径为 10 的粉色实心圆
 pygame.draw.circle(screen, color, position, radius, width)

 # 随机产生食物
 def update(self, screen, enlarge, snack):
 if enlarge:
  self.item = np.random.randint(1, BOARDWIDTH - 2), np.random.randint(1, BOARDHEIGHT - 2)
  while self.item in snack.item:
  self.item = np.random.randint(1, BOARDWIDTH - 2), np.random.randint(1, BOARDHEIGHT - 2)
 self._draw(screen, self.item[0], self.item[1])


# 贪吃蛇
class Snack(object):
 def __init__(self):
 # self.item = [(3, 25), (2, 25), (1, 25), (1,24), (1,23),
 # (1,22), (1,21), (1,20), (1,19), (1,18), (1,17), (1,16)]
 # x 水平方向 y 竖直方向
 # 初始方向竖直向上
 self.item = [(3, 25), (2, 25), (1, 25), (1, 24), ]
 self.x = 0
 self.y = -1

 def move(self, enlarge):
 # enlarge 标记贪吃蛇有没有吃到食物
 if not enlarge:
  # 吃到食物删除尾部元素
  self.item.pop()
 # 新蛇头的坐标为旧蛇头坐标加上移动方向的位移
 head = (self.item[0][0] + self.x, self.item[0][1] + self.y)
 # 将新的蛇头坐标插入在 list 最前面
 self.item.insert(0, head)

 def eat_food(self, food):
 global score
 # snack_x,snack_y 蛇头坐标
 # food_x, food_y 食物坐标
 snack_x, snack_y = self.item[0]
 food_x, food_y = food.item
 # 比较蛇头坐标与食物坐标
 if (food_x == snack_x) and (food_y == snack_y):
  score += 100
  return 1
 else:
  return 0

 def toward(self, x, y):
 # 改变蛇头朝向
 if self.x * x >= 0 and self.y * y >= 0:
  self.x = x
  self.y = y

 def get_head(self):
 # 获取蛇头坐标
 return self.item[0]

 def draw(self, screen):
 # 画出贪吃蛇
 # 蛇头为半径为 15 的红色实心圆
 radius = 15
 width = 15
 # i:1---34 j:1---25
 color = 255, 0, 0
 # position 为图形的坐标
 position = 10 + 20 * self.item[0][0], 10 + 20 * self.item[0][1]
 pygame.draw.circle(screen, color, position, radius, width)
 # 蛇身为半径为 10 的黄色实心圆
 radius = 10
 width = 10
 color = 255, 255, 0
 for i, j in self.item[1:]:
  position = 10 + 20 * i, 10 + 20 * j
  pygame.draw.circle(screen, color, position, radius, width)


# 初始界面
def init_board(screen):
 board_width = BOARDWIDTH
 board_height = BOARDHEIGHT
 color = 10, 255, 255
 width = 0
 # width:x, height:y
 # 左右边框占用了 X: 0 35*20
 for i in range(board_width):
 pos = i * 20, 0, 20, 20
 pygame.draw.rect(screen, color, pos, width)
 pos = i * 20, (board_height - 1) * 20, 20, 20
 pygame.draw.rect(screen, color, pos, width)
 # 上下边框占用了 Y: 0 26*20
 for i in range(board_height - 1):
 pos = 0, 20 + i * 20, 20, 20
 pygame.draw.rect(screen, color, pos, width)
 pos = (board_width - 1) * 20, 20 + i * 20, 20, 20
 pygame.draw.rect(screen, color, pos, width)


# 游戏失败
def game_over(snack):
 broad_x, broad_y = snack.get_head()
 flag = 0
 old = len(snack.item)
 new = len(set(snack.item))
 # 游戏失败的两种可能
 # 咬到自身
 if new < old:
 flag = 1
 # 撞到边框
 if broad_x == 0 or broad_x == BOARDWIDTH - 1:
 flag = 1
 if broad_y == 0 or broad_y == BOARDHEIGHT - 1:
 flag = 1

 if flag:
 return True
 else:
 return False


# 打印字符
def print_text(screen, font, x, y, text, color=(255, 0, 0)):
 # 在屏幕上打印字符
 # text是需要打印的文本,color为字体颜色
 # (x,y)是文本在屏幕上的位置
 imgText = font.render(text, True, color)
 screen.blit(imgText, (x, y))


# 按键
def press(keys, snack):
 global score
 # K_w 为 pygame.locals 中的常量
 # keys[K_w] 返回 True or False
 # 上移
 if keys[K_w] or keys[K_UP]:
 snack.toward(0, -1)
 # 下移
 elif keys[K_s] or keys[K_DOWN]:
 snack.toward(0, 1)
 # 左移
 elif keys[K_a] or keys[K_LEFT]:
 snack.toward(-1, 0)
 # 右移
 elif keys[K_d] or keys[K_RIGHT]:
 snack.toward(1, 0)
 # 重置游戏
 elif keys[K_r]:
 score = 0
 main()
 # 退出游戏
 elif keys[K_ESCAPE]:
 exit()


# 游戏初始化
def game_init():
 # pygame 初始化
 pygame.init()
 # 设置游戏界面大小
 screen = pygame.display.set_mode((BOARDWIDTH * 20, BOARDHEIGHT * 20))
 # 设置游戏标题
 pygame.display.set_caption('贪吃蛇游戏')
 # sound = pygame.mixer.Sound(AUDIONAME)
 # channel = pygame.mixer.find_channel(True)
 # channel.play(sound)
 return screen


# 开始游戏
def game(screen):
 snack = Snack()
 food = Food()
 # 设置中文字体和大小
 font = pygame.font.SysFont('SimHei', 20)
 is_fail = 0
 while True:
 for event in pygame.event.get():
  if event.type == QUIT:
  exit()
 # 填充屏幕
 screen.fill((0, 0, 100))
 init_board(screen=screen)
 # 获得用户按键命令
 keys = pygame.key.get_pressed()
 press(keys, snack)
 # 游戏失败打印提示
 if is_fail:
  font2 = pygame.font.Font(None, 40)
  print_text(screen, font2, 400, 200, "GAME OVER")
 # 游戏主进程
 if not is_fail:
  enlarge = snack.eat_food(food)
  food.update(screen, enlarge, snack)
  snack.move(enlarge)
  is_fail = game_over(snack=snack)
  snack.draw(screen)
 # 游戏刷新
 pygame.display.update()
 time.sleep(0.1)


# 主程序
def main():
 screen = game_init()
 game(screen)


if __name__ == '__main__':
 main()

程序运行效果

简单截图了一下
可以按住方向键移动蛇的运动方向

200行python代码实现贪吃蛇游戏

更多有趣的经典小游戏实现专题,分享给大家:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python将DataFrame的某一列作为index的方法
Apr 08 Python
Python生成器generator用法示例
Aug 10 Python
钉钉群自定义机器人消息Python封装的实例
Feb 20 Python
python接口自动化测试之接口数据依赖的实现方法
Apr 26 Python
基于python分析你的上网行为 看看你平时上网都在干嘛
Aug 13 Python
Django配置MySQL数据库的完整步骤
Sep 07 Python
python 实现在无序数组中找到中位数方法
Mar 03 Python
简单了解Python变量作用域正确使用方法
Jun 12 Python
基于Python的自媒体小助手---登录页面的实现代码
Jun 29 Python
openCV提取图像中的矩形区域
Jul 21 Python
Python selenium环境搭建实现过程解析
Sep 08 Python
python安装及变量名介绍详解
Dec 12 Python
python Canny边缘检测算法的实现
Apr 24 #Python
python实现文字版扫雷
Apr 24 #Python
离线状态下在jupyter notebook中使用plotly实例
Apr 24 #Python
python3中sys.argv的实例用法
Apr 24 #Python
VScode连接远程服务器上的jupyter notebook的实现
Apr 23 #Python
Python实现仿射密码的思路详解
Apr 23 #Python
利用matplotlib为图片上添加触发事件进行交互
Apr 23 #Python
You might like
PHP第一季视频教程(李炎恢+php100 不断更新)
2011/05/29 PHP
谨慎使用PHP的引用原因分析
2012/09/06 PHP
PHP文件缓存类实现代码
2015/10/26 PHP
针对thinkPHP5框架存储过程bug重写的存储过程扩展类完整实例
2018/06/16 PHP
Laravel5.5 动态切换多语言的操作方式
2019/10/25 PHP
textarea中的手动换行处理的jquery代码
2011/02/26 Javascript
js数组的基本用法及数组根据下标(数值或字符)移除元素
2013/10/20 Javascript
jquery左边浮动到一定位置时显示返回顶部按钮
2014/06/05 Javascript
jQuery中:empty选择器用法实例
2014/12/30 Javascript
JS获取图片高度宽度的方法分享
2015/04/17 Javascript
c#程序员对TypeScript的认识过程
2015/06/19 Javascript
jQuery实现可展开合拢的手风琴面板菜单
2015/09/15 Javascript
jquery获取select选中值的方法分析
2015/12/22 Javascript
jquery+css3实现会动的小圆圈效果
2016/01/27 Javascript
JS封装通过className获取元素的函数示例
2016/12/20 Javascript
Bootstrap表单控件学习使用
2017/03/07 Javascript
javascript基本常用排序算法解析
2017/09/27 Javascript
详解.vue文件解析的实现
2018/06/11 Javascript
如何把vuejs打包出来的文件整合到springboot里
2018/07/26 Javascript
koa+mongoose实现简单增删改查接口的示例代码
2019/05/13 Javascript
Vue-Cli 3.0 中配置高德地图的两种方式
2019/06/19 Javascript
在Vue环境下利用worker运行interval计时器的步骤
2019/08/01 Javascript
JS页面获取 session 值,作用域和闭包学习笔记
2019/10/16 Javascript
js单线程的本质 Event Loop解析
2019/10/29 Javascript
Python中的闭包总结
2014/09/18 Python
Python处理文本文件中控制字符的方法
2017/02/07 Python
详解python Todo清单实战
2018/11/01 Python
Python数据可视化之画图
2019/01/15 Python
Python中的元组介绍
2019/01/28 Python
基于Python的Post请求数据爬取的方法详解
2019/06/14 Python
pyQt5实时刷新界面的示例
2019/06/25 Python
迪士尼西班牙官方网上商店:ShopDisney西班牙
2020/02/02 全球购物
公司董事长职责
2013/12/12 职场文书
应聘面试自我评价
2014/01/24 职场文书
党的群众路线教育实践活动心得体会(教师)
2014/10/31 职场文书
少年的你:世界上没有如果,要在第一次就勇敢的反抗
2019/11/20 职场文书