This article mainly describes how to use Python to write an unbounded 2048 game. if you need more information, refer to the previous 2048 games, you can write one in other languages, now I want to learn python, just think of it, I decided to use python to write a 2048. since I have never learned interface programming in python, I wrote an extremely simple interface-less 2048. The principle and implementation of game 2048 are not difficult. you can just use it to train your hands. if you don't know about the game, you can check it online or download it to your mobile phone, I will not talk about its principles. I know that if you don't want to show a picture, you will have no interest at all. Next, let's first put a game picture, and then let's talk about how to implement it step by step with the most basic knowledge.

Matix = [[for I in range ()] # initialize and generate a * list using list derivation. the list elements are all # Functions of notzero: it is displayed only when the game interface is non-zero. in this case, make it empty. def notzero (s): return s if s! = Else ''# return itself if it is not zero; otherwise, return ''def display (): # display the interface function. use the functions provided by ┌ ├, ┤, ┘ │,-, ┬, border, print ("\ r \ ── ┬ print \ n \ │ % s │ \ n in the middle \ ├ ── ┬ ── ┤ \ n \ │ % s │ \ n \ ├ ── ┬ ── ┤ \ n \ │ % s │ \ n \ ── ┬ ┤ %\ n \ │ % s │ % s │ \ n \ ── ┴ ── ┘ "\ % (notzero (matix [] []), notzero (matix [] []), notzero (matix [] []), notzero (matix [] []), \ notzero (matix [] []), notzero (matix [] []), notzero (matix [] []), notzero (matix [] []), \ notzero (matix [] []), notzero (matix [] []), notzero (matix [] []), notzero (matix [] []), \ notzero (matix [] []), notzero (matix [] []), notzero (matix [] []), notzero (matix [] []),) display ()

Let's take a look at the effect of the code above. does it feel like a game framework is ready? because the matrix elements are all zero during initialization, the following figure does not show 0. is it very simple, we have built a game interface, but we have never learned the interface, so don't complain about how ugly the interface is.

Def init (): # initialization matrix initNumFlag = while: k = if random. randrange (,)> else # When the generated random number is greater than k = Otherwise k = the probability of generating and s = pmod (random. randrange (,),) # Generate the subscript for matrix initialization, for example, pmod (,), s is (,) it can be used as the matrix subscript if matix [s [] [s [] ==:# it is assigned only when its value is not the same, avoid duplicate matix [s [] [s [] = k initNumFlag + = if initNumFlag =: # When initNumFlag =, the two random numbers in the matrix are generated, and the loop breakinit () display () is exited ()

Let's take a look at the effect of the above code. have two numbers already been generated at two random locations? if you have time to try it, you can see that each execution is, the positions on the matrix are different, and the numbers displayed each time are different. because I set the probability of to, 2 is usually displayed, which is also the need of the game. Now, the matrix can be moved, and the game's functionality is half done.

Def addRandomNum (): # A Number pass def moveDown () is generated randomly in the matrix after each move: # The processing function pass to move up

AddRandomNum () # after the mobile processing is completed, a number def moveLeft () is randomly generated: # The processing function to move to the left pass addRandomNum () def moveUp (): # The processing function pass addRandomNum () def moveRight (): # The processing function pass addRandomNum () def main (): while flag: # defines an endless loop, read User input continuously, and then make judgments to see where to move d = input ('(rows: w) (rows: s) (rows: a) (→: d), q (uit): ") if d = 'a': moveLeft () elif d = 'S': moveDown () elif d = 'w ': moveUp () elif d = 'd': moveRight () elif d = 'Q': break else: pass

The above is a piece of pseudo code for understanding. let's take a look at how to implement a mobile processing function. here is the most difficult part of the game, the entire game is basically implemented. here I use the downward movement processing function as an example. everything else is the same. when the user inputs the downward movement, all the numbers move downward, if the same number is matched, the square with a number moves toward the square without a number. Here we need to implement it in a loop. There are four columns, so there are four loops in the outermost layer, and each column needs to be processed cyclically. let's take a look at how to implement it,

Def addRandomNum (): # It is the same as the random number generated during initialization, except that a random number is generated here while: k = if random. randrange (,)> else s = pmod (random. randrange (,),) if matix [s [] [s [] ==: matix [s [] [s [] = k break display () # after the random number is added, the display function is called directly to display the game interface def moveDown (): # function for processing downward movement in range (): # External level loop processing example: Two layer loops in the inner layer are used to process two adjacent numbers for j in range (,-): for k in range (j -,-,-): if matix [k] [I] >:# process two adjacent numbers starting from the lowest number. if matix [j] [I] =: matix [j] [I] = matix [k] [I] # if the number below is null, if the number above is not blank, move the number above to the number below matix [k] [I] = elif matix [j] [I] = matix [k] [I]: # If the two adjacent numbers are equal, they are connected to and set the input value to zero, the number below is doubled. matix [j] [I] * = matix [k] [I] = break addRandomNum () # A random number is generated after the movement is completed.

After writing down the processing function, the moving function in other directions will also be the same. just write it, and the most difficult part of the game will be completed here, it can be said that victory is just in sight. well, before that, we still need to deal with other problems, that is, we need to check whether the Game is Over after every move, another is to define a variable to record scores. these implementations are relatively simple.

**4. record game scores and check whether the game is over**

The ending sign of the game is that all numbers in the matrix are not 0, and all adjacent numbers cannot be merged. Based on this, we can write a function to determine whether the game is GG, as for the score record, we only need to define a variable and add a certain score each time when there is a sum. Let's take a look at the implementation of the function.

Def check (): for I in range (4): # Loop 4 times in each row for j in range (3): # if 0 exists in the matrix, or if there is an adjacent number, the game can continue to work, otherwise, GG if matix [I] [j] = 0 or matix [I] [j] = matix [I] [j + 1] or matix [j] [I] = matix [j + 1] [I]: return True else: return False

**V. complete game source code**

After completing the above part, the entire game process is implemented. the source code of the entire game is attached below. There are still many imperfections in the game. for example, if the game shows 2048, it means the player wins and the game ends, but I have not done anything here, so this game can play until 4096 .... it's not over. unless you have GG in the game, it's easy to process. you can also store the matrix in a file to complete the game archiving function. If you are interested, implement it.

Import randomscore = 0 # record the game's score matix = [[0 for I in range (4)] for I in range (4)] # initialize and generate a 4*4 list def notzero (s): return s if s! = 0 else ''def display (): print ("\ r \ ── ┬ ┐ \ n \ │ % 4s │ % 4s │ % 4s │ % 4s │ \ n \ ── ┬ ── ── ┤ \ n \ │ % 4s │ % 4s │ % 4s │ % 4s │ \ n \ ── ┬ ┤ \ n \ │ % 4s │ % 4s │ % 4s │ % 4s │ \ n \ ── ┬ ── ┤ \ n \ │ % 4s │ % 4s │ % 4s │ % 4s │ \ n \ ── ── ┴ ┘ "\ % (notzero (matix [0] [0]), notzero (matix [0] [1]), notzero (matix [0] [2]), notzero (matix [0] [3]), \ notzero (matix [1] [0]), notzero (matix [1] [1]), notzero (matix [1] [2]), notzero (matix [1] [3]), \ notzero (mati X [2] [0]), notzero (matix [2] [1]), notzero (matix [2] [2]), notzero (matix [2] [3]), \ notzero (matix [3] [0]), notzero (matix [3] [1]), notzero (matix [3] [2]), notzero (matix [3] [3]),) def init (): # initialization matrix initNumFlag = 0 while 1: k = 2 if random. randrange (0, 10)> 1 else 4 # randomly generate 2 or 4 s = pmod (random. randrange (0, 16), 4) # Generate the subscript for matrix initialization if matix [s [0] [s [1] = 0: # assign a value only when the value is not 0. avoid the second value repeating matix [s [0] [s [1] = k initN UmFlag + = 1 if initNumFlag = 2: break display () def addRandomNum (): # Add a random number after processing the movement while 1: k = 2 if random. randrange (0, 10)> 1 else 4 s = pmod (random. randrange (0, 16), 4) if matix [s [0] [s [1] = 0: matix [s [0] [s [1] = k break display () def check (): # check whether the game GG for I in range (4 ): for j in range (3 ): if matix [I] [j] = 0 or matix [I] [j] = matix [I] [j + 1] or matix [j] [I] = matix [j + 1] [I]: return True Else: return Falsedef moveRight (): # global score for I in range (4): for j in range (3, 0,-1 ): for k in range (j-1,-1,-1): if matix [I] [k]> 0: if matix [I] [j] = 0: matix [I] [j] = matix [I] [k] matix [I] [k] = 0 elif matix [I] [j] = matix [I] [k ]: matix [I] [j] * = 2 score + = matix [I] [j] # add the current number as the score plus matix [I] [k] = 0 break addRandomNum () def moveUp (): global score for I in range (4): for j in rang E (3): for k in range (j + 1, 4): if matix [k] [I]> 0: if matix [j] [I] = 0: matix [j] [I] = matix [k] [I] matix [k] [I] = 0 elif matix [k] [I] = matix [j] [I ]: matix [j] [I] * = 2 score + = matix [j] [I] matix [k] [I] = 0 break addRandomNum () def moveDown (): global score for I in range (4): for j in range (3, 0,-1): for k in range (j-1,-1,-1 ): if matix [k] [I]> 0: if matix [j] [I] = 0: matix [j] [I] = matix [k] [I] matix [K] [I] = 0 elif matix [j] [I] = matix [k] [I]: matix [j] [I] * = 2 score + = matix [j] [I] matix [k] [I] = 0 break addRandomNum () def moveLeft (): global score for I in range (4): for j in range (3): for k in range (1 + j, 4 ): if matix [I] [k]> 0: if matix [I] [j] = 0: matix [I] [j] = matix [I] [k] matix [I] [k] = 0 elif matix [I] [j] = matix [I] [k ]: matix [I] [j] * = 2 score + = matix [I] [j] matix [I] [k] = 0 break addRandomNum () Def main (): print ("\ 033 [33; 1 mWelcome to the Game of 2048! \ 033 [0 m ") flag = True init () while flag: # print ('\ 033 [33; 1 m You Score: % s \ 033 [0m' % (score) d = input ('\ 033 [33; 1 m (cost: w) (cost: s) (cost:) (→: d), q (uit): \ 033 [0m') # process user input continuously if d = 'a': moveLeft () if not check (): # check whether the game has GG print ('GG ') flag = False # directly exit elif d = 'S': moveDown () if not check () if GG (): print ('GG ') flag = False elif d = 'w': moveUp () if not check (): print ('GG ') flag = False elif d = 'd': moveRight () if not check (): print ('GG ') flag = False elif d = 'Q ': # exit break else: # do not process other user input passif _ name _ = '_ main _': main ()

Finally, the end of the attached image is

The above section describes how to use Python to write an unbounded 2048 game. I hope it will be helpful to you. if you have any questions, please leave a message and I will reply to you in a timely manner. I would like to thank you for your support for PHP chinnet!

For more Python-related articles on an unbounded 2048 game, please follow the PHP Chinese network!