Вот мой пример игры в крестики-нолики, в которой компьютер играет, выбирая случайные квадраты, а код пытается максимально избежать чисел. У него есть возможность обнаружить и объявить победителя:
from turtle import Turtle, Screen
from random import choice
SQUARE_SIZE = 200
FONT_SIZE = 160
FONT = ('Arial', FONT_SIZE, 'bold')
CURSOR_SIZE = 20
GAME_SIZE = 3
class TicTacToe:
wins = [
[True, True, True, False, False, False, False, False, False],
[False, False, False, True, True, True, False, False, False],
[False, False, False, False, False, False, True, True, True],
[True, False, False, True, False, False, True, False, False],
[False, True, False, False, True, False, False, True, False],
[False, False, True, False, False, True, False, False, True],
[True, False, False, False, True, False, False, False, True],
[False, False, True, False, True, False, True, False, False]
]
def __init__(self):
self.board = [Turtle('square', visible=False) for _ in range(GAME_SIZE * GAME_SIZE)]
self.background = Turtle('square', visible=False)
def drawBoard(self):
screen.tracer(False)
self.background.shapesize(SQUARE_SIZE * GAME_SIZE / CURSOR_SIZE)
self.background.color('black')
self.background.stamp()
for j in range(GAME_SIZE):
for i in range(GAME_SIZE):
square = self.board[i + j * GAME_SIZE]
square.shapesize(SQUARE_SIZE / CURSOR_SIZE)
square.color('white')
square.penup()
square.goto((i - 1) * (SQUARE_SIZE + 2), (j - 1) * (SQUARE_SIZE + 2))
square.state = None
square.onclick(lambda x, y, s=square: self.mouse(s))
square.showturtle()
square.stamp() # blank out background behind turtle (for later)
screen.tracer(True)
def select(self, square, turn):
square.onclick(None) # disable further moves to this square
square.state = turn
# replace square/turtle with (written) X or O
square.hideturtle()
square.color('black')
square.sety(square.ycor() - FONT_SIZE / 2)
square.write(turn, align='center', font=FONT)
return self.is_winner(turn)
def is_winner(self, turn):
for win in self.wins:
for index, flag in enumerate(win):
if flag and self.board[index].state != turn:
break
else: # no break
self.deactivate()
screen.textinput("Game Over", turn + " Wins!")
return True
return False
def deactivate(self):
for square in self.board:
if square.state is None:
square.onclick(None)
def mouse(self, square):
if self.select(square, 'X'):
return
choices = [square for square in self.board if square.state is None]
if not choices:
self.deactivate()
return
if self.select(choice(choices), 'O'):
return
screen = Screen()
game = TicTacToe()
game.drawBoard()
screen.mainloop()
Таблица типа wins
может использоваться для реализации стратегии, если / когда вы хотите сделать компьютерный плеер умнее.