Skip to content

Instantly share code, notes, and snippets.

@newbornfrontender
Created October 5, 2019 16:28
Show Gist options
  • Save newbornfrontender/caaca21d9a1e64cb7b0c8ee1cc2a6f0e to your computer and use it in GitHub Desktop.
Save newbornfrontender/caaca21d9a1e64cb7b0c8ee1cc2a6f0e to your computer and use it in GitHub Desktop.
Game - helpers
export const createTable = (rowNum: number, cellNum: number): number[][] => {
const row: number[] = Array(rowNum).fill(0);
const table: number[][] = Array(cellNum)
.fill(row)
.map((row: number[]) => [...row]);
return table;
};
export const recalculateTable = (table: number[][], index: number, value: number): number[][] => {
return table.map((row: number[], i: number) => {
if (index === i) {
let emptyCell: number = row.indexOf(0);
row[emptyCell] = value;
}
return [...row];
});
};
const checkVertical = (table: number[][]) => {
for (let r = 3; r < 7; r++) {
for (let c = 0; c < 6; c++) {
if (table[r][c]) {
if (
table[r][c] === table[r - 1][c] &&
table[r][c] === table[r - 2][c] &&
table[r][c] === table[r - 3][c]
) {
return table[r][c];
}
}
}
}
};
const checkHorizontal = (table: number[][]) => {
for (let r = 0; r < 7; r++) {
for (let c = 0; c < 4; c++) {
if (table[r][c]) {
if (
table[r][c] === table[r][c + 1] &&
table[r][c] === table[r][c + 2] &&
table[r][c] === table[r][c + 3]
) {
return table[r][c];
}
}
}
}
};
const checkDiagonalRight = (table: number[][]) => {
for (let r = 3; r < 7; r++) {
for (let c = 0; c < 5; c++) {
if (table[r][c]) {
if (
table[r][c] === table[r - 1][c + 1] &&
table[r][c] === table[r - 2][c + 2] &&
table[r][c] === table[r - 3][c + 3]
) {
return table[r][c];
}
}
}
}
};
const checkDiagonalLeft = (table: number[][]) => {
for (let r = 3; r < 6; r++) {
for (let c = 3; c < 7; c++) {
if (table[r][c]) {
if (
table[r][c] === table[r - 1][c - 1] &&
table[r][c] === table[r - 2][c - 2] &&
table[r][c] === table[r - 3][c - 3]
) {
return table[r][c];
}
}
}
}
};
const checkDraw = (table: number[][]) => {
for (let r = 0; r < 6; r++) {
for (let c = 0; c < 7; c++) {
if (table[r][c] === 0) {
return 0;
}
}
}
return 'draw';
};
export const checkWinner = (table: number[][]) => {
return (
checkVertical(table) ||
checkDiagonalRight(table) ||
checkDiagonalLeft(table) ||
checkHorizontal(table) ||
checkDraw(table)
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment