Python贪吃蛇游戏编写代码


Posted in Python onOctober 26, 2020

最近在学Python,想做点什么来练练手,命令行的贪吃蛇一般是C的练手项目,但是一时之间找不到别的,就先做个贪吃蛇来练练简单的语法。

由于Python监听键盘很麻烦,没有C语言的kbhit(),所以这条贪吃蛇不会自己动,运行效果如下:

Python贪吃蛇游戏编写代码

要求:用#表示边框,用*表示食物,o表示蛇的身体,O表示蛇头,使用wsad来移动

Python版本:3.6.1

系统环境:Win10

类:

board:棋盘,也就是游戏区域

snake:贪吃蛇,通过记录身体每个点来记录蛇的状态

game:游戏类

本来还想要个food类的,但是food只需要一个坐标,和一个新建,所以干脆使用list来保存坐标,新建food放在game里面,从逻辑上也没有太大问题

源码:

# Write By Guobao
# 2017/4//7
#
# 贪吃蛇
# 用#做边界,*做食物,o做身体和头部
# python 3.6.1

import copy
import random
import os
import msvcrt

# the board class, used to put everything
class board:

 __points =[]

 def __init__(self):
 self.__points.clear()
 for i in range(22):
 line = []
 if i == 0 or i == 21:
 for j in range(22):
  line.append('#')
 else:
 line.append('#')
 for j in range(20):
  line.append(' ')
 line.append('#')
 self.__points.append(line)

 def getPoint(self, location):
 return self.__points[location[0]][location[1]]

 def clear(self):
 self.__points.clear()
 for i in range(22):
 line = []
 if i == 0 or i == 21:
 for j in range(22):
  line.append('#')
 else:
 line.append('#')
 for j in range(20):
  line.append(' ')
 line.append('#')
 self.__points.append(line)

 def put_snake(self, snake_locations):
 # clear the board
 self.clear()

 # put the snake points
 for x in snake_locations:
 self.__points[x[0]][x[1]] = 'o'

 # the head
 x = snake_locations[len(snake_locations) - 1]
 self.__points[x[0]][x[1]] = 'O'

 def put_food(self, food_location):
 self.__points[food_location[0]][food_location[1]] = '*'

 def show(self):
 os.system("cls")
 for i in range(22):
 for j in range(22):
 print(self.__points[i][j], end='')
 print()

# the snake class
class snake:
 __points = []

 def __init__(self):
 for i in range(1, 6):
 self.__points.append([1, i])

 def getPoints(self):
 return self.__points

 # move to the next position
 # give the next head
 def move(self, next_head):
 self.__points.pop(0)
 self.__points.append(next_head)

 # eat the food
 # give the next head
 def eat(self, next_head):
 self.__points.append(next_head)

 # calc the next state
 # and return the direction
 def next_head(self, direction='default'):

 # need to change the value, so copy it
 head = copy.deepcopy(self.__points[len(self.__points) - 1])

 # calc the "default" direction
 if direction == 'default':
 neck = self.__points[len(self.__points) - 2]
 if neck[0] > head[0]:
 direction = 'up'
 elif neck[0] < head[0]:
 direction = 'down'
 elif neck[1] > head[1]:
 direction = 'left'
 elif neck[1] < head[1]:
 direction = 'right'

 if direction == 'up':
 head[0] = head[0] - 1
 elif direction == 'down':
 head[0] = head[0] + 1
 elif direction == 'left':
 head[1] = head[1] - 1
 elif direction == 'right':
 head[1] = head[1] + 1
 return head

# the game
class game:

 board = board()
 snake = snake()
 food = []
 count = 0

 def __init__(self):
 self.new_food()
 self.board.clear()
 self.board.put_snake(self.snake.getPoints())
 self.board.put_food(self.food)

 def new_food(self):
 while 1:
 line = random.randint(1, 20)
 column = random.randint(1, 20)
 if self.board.getPoint([column, line]) == ' ':
 self.food = [column, line]
 return

 def show(self):
 self.board.clear()
 self.board.put_snake(self.snake.getPoints())
 self.board.put_food(self.food)
 self.board.show()


 def run(self):
 self.board.show()

 # the 'w a s d' are the directions
 operation_dict = {b'w': 'up', b'W': 'up', b's': 'down', b'S': 'down', b'a': 'left', b'A': 'left', b'd': 'right', b'D': 'right'}
 op = msvcrt.getch()

 while op != b'q':
 if op not in operation_dict:
 op = msvcrt.getch()
 else:
 new_head = self.snake.next_head(operation_dict[op])

 # get the food
 if self.board.getPoint(new_head) == '*':
  self.snake.eat(new_head)
  self.count = self.count + 1
  if self.count >= 15:
  self.show()
  print("Good Job")
  break
  else:
  self.new_food()
  self.show()

 # 反向一Q日神仙
 elif new_head == self.snake.getPoints()[len(self.snake.getPoints()) - 2]:
  pass

 # rush the wall
 elif self.board.getPoint(new_head) == '#' or self.board.getPoint(new_head) == 'o':
  print('GG')
  break

 # normal move
 else:
  self.snake.move(new_head)
  self.show()
 op = msvcrt.getch()

