A two player tic-tac-toe
Your task is to develop a two player tic-tac-toe.
The game rules:
-
You have two players, one is called "X" and the other "O".
-
You have a field of 3×3 positions; any position may be marked as "." (empty), "X" or "O". We start with every position being "." (empty).
-
The player called "X" starts by marking any "." position with an "X". Then it's the other player's turn, who has to mark any "." position with an "O". They continue alternating until we have a winner or a tie.
-
We have a winner if there are three consecutive "X"s or "O"s in any row, column or diagonal. Example:
O.X OX. X.O
-
We have a tie if the board has been completely filled without any player having won.
The fields are enumerated according to the following pattern
012
345
678
In every turn the game outputs the full board as shown above followed by a new-line and a prompt consisting of the player active and the following sequence: >
. Example:
...
.X.
.O.
X> (cursor here)
The player inputs the number of the position they want to add their mark to. If the input is valid (a valid number between 0 and 8 and the position is yet empty), the game applies the input and starts a new turn (for the other player). Otherwise it'll print invalid.
followed by a new line and a new prompt; the game may print a new board too.
After every turn, the game checks if a win or a tie has been created. In this case the game shows "X won.", "O won." or "tie." respectively.
Your task is to write the game in your language of choice. You have to follow this specification exactly as written above. Additional new-lines are allowed around game boards and messages (invalid, win, tie) and at the end.
There's an ungolfed example implementation at Try it online!
Example inputs:
Tie:
4, 2, 8, 0, 1, 7, 3, 5, 6
Win for X:
0, 1, 2, 3, 4, 5, 6
Win for O:
6, 4, 0, 3, 1, 5
You may get your input via any way you want, including via stdin or arguments. Output to stdout. Standard loopholes apply. This is code-golf, so the shortest code in any language wins.
0 comment threads