In the pencil-and-paper game, Tic-tac-toe, 2 players take turns to mark 'X' and 'O' on a board of 3x3 squares. The player who succeeds in marking 3 successive 'X' or 'O' in vertical, horizontal or diagonal stripe wins the game. Write a function that determines the outcome of a tic-tac-toe game.
Examples
>>> tictactoe([('X', ' ', 'O'),
(' ', 'O', 'O'),
('X', 'X', 'X') ])
"'X' wins (horizontal)."
>>> tictactoe([('X', 'O', 'X'),
... ('O', 'X', 'O'),
... ('O', 'X', 'O') ])
'Draw.'
>>> tictactoe([('X', 'O', 'O'),
... ('X', 'O', ' '),
... ('O', 'X', ' ') ])
"'O' wins (diagonal)."
>>> tictactoe([('X', 'O', 'X'),
... ('O', 'O', 'X'),
... ('O', 'X', 'X') ])
"'X' wins (vertical)."
def tictactoe(moves):
for r in range(len(moves)):
for c in range(len(moves[r])):
if moves[0][c]==moves[1][c]==moves[2][c]:
a="'%s' wins (%s)."%((moves[0][c]),'vertical')
elif moves[r][0]==moves[r][1]==moves[r][2]:
a="'%s' wins (%s)."%((moves[r][0]),'horizontal')
elif moves[0][0]==moves[1][1]==moves[2][2]:
a="'%s' wins (%s)."%((moves[0][0]),'diagonal')
elif moves[0][2]==moves[1][1]==moves[2][0]:
a="'%s' wins (%s)."%((moves[0][2]),'diagonal')
else:
a='Draw.'
print(a)
I wrote a code like this and my range is not working(i think). because, it takes the value for r and c as 3, not 0,1,2,3. So, please anyone can help me with this ? Thank you
Your loop doesn't exit when a player wins. I'd try something like this:
def tictactoe_state(moves):
for r in range(len(moves)):
for c in range(len(moves[r])):
if moves[0][c] == moves[1][c] == moves[2][c]:
return "'%s' wins (%s)." % (moves[0][c], 'vertical')
elif moves[r][0] == moves[r][1] == moves[r][2]:
return "'%s' wins (%s)." % (moves[r][0], 'horizontal')
elif moves[0][0] == moves[1][1] == moves[2][2]:
return "'%s' wins (%s)." % (moves[0][0], 'diagonal')
elif moves[0][2] == moves[1][1] == moves[2][0]:
return "'%s' wins (%s)." % (moves[0][2], 'diagonal')
# You still have to make sure the game isn't a draw.
# To do that, see if there are any blank squares.
return 'Still playing'
Also, I'd move the if
statements that check the diagonals out of the loop. They don't depend on r
and c
.