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 相关文章推荐
压缩包密码破解示例分享(类似典破解)
Jan 17 Python
Python函数中定义参数的四种方式
Nov 30 Python
Python使用urllib2模块实现断点续传下载的方法
Jun 17 Python
Python的Flask框架中使用Flask-Migrate扩展迁移数据库的教程
Jun 14 Python
Python读取指定目录下指定后缀文件并保存为docx
Apr 23 Python
Python原始字符串与Unicode字符串操作符用法实例分析
Jul 22 Python
Ubuntu下使用python读取doc和docx文档的内容方法
May 08 Python
对Python生成汉字字库文字,以及转换为文字图片的实例详解
Jan 29 Python
python shutil文件操作工具使用实例分析
Dec 25 Python
Python sep参数使用方法详解
Feb 12 Python
Python使用QQ邮箱发送邮件实例与QQ邮箱设置详解
Feb 18 Python
Python关于__name__属性的含义和作用详解
Feb 19 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
PHP4与PHP3中一个不兼容问题的解决方法
2006/10/09 PHP
linux命令之调试工具strace的深入分析
2013/06/03 PHP
PHP判断远程图片或文件是否存在的实现代码
2014/02/20 PHP
PHP+Javascript实现在线拍照功能实例
2015/07/18 PHP
详解PHP对数组的定义以及数组的创建方法
2015/11/27 PHP
js同时按下两个方向键
2007/12/01 Javascript
JQuery实现级联下拉框效果实例讲解
2015/09/17 Javascript
jQuery实现下拉框功能实例代码
2016/05/06 Javascript
javascript十六进制数字和ASCII字符之间的转换方法
2016/12/27 Javascript
jQuery插件HighCharts绘制的2D堆柱状图效果示例【附demo源码下载】
2017/03/14 Javascript
JS设计模式之单例模式(一)
2017/09/29 Javascript
webpack开发环境和生产环境的深入理解
2018/11/08 Javascript
vue新建项目并配置标准路由过程解析
2019/12/09 Javascript
jquery实现进度条状态展示
2020/03/26 jQuery
python实现在目录中查找指定文件的方法
2014/11/11 Python
Python中使用select模块实现非阻塞的IO
2015/02/03 Python
用python脚本24小时刷浏览器的访问量方法
2018/12/07 Python
Python判断变量名是否合法的方法示例
2019/01/28 Python
mac系统下Redis安装和使用步骤详解
2019/07/09 Python
Apache部署Django项目图文详解
2019/07/30 Python
在django-xadmin中APScheduler的启动初始化实例
2019/11/15 Python
python计算导数并绘图的实例
2020/02/29 Python
Python如何合并多个字典或映射
2020/07/24 Python
Python操作dict时避免出现KeyError的几种解决方法
2020/09/20 Python
CSS3弹性伸缩布局之box布局
2016/07/12 HTML / CSS
CSS3 @media的基本用法总结
2019/09/10 HTML / CSS
C#中的验证控件有几种
2014/03/08 面试题
远程教育心得体会
2014/01/03 职场文书
会计专业导师推荐信
2014/03/08 职场文书
幼儿园中班上学期评语
2014/04/18 职场文书
大学学风建设方案
2014/05/04 职场文书
我与祖国共奋进演讲稿
2014/09/13 职场文书
营销与策划实训报告
2014/11/05 职场文书
雷锋观后感
2015/06/10 职场文书
学雷锋广播稿大全
2015/08/19 职场文书
三严三实学习心得体会(精选N篇)
2016/01/05 职场文书