how to Create your Own 2048 Game with Python

04 May 2023 Balmiki Mandal 0 Python

Create 2048 Game in Python

2048 is an easy to play puzzle game that is becoming increasingly popular. Get ready to enjoy this addictive and popular game with this tutorial on how to create a 2048 game in Python!

Requirements for the 2048 game

  • Python 3.x
  • Pygame module

Getting Started

The first thing you need to do is set up your environment. Create a folder called "2048" and open it in your text editor. Create a file called "game.py" and save it in the same folder.

Now you need to install Pygame. Open the command prompt (or terminal) and type in the following:

python -m pip install pygame

If you see a message saying "Requirement already satisfied" then you already have Pygame installed. Once you're done with this, you can start writing your code.

Writing the Code

In this section we will be writing the code for our game. Open the game.py file and add the following code:

import pygame
 
# Initialize pygame
pygame.init()
 
# Define colors
white = (255, 255, 255)
black = (0, 0, 0)
 
# Create window
size = width, height = 400, 400
screen = pygame.display.set_mode(size)
pygame.display.set_caption("2048")
 
# Render board
board = [[2, 4, 8, 16],
         [32, 64, 128, 256],
         [512, 1024, 2048, 0],
         [0, 0, 0, 0]]
for y, row in enumerate(board):
    for x, num in enumerate(row):
        if num != 0:
            rect = pygame.Rect(x * 100 + 10, y * 100 + 10, 80, 80)
            pygame.draw.rect(screen, white, rect)
            font = pygame.font.Font(None, 42)
            text = font.render(str(num), 1, black)
            size = text.get_rect().width, text.get_rect().height
            screen.blit(text, (x * 100 + (80 - size[0]) / 2 + 10, y * 100 + (80 - size[1]) / 2 + 10))
 
# Update display
pygame.display.update()
 
# Keep game running until close
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

Now save the file and run it using the following command:

python game.py

You should now see a window pop up with the 2048 board rendered! You now have a basic working version of the game. In the next section we will be adding the necessary logic to make the game playable.

Adding Game Logic

Now that we've created the basic game, let's add the necessary logic to make it playable. We'll start by adding code for the user input. Add the following code after the event loop:

# Get user input
while True:
    key = pygame.key.get_pressed()
    if key[pygame.K_UP]:
        # Move pieces up
    elif key[pygame.K_DOWN]:
        # Move pieces down
    elif key[pygame.K_LEFT]:
        # Move pieces left
    elif key[pygame.K_RIGHT]:
        # Move pieces right
 
    # Update display
    pygame.display.update()

Now we just need to add the code for moving the pieces. Add the following code after the user input code:

def move_pieces(direction):
    # Get tiles
    tiles = []
    for y, row in enumerate(board):
        for x, num in enumerate(row):
            if num != 0:
                tiles.append((x, y))
   
    # Move pieces
    moved = False
    if direction == "up":
        for x, y in tiles:
            if y == 0:
                continue
            if board[y - 1][x] == 0 or board[y - 1][x] == board[y][x]:
                moved = True
                board[y - 1][x] += board[y][x]
                board[y][x] = 0
    elif direction == "down":
        for x, y in tiles:
            if y == 3:
                continue
            if board[y + 1][x] == 0 or board[y + 1][x] == board[y][x]:
                moved = True
                board[y + 1][x] += board[y][x]
                board[y][x] = 0
    elif direction == "left":
        for x, y in tiles:
            if x == 0:
                continue
            if board[y][x - 1] == 0 or board[y][x - 1] == board[y][x]:
                moved = True
                board[y][x - 1] += board[y][x]
                board[y][x] = 0
    elif direction == "right":
        for x, y in tiles:
            if x == 3:
                continue
            if board[y][x + 1] == 0 or board[y][x + 1] == board[y][x]:
                moved = True
                board[y][x + 1] += board[y][x]
                board[y][x] = 0
 
    # Update display
    if moved:
        pygame.display.update()
 
    return moved

Finally update the user input code to call the move pieces function:

# Get user input
while True:
    key = pygame.key.get_pressed()
    if key[pygame.K_UP]:
        moved = move_pieces("up")
    elif key[pygame.K_DOWN]:
        moved = move_pieces("down")
    elif key[pygame.K_LEFT]:
        moved = move_pieces("left")
    elif key[pygame.K_RIGHT]:
        moved = move_pieces("right")
 
    # Update display
    if moved:
        pygame.display.update()

Save your changes and run the game again. Now you should be able to move the pieces around and see the board update.

Conclusion

Congratulations! You now have a working version of 2048 in Python. You can continue to add features such as score tracking and an AI opponent to make the game even more fun!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.