Connect 4 Prototype 2

by Sam Fereday

HTML

<button id="start">
Start
</button>

JavaScript 1.7

/*
- 7x6 grid
- 21 checkers each (black and red)
- 2 players
- must score 4 in a row horizontally, vertically or diagonally
- consider using redux as single source of truth

From doc:
Requirements
● Allow each player to enter their name before starting the game.
● One player is given red counters, one player is given yellow counters.
● The game board must be a seven-column, six-row grid.
● The players select a column to place their counter. Counters fall straight down, occupying the next available space within the column.
● The game is won by the first player to form a horizontal, vertical, or diagonal line of four of their own counters.
● Store the name of the winning player.
● Have a ‘hall of fame’ button that launches a modal dialogue that displays an ordered list of the top winning players, with how many games they have won.
Recommended Technologies
● React
● GraphQL
● Node.js
● MongoDB
*/

/* Consts And Settings */
const OWNER_TYPES = {
  EMPTY: 0,
  PLAYERA: 1,
  PLAYERB: 2
}

const VICTORY_VALUE = 4;

const MAP_CONFIG = {
  WIDTH: 7,
  HEIGHT: 6
}

/* Grid  Section */
class Cell {
  constructor(x, y, ownerType = OWNER_TYPES.NONE) {
    this.x = x;
    this.y = y;
    this.owner = ownerType;
  }
}

const makeGrid = (w, h) => {
  let cells = [];
  for (let col = w; col >= 0; col--) {
    for (let row = h; row >= 0; row--) {
      cells.push(new Cell(row, col));
    }
  }
  return cells;
}

// Utils
const getRandomIntInclusive = (_min, _max) => {
  const min = Math.ceil(_min);
  const max = Math.floor(_max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

const findItemAt = (x, y, items) =>
  items.find(item => item.x === x && item.y === y);

const findFirstEligibleSlot = (x, items) =>
  items.find(item => item.x === x && item.owner === OWNER_TYPES.EMPTY);

const findAllEligibleColumns = (items) =>
  items.reduce((acc, cur) => {

    const {
      owner,
      x
    } = cur;

    if (owner === OWNER_TYPES.EMPTY && !acc.some(n => n == x)) {
    ...