Four in a Row is the classic two player game where you take turns to place a counter in an upright grid and try and beat your opponent to place 4 counters in a row.
At the start of the game you are assigned a disc colour either yellow or red. The game is played with a seven-column and six-row grid, which is arranged upright. The number of columns may be changed from six to ten, creating a greater variety of the game, but the number of rows is usually seven.
The starting player is randomly chosen and can place a disc in any row. Each player then alternately takes a turn placing a disc in any column that is not already full. The disc falls down straight and will only be stopped by another piece. The aim is to be the first of the two players to connect four discs of the same colour vertically, horizontally or diagonally, an example is shown below:
Connecting five or six instead of four pieces in a row is a different version of this game and is played with a bigger grid. If each cell of the grid is filled and no player has already connected four discs, the game ends in a draw, so no player wins.
See the programmer's reference for details about the gamestate and making a valid move for this game
Four in a Row is a strongly solved perfect information strategy game by that we mean the player who has the first move has a winning strategy whatever his opponent plays.
To play this perfect game the code required is quite complex but below are some basic strategies.
Produce a sub-routine to check if there is a winning solution on any given board. You can then use this to simulate what will happen if you play any valid move.
Simply check if you can play a counter to win the game.
Next check to see if you need to play a move to block your opponent from winning.
Eliminate moves that if you play them your opponent can play a winning move i.e. you should never play under an opponent winning positions. So in the example below yellow should not play a counter in position 'x':
Try and get into a position where you can force a win no matter what you opponents does. This can be achieved by creating a sequence called the 'magic 7' as shown below:
In this position red can force a win as they have positions 'x' and 'y' where both result in a win for red.