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


Posted in Python onApril 24, 2020

上篇博文我们实现了两百行代码实现贪吃蛇游戏,这次我们来实现一个代码量更加少,功能却更加完整的

python代码实现贪吃蛇游戏,具体代码与文件可以访问我的GitHub地址获取

游戏截图

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

动图

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

贪吃蛇python代码

"""贪吃蛇"""

import random
import sys
import time
import pygame
from pygame.locals import *
from collections import deque

SCREEN_WIDTH = 600  # 屏幕宽度
SCREEN_HEIGHT = 480  # 屏幕高度
SIZE = 20    # 小方格大小
LINE_WIDTH = 1   # 网格线宽度

# 游戏区域的坐标范围
SCOPE_X = (0, SCREEN_WIDTH // SIZE - 1)
SCOPE_Y = (2, SCREEN_HEIGHT // SIZE - 1)

# 食物的分值及颜色
FOOD_STYLE_LIST = [(10, (255, 100, 100)), (20, (100, 255, 100)), (30, (100, 100, 255))]

LIGHT = (100, 100, 100)
DARK = (200, 200, 200)  # 蛇的颜色
BLACK = (0, 0, 0)   # 网格线颜色
RED = (200, 30, 30)   # 红色,GAME OVER 的字体颜色
BGCOLOR = (40, 40, 60)  # 背景色


def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
 imgText = font.render(text, True, fcolor)
 screen.blit(imgText, (x, y))


# 初始化蛇
def init_snake():
 snake = deque()
 snake.append((2, SCOPE_Y[0]))
 snake.append((1, SCOPE_Y[0]))
 snake.append((0, SCOPE_Y[0]))
 return snake


def create_food(snake):
 food_x = random.randint(SCOPE_X[0], SCOPE_X[1])
 food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1])
 while (food_x, food_y) in snake:
  # 如果食物出现在蛇身上,则重来
  food_x = random.randint(SCOPE_X[0], SCOPE_X[1])
  food_y = random.randint(SCOPE_Y[0], SCOPE_Y[1])
 return food_x, food_y


def get_food_style():
 return FOOD_STYLE_LIST[random.randint(0, 2)]


def main():
 pygame.init()
 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
 pygame.display.set_caption('贪吃蛇')

 font1 = pygame.font.SysFont('SimHei', 24) # 得分的字体
 font2 = pygame.font.Font(None, 72) # GAME OVER 的字体
 fwidth, fheight = font2.size('GAME OVER')

 # 如果蛇正在向右移动,那么快速点击向下向左,由于程序刷新没那么快,向下事件会被向左覆盖掉,导致蛇后退,直接GAME OVER
 # b 变量就是用于防止这种情况的发生
 b = True

 # 蛇
 snake = init_snake()
 # 食物
 food = create_food(snake)
 food_style = get_food_style()
 # 方向
 pos = (1, 0)

 game_over = True
 start = False  # 是否开始,当start = True,game_over = True 时,才显示 GAME OVER
 score = 0   # 得分
 orispeed = 0.5  # 原始速度
 speed = orispeed
 last_move_time = None
 pause = False  # 暂停

 while True:
  for event in pygame.event.get():
   if event.type == QUIT:
    sys.exit()
   elif event.type == KEYDOWN:
    if event.key == K_RETURN:
     if game_over:
      start = True
      game_over = False
      b = True
      snake = init_snake()
      food = create_food(snake)
      food_style = get_food_style()
      pos = (1, 0)
      # 得分
      score = 0
      last_move_time = time.time()
    elif event.key == K_SPACE:
     if not game_over:
      pause = not pause
    elif event.key in (K_w, K_UP):
     # 这个判断是为了防止蛇向上移时按了向下键,导致直接 GAME OVER
     if b and not pos[1]:
      pos = (0, -1)
      b = False
    elif event.key in (K_s, K_DOWN):
     if b and not pos[1]:
      pos = (0, 1)
      b = False
    elif event.key in (K_a, K_LEFT):
     if b and not pos[0]:
      pos = (-1, 0)
      b = False
    elif event.key in (K_d, K_RIGHT):
     if b and not pos[0]:
      pos = (1, 0)
      b = False

  # 填充背景色
  screen.fill(BGCOLOR)
  # 画网格线 竖线
  for x in range(SIZE, SCREEN_WIDTH, SIZE):
   pygame.draw.line(screen, BLACK, (x, SCOPE_Y[0] * SIZE), (x, SCREEN_HEIGHT), LINE_WIDTH)
  # 画网格线 横线
  for y in range(SCOPE_Y[0] * SIZE, SCREEN_HEIGHT, SIZE):
   pygame.draw.line(screen, BLACK, (0, y), (SCREEN_WIDTH, y), LINE_WIDTH)

  if not game_over:
   curTime = time.time()
   if curTime - last_move_time > speed:
    if not pause:
     b = True
     last_move_time = curTime
     next_s = (snake[0][0] + pos[0], snake[0][1] + pos[1])
     if next_s == food:
      # 吃到了食物
      snake.appendleft(next_s)
      score += food_style[0]
      speed = orispeed - 0.03 * (score // 100)
      food = create_food(snake)
      food_style = get_food_style()
     else:
      if SCOPE_X[0] <= next_s[0] <= SCOPE_X[1] and SCOPE_Y[0] <= next_s[1] <= SCOPE_Y[1] \
        and next_s not in snake:
       snake.appendleft(next_s)
       snake.pop()
      else:
       game_over = True

  # 画食物
  if not game_over:
   # 避免 GAME OVER 的时候把 GAME OVER 的字给遮住了
   pygame.draw.rect(screen, food_style[1], (food[0] * SIZE, food[1] * SIZE, SIZE, SIZE), 0)

  # 画蛇
  for s in snake:
   pygame.draw.rect(screen, DARK, (s[0] * SIZE + LINE_WIDTH, s[1] * SIZE + LINE_WIDTH,
           SIZE - LINE_WIDTH * 2, SIZE - LINE_WIDTH * 2), 0)

  print_text(screen, font1, 30, 7, f'速度: {score//100}')
  print_text(screen, font1, 450, 7, f'得分: {score}')

  if game_over:
   if start:
    print_text(screen, font2, (SCREEN_WIDTH - fwidth) // 2, (SCREEN_HEIGHT - fheight) // 2, 'GAME OVER', RED)

  pygame.display.update()


if __name__ == '__main__':
 main()

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

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

Python 相关文章推荐
python生成日历实例解析
Aug 21 Python
从Python的源码来解析Python下的freeblock
May 11 Python
浅谈python多线程和队列管理shell程序
Aug 04 Python
Pycharm学习教程(3) 代码运行调试
May 03 Python
Python编程实现两个文件夹里文件的对比功能示例【包含内容的对比】
Jun 20 Python
python中set()函数简介及实例解析
Jan 09 Python
django主动抛出403异常的方法详解
Jan 04 Python
使用APScheduler3.0.1 实现定时任务的方法
Jul 22 Python
将python2.7添加进64位系统的注册表方式
Nov 20 Python
Python+Redis实现布隆过滤器
Dec 08 Python
Python warning警告出现的原因及忽略方法
Jan 31 Python
Python decimal模块使用方法详解
Jun 08 Python
用 Python 制作地球仪的方法
Apr 24 #Python
解决python中显示图片的plt.imshow plt.show()内存泄漏问题
Apr 24 #Python
基于打开pycharm有带图片md文件卡死问题的解决
Apr 24 #Python
解决Opencv+Python cv2.imshow闪退问题
Apr 24 #Python
python实现五子棋程序
Apr 24 #Python
opencv python 图片读取与显示图片窗口未响应问题的解决
Apr 24 #Python
jupyter notebook oepncv 显示一张图像的实现
Apr 24 #Python
You might like
作为PHP程序员应该了解MongoDB的五件事
2013/06/03 PHP
php基于表单密码验证与HTTP验证用法实例
2015/01/06 PHP
深入讲解PHP的对象注入(Object Injection)
2017/03/01 PHP
PhpStorm 如何优雅的调试Hyperf的方法步骤
2019/11/24 PHP
javascript 实用的文字链提示框效果
2010/06/30 Javascript
三级下拉菜单的js实现代码
2011/05/23 Javascript
CSS(js)限制页面显示的文本字符长度
2012/12/27 Javascript
jQuery父级以及同级元素查找介绍
2013/09/04 Javascript
js过滤特殊字符输入适合输入、粘贴、拖拽多种情况
2014/03/22 Javascript
jQuery实现在最后一个元素之前插入新元素的方法
2015/07/18 Javascript
JavaScript中this的9种应用场景及三种复合应用场景
2015/09/12 Javascript
Jquery on方法绑定事件后执行多次的解决方法
2016/06/02 Javascript
JS对象序列化成json数据和json数据转化为JS对象的代码
2017/08/23 Javascript
实例分析JS与Node.js中的事件循环
2017/12/12 Javascript
使用 Node.js 开发资讯爬虫流程
2018/01/07 Javascript
详解Nodejs get获取远程服务器接口数据
2019/03/26 NodeJs
微信小程序rich-text富文本用法实例分析
2019/05/20 Javascript
Angular.JS读取数据库数据调用完整实例
2019/07/02 Javascript
解决vue与node模版引擎的渲染标记{{}}(双花括号)冲突问题
2020/09/11 Javascript
Python编程pygame模块实现移动的小车示例代码
2018/01/03 Python
python 多维切片之冒号和三个点的用法介绍
2018/04/19 Python
PyTorch 普通卷积和空洞卷积实例
2020/01/07 Python
html5 canvas里绘制椭圆并保持线条粗细均匀的技巧
2013/03/25 HTML / CSS
Expedia丹麦:全球领先的旅游网站
2018/03/18 全球购物
美国牙科折扣计划:DentalPlans.com
2019/08/26 全球购物
请说出以下代码输出什么
2013/08/30 面试题
《邮票齿孔的故事》教学反思
2014/02/22 职场文书
三月学雷锋月活动总结
2014/04/28 职场文书
2014年学校党建工作汇报材料
2014/11/02 职场文书
给老师的一封感谢信
2015/01/20 职场文书
学年个人总结范文
2015/03/05 职场文书
大学生读书笔记范文
2015/07/01 职场文书
纪检部部长竞选稿
2015/11/21 职场文书
《跨越海峡的生命桥》教学反思
2016/02/18 职场文书
交通事故协议书范本
2016/03/19 职场文书
Python移位密码、仿射变换解密实例代码
2021/06/27 Python