Skip to content

Commit

Permalink
implement ai opponent, random strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
soryy708 committed May 23, 2023
1 parent d18ad87 commit ecae4b3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/front/game/ai/solver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { BoardPosition } from '../board/abstract-board';
import { Board } from '../board/board';
import { GamePiece } from '../piece/interface';

export class AiSolver {
constructor(private board: Board) {}

solveNextTurn(_piece: GamePiece): { x: BoardPosition; y: BoardPosition } {
// eslint-disable-next-line no-constant-condition
while (true) {
const randomX: BoardPosition = Math.floor(
Math.random() * 4,
) as never;
const randomY: BoardPosition = Math.floor(
Math.random() * 4,
) as never;
if (this.board.canStack(randomX, randomY)) {
return { x: randomX, y: randomY };
}
}
}
}
16 changes: 16 additions & 0 deletions src/front/game/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { GamePiece } from './piece/interface';
import { WinChecker } from './win';
import { showMessageBar } from './message-bar';
import { Vector } from '../engine/math/vector';
import { AiSolver } from './ai/solver';

type Player = 'player1' | 'player2';

Expand All @@ -23,6 +24,7 @@ export class Game {
private pointer: Pointer;
private boardPosition: { x: BoardPosition; y: BoardPosition } = null;
private winChecker: WinChecker;
private ai: AiSolver;

constructor(private engine: Engine) {}

Expand All @@ -40,6 +42,7 @@ export class Game {
this.orbitIo.setTarget(this.board.getCenter());
this.pointer.onClick(() => this.onClick());
this.winChecker = new WinChecker(this.board);
this.ai = new AiSolver(this.board);
}

tick(_deltaTime: number) {
Expand Down Expand Up @@ -112,11 +115,24 @@ export class Game {

if (this.currentPlayer === 'player1') {
this.currentPlayer = 'player2';
this.playAsAi();
} else {
this.currentPlayer = 'player1';
}
}

private playAsAi(): void {
const position = this.ai.solveNextTurn(
new Nought({ x: 0, y: 0, z: 0 }),
);
const piece = this.buildCurrentPlayerPiece({
...position,
z: this.board.getStackHeight(position),
});
this.board.stack(position, piece);
this.advanceTurn();
}

private reset() {
this.currentPlayer = 'player1';

Expand Down

0 comments on commit ecae4b3

Please sign in to comment.