20
5
Write a program to play the game of Connect 4. You are given the state of the board as input and you must decide which column to place your piece in to either get 4 in a row (horizontally, vertically, or diagonally) or block your opponent from doing the same.
The board is a 6x7 array, where each cell may be empty (' '), contain your piece ('X') or your opponent's piece ('O'). An example board:
O
XX X
XOX OO
XOO OXO
OXXOXXO
XOXOXOX
You would want to play in column 3 (columns are 0-6, numbered from the left) for the diagonal win. So you output:
3
Your code must output a column number, and it must satisfy the following criteria:
- You cannot play in a column that already has 6 pieces in it.
- If there is at least one winning move, you must play one of them.
- If you can prevent your opponent from winning on his next move, you must do so.
Note that optimal play is not necessary, only that you take an immediate win or prevent your opponent's immediate win. If your opponent has more than one way to win, you need not block any of them.
You are given the board on standard input and must print a column number in which you want to play on standard output. The board is guaranteed to be well-formed (no holes, at least one possible move) and to not already have a win for either player.
Shortest code wins.
Example 1
X
O
X
O
OOO X
XXX O
You must play either column 0 or 4 for the win.
Example 2
X
X X
O O
XOX XO
XXO XOX
XXO XXO
You must play column 3 to block your opponent's immediate win.
Example 3
X
XO
OX O
XO XX
XXO OOO
OOO XXO
You cannot win or stop your opponent from winning, so you may play any column 1-6 (0 is full).
Example 4
X
O
X
OOO
XOX
OXOX
You cannot play in column 3, as it lets your opponent win immediately. You may play in columns 1-2 or 4-6.
2I spend way too much time refining these. Also, the 458 byte version didn't work correctly for example #4. Take 25 bytes away and it does. Magic. – seequ – 2014-06-05T06:26:30.813