Python 练习 —— 2048
2048 这段时间火的不行啊,大家都纷纷仿造,“百家争鸣”,于是出现了各种技术版本号:除了手机版本号,还有C语言版、Qt版、Web版、java版、C#版等,刚好我接触Python不久,于是弄了个Python版——控制台的2048,正好熟悉下Python语法,程序执行效果例如以下:
| 移动方向 | 移动前 | 移动后 |
|
handle(x, 'left')
|
x = [0, 2, 2, 2]
|
x = [4, 2, 0, 0]
|
| handle(x, 'left') |
x = [2, 4, 2, 2]
|
x = [2, 8, 0, 0] |
| handle(x, 'right') | x = [2, 4, 2, 2] | x = [0, 0, 2, 8] |
这些是所有代码,保存在单一文件里就可以执行,执行环境 Python3.0+
# -*- 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 v[i]] 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)
Python 练习 —— 2048的更多相关文章
- python写2048小游戏
#!/usr/bin/env python # coding=utf-8 #******************************************************** # > ...
- [python] python实现2048游戏,及代码解析。
我初学python,有不对之处望大家指教.转载请征得同意. 我在网络上也找了一些2048游戏代码的讲解,但都不是特别详细.所以我希望能够尽量详细的讲解.同时,有的地方我也不懂,希望大家能帮助补充.我会 ...
- 用Python做2048游戏 网易云课堂配套实验课。通过GUI来体验编程的乐趣。
第1节 认识wxpython 第2节 画几个形状 第3节 再做个计算器 第4节 最后实现个2048游戏 实验1-认识wxpython 一.实验说明 1. 环境登录 无需密码自动登录,系统用户名shiy ...
- Python入门 —— 2048实战(字符界面和图形界面)
2048 game (共4种实现方法) 目录: .. 图形界面 ... pygame 和 numpy .. 字符界面 ... 第一种 ... curses ... wxpython ... 第二种 . ...
- python作业-2048小游戏
需了解的知识 Pygame中的各个模块及其功能: Pygame.init():初始化所有导入的模块 pygame.display: pygame.display.init() - 初始化 disp ...
- python之2048
#-*- coding:utf-8 -*- import curses from random import randrange, choice # generate and place new ti ...
- 【python】2048
来源:https://www.shiyanlou.com/courses/368 实验楼的2048程序,在linux下可实现通过终端游戏. 主要学习的知识点: 1.状态机函数实现,用字典将状态和函数相 ...
- Python 008- 游戏2048
#-*- coding:utf-8 -*- import curses from random import randrange, choice # generate and place new ti ...
- python项目练习地址
作者:Wayne Shi链接:http://www.zhihu.com/question/29372574/answer/88744491来源:知乎著作权归作者所有,转载请联系作者获得授权. 目前是3 ...
随机推荐
- iPhone/iPad全屏截图与区域截图的几种方法
本文由社区会员taonavy分享 截取本区域(self.view): UIGraphicsBeginImageContext(CGSizeMake(self.view.frame.size.width ...
- NYOJ130 同样的雪花 【Hash】
同样的雪花 时间限制:1000 ms | 内存限制:65535 KB 难度:4 描写叙述 You may have heard that no two snowflakes are alike. ...
- [Hapi.js] Friendly error pages with extension events
hapi automatically responds with JSON for any error passed to a route's reply()method. But what if y ...
- 使用xtrabakcup 备份inodb数据库
1,获取yum源 rpm -ivh http://www.percona.com/downloads/percona-release/redhat/0.1-3/percona-release-0.1- ...
- .Net Errors
1.Unknown column 'Extent1.Discriminator' in 'field list' Resole:http://blog.csdn.net/philip502/artic ...
- javascript无缝流畅动画轮播,终于让我给搞出来了。
自己一直想写一个真正能用的轮播图,以前是写过一个,但是不是无缝的轮播,感觉体验很差,这个轮播之前也搞了很多实例,看了很多代码,但是脑子总转不过弯,为什么在运动到一定距离后可以突然转回到原始位置,而没有 ...
- asp.net缓存(二)
ASP.NET页面局部缓存 有时缓存整个页面是不现实的,因为页的某些部分可能在每次请求时都需要变化.在这些情况下,只能缓存页的一部分.顾名思义,页面部分缓存是将页面部分内容保存在内存中以便响应用户请求 ...
- 莫比乌斯反演题目泛做(为了对应smz的课件)
题1:BZOJ2190 SDOI 2010 仪仗队 题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=2190 算法讨论: 我们先来考虑一个点被 ...
- [原创]Windows下更改特定后缀名以及特定URL前缀的默认打开方式
Windows下,特定后缀名的文件会由特定的应用程序来运行,比如双击readme.txt,通常情况下会由Windows自带的notepad.exe(记事本)打开文件.如果现在安装了记事本以外的其他文本 ...
- 22. Generate Parentheses
https://leetcode.com/problems/generate-parentheses/ 题目大意:给出n对小括号,求出括号匹配的情况,用列表存储并返回,例如:n=3时,答案应为: [ ...