SoFunction
Updated on 2024-10-30

Python implementation of a simple 2048 game

Simple 2048 game

Not much to say, directly on the map, here did not realize the GUI and so on, if necessary, you can realize:

Next is the code module, which the 2048 game turned out to be a lot of the network, I will not write up in detail, are written in the notes inside. The only thing to pay attention to is the need to go first to understand the matrix transpose, here will use the

import random

board = [[0, 0, 0, 0],
         [0, 0, 0, 0],
         [0, 0, 0, 0],
         [0, 0, 0, 0]]


# Print the game interface
def display(board, score):
    print('{0:4} {1:4} {2:4} {3:4}'.format(board[0][0], board[0][1], board[0][2], board[0][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(board[1][0], board[1][1], board[1][2], board[1][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(board[2][0], board[2][1], board[2][2], board[2][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(board[3][0], board[3][1], board[3][2], board[3][3]), ' Score:', score)


# Initialize the game, generate two random 2's in a 4*4.
def init(board):
    # The game first all reset to zero
    for i in range(4):
        for j in range(4):
            board[i][j] = 0
    # Randomly generate two 2-save locations
    randomposition = (range(0, 15), 2)
    board[int(randomposition[0] / 4)][randomposition[0] % 4] = 2
    board[int(randomposition[1] / 4)][randomposition[1] % 4] = 2


def addSameNumber(boardList, direction):
    '''Need to find neighboring identical numbers in the list and add them together,Returns the increased score

    :param boardList: A two-dimensional array of aligned non-zero numbers.
    :param direction: direction == 'left'search from right to left,Find two numbers that are the same and next to each other,Double the number on the left,right-hand numeric display0
                      direction == 'right'Search from left to right,Find two numbers that are the same and next to each other,Double the number on the right,left lateral numeric position (math.)0
    :return:
    '''
    addNumber = 0
    # Left and up operations
    if direction == 'left':
        for i in [0, 1, 2]:
            if boardList[i] == boardList[i+1] != 0:
                boardList[i] *= 2
                boardList[i + 1] = 0
                addNumber += boardList[i]
                return {'continueRun': True, 'addNumber': addNumber}
        return {'continueRun': False, 'addNumber': addNumber}
    # Rightward and downward maneuvers
    else:
        for i in [3, 2, 1]:
            if boardList[i] == boardList[i-1] != 0:
                boardList[i] *= 2
                boardList[i - 1] = 0
                addNumber += boardList[i]
                return {'continueRun': True, 'addNumber': addNumber}
        return {'continueRun': False, 'addNumber': addNumber}


def align(boardList, direction):
    '''Aligning non-zero numbers

    direction == 'left':left justification,for example[8,0,0,2]left justified[8,2,0,0]
    direction == 'right':right justification,for example[8,0,0,2]right justified[0,0,8,2]
    '''
    # First remove the 0's from the list, e.g. [8,0,0,2]->[8,2],1. First find the number of 0's, and then clean up according to the number.
    # (0): removes the first match of a value in the list, so [8,0,0,2] removes 0 twice
    for x in range((0)):
        (0)
    # Removed zeros refilled, [8,2]->[8,2,0,0]
    if direction == 'left':
        ([0 for x in range(4 - len(boardList))])
    else:
        boardList[:0] = [0 for x in range(4 - len(boardList))]


def handle(boardList, direction):
    '''
    Process the data in a row (column) to get the final numeric state value of the row (column), return the score
    :param boardList: list structure that stores the data in a row (column).
    :param direction: direction of movement, use direction for both up and left 'left', both rightward and downward using 'right'
    :return: Returns a row (column) of processed added scores
    '''
    addscore = 0
    # Process the data first, move it all in a specified direction #
    align(boardList, direction)
    result = addSameNumber(boardList, direction)
    # When result['continueRun'] is True, it means it needs to be executed again.
    while result['continueRun']:
        # Re-pair it and re-execute the merge until it can no longer be merged
        addscore += result['addNumber']
        align(boardList, direction)
        result = addSameNumber(boardList, direction)
    # Until the execution is complete, and the data in a row are not the same
    return {'addscore': addscore}


# Game manipulation function that recalculates matrix state values based on direction of movement and records score
def operator(board):
    # The number of points added for each action and whether the game triggers an end state (i.e., the data occupies the full position) after the action
    addScore = 0
    gameOver = False
    # Default to the left
    direction = 'left'
    op = input("Please enter your action:")
    if op in ['a', 'A']:
        # Direction to the left
        direction = 'left'
        # Processing line by line
        for row in range(4):
            addScore += handle(board[row], direction)['addscore']

    elif op in ['d', 'D']:
        direction = 'right'
        for row in range(4):
            addScore += handle(board[row], direction)['addscore']

    elif op in ['w', 'W']:
        # Up is equivalent to left transposition processing
        direction = 'left'
        board = list(map(list, zip(*board)))
        # Processing line by line
        for row in range(4):
            addScore += handle(board[row], direction)['addscore']
        board = list(map(list, zip(*board)))

    elif op in ['s', 'S']:
        # Downward equivalent to rightward transposition processing
        direction = 'right'
        board = list(map(list, zip(*board)))
        # Processing line by line
        for row in range(4):
            addScore += handle(board[row], direction)['addscore']
        board = list(map(list, zip(*board)))
    else:
        print("Error input! Please enter [W, S, A, D] or lowercase equivalent")
        return {'gameOver': gameOver, 'addScore': addScore, 'board': board}

    # The number of zeros needs to be determined after each operation, and if it's full, the game ends
    number_0 = 0
    for q in board:
        # count(0) is the number of occurrences of 0, is to scan each line of the
        number_0 += (0)
    # If number_0 is 0, it's full
    if number_0 == 0:
        gameOver = True
        return {'gameOver': gameOver, 'addScore': addScore, 'board': board}
    # Explain that it is not yet full, then add a 2 or 4 to the empty position with probability 3:1
    else:
        addnum = ([2,2,2,4])
        position_0_list = []
        # Find the position of 0 and save it
        for i in range(4):
            for j in range(4):
                if board[i][j] == 0:
                    position_0_list.append(i*4 + j)
    # Find a random 0 in the position you just recorded and replace it with the resulting 2 or 4.
    randomposition = (position_0_list, 1)
    board[int(randomposition[0] / 4)][randomposition[0] % 4] = addnum
    return {'gameOver': gameOver, 'addScore': addScore, 'board': board}


if __name__ == '__main__':
    print('importation:W(first (of multiple parts)) S(arrive at (a decision, conclusion etc)) A(unorthodox) D(right (-hand)).')
    # Initialize game interface, game score
    gameOver = False
    init(board)
    score = 0
    # The game stays running until it's over
    while gameOver != True:
        display(board, score)
        operator_result = operator(board)
        board = operator_result['board']
        if operator_result['gameOver'] == True:
            print("Game over, you lose!")
            print("Your final score:", score)
            gameOver = operator_result['gameOver']
            break
        else:
            # Plus the points for this step
            score += operator_result['addScore']
            if score >= 2048:
                print("Cow ah cow ah, you hang surprisingly won!")
                print("Your final score:", score)
                # End the game
                gameOver = True
                break

This is the whole content of this article.