This project started with me wondering how difficult it would be to make connect 4 with HTML/CSS/JS. I built a quick prototype with jQuery and was pleased that it worked. I ended up switching to Angular mostly because of the huge stack of html that I had to insert to get all of the cells, and thought Angular's repeater would work nicely for that.
Before talking about the AI, I'd like to mention that since building this I've read about mathematically perfect connect 4 AI's that look at every possible game path and always choose the best option and can't be beat (but can be tied). This AI is not that. I wanted to build the computer to play how a human plays the game. First the computer will say 'can I win right now?' and take action if it can. Failing that, it will say 'can the opponent win as soon as they go?' at which point it will prevent that. After that it will re-examine both of those scenarios, but 2 turns out rather than one. If all of that fails, it will just play randomly. It does this by looking for patterns in the horizontal rows, vertical columns, and diagonals. For example, it knows that if this exists in a horizontal row: [0,r,r,r] (r being red, 0 being empty) it needs to first check if there's anything under that 0 for it's piece to land on, and if so, play there to block the opponents win.
If you're a developer, feel free to fork this off and make something cool, just attribute me please =]
AI Comments