Skip to content

Instantly share code, notes, and snippets.

View parzibyte's full-sized avatar
💻
Coding

Parzibyte parzibyte

💻
Coding
View GitHub Profile
cellImage(cell) {
if (cell === this.PLAYER_1) {
return "img/player1.png";
} else if (cell === this.PLAYER_2) {
return "img/player2.png";
} else {
return "img/empty.png"
}
},
/*
____ _____ _ _ _
| _ \ | __ \ (_) | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___|
__/ | __/ |
|___/ |___/
getBestColumnForCpu() {
const winnerColumn = this.getWinnerColumn(this.board, this.currentPlayer);
if (winnerColumn !== -1) {
console.log("Cpu chooses winner column");
return winnerColumn;
}
// Check if adversary wins in the next move, if so, we take it
const adversary = this.getAdversary(this.currentPlayer);
const winnerColumnForAdversary = this.getWinnerColumn(this.board, adversary);
async makeCpuMove() {
if (!this.isCpuPlaying || this.currentPlayer !== PLAYER_CPU) {
return;
}
const bestColumn = this.getBestColumnForCpu();
const firstEmptyRow = this.getFirstEmptyRow(bestColumn, this.board);
console.log({ firstEmptyRow });
Vue.set(this.board[firstEmptyRow], bestColumn, this.currentPlayer);
const status = await this.checkGameStatus();
if (!status) {
isTie(board) {
for (let y = 0; y < ROWS; y++) {
for (let x = 0; x < COLUMNS; x++) {
const currentCell = board[y][x];
if (currentCell === EMPTY_SPACE) {
return false;
}
}
}
return true;
isWinner(player, board) {
for (let y = 0; y < ROWS; y++) {
for (let x = 0; x < COLUMNS; x++) {
let count = 0;
count = this.countUp(x, y, player, board);
if (count >= CONNECT) return true;
count = this.countRight(x, y, player, board);
if (count >= CONNECT) return true;
count = this.countUpRight(x, y, player, board);
if (count >= CONNECT) return true;
countUp(x, y, player, board) {
let startY = (y - CONNECT >= 0) ? y - CONNECT + 1 : 0;
let counter = 0;
for (; startY <= y; startY++) {
if (board[startY][x] === player) {
counter++;
} else {
counter = 0;
}
}
// Returns true if there's a winner or a tie. False otherwise
async checkGameStatus() {
if (this.isWinner(this.currentPlayer, this.board)) {
await this.showWinner();
return true;
} else if (this.isTie(this.board)) {
await this.showTie();
return true;
}
return false;
async makeMove(columnNumber) {
const columnIndex = columnNumber - 1;
const firstEmptyRow = this.getFirstEmptyRow(columnIndex, this.board);
if (firstEmptyRow === -1) {
Swal.fire('Cannot put here, it is full');
return;
}
Vue.set(this.board[firstEmptyRow], columnIndex, this.currentPlayer);
const status = await this.checkGameStatus();
if (!status) {
async resetGame() {
await this.askUserGameMode();
this.fillBoard();
this.selectPlayer();
this.makeCpuMove();
},