#2048 用python实现
import random
import math
import os
global score
score = 0
def start():#开始
a = [[0 for i in range(4)] for i in range(4)] #构造一个4*4的列表
i = random.randint(0,3)
j = random.randint(0,3)
p2 = random.random()
if p2>0.9: a[i][j] = 4 #有0.9几率出现2
else: a[i][j] = 2
display(a)
def display(a):
os.system('cls')
global score
if (notlose):
print('现在你的分数:',score)
for i in range(4):
for j in range(4):
print("%6s" % a[i][j] , end = '')
print()
action = input('请输入移动方向。输入wsad分别表示上下左右。请注意调成小写模式。')
move(action,a)
else:
print('没有可以用的数字。游戏结束。你得了',score,'分')
def move(action,a):
if action == 'w':
up(a)
elif action == 's':
down(a)
elif action == 'a':
left(a)
elif action == 'd':
right(a)
else:
print('非法操作。')
display(a)
def left(a):
global score
for i in range(0,4):
for j in range(3,0,-1):
#print('test : a[' ,i,'][', j,'] = ' ,a[i][j])
if a[i][j-1] == 0:
a[i][j-1] = a[i][j]
a[i][j] = 0
elif a[i][j-1] == a[i][j]:
a[i][j-1] = 2 * a[i][j]
a[i][j] = 0
score +=a[i][j-1]
newnum(a)
def down(a):
global score
for j in range(0,4):
for i in range(0,3):
#print('test : a[' ,i,'][', j,'] = ' ,a[i][j])
if a[i+1][j] == 0:
a[i+1][j] = a[i][j]
a[i][j] = 0
elif a[i+1][j] == a[i][j]:
a[i+1][j] = 2 * a[i][j]
a[i][j] = 0
score +=a[i+1][j]
newnum(a)
def up(a):
global score
for j in range(0,4):
for i in range(3,0,-1):
#print('test : a[' ,i,'][', j,'] = ' ,a[i][j])
if a[i-1][j] == 0:
a[i-1][j] = a[i][j]
a[i][j] = 0
elif a[i-1][j] == a[i][j]:
a[i-1][j] = 2 * a[i][j]
a[i][j] = 0
score +=a[i-1][j]
newnum(a)
def right(a):
global score
for i in range(0,4):
for j in range(0,3):
#print('test : a[' ,i,'][', j,'] = ' ,a[i][j])
if a[i][j+1] == 0:
a[i][j+1] = a[i][j]
a[i][j] = 0
elif a[i][j+1] == a[i][j]:
a[i][j+1] = 2 * a[i][j]
a[i][j] = 0
score +=a[i][j+1]
newnum(a)
def newnum(a):
while (1):
i = random.randint(0,3)
j = random.randint(0,3)
if a[i][j] == 0:
a[i][j] = random.choice([2,2,2,2,2,2,2,2,2,4])
break
display(a)
def notlose(a):
for i in range(3):
for j in range(3):
if a[j][i] == a[j][i+1]:
return True
if a[j][i] == a[j+1][i]:
return True
return False
start()
如果觉得《python文字游戏源代码_【Python】用Python实现2048小游戏(源代码 1.0版本)》对你有帮助,请点赞、收藏,并留下你的观点哦!