Python2048小游戏demo
# -*- coding:UTF-8 -*-
#! /usr/bin/python3
import random
v = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
def display(v, score):
'''显示界面
'''
print('{0:4} {1:4} {2:4} {3:4}'.format(v[0][0], v[0][1], v[0][2], v[0][3]))
print('{0:4} {1:4} {2:4} {3:4}'.format(v[1][0], v[1][1], v[1][2], v[1][3]))
print('{0:4} {1:4} {2:4} {3:4}'.format(v[2][0], v[2][1], v[2][2], v[2][3]))
print('{0:4} {1:4} {2:4} {3:4}'.format(v[3][0], v[3][1], v[3][2], v[3][3]), ' Total score: ', score)
def init(v):
'''随机分布网格值
'''
for i in range(4):
v[i] = [random.choice([0, 0, 0, 2, 2, 4]) for x in range(4)]
def align(vList, direction):
'''对齐非零的数字
direction == 'left':向左对齐,例如[8,0,0,2]左对齐后[8,2,0,0]
direction == 'right':向右对齐,例如[8,0,0,2]右对齐后[0,0,8,2]
'''
# 移除列表中的0
for i in range(vList.count(0)):
vList.remove(0)
# 被移除的0
zeros = [0 for x in range(4 - len(vList))]
# 在非0数字的一侧补充0
if direction == 'left':
vList.extend(zeros)
else:
vList[:0] = zeros
def addSame(vList, direction):
'''在列表查找相同且相邻的数字相加, 找到符合条件的返回True,否则返回False,同时还返回增加的分数
direction == 'left':从右向左查找,找到相同且相邻的两个数字,左侧数字翻倍,右侧数字置0
direction == 'right':从左向右查找,找到相同且相邻的两个数字,右侧数字翻倍,左侧数字置0
'''
score = 0
if direction == 'left':
for i in [0, 1, 2]:
if vList[i] == vList[i+1] != 0:
vList[i] *= 2
vList[i+1] = 0
score += vList[i]
return {'bool':True, 'score':score}
else:
for i in [3, 2, 1]:
if vList[i] == vList[i-1] != 0:
vList[i-1] *= 2
vList[i] = 0
score += vList[i-1]
return {'bool':True, 'score':score}
return {'bool':False, 'score':score}
def handle(vList, direction):
'''处理一行(列)中的数据,得到最终的该行(列)的数字状态值, 返回得分
vList: 列表结构,存储了一行(列)中的数据
direction: 移动方向,向上和向左都使用方向'left',向右和向下都使用'right'
'''
totalScore = 0
align(vList, direction)
result = addSame(vList, direction)
while result['bool'] == True:
totalScore += result['score']
align(vList, direction)
result = addSame(vList, direction)
return totalScore
def operation(v):
'''根据移动方向重新计算矩阵状态值,并记录得分
'''
totalScore = 0
gameOver = False
direction = 'left'
op = input('operator:')
if op in ['a', 'A']: # 向左移动
direction = 'left'
for row in range(4):
totalScore += handle(v[row], direction)
elif op in ['d', 'D']: # 向右移动
direction = 'right'
for row in range(4):
totalScore += handle(v[row], direction)
elif op in ['w', 'W']: # 向上移动
direction = 'left'
for col in range(4):
# 将矩阵中一列复制到一个列表中然后处理
vList = [v[row][col] for row in range(4)]
totalScore += handle(vList, direction)
# 从处理后的列表中的数字覆盖原来矩阵中的值
for row in range(4):
v[row][col] = vList[row]
elif op in ['s', 'S']: # 向下移动
direction = 'right'
for col in range(4):
# 同上
vList = [v[row][col] for row in range(4)]
totalScore += handle(vList, direction)
for row in range(4):
v[row][col] = vList[row]
else:
print('Invalid input, please enter a charactor in [W, S, A, D] or the lower')
return {'gameOver':gameOver, 'score':totalScore}
# 统计空白区域数目 N
N = 0
for q in v:
N += q.count(0)
# 不存在剩余的空白区域时,游戏结束
if N == 0:
gameOver = True
return {'gameOver':gameOver, 'score':totalScore}
# 按2和4出现的几率为3/1来产生随机数2和4
num = random.choice([2, 2, 2, 4])
# 产生随机数k,上一步产生的2或4将被填到第k个空白区域
k = random.randrange(1, N+1)
n = 0
for i in range(4):
for j in range(4):
if v[i][j] == 0:
n += 1
if n == k:
v[i][j] = num
break
return {'gameOver':gameOver, 'score':totalScore}
init(v)
score = 0
print('Input:W(Up) S(Down) A(Left) D(Right), press <CR>.')
while True:
display(v, score)
result = operation(v)
if result['gameOver'] == True:
print('Game Over, You failed!')
print('Your total score:', score)
else:
score += result['score']
if score >= 2048:
print('Game Over, You Win!!!')
print('Your total score:', score)
Python2048小游戏demo的更多相关文章
- 微信小游戏 demo 飞机大战 代码分析(四)(enemy.js, bullet.js, index.js)
微信小游戏 demo 飞机大战 代码分析(四)(enemy.js, bullet.js, index.js) 微信小游戏 demo 飞机大战 代码分析(一)(main.js) 微信小游戏 demo 飞 ...
- 微信小游戏 demo 飞机大战 代码分析 (三)(spirit.js, animation.js)
微信小游戏 demo 飞机大战 代码分析(三)(spirit.js, animation.js) 微信小游戏 demo 飞机大战 代码分析(一)(main.js) 微信小游戏 demo 飞机大战 代码 ...
- 微信小游戏 demo 飞机大战 代码分析 (二)(databus.js)
微信小游戏 demo 飞机大战 代码分析(二)(databus.js) 微信小游戏 demo 飞机大战 代码分析(一)(main.js) 微信小游戏 demo 飞机大战 代码分析(三)(spirit. ...
- 微信小游戏 demo 飞机大战 代码分析 (一)(game.js, main.js)
微信小游戏 demo 飞机大战 代码分析(一)(main.js) 微信小游戏 demo 飞机大战 代码分析(二)(databus.js) 微信小游戏 demo 飞机大战 代码分析(三)(spirit. ...
- unity + win8.1 apps 小游戏demo
unity3d用的人挺多. . .本来想写个3d游戏试试. .额..貌似挺麻烦.. . .. ..先用unity写个简单的2d游戏吧.. (adsw回车 或者 触摸屏虚拟摇杆) 开发环境 unit ...
- 带你使用h5开发移动端小游戏
带你使用h5开发移动端小游戏 在JY1.x版本中,你要做一个pc端的小游戏,会非常的简单,包括说,你要在低版本的浏览器IE8中,也不会出现明显的卡顿现象,你只需要关心游戏的逻辑就行了,比较适合逻辑较为 ...
- 【开源】微信小程序、小游戏以及 Web 通用 Canvas 渲染引擎 - Cax
Cax 小程序.小游戏以及 Web 通用 Canvas 渲染引擎 Github → https://github.com/dntzhang/cax 点我看看 DEMO 小程序 DEMO 正在审核中敬请 ...
- 拼图小游戏之计算后样式与CSS动画的冲突
先说结论: 前几天写了几个非常简单的移动端小游戏,其中一个拼图游戏让我郁闷了一段时间.因为要获取每张图片的位置,用`<style>`标签写的样式,直接获取计算后样式再用来交换位置,结果就悲 ...
- 小游戏runpig总结
前几天写了一个JavaScript小游戏,大概是这样的 demo:strongfanfan.top/RunPig 源代码:www.github.com/strongfanfan/RunPig 画风简 ...
随机推荐
- Nginx详解二十二:Nginx深度学习篇之Lua解释器安装及基础语法
解释器 Lua:Lua是一个简洁.轻量.可扩展的脚本语言 Nginx+Lua优势充分的结合Nginx的并发处理epoll优势的Lua的轻量实现简单的功能切高并发的场景 安装Lua 1.安装解释器:yu ...
- C/C++中二进制与文本方式打开文件的区别
二进制与文本文件主要有两个大的区别: 1.换行符的区别: Windows平台下 对于Windows文本文件,它们使用回车和换行来表示换行符:如果以“文本”方式打开文件,当读取文件的时候,系统会将所有 ...
- 如果IDEA右上角的tomcat消失了,解决办法
看了很多博客都没有找到解决办法,还是老师帮我解决的
- Python sendmail
#coding:utf- #强制使用utf-8编码格式 import smtplib #加载smtplib模块 from email.mime.text import MIMEText from em ...
- 【C++ Primer 第13章】2. 拷贝控制和资源管理
拷贝控制和资源管理 • 类的行为像一个值.意味着它应该有自己的状态,当我们拷贝一个像值得对象时,副本和原对象是完全独立的,改变副本不会对原对象有任何影响. • 行为像指针的类则共享状态.当我们拷贝一个 ...
- 期货大赛项目|二,DAL详解
接口层就不重点讲述了,直接DAL层 DAL层 using System; using System.Collections.Generic; using System.Linq; using Syst ...
- 【BZOJ】3730: 震波
原题链接 题解 查询距离一个点距离在一定范围内的点,直接点分树,前缀和用树状数组维护 答案是当前重心距离不超过k - (x到重心距离)的点的前缀和,减去在x所在子树中,距离重心不超过k - (x到重心 ...
- 【Android】Android 代码判断是否获取ROOT权限(二)
[Android]Android 代码判断是否获取ROOT权限 方法比较简单,直接粘贴代码 /** * 判断当前手机是否有ROOT权限 * @return */ public boolean isRo ...
- python全栈开发day72-django之Form组件
一.ajax 1. 复习JSON 1. JSON是什么? 一种数据格式,和语言无关的数据格式. 2. Python里面转换 1. Python对象 --> 字符串 import json 字符串 ...
- SQL Server数据库存储过程中拼接字符串注意的问题
在SQL Server数据库中书写复杂的存储过程时,一般的做法是拼接字符串,最后使用EXEC sp_executesql '拼接的字符串' 查询出结果. 先看一段代码: -- ============ ...