import pygame, sys
pygame.init()
W = H = 500
CELL = W // 3
screen = pygame.display.set_mode((W, H + 60))
pygame.display.set_caption("Крестики-нолики")
font = pygame.font.SysFont("arial", 40, bold=True)
board = [""] * 9
turn = "X"
winner = None
def check_winner():
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)]
for a,b,c in lines:
if board[a] and board[a] == board[b] == board[c]:
return board[a]
if "" not in board:
return "Ничья"
return None
def draw():
screen.fill((30,30,40))
for i in range(1,3):
pygame.draw.line(screen, (200,200,200), (i*CELL,0), (i*CELL,W), 4)
pygame.draw.line(screen, (200,200,200), (0,i*CELL), (W,i*CELL), 4)
for i, v in enumerate(board):
x, y = (i%3)*CELL, (i//3)*CELL
if v == "X":
pygame.draw.line(screen,(220,60,60),(x+20,y+20),(x+CELL-20,y+CELL-20),8)
pygame.draw.line(screen,(220,60,60),(x+CELL-20,y+20),(x+20,y+CELL-20),8)
elif v == "O":
pygame.draw.circle(screen,(60,120,220),(x+CELL//2,y+CELL//2),CELL//2-20,8)
msg = f"Ход: {turn}" if not winner else (f"Победил: {winner}" if winner!="Ничья" else "Ничья!")
if winner:
msg += " (R - заново)"
text = font.render(msg, True, (255,255,255))
screen.blit(text, (W//2 - text.get_width()//2, W + 10))
pygame.display.flip()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN and not winner:
mx, my = event.pos
if my < W:
col, row = mx // CELL, my // CELL
idx = row*3 + col
if board[idx] == "":
board[idx] = turn
winner = check_winner()
turn = "O" if turn == "X" else "X"
if event.type == pygame.KEYDOWN and event.key == pygame.K_r:
board = [""] * 9
turn = "X"
winner = None
draw()
pygame.quit()
sys.exit()