|
import pygame, sys |
|
|
|
from game import Game |
|
|
|
pygame.init() |
|
|
|
SIZE = 100 |
|
BORDER = 10 |
|
PADDING = 20 |
|
DIMENSION = SIZE * 3 + BORDER * 4 |
|
THICKNESS = 10 |
|
|
|
WHITE = (255, 255, 255) |
|
BLACK = ( 0, 0, 0) |
|
|
|
OVERLAY_ALPHA = 180 |
|
|
|
screen = pygame.display.set_mode([DIMENSION, DIMENSION]) |
|
font = pygame.font.SysFont("monospace", 33, True) |
|
game = Game() |
|
|
|
def square_to_rectangle(square): |
|
row = square // 3 |
|
column = square % 3 |
|
|
|
x = BORDER + (SIZE + BORDER) * row |
|
y = BORDER + (SIZE + BORDER) * column |
|
|
|
return [x, y, SIZE, SIZE] |
|
|
|
def square_to_inner_rectangle(square): |
|
x, y, w, h = square_to_rectangle(square) |
|
|
|
x += PADDING |
|
y += PADDING |
|
w -= PADDING * 2 |
|
h -= PADDING * 2 |
|
|
|
return [x, y, w, h] |
|
|
|
def draw_x(square): |
|
x, y, w, h = square_to_inner_rectangle(square) |
|
|
|
pygame.draw.line(screen, WHITE, [x, y], [x + w, y + h], THICKNESS) |
|
pygame.draw.line(screen, WHITE, [x + w, y], [x, y + h], THICKNESS) |
|
|
|
def draw_o(square): |
|
x, y, w, h = square_to_inner_rectangle(square) |
|
|
|
pygame.draw.ellipse(screen, WHITE, [x, y, w, h], THICKNESS) |
|
|
|
def within(point, rectangle): |
|
x, y = point |
|
l, t, w, h = rectangle |
|
|
|
return l <= x <= l + w and t <= y <= t + h |
|
|
|
def square_for(position): |
|
for i in range(9): |
|
rectangle = square_to_rectangle(i) |
|
if within(position, rectangle): |
|
return i |
|
|
|
return None |
|
|
|
def draw_board(): |
|
screen.fill(WHITE) |
|
|
|
for i in range(9): |
|
rectangle = square_to_rectangle(i) |
|
pygame.draw.rect(screen, BLACK, rectangle) |
|
|
|
for i in range(9): |
|
if game.at(i) == Game.X: |
|
draw_x(i) |
|
elif game.at(i) == Game.O: |
|
draw_o(i) |
|
|
|
def draw_message(msg): |
|
label = font.render(msg, 1, WHITE) |
|
rect = label.get_rect() |
|
rect.centerx = screen.get_rect().centerx |
|
rect.centery = screen.get_rect().centery |
|
|
|
overlay = pygame.Surface((DIMENSION, DIMENSION)) |
|
overlay.set_alpha(OVERLAY_ALPHA) |
|
overlay.fill(BLACK) |
|
|
|
screen.blit(overlay, (0, 0)) |
|
screen.blit(label, rect) |
|
|
|
while True: |
|
for event in pygame.event.get(): |
|
if event.type == pygame.QUIT: |
|
sys.exit() |
|
elif event.type == pygame.MOUSEBUTTONUP: |
|
position = pygame.mouse.get_pos() |
|
square = square_for(position) |
|
if game.valid_move(square): |
|
game.play(square) |
|
|
|
draw_board() |
|
|
|
outcome = game.outcome() |
|
if outcome == Game.X_WINS: |
|
draw_message("X wins") |
|
elif outcome == Game.O_WINS: |
|
draw_message("O wins") |
|
elif outcome == Game.TIE: |
|
draw_message("Tie ;(") |
|
pygame.display.flip() |