HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Tic-Tac-Toe game using the minimax algorithm

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
minimaxthetoetictacalgorithmgameusing

Problem

I have written a Tic-Tac-Toe game in Python that contains, among others, a player that uses the minimax algorithm. I am not exactly a beginner at Python, but I'm not very experienced with it - so I want to know if my code follows bad practices and style. Any feedback about it is welcome.

```
# Play tic-tac-toe. The first player will be always X.
# Each tic-tac-toe board is represented by a sequence of three values:
# (set of squares that have an X, set of squares that have a y, board's width)
import random
import os
import string

def TicTacToe(X, O, width=3):
"""Play a tic-tac-toe game between the two given functions. After each
turn, yield the new board.
Each function should get a tic-tac-toe board and a char - 'X' or 'O',
that represents the current turn, and return the number of
square where it wants to put a sign.
width is the board's width and length - it's 3 as default.

X, O -- functions
width -- natural number
"""
board = (set(), set(), width)
turn = 'X'
while result(board) == False:
if turn == 'X':
board[0].add(X(board, turn))
else:
board[1].add(O(board, turn))
yield board
turn = list({'X', 'O'} - set([turn]))[0]

def displayTicTacToe(X, O, width=3):
"""Play a tic-tac-toe game (see TicTacToe's docstring for explanation) and
display the new board to the user when a player plays, and the result of
the game after its end.

X, O - functions
width - natural number"""
for board in TicTacToe(X, O, width):
os.system('cls' if os.name == 'nt' else 'clear') # clearscreen
print str_board(board)
winner = result(board)
if winner in {'X', 'O'}: print winner + ' won!'
elif winner == None: print 'Tie!'
else: raise ValueError("The game didn't end")

def result(board):
"""Return 'X' if X won in the given board, 'O' if O won, None if the game
ended with a tie, False if the game didn't end yet, and raise an ex

Solution

I think your code is very well written. Also very nice structure. I enjoyed reading it.

Just two notes.

One. This seems too much involved, to my taste:

turn = list({'X', 'O'} - set([turn]))[0]


what about:

turn = 'O' if turn=='X' else 'X'


or maybe

turn = {'O': 'X', 'X': 'O'}[turn]


(added: the difficulty to achieve a DRY result is an indication that the variable turn could better be an integer in (0,1) which can be used as an index in the "OX" string.)

Two. This:

os.system('cls' if os.name == 'nt' else 'clear')  # clearscreen


is a thing I would avoid. Since the program is so clean and self contained, I would keep it as abstract as possible. Maybe in 5 years there will be an OS which could run python happily but which does not have a 'clear' command... what a pity if your program will break for such a triviality!

And if you insist in using a system call, wrap it in a function, don't write it twice!

Code Snippets

turn = list({'X', 'O'} - set([turn]))[0]
turn = 'O' if turn=='X' else 'X'
turn = {'O': 'X', 'X': 'O'}[turn]
os.system('cls' if os.name == 'nt' else 'clear')  # clearscreen

Context

StackExchange Code Review Q#63375, answer score: 3

Revisions (0)

No revisions yet.