Before the game 2048 fire, just in other languages to write a, now learning python, just think up, then decided to write a 2048 with Python, because did not learn the interface programming in Python, so wrote an extremely simple interface 2048. Game 2048 the principle and implementation are not difficult, just can take to practiced hand, if do not know this game, can go online check, or download a to mobile phone to play, I do not say its principle. I know not to put the picture, we have no interest, the following first put a game molding diagram, and then we are in terms of how to step by step with the most basic knowledge to achieve.
First, the matrix of generating 4*4
The first step of the game is to generate a 4*4 matrix, as the main interface of our game, in fact, it is relatively simple, here used the most primitive method, directly with
Print it out. First we're going to create a 4*4 two-dimensional list of all 0, and then use some of the characters like ' ┌├└,┤,┘┐│,─,┬,┴ ' to make our borders, so let's look at the implementation of the Code.
matix=[[for I in range () [] for I in range ()] # generates a list of * in a list-derived initialization, and the list element is all the function of the # Notzero: The game interface is not zero when it is displayed, when the time, let it show empty, Def N Otzero (s): return S if s!= else ' # not 0 words returned itself, otherwise return ' Def display (): # Display interface function, with ┌├└,┤,┘┐│,─, ┬,┴ the display border, in the middle shows the element print in the matrix ("\r\┌──┬──┬──┬──┐\n\│%s│%s│%s│%s│\n\├──┬──┬──┬──┤\n\│%s│%s│%s│%s│\n\ ├──┬──┬──┬──┤\n\│%s│%s│%s│%s│\n\├──┬──┬──┬──┤\n\│%s│%s│%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 ()
Look at the effect of the above code, is not feel a game frame has been set up, because of the initialization, The matrix element is zero, the following figure also does not show 0, is not very simple, a game interface is we set up well, but after all, did not learn the interface, So let's not complain about how ugly the interface is.
Second, initialize the generation of random numbers
Every time this game starts randomly generates two random numbers 2 or 4 in a matrix above, then how do we implement a random number 2 or 4 in a random position in the matrix above, of course, using the random module we learned before and Pmod (), Let's take a look at how to implement a function with the random module.
DEF init (): # initialization Matrix Initnumflag = while : k = if Random.randrange (,) > Else # When generating a random number greater than k= otherwise k= generated And the probability is: s = Pmod (Random.randrange (,),) # Generate matrix initialization subscript such as Pmod (,), S is (,) exactly can be used as matrix subscript if matix[s[]][s[]] = =: c10/># is only assigned when its value is not, avoid repeating the second value matix[s[]][s[]] = k Initnumflag + = if Initnumflag = =: # When initnumflag== words indicate that two random numbers in the matrix have been generated, exit the Loop Breakinit () display ()
Take a look at the effect of the above code, is not already in two random positions generated two numbers, if you have time to try, you can see each execution, appear in the matrix above the position is not the same, and each occurrence of the number is not the same, Because I set above the probability of 2:4 appears 9:1 so most of the time appears 2, which is also the need of the game. Here the matrix can be moved, the function of the game can be said to complete half.
Third, the game logic part of the implementation
If you play this game, you will know that every time you move up and down in the game, such as moving like down, all the numbers will move down, hit the same number, will be a new number, such as 2 and 2 hit, will generate 4, and then randomly in other locations to generate a 2 or 4, The same way 4 and 4 encounter the words will also generate 8, until the synthesis of 2048 games even if the success, or the matrix of the number can not move that is game over. Of course, we play games on the mobile phone, casually swipe, all the numbers can slide in one direction, but there is no interface, the conditions are more difficult, so you can only read from the console user input letters, and then each to determine where to move, So we're going to write 4 functions to handle the user's move up and down, so that after a function is processed each time the user moves, how to add a random number, the following first write a pseudo-code to explain the process
Def addrandomnum (): #每次移动后随机在矩阵中在生成一个数 pass def movedown (): #向上移动的处理函数 pass<b R> addrandomnum () #移动处理完成后, randomly generates a number Def moveLeft (): #向左移动的处理函数 pass addrandomnum () d EF moveUp (): #向上移动的处理函数 pass addrandomnum () def moveright (): #向右移动的处理函数 Pass Addrandomnum () def main (): While flag: #定义一个死循环, read the input of the user continuously, then make a judgment, see where to move d = input (' (↑:w) (↓:s) (←: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
Above is a paragraph in order to understand the pseudo-code, the following we look at how to implement the mobile processing function, here is the most difficult part of the game, complete this part, the whole game is basically implemented, here I take the downward moving processing function as an example, the other is the same, when the user input downward movement, All the numbers move down, and if you hit the same number, a number block moves to a block with no numbers. Here need to use loop implementation, there are 4 columns so the outermost loop has 4 times, each column inside and need to loop processing, the following to see how the concrete implementation,
Def addrandomnum (): # like initializing a random number, just generate a random number while : k = if Random.randrange (,) > E LSE s = Pmod (Random.randrange (,),) if matix[s[]][s[]] = =: matix[s[]][s[]] = k break display () # random number added after the completion of the direct call to the display function, directly display the game Interface Def MoveDown (): #处理向下移动的函数 for i in Range (): #外层次循环处理例, inner Layer Two layers loop, to process adjacent two numbers for J in Range (,-): for K in range (J-,-,-): if matix[k][i] >: # start with the bottom number of adjacent two numbers if matix[j][i] = =: Matix[j][i] = matix[k][i] # If the following number is empty, the above number is not empty to move the above number to the following number matix[k][i] = elif matix[j][i] = = Matix[k][i]: # If the adjacent two numbers are equal Words, and then, and put above the zero, the following number becomes twice times Matix[j][i] *= matix[k][i] = break addrandomnum () # randomly generate a number after the move is complete
After writing down the movement of the processing function, then to the other direction of the move function is the same, according to write, you can, to the most difficult part of the game to complete, you can say that victory is in front of us, OK before this, we also need to deal with other problems, that is, every move after the game is not Over, there is a definition of a variable to record the score, which is relatively simple to implement.
Iv. Game record score and check whether the game is over
The end of the game is the symbol of all the number is not 0, and all the adjacent number can not be merged, according to this we could write a function to determine whether the game GG, as for the score record, we just define a variable, and then each time there is a time, add a certain score. Let's look at the implementation of the check function.
def check (): for I in range (4): #按每一排循环4 times for J in Range (3): # If 0 exists in the matrix, or if there are adjacent numbers, the game can also be Continuation line, otherwise is 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
Five, complete game source
Completed the above section, the entire game process is realized, the following is attached to the entire game source code. There are a lot of games are not perfect, such as the game if there are 2048 words, it means the player wins, the game is over, but I do not do the processing here, so this game can play until 4096 .... No end, unless you are in the game GG, to deal with is also very simple, you can also exist in the matrix file, complete a game archive function. If you are interested, let's make it a little bit.
Import randomscore = 0 # record game score Matix = [[0 for I in range (4)] for I in range (4)] # Initialize generate a list of 4*4 D EF 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 (matix[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 W Hile 1:k = 2 if Random.randrange (0, ten) > 1 Else 4 # randomly generated 2 or 4 s = pmod (Random.randrange (0, 16), 4) # Generate matrix-initialized subscript if MATIX[S[0]][S[1]] = = 0: # is only assigned if its value is not 0, avoid repeating the second value matix[s[0]][s[1]] = k Initnumflag + = 1 if Initnumflag = = 2:break display () def addrandomnum (): #处理完移动后添加一个新的随机数 while 1:k = 2 I F random.randrange (0, ten) > 1 else 4 s = pmod (Random.randrange (0,), 4) if matix[s[0]][s[1]] = = 0:matix[s [0]] [S[1]] = k break display () def check (): #检查游戏是否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 (): # Move the handler to the right 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] #将当前数作为score加上 Matix[i][k] = 0 Break addrandomnum () def moveUp (): Global score for I in Range (4): for J in Range (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]: Mati X[j][i] *= 2 score + matix[j][i] matix[k][i] = 0 Break addrandomnum () def movedown (): Glo Bal 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 ad Drandomnum () 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 AddRan Domnum () def main (): Print ("\033[33;1mwelcome to the Game of 2048!\033[0m"), flag = True init () while flag: #循环的标志 print (' \033[33;1m you score:%s\033[0m '% (score)) d = input (' \033[33;1m (↑ : w) (↓:s) (←:a) (→:d), q (uit): \033[0m ') #不断处理用户输入 if d = = ' A ': MoveLeft () If not check (): #检查游戏是否GG print (' GG ') flag = False # GG directly exit elif D = = ' s ': MoveDown () if not check (): Print (' GG ') flag = False elif D = = ' W ': MoveUp () if not check (): Print (' GG ') flag = False elif D = = ' d ': moveright () if not ch Eck (): Print (' GG ') flag = False elif D = = ' Q ': # exit Break Else: # Do not process the user's other input passif __name__ = = ' __main__ ': Main ()
Finally, attach a picture to the end
The above is a small part of the introduction of the use of Python to write a non-interface 2048 small game, I hope that we have some help, if you have any questions please give me a message, small series will promptly reply to you. Thank you very much for your support for topic.alibabacloud.com!