CodeNewbie Community 🌱

Hichem MG
Hichem MG

Posted on

How to Make a Checkers Game with Python and Pygame

Creating a Checkers game in Python involves using a library that supports graphics and user interaction. Pygame is a popular choice for such projects due to its simplicity and comprehensive documentation.

Here’s a small guide on how to make a Checkers game using Python and Pygame.

How to Make a Checkers Game with Python and Pygame

Prerequisites

  • Basic understanding of Python programming
  • Python installed on your system (Python 3.7+ recommended)
  • Pygame library installed (you can install it using pip install pygame)

Step 1: Setting Up the Project

Create a new directory for your Checkers game project. Inside this directory, create a Python file, for example, checkers.py.

Step 2: Installing Pygame

Install the Pygame library using pip:

pip install pygame
Enter fullscreen mode Exit fullscreen mode

Step 3: Initializing Pygame

In your checkers.py file, start by importing and initializing Pygame.

import pygame
import sys

# Initialize Pygame
pygame.init()

# Screen dimensions
WIDTH, HEIGHT = 800, 800
ROWS, COLS = 8, 8
SQUARE_SIZE = WIDTH // COLS

# Colors
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
GREY = (128, 128, 128)

# Initialize the screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Checkers')
Enter fullscreen mode Exit fullscreen mode

Step 4: Creating the Board

Define functions to draw the board and squares.

def draw_squares(screen):
    screen.fill(BLACK)
    for row in range(ROWS):
        for col in range(row % 2, COLS, 2):
            pygame.draw.rect(screen, WHITE, (row * SQUARE_SIZE, col * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))

def main():
    run = True
    clock = pygame.time.Clock()

    while run:
        clock.tick(60)  # Limit the frame rate to 60 FPS

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        draw_squares(screen)
        pygame.display.flip()

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

This code will create a window with an 8x8 checkers board.

Step 5: Creating the Pieces

Define a Piece class to represent each checkers piece.

class Piece:
    PADDING = 15
    OUTLINE = 2

    def __init__(self, row, col, color):
        self.row = row
        self.col = col
        self.color = color
        self.king = False

        if self.color == RED:
            self.direction = -1
        else:
            self.direction = 1

        self.x = 0
        self.y = 0
        self.calc_pos()

    def calc_pos(self):
        self.x = SQUARE_SIZE * self.col + SQUARE_SIZE // 2
        self.y = SQUARE_SIZE * self.row + SQUARE_SIZE // 2

    def make_king(self):
        self.king = True

    def draw(self, screen):
        radius = SQUARE_SIZE // 2 - self.PADDING
        pygame.draw.circle(screen, GREY, (self.x, self.y), radius + self.OUTLINE)
        pygame.draw.circle(screen, self.color, (self.x, self.y), radius)
        if self.king:
            crown = pygame.image.load('crown.png')
            crown = pygame.transform.scale(crown, (44, 25))
            screen.blit(crown, (self.x - crown.get_width()//2, self.y - crown.get_height()//2))

    def move(self, row, col):
        self.row = row
        self.col = col
        self.calc_pos()
Enter fullscreen mode Exit fullscreen mode

Step 6: Creating the Board Class

Define a Board class to manage the game state.

class Board:
    def __init__(self):
        self.board = []
        self.red_left = self.white_left = 12
        self.red_kings = self.white_kings = 0
        self.create_board()

    def create_board(self):
        for row in range(ROWS):
            self.board.append([])
            for col in range(COLS):
                if col % 2 == ((row + 1) % 2):
                    if row < 3:
                        self.board[row].append(Piece(row, col, WHITE))
                    elif row > 4:
                        self.board[row].append(Piece(row, col, RED))
                    else:
                        self.board[row].append(0)
                else:
                    self.board[row].append(0)

    def draw(self, screen):
        self.draw_squares(screen)
        for row in range(ROWS):
            for col in range(COLS):
                piece = self.board[row][col]
                if piece != 0:
                    piece.draw(screen)

    def draw_squares(self, screen):
        screen.fill(BLACK)
        for row in range(ROWS):
            for col in range(row % 2, COLS, 2):
                pygame.draw.rect(screen, WHITE, (row * SQUARE_SIZE, col * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE))

    def move(self, piece, row, col):
        self.board[piece.row][piece.col], self.board[row][col] = self.board[row][col], self.board[piece.row][piece.col]
        piece.move(row, col)

        if row == ROWS - 1 or row == 0:
            piece.make_king()
            if piece.color == WHITE:
                self.white_kings += 1
            else:
                self.red_kings += 1
Enter fullscreen mode Exit fullscreen mode

Step 7: Handling User Input

Add functions to handle user clicks and piece selection.

def get_row_col_from_mouse(pos):
    x, y = pos
    row = y // SQUARE_SIZE
    col = x // SQUARE_SIZE
    return row, col

def main():
    run = True
    clock = pygame.time.Clock()
    board = Board()
    selected_piece = None

    while run:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                if selected_piece:
                    board.move(selected_piece, row, col)
                    selected_piece = None
                else:
                    piece = board.board[row][col]
                    if piece != 0:
                        selected_piece = piece

        board.draw(screen)
        pygame.display.flip()

    pygame.quit()
    sys.exit()
Enter fullscreen mode Exit fullscreen mode

Step 8: Enhancing the Game Logic

Implement game logic for capturing pieces, switching turns, and determining the winner. Here’s a simplified version of the game loop with basic capturing logic.

class Game:
    def __init__(self, screen):
        self._init()
        self.screen = screen

    def _init(self):
        self.selected = None
        self.board = Board()
        self.turn = RED
        self.valid_moves = {}

    def update(self):
        self.board.draw(self.screen)
        self.draw_valid_moves(self.valid_moves)
        pygame.display.update()

    def reset(self):
        self._init()

    def select(self, row, col):
        if self.selected:
            result = self._move(row, col)
            if not result:
                self.selected = None
                self.select(row, col)

        piece = self.board.get_piece(row, col)
        if piece != 0 and piece.color == self.turn:
            self.selected = piece
            self.valid_moves = self.board.get_valid_moves(piece)
            return True

        return False

    def _move(self, row, col):
        piece = self.board.get_piece(row, col)
        if self.selected and piece == 0 and (row, col) in self.valid_moves:
            self.board.move(self.selected, row, col)
            skipped = self.valid_moves[(row, col)]
            if skipped:
                self.board.remove(skipped)
            self.change_turn()
        else:
            return False

        return True

    def draw_valid_moves(self, moves):
        for move in moves:
            row, col = move
            pygame.draw.circle(self.screen, BLUE, (col * SQUARE_SIZE + SQUARE_SIZE // 2, row * SQUARE_SIZE + SQUARE_SIZE // 2), 15)

    def change_turn(self):
        self.valid_moves = {}
        if self.turn == RED:
            self.turn = WHITE
        else:
            self.turn = RED

def main():
    run = True
    clock = pygame.time.Clock()
    game = Game(screen)

    while run:
        clock.tick(60)

        if game.turn == RED:
            print("Red's turn")
        else:
            print("White's turn")

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                game.select(row, col)

        game.update()

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Conclusion

This guide walks you through the basics of creating a Checkers game in Python using Pygame. You can further enhance the game by adding more features such as a more sophisticated AI opponent, better graphics, and improved game logic. This project provides a solid foundation for exploring game development with Python.

Top comments (1)

Collapse
 
shahsahb123 profile image
Alex Hales

Thanks for sharing amazing information