Wire up main module with event handling and game loop

This commit is contained in:
Jared Miller 2026-02-23 17:40:36 -05:00
parent 87d2724c3c
commit 8a7facb35e
Signed by: shmup
GPG key ID: 22B5C6D66A38B06C

110
src/main.js Normal file
View file

@ -0,0 +1,110 @@
import { getCard } from "./cards.js";
import { checkCombatEnd, resolveEnemyTurn, startTurn } from "./combat.js";
import { createCombatState, endTurn, playCard } from "./state.js";
import { render } from "./render.js";
let state = null;
function init() {
state = createCombatState("ironclad", "jaw_worm");
state = startTurn(state);
render(state);
bindEvents();
}
function bindEvents() {
document.getElementById("hand").addEventListener("click", (e) => {
const cardEl = e.target.closest(".card");
if (!cardEl || state.combat.phase !== "player_turn") return;
const index = Number(cardEl.dataset.index);
if (state.combat.selectedCard === index) {
state = { ...state, combat: { ...state.combat, selectedCard: null } };
render(state);
return;
}
state = { ...state, combat: { ...state.combat, selectedCard: index } };
const cardId = state.player.hand[index];
const card = getCard(cardId);
if (card.type === "skill") {
// auto-play skills (they target self)
const result = playCard(state, index);
if (result === null) {
// not enough energy
state = { ...state, combat: { ...state.combat, selectedCard: null } };
render(state);
return;
}
state = { ...result, combat: { ...result.combat, selectedCard: null } };
const end = checkCombatEnd(state);
if (end) {
state = {
...state,
combat: { ...state.combat, phase: "ended", result: end },
};
}
render(state);
return;
}
render(state);
});
document.getElementById("enemy-zone").addEventListener("click", () => {
if (state.combat.selectedCard === null) return;
if (state.combat.phase !== "player_turn") return;
const result = playCard(state, state.combat.selectedCard);
if (result === null) {
state = { ...state, combat: { ...state.combat, selectedCard: null } };
render(state);
return;
}
state = { ...result, combat: { ...result.combat, selectedCard: null } };
const end = checkCombatEnd(state);
if (end) {
state = {
...state,
combat: { ...state.combat, phase: "ended", result: end },
};
render(state);
return;
}
render(state);
});
document.getElementById("end-turn-btn").addEventListener("click", async () => {
if (state.combat.phase !== "player_turn") return;
state = endTurn(state);
render(state);
await delay(800);
state = resolveEnemyTurn(state);
const end = checkCombatEnd(state);
if (end) {
state = {
...state,
combat: { ...state.combat, phase: "ended", result: end },
};
render(state);
return;
}
state = startTurn(state);
render(state);
});
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
init();