259. Python Program to Find the Winner of Tic-Tac-Toe
HardPhase 3 · Challenge
You can solve this with a list, string indexes, a for loop and if, and you know them all. Draw a board on paper first and find its 8 lines.
Overview
Every game app needs a referee: a piece of code that looks at the board and says who has won. Tic-tac-toe is the classic first one to write.
Problem Statement
Pablo is making a tic-tac-toe game. The board has 3 rows of 3 squares. Each square holds X, O, or . for an empty square.
A player wins when one line has 3 of their marks. A line is a row, a column or a diagonal: 8 lines in all.
Read the board. Print one of these 4 results:
X winswhen X has a full line.O winswhen O has a full line.Drawwhen nobody has a full line and the board has no empty square.Not finishedwhen nobody has a full line and at least one square is still empty.
A full board with a full line is a win, not a draw.
Examples
Example 1. Input:
XO.
.XO
..X
gives:
X wins
Why: the diagonal from the top left to the bottom right is X, X, X.
Example 2. Input:
XOX
XOO
OXX
gives:
Draw
Why: none of the 8 lines has 3 of the same mark, and there is no . left on the board.
Input
Three lines, one for each row from top to bottom. Each line has exactly 3 characters, and each character is X, O or .. The board is always from a real game, so at most one player has a full line. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: X wins, O wins, Draw or Not finished. The tests try 9 different inputs: wins on a row, a column and each diagonal, a full board that is a win, an empty board, and a board where a player has only 2 in a line.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.