谈不上自己写,还是按你的思路,自己写了一遍,获益匪浅,稍微简化了下布局import numpy as np
import os
import random
class game2048:
def __init__(self):
self.t1 = np.array([[0]*4 for i in range(4)])
self.list1 = [[0]*4 for i in range(4)]
def show(self):
for i in range(4):
for j in range(4):
if self.t1[i][j] == 0:
self.list1[i][j] = ' '*6
else:
self.list1[i][j] = self.t1[i][j]
count = 0
for i in range(21):
if i%5 == 0:
print('-'*32)
elif i%5 == 2:
for j in range(4):
print('| '+str(self.list1[count][j])+' '*(6-len(str(self.list1[count][j]))),end='')
print('|')
count += 1
else:
print('|',' | '*4)
def bottom_up(self):
self.t1 = self.t1.transpose()
def reverse(self):
for i in range(4):
self.t1[i] = self.t1[i][::-1]
def right(self):
for i in range(4):
for k in range(4):
for j in range(3):
if self.t1[i][j] == self.t1[i][j+1]:
self.t1[i][j+1] += self.t1[i][j]
self.t1[i][j] = 0
if self.t1[i][j+1] == 0:
self.t1[i][j+1] = self.t1[i][j]
self.t1[i][j] = 0
def left(self):
self.reverse()
self.right()
self.reverse()
def down(self):
self.bottom_up()
self.right()
self.bottom_up()
def up(self):
self.bottom_up()
self.reverse()
self.right()
self.reverse()
self.bottom_up()
def creat(self):
kongbai = []
for i in range(4):
for j in range(4):
if self.t1[i][j] ==0:
kongbai.append((i,j))
if len(kongbai):
(a,b) = random.choice(kongbai)
self.t1[a][b] = random.choice([2,4])
else:
self.gameover()
def gameover(self):
self.show()
print('你输咯')
input()
def win(self):
self.show()
print('你赢了,呵呵,呵呵')
input()
def check(self):
for i in range(4):
for j in range(4):
if self.t1[i][j] ==2048:
self.win()
def move(self):
print('w 上移,a左移,s下移,d右移,')
step = input('。◕ᴗ◕。◞✺')
if step == ('w' or 'W'):
self.up()
elif step == ('a' or 'A'):
self.left()
elif step == ('s' or 'S'):
self.down()
elif step == ('d' or 'D'):
self.right()
else:
print('输入错误')
move()
if __name__ == '__main__':
game = game2048()
game.creat()
game.creat()
game.show()
while True:
game.move()
game.check()
game.creat()
game.show()
|