Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- );
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement