Connect 4 Prototype 2
by Sam Fereday
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
*/
/* Consts And Settings */
const OWNER_TYPES = {
NONE: 0,
PLAYERA: 1,
PLAYERB: 2
}
/* Grid Section */
class Cell {
constructor(x, y, ownerType = OWNER_TYPES.NONE) {
this.x = x;
this.y = y;
this.owner = ownerType;
}
}
const makeGrid = (w = 7, h = 6) => {
let cells = [];
for (let col = w; col >= 0; col--) {
for (let row = h; row >= 0; row--) {
cells.push(new Cell(col, row));
}
}
return cells;
}
// Utils
const isMine = (x, y, items, expected) => {
const item = items.find(it => it.x === x && it.y === y);
return item && expected === item.owner;
}
// Test (We also flag a four in a row to test)
const testGrid = makeGrid(4, 4);
// Plot a few points the player has placed.
const plotted = testGrid.map(item => {
if (item.x === 3 && item.y === 0) {
return {
...item,
owner: 1
}
}
if (item.x === 2 && item.y === 1) {
return {
...item,
owner: 1
}
}
if (item.x === 1 && item.y === 2) {
return {
...item,
owner: 1
}
}
if (item.x === 0 && item.y === 3) {
return {
...item,
owner: 1
}
}
return { ...item };
})
.filter(item => item.owner !== 0); // We also only care about occupied nodes.
/* Scoring Logic Section */
// Now we check to see for any rows in any given direction
const analyseDirection = (startPoint, dx, dy) => {
let vectorSteps = [];
for (let i = 0; i < 4; i++) {
//const x = dx !== 0 ? dx > 0 ? i : -i : 0;
const x = dx !== 0 ?
const y = dy !== 0 ? dy > 0 ? i : -i : 0;
if (isMine(startPoint.x + x, startPoint.y + dy, plotted, 1)) {
vectorSteps.push({
startPoint,
node: {
x,
y,
owner: startPoint.owner
}
});
}
}
return vectorSteps;
}
// Create a...