Python Practice--2048

Source: Internet
Author: User

1. Introduction2048 This period of time the fire does not ah, we all have to imitate, "contending", so there are various technical version number: In addition to the phone version number, there is a C language version, QT version, web version, Java version, C # version, and so on, just I contact Python soon, so I got a python version- 2048 of the console, just familiar with the Python syntax, program execution effects such as the following:
Figure 1 Python version console 2048 execution

program code with a gaze of about 150 lines, the use of some python built-in data types of operations to save a lot of code. The following talk about my writing ideas, and finally will give the source code.
2.2048 realization Ideas
2.1 Game RulesThis game is very good to play, simple to move the key to let the number overlay, and to obtain the number of these numbers after each overlay score, when the number 2048 appears when the game wins. At the same time, each time you move the arrow keys, you will randomly generate a number 2 or 4 in the blank area of the 4*4 grid, assuming the squares are filled with numbers, then Gameover.

  2.2 Realization IdeasAll operations of the game are carried out around a 4*4 matrix, each time from the user interface to get the user's operation (that is, the direction of movement), and then once again calculate the state of the 4*4 matrix, and finally refresh the user interface display 4*4 matrix of the latest state, continuous cycle of the process, Until 2048 or no blank squares appear, here is a process:
I am writing a console program with no UI interface, so the characters (W/S/A/D) represent the input of the arrow keys, and the number 0 represents the blank squares. Next is the calculation section, which moves to the left as an example, when the 4*4 matrix receives the instruction to the left, it should overlay the number of each row to the left, define a row of overlays as function handle (list, direction), and its first parameter is used to store a row (column) in the 4*4 matrix. The second parameter indicates the direction of the move (up or down).
This allows the matrix to be computed when the left and right keys are moved: Iterate through each row of the matrix and overlay the numbers of each row along the left or right. For row in Matrix:handle (row, direction)
For moving the arrow keys up or down, because the matrix is stored in rows, the columns in the matrix cannot be processed directly, and can be handle () by using the above function. For each column in the matrix, copy it to a list, and then call the handle () function to overlay the list, and then copy the superimposed new list back to the column in the original matrix, which is logically equivalent to the following code operation. For Col in Matrix:handle (col, direction)
The role of the handle (row, direction) function is to overlay numbers in a row in a specified direction, see the following examples:
Move direction Before moving After moving
Handle (x, ' left ') x = [0, 2, 2, 2] x = [4, 2, 0, 0]
Handle (x, ' left ') x = [2, 4, 2, 2] x = [2, 8, 0, 0]
Handle (x, ' right ') x = [2, 4, 2, 2] x = [0, 0, 2, 8]

