首页 > 其他 > 详细

用numpy写的2048

时间:2019-08-16 01:03:45      阅读:116      评论:0      收藏:0      [点我收藏+]

功能还不是很完善,做个记录,有优化之处还请指出。

 


#time: 2019/8/15 19:02

# -*- coding: utf-8 -*-

import numpy as np



def move(lst):
length = len(lst)
ismove = False
for _ in range(3):
index = length - 1
while index < length and index>0:
if lst[index] == 0 and lst[index-1] != 0:
lst[index] = lst[index-1]
lst[index-1] = 0
ismove = True
elif lst[index] == 2048:
index -=1
continue
elif lst[index] == lst[index-1] and lst[index-1] != 0:
lst[index] *= 2
lst[index-1]=0
ismove = True
index -= 1
return ismove





def move_direction(direction,a):


ismovei = False
ismovej = False
ismovek = False
ismovel = False
if direction == ‘d‘:
i, j, k, l = a
ismovei = move(i)
ismovej = move(j)
ismovek = move(k)
ismovel = move(l)
a = np.concatenate((i, j, k, l)).reshape(4, 4)
elif direction == ‘a‘:
i = a[0,::-1]
j = a[1, ::-1]
k = a[2, ::-1]
l = a[3, ::-1]
ismovei = move(i)
ismovej = move(j)
ismovek = move(k)
ismovel = move(l)
a = np.concatenate((i[::-1], j[::-1], k[::-1], l[::-1])).reshape(4, 4)

elif direction == ‘s‘:
a = a.T
i, j, k, l = a
ismovei = move(i)
ismovej = move(j)
ismovek = move(k)
ismovel = move(l)
a = np.concatenate((i, j, k, l)).reshape(4, 4)
a = a.T

elif direction == ‘w‘:
a = a.T
i = a[0, ::-1]
j = a[1, ::-1]
k = a[2, ::-1]
l = a[3, ::-1]
ismovei = move(i)
ismovej = move(j)
ismovek = move(k)
ismovel = move(l)
a = np.concatenate((i[::-1], j[::-1], k[::-1], l[::-1])).reshape(4, 4)
a = a.T
elif direction == ‘p‘:
game_2048()

elif direction == ‘q‘:
exit(0)
else:
direction = input("输入不正确,重新输入")
move_direction(direction,a)

if True in [ismovei,ismovej,ismovek,ismovel]:
return a

elif a[np.where(a==0)].size == 0:
print("your lose")
exit(0)
else:
direction = input("不能移动,重新输入")
move_direction(direction, a)
return a

def create_rand(arr):
if arr[np.where(arr==2048)].size == 16:
print("you win")
exit(0)
i,j=np.where(arr==0)
np.random.seed(100)
arr[np.random.choice(i),np.random.choice(j)] = 2

def init_map():
a = np.arange(16, dtype=int).reshape(4, 4)
a.fill(0)
return a

def print_arr(a):
for row in a:
print("{:^6}{:^6}{:^6}{:^6}".format(row[0],row[1],row[2],row[3]))




def game_2048():
a= init_map()
print("q退出,p重新开始")
while True:
create_rand(a)
print_arr(a)
direction = input("请输入")
a = move_direction(direction,a)



if __name__ == ‘__main__‘:
game_2048()


用numpy写的2048

原文:https://www.cnblogs.com/zion412/p/11361195.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!