[Home] [Puzzles & Projects] [Delphi Techniques] [Math topics] [Library] [Utilities]
Here is version 1 of Four-In-A-Row, also known as Connect-4, or Connect Four. It's an extended version of Tic-Tac-Toe with the winner being the first player to get 4 tokens in line, horizontally, vertically, or diagonally.
The game is normally played on a board that is 7 columns wide and 6 rows high with the additional constraint that a token played in any column must occupy the lowest empty space in that column.
This Version 1 implements Human vs. Human play; a future version will add computer play.
Background & Techniques
The mechanical version of FourInARow typically stands upright with separators between columns so that token dropped into any column will automatically fall to the lowest open spot in that column. This version is introduced mainly to describe the graphics and animation framework before we go on to explore a computerized minimax search for winning plays.
Non-programmers are welcome to skip to the bottom of the page and download the executable version of this Human vs. Human version. There are, however dozens of free versions around including many online Java versions.
For simplicity, there are a number of constants defined up front to define board sizes and colors. Most of these could become user controlled variables in a future version.
Board is defined as 2 dimensional array of integers: 0 represents an empty slot, 1 and 2 indicate that that space is occupied by players 1 and 2 respectively. Image1 is a TImage component which holds the board image. I chose a circular TShape component, NewChip, to represent the next token to be played. To move, NewChip is dragged horizontally across the top of the board image and dropped on the selected column. Both Image1 and NewChip were dropped on a TPanel in order to simplify coordinate calculations. (The panel is a TWindow control that is the parent of both NewChip and Image1. Image1 is aligned to fill the panel, so drawing of both board and token can be referenced to (0,0) in the upper left corner. If the advantage of that isn't clear, make version without the Panel and it will be. )
OnMouse exits for NewChip are used to detect selecting, moving and dropping the token. At drop time, the token is moved incrementally in a delay loop down to the lowest open position. Once there, a circle is drawn on the image and NewChip is drawn back to it's starting position (with the other player's color of course).
Everything else is pretty straightforward:
Next time we'll explore the Minimax search algorithm for this game, assuming I get it working better than it is now - I beat the computer regularly, which I'm pretty sure is not due to my superior intelligence.
Suggestions for Further Explorations
Copyright © 2000-2018, Gary Darby All rights reserved.