Python novice to achieve 2048 small games _python

Source: Internet
Author: User

Shortly after touching python, I saw a lot of people writing 2048, and I got one, mostly familiar with the python syntax.

The program uses the Python3 write, the code 150 lines around, based on the console, the directional key uses 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} '. Format (3:4], v[3][0], v[3][1], v[3][2]), ' Total v[3][3:  ', Score def init (v): ' Random distribution 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): ' Qife zero number direction = = ' Left ': aligned to the left, such as [8,0,0,2]-aligned after [8,2,0
        , 0] Direction = = ' right ': alignment to the right, such as [8,0,0,2] after right-aligned [0,0,8,2] ' # Remove the 0 for-I in range (Vlist.count (0)) from the list: Vlist.remove (0) # removed 0 zeros = [0 for x in range (4-len (Vlist))] # Add 0 if direction = on one side of non 0 digitsLeft ': vlist.extend (zeros) else:vlist[:0] = Zeros def addsame (Vlist, direction): "" Find the same in the list  And the adjacent number is added to find the eligible return true, otherwise return false, and return the added score direction = = ' Left ': looking from right to to, find the same and adjacent two digits, the left digit doubled, the right digit 0 direction = = ' Right ': Look up from left, find the same and adjacent two digits, the right digit doubled, left digit to 0 ' ' score = 0 if direction = = ' to ": 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 + = Vlis T[i-1] Return {' bool ': True, ' score ': score} return {' bool ': False, ' score ': Score} def handle (Vlist, di rection): ' Process the data in one row (column), get the final number state value of the row (column), return the score Vlist: List structure, store the data in one row (column) direction: Move direction, use the direction ' left ' to the right
  And down all using ' right '  Totalscore = 0 align (vlist, direction) result = Addsame (vlist, direction) while result[' bool '] = = True: Totalscore + = result[' score '] align (vlist, direction) result = Addsame (vlist, direction) Talscore def operation (v): "Recalculates the matrix state value according to the direction of movement and record the score" ' Totalscore = 0 Gameover = False Direct Ion = ' Left ' op = input (' operator: ') if op in [' A ', ' a ']: # Move direction = ' ieft ' for row in RA
        Nge (4): Totalscore + + handle (V[row], direction) elif op in [' d ', ' d ']: # move Right Direction = ' right-hand '
        For row in range (4): Totalscore = handle (V[row], direction) elif op in [' W ', ' W ']: # Move Up  Direction = ' Left ' to Col in range (4): # Copy a column of a matrix into a list and then process the Vlist = [V[row][col] for row  In range (4)] Totalscore + = handle (Vlist, direction) # Overwrite the value in the original matrix with the number from the processed list for row in
             Range (4):   V[row][col] = Vlist[row] elif op in [' s ', ' s ']: # moving down direction = ' right ' for Col in Range (4):
            # ditto vlist = [V[row][col] for row in range (4)] Totalscore + = handle (Vlist, direction) For row in range (4): V[row][col] = Vlist[row] Else:print (' Invalid input, please ente
    R a charactor in [W, S, A, D] or the "lower") return {' Gameover ': Gameover, ' score ': Totalscore} # Statistical blank area number N n = 0 for q in V:n + = Q.count (0) # when there is no remaining blank area, the game End if N = = 0:gameover = True retur n {' Gameover ': Gameover, ' score ': Totalscore} # 2 and 4 probability is 3/1 to generate random numbers 2 and 4 num = Random.choice ([2, 2, 2, 4]) # Generate
            Random number k, the 2 or 4 generated in the previous step will be filled to 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 = 0 print (' input:w (UP) S (down) A (off) D (right), press <CR
".") While True:display (V, score) result = operation (v) if result[' gameover '] = = True:print (' Game over, Y
        Ou failed! ') Print (' Your total score: ', score) Else:score + = result[' score '] if score >=
            T (' Game over, Win!!! ') Print (' Your total score: ', score)

The above is the entire code that this article shares, hope to be able to learn python to be helpful to everybody.

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.