game().run()

笔记:

1.Python 没有Switch case语句,可以利用dirt来实现

2.Python的=号是复制,复制引用,深复制需要使用copy的deepcopy()函数来实现

3.即使在成员函数内,也需要使用self来访问成员变量,这和C++、JAVA很不一样

更多关于python游戏的精彩文章请点击查看以下专题:

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

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

Python 相关文章推荐
TensorFlow实现Softmax回归模型
Mar 09 Python
idea创建springMVC框架和配置小文件的教程图解
Sep 18 Python
详解如何为eclipse安装合适版本的python插件pydev
Nov 04 Python
Python3自动签到 定时任务 判断节假日的实例
Nov 13 Python
python 遍历列表提取下标和值的实例
Dec 25 Python
对python numpy.array插入一行或一列的方法详解
Jan 29 Python
Python函数的参数常见分类与用法实例详解
Mar 30 Python
python学习开发mock接口
Apr 28 Python
最新2019Pycharm安装教程 亲测
Feb 28 Python
小白教你PyCharm从下载到安装再到科学使用PyCharm2020最新激活码
Sep 25 Python
Python实现对齐打印 format函数的用法
Apr 28 Python
Python中requests库的用法详解
Jun 05 Python
OpenCV实现人脸识别
Apr 07 #Python
python使用opencv进行人脸识别
Apr 07 #Python
Python 实现链表实例代码
Apr 07 #Python
python中如何使用朴素贝叶斯算法
Apr 06 #Python
python获取当前运行函数名称的方法实例代码
Apr 06 #Python
python爬取w3shcool的JQuery课程并且保存到本地
Apr 06 #Python
使用Python对SQLite数据库操作
Apr 06 #Python
You might like
php输出echo、print、print_r、printf、sprintf、var_dump的区别比较
2013/06/21 PHP
php获取远程图片体积大小的实例
2013/11/12 PHP
smarty模板引擎中自定义函数的方法
2015/01/22 PHP
PHP 常用时间函数资料整理
2016/10/22 PHP
PHP实现生成数据字典功能示例
2018/05/24 PHP
可以将word转成html的js代码
2010/04/11 Javascript
javascript中递归函数用法注意点
2015/07/30 Javascript
js贪吃蛇网页版游戏特效代码分享(挑战十关)
2015/08/24 Javascript
Angular Js文件上传之form-data
2015/08/28 Javascript
js获取鼠标位置实例详解
2015/12/09 Javascript
jQuery层次选择器用法示例
2016/09/09 Javascript
node.js平台下的mysql数据库配置及连接
2017/03/31 Javascript
webpack多入口文件页面打包配置详解
2018/01/09 Javascript
使用Vue如何写一个双向数据绑定(面试常见)
2018/04/20 Javascript
jQuery实现ajax回调函数带入参数的方法示例
2018/06/26 jQuery
laydate时间日历插件使用方法详解
2018/11/14 Javascript
JS+php后台实现文件上传功能详解
2019/03/02 Javascript
JavaScript代码实现微博批量取消关注功能
2021/02/05 Javascript
python分割文件的常用方法
2014/11/01 Python
Python中实现结构相似的函数调用方法
2015/03/10 Python
python调用xlsxwriter创建xlsx的方法
2018/05/03 Python
Python爬虫之正则表达式的使用教程详解
2018/10/25 Python
python增加图像对比度的方法
2019/07/12 Python
用Python+OpenCV对比图像质量的几种方法
2019/07/15 Python
Python Django Vue 项目创建过程详解
2019/07/29 Python
PyQtGraph在pyqt中的应用及安装过程
2019/08/04 Python
python的常见矩阵运算(小结)
2019/08/07 Python
基于Python爬取51cto博客页面信息过程解析
2020/08/25 Python
Python实现JS解密并爬取某音漫客网站
2020/10/23 Python
浅析数据存储的三种方式 cookie sessionstorage localstorage 的异同
2020/06/04 HTML / CSS
GetYourGuide台湾:预订旅游活动、景点和旅游项目
2019/06/10 全球购物
小学教师个人工作总结2015
2015/04/20 职场文书
2016年安全月活动总结
2016/04/06 职场文书
适合青年人白手起家的创业项目分享
2019/08/16 职场文书
仅用几行Python代码就能复制她的U盘文件?
2021/06/26 Python
SpringCloud中分析讲解Feign组件添加请求头有哪些坑梳理
2022/06/21 Java/Android