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 .’)
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有所帮助。

Posted in 未分类

发表评论