Python Novice implementation 2048 small game

Source: Internet
Author: User
Contact Python soon, see a lot of people write 2048, oneself also tinkering with one, mainly is familiar with Python syntax.

The program uses Python3 write, code 150 lines around, based on the console, the arrow keys using the input character simulation.

Demo pictures

2048.py

#-*-Coding:utf-8-*-#!    /usr/bin/python3 Import Random v = [[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]) print (' {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]), ' Total score: ', score) def in  It (v): ' Randomly distributed grid value ' for I in range (4): v[i] = [Random.choice ([0, 0, 0, 2, 2, 4]) for X in range (4)] def align (vList, direction): "The number of Qife zeros Direction = = ' Left ': aligned to the right, e.g. [8,0,0,2] after left alignment [8,2,0,0] Direction = ' right ':    Align Right, for example [8,0,0,2] right-aligned [0,0,8,2] "# Remove 0 for I in range from list (Vlist.count (0)): Vlist.remove (0) # 0 removed Zeros = [0 for x in range (4-len (vList))] # complements 0 if direction = = ' Left ' on a non-0-digit side: vlist.extend (zeros) ElsE:vlist[:0] = Zeros def addsame (vList, direction): "' finds the same and adjacent numbers in the list to add, finds the matching conditional return true, otherwise returns false, and also returns the increased score    Direction = = ' Left ': Find the same and adjacent two digits, the left digit double, the right digit 0 Direction = = ' Right ': Search from left to right, find the same and adjacent two digits, double right digit, left digit 0                 "' score = 0 if direction = = ' Left ': 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} RET Urn {' bool ': False, ' score ': Score} def handle (vList, direction): ' Process data in one row (column), get the final number status value for that row (column), return score VList: List structure, save The data in one row (column) is stored direction: Move direction, use direction ' left ' both up and down, use ' right ' Totalscore = 0 align (vList, direction) res Ult = Addsame (VList, direction) while result[' bool '] = = True:totalscore + = result[' score '] align (vList, direction) result = Addsame (vList, direction) return Totalscore def operation (v): "' re-computes the matrix state value according to the direction of movement and records the score ' ' Totalscore = 0 Gameover = False Direction = ' Left ' op = input (' operator: ') if op in [' A ', ' a ']: # to move direction        = ' Left ' for row in range (4): Totalscore + = handle (V[row], direction) elif op in [' d ', ' d ']: # Move Right Direction = ' Right ' for row in range (4): Totalscore + = handle (V[row], direction) elif op in [' W ', ' W ']: # Move Up direction = ' left ' for Col in Range (4): # Copy a column from the matrix into a list and then process vList = [            V[row][col] for row in range (4)] Totalscore + = handle (vList, direction) # overwrites the values in the original matrix from the numbers in the processed list For row in range (4): V[row][col] = Vlist[row] elif op in [' s ', ' s ']: # Move Down direction = ' RI Ght ' for Col in RAnge (4): # ditto vList = [V[row][col] for row in range (4)] Totalscore + = handle (VList, Direc  tion) 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 ') return {' Gameover ': Gameover, ' score ': Totalscore} # Count the number of empty spaces N n = 0 for q in V:n + = Q.count (0) # when there is no remaining white space, the game ends if N = = 0:gameover = True return {' G Ameover ': 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]) # Generate random number K, previous production The raw 2 or 4 will be filled with the K blank area k = Random.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 ': Totalscore} init (v) score = 0print (' input:w (UP) S (off) A (left) D (right), press
 
  
   .') While True:display (V, score) result = operation (v) if result[' gameover '] = = True:print (' Game over, you f        ailed! ') Print (' Your total score: ', score) Else:score + = result[' score '] if score >= 2048:print (' G            Ame over, you Win!!! ') Print (' Your total score: ', score)
  
 

The above is this article to share all the code, I hope we can learn python to help.

  • 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.