I have just watched a video on You Tube by Ania Kubow where she explains how to create a Connect 4 game by coding in JavaScript.
The video is here: Connect Four in JavaScript - YouTube
What I would like to know is how to work out the winning combinations, can anyone assist?
If I were building this, I would probably have a two dimensional array that starts out as undefined. Then I would add in a 1 or a 2, for first and second player. Then, at the end of each move, for that square, I would check in each of the eight directions. One simple way would be to grab the three in each direction, compact them into a string 7 chars long, then search for either “1111” or “2222”, depending. There are probably sexier ways to do it, but that works.
Hi,
Thanks for the reply. I don’t know if you have watched the You Tube video as Ania Kubow has an array named winningArray. I would like to know how she worked out all of the winning combinations.
They’re not “worked out”, they’re hardcoded / copy-pasted from somewhere. Presumably because that tutorial is more about DOM manipulation, while the problem to find the winning combinations is mostly an algorithm challenge.
Thinking on this a little more, if we wanted a more efficient algorithm…
There are eight directions, but we really only need to test half of those - if there is a line of four going south, that is also a line of 4 going north. Also, we don’t need to check every square - for example, if am working through the squares left to right and down, if I encounter a square and want to see if there is a line of four extending south, if there is a “positive” square to the north of it, there is no need to check because it would have already been checked once before.
So, I would work left to right and top to bottom. When I get to a square, I want to check lines going S, going E, going SE, and going SW. Before checking each of those, I peek at the square before it (so if I’m checking SE, I check the square NW) - if it is “positive” then I don’t need to bother checking. And of course, I only need to check the current player.
To me that is a nice clean algorithm that would be efficient. I can’t think of a way to make it more efficient, but maybe someone smarter than me can.
She may or may not have used a formula, but in terms of implementation, she just wrote out every possible win. If it was tic tac toe, if this is the board:
Those are the only possible wins, period. So, you just check if it matches. It’s a simple solution, if not particularly “elegant”. That’s what she’s done.
There are other ways to do it. I mentioned one. You could also generate this list dynamically.