import pygame import sys # Initialize pygame pygame.init() # Define colors white = (255, 255, 255) black = (0, 0, 0) gray = (200, 200, 200) red = (255, 0, 0) blue = (0, 0, 255) # Set up display cell_size = 100 board_size = 3 width = height = board_size * cell_size dis = pygame.display.set_mode((width, height)) pygame.display.set_caption('Tic Tac Toe') # Define fonts font = pygame.font.SysFont(None, 55) def draw_board(): dis.fill(white) for x in range(1, board_size): pygame.draw.line(dis, black, (0, x * cell_size), (width, x * cell_size), 3) pygame.draw.line(dis, black, (x * cell_size, 0), (x * cell_size, height), 3) def draw_markers(board): for x in range(board_size): for y in range(board_size): if board[x][y] != '': mark = font.render(board[x][y], True, black) dis.blit(mark, (y * cell_size + cell_size // 4, x * cell_size + cell_size // 4)) def check_winner(board): # Check rows for row in board: if row[0] == row[1] == row[2] and row[0] != '': return row[0] # Check columns for col in range(board_size): if board[0][col] == board[1][col] == board[2][col] and board[0][col] != '': return board[0][col] # Check diagonals if board[0][0] == board[1][1] == board[2][2] and board[0][0] != '': return board[0][0] if board[0][2] == board[1][1] == board[2][0] and board[0][2] != '': return board[0][2] # Check for a tie for row in board: if '' in row: return None # Game is still ongoing return 'Tie' def gameLoop(): board = [['' for _ in range(board_size)] for _ in range(board_size)] player = 'X' game_over = False while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN and not game_over: x, y = event.pos row = x // cell_size col = y // cell_size if board[col][row] == '': board[col][row] = player winner = check_winner(board) if winner: if winner == 'Tie': print("It's a tie!") else: print(f"Player {winner} wins!") game_over = True player = 'O' if player == 'X' else 'X' draw_board() draw_markers(board) pygame.display.update() gameLoop()