Implementing the handle (row, direction) function
According to the above introduction, the realization of handle function is the key. Careful observation of the superposition process, which is composed of two sub-processes: (1) align (row, direction)  Aligns the numbers in the list row along the direction direction, for example: x = [0, 4, 0, 2]align (x, ' left ') after x = [4, 2, 0, 0] after align (x, ' right ') x = [0, 0, 4, 2]
(2)  addsame (row, direction) Find Same and adjacentThe number. Suppose to find, will be one of the double, there is a set of 0 (assuming that direction is ' left ' to double, right side 0, assuming direction as ' right ', will double on the left side 0), and return true; otherwise, return false. For example: x = [2, 2, 2, 2]addsame (x, ' left ') after x = [4, 0, 2, 2] returns true after Addsame (x, ' left ') after x = [4, 0, 4, 0] returns true again ad Dsame (x, ' left ') after x = [4, 0, 4, 0] returns False
With the above two sub-functions, it should not be difficult to implement. With these two sub-functions, the function handle () is very well implemented, such as the following: Handle (row, direction): Align (row, direction) result = Addsame (row, dire ction) While result = = true:align (row, direction) result = Addsame (row, di Rection)
The following is a practical example of the processing of the handle function: x = [2, 4, 2, 2] calls handle (x, ' right '), variable x changes the process: Align (x, ' right '), [2, 4, 2,    2]addsame (x, ' right '), [2, 4, 0, 4], and return truealign (x, ' right '), [0, 2, 4, 4] Addsame (x, ' right '), [0, 2, 0, 8], and return truealign (x, ' right '), [0, 0, 2, 8 ] Addsame (x, ' right '), [0, 0, 2, 8], return false finally get x = [0, 0, 2, 8] The most basic part has been said, the following Just post the code, because the code is not too much to directly post it.
3. Code
These are all code, saved in a single file can be executed, execution environment python3.0+
#-*-Coding:utf-8-*-#! /usr/bin/python3import RANDOMV = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]def display (V, score) : ' Display interface ' ' Print (' {0:4} {1:4} {2:4} {3:4} '. Format (v[0][0], v[0][1], v[0][2], v[0][3]) prin T (' {0:4} {1:4} {2:4} {3:4} '. Format (v[1][0], v[1][1], v[1][2], v[1][3])) print (' {0:4} {1:4} {2:4} {3:4} '. Format (v[2] [0], v[2][1], v[2][2], v[2][3]) print (' {0:4} {1:4} {2:4} {3:4} '. Format (v[3][0], v[3][1], v[3][2], v[3][3]), ' T Otal score: ', score) def init (v): "' Random distribution grid value ' ' For I in range (4): v[i] = [ra Ndom.choice ([0, 0, 0, 2, 2, 4]) for x in V[i]]def align (vList, direction): "To Qife zero number direction = = ' Left ': Alignment, such as [8,0,0,2] left-aligned [8,2,0,0] Direction = = ' right ': aligned to starboard, such as [8,0,0,2] right-aligned [0,0,8,2] ' # Remove 0 F from the list or I in range (Vlist.count (0)): Vlist.remove (0) # removed 0 zeros = [0 for x in range (4-len (vLiST)] # on a side of a non-0 digit supplement 0 if direction = = ' Left ': vlist.extend (zeros) else:v                List[:0] = Zeros def addsame (vList, direction): "' Find the same and adjacent numbers in the list to add, find the matching conditional return true, otherwise return false, also return the added? ' Fraction at the same time Direction = = ' Left ': Find the same and adjacent two numbers with the same and neighboring numbers, double the left-hand number and 0 direction = = ' Right ': Search from left to right, find the same and adjacent two numbers, double the right-hand number,                        Left side digit 0 "' score = 0 if direction = = ' Ieft ': For I in [0, 1, 2]: If vlist[i] = = vlist[i+1]! = 0:vlist[i] *= 2 vlist[i+1]        = 0 Score + = Vlist[i] Return {' bool ': True, ' score ': score}                                Else:for I in [3, 2, 1]: if vlist[i] = = vlist[i-1]! = 0:                          Vlist[i-1] *= 2 vlist[i] = 0 score + + vlist[i-1]      return {' bool ': True, ' score ': score} return {' bool ': False, ' score ': Score}def handle (VList, direction): "Process data in one row (column), get the number state value of the row (column) Finally, return the score vList: List structure, store the data in one row (column) direction: Move direction, use the direction ' left ' both up and down, use ' rig ' for right and down  HT "' Totalscore = 0 align (vList, direction) result = Addsame (vList, direction) while                result[' bool '] = = True:totalscore + = result[' score '] align (vList, direction)        result = Addsame (vList, direction) return Totalscore def operation (v): "" Calculates the matrix state value once again based on the direction of movement and records the score "' Totalscore = 0 Gameover = False Direction = ' Left ' op = input (' operator: ') if Op in [' A ', ' a ']: # Move direction = ' left ' for row in range (4): t                Otalscore + = handle (V[row], direction) elif op in [' d ', ' d ']: # move Right direction = ' OK ' For row in range (4): Totalscore + = handle (V[row], direction) elif op in [' W ', ' W ']: # Move up dire ction = ' left ' for Col in Range (4): # Copy a column from the matrix into a list and then process the Vlis                        t = [V[row][col] for row in range (4)] Totalscore + = handle (vList, direction) # Overwrite the value in the original matrix from the number in the processed list for row in range (4): v[row][col] = Vlist[row                        ] Elif op in [' s ', ' s ']: # Move Down direction = ' right ' for Col in Range (4): # Ibid. vList = [V[row][col] for row in range (4)] Totalscore + = Han        Dle (vList, direction) for row in range (4): V[row][col] = Vlist[row] Else:print (' Invalid input, please enter a charactor in [W, S, A, D] or the lower ') r Eturn {' Gameover ': GameovEr, ' score ': Totalscore} # Statistics white space number n n = 0 for q in V:n + q.count (0) # No remaining white space exists        When the game is over if N = = 0:gameover = True return {' Gameover ': Gameover, ' score ': Totalscore} # 2 and 4 appear with a chance of 3/1 to generate a random number 2 and 4 num = Random.choice ([2, 2, 2, 4]) # generates a random number k, the previous step resulting in 2 or 4 will be filled with K-blank area k = Ra Ndom.randrange (1, n+1) N = 0 for I in range (4): for J in Range (4): if                                        V[I][J] = = 0:n + = 1 if n = = k: V[I][J] = num break return {' Gameover ': Gameover, ' score ': Totalsco Re}init (v) score = 0print (' input:w (UP) S (off) A (left) D (right), press <cr>. ') While True:display (V, score) result = operation (v) if result[' gameover '] = = True:pri                NT (' Game over, you failed! ') Print (' Your total sCore: ', score) Else:score + = result[' score '] if score >= 2048:                        Print (' Game over, you Win!!! ') Print (' Your total score: ', score)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.