import random
List = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def shuchu (List) : ##把一排16个数字输出成4x4方形
n = 0
while n <= 3 :
i = 0
m1 = " "
while i <= 3 :
m1 = m1 + str(List[i + n*4]) + " "
i = i + 1
print(m1)
n = n + 1
def suiji (List) : ##每一轮会随机出一个数,2或4,在0的位置输出
d = random.randint (0 , 15)
while List[d] != 0 :
d = random.randint (0 , 15)
d1 = random.randint (0,1)
if d1 == 0 :
List[d] = 2
else:
List[d] = 4
def zonglie_ (List,ts,t1,t2,tk): ##我算是把所有情况枚举了然后分了这么几类情况,这是纵列
n = 0
while n <= 3:
e1 = ts
while e1 <= 3 and e1 >= 0 :
if List[n + e1*4] != 0 : ##这里我是用n+e1x4这种来表示数组中数字的位置,这样就比较讨巧,四行我只要改变e1的值就行
e2 = e1 + t1
while e2 <= 3 and e2 >= 0 :
if List[n + e2*4] == List[n + e1*4]:
List[n + e1*4] = 2 * List[n + e2*4]
List[n + e2*4] = 0
e2 = e2 + t2
e1 = e1 + t2
elif List[n + e2*4] != 0:
e1 = e1 + t1
e2 = e2 + t1
else:
e2 = e2 + t1
e1 = tk
else:
e1 = e1 + t1
list1 = [0,0,0,0] ##实现把数字推到一边
k = ts
k1 = ts
while k <= 3 and k >= 0 and k1 >= 0 and k1 <= 3 :
if List [n + k1*4] != 0 :
list1[k] = List [n + k1*4]
k = k + t1
k1 = k1 + t1
k2 = 0
while k2 <= 3:
List[n + k2*4] = list1[k2]
k2 = k2 + 1
n = n + 1
def henglie_ (List,ts,t1,t2,tk): ##和上面基本一样,把个边变量修改一下就行
n = 0
while n <= 3:
e1 = ts
while e1 <= 3 and e1 >= 0 : ##细节,上面是n+e1x4,这里换了一下
if List[e1 + n*4] != 0 :
e2 = e1 + t1
while e2 <= 3 and e2 >= 0 :
if List[e2 + n*4] == List[e1 + n*4]:
List[e1 + n*4] = 2 * List[e2 + n*4]
List[e2 + n*4] = 0
e2 = e2 + t2
e1 = e1 + t2
elif List[e2 + n*4] != 0:
e1 = e1 + t1
e2 = e2 + t1
else:
e2 = e2 + t1
e1 = tk
else:
e1 = e1 + t1
list1 = [0,0,0,0]
k = ts
k1 = ts
while k <= 3 and k >= 0 and k1 >= 0 and k1 <= 3 :
if List [k1 + n*4] != 0 :
list1[k] = List [k1 + n*4]
k = k + t1
k1 = k1 + t1
k2 = 0
while k2 <= 3:
List[k2 + n*4] = list1[k2]
k2 = k2 + 1
n = n + 1
play = int(input("Start game? Press 1:"))
while play == 1 :
suiji(List)
suiji(List) ##先出两个数
shuchu(List)
key = 1 ##initialize
while key > 0:
n = str(input("Press wasd to play"))
if n == "a":
henglie_ (List,0,1,2,4)
if n == "d":
henglie_ (List,3,-1,-2,-1)
if n == "w":
zonglie_ (List,0,1,2,4)
if n == "s":
zonglie_ (List,3,-1,-2,-1)
test = List.count(0)
if test > 0:
suiji(List)
shuchu(List)
else:
key = 0
play = int (input("You lose! Press 1 to play again"))
python简易实现2048
于 2023-08-11 10:58:09 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)