impelment 2048 in python

To implement 2048 in Python, we need to first understand the game mechanics and rules. In 2048, the player moves numbered tiles in four directions (up, down, left and right) on a 4x4 grid. Each move combines identical adjacent tiles into one tile, doubling its value until reaching the highest value of 2048.

Here is one way to implement 2048 in Python using a 2D NumPy array as the game grid:

main.py
import numpy as np

# initialize game grid
grid = np.zeros((4, 4), dtype=int) 

# place two random tiles at the start of the game
new_tiles = [(i, j) for i in range(4) for j in range(4)]
(np.random.choice(len(new_tiles), size=2, replace=False)
 .tolist())
tiles = [new_tiles[i] for i in tile_indexes]
for tile in tiles:
    grid[tile] = np.random.choice([2, 4])

# function to move tiles and combine identical values
def move_tiles(grid, direction):
    if direction == 'up':
        grid = np.rot90(grid, k=1)
    elif direction == 'right':
        grid = np.rot90(grid, k=2)
    elif direction == 'down':
        grid = np.rot90(grid, k=3)
    moves = 0
    for i in range(4):
        row = [num for num in grid[i] if num != 0]
        for j in range(len(row)-1):
            if row[j] == row[j+1]:
                row[j] *= 2
                row[j+1] = 0
        row = [num for num in row if num != 0] + [0]*(4-len(row))
        moves += sum([grid[i][j] != row[j] for j in range(4)])
        grid[i] = row
    if direction == 'up':
        grid = np.rot90(grid, k=3)
    elif direction == 'right':
        grid = np.rot90(grid, k=2)
    elif direction == 'down':
        grid = np.rot90(grid, k=1)
    return grid, moves

# main game loop
while True:
    print(grid)
    move = input()
    if move in ('up', 'down', 'left', 'right'):
        grid_new, moves = move_tiles(grid, move)
        if moves > 0:
            # add a new random tile if a move was made
            new_tile = np.random.choice(
                [(i, j) for i in range(4) for j in range(4)
                 if grid_new[i][j] == 0])
            grid_new[new_tile] = np.random.choice([2, 4])
            grid = grid_new
        else:
            print("Invalid move. Try again.")
    else:
        print("Invalid input. Please enter up, down, left, or right.")
1833 chars
57 lines

This implementation uses a numpy array to represent the 4x4 game grid and the move_tiles function to perform the game mechanics. The main game loop takes user input for the direction of the move and updates the grid accordingly. If a move is valid, the function adds a new random tile to the grid with a value of either 2 or 4.

gistlibby LogSnag