Search⌘ K
AI Features

Connect-4 Solver

Discover how to implement an ES6 solution to detect a winner in Connect-4 by checking four consecutive symbols horizontally and vertically. Explore array manipulation, recursion, and practical use of arrow functions and map to simplify the logic for game state evaluation.

We'll cover the following...

Suppose an 8*6 Connect-Four table is given. Each cell of the table is either empty (null), or contains the player’s number from the possible values 1 and 2. Determine if any player has won the game by connecting four of their symbols horizontally or vertically. For simplicity, ignore diagonal matches.

Solution:

As there is no example data, we have to model the table ourselves.

Node.js
const createEmptyTable = () =>
new Array( 8 ).fill( null ).map(
() => new Array( 6 ).fill( null )
);

This simple arrow function returns an empty 6*8 array:

Node.js
let table = createEmptyTable()
console.log(table)

It is evident that we will need a function that checks all elements of the array for four consecutive matches. I encourage you to implement this function yourself. Reading my ...