Skip to content
Advertisement

Connect 4 check for a win algorithm

I know there is a lot of of questions regarding connect 4 check for a win. The issue is that most of other algorithms make my program have runtime errors, because they try to access an index outside of my array. My algorithm is like this:

JavaScript

count is the variable that checks for a win if count is equal or more than 4 means they should be 4 or more consecutive tokens of the same player.

THE PROBLEM: sometimes the method checks for a win without being 4 tokens in order and other times does not check for a win when 4 tokens are in order.

Advertisement

Answer

Looks like your code is correct for the horizontal and vertical cases. The tricky part is the diagonal case.

Let’s try a picture:

red and green diagonal lines from left to right across the board

For the green lines, your starting row position is 0 … maxRow – 4. The column would be 0 … startingRow –

Pseudocode:

JavaScript

You could do something similar for diagonals going the other way (from bottom-left to top-right).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement