72 lines
2.5 KiB
JavaScript
72 lines
2.5 KiB
JavaScript
import "./style.css";
|
|
import * as E from "../engine/index.js";
|
|
import { mountGame } from "./ui.js";
|
|
import { chapterMetadata } from "./tutorials.js";
|
|
import { mountLesson } from "./index.js";
|
|
const params = new URLSearchParams(location.search),
|
|
chapter = params.get("chapter"),
|
|
target = document.querySelector("#game"),
|
|
nav = document.querySelector("#preview-nav");
|
|
nav.className = "practice-nav";
|
|
nav.innerHTML = `<span>Private local playtest</span><a href="/">Practice game</a><label>Learn <select aria-label="Tutorial chapter"><option value="">Choose a chapter</option>${chapterMetadata.map((c) => `<option value="${c.id}" ${c.id === chapter ? "selected" : ""}>${c.title}</option>`).join("")}</select></label>${chapter ? "" : '<button id="new-three">New 3-colony game</button><button id="new-four">New 4-colony game</button>'}`;
|
|
nav.querySelector("select").addEventListener("change", (e) => {
|
|
location.href = e.target.value ? `/?chapter=${e.target.value}` : "/";
|
|
});
|
|
if (chapter) {
|
|
const next =
|
|
chapterMetadata[chapterMetadata.findIndex((c) => c.id === chapter) + 1];
|
|
await mountLesson(target, {
|
|
chapter,
|
|
nextChapter: next
|
|
? {
|
|
id: next.id,
|
|
title: next.title,
|
|
open() {
|
|
location.href = `/?chapter=${next.id}`;
|
|
},
|
|
}
|
|
: undefined,
|
|
});
|
|
} else {
|
|
let state;
|
|
try {
|
|
state = JSON.parse(localStorage.getItem("soup:practice:1"));
|
|
} catch {}
|
|
if (!state || state.version !== 1)
|
|
state = E.init(3, [], {}, "practice-" + Date.now());
|
|
state.players.forEach((p, i) => (p.name = ["You", "Maya", "Leo", "Nina"][i]));
|
|
const ui = mountGame(target, {
|
|
onMove: async (m) => {
|
|
state = E.move(state, m, 0);
|
|
draw();
|
|
await bots();
|
|
},
|
|
});
|
|
ui.setPlayer(0);
|
|
const draw = () => {
|
|
ui.render(E.stripSecret(state));
|
|
try {
|
|
localStorage.setItem("soup:practice:1", JSON.stringify(state));
|
|
} catch {}
|
|
};
|
|
async function bots() {
|
|
let n = 0;
|
|
while (!E.ended(state) && E.currentPlayer(state) !== 0 && n++ < 500) {
|
|
await new Promise((r) => setTimeout(r, 180));
|
|
state = E.moveAI(state, E.currentPlayer(state));
|
|
draw();
|
|
}
|
|
}
|
|
for (const count of [3, 4])
|
|
nav
|
|
.querySelector(count === 3 ? "#new-three" : "#new-four")
|
|
.addEventListener("click", () => {
|
|
localStorage.setItem(
|
|
"soup:practice:1",
|
|
JSON.stringify(E.init(count, [], {}, "practice-" + Date.now())),
|
|
);
|
|
location.reload();
|
|
});
|
|
draw();
|
|
await bots();
|
|
}
|