To implement a basic 2048 game in Python, you can use a 2D list to represent the grid, and define functions to handle swiping and merging tiles. Since we won't have touch input in a console application, we'll simulate swipes using keyboard inputs or predefined directions. Here's a basic outline of how you can achieve this:
- Set up the grid.
- Implement functions to handle swipes in four directions.
- Implement logic for merging tiles.
- Implement a scoring system.
Here's a simple implementation using the built-in curses library to handle arrow key inputs for swiping (adjust if you’re not working in a terminal that supports curses, like replacing input handling with console inputs):
import random
def initialize_grid():
# Start with an empty 4x4 grid
grid = [[0] * 4 for _ in range(4)]
add_random_tile(grid)
add_random_tile(grid)
return grid
def add_random_tile(grid):
empty_cells = [(i, j) for i in range(4) for j in range(4) if grid[i][j] == 0]
if not empty_cells:
return
i, j = random.choice(empty_cells)
grid[i][j] = random.choice([2, 4])
def compress_tiles(row):
""" Shift all non-zero values to the left side of the row. """
new_row = [i for i in row if i != 0]
new_row += [0] * (4 - len(new_row))
return new_row
def merge_tiles(row):
""" Merge adjacent tiles with the same value. """
for i in range(3):
if row[i] == row[i + 1] and row[i] != 0:
row[i] *= 2
row[i + 1] = 0
return row
def move_left(grid):
for i in range(4):
grid[i] = compress_tiles(grid[i])
grid[i] = merge_tiles(grid[i])
grid[i] = compress_tiles(grid[i])
return grid
def move_right(grid):
for i in range(4):
grid[i].reverse()
grid[i] = compress_tiles(grid[i])
grid[i] = merge_tiles(grid[i])
grid[i] = compress_tiles(grid[i])
grid[i].reverse()
return grid
def move_up(grid):
grid = rotate_grid_anti_clockwise(grid)
grid = move_left(grid)
grid = rotate_grid_clockwise(grid)
return grid
def move_down(grid):
grid = rotate_grid_anti_clockwise(grid)
grid = move_right(grid)
grid = rotate_grid_clockwise(grid)
return grid
def rotate_grid_clockwise(grid):
return [list(row) for row in zip(*grid[::-1])]
def rotate_grid_anti_clockwise(grid):
return rotate_grid_clockwise(rotate_grid_clockwise(rotate_grid_clockwise(grid)))
def is_move_possible(grid):
""" Check if there are any valid moves available. """
for i in range(4):
for j in range(4):
if grid[i][j] == 0:
return True
if j < 3 and grid[i][j] == grid[i][j + 1]:
return True
if i < 3 and grid[i][j] == grid[i + 1][j]:
return True
return False
def print_grid(grid):
for row in grid:
print("+----+----+----+----+")
print("|" + "|".join(f"{val:^4}" if val else " " for val in row) + "|")
print("+----+----+----+----+")
def main():
grid = initialize_grid()
while is_move_possible(grid):
print("2048 Game")
print_grid(grid)
move = input("Enter move (w=up, s=down, a=left, d=right): ")
if move == "a":
grid_before = [row[:] for row in grid]
grid = move_left(grid)
elif move == "d":
grid_before = [row[:] for row in grid]
grid = move_right(grid)
elif move == "w":
grid_before = [row[:] for row in grid]
grid = move_up(grid)
elif move == "s":
grid_before = [row[:] for row in grid]
grid = move_down(grid)
else:
print("Invalid move! Use 'w', 'a', 's', or 'd'.")
continue
if grid != grid_before:
add_random_tile(grid)
print("Game Over!")
print_grid(grid)
if __name__ == "__main__":
main()
Key Components:
- Grid Initialization and Handling: The game initially starts with two random "2" or "4" tiles placed on a grid. We use helper functions to rotate and manage grid transformations.
- Movement Functions: Treat each swipe direction as a list manipulation, handling merging, moving, and compressing of non-zero tiles.
- Merge Logic: When two tiles of the same number collide, they merge into one, doubling the number.
- Direction Movement: Moving tiles involves different operations based on direction (left, right, up, down). We rotate the grid to simplify logic using row-based manipulations.
- Game Over Condition: The game ends when no moves are possible. This is checked by finding at least one zero cell or adjacent matching tiles.
This is a text-based implementation for simplicity. For a graphical user interface (GUI), you might use libraries such as tkinter, pygame, or others which provide event handling for more interactive user input.