Zpět na projektyBack to projects

2048 - Python Pygame Edition

Python Pygame JSON ctypes

Objektově orientovaná implementace klasické logické hry 2048 vytvořená v Pythonu pomocí knihovny Pygame. Tento projekt jde nad rámec jednoduchého skriptu a implementuje profesionální postupy, včetně stavového automatu, event-driven audia a statického typování. Object-oriented implementation of the classic 2048 puzzle game built in Python using Pygame. This project goes beyond a simple script by implementing professional software development practices, including a state machine, event-driven audio, and static type hinting.

2048 Game Demo

Ukázka herní plochy a uživatelského rozhraní Game board and user interface showcase

Klíčové funkceKey Features

OvládáníControls

Struktura projektuProject Structure

Directory Tree
2048/
├── main.py                 # Entry point of the application
├── requirements.txt
├── save.json               # Auto-generated save state
├── README.md
├── assets/                 # Media assets
│   ├── icon.png            # Application window/taskbar icon
│   └── music/              # Directory for background music (.mp3)
└── src/
    ├── board.py            # Grid logic and game over detection
    ├── config.py           # Constants, dimensions, and color palette
    ├── game.py             # Main game loop, state machine, and audio mixer
    └── tile.py             # Tile rendering and animation logic

Rychlý startQuick Start

Doporučuje se použít virtuální prostředí (venv/conda). It is recommended to use a virtual environment (venv/conda).

1. Instalace závislostí1. Install Dependencies

Terminal
pip install -r requirements.txt

2. Spuštění hry2. Run the game

Terminal
python main.py

Detail herní logiky (Komprese a slučování)Game Logic Detail (Compress and Merge)

Srdcem hry je logika, která při každém tahu nejprve posune všechny dlaždice jedním směrem (komprese) a následně sečte ty se stejnou hodnotou. Níže je zjednodušená ukázka této logiky ze souboru board.py. The core of the game is the logic that slides all tiles in one direction (compression) and then merges adjacent equal values. Below is a simplified representation of this logic from board.py.

board.py
def compress(row: list[int]) -> list[int]:
    """Slides all non-zero tiles to one side of the row."""
    new_row = [tile for tile in row if tile != 0]
    new_row += [0] * (len(row) - len(new_row))
    return new_row

def merge(row: list[int]) -> list[int]:
    """Merges adjacent tiles of the same value."""
    for i in range(len(row) - 1):
        if row[i] != 0 and row[i] == row[i + 1]:
            row[i] *= 2
            row[i + 1] = 0
    return row

def move_row_left(row: list[int]) -> list[int]:
    """Executes a full move on a single row."""
    compressed = compress(row)
    merged = merge(compressed)
    final_row = compress(merged) # Compress again to fill gaps
    return final_row
Zobrazit kód na GitHubu View Code on GitHub