84 lines
1.5 KiB
TypeScript
84 lines
1.5 KiB
TypeScript
/* eslint-disable @typescript-eslint/prefer-for-of */
|
|
/* eslint-disable @typescript-eslint/member-ordering */
|
|
import { Component, OnInit } from '@angular/core';
|
|
import { AiService } from '../ai.service';
|
|
|
|
@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[];
|
|
history: any[];
|
|
|
|
constructor() {}
|
|
|
|
ngOnInit(): void {
|
|
this.resetGame();
|
|
}
|
|
|
|
resetGame() {
|
|
this.winner = null;
|
|
this.draw = false;
|
|
this.xIsNext = true;
|
|
this.fields = Array(9).fill(null);
|
|
this.history = [];
|
|
}
|
|
|
|
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.history.push(this.fields.slice());
|
|
|
|
this.xIsNext = !this.xIsNext;
|
|
this.calculateWinner();
|
|
}
|
|
}
|
|
|
|
calculateWinner() {
|
|
const winners = [
|
|
[0, 1, 2],
|
|
|
|
[3, 4, 5],
|
|
|
|
[6, 7, 8],
|
|
|
|
[0, 3, 6],
|
|
|
|
[1, 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;
|
|
}
|
|
}
|