Skip to the content of the web site.

Project M.3: Connect four

Write a game to play Connect Four. The trademark Connect Four is held by Milton Bradley.

Start by displaying the available positions by

a b c d e f g
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .

Do you wish to move first (y/n)?

A player then indicates where the player plays a piece by entering a column. Indicate moves by either an 'x' or an 'o'. You will have to redraw the board each time a piece is played; however, the computer should play before the board is redrawn.

Enter a column: c

a b c d e f g
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . x o . . .

Enter a column:

If a column is full, don't print the corresponding column identifier:

a b c   e f g
. . . x . . .
. . o o . . .
. x x x o . .
. x o o x . .
. o o x x . o
. o x o x . x

Enter a column:

There are three outcomes: the player wins, there is a draw or the computer wins.

You should try to program strategies for winning.

Your computer's strategy should be implemented as a function that takes in a two-dimensional character array and returns a character.

char calculate_move( char board[6][7] );

This function will perform two operations:

  • it will return the column in which a piece was moved, and
  • it will update the board.

This way, you could have your computer program play against another by passing the board back and forth, each time checking if there was a win.

Special rule

If the first player places a piece in the central column (d), there is a simple straggly that allows that player to always win regardless of any move the opponent makes. You should require that the first move is not in the central column.