Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨Feature: QuantumTTT vs AI mode #215

Merged
merged 6 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
227 changes: 227 additions & 0 deletions src/lib/games/quantum-tictactoe/AiApp.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
<!--
QuantumTicTacToe is made by Rohan Pandit in 2017 and changed by Shouhei Uechi in 2021.
Copyright (C) 2021 Shouhei Uechi
Copyright (C) 2017 Rohan Pandit, available at <https://github.com/rohanp/QuantumTicTacToe/tree/master/>

This file is part of QuantumTicTacToe.

QuantumTicTacToe is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

QuantumTicTacToe is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with QuantumTicTacToe. If not, see <https://www.gnu.org/licenses/>.
-->
<script lang="ts">
import type { MaxLengthArray } from '$lib/types/generics';
import { getRandomInt } from '$lib/utils/getRandomInt';
import { getOrdinal } from '$lib/utils/getNumeral';
import { sleep } from '$lib/utils/sleep';

import GameBoard from './GameBoard.svelte';
import GameInfo from './GameInfo.svelte';
import type { MarkType, SquareType } from './QuantumTTT.type';
import Game from './QuantumTTT';

let game = new Game();
let gameCount = 1;

let state = game.state;
let message = state.status;

$: choices =
state.collapseSquare !== null && state.cycleMarks !== null
? ((state.qSquares[state.collapseSquare] as Exclude<MaxLengthArray<MarkType, 9>, []>).filter(
(choice) => (state.cycleMarks as Exclude<typeof state.cycleMarks, []>).includes(choice)
) as MaxLengthArray<MarkType, 3> | undefined)
: undefined;

const handleSquareClick = (i: SquareType): void => {
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

改善の余地大いにあり

if (game.state.isOver) return;
const isPlayerMove = game.whoseTurn() === 'X' && !state.cycleSquares;
const isPlayerResolvableCollapse =
game.whoseTurn() === 'Y' && state.cycleSquares && state.cycleSquares.length > 0;
if (isPlayerMove || isPlayerResolvableCollapse) {
const status = game.handleSquareClick(i);

if (import.meta.env.DEV) console.table(game.state);
state = { ...game.state };
message = status;
} else {
message = 'AI is thinking!';
return;
}

const isAIResolvableCollapse =
game.whoseTurn() === 'X' && state.cycleSquares && state.cycleSquares.length > 0;
if (isAIResolvableCollapse) {
message = 'AI is thinking...';
sleep(1200)
.then(async () => {
await aiResolveCollapse();
await sleep(700);

if (game.state.isOver) {
message = game.state.status;
return;
}

message = 'AI is thinking...';
await sleep(1200);
aiMove();
return;
})
.catch((err) => {
console.error(err);
});
return;
}

const isAIMove = game.whoseTurn() === 'Y' && !state.cycleSquares;
if (isAIMove) {
message = 'AI is thinking...';
sleep(1200)
.then(() => {
aiMove();
})
.catch((err) => {
console.error(err);
});
}
return;
};

const aiMove = (): void => {
let cSquares: MaxLengthArray<SquareType, 9> = [];
for (let i = 0; i < 9; i++) {
if (state.cSquares[i] !== null) cSquares = [...cSquares, i as SquareType];
}
const aiMove1 = getRandomInt({ min: 0, max: 8, excepts: cSquares }) as SquareType;
const aiMove2 = getRandomInt({ min: 0, max: 8, excepts: [...cSquares, aiMove1] }) as SquareType;
game.handleSquareClick(aiMove1);

const status = game.handleSquareClick(aiMove2);
state = { ...game.state };
message = status;
return;
};

const aiResolveCollapse = async (): Promise<void> => {
if (state.cycleSquares != null) {
const randomInt = getRandomInt({ min: 0, max: state.cycleSquares.length - 1 });
const aiChoiceSquare = state.cycleSquares[randomInt];
game.handleSquareClick(aiChoiceSquare);
state = { ...game.state };
}

message = 'AI is thinking...';
await sleep(1200);
if (choices === undefined) return;
const aiChoiceMark = choices[getRandomInt({ min: 0, max: choices.length - 1 })];
game.handleCollapse(aiChoiceMark);
state = { ...game.state };

message = 'AI resolved collapse!';
return;
};

const handleCollapse = (mark: MarkType): void => {
const isPlayerResolvableCollapse = game.whoseTurn() === 'Y';
if (!isPlayerResolvableCollapse) return;

const status = game.handleCollapse(mark);

state = { ...game.state };
message = status;
return;
};

const handleNextGameClick = (): void => {
game = new Game();
game.setState({ scores: { ...state.scores } });
gameCount += 1;

state = { ...game.state };
message = `The ${getOrdinal(gameCount)} game!\n${game.state.status}`;
return;
};

const handleResetGameClick = (): void => {
game = new Game();
gameCount = 1;

state = { ...game.state };
message = game.state.status;
return;
};
</script>

<div class="game">
<GameBoard
cSquares={state.cSquares}
qSquares={state.qSquares}
cycleSquares={state.cycleSquares}
cycleMarks={state.cycleMarks}
collapseSquare={state.collapseSquare}
onSquareClick={handleSquareClick}
/>
<GameInfo
{choices}
status={message}
isGameOver={state.isOver}
scores={state.scores}
onChoiceClick={handleCollapse}
onNextGameClick={handleNextGameClick}
onResetGameClick={handleResetGameClick}
/>
</div>
<div class="game-footer">
<p>
<small>
<a rel="license" href="https://www.gnu.org/licenses/">GNU Public Licensed</a>
</small>
</p>
<p>
<small>
QuantumTicTacToe is written by Rohan Pandit in 2017 and changed by Shouhei Uechi in 2021.
</small>
<br />
<small>
Copyright &copy; 2021
<a rel="author" href="https://github.com/u-sho">Shouhei Uechi</a>. Rights reserved.
</small>
<br />
<small>
Copyright &copy; 2017 Rohan Pandit, available at
<a href="https://github.com/rohanp/QuantumTicTacToe/tree/master/">his GitHub repository</a>.
</small>
</p>
</div>

<style lang="scss">
.game {
display: flex;
flex-direction: row;
justify-content: center;
flex-wrap: wrap;
margin-top: 50px;
}

.game-footer {
width: 100%;
margin-top: 50px;
text-align: center;
background-color: var(--theme-color);
color: var(--bg-color);
a {
color: var(--bg-light-color);
text-decoration-line: underline;
}
}
</style>
49 changes: 49 additions & 0 deletions src/lib/utils/getRandomInt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
type GetRandomInt = (prop: { min?: number; max: number; excepts?: number[] }) => number;

const getRandomInt: GetRandomInt = ({ min, max, excepts }) => {
if (min === undefined) min = 0;
if (!Number.isInteger(min) || !Number.isInteger(max))
console.error('getRandomInt: arguments min and max should be integers.');

if (max < min) console.error('getRandomInt: argument max should be greater than min.');

if (excepts && !Array.isArray(excepts))
console.error('getRandomInt: argument excepts should be an array.');
if (excepts && Array.isArray(excepts)) {
while (excepts.includes(min)) min++;
while (excepts.includes(max)) max--;
if (max < min)
console.error(
'getRandomInt: range [min, max] must have at least one integer not included in excepts.'
);
}

let ret = Math.floor(Math.random() * (max - min + 1)) + min;
while (excepts && Array.isArray(excepts) && excepts.includes(ret))
ret = Math.floor(Math.random() * (max - min + 1)) + min;

return ret;
};

export { getRandomInt };

// test
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('getRandomInt', () => {
const min = 1;
const max = 10;
const n = getRandomInt({ min, max });
expect(n).toBeGreaterThanOrEqual(min);
expect(n).toBeLessThanOrEqual(max);
});
test('getRandomInt with excepts', () => {
const min = 1;
const max = 10;
const excepts = [1, 2, 3, 8, 10];
const n = getRandomInt({ min, max, excepts });
expect(n).toBeGreaterThanOrEqual(4);
expect(n).toBeLessThanOrEqual(9);
expect(excepts.includes(n)).toBe(false);
});
}
16 changes: 16 additions & 0 deletions src/lib/utils/sleep.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const sleep = async (ms: number): Promise<void> =>
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utils/ 系は該当の npm パッケージを使った方がいいかもしれない

new Promise((resolve) => setTimeout(resolve, ms));

export { sleep };

// test
if (import.meta.vitest) {
const { test, expect } = import.meta.vitest;
test('sleep', async () => {
const sleepTime = 100;
const start = Date.now();
await sleep(sleepTime);
const end = Date.now();
expect(end - start).toBeGreaterThanOrEqual(sleepTime);
});
}
4 changes: 4 additions & 0 deletions src/routes/games/quantum-tictactoe/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ let footerHeight: number;
>チュートリアル</a
>
</li>
<li>
<a class="btn" href="/games/quantum-tictactoe/play/ai" type="application/ecmascript">AI対局</a
>
</li>
<li>
<a class="btn" href="/games/quantum-tictactoe/play/human" type="application/ecmascript"
>オフライン対局</a
Expand Down
33 changes: 33 additions & 0 deletions src/routes/games/quantum-tictactoe/play/ai/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<script lang="ts">
import AiApp from '$lib/games/quantum-tictactoe/AiApp.svelte';
</script>

<svelte:head>
<link rel="canonical" href="https://qgame.app/games/quantum-tictactoe/play/human" />
<title>Quantum Tic-Tac-Toe - Quantum Game Arena</title>
<meta property="og:url" content="https://qgame.app/games/quantum-tictactoe/play/human" />
<meta property="og:title" content="Quantum Tic-Tac-Toe - Quantum Game Arena" />
</svelte:head>

<main class="main">
<!-- <SvelteDipper /> -->
<h1 class="title">Quantum Tic-Tac-Toe</h1>
<AiApp />
</main>

<style lang="scss">
.main {
width: 100%;
height: 100%;
min-height: calc(100svh - var(--header-height));
padding-top: var(--header-height);
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
}

.title {
text-align: center;
}
</style>
9 changes: 8 additions & 1 deletion static/sitemap.xml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

<url>
<loc>https://qgame.app/games/quantum-tictactoe</loc>
<lastmod>2022-09-29</lastmod>
<lastmod>2024-05-04</lastmod>
<changefreq>yearly</changefreq>
<priority>0.8</priority>
</url>
Expand All @@ -20,6 +20,13 @@
<changefreq>yearly</changefreq>
</url>

<url>
<loc>https://qgame.app/games/quantum-tictactoe/play/ai</loc>
<lastmod>2024-05-04</lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>

<url>
<loc>https://qgame.app/games/quantum-tictactoe/play/human</loc>
<lastmod>2023-12-22</lastmod>
Expand Down
Loading