Python Programming 3.4.2, Naughts And Crosses. Best Way To Check How To See If Game Is Won?
Solution 1:
defget_winner(grid):
'''returns 'X', 'O', or None'''
line_dxs = [
# rows
(0,1,2),
(3,4,5),
(6,7,8),
# cols
(0,3,6),
(1,4,7),
(2,5,8),
# diags
(0,4,8),
(2,4,6)
]
for dxs in line_dxs:
line = [grid[dx] for dx in dxs]
if line == ['X', 'X', 'X']:
return'X'elif line == ['O', 'O', 'O']:
return'O'
In action:
>>>get_winner(['X', 'O', 'X',...'O', 'O', 'X',...'X', 'O', '' ])
'O'
>>>get_winner(['X', 'O', 'X',...'O', 'O', 'X',...'X', '' , 'O' ])>>>get_winner(['X', 'O', 'X',...'O', 'O', 'X',...'X', '' , 'X' ])
'X'
Solution 2:
Your data representation makes this harder than it needs to be. Presently, you store a grid as a list of the 9 squares, starting at the upper left and proceeding by rows, across and then down. Just to access the square in (row 1, column 2), for example, you have to do arithmetic.
Better representations let you address squares directly by their row and column indexes. In Python, counting starts at 0, so let's say that the rows are 0, 1, 2, and likewise the columns. Two alternatives to consider:
a 3-element list of the rows, each row a 3-element list for the values in the squares at the corresponding columns:
grid = [["", "", ""], ["", "", ""], ["", "", ""]]
With this
grid
, the square in rowi
, columnj
is justgrid[i][j]
.A
dict
:dgrid = {(i,j): "" for i in range(3) for j in range(3)}
With this representation, the square in row
i
, columnj
is justdgrid[i,j]
. I'll use this in the code that follows.
Checking the grid for a winning state is now much simpler. Here's a function to check whether row i
has a win for player
(equal to 'X' or 'O', let's say):
defwinning_row(i, player):
'''Return True if all entries in row i are equal to player.
player is either 'X' or 'O'.
'''returnall(dgrid[i,j] == player for j inrange(3))
You can define the function winning_column(j, player)
similarly. Checking the diagonals is a little different. We can use two functions, winning_main_diagonal(player)
and winning_other_diagonal(player)
. Here's the latter:
defwinning_other_diagonal(player):
returnall(dgrid[i,2-i] for i inrange(3))
These functions all take a player
parameter because you only need to check for a winning configuration after a particular player
has moved. You don't need to check the entire grid to see whether some player won, and if so which one.
This function reports whether the player
who just moved by marking square (i,j)
has just won:
defjust_won(i, j, player):
if winning_row(i, player):
returnTrueif winning_column(j, player):
returnTrueif i == j and winning_diagonal(player):
returnTrueif I + j == 2and winning_other_diagonal(player):
returnTruereturnFalse
Post a Comment for "Python Programming 3.4.2, Naughts And Crosses. Best Way To Check How To See If Game Is Won?"