In a text-based version of this, I had an array which represented the board (as in Dim board(6,7)) to represent the six rows and seven columns. Each location in the array was filled with '0' if nobody occupied that location, '1' if player 1 occupied it, and '2' if player 2 occupied it. Next I wrote a function which looked like the following (doing this from memory):
This worked fine and was faster than using loops. Then I used this logic in a Alpha-Beta A* algorithm (for the computer AI). It was way too slow. I then had to encode the board into bits for each player's locations. I then 'And'ed the numbers against a set which represented winning lines. This was VERY fast, but obfuscated. For example, visualize this 3x3 board for Tic-Tac-Toe:
O O X
O X X
X O X
X's representation would be (001 011 101) in binary or 93 in decimal. O's representation would be (110 100 010) or 418 in decimal. The winning positions would be (111 000 000), (000 111 000), (000 000 111), (100 100 100), (010 010 010), (001 001 001), (100 010 001), and (001 010 100). (In decimal this is 384, 56, 7, 292, 146, 73, 273, and 84.)
And X's positions with each winning position to see if they match.
93 And 384 = 0. Fail.
93 And 56 = 24. Fail.
93 And 7 = 5. Fail.
...
93 And 84 = 84. Winner!
This method is insanely fast, but I only recommend it if you are writing an AI for your Connect4 program. Of course, you have to modify my example to work with Connect4, but it takes only a little effort.
Function checkWin( player ) If board(1,1) = player And board(1,2) = player And board(1,3) = player And board(1,4) = player Then Return True If board(1,2) = player And board(1,3) = player And board(1,4) = player and board(1,5) = player Then Return True ; Continue this for all rows, columns, and diagonals. Return False End Function
This worked fine and was faster than using loops. Then I used this logic in a Alpha-Beta A* algorithm (for the computer AI). It was way too slow. I then had to encode the board into bits for each player's locations. I then 'And'ed the numbers against a set which represented winning lines. This was VERY fast, but obfuscated. For example, visualize this 3x3 board for Tic-Tac-Toe:
O O X
O X X
X O X
X's representation would be (001 011 101) in binary or 93 in decimal. O's representation would be (110 100 010) or 418 in decimal. The winning positions would be (111 000 000), (000 111 000), (000 000 111), (100 100 100), (010 010 010), (001 001 001), (100 010 001), and (001 010 100). (In decimal this is 384, 56, 7, 292, 146, 73, 273, and 84.)
And X's positions with each winning position to see if they match.
93 And 384 = 0. Fail.
93 And 56 = 24. Fail.
93 And 7 = 5. Fail.
...
93 And 84 = 84. Winner!
This method is insanely fast, but I only recommend it if you are writing an AI for your Connect4 program. Of course, you have to modify my example to work with Connect4, but it takes only a little effort.