from math import inf
from random import choice
from itertools import permutations
# basic functions
def full(board):
return all(s != " " for row in board for s in row)
def victory(board, player):
return any(all(s == player for s in row) for row in (*board, *zip(*board), (board[i][i] for i in range(3)), (board[2-i][i] for i in range(3))))
def options(board):
return [(y, x) for y, row in enumerate(board) for x, s in enumerate(row) if s == " "]
def start():
return [[" " for x in range(3)] for y in range(3)]
def other(player):
return "x" if player == "o" else "o"
# game mechanic
def copy(board):
return [[s for s in row] for row in board]
def valid_move(prev, board):
different = [(y, x) for y in range(3) for x in range(3) if prev[y][x] != board[y][x]]
if len(different) != 1:
return False
y, x = different[0]
return prev[y][x] == " " and board[y][x] in "xo"
def play_game(robot1, robot2):
board = start()
robots = {"x": robot1, "o": robot2}
player = "x"
while True:
prev = copy(board)
board = robots[player](board, player)
if not valid_move(prev, board):
return other(player)
if victory(board, player):
return player
if full(board):
return " "
player = other(player)
def tournament(robots, rounds=1):
score = {r: 0 for r in robots}
for i in range(rounds):
for a, b in permutations(robots, 2):
result = play_game(a, b)
if result == "x":
score[a] += 1
elif result == "o":
score[b] += 1
return [score[r] for r in robots]
# start editing from here
def rating_adam(board, player):
if victory(board, player):
return inf
elif victory(board, other(player)):
return -inf
return 0 # no clue...
def robot_adam(board, player):
best = -inf
for y, x in options(board):
board[y][x] = player
r = rating_adam(board, player)
if r > best:
best = r
best_option = y, x
board[y][x] = " "
y, x = best_option
board[y][x] = player
return board
def robot_random(board, player):
y, x = choice(options(board))
board[y][x] = player
return board
def robot_optimal(board, player):
for y, x in options(board):
if result_optimal(board, player):
board[y][x] = player
return board
# don't edit this
if __name__ == "__main__":
robots = [robot_adam, robot_random]
print(tournament(robots, 2))