python贪吃蛇游戏代码详解外加中文_Python贪吃蛇游戏编写代码
Python贪吃蛇游戏编写代码
来源:中文源码网 浏览: 次 日期:2018年9月2日
【下载文档: Python贪吃蛇游戏编写代码.txt 】
(友情提示:右键点上行txt文档名->目标另存为)
Python贪吃蛇游戏编写代码 最近在学Python,想做点什么来练练手,命令行的贪吃蛇一般是C的练手项目,但是一时之间找不到别的,就先做个贪吃蛇来练练简单的语法。
由于Python监听键盘很麻烦,没有C语言的kbhit(),所以这条贪吃蛇不会自己动,运行效果如下:要求:用#表示边框,用*表示食物,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.1import 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贪吃蛇游戏编写代码相关推荐
- 朴素贝叶斯分类器详解及中文文本舆情分析(附代码实践)
参加 2018 AI开发者大会,请点击 ↑↑↑ 作者 | 杨秀璋(笔名:Eastmount),贵州财经大学信息学院老师,硕士毕业于北京理工大学,主要研究方向是Web数据挖掘.知识图谱.Python数据 ...
- 【C语言】初始C语言系列 代码详解 _ 编程入门 _【内附代码和图片】_ [初阶篇 _ 总结复习]
[前言] 本篇文章为初始C语言部分,C语言是编程的入门语言,所以也说是编程入门: 学好C语言的入门内容,才能真正的入门编程,而C语言的学习对于刚入门的同学还是有一些难度的,需要踏踏实实的自己去理解. ...
- mvcnn代码详解_Tensorflow,OpenCV实现的CNN车牌识别代码
[实例简介] 某位大牛在github上分享的 CNN 车牌识别源代码,在将其装到Windows的Python下运行时碰到了各种报错(WIN8下python3.6,Opencv3.0),有些问题搜遍网络 ...
- 认知无线电matlab代码详解,认知无线电频谱感知之功率检测matlab代码.docx
认知无线电频谱感知之功率检测matlab代码 能量检测仿真实验代码:clear all;clc;n = 5;ps = 1;SNR1 = -5;SNR2 = -8;SNR3 = -10;% Sim_Ti ...
- 【spinning up】代码详解目录
[spinning up]代码详解目录 文章目录 [spinning up]代码详解目录 前言: 1.[Spinning Up]实验输出 1.1 加强版plot.py,更有效输出性能曲线 2.[Spi ...
- socket 获取回传信息_Luat系列官方教程5:Socket代码详解
文章篇幅较长,代码部分建议横屏查看,或在PC端打开本文链接.文末依然为爱学习的你准备了专属福利~ TCP和UDP除了在Lua代码声明时有一些不同,其他地方完全一样,所以下面的代码将以TCP长连接的数据 ...
- yolov5的detect.py代码详解
目标检测系列之yolov5的detect.py代码详解 前言 哈喽呀!今天又是小白挑战读代码啊!所写的是目标检测系列之yolov5的detect.py代码详解.yolov5代码对应的是官网v6.1版本 ...
- jQuery选择器代码详解(一)——Sizzle方法
对jQuery的Sizzle各方法做了深入分析(同时也参考了一些网上资料)后,将结果分享给大家.我将采用连载的方式,对Sizzle使用的一些方法详细解释一下,每篇文章介绍一个方法. 若需要转载,请写明 ...
- 要怎么通过PHP发布微博动态:附代码详解
今天主要聊聊关于如何通过PHP发布微博动态(代码详解),这里通过一些实例讲解与代码示例让大家通过直观的表现了解其中内容,相信大家能从中收获到有用的知识. 首先,肯定是注册成为开发者新浪微博开放平台 选 ...
- VINS技术路线与代码详解
VINS技术路线 写在前面:本文整和自己的思路,希望对学习VINS或者VIO的同学有所帮助,如果你觉得文章写的对你的理解有一点帮助,可以推荐给周围的小伙伴们,当然,如果你有任何问题想要交流,欢迎随时探 ...
最新文章
- 清华大学《高级机器学习》课件和Fellow专家特邀报告(附pdf下载)
- collection_check_boxes的应用
- 巴克莱对冲_“巴克莱的财政预算案”:使金钱管理对心理健康有效—用户体验案例研究
- 【Blog.Core开源】网关自定义认证鉴权与传参
- 静态内部类实现 单例模式
- 中国移动宣布已开通5G基站近5万个,在50个城市提供5G服务
- JavaScript------表单约束验证DOM方法
- POJ1107 ZOJ1042 UVALive2291 W's Cipher【密码+模拟】
- 零基础入门深度学习(2) - 线性单元和梯度下降
- Photo Size Changer三步压缩太大的jpg照片
- mysql 修改数据库密码
- nfine框架 上传文件_NFine快速开发框架
- S32K144(12)FTM
- 包络线公式如何用计算机求,包络线公式
- 自己的联想Y450笔记本无法连接无线网络的解决办法
- VideoView播放视频的时候尺寸异常
- firefox插件(plugin)开发概述
- 防火墙和系统安全防护
- linux环境oracle环境变量,Linux下设置oracle环境变量
- 西藏拉萨某知名大饭店