Skip to content

Instantly share code, notes, and snippets.

@rgaidot
Last active November 21, 2023 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgaidot/bf1364991bafa9cd55dcc1352270e645 to your computer and use it in GitHub Desktop.
Save rgaidot/bf1364991bafa9cd55dcc1352270e645 to your computer and use it in GitHub Desktop.
Tic Tac Toe
class Game {
private gameBoard: number[] = []; // 3x3 grid of squares
private playerPieces: string[] = ['X', 'O']; // array of player pieces (X or O)
private winningConditions: string[] = ['horizontally', 'vertically', 'diagonally']; // array of winning conditions
constructor() {
this.resetGame();
}
resetGame(): void {
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
this.gameBoard[i][j] = 0; // initialize game board with empty squares
}
}
this.playerPieces = [this.playerPieces[0], this.playerPieces[1]]; // reset player pieces to starting positions
}
checkWin(): boolean {
for (let i = 0; i < 3; i++) {
if (this.gameBoard[i][0] === this.playerPieces[0] && this.gameBoard[i][1] === this.playerPieces[1]) {
return true; // check for horizontal win
}
if (this.gameBoard[0][i] === this.playerPieces[0] && this.gameBoard[1][i] === this.playerPieces[1]) {
return true; // check for vertical win
}
if (this.gameBoard[0][0] === this.playerPieces[0] && this.gameBoard[1][1] === this.playerPieces[1]) {
return true; // check for diagonal win
}
}
return false; // no win, game continues
}
displayBoard(): void {
const htmlElement = document.createElement('div');
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
const square = document.createElement('div');
square.innerHTML = ` ${this.gameBoard[i][j]}`;
htmlElement.appendChild(square);
}
}
document.body.appendChild(htmlElement);
}
move Piece(piece: string, direction: string): void {
switch (direction) {
case 'left':
this.playerPieces = [...this.playerPieces, piece];
break;
case 'right':
this.playerPieces = [...this.playerPieces, piece];
break;
case 'up':
this.playerPieces = [piece, ...this.playerPieces];
break;
case 'down':
this.playerPieces = [...this.playerPieces, piece];
break;
}
this.checkWin();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment