initial commit
This commit is contained in:
76
src/app/board/board.component.ts
Normal file
76
src/app/board/board.component.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'app-board',
|
||||
templateUrl: './board.component.html',
|
||||
styleUrls: ['./board.component.scss'],
|
||||
})
|
||||
export class BoardComponent implements OnInit {
|
||||
winner: string;
|
||||
draw: boolean;
|
||||
xIsNext: boolean;
|
||||
fields: any[];
|
||||
|
||||
constructor() {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.resetGame();
|
||||
}
|
||||
|
||||
resetGame() {
|
||||
this.winner = null;
|
||||
this.draw = false;
|
||||
this.xIsNext = true;
|
||||
this.fields = Array(9).fill(null);
|
||||
}
|
||||
|
||||
get player() {
|
||||
return this.xIsNext ? 'X' : 'O';
|
||||
}
|
||||
|
||||
playerPress(i: number) {
|
||||
if(this.winner != null) {
|
||||
this.resetGame();
|
||||
return;
|
||||
}
|
||||
if (!this.fields[i]) {
|
||||
this.fields.splice(i, 1, this.player);
|
||||
|
||||
this.xIsNext = !this.xIsNext;
|
||||
this.calculateWinner();
|
||||
}
|
||||
}
|
||||
|
||||
calculateWinner() {
|
||||
const winners = [
|
||||
[0, 1, 2],
|
||||
|
||||
[3, 4, 5],
|
||||
|
||||
[6, 7, 8],
|
||||
|
||||
[0, 3, 6],
|
||||
|
||||
[2, 4, 7],
|
||||
|
||||
[2, 5, 8],
|
||||
|
||||
[0, 4, 8],
|
||||
|
||||
[2, 4, 6],
|
||||
];
|
||||
for (let i = 0; i < winners.length; i++) {
|
||||
const [a, b, c] = winners[i];
|
||||
|
||||
if (
|
||||
this.fields[a] &&
|
||||
this.fields[a] === this.fields[b] &&
|
||||
this.fields[a] === this.fields[c]
|
||||
) {
|
||||
this.winner = this.fields[a];
|
||||
return this.fields[a];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user