python command line version 2048 games

Complete code, please move Python implements command line version 2048.

It is reasonable to see here and write here, you should be considered to have completed the introduction, so next, you should use the knowledge learned by the introduction to write a command-line version of 2048 game.

The logic of 2048 is nothing more than the operation of 4x4 squares. There is a number in each square. We can operate these numbers to move. If two identical numbers collide under our operation, they can be merged.

And this 4x4 square is nothing more than a matrix.

Our operation can be understood as input characters. wsad stands for up, down, left and right, y stands for OK, and n stands for cancel.

python's function to receive characters is input, for example

>>> x = input("input a number")
input a number5
>>> x
'5'


To create a matrix, np.zeros([4,4]).astype(int) can be used to represent the creation of a matrix 4 × 4 4\times4 four × All 0 matrices of 4 and transformed into shaping.

There are only 16 elements in the matrix. Although the cycle efficiency is low, it is enough to meet people's operation speed.

Operation logic

2048 has only four gesture actions, i.e. up, down, left and right. The results caused by these four actions can be attributed to the operation of a single line or column, and then to the operation of a list.

For example, for [0,2,2,0], if you merge to the right, the output is [0,0,0,4], and if you merge to the left, the output is [4,0,0,0].

The implementation method is as follows

def addZeros(lst:list,flag:bool=True):
zeros = [0]*(4-len(lst))
return zeros+lst if flag else lst+zeros

# When flat is true, fill 0 on the left; Otherwise, fill the right
def rmZero(lst, flag=True):
lst = [x for x in lst if x]
end = len(lst)-1
if end < 1:
index = range(end) if flag else range(end,-1,-1)
iter = 1 if flag else -1
for i in index:
if lst[i] == lst[i+iter]:
lst[i] *= 2
lst[i+iter] = 0
lst = [x for x in lst if x]


Then, rmZero is executed for both rows and columns. Where wsad represents up, down, left and right respectively

# w. S, a and D are up, down, left and right respectively
def updateMat(mat,op):
flag = op in "sd"
if op in "ws":
for i in range(4):
mat[:,i] = rmZero(mat[:,i],flag)
else:
for i  in range(4):
mat[i,:] = rmZero(mat[i,:],flag)
return mat


These three functions have completed the interaction logic of 2048. The next step is to embed the updateMat function into the game process.

initialization

Before the 2048 game starts, you need to initialize a 4x4 matrix, and then before each operation, you need to randomly generate a number at the position of 0 in the matrix. The value range of randomly generated numbers determines the difficulty of the game, so the generation method is also flexible. A common generation method is given below

def addNew(mat):
i,j = randint(4),randint(4)
while(mat[i,j]!=0):
i,j = randint(4),randint(4)
else:
x = randint(1,100)
x = 7 - np.floor(np.log2(x))
mat[i,j] = int(2**x)
print(mat)


Interactive operation

Then there is interactive operation. asdw means operation and q means exit.

def InputNew(mat):
op = input("input operator:")
if op in "asdw":
newMat = updateMat(mat*1,op)
if np.max(np.abs(mat-newMat))==0:
print("Invalid operation")
return mat,"Error"
else:
return newMat,"True"
if op == 'q':
return mat, "Exit"
print("Invalid Input")
return mat, "Error"


main

if __name__ == "__main__":
while(1):
newMat,flag = InputNew(mat)
while flag=="Error":
newMat,flag = InputNew(mat)
if flag == "Exit":
break
mat = newMat
print(mat)
print('-'*30)

if np.max(mat)==2048: flag == "win"
if np.min(mat)!=0: flag == "lose"
if flag in ["win","lose"]:
if input(f"you {flag}, play again? ")=="y":
mat *= 0
else: break


Posted by haijie1984 at Nov 14, 2021 - 9:03 PM Tag: Python Back-end