Python新手实现2048小游戏
作者:hebedich 发布时间:2021-02-19 14:12:57
标签:Python,2048
接触 Python 不久,看到很多人写2048,自己也捣鼓了一个,主要是熟悉Python语法。
程序使用Python3 写的,代码150行左右,基于控制台,方向键使用输入字符模拟。
演示图片
2048.py
# -*- 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)
以上所述就是本文给大家分享的全部代码了,希望能够对大家学习Python有所帮助。


猜你喜欢
- 废话不多说,直接上代码<?php // 暂不支持断点续传 // $url = 'http://www.
- Python 截取字符串使用 变量[头下标:尾下标],就可以截取相应的字符串,其中下标是从0开始算起,可以是正数或负数,下标可以为空表示取到
- 游戏规则:一付扑克牌,去掉大小王,每个玩家发3张牌,最后比大小,看谁赢。有以下几种牌:豹子:三张一样的牌,如3张6.顺金:又称同花顺,即3张
- PyCharm是Python著名的Python集成开发环境(IDE)conda有Miniconda和Anaconda,前者应该是类似最小化版
- 本文实例讲述了Python实现字符串与数组相互转换功能。分享给大家供大家参考,具体如下:字符串转数组str = '1,2,3'
- 例如输入:['adam', 'LISA', 'barT'],输出:['Adam
- 在使用ORACLE的过程过,我们会经常遇到一些ORACLE产生的错误,对于初学者而言,这些错误可能有点模糊,而且可能一时不知怎么去处理产生的
- 之前我给粉丝们搞过个投票,寻找MySQL中那个最熟悉的陌生人~~MySQL中哪些技术点是你既熟悉又陌生的?前三名和我预料大差不差,分别是
- 函数较简单,看下面的例子: s = 'hEllo pYthon' print s.upper() print s.lower
- 非常好的边框样式设置工具,使用该工具您可以很方便的为DIV设置简单的边框样式,如果放在DW中会更好。会制作DW插件的高手,请帮忙制作成DW插
- 字符串中字符大小写的变换1. str.lower() //小写>>> 'SkatE'
- 数据表都已经创建起来了,假设我们已经插入了许多的数据,我们就可以用自己喜欢的方式对数据表里面的信息进行检索和显示了,比如说:可以象下面这样把
- 如下所示:import urllib.requestimport sysimport http.cookiejarimport urllib
- 1.order by rand()数据多了极慢,随机性非常好,适合非常小数据量的情况。SELECT * FROM table_name AS
- 本次分享将介绍如何在Python中使用Pandas库实现MySQL数据库的读写。首先我们需要了解点ORM方面的知识ORM技术对象关系映射技术
- 本文介绍了一种将英文字符首个字母串转换为大写的asp代码,当然这个功能可能英文网站比较有用。转换大写功能英文介绍:Code Title: P
- 使用Python爬虫库requests多线程抓取猫眼电影TOP100思路:查看网页源代码抓取单页内容正则表达式提取信息猫眼TOP100所有信
- 这些存储过程如下: sp_makewebtask xp_cmdshell xp_dirtree xp_fileexist xp_termin
- 环境:go 1.19.8在读多写少的情况下,即使一段时间内没有写操作,大量并发的读访问也不得不在Mutex的保护下变成串行访问,这种情况下,
- 整理了一下python 中文件的输入输出及主要介绍一些os模块中对文件系统的操作。文件输入输出1、内建函数open(file_name,文件