Read a finished board and say who won.
What to build
A program that checks every possible winning line.
Requirements
- Read three rows of three characters.
- Print
XorOif that player has three in a line. - Print
drawif nobody has.
Input
Three lines, each with three characters: X, O or ..
Output
One word.
Constraints
At most one player has three in a line.
Example
Input:
XXX
OO.
...
Output:
X
Why it works
Collecting all eight lines into one list means a single simple test covers every direction, and rows, columns and diagonals are no longer special cases.
Examples
Example 1 · Input
XXX OO. ...
Expected output
X
Example 2 · Input
XOX OXO OXO
Expected output
draw
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
There are eight lines to check: three rows, three columns and two diagonals.
Hint 2
Make a list of the eight lines, each as a list of three characters.
Hint 3
A player has won if a line is all X or all O.
Solution
Show one correct solution (try it yourself first)
board = [input() for _ in range(3)]
lines = []
for i in range(3):
lines.append([board[i][0], board[i][1], board[i][2]])
lines.append([board[0][i], board[1][i], board[2][i]])
lines.append([board[0][0], board[1][1], board[2][2]])
lines.append([board[0][2], board[1][1], board[2][0]])
winner = "draw"
for line in lines:
if line == ["X", "X", "X"]:
winner = "X"
elif line == ["O", "O", "O"]:
winner = "O"
print(winner)