import pygame
# Define as cores
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# Inicializa o Pygame
pygame.init()
# Define o tamanho da janela
size = (400, 400)
screen = pygame.display.set_mode(size)
# Define o título da janela
pygame.display.set_caption("Jogo da Velha")
# Define o tamanho da grade
TILE_SIZE = 100
# Cria a grade
board = [['', '', ''], ['', '', ''], ['', '', '']]
# Define o jogador atual
current_player = 'X'
# Define a fonte do texto
font = pygame.font.Font(None, 30)
# Define a função que desenha o texto
def draw_text(text, x, y):
text = font.render(text, True, BLACK)
screen.blit(text, (x, y))
# Define a função que desenha a grade
def draw_board():
for row in range(3):
for col in range(3):
x = col * TILE_SIZE
y = row * TILE_SIZE
pygame.draw.rect(screen, WHITE, (x, y, TILE_SIZE, TILE_SIZE), 2)
draw_text(board[row][col], x + 30, y + 30)
# Define a função que verifica se o jogo acabou
def game_over():
for row in range(3):
if board[row][0] == board[row][1] == board[row][2] != '':
return True
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] != '':
return True
if board[0][0] == board[1][1] == board[2][2] != '':
return True
if board[0][2] == board[1][1] == board[2][0] != '':
return True
for row in range(3):
for col in range(3):
if board[row][col] == '':
return False
return True
# Define o loop principal do jogo
done = False
while not done:
# Eventos do Pygame
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
# Verifica se o jogo acabou
if game_over():
board = [['', '', ''], ['', '', ''], ['', '', '']]
current_player = 'X'
# Verifica se a posição do mouse está dentro da grade
pos = pygame.mouse.get_pos()
row = pos[1] // TILE_SIZE
col = pos[0] // TILE_SIZE
# Verifica se a posição está vazia
if board[row][col] == '':
# Preenche a posição com o símbolo do jogador atual
board[row][col] = current_player
# Alterna o jogador atual
if current_player == 'X':
current_player = 'O'
else:
current_player = 'X'
# Preenche a tela com a cor branca
screen.fill(WHITE)
# Desenha a grade
draw_board()
# Verifica se o jogo acabou
if game_over():
draw_text("Fim de Jogo", 150, 350)
# Atualiza a tela
pygame.display.flip()
# Finaliza o Pygame
pygame.quit()