Skip to content Skip to sidebar Skip to footer

Widget HTML #1

Building Chess & Tic Tac Toe Game with Pygame

 


Building Chess & Tic Tac Toe Game with Pygame

Build interactive chess and tic tac toe games using Pygame. Train your Chess with Monte Carlo Tree Search algorithm.

Enroll Now

Pygame is a popular library for creating games in Python. It provides functionalities for rendering graphics, handling user input, and more. In this tutorial, we'll explore how to create two classic games: Chess and Tic Tac Toe. By the end of this guide, you'll have a solid foundation for building these games using Pygame.

Setting Up Your Environment

Before we dive into coding, ensure you have Pygame installed. You can install it using pip:

sh
pip install pygame

Creating Tic Tac Toe

Let's start with the simpler game, Tic Tac Toe. This game has a 3x3 grid where two players alternate marking Xs and Os. The player who first places three of their marks in a row, column, or diagonal wins.

Step 1: Setting Up the Game Window

First, we need to initialize Pygame and set up the game window:

python
import pygame import sys pygame.init() # Constants WIDTH, HEIGHT = 300, 300 LINE_WIDTH = 15 BOARD_ROWS, BOARD_COLS = 3, 3 SQUARE_SIZE = WIDTH // BOARD_COLS CIRCLE_RADIUS = SQUARE_SIZE // 3 CIRCLE_WIDTH = 15 CROSS_WIDTH = 25 SPACE = SQUARE_SIZE // 4 # Colors RED = (255, 0, 0) BG_COLOR = (28, 170, 156) LINE_COLOR = (23, 145, 135) CIRCLE_COLOR = (239, 231, 200) CROSS_COLOR = (66, 66, 66) # Initialize the screen screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Tic Tac Toe') screen.fill(BG_COLOR)

Step 2: Drawing the Board

Next, we draw the grid lines:

python
def draw_lines(): # Horizontal lines pygame.draw.line(screen, LINE_COLOR, (0, SQUARE_SIZE), (WIDTH, SQUARE_SIZE), LINE_WIDTH) pygame.draw.line(screen, LINE_COLOR, (0, 2 * SQUARE_SIZE), (WIDTH, 2 * SQUARE_SIZE), LINE_WIDTH) # Vertical lines pygame.draw.line(screen, LINE_COLOR, (SQUARE_SIZE, 0), (SQUARE_SIZE, HEIGHT), LINE_WIDTH) pygame.draw.line(screen, LINE_COLOR, (2 * SQUARE_SIZE, 0), (2 * SQUARE_SIZE, HEIGHT), LINE_WIDTH) draw_lines()

Step 3: Handling Player Moves

To handle player moves, we need to keep track of the game state. We'll use a 2D list for the board:

python
board = [[None] * BOARD_COLS for _ in range(BOARD_ROWS)] player = 'X' # Starting player def mark_square(row, col, player): board[row][col] = player def available_square(row, col): return board[row][col] is None def is_board_full(): for row in board: for cell in row: if cell is None: return False return True

Step 4: Drawing Xs and Os

Now, let's add functions to draw Xs and Os:

python
def draw_figures(): for row in range(BOARD_ROWS): for col in range(BOARD_COLS): if board[row][col] == 'O': pygame.draw.circle(screen, CIRCLE_COLOR, (int(col * SQUARE_SIZE + SQUARE_SIZE // 2), int(row * SQUARE_SIZE + SQUARE_SIZE // 2)), CIRCLE_RADIUS, CIRCLE_WIDTH) elif board[row][col] == 'X': pygame.draw.line(screen, CROSS_COLOR, (col * SQUARE_SIZE + SPACE, row * SQUARE_SIZE + SQUARE_SIZE - SPACE), (col * SQUARE_SIZE + SQUARE_SIZE - SPACE, row * SQUARE_SIZE + SPACE), CROSS_WIDTH) pygame.draw.line(screen, CROSS_COLOR, (col * SQUARE_SIZE + SPACE, row * SQUARE_SIZE + SPACE), (col * SQUARE_SIZE + SQUARE_SIZE - SPACE, row * SQUARE_SIZE + SQUARE_SIZE - SPACE), CROSS_WIDTH)

Step 5: Checking for a Win

To determine the winner, we need a function to check for three consecutive marks:

python
def check_win(player): # Vertical win check for col in range(BOARD_COLS): if board[0][col] == board[1][col] == board[2][col] == player: return True # Horizontal win check for row in range(BOARD_ROWS): if board[row][0] == board[row][1] == board[row][2] == player: return True # Ascending diagonal win check if board[2][0] == board[1][1] == board[0][2] == player: return True # Descending diagonal win check if board[0][0] == board[1][1] == board[2][2] == player: return True return False

Step 6: Running the Game Loop

Finally, we run the game loop to handle events and update the display:

python
running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN and not is_board_full(): mouseX = event.pos[0] # x mouseY = event.pos[1] # y clicked_row = mouseY // SQUARE_SIZE clicked_col = mouseX // SQUARE_SIZE if available_square(clicked_row, clicked_col): mark_square(clicked_row, clicked_col, player) if check_win(player): print(f'{player} wins!') running = False player = 'O' if player == 'X' else 'X' draw_figures() pygame.display.update() pygame.quit() sys.exit()

Creating Chess

Chess is more complex than Tic Tac Toe, involving a larger board and more sophisticated rules. We'll break down the essential steps to create a basic Chess game.

Step 1: Setting Up the Game Window

Similar to Tic Tac Toe, we start by initializing Pygame and setting up the game window:

python
import pygame import sys pygame.init() # Constants WIDTH, HEIGHT = 800, 800 DIMENSION = 8 # Chessboard is 8x8 SQ_SIZE = HEIGHT // DIMENSION # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) # Initialize the screen screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Chess')

Step 2: Drawing the Board

We need a function to draw the 8x8 chessboard:

python
def draw_board(): colors = [pygame.Color("white"), pygame.Color("gray")] for row in range(DIMENSION): for col in range(DIMENSION): color = colors[((row + col) % 2)] pygame.draw.rect(screen, color, pygame.Rect(col * SQ_SIZE, row * SQ_SIZE, SQ_SIZE, SQ_SIZE)) draw_board()

Step 3: Loading Pieces

Chess pieces can be represented by images. Load the images and place them on the board:

python
def load_images(): pieces = ['bR', 'bN', 'bB', 'bQ', 'bK', 'bP', 'wR', 'wN', 'wB', 'wQ', 'wK', 'wP'] images = {} for piece in pieces: images[piece] = pygame.transform.scale(pygame.image.load(f"images/{piece}.png"), (SQ_SIZE, SQ_SIZE)) return images images = load_images()

Step 4: Drawing Pieces

Now, let's add a function to draw pieces on the board:

python
def draw_pieces(board): for row in range(DIMENSION): for col in range(DIMENSION): piece = board[row][col] if piece != '--': screen.blit(images[piece], pygame.Rect(col * SQ_SIZE, row * SQ_SIZE, SQ_SIZE, SQ_SIZE))

Step 5: Handling Moves

We need to handle user inputs and piece movements. This involves detecting mouse clicks and updating the board state:

python
def main(): running = True board = [ ['bR', 'bN', 'bB', 'bQ', 'bK', 'bB', 'bN', 'bR'], ['bP', 'bP', 'bP', 'bP', 'bP', 'bP', 'bP', 'bP'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['wP', 'wP', 'wP', 'wP', 'wP', 'wP', 'wP', 'wP'], ['wR', 'wN', 'wB', 'wQ', 'wK', 'wB', 'wN', 'wR'] ] selected_piece = None player_turn = 'w' while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: col = event.pos[0] // SQ_SIZE row = event.pos[1] // SQ_SIZE if selected_piece: if (row, col) != selected_piece: board[row][col] = board[selected_piece[0]][selected_piece[1]] board[selected_piece[0]][selected_piece[1]] = '--' player_turn = 'b' if player_turn == 'w' else 'w' selected_piece = None else: selected_piece = (row, col) draw_board() draw_pieces(board) pygame.display.flip() pygame.quit() sys.exit() if __name__ == "__main__": main()

Conclusion

By following this guide, you have built two classic games using Pygame: Tic Tac Toe and a basic version of Chess. This tutorial provides a foundation for you to expand upon, adding features like game logic for valid moves in Chess, more sophisticated win detection, and better user interfaces. Pygame is a versatile library, and with practice, you'll be able to create a wide range of games and graphical applications.