"""Tic-tac-toe - a Pygame.net game project. Play against a friend or against a computer that uses the minimax algorithm (it never loses). Press M to switch modes. Run it: pip install pygame-ce (or: pip install pygame) python tic_tac_toe.py Controls: Click a square, or use the arrow keys and Space/Enter. M switches between 1 and 2 players, R starts a new round. License: MIT - https://pygame.net/licenses/ """ import asyncio from functools import lru_cache import pygame WIDTH, HEIGHT = 640, 480 FPS = 60 SIZE = 110 LEFT = (WIDTH - SIZE * 3) // 2 TOP = 66 BG = (16, 26, 48) GRID = (91, 147, 230) X_COLOR = (244, 197, 49) O_COLOR = (157, 194, 255) WHITE = (230, 236, 247) WIN_LINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)] def winner(board): for a, b, c in WIN_LINES: if board[a] != " " and board[a] == board[b] == board[c]: return board[a], (a, b, c) if " " not in board: return "draw", None return None, None @lru_cache(maxsize=None) def minimax(board, player): """Return (score, move) for `player` to move. Scores: X win +1, O win -1, draw 0.""" result, _ = winner(board) if result == "X": return 1, None if result == "O": return -1, None if result == "draw": return 0, None best = None for i, cell in enumerate(board): if cell != " ": continue child = board[:i] + player + board[i + 1:] score, _ = minimax(child, "O" if player == "X" else "X") if best is None or (player == "X" and score > best[0]) or (player == "O" and score < best[0]): best = (score, i) return best class Game: def __init__(self): self.font = pygame.font.Font(None, 34) self.big = pygame.font.Font(None, 52) self.vs_computer = True self.tally = {"X": 0, "O": 0, "draw": 0} self.new_round() def new_round(self): self.board = " " * 9 self.turn = "X" # the human is always X against the computer self.result = None self.line = None self.cursor = 4 self.think = 0.0 def play(self, index): if self.result or self.board[index] != " ": return False self.board = self.board[:index] + self.turn + self.board[index + 1:] self.result, self.line = winner(self.board) if self.result: self.tally[self.result] += 1 else: self.turn = "O" if self.turn == "X" else "X" if self.vs_computer and self.turn == "O": self.think = 0.35 # short pause so the reply is visible return True def handle_event(self, event): human_turn = not (self.vs_computer and self.turn == "O") if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: if self.result: self.new_round() return x, y = event.pos c, r = (x - LEFT) // SIZE, (y - TOP) // SIZE if 0 <= c < 3 and 0 <= r < 3 and human_turn: self.cursor = r * 3 + c self.play(self.cursor) elif event.type == pygame.KEYDOWN: c, r = self.cursor % 3, self.cursor // 3 if event.key == pygame.K_LEFT: c = (c - 1) % 3 elif event.key == pygame.K_RIGHT: c = (c + 1) % 3 elif event.key == pygame.K_UP: r = (r - 1) % 3 elif event.key == pygame.K_DOWN: r = (r + 1) % 3 elif event.key in (pygame.K_SPACE, pygame.K_RETURN): if self.result: self.new_round() elif human_turn: self.play(self.cursor) return elif event.key == pygame.K_r: self.new_round() return elif event.key == pygame.K_m: self.vs_computer = not self.vs_computer self.tally = {"X": 0, "O": 0, "draw": 0} self.new_round() return self.cursor = r * 3 + c def update(self, dt): if self.vs_computer and self.turn == "O" and not self.result: self.think -= dt if self.think <= 0: _, move = minimax(self.board, "O") self.play(move) def cell_rect(self, i): return pygame.Rect(LEFT + (i % 3) * SIZE, TOP + (i // 3) * SIZE, SIZE, SIZE) def draw(self, surface): surface.fill(BG) mode = "You (X) vs computer (O)" if self.vs_computer else "Two players" surface.blit(self.font.render(mode + " - M to switch", True, WHITE), (LEFT - 60, 28)) for i in range(1, 3): pygame.draw.line(surface, GRID, (LEFT + i * SIZE, TOP), (LEFT + i * SIZE, TOP + 3 * SIZE), 4) pygame.draw.line(surface, GRID, (LEFT, TOP + i * SIZE), (LEFT + 3 * SIZE, TOP + i * SIZE), 4) for i, mark in enumerate(self.board): r = self.cell_rect(i).inflate(-36, -36) if mark == "X": pygame.draw.line(surface, X_COLOR, r.topleft, r.bottomright, 10) pygame.draw.line(surface, X_COLOR, r.topright, r.bottomleft, 10) elif mark == "O": pygame.draw.circle(surface, O_COLOR, r.center, r.width // 2, 9) if not self.result: pygame.draw.rect(surface, WHITE, self.cell_rect(self.cursor).inflate(-8, -8), 2, border_radius=6) if self.line: a, c = self.cell_rect(self.line[0]).center, self.cell_rect(self.line[2]).center pygame.draw.line(surface, (232, 93, 82), a, c, 8) y = TOP + 3 * SIZE + 12 if self.result: msg = "It's a draw" if self.result == "draw" else f"{self.result} wins!" t = self.big.render(msg + " (Space)", True, X_COLOR) else: t = self.font.render(f"{self.turn} to play", True, WHITE) surface.blit(t, t.get_rect(midtop=(WIDTH // 2, y))) tally = self.font.render(f"X {self.tally['X']} O {self.tally['O']} Draws {self.tally['draw']}", True, WHITE) surface.blit(tally, tally.get_rect(midbottom=(WIDTH // 2, HEIGHT - 6))) async def main(): pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Tic-tac-toe - Pygame.net") clock = pygame.time.Clock() game = Game() running = True while running: dt = clock.tick(FPS) / 1000 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False else: game.handle_event(event) game.update(dt) game.draw(screen) pygame.display.flip() await asyncio.sleep(0) pygame.quit() if __name__ == "__main__": asyncio.run(main())