Python beginners implement 2048 games and python2048 games

Source: Internet
Author: User

Python beginners implement 2048 games and python2048 games

Not long after I got started with Python, I saw a lot of people write 2048, but I was also familiar with Python syntax.

The program uses Python3 to write the code about 150 lines. Based on the console, the arrow keys use the input characters for simulation.

Demo Image

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 }'. format (v [0] [0], v [0] [1], v [0] [2], v [0] [3]) print }'. format (v [1] [0], v [1] [1], v [1] [2], v [1] [3]) print }'. format (v [2] [0], v [2] [1], v [2] [2], v [2] [3]) print }'. format (v [3] [0 ], V [3] [1], v [3] [2], v [3] [3]), 'total score: ', score) def init (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 ): ''' alignment a non-zero number ction = 'left': Align to the left. For example, [,] After the left alignment, [,] direction = 'right ': right alignment, for example, [,] After right alignment [,] ''' # Remove 0 for I in range (vList. count (0): vList. remove (0) #0 zeros = [0 for x in range (4-len (vList)] # Add 0 if ction = 'left': vList on the side of a non-zero number. extend (zeros) else: vList [: 0] = zeros def addSame (vList, direction): ''' Add the same and adjacent numbers in the list, returns True if the condition is met. Otherwise, returns False. Also, returns the added score direction = 'left': right-to-left lookup to find the same and adjacent two numbers, double the number on the left, and set 0 ction = 'right' to the right. Search for the two numbers that are the same and adjacent to the right, and double the number on the right, 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} return {'bool ': False, 'score': score} def handle (vList, direction): ''' processes data in a row (column, obtain the numeric status value of the final row (column), and return the score vList: List structure, which stores the data direction in a row (column): moving direction, use 'left' in both the upward and left directions, and 'right' in both the right and downward directions. ''totalscore = 0 align (vList, direction) result = addSame (vList, direction) while result ['bool '] = True: totalScore + = result [' SC Ore '] align (vList, direction) result = addSame (vList, direction) return totalScore def operation (v): ''' recalculates the matrix state value based on the moving direction, and record the score ''' totalScore = 0 gameOver = False ction = 'left' op = input ('operator: ') if op in ['A', 'a']: # Move ction = 'left' for row in range (4): totalScore + = handle (v [row], direction) elif op in ['D ', 'D']: # Move ction = 'right' for row in range (4): totalScore + = ha Ndle (v [row], direction) elif op in ['w', 'w']: # Move up direction = 'left' for col in range (4 ): # copy a column in the Matrix to a list. After that, vList = [v [row] [col] for row in range (4)] totalScore + = handle (vList, direction) # overwrite the value in the original matrix for row in range (4) from the number in the processed list ): v [row] [col] = vList [row] elif op in ['s ','s']: # Move down direction = 'right' for col in range (4): # Same as 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 ') return {'gameover': gameOver, 'score ': totalScore} # count the number of blank areas N = 0 for q in v: N + = q. count (0) # if the remaining blank area does not exist, the game ends if N = 0: gameOver = True return {'gameover': gameOver, 'score ': totalScore} # the probability of occurrence of 2 and 4 is 3/1 to generate random numbers 2 and 4 num = random. choice ([2, 2, 2, 4]) # Generate a random number k. The 2 or 4 generated in the previous step will be filled in 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 (Left) D (Right), press <CR>. ') while True: display (v, score) result = operation (v) if result ['gameover'] = True: print ('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)

The above is all the code shared in this article. I hope it will help you learn Python.

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.