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 相关文章推荐
python将xml xsl文件生成html文件存储示例讲解
Dec 03 Python
python生成指定长度的随机数密码
Jan 23 Python
Python中方法链的使用方法
Feb 23 Python
Python脚本获取操作系统版本信息
Dec 17 Python
Python使用matplotlib绘制正弦和余弦曲线的方法示例
Jan 06 Python
Python 实现一行输入多个值的方法
Apr 21 Python
Python中logging实例讲解
Jan 17 Python
详解Python学习之安装pandas
Apr 16 Python
Python简单处理坐标排序问题示例
Jul 11 Python
django如何自己创建一个中间件
Jul 24 Python
Python实现发票自动校核微信机器人的方法
May 22 Python
PyCharm 安装与使用配置教程(windows,mac通用)
May 12 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笔试题
2009/08/04 PHP
php实现两表合并成新表并且有序排列的方法
2014/12/05 PHP
php生成curl命令行的方法
2015/12/14 PHP
Laravel用户授权系统的使用方法示例
2018/09/16 PHP
多个Laravel项目如何共用migrations详解
2018/09/25 PHP
js TextArea的选中区域处理
2010/12/28 Javascript
javascript设置页面背景色及背景图片的方法
2015/12/29 Javascript
理解JavaScript表单的基础知识
2016/01/25 Javascript
javascript的几种继承方法介绍
2016/03/22 Javascript
关于json字符串与实体之间的严格验证代码
2016/11/10 Javascript
jQuery实现导航回弹效果
2017/02/27 Javascript
vue之数据交互实例代码
2017/06/20 Javascript
javascript cookie的基本操作(添加和删除)
2017/07/24 Javascript
vue-cli中打包图片路径错误的解决方法
2017/10/26 Javascript
简述ES6新增关键字let与var的区别
2019/08/23 Javascript
centos系统升级python 2.7.3
2014/07/03 Python
深入理解python中的闭包和装饰器
2016/06/12 Python
Python进阶-函数默认参数(详解)
2017/05/18 Python
详解django中Template语言
2020/02/22 Python
Python无头爬虫下载文件的实现
2020/04/02 Python
深入了解NumPy 高级索引
2020/07/24 Python
用python实现一个简单计算器(完整DEMO)
2020/10/14 Python
html5文本内容_动力节点Java学院整理
2017/07/11 HTML / CSS
Gucci法国官方网站:意大利奢侈品牌
2018/07/25 全球购物
Java语言程序设计测试题选择题部分
2014/04/03 面试题
护理专业求职信
2014/06/15 职场文书
另类冲刺标语
2014/06/24 职场文书
花坛标语大全
2014/06/30 职场文书
教师党的群众路线教育实践活动学习心得体会
2014/10/30 职场文书
2014年社区妇联工作总结
2014/12/02 职场文书
护士个人年度总结范文
2015/02/13 职场文书
党小组鉴定意见
2015/06/02 职场文书
陈斌强事迹观后感
2015/06/17 职场文书
2019年房屋委托租赁合同范本(通用版)!
2019/07/17 职场文书
HTML页面中使两个div并排显示的实现
2022/05/15 HTML / CSS
Python测试框架pytest高阶用法全面详解
2022/06/01 Python