Monday, December 2, 2024

Building a Chess Game App: Python, Pygame, and Chess Logic in Action

 

 

chess board


Creating a chess game app involves multiple components including the game logic, a user interface (UI), and possibly networking features if you want multiplayer functionality. Below is a simple example of a Python script that uses the `pygame` library for the UI and `chess` library for game logic. This will set up a basic chess game with a GUI where two players can play against each other.


### Requirements

You will need to install the following Python packages:

- `pygame`: For the GUI

- `python-chess`: For the chess game logic


You can install these packages via pip:


```bash

pip install pygame python-chess

```


### Simple Chess Game App Script


```python

import pygame

import chess

import chess.svg


# Initialize Pygame

pygame.init()


# Constants

SCREEN_WIDTH = 480

SCREEN_HEIGHT = 480

SQUARE_SIZE = SCREEN_WIDTH // 8

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)


# Load chess board and pieces

board = chess.Board()


# Screen setup

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

pygame.display.set_caption("Chess")


# Load images for the chess pieces

piece_images = {}

for piece in ['p', 'r', 'n', 'b', 'q', 'k', 'P', 'R', 'N', 'B', 'Q', 'K']:

    piece_images[piece] = pygame.image.load(f'assets/{piece}.png').convert_alpha()

    piece_images[piece] = pygame.transform.scale(piece_images[piece], (SQUARE_SIZE, SQUARE_SIZE))


def draw_board():

    colors = [WHITE, BLACK]

    for row in range(8):

        for col in range(8):

            color = colors[(row + col) % 2]

            pygame.draw.rect(screen, color, pygame.Rect(col * SQUARE_SIZE, row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))


def draw_pieces():

    for row in range(8):

        for col in range(8):

            piece = board.piece_at(chess.square(col, 7-row))

            if piece:

                screen.blit(piece_images[piece.symbol()], pygame.Rect(col * SQUARE_SIZE, row * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))


def get_square_under_mouse():

    mouse_pos = pygame.Vector2(pygame.mouse.get_pos())

    x, y = [int(v // SQUARE_SIZE) for v in mouse_pos]

    return chess.square(x, 7 - y)


def main():

    clock = pygame.time.Clock()

    selected_square = None

    running = True


    while running:

        draw_board()

        draw_pieces()


        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                running = False

            elif event.type == pygame.MOUSEBUTTONDOWN:

                square = get_square_under_mouse()

                if selected_square is None:

                    if board.piece_at(square):

                        selected_square = square

                else:

                    move = chess.Move(selected_square, square)

                    if move in board.legal_moves:

                        board.push(move)

                    selected_square = None

        

        pygame.display.flip()

        clock.tick(60)


    pygame.quit()


if __name__ == "__main__":

    main()

```


### Explanation:


- **Pygame**: Handles the GUI for the chessboard and pieces.

- **chess.Board()**: Represents the chessboard and handles game logic, move legality, and checkmate conditions.

- **Images**: Piece images need to be in an `assets` folder, named by their respective piece symbols (e.g., `p.png` for a black pawn, `P.png` for a white pawn).

- **Main Loop**: Handles events such as selecting and moving pieces, updating the display, and checking for quit events.


### Asset Preparation:

You need images for each piece. You can find or create 64x64 PNG images for each piece (`p.png`, `r.png`, `n.png`, `b.png`, `q.png`, `k.png`, `P.png`, `R.png`, `N.png`, `B.png`, `Q.png`, `K.png`) and put them in an `assets` directory.


### Running the Script

Once everything is set up, running the script should open a window displaying the chessboard. You can click on pieces to move them, and the game will enforce the rules of chess.


This script covers the basics. To add features like move history, undo/redo, or AI opponents, you'll need to extend this code with additional logic.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

------------------------------------------------------------------------------------------------------