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:
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.
X O X O OOO X XXX O
You must play either column 0 or 4 for the win.
X X X O O XOX XO XXO XOX XXO XXO
You must play column 3 to block your opponent's immediate win.
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).
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.