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:
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.
6 Answers 6
Looks like your code is correct for the horizontal and vertical cases. The tricky part is the diagonal case.
Let’s try a picture:
For the green lines, your starting row position is 0 . maxRow – 4. The column would be 0 . startingRow –
You could do something similar for diagonals going the other way (from bottom-left to top-right).
For some reason I am not so fond of counters, so I did it this way (It works for boards with different sizes).
So, having dug through your code, it would seem that the diagonal check can only win in a single direction (what happens if I add a token to the lowest row and lowest column?)
Instead, the basic check algorithm is always the same process, regardless of which direction you’re checking in.
You need a start point (x/y) and x/y delta (direction of movement). You can summarise this down into a single method.
This will basically allow you to check in four directions, but also do them backwards
So, if we were to use something like.
Now, you could just summarise it down to.
So, using something like.
Which prints out something like.
I would add that this approach does only work if you provide the correct start of the 4 chips on a row. For example didWin(gridTable, 1, 3, 3) will provide false instead of true for your horizontal check, because the loop can only check one direction.
The intention wasn’t to provide a “full fledged, out of the box” solution, but a concept from which a broader solution could be developed (I mean, I’d hate for people to actually have to think ;)). I also designed the solution based on the idea that the OP would know where the last piece was placed, ie, the starting point 😉
By modifying the didWin method ever so slightly, it’s possible to check a n by n grid from any point.
and was able to get it to work. Sometimes an answer isn’t a complete solution, but a seed for an idea which takes someone to a new place 😉
I further enhancement would include providing the number of expected conjoined pieces, but I’m pretty sure that’s an enhancement I really don’t need to demonstrate 😉
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,