Merge commit 'd49272e17e6b162b9bf4a6934d0f89de3285316e' into HEAD

This commit is contained in:
Scott Anderson
2025-05-13 03:40:58 -04:00
717 changed files with 14198 additions and 11204 deletions
+48
View File
@@ -0,0 +1,48 @@
import { z } from "zod";
import { base64urlToUuid } from "./Base64";
export const RefreshResponseSchema = z.object({
token: z.string(),
});
export type RefreshResponse = z.infer<typeof RefreshResponseSchema>;
export const TokenPayloadSchema = z.object({
jti: z.string(),
sub: z
.string()
.refine(
(val) => {
const uuid = base64urlToUuid(val);
return uuid != null;
},
{
message: "Invalid base64-encoded UUID",
},
)
.transform((val) => {
const uuid = base64urlToUuid(val);
if (!uuid) throw new Error("Invalid base64 UUID");
return uuid;
}),
iat: z.number(),
iss: z.string(),
aud: z.string(),
exp: z.number(),
rol: z
.string()
.optional()
.transform((val) => val.split(",")),
});
export type TokenPayload = z.infer<typeof TokenPayloadSchema>;
export const UserMeResponseSchema = z.object({
user: z.object({
id: z.string(),
avatar: z.string(),
username: z.string(),
global_name: z.string(),
discriminator: z.string(),
locale: z.string(),
}),
});
export type UserMeResponse = z.infer<typeof UserMeResponseSchema>;
+37
View File
@@ -0,0 +1,37 @@
import { base64url } from "jose";
/**
* Converts a UUID string to a base64url-encoded binary representation.
* @param uuid - The UUID string (e.g., '123e4567-e89b-12d3-a456-426614174000')
* @returns base64url string (e.g., 'Ej5FZ+i7EtOkVkJmFBdAAA')
*/
export function uuidToBase64url(uuid: string): string {
const hex = uuid.replace(/-/g, "");
const bytes = new Uint8Array(16);
for (let i = 0; i < 16; i++) {
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return base64url.encode(bytes);
}
/**
* Converts a base64url-encoded binary UUID back to its canonical UUID string.
* @param encoded - base64url string (e.g., 'Ej5FZ+i7EtOkVkJmFBdAAA')
* @returns UUID string (e.g., '123e4567-e89b-12d3-a456-426614174000')
*/
export function base64urlToUuid(encoded: string): string {
const bytes = base64url.decode(encoded);
const hex = Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20),
].join("-");
}
+47 -3
View File
@@ -11,7 +11,8 @@ import {
import { createGameRecord } from "../core/Util";
import { ServerConfig } from "../core/configuration/Config";
import { getConfig } from "../core/configuration/ConfigLoader";
import { Team, UnitType } from "../core/game/Game";
import { Cell, Team, UnitType } from "../core/game/Game";
import { TileRef } from "../core/game/GameMap";
import {
ErrorUpdate,
GameUpdateType,
@@ -28,6 +29,7 @@ import { endGame, startGame, startTime } from "./LocalPersistantStats";
import { getPersistentIDFromCookie } from "./Main";
import {
SendAttackIntentEvent,
SendBoatAttackIntentEvent,
SendHashEvent,
SendSpawnIntentEvent,
Transport,
@@ -221,6 +223,7 @@ export class ClientGameRunner {
public start() {
consolex.log("starting client game");
this.isActive = true;
this.lastMessageTime = Date.now();
setTimeout(() => {
@@ -362,8 +365,13 @@ export class ClientGameRunner {
this.myPlayer = myPlayer;
}
this.myPlayer.actions(tile).then((actions) => {
console.log(`got actions: ${JSON.stringify(actions)}`);
if (this.myPlayer === null) return;
const bu = actions.buildableUnits.find(
(bu) => bu.type == UnitType.TransportShip,
);
if (bu == null) {
console.warn(`no transport ship buildable units`);
return;
}
if (actions.canAttack) {
this.eventBus.emit(
new SendAttackIntentEvent(
@@ -371,6 +379,30 @@ export class ClientGameRunner {
this.myPlayer.troops() * this.renderer.uiState.attackRatio,
),
);
} else if (
bu.canBuild !== false &&
this.shouldBoat(tile, bu.canBuild) &&
this.gameView.isLand(tile)
) {
this.myPlayer
.bestTransportShipSpawn(this.gameView.ref(cell.x, cell.y))
.then((spawn: number | false) => {
let spawnCell = null;
if (spawn !== false) {
spawnCell = new Cell(
this.gameView.x(spawn),
this.gameView.y(spawn),
);
}
this.eventBus.emit(
new SendBoatAttackIntentEvent(
this.gameView.owner(tile).id(),
cell,
this.myPlayer.troops() * this.renderer.uiState.attackRatio,
spawnCell,
),
);
});
}
const owner = this.gameView.owner(tile);
@@ -382,6 +414,18 @@ export class ClientGameRunner {
});
}
private shouldBoat(tile: TileRef, src: TileRef) {
// TODO: Global enable flag
// TODO: Global limit autoboat to nearby shore flag
// if (!enableAutoBoat) return false;
// if (!limitAutoBoatNear) return true;
const distanceSquared = this.gameView.euclideanDistSquared(tile, src);
const limit = 100;
const limitSquared = limit * limit;
if (distanceSquared > limitSquared) return false;
return true;
}
private onMouseMove(event: MouseMoveEvent) {
this.lastMousePosition = { x: event.x, y: event.y };
this.checkTileUnderCursor();
+77 -18
View File
@@ -4,7 +4,13 @@ import randomMap from "../../resources/images/RandomMap.webp";
import { translateText } from "../client/Utils";
import { getServerConfigFromClient } from "../core/configuration/ConfigLoader";
import { consolex } from "../core/Consolex";
import { Difficulty, GameMapType, GameMode } from "../core/game/Game";
import {
Difficulty,
Duos,
GameMapType,
GameMode,
mapCategories,
} from "../core/game/Game";
import { GameConfig, GameInfo } from "../core/Schemas";
import { generateID } from "../core/Util";
import "./components/baseComponents/Modal";
@@ -23,6 +29,7 @@ export class HostLobbyModal extends LitElement {
@state() private selectedDifficulty: Difficulty = Difficulty.Medium;
@state() private disableNPCs = false;
@state() private gameMode: GameMode = GameMode.FFA;
@state() private teamCount: number | typeof Duos = 2;
@state() private disableNukes: boolean = false;
@state() private bots: number = 400;
@state() private infiniteGold: boolean = false;
@@ -73,23 +80,40 @@ export class HostLobbyModal extends LitElement {
<!-- Map Selection -->
<div class="options-section">
<div class="option-title">${translateText("map.map")}</div>
<div class="option-cards">
${Object.entries(GameMapType)
.filter(([key]) => isNaN(Number(key)))
.map(
([key, value]) => html`
<div @click=${() => this.handleMapSelection(value)}>
<map-display
.mapKey=${key}
.selected=${!this.useRandomMap &&
this.selectedMap === value}
.translation=${translateText(
`map.${key.toLowerCase()}`,
)}
></map-display>
<div class="option-cards flex-col">
<!-- Use the imported mapCategories -->
${Object.entries(mapCategories).map(
([categoryKey, maps]) => html`
<div class="w-full mb-4">
<h3
class="text-lg font-semibold mb-2 text-center text-gray-300"
>
${translateText(`map_categories.${categoryKey}`)}
</h3>
<div class="flex flex-row flex-wrap justify-center gap-4">
${maps.map((mapValue) => {
const mapKey = Object.keys(GameMapType).find(
(key) => GameMapType[key] === mapValue,
);
return html`
<div
@click=${() => this.handleMapSelection(mapValue)}
>
<map-display
.mapKey=${mapKey}
.selected=${!this.useRandomMap &&
this.selectedMap === mapValue}
.translation=${translateText(
`map.${mapKey.toLowerCase()}`,
)}
></map-display>
</div>
`;
})}
</div>
`,
)}
</div>
`,
)}
<div
class="option-card random-map ${
this.useRandomMap ? "selected" : ""
@@ -103,7 +127,9 @@ export class HostLobbyModal extends LitElement {
style="width:100%; aspect-ratio: 4/2; object-fit:cover; border-radius:8px;"
/>
</div>
<div class="option-card-title">${translateText("map.random")}</div>
<div class="option-card-title">
${translateText("map.random")}
</div>
</div>
</div>
</div>
@@ -159,6 +185,33 @@ export class HostLobbyModal extends LitElement {
</div>
</div>
${
this.gameMode === GameMode.FFA
? ""
: html`
<!-- Team Count Selection -->
<div class="options-section">
<div class="option-title">
${translateText("host_modal.team_count")}
</div>
<div class="option-cards">
${[Duos, 2, 3, 4, 5, 6, 7].map(
(o) => html`
<div
class="option-card ${this.teamCount === o
? "selected"
: ""}"
@click=${() => this.handleTeamCountSelection(o)}
>
<div class="option-card-title">${o}</div>
</div>
`,
)}
</div>
</div>
`
}
<!-- Game Options -->
<div class="options-section">
<div class="option-title">
@@ -413,6 +466,11 @@ export class HostLobbyModal extends LitElement {
this.putGameConfig();
}
private async handleTeamCountSelection(value: number | typeof Duos) {
this.teamCount = value === Duos ? Duos : Number(value);
this.putGameConfig();
}
private async putGameConfig() {
const config = await getServerConfigFromClient();
const response = await fetch(
@@ -432,6 +490,7 @@ export class HostLobbyModal extends LitElement {
infiniteTroops: this.infiniteTroops,
instantBuild: this.instantBuild,
gameMode: this.gameMode,
playerTeams: this.teamCount,
} as GameConfig),
},
);
+56 -63
View File
@@ -113,6 +113,17 @@ export class InputHandler {
) {}
initialize() {
const keybinds = {
toggleView: "Space",
centerCamera: "KeyC",
moveUp: "KeyW",
moveDown: "KeyS",
moveLeft: "KeyA",
moveRight: "KeyD",
zoomOut: "KeyQ",
zoomIn: "KeyE",
...JSON.parse(localStorage.getItem("settings.keybinds") ?? "{}"),
};
this.canvas.addEventListener("pointerdown", (e) => this.onPointerDown(e));
window.addEventListener("pointerup", (e) => this.onPointerUp(e));
this.canvas.addEventListener(
@@ -122,59 +133,65 @@ export class InputHandler {
this.onShiftScroll(e);
e.preventDefault();
},
{
passive: false,
},
{ passive: false },
);
window.addEventListener("pointermove", this.onPointerMove.bind(this));
this.canvas.addEventListener("contextmenu", (e: MouseEvent) => {
this.onContextMenu(e);
});
this.canvas.addEventListener("contextmenu", (e) => this.onContextMenu(e));
window.addEventListener("mousemove", (e) => {
if (e.movementX === 0 && e.movementY === 0) {
return;
if (e.movementX || e.movementY) {
this.eventBus.emit(new MouseMoveEvent(e.clientX, e.clientY));
}
this.eventBus.emit(new MouseMoveEvent(e.clientX, e.clientY));
});
this.pointers.clear();
// Initialize the combined movement interval
this.moveInterval = setInterval(() => {
let deltaX = 0;
let deltaY = 0;
// Handle both WASD and arrow keys
if (this.activeKeys.has("KeyW") || this.activeKeys.has("ArrowUp"))
if (
this.activeKeys.has(keybinds.moveUp) ||
this.activeKeys.has("ArrowUp")
)
deltaY += this.PAN_SPEED;
if (this.activeKeys.has("KeyS") || this.activeKeys.has("ArrowDown"))
if (
this.activeKeys.has(keybinds.moveDown) ||
this.activeKeys.has("ArrowDown")
)
deltaY -= this.PAN_SPEED;
if (this.activeKeys.has("KeyA") || this.activeKeys.has("ArrowLeft"))
if (
this.activeKeys.has(keybinds.moveLeft) ||
this.activeKeys.has("ArrowLeft")
)
deltaX += this.PAN_SPEED;
if (this.activeKeys.has("KeyD") || this.activeKeys.has("ArrowRight"))
if (
this.activeKeys.has(keybinds.moveRight) ||
this.activeKeys.has("ArrowRight")
)
deltaX -= this.PAN_SPEED;
if (deltaX !== 0 || deltaY !== 0) {
if (deltaX || deltaY) {
this.eventBus.emit(new DragEvent(deltaX, deltaY));
}
// Handle zooming
const screenCenterX = window.innerWidth / 2;
const screenCenterY = window.innerHeight / 2;
const cx = window.innerWidth / 2;
const cy = window.innerHeight / 2;
if (this.activeKeys.has("Minus") || this.activeKeys.has("KeyQ")) {
this.eventBus.emit(
new ZoomEvent(screenCenterX, screenCenterY, this.ZOOM_SPEED),
);
if (
this.activeKeys.has(keybinds.zoomOut) ||
this.activeKeys.has("Minus")
) {
this.eventBus.emit(new ZoomEvent(cx, cy, this.ZOOM_SPEED));
}
if (this.activeKeys.has("Equal") || this.activeKeys.has("KeyE")) {
this.eventBus.emit(
new ZoomEvent(screenCenterX, screenCenterY, -this.ZOOM_SPEED),
);
if (
this.activeKeys.has(keybinds.zoomIn) ||
this.activeKeys.has("Equal")
) {
this.eventBus.emit(new ZoomEvent(cx, cy, -this.ZOOM_SPEED));
}
}, 1);
window.addEventListener("keydown", (e) => {
if (e.code === "Space") {
if (e.code === keybinds.toggleView) {
e.preventDefault();
if (!this.alternateView) {
this.alternateView = true;
@@ -187,24 +204,23 @@ export class InputHandler {
this.eventBus.emit(new CloseViewEvent());
}
// Add all movement keys to activeKeys
if (
[
"KeyW",
"KeyA",
"KeyS",
"KeyD",
keybinds.moveUp,
keybinds.moveDown,
keybinds.moveLeft,
keybinds.moveRight,
keybinds.zoomOut,
keybinds.zoomIn,
"ArrowUp",
"ArrowLeft",
"ArrowDown",
"ArrowRight",
"Minus",
"Equal",
"KeyE",
"KeyQ",
"Digit1",
"Digit2",
"KeyC",
keybinds.centerCamera,
"ControlLeft",
"ControlRight",
].includes(e.code)
@@ -212,13 +228,13 @@ export class InputHandler {
this.activeKeys.add(e.code);
}
});
window.addEventListener("keyup", (e) => {
if (e.code === "Space") {
if (e.code === keybinds.toggleView) {
e.preventDefault();
this.alternateView = false;
this.eventBus.emit(new AlternateViewEvent(false));
}
if (e.key.toLowerCase() === "r" && e.altKey && !e.ctrlKey) {
e.preventDefault();
this.eventBus.emit(new RefreshGraphicsEvent());
@@ -234,35 +250,12 @@ export class InputHandler {
this.eventBus.emit(new AttackRatioEvent(10));
}
if (e.code === "KeyC") {
if (e.code === keybinds.centerCamera) {
e.preventDefault();
this.eventBus.emit(new CenterCameraEvent());
}
// Remove all movement keys from activeKeys
if (
[
"KeyW",
"KeyA",
"KeyS",
"KeyD",
"ArrowUp",
"ArrowLeft",
"ArrowDown",
"ArrowRight",
"Minus",
"Equal",
"KeyE",
"KeyQ",
"Digit1",
"Digit2",
"KeyC",
"ControlLeft",
"ControlRight",
].includes(e.code)
) {
this.activeKeys.delete(e.code);
}
this.activeKeys.delete(e.code);
});
}
+15
View File
@@ -3,14 +3,21 @@ import { customElement, state } from "lit/decorators.js";
import "./LanguageModal";
import bg from "../../resources/lang/bg.json";
import bn from "../../resources/lang/bn.json";
import de from "../../resources/lang/de.json";
import en from "../../resources/lang/en.json";
import eo from "../../resources/lang/eo.json";
import es from "../../resources/lang/es.json";
import fr from "../../resources/lang/fr.json";
import hi from "../../resources/lang/hi.json";
import it from "../../resources/lang/it.json";
import ja from "../../resources/lang/ja.json";
import nl from "../../resources/lang/nl.json";
import pl from "../../resources/lang/pl.json";
import pt_br from "../../resources/lang/pt_br.json";
import ru from "../../resources/lang/ru.json";
import sh from "../../resources/lang/sh.json";
import tr from "../../resources/lang/tr.json";
import uk from "../../resources/lang/uk.json";
@customElement("lang-selector")
@@ -26,14 +33,21 @@ export class LangSelector extends LitElement {
private languageMap: Record<string, any> = {
bg,
bn,
de,
en,
es,
eo,
fr,
it,
hi,
ja,
nl,
pl,
pt_br,
ru,
sh,
tr,
uk,
};
@@ -159,6 +173,7 @@ export class LangSelector extends LitElement {
"help-modal",
"username-input",
"public-lobby",
"user-setting",
"o-modal",
"o-button",
];
+95
View File
@@ -21,12 +21,17 @@ import { LangSelector } from "./LangSelector";
import { LanguageModal } from "./LanguageModal";
import "./PublicLobby";
import { PublicLobby } from "./PublicLobby";
import "./RandomNameButton";
import { RandomNameButton } from "./RandomNameButton";
import { SinglePlayerModal } from "./SinglePlayerModal";
import { UserSettingModal } from "./UserSettingModal";
import "./UsernameInput";
import { UsernameInput } from "./UsernameInput";
import { generateCryptoRandomUUID } from "./Utils";
import "./components/baseComponents/Button";
import { OButton } from "./components/baseComponents/Button";
import "./components/baseComponents/Modal";
import { discordLogin, getUserMe, isLoggedIn, logOut } from "./jwt";
import "./styles.css";
export interface JoinLobbyEvent {
@@ -45,6 +50,7 @@ class Client {
private usernameInput: UsernameInput | null = null;
private flagInput: FlagInput | null = null;
private darkModeButton: DarkModeButton | null = null;
private randomNameButton: RandomNameButton | null = null;
private joinModal: JoinPrivateLobbyModal;
private publicLobby: PublicLobby;
@@ -79,6 +85,20 @@ class Client {
consolex.warn("Dark mode button element not found");
}
this.randomNameButton = document.querySelector(
"random-name-button",
) as RandomNameButton;
if (!this.randomNameButton) {
consolex.warn("Random name button element not found");
}
const loginDiscordButton = document.getElementById(
"login-discord",
) as OButton;
const logoutDiscordButton = document.getElementById(
"logout-discord",
) as OButton;
this.usernameInput = document.querySelector(
"username-input",
) as UsernameInput;
@@ -122,6 +142,49 @@ class Client {
hlpModal.open();
});
const claims = isLoggedIn();
if (claims === false) {
// Not logged in
loginDiscordButton.disable = false;
loginDiscordButton.translationKey = "main.login_discord";
loginDiscordButton.addEventListener("click", discordLogin);
logoutDiscordButton.hidden = true;
} else {
// JWT appears to be valid, assume we are logged in
loginDiscordButton.disable = true;
loginDiscordButton.translationKey = "main.logged_in";
logoutDiscordButton.hidden = false;
logoutDiscordButton.addEventListener("click", () => {
// Log out
logOut();
loginDiscordButton.disable = false;
loginDiscordButton.translationKey = "main.login_discord";
loginDiscordButton.addEventListener("click", discordLogin);
logoutDiscordButton.hidden = true;
});
// Look up the discord user object.
// TODO: Add caching
getUserMe().then((userMeResponse) => {
if (userMeResponse === false) {
// Not logged in
loginDiscordButton.disable = false;
loginDiscordButton.translationKey = "main.login_discord";
loginDiscordButton.addEventListener("click", discordLogin);
logoutDiscordButton.hidden = true;
return;
}
// TODO: Update the page for logged in user
});
}
const settingsModal = document.querySelector(
"user-setting",
) as UserSettingModal;
settingsModal instanceof UserSettingModal;
document.getElementById("settings-button").addEventListener("click", () => {
settingsModal.open();
});
const hostModal = document.querySelector(
"host-lobby-modal",
) as HostPrivateLobbyModal;
@@ -207,6 +270,33 @@ class Client {
gameRecord: lobby.gameRecord,
},
() => {
console.log("Closing modals");
document.getElementById("settings-button").classList.add("hidden");
[
"single-player-modal",
"host-lobby-modal",
"join-private-lobby-modal",
"game-starting-modal",
"top-bar",
"help-modal",
"user-setting",
].forEach((tag) => {
const modal = document.querySelector(tag) as HTMLElement & {
close?: () => void;
isModalOpen?: boolean;
};
if (modal?.close) {
modal.close();
} else if ("isModalOpen" in modal) {
modal.isModalOpen = false;
}
});
this.publicLobby.stop();
document.querySelectorAll(".ad").forEach((ad) => {
(ad as HTMLElement).style.display = "none";
});
// show when the game loads
const startingModal = document.querySelector(
"game-starting-modal",
) as GameStartingModal;
@@ -254,6 +344,11 @@ function setFavicon(): void {
// WARNING: DO NOT EXPOSE THIS ID
export function getPersistentIDFromCookie(): string {
const claims = isLoggedIn();
if (claims !== false && claims.sub) {
return claims.sub;
}
const COOKIE_NAME = "player_persistent_id";
// Try to get existing cookie
+108
View File
@@ -0,0 +1,108 @@
export class MultiTabDetector {
private readonly tabId = `${Date.now()}-${Math.random()}`;
private readonly lockKey = "multi-tab-lock";
private readonly heartbeatIntervalMs = 1_000;
private readonly staleThresholdMs = 3_000;
private heartbeatTimer: number | null = null;
private isPunished = false;
private punishmentCount = 0;
private startPenaltyCallback: (duration: number) => void = () => {};
constructor() {
window.addEventListener("storage", this.onStorageEvent.bind(this));
window.addEventListener("beforeunload", this.onBeforeUnload.bind(this));
}
public startMonitoring(startPenalty: (duration: number) => void): void {
this.startPenaltyCallback = startPenalty;
this.writeLock();
this.heartbeatTimer = window.setInterval(
() => this.heartbeat(),
this.heartbeatIntervalMs,
);
}
public stopMonitoring(): void {
if (this.heartbeatTimer !== null) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
const lock = this.readLock();
if (lock?.owner === this.tabId) {
localStorage.removeItem(this.lockKey);
}
window.removeEventListener("storage", this.onStorageEvent.bind(this));
window.removeEventListener("beforeunload", this.onBeforeUnload.bind(this));
}
private heartbeat(): void {
const now = Date.now();
const lock = this.readLock();
if (
!lock ||
lock.owner === this.tabId ||
now - lock.timestamp > this.staleThresholdMs
) {
this.writeLock();
this.isPunished = false;
return;
}
if (!this.isPunished) {
this.applyPunishment();
}
}
private onStorageEvent(e: StorageEvent): void {
if (e.key === this.lockKey && e.newValue) {
let other: { owner: string; timestamp: number };
try {
other = JSON.parse(e.newValue);
} catch (e) {
console.error("Failed to parse lock", e);
return;
}
if (other.owner !== this.tabId && !this.isPunished) {
this.applyPunishment();
}
}
}
private onBeforeUnload(): void {
const lock = this.readLock();
if (lock?.owner === this.tabId) {
localStorage.removeItem(this.lockKey);
}
}
private applyPunishment(): void {
this.isPunished = true;
this.punishmentCount++;
const delay = 10_000;
this.startPenaltyCallback(delay);
setTimeout(() => {
this.isPunished = false;
}, delay);
}
private writeLock(): void {
localStorage.setItem(
this.lockKey,
JSON.stringify({ owner: this.tabId, timestamp: Date.now() }),
);
}
private readLock(): { owner: string; timestamp: number } | null {
const raw = localStorage.getItem(this.lockKey);
if (!raw) return null;
try {
return JSON.parse(raw);
} catch (e) {
console.error("Failed to parse lock", raw, e);
return null;
}
}
}
+7 -2
View File
@@ -91,6 +91,11 @@ export class PublicLobby extends LitElement {
const seconds = timeRemaining % 60;
const timeDisplay = minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s`;
const teamCount =
lobby.gameConfig.gameMode === GameMode.Team
? lobby.gameConfig.playerTeams || 0
: null;
return html`
<button
@click=${() => this.lobbyClicked(lobby)}
@@ -123,8 +128,8 @@ export class PublicLobby extends LitElement {
)}
</div>
<div class="text-md font-medium text-blue-100">
${lobby.gameConfig.gameMode === GameMode.Team
? translateText("game_mode.teams")
${lobby.gameConfig.gameMode == GameMode.Team
? translateText("public_lobby.teams", { num: teamCount })
: translateText("game_mode.ffa")}
</div>
</div>
+30
View File
@@ -0,0 +1,30 @@
import { LitElement, html } from "lit";
import { customElement, state } from "lit/decorators.js";
import { UserSettings } from "../core/game/UserSettings";
@customElement("random-name-button")
export class RandomNameButton extends LitElement {
private userSettings: UserSettings = new UserSettings();
@state() private randomName: boolean = this.userSettings.anonymousNames();
createRenderRoot() {
return this;
}
toggleRandomName() {
this.userSettings.toggleRandomName();
this.randomName = this.userSettings.anonymousNames();
}
render() {
return html`
<button
title="Random Name"
class="absolute top-0 left-0 md:top-[10px] md:left-[10px] border-none bg-none cursor-pointer text-2xl"
@click=${() => this.toggleRandomName()}
>
${this.randomName ? "🥷" : "🕵️"}
</button>
`;
}
}
+71 -20
View File
@@ -3,7 +3,14 @@ import { customElement, query, state } from "lit/decorators.js";
import randomMap from "../../resources/images/RandomMap.webp";
import { translateText } from "../client/Utils";
import { consolex } from "../core/Consolex";
import { Difficulty, GameMapType, GameMode, GameType } from "../core/game/Game";
import {
Difficulty,
Duos,
GameMapType,
GameMode,
GameType,
mapCategories,
} from "../core/game/Game";
import { generateID } from "../core/Util";
import "./components/baseComponents/Button";
import "./components/baseComponents/Modal";
@@ -30,6 +37,7 @@ export class SinglePlayerModal extends LitElement {
@state() private instantBuild: boolean = false;
@state() private useRandomMap: boolean = false;
@state() private gameMode: GameMode = GameMode.FFA;
@state() private teamCount: number | typeof Duos = 2;
render() {
return html`
@@ -38,27 +46,40 @@ export class SinglePlayerModal extends LitElement {
<!-- Map Selection -->
<div class="options-section">
<div class="option-title">${translateText("map.map")}</div>
<div class="option-cards">
${Object.entries(GameMapType)
.filter(([key]) => isNaN(Number(key)))
.map(
([key, value]) => html`
<div
@click=${function () {
this.handleMapSelection(value);
}}
<div class="option-cards flex-col">
<!-- Use the imported mapCategories -->
${Object.entries(mapCategories).map(
([categoryKey, maps]) => html`
<div class="w-full mb-4">
<h3
class="text-lg font-semibold mb-2 text-center text-gray-300"
>
<map-display
.mapKey=${key}
.selected=${!this.useRandomMap &&
this.selectedMap === value}
.translation=${translateText(
`map.${key.toLowerCase()}`,
)}
></map-display>
${translateText(`map_categories.${categoryKey}`)}
</h3>
<div class="flex flex-row flex-wrap justify-center gap-4">
${maps.map((mapValue) => {
const mapKey = Object.keys(GameMapType).find(
(key) => GameMapType[key] === mapValue,
);
return html`
<div
@click=${() => this.handleMapSelection(mapValue)}
>
<map-display
.mapKey=${mapKey}
.selected=${!this.useRandomMap &&
this.selectedMap === mapValue}
.translation=${translateText(
`map.${mapKey.toLowerCase()}`,
)}
></map-display>
</div>
`;
})}
</div>
`,
)}
</div>
`,
)}
<div
class="option-card random-map ${this.useRandomMap
? "selected"
@@ -136,6 +157,31 @@ export class SinglePlayerModal extends LitElement {
</div>
</div>
${this.gameMode === GameMode.FFA
? ""
: html`
<!-- Team Count Selection -->
<div class="options-section">
<div class="option-title">
${translateText("host_modal.team_count")}
</div>
<div class="option-cards">
${["Duos", 2, 3, 4, 5, 6, 7].map(
(o) => html`
<div
class="option-card ${this.teamCount === o
? "selected"
: ""}"
@click=${() => this.handleTeamCountSelection(o)}
>
<div class="option-card-title">${o}</div>
</div>
`,
)}
</div>
</div>
`}
<!-- Game Options -->
<div class="options-section">
<div class="option-title">
@@ -310,6 +356,10 @@ export class SinglePlayerModal extends LitElement {
this.gameMode = value;
}
private handleTeamCountSelection(value: number | string) {
this.teamCount = value === "Duos" ? Duos : Number(value);
}
private getRandomMap(): GameMapType {
const maps = Object.values(GameMapType);
const randIdx = Math.floor(Math.random() * maps.length);
@@ -361,6 +411,7 @@ export class SinglePlayerModal extends LitElement {
gameMap: this.selectedMap,
gameType: GameType.Singleplayer,
gameMode: this.gameMode,
playerTeams: this.teamCount,
difficulty: this.selectedDifficulty,
disableNPCs: this.disableNPCs,
disableNukes: this.disableNukes,
+8 -5
View File
@@ -67,9 +67,10 @@ export class SendAttackIntentEvent implements GameEvent {
export class SendBoatAttackIntentEvent implements GameEvent {
constructor(
public readonly targetID: PlayerID | null,
public readonly cell: Cell,
public readonly targetID: PlayerID,
public readonly dst: Cell,
public readonly troops: number,
public readonly src: Cell | null = null,
) {}
}
@@ -87,7 +88,7 @@ export class SendTargetPlayerIntentEvent implements GameEvent {
export class SendEmojiIntentEvent implements GameEvent {
constructor(
public readonly recipient: PlayerView | typeof AllPlayers,
public readonly emoji: string,
public readonly emoji: number,
) {}
}
@@ -421,8 +422,10 @@ export class Transport {
clientID: this.lobbyConfig.clientID,
targetID: event.targetID,
troops: event.troops,
x: event.cell.x,
y: event.cell.y,
dstX: event.dst.x,
dstY: event.dst.y,
srcX: event.src?.x,
srcY: event.src?.y,
});
}
+393
View File
@@ -0,0 +1,393 @@
import { LitElement, html } from "lit";
import { customElement, query, state } from "lit/decorators.js";
import { translateText } from "../client/Utils";
import { UserSettings } from "../core/game/UserSettings";
import "./components/baseComponents/setting/SettingKeybind";
import { SettingKeybind } from "./components/baseComponents/setting/SettingKeybind";
import "./components/baseComponents/setting/SettingNumber";
import "./components/baseComponents/setting/SettingSlider";
import "./components/baseComponents/setting/SettingToggle";
@customElement("user-setting")
export class UserSettingModal extends LitElement {
private userSettings: UserSettings = new UserSettings();
@state() private settingsMode: "basic" | "keybinds" = "basic";
@state() private keybinds: Record<string, string> = {};
@state() private keySequence: string[] = [];
@state() private showEasterEggSettings = false;
connectedCallback() {
super.connectedCallback();
window.addEventListener("keydown", this.handleKeyDown);
const savedKeybinds = localStorage.getItem("settings.keybinds");
if (savedKeybinds) {
try {
this.keybinds = JSON.parse(savedKeybinds);
} catch (e) {
console.warn("Invalid keybinds JSON:", e);
}
}
}
@query("o-modal") private modalEl!: HTMLElement & {
open: () => void;
close: () => void;
isModalOpen: boolean;
};
createRenderRoot() {
return this;
}
disconnectedCallback() {
window.removeEventListener("keydown", this.handleKeyDown);
super.disconnectedCallback();
document.body.style.overflow = "auto";
}
private handleKeyDown = (e: KeyboardEvent) => {
if (!this.modalEl?.isModalOpen || this.showEasterEggSettings) return;
const key = e.key.toLowerCase();
const nextSequence = [...this.keySequence, key].slice(-4);
this.keySequence = nextSequence;
if (nextSequence.join("") === "evan") {
this.triggerEasterEgg();
this.keySequence = [];
}
};
private triggerEasterEgg() {
console.log("🪺 Setting~ unlocked by EVAN combo!");
this.showEasterEggSettings = true;
const popup = document.createElement("div");
popup.className = "easter-egg-popup";
popup.textContent = "🎉 You found a secret setting!";
document.body.appendChild(popup);
setTimeout(() => {
popup.remove();
}, 5000);
}
toggleDarkMode(e: CustomEvent<{ checked: boolean }>) {
const enabled = e.detail?.checked;
if (typeof enabled !== "boolean") {
console.warn("Unexpected toggle event payload", e);
return;
}
this.userSettings.set("settings.darkMode", enabled);
if (enabled) {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
console.log("🌙 Dark Mode:", enabled ? "ON" : "OFF");
}
private toggleEmojis(e: CustomEvent<{ checked: boolean }>) {
const enabled = e.detail?.checked;
if (typeof enabled !== "boolean") return;
this.userSettings.set("settings.emojis", enabled);
console.log("🤡 Emojis:", enabled ? "ON" : "OFF");
}
private toggleLeftClickOpensMenu(e: CustomEvent<{ checked: boolean }>) {
const enabled = e.detail?.checked;
if (typeof enabled !== "boolean") return;
this.userSettings.set("settings.leftClickOpensMenu", enabled);
console.log("🖱️ Left Click Opens Menu:", enabled ? "ON" : "OFF");
this.requestUpdate();
}
private sliderAttackRatio(e: CustomEvent<{ value: number }>) {
const value = e.detail?.value;
if (typeof value === "number") {
const ratio = value / 100;
localStorage.setItem("settings.attackRatio", ratio.toString());
} else {
console.warn("Slider event missing detail.value", e);
}
}
private sliderTroopRatio(e: CustomEvent<{ value: number }>) {
const value = e.detail?.value;
if (typeof value === "number") {
const ratio = value / 100;
localStorage.setItem("settings.troopRatio", ratio.toString());
} else {
console.warn("Slider event missing detail.value", e);
}
}
private handleKeybindChange(
e: CustomEvent<{ action: string; value: string }>,
) {
const { action, value } = e.detail;
const prevValue = this.keybinds[action] ?? "";
const values = Object.entries(this.keybinds)
.filter(([k]) => k !== action)
.map(([, v]) => v);
if (values.includes(value) && value !== "Null") {
const popup = document.createElement("div");
popup.className = "setting-popup";
popup.textContent = `The key "${value}" is already assigned to another action.`;
document.body.appendChild(popup);
const element = this.renderRoot.querySelector(
`setting-keybind[action="${action}"]`,
) as SettingKeybind;
if (element) {
element.value = prevValue;
element.requestUpdate();
}
return;
}
this.keybinds = { ...this.keybinds, [action]: value };
localStorage.setItem("settings.keybinds", JSON.stringify(this.keybinds));
}
render() {
return html`
<o-modal title="${translateText("user_setting.title")}">
<div class="modal-overlay">
<div class="modal-content user-setting-modal">
<div class="flex mb-4 w-full justify-center">
<button
class="w-1/2 text-center px-3 py-1 rounded-l
${this.settingsMode === "basic"
? "bg-white/10 text-white"
: "bg-transparent text-gray-400"}"
@click=${() => (this.settingsMode = "basic")}
>
${translateText("user_setting.tab_basic")}
</button>
<button
class="w-1/2 text-center px-3 py-1 rounded-r
${this.settingsMode === "keybinds"
? "bg-white/10 text-white"
: "bg-transparent text-gray-400"}"
@click=${() => (this.settingsMode = "keybinds")}
>
${translateText("user_setting.tab_keybinds")}
</button>
</div>
<div class="settings-list">
${this.settingsMode === "basic"
? this.renderBasicSettings()
: this.renderKeybindSettings()}
</div>
</div>
</div>
</o-modal>
`;
}
private renderBasicSettings() {
return html`
<!-- 🌙 Dark Mode -->
<setting-toggle
label="${translateText("user_setting.dark_mode_label")}"
description="${translateText("user_setting.dark_mode_desc")}"
id="dark-mode-toggle"
.checked=${this.userSettings.darkMode()}
@change=${(e: CustomEvent<{ checked: boolean }>) =>
this.toggleDarkMode(e)}
></setting-toggle>
<!-- 😊 Emojis -->
<setting-toggle
label="${translateText("user_setting.emojis_label")}"
description="${translateText("user_setting.emojis_desc")}"
id="emoji-toggle"
.checked=${this.userSettings.emojis()}
@change=${this.toggleEmojis}
></setting-toggle>
<!-- 🖱️ Left Click Menu -->
<setting-toggle
label="${translateText("user_setting.left_click_label")}"
description="${translateText("user_setting.left_click_desc")}"
id="left-click-toggle"
.checked=${this.userSettings.leftClickOpensMenu()}
@change=${this.toggleLeftClickOpensMenu}
></setting-toggle>
<!-- ⚔️ Attack Ratio -->
<setting-slider
label="${translateText("user_setting.attack_ratio_label")}"
description="${translateText("user_setting.attack_ratio_desc")}"
min="1"
max="100"
.value=${Number(localStorage.getItem("settings.attackRatio") ?? "0.2") *
100}
@change=${this.sliderAttackRatio}
></setting-slider>
<!-- 🪖🛠️ Troop Ratio -->
<setting-slider
label="${translateText("user_setting.troop_ratio_label")}"
description="${translateText("user_setting.troop_ratio_desc")}"
min="1"
max="100"
.value=${Number(localStorage.getItem("settings.troopRatio") ?? "0.95") *
100}
@change=${this.sliderTroopRatio}
></setting-slider>
${this.showEasterEggSettings
? html`
<setting-slider
label="${translateText(
"user_setting.easter_writing_speed_label",
)}"
description="${translateText(
"user_setting.easter_writing_speed_desc",
)}"
min="0"
max="100"
value="40"
easter="true"
@change=${(e: CustomEvent) => {
const value = e.detail?.value;
if (typeof value !== "undefined") {
console.log("Changed:", value);
} else {
console.warn("Slider event missing detail.value", e);
}
}}
></setting-slider>
<setting-number
label="${translateText("user_setting.easter_bug_count_label")}"
description="${translateText(
"user_setting.easter_bug_count_desc",
)}"
value="100"
min="0"
max="1000"
easter="true"
@change=${(e: CustomEvent) => {
const value = e.detail?.value;
if (typeof value !== "undefined") {
console.log("Changed:", value);
} else {
console.warn("Slider event missing detail.value", e);
}
}}
></setting-number>
`
: null}
`;
}
private renderKeybindSettings() {
return html`
<div class="text-center text-white text-base font-semibold mt-5 mb-2">
${translateText("user_setting.view_options")}
</div>
<setting-keybind
action="toggleView"
label=${translateText("user_setting.toggle_view")}
description=${translateText("user_setting.toggle_view_desc")}
defaultKey="Space"
.value=${this.keybinds["toggleView"] ?? ""}
@change=${this.handleKeybindChange}
></setting-keybind>
<div class="text-center text-white text-base font-semibold mt-5 mb-2">
${translateText("user_setting.zoom_controls")}
</div>
<setting-keybind
action="zoomOut"
label=${translateText("user_setting.zoom_out")}
description=${translateText("user_setting.zoom_out_desc")}
defaultKey="KeyQ"
.value=${this.keybinds["zoomOut"] ?? ""}
@change=${this.handleKeybindChange}
></setting-keybind>
<setting-keybind
action="zoomIn"
label=${translateText("user_setting.zoom_in")}
description=${translateText("user_setting.zoom_in_desc")}
defaultKey="KeyE"
.value=${this.keybinds["zoomIn"] ?? ""}
@change=${this.handleKeybindChange}
></setting-keybind>
<div class="text-center text-white text-base font-semibold mt-5 mb-2">
${translateText("user_setting.camera_movement")}
</div>
<setting-keybind
action="centerCamera"
label=${translateText("user_setting.center_camera")}
description=${translateText("user_setting.center_camera_desc")}
defaultKey="KeyC"
.value=${this.keybinds["centerCamera"] ?? ""}
@change=${this.handleKeybindChange}
></setting-keybind>
<setting-keybind
action="moveUp"
label=${translateText("user_setting.move_up")}
description=${translateText("user_setting.move_up_desc")}
defaultKey="KeyW"
.value=${this.keybinds["moveUp"] ?? ""}
@change=${this.handleKeybindChange}
></setting-keybind>
<setting-keybind
action="moveLeft"
label=${translateText("user_setting.move_left")}
description=${translateText("user_setting.move_left_desc")}
defaultKey="KeyA"
.value=${this.keybinds["moveLeft"] ?? ""}
@change=${this.handleKeybindChange}
></setting-keybind>
<setting-keybind
action="moveDown"
label=${translateText("user_setting.move_down")}
description=${translateText("user_setting.move_down_desc")}
defaultKey="KeyS"
.value=${this.keybinds["moveDown"] ?? ""}
@change=${this.handleKeybindChange}
></setting-keybind>
<setting-keybind
action="moveRight"
label=${translateText("user_setting.move_right")}
description=${translateText("user_setting.move_right_desc")}
defaultKey="KeyD"
.value=${this.keybinds["moveRight"] ?? ""}
@change=${this.handleKeybindChange}
></setting-keybind>
`;
}
public open() {
this.requestUpdate();
this.modalEl?.open();
}
public close() {
this.modalEl?.close();
}
}
+3
View File
@@ -7,6 +7,7 @@ import { getMapsImage } from "../utilities/Maps";
export const MapDescription: Record<keyof typeof GameMapType, string> = {
World: "World",
Europe: "Europe",
EuropeClassic: "Europe Classic",
Mena: "MENA",
NorthAmerica: "North America",
Oceania: "Oceania",
@@ -23,6 +24,8 @@ export const MapDescription: Record<keyof typeof GameMapType, string> = {
Japan: "Japan",
BetweenTwoSeas: "Between Two Seas",
KnownWorld: "Known World",
FaroeIslands: "Faroe Islands",
DeglaciatedAntarctica: "Deglaciated Antarctica",
};
@customElement("map-display")
@@ -0,0 +1,115 @@
import { LitElement, html } from "lit";
import { customElement, property } from "lit/decorators.js";
import { translateText } from "../../../../client/Utils";
@customElement("setting-keybind")
export class SettingKeybind extends LitElement {
@property() label = "Setting";
@property() description = "";
@property({ type: String, reflect: true }) action = "";
@property({ type: String }) defaultKey = "";
@property({ type: String }) value = "";
@property({ type: Boolean }) easter = false;
createRenderRoot() {
return this;
}
private listening = false;
render() {
return html`
<div class="setting-item column${this.easter ? " easter-egg" : ""}">
<div class="setting-label-group">
<label class="setting-label block mb-1">${this.label}</label>
<div class="setting-keybind-box">
<div class="setting-keybind-description">${this.description}</div>
<div class="flex items-center gap-2">
<span
class="setting-key"
tabindex="0"
@keydown=${this.handleKeydown}
@click=${this.startListening}
>
${this.displayKey(this.value || this.defaultKey)}
</span>
<button
class="text-xs text-gray-400 hover:text-white border border-gray-500 px-2 py-0.5 rounded transition"
@click=${this.resetToDefault}
>
${translateText("user_setting.reset")}
</button>
<button
class="text-xs text-gray-400 hover:text-white border border-gray-500 px-2 py-0.5 rounded transition"
@click=${this.unbindKey}
>
${translateText("user_setting.unbind")}
</button>
</div>
</div>
</div>
</div>
`;
}
private displayKey(key: string): string {
if (key === " ") return "Space";
if (key.startsWith("Key") && key.length === 4) {
return key.slice(3);
}
return key.length
? key.charAt(0).toUpperCase() + key.slice(1)
: "Press a key";
}
private startListening() {
this.listening = true;
this.requestUpdate();
}
private handleKeydown(e: KeyboardEvent) {
if (!this.listening) return;
e.preventDefault();
const code = e.code;
this.value = code;
this.dispatchEvent(
new CustomEvent("change", {
detail: { action: this.action, value: code },
bubbles: true,
composed: true,
}),
);
this.listening = false;
this.requestUpdate();
}
private resetToDefault() {
this.value = this.defaultKey;
this.dispatchEvent(
new CustomEvent("change", {
detail: { action: this.action, value: this.defaultKey },
bubbles: true,
composed: true,
}),
);
}
private unbindKey() {
this.value = "";
this.dispatchEvent(
new CustomEvent("change", {
detail: { action: this.action, value: "Null" },
bubbles: true,
composed: true,
}),
);
this.requestUpdate();
}
}
@@ -0,0 +1,52 @@
import { LitElement, html } from "lit";
import { customElement, property } from "lit/decorators.js";
@customElement("setting-number")
export class SettingNumber extends LitElement {
@property() label = "Setting";
@property() description = "";
@property({ type: Number }) value = 0;
@property({ type: Number }) min = 0;
@property({ type: Number }) max = 100;
@property({ type: Boolean }) easter = false;
createRenderRoot() {
return this;
}
private handleInput(e: Event) {
const input = e.target as HTMLInputElement;
const newValue = Number(input.value);
this.value = newValue;
this.dispatchEvent(
new CustomEvent("change", {
detail: { value: newValue },
bubbles: true,
composed: true,
}),
);
}
render() {
return html`
<div class="setting-item${this.easter ? " easter-egg" : ""}">
<div class="setting-label-group">
<label class="setting-label" for="setting-number-input"
>${this.label}</label
>
<div class="setting-description">${this.description}</div>
</div>
<input
type="number"
id="setting-number-input"
class="setting-input number"
.value=${String(this.value ?? 0)}
min=${this.min}
max=${this.max}
@input=${this.handleInput}
/>
</div>
`;
}
}
@@ -0,0 +1,76 @@
import { LitElement, html } from "lit";
import { customElement, property } from "lit/decorators.js";
@customElement("setting-slider")
export class SettingSlider extends LitElement {
@property() label = "Setting";
@property() description = "";
@property({ type: Number }) value = 0;
@property({ type: Number }) min = 0;
@property({ type: Number }) max = 100;
@property({ type: Boolean }) easter = false;
createRenderRoot() {
return this;
}
private handleInput(e: Event) {
const input = e.target as HTMLInputElement;
this.value = Number(input.value);
this.updateSliderStyle(input);
this.dispatchEvent(
new CustomEvent("change", {
detail: { value: this.value },
bubbles: true,
composed: true,
}),
);
}
private handleSliderChange(e: Event) {
const detail = (e as CustomEvent)?.detail;
if (!detail || typeof detail.value === "undefined") {
console.warn("Invalid slider change event", e);
return;
}
const value = detail.value;
console.log("Slider changed to", value);
}
private updateSliderStyle(slider: HTMLInputElement) {
const percent = ((this.value - this.min) / (this.max - this.min)) * 100;
slider.style.background = `linear-gradient(to right, #2196f3 ${percent}%, #444 ${percent}%)`;
}
firstUpdated() {
const slider = this.renderRoot.querySelector(
"input[type=range]",
) as HTMLInputElement;
if (slider) this.updateSliderStyle(slider);
}
render() {
return html`
<div class="setting-item vertical${this.easter ? " easter-egg" : ""}">
<div class="setting-label-group">
<label class="setting-label" for="setting-slider-input"
>${this.label}</label
>
<div class="setting-description">${this.description}</div>
</div>
<input
type="range"
id="setting-slider-input"
class="setting-input slider full-width"
min=${this.min}
max=${this.max}
.value=${String(this.value)}
@input=${this.handleInput}
/>
<div class="slider-value">${this.value}%</div>
</div>
`;
}
}
@@ -0,0 +1,47 @@
import { LitElement, html } from "lit";
import { customElement, property } from "lit/decorators.js";
@customElement("setting-toggle")
export class SettingToggle extends LitElement {
@property() label = "Setting";
@property() description = "";
@property() id = "";
@property({ type: Boolean, reflect: true }) checked = false;
@property({ type: Boolean }) easter = false;
createRenderRoot() {
return this;
}
private handleChange(e: Event) {
const input = e.target as HTMLInputElement;
this.checked = input.checked;
this.dispatchEvent(
new CustomEvent("change", {
detail: { checked: this.checked },
bubbles: true,
composed: true,
}),
);
}
render() {
return html`
<div class="setting-item vertical${this.easter ? " easter-egg" : ""}">
<div class="toggle-row">
<label class="setting-label" for=${this.id}>${this.label}</label>
<label class="switch">
<input
type="checkbox"
id=${this.id}
?checked=${this.checked}
@change=${this.handleChange}
/>
<span class="slider-round"></span>
</label>
</div>
<div class="setting-description">${this.description}</div>
</div>
`;
}
}
File diff suppressed because it is too large Load Diff
+10
View File
@@ -12,6 +12,7 @@ import { EmojiTable } from "./layers/EmojiTable";
import { EventsDisplay } from "./layers/EventsDisplay";
import { Layer } from "./layers/Layer";
import { Leaderboard } from "./layers/Leaderboard";
import { MultiTabModal } from "./layers/MultiTabModal";
import { NameLayer } from "./layers/NameLayer";
import { OptionsMenu } from "./layers/OptionsMenu";
import { PlayerInfoOverlay } from "./layers/PlayerInfoOverlay";
@@ -125,6 +126,14 @@ export function createRenderer(
playerPanel.eventBus = eventBus;
playerPanel.emojiTable = emojiTable;
const multiTabModal = document.querySelector(
"multi-tab-modal",
) as MultiTabModal;
if (!(multiTabModal instanceof MultiTabModal)) {
console.error("multi-tab modal not found");
}
multiTabModal.game = game;
const layers: Layer[] = [
new TerrainLayer(game, transformHandler),
new TerritoryLayer(game, eventBus),
@@ -153,6 +162,7 @@ export function createRenderer(
optionsMenu,
topBar,
playerPanel,
multiTabModal,
];
return new GameRenderer(
+135
View File
@@ -0,0 +1,135 @@
import { Colord } from "colord";
import atomBombSprite from "../../../resources/sprites/atombomb.png";
import hydrogenBombSprite from "../../../resources/sprites/hydrogenbomb.png";
import mirvSprite from "../../../resources/sprites/mirv2.png";
import samMissileSprite from "../../../resources/sprites/samMissile.png";
import tradeShipSprite from "../../../resources/sprites/tradeship.png";
import transportShipSprite from "../../../resources/sprites/transportship.png";
import warshipSprite from "../../../resources/sprites/warship.png";
import { Theme } from "../../core/configuration/Config";
import { UnitType } from "../../core/game/Game";
import { UnitView } from "../../core/game/GameView";
const SPRITE_CONFIG: Partial<Record<UnitType, string>> = {
[UnitType.TransportShip]: transportShipSprite,
[UnitType.Warship]: warshipSprite,
[UnitType.SAMMissile]: samMissileSprite,
[UnitType.AtomBomb]: atomBombSprite,
[UnitType.HydrogenBomb]: hydrogenBombSprite,
[UnitType.TradeShip]: tradeShipSprite,
[UnitType.MIRV]: mirvSprite,
};
const spriteMap: Map<UnitType, ImageBitmap> = new Map();
// preload all images
export const loadAllSprites = async (): Promise<void> => {
const entries = Object.entries(SPRITE_CONFIG);
const totalSprites = entries.length;
let loadedCount = 0;
await Promise.all(
entries.map(async ([unitType, url]) => {
const typedUnitType = unitType as UnitType;
if (!url || url === "") {
console.warn(`No sprite URL for ${typedUnitType}, skipping...`);
return;
}
try {
const img = new Image();
img.crossOrigin = "anonymous";
img.src = url;
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve();
img.onerror = (err) => reject(err);
});
const bitmap = await createImageBitmap(img);
spriteMap.set(typedUnitType, bitmap);
loadedCount++;
if (loadedCount === totalSprites) {
console.log("All sprites loaded.");
}
} catch (err) {
console.error(`Failed to load sprite for ${typedUnitType}:`, err);
}
}),
);
};
const getSpriteForUnit = (unitType: UnitType): ImageBitmap | null => {
return spriteMap.get(unitType) ?? null;
};
export const isSpriteReady = (unitType: UnitType): boolean => {
return spriteMap.has(unitType);
};
const coloredSpriteCache: Map<string, HTMLCanvasElement> = new Map();
// puts the sprite in an canvas colors it and caches the colored canvas
export const getColoredSprite = (
unit: UnitView,
theme: Theme,
customTerritoryColor?: Colord,
customBorderColor?: Colord,
): HTMLCanvasElement => {
const owner = unit.owner();
const territoryColor = customTerritoryColor ?? theme.territoryColor(owner);
const borderColor = customBorderColor ?? theme.borderColor(owner);
const spawnHighlightColor = theme.spawnHighlightColor();
const colorKey = territoryColor.toRgbString() + borderColor.toRgbString();
const key = unit.type() + colorKey;
if (coloredSpriteCache.has(key)) {
return coloredSpriteCache.get(key)!;
}
const sprite = getSpriteForUnit(unit.type());
const territoryRgb = territoryColor.toRgb();
const borderRgb = borderColor.toRgb();
const spawnHighlightRgb = spawnHighlightColor.toRgb();
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d")!;
canvas.width = sprite.width;
canvas.height = sprite.height;
ctx.drawImage(sprite, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
if (r === 180 && g === 180 && b === 180) {
data[i] = territoryRgb.r;
data[i + 1] = territoryRgb.g;
data[i + 2] = territoryRgb.b;
}
if (r === 70 && g === 70 && b === 70) {
data[i] = borderRgb.r;
data[i + 1] = borderRgb.g;
data[i + 2] = borderRgb.b;
}
if (r === 130 && g === 130 && b === 130) {
data[i] = spawnHighlightRgb.r;
data[i + 1] = spawnHighlightRgb.g;
data[i + 2] = spawnHighlightRgb.b;
}
}
ctx.putImageData(imageData, 0.5, 0.5);
coloredSpriteCache.set(key, canvas);
return canvas;
};
+8 -4
View File
@@ -97,6 +97,10 @@ export class TransformHandler {
}
screenBoundingRect(): [Cell, Cell] {
const canvasRect = this.boundingRect();
const canvasWidth = canvasRect.width;
const canvasHeight = canvasRect.height;
const LeftX = -this.game.width() / 2 / this.scale + this.offsetX;
const TopY = -this.game.height() / 2 / this.scale + this.offsetY;
@@ -104,12 +108,12 @@ export class TransformHandler {
const gameTopY = TopY + this.game.height() / 2;
const rightX =
(screen.width - this.game.width() / 2) / this.scale + this.offsetX;
const rightY =
(screen.height - this.game.height() / 2) / this.scale + this.offsetY;
(canvasWidth - this.game.width() / 2) / this.scale + this.offsetX;
const bottomY =
(canvasHeight - this.game.height() / 2) / this.scale + this.offsetY;
const gameRightX = rightX + this.game.width() / 2;
const gameBottomY = rightY + this.game.height() / 2;
const gameBottomY = bottomY + this.game.height() / 2;
return [
new Cell(Math.floor(gameLeftX), Math.floor(gameTopY)),
+1 -1
View File
@@ -300,7 +300,7 @@ export class BuildMenu extends LitElement implements Layer {
if (unit.length === 0) {
return false;
}
return unit[0].canBuild;
return unit[0].canBuild !== false;
}
private cost(item: BuildItemDisplay): number {
+16 -1
View File
@@ -56,8 +56,16 @@ export class ControlPanel extends LitElement implements Layer {
private _popRateIsIncreasing: boolean = true;
private init_: boolean = false;
init() {
this.attackRatio = 0.2;
this.attackRatio = Number(
localStorage.getItem("settings.attackRatio") ?? "0.2",
);
this.targetTroopRatio = Number(
localStorage.getItem("settings.troopRatio") ?? "0.95",
);
this.init_ = true;
this.uiState.attackRatio = this.attackRatio;
this.currentTroopRatio = this.targetTroopRatio;
this.eventBus.on(AttackRatioEvent, (event) => {
@@ -87,6 +95,13 @@ export class ControlPanel extends LitElement implements Layer {
}
tick() {
if (this.init_) {
this.eventBus.emit(
new SendSetTargetTroopRatioEvent(this.targetTroopRatio),
);
this.init_ = false;
}
if (!this._isVisible && !this.game.inSpawnPhase()) {
this.setVisibile(true);
}
+7 -15
View File
@@ -4,24 +4,11 @@ import { EventBus } from "../../../core/EventBus";
import { AllPlayers } from "../../../core/game/Game";
import { GameView, PlayerView } from "../../../core/game/GameView";
import { TerraNulliusImpl } from "../../../core/game/TerraNulliusImpl";
import { emojiTable, flattenedEmojiTable } from "../../../core/Util";
import { ShowEmojiMenuEvent } from "../../InputHandler";
import { SendEmojiIntentEvent } from "../../Transport";
import { TransformHandler } from "../TransformHandler";
const emojiTable: string[][] = [
["😀", "😊", "🥰", "😇", "😎"],
["😞", "🥺", "😭", "😱", "😡"],
["😈", "🤡", "🖕", "🥱", "🤦‍♂️"],
["👋", "👏", "🤌", "💪", "🫡"],
["👍", "👎", "❓", "🐔", "🐀"],
["🤝", "🆘", "🕊️", "🏳️", "⏳"],
["🔥", "💥", "💀", "☢️", "⚠️"],
["↖️", "⬆️", "↗️", "👑", "🥇"],
["⬅️", "🎯", "➡️", "🥈", "🥉"],
["↙️", "⬇️", "↘️", "❤️", "💔"],
["💰", "⚓", "⛵", "🏡", "🛡️"],
];
@customElement("emoji-table")
export class EmojiTable extends LitElement {
public eventBus: EventBus;
@@ -130,7 +117,12 @@ export class EmojiTable extends LitElement {
targetPlayer === this.game.myPlayer()
? AllPlayers
: (targetPlayer as PlayerView);
this.eventBus.emit(new SendEmojiIntentEvent(recipient, emoji));
this.eventBus.emit(
new SendEmojiIntentEvent(
recipient,
flattenedEmojiTable.indexOf(emoji),
),
);
this.hideTable();
});
});
+11 -2
View File
@@ -273,10 +273,19 @@ export class EventsDisplay extends LitElement implements Layer {
const malusPercent = Math.round(
(1 - this.game.config().traitorDefenseDebuff()) * 100,
);
const traitorDurationRaw =
Number(this.game.config().traitorDuration) / 10;
const traitorDurationSeconds = Math.floor(traitorDurationRaw);
const durationText =
traitorDurationSeconds === 1
? "1 second"
: `${traitorDurationSeconds} seconds`;
this.addEvent({
description:
`You broke your alliance with ${betrayed.name()}, making you a TRAITOR ` +
`(${malusPercent}% defense debuff)`,
`(${malusPercent}% defense debuff for ${durationText})`,
type: MessageType.ERROR,
highlight: true,
createdAt: this.game.ticks(),
@@ -284,7 +293,7 @@ export class EventsDisplay extends LitElement implements Layer {
});
} else if (betrayed === myPlayer) {
this.addEvent({
description: `${traitor.name()}, broke their alliance with you`,
description: `${traitor.name()} broke their alliance with you`,
type: MessageType.ERROR,
highlight: true,
createdAt: this.game.ticks(),
+190
View File
@@ -0,0 +1,190 @@
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
import { GameEnv } from "../../../core/configuration/Config";
import { GameType } from "../../../core/game/Game";
import { GameView } from "../../../core/game/GameView";
import { MultiTabDetector } from "../../MultiTabDetector";
import { translateText } from "../../Utils";
import { Layer } from "./Layer";
@customElement("multi-tab-modal")
export class MultiTabModal extends LitElement implements Layer {
public game: GameView;
private detector: MultiTabDetector;
@property({ type: Number }) duration: number = 5000;
@state() private countdown: number = 5;
@state() private isVisible: boolean = false;
@state() private fakeIp: string = "";
@state() private deviceFingerprint: string = "";
@state() private reported: boolean = true;
private intervalId?: number;
// Disable shadow DOM to allow Tailwind classes to work
createRenderRoot() {
return this;
}
tick() {
if (
this.game.inSpawnPhase() ||
this.game.config().gameConfig().gameType == GameType.Singleplayer ||
this.game.config().serverConfig().env() == GameEnv.Dev
) {
return;
}
if (!this.detector) {
this.detector = new MultiTabDetector();
this.detector.startMonitoring((duration: number) => {
this.show(duration);
});
}
}
init() {
this.fakeIp = this.generateFakeIp();
this.deviceFingerprint = this.generateDeviceFingerprint();
this.reported = true;
}
// Generate fake IP in format xxx.xxx.xxx.xxx
private generateFakeIp(): string {
return Array.from({ length: 4 }, () =>
Math.floor(Math.random() * 255),
).join(".");
}
// Generate fake device fingerprint (32 character hex)
private generateDeviceFingerprint(): string {
return Array.from({ length: 32 }, () =>
Math.floor(Math.random() * 16).toString(16),
).join("");
}
// Show the modal with penalty information
public show(duration: number): void {
if (!this.game.myPlayer()?.isAlive()) {
return;
}
this.duration = duration;
this.countdown = Math.ceil(duration / 1000);
this.isVisible = true;
// Start countdown timer
this.intervalId = window.setInterval(() => {
this.countdown--;
if (this.countdown <= 0) {
this.hide();
}
}, 1000);
this.requestUpdate();
}
// Hide the modal
public hide(): void {
this.isVisible = false;
if (this.intervalId) {
window.clearInterval(this.intervalId);
this.intervalId = undefined;
}
// Dispatch event when modal is closed
this.dispatchEvent(
new CustomEvent("penalty-complete", {
bubbles: true,
composed: true,
}),
);
this.requestUpdate();
}
disconnectedCallback() {
super.disconnectedCallback();
if (this.intervalId) {
window.clearInterval(this.intervalId);
}
}
render() {
if (!this.isVisible) {
return html``;
}
return html`
<div
class="fixed inset-0 z-50 overflow-auto bg-red-500/20 flex items-center justify-center"
>
<div
class="relative p-6 bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full m-4 transition-all transform"
>
<div class="flex items-center justify-between mb-4">
<h2 class="text-2xl font-bold text-red-600 dark:text-red-400">
${translateText("multi_tab.warning")}
</h2>
<div
class="px-2 py-1 bg-red-600 text-white text-xs font-bold rounded-full animate-pulse"
>
RECORDING
</div>
</div>
<p class="mb-4 text-gray-800 dark:text-gray-200">
${translateText("multi_tab.detected")}
</p>
<div
class="mb-4 p-3 bg-gray-100 dark:bg-gray-900 rounded-md text-sm font-mono"
>
<div class="flex justify-between mb-1">
<span class="text-gray-500 dark:text-gray-400">IP:</span>
<span class="text-red-600 dark:text-red-400">${this.fakeIp}</span>
</div>
<div class="flex justify-between mb-1">
<span class="text-gray-500 dark:text-gray-400"
>Device Fingerprint:</span
>
<span class="text-red-600 dark:text-red-400"
>${this.deviceFingerprint}</span
>
</div>
<div class="flex justify-between">
<span class="text-gray-500 dark:text-gray-400">Reported:</span>
<span class="text-red-600 dark:text-red-400"
>${this.reported ? "TRUE" : "FALSE"}</span
>
</div>
</div>
<p class="mb-4 text-gray-800 dark:text-gray-200">
${translateText("multi_tab.please_wait")}
<span class="font-bold text-xl">${this.countdown}</span>
${translateText("multi_tab.seconds")}
</p>
<div
class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2.5 mb-4"
>
<div
class="bg-red-600 dark:bg-red-500 h-2.5 rounded-full transition-all duration-1000 ease-linear"
style="width: ${(this.countdown / (this.duration / 1000)) * 100}%"
></div>
</div>
<p class="text-sm text-gray-600 dark:text-gray-400">
${translateText("multi_tab.explanation")}
</p>
<p class="mt-3 text-xs text-red-500 font-semibold">
Repeated violations may result in permanent account suspension.
</p>
</div>
</div>
`;
}
}
+44
View File
@@ -4,6 +4,7 @@ import crownIcon from "../../../../resources/images/CrownIcon.svg";
import embargoIcon from "../../../../resources/images/EmbargoIcon.svg";
import nukeRedIcon from "../../../../resources/images/NukeIconRed.svg";
import nukeWhiteIcon from "../../../../resources/images/NukeIconWhite.svg";
import shieldIcon from "../../../../resources/images/ShieldIconBlack.svg";
import targetIcon from "../../../../resources/images/TargetIcon.svg";
import traitorIcon from "../../../../resources/images/TraitorIcon.svg";
import { PseudoRandom } from "../../../core/PseudoRandom";
@@ -44,6 +45,7 @@ export class NameLayer implements Layer {
private embargoIconImage: HTMLImageElement;
private nukeWhiteIconImage: HTMLImageElement;
private nukeRedIconImage: HTMLImageElement;
private shieldIconImage: HTMLImageElement;
private container: HTMLDivElement;
private myPlayer: PlayerView | null = null;
private firstPlace: PlayerView | null = null;
@@ -70,6 +72,8 @@ export class NameLayer implements Layer {
this.nukeWhiteIconImage.src = nukeWhiteIcon;
this.nukeRedIconImage = new Image();
this.nukeRedIconImage.src = nukeRedIcon;
this.shieldIconImage = new Image();
this.shieldIconImage.src = shieldIcon;
}
resizeCanvas() {
@@ -195,6 +199,7 @@ export class NameLayer implements Layer {
nameDiv.style.alignItems = "center";
const nameSpan = document.createElement("span");
nameSpan.className = "player-name-span";
nameSpan.innerHTML = player.name();
nameDiv.appendChild(nameSpan);
element.appendChild(nameDiv);
@@ -209,6 +214,21 @@ export class NameLayer implements Layer {
troopsDiv.style.marginTop = "-5%";
element.appendChild(troopsDiv);
// TODO: enable this for new meta.
// const shieldDiv = document.createElement("div");
// shieldDiv.classList.add("player-shield");
// shieldDiv.style.zIndex = "3";
// shieldDiv.style.marginTop = "-5%";
// shieldDiv.style.display = "flex";
// shieldDiv.style.alignItems = "center";
// shieldDiv.style.gap = "0px";
// shieldDiv.innerHTML = `
// <img src="${this.shieldIconImage.src}" style="width: 16px; height: 16px;" />
// <span style="color: black; font-size: 10px; margin-top: -2px;">0</span>
// `;
// element.appendChild(shieldDiv);
// Start off invisible so it doesn't flash at 0,0
element.style.display = "none";
@@ -262,6 +282,10 @@ export class NameLayer implements Layer {
nameDiv.style.fontSize = `${render.fontSize}px`;
nameDiv.style.lineHeight = `${render.fontSize}px`;
nameDiv.style.color = render.fontColor;
const span = nameDiv.querySelector(".player-name-span");
if (span) {
span.innerHTML = render.player.name();
}
if (flagDiv) {
flagDiv.style.height = `${render.fontSize}px`;
}
@@ -269,6 +293,26 @@ export class NameLayer implements Layer {
troopsDiv.style.color = render.fontColor;
troopsDiv.textContent = renderTroops(render.player.troops());
// TODO: enable this for new meta.
// const density = renderNumber(
// render.player.troops() / render.player.numTilesOwned(),
// );
// const shieldDiv = render.element.querySelector(
// ".player-shield",
// ) as HTMLDivElement;
// const shieldImg = shieldDiv.querySelector("img");
// const shieldNumber = shieldDiv.querySelector("span");
// if (shieldImg) {
// shieldImg.style.width = `${render.fontSize * 0.8}px`;
// shieldImg.style.height = `${render.fontSize * 0.8}px`;
// }
// if (shieldNumber) {
// shieldNumber.style.fontSize = `${render.fontSize * 0.6}px`;
// shieldNumber.style.marginTop = `${-render.fontSize * 0.1}px`;
// shieldNumber.textContent = density;
// }
// Handle icons
const iconsDiv = render.element.querySelector(
".player-icons",
+10
View File
@@ -106,6 +106,10 @@ export class OptionsMenu extends LitElement implements Layer {
this.eventBus.emit(new RefreshGraphicsEvent());
}
private onToggleRandomNameModeButtonClick() {
this.userSettings.toggleRandomName();
}
private onToggleFocusLockedButtonClick() {
this.userSettings.toggleFocusLocked();
this.requestUpdate();
@@ -197,6 +201,12 @@ export class OptionsMenu extends LitElement implements Layer {
title: "Dark Mode",
children: "🌙: " + (this.userSettings.darkMode() ? "On" : "Off"),
})}
${button({
onClick: this.onToggleRandomNameModeButtonClick,
title: "Random name mode",
children:
"🥷: " + (this.userSettings.anonymousNames() ? "On" : "Off"),
})}
${button({
onClick: this.onToggleLeftClickOpensMenu,
title: "Left click",
@@ -207,6 +207,9 @@ export class PlayerInfoOverlay extends LitElement implements Layer {
: ""}
${player.name()}
</div>
${player.team() != null
? html`<div class="text-sm opacity-80">Team: ${player.team()}</div>`
: ""}
<div class="text-sm opacity-80">Type: ${playerType}</div>
${player.troops() >= 1
? html`<div class="text-sm opacity-80" translate="no">
+22 -6
View File
@@ -15,6 +15,7 @@ import {
} from "../../../core/game/Game";
import { TileRef } from "../../../core/game/GameMap";
import { GameView, PlayerView } from "../../../core/game/GameView";
import { flattenedEmojiTable } from "../../../core/Util";
import { MouseUpEvent } from "../../InputHandler";
import {
SendAllianceRequestIntentEvent,
@@ -121,10 +122,17 @@ export class PlayerPanel extends LitElement implements Layer {
private handleEmojiClick(e: Event, myPlayer: PlayerView, other: PlayerView) {
e.stopPropagation();
this.emojiTable.showTable((emoji: string) => {
if (myPlayer === other) {
this.eventBus.emit(new SendEmojiIntentEvent(AllPlayers, emoji));
if (myPlayer == other) {
this.eventBus.emit(
new SendEmojiIntentEvent(
AllPlayers,
flattenedEmojiTable.indexOf(emoji),
),
);
} else {
this.eventBus.emit(new SendEmojiIntentEvent(other, emoji));
this.eventBus.emit(
new SendEmojiIntentEvent(other, flattenedEmojiTable.indexOf(emoji)),
);
}
this.emojiTable.hideTable();
this.hide();
@@ -145,8 +153,14 @@ export class PlayerPanel extends LitElement implements Layer {
this.eventBus.on(MouseUpEvent, (e: MouseEvent) => this.hide());
}
tick() {
this.requestUpdate();
async tick() {
if (this.isVisible && this.tile) {
const myPlayer = this.g.myPlayer();
if (myPlayer !== null && myPlayer.isAlive()) {
this.actions = await myPlayer.actions(this.tile);
this.requestUpdate();
}
}
}
getTotalNukesSent(otherId: PlayerID): number {
@@ -180,7 +194,9 @@ export class PlayerPanel extends LitElement implements Layer {
if (this.tile === null) return;
let other = this.g.owner(this.tile);
if (!other.isPlayer()) {
throw new Error("Tile is not owned by a player");
this.hide();
console.warn("Tile is not owned by a player");
return;
}
other = other as PlayerView;
+67 -26
View File
@@ -8,7 +8,12 @@ import swordIcon from "../../../../resources/images/SwordIconWhite.svg";
import traitorIcon from "../../../../resources/images/TraitorIconWhite.svg";
import { consolex } from "../../../core/Consolex";
import { EventBus } from "../../../core/EventBus";
import { Cell, PlayerActions } from "../../../core/game/Game";
import {
Cell,
PlayerActions,
TerraNullius,
UnitType,
} from "../../../core/game/Game";
import { TileRef } from "../../../core/game/GameMap";
import { GameView, PlayerView } from "../../../core/game/GameView";
import { ClientID } from "../../../core/Schemas";
@@ -44,6 +49,7 @@ export class RadialMenu implements Layer {
private clickedCell: Cell | null = null;
private lastClosed: number = 0;
private originalTileOwner: PlayerView | TerraNullius;
private menuElement: d3.Selection<HTMLDivElement, unknown, null, undefined>;
private isVisible: boolean = false;
private readonly menuItems: Map<
@@ -147,6 +153,7 @@ export class RadialMenu implements Layer {
.style("touch-action", "none")
.on("contextmenu", (e) => {
e.preventDefault();
this.hideRadialMenu();
});
const svg = this.menuElement
@@ -275,8 +282,26 @@ export class RadialMenu implements Layer {
.style("pointer-events", "none");
}
tick() {
// Update logic if needed
async tick() {
// Only update when menu is visible
if (!this.isVisible || this.clickedCell === null) return;
const myPlayer = this.g.myPlayer();
if (myPlayer === null || !myPlayer.isAlive()) return;
const tile = this.g.ref(this.clickedCell.x, this.clickedCell.y);
if (this.originalTileOwner.isPlayer()) {
if (this.g.owner(tile) != this.originalTileOwner) {
this.closeMenu();
return;
}
} else {
if (this.g.owner(tile).isPlayer() || this.g.owner(tile) == myPlayer) {
this.closeMenu();
return;
}
}
const actions = await myPlayer.actions(tile);
this.disableAllButtons();
this.handlePlayerActions(myPlayer, actions, tile);
}
renderLayer(context: CanvasRenderingContext2D) {
@@ -299,12 +324,7 @@ export class RadialMenu implements Layer {
} else {
this.showRadialMenu(event.x, event.y);
}
this.enableCenterButton(false);
for (const item of this.menuItems.values()) {
item.disabled = true;
this.updateMenuItemState(item);
}
this.disableAllButtons();
this.clickedCell = this.transformHandler.screenToWorldCoordinates(
event.x,
event.y,
@@ -313,7 +333,7 @@ export class RadialMenu implements Layer {
return;
}
const tile = this.g.ref(this.clickedCell.x, this.clickedCell.y);
this.originalTileOwner = this.g.owner(tile);
if (this.g.inSpawnPhase()) {
if (this.g.isLand(tile) && !this.g.hasOwner(tile)) {
this.enableCenterButton(true);
@@ -321,10 +341,8 @@ export class RadialMenu implements Layer {
return;
}
const myPlayer = this.g
.playerViews()
.find((p) => p.clientID() === this.clientID);
if (myPlayer === undefined) {
const myPlayer = this.g.myPlayer();
if (myPlayer === null) {
consolex.warn("my player not found");
return;
}
@@ -341,9 +359,12 @@ export class RadialMenu implements Layer {
actions: PlayerActions,
tile: TileRef,
) {
this.activateMenuElement(Slot.Build, "#ebe250", buildIcon, () => {
this.buildMenu.showMenu(tile);
});
if (!this.g.inSpawnPhase()) {
this.activateMenuElement(Slot.Build, "#ebe250", buildIcon, () => {
this.buildMenu.showMenu(tile);
});
}
if (this.g.hasOwner(tile)) {
this.activateMenuElement(Slot.Info, "#64748B", infoIcon, () => {
this.playerPanel.show(actions, tile);
@@ -370,16 +391,28 @@ export class RadialMenu implements Layer {
);
});
}
if (actions.canBoat) {
if (
actions.buildableUnits.find((bu) => bu.type == UnitType.TransportShip)
?.canBuild
) {
this.activateMenuElement(Slot.Boat, "#3f6ab1", boatIcon, () => {
if (this.clickedCell === null) return;
this.eventBus.emit(
new SendBoatAttackIntentEvent(
this.g.owner(tile).id(),
this.clickedCell,
this.uiState.attackRatio * myPlayer.troops(),
),
);
// BestTransportShipSpawn is an expensive operation, so
// we calculate it here and send the spawn tile to other clients.
myPlayer.bestTransportShipSpawn(tile).then((spawn) => {
let spawnTile: Cell | null = null;
if (spawn !== false) {
spawnTile = new Cell(this.g.x(spawn), this.g.y(spawn));
}
this.eventBus.emit(
new SendBoatAttackIntentEvent(
this.g.owner(tile).id(),
this.clickedCell,
this.uiState.attackRatio * myPlayer.troops(),
spawnTile,
),
);
});
});
}
if (actions.canAttack) {
@@ -440,6 +473,14 @@ export class RadialMenu implements Layer {
this.hideRadialMenu();
}
private disableAllButtons() {
this.enableCenterButton(false);
for (const item of this.menuItems.values()) {
item.disabled = true;
this.updateMenuItemState(item);
}
}
private activateMenuElement(
slot: Slot,
color: string,
+51 -29
View File
@@ -1,13 +1,11 @@
import { blue, red } from "../../../core/configuration/Colors";
import { GameMode, Team } from "../../../core/game/Game";
import { GameView } from "../../../core/game/GameView";
import { TransformHandler } from "../TransformHandler";
import { Layer } from "./Layer";
export class SpawnTimer implements Layer {
private ratio = 0;
private leftColor = "rgba(0, 128, 255, 0.7)";
private rightColor = "rgba(0, 0, 0, 0.5)";
private ratios = [0];
private colors = ["rgba(0, 128, 255, 0.7)", "rgba(0, 0, 0, 0.5)"];
constructor(
private game: GameView,
@@ -18,27 +16,35 @@ export class SpawnTimer implements Layer {
tick() {
if (this.game.inSpawnPhase()) {
this.ratio = this.game.ticks() / this.game.config().numSpawnPhaseTurns();
return;
}
if (this.game.config().gameConfig().gameMode !== GameMode.Team) {
this.ratio = 0;
this.ratios[0] =
this.game.ticks() / this.game.config().numSpawnPhaseTurns();
return;
}
const numBlueTiles = this.game
.players()
.filter((p) => p.team() === Team.Blue)
.reduce((acc, p) => acc + p.numTilesOwned(), 0);
this.ratios = [];
this.colors = [];
const numRedTiles = this.game
.players()
.filter((p) => p.team() === Team.Red)
.reduce((acc, p) => acc + p.numTilesOwned(), 0);
if (this.game.config().gameConfig().gameMode != GameMode.Team) {
return;
}
this.ratio = numBlueTiles / (numBlueTiles + numRedTiles);
this.leftColor = blue.toRgbString();
this.rightColor = red.toRgbString();
const teamTiles: Map<Team, number> = new Map();
for (const player of this.game.players()) {
const team = player.team();
const tiles = teamTiles.get(team) ?? 0;
const sum = tiles + player.numTilesOwned();
teamTiles.set(team, sum);
}
const theme = this.game.config().theme();
const total = sumIterator(teamTiles.values());
if (total === 0) return;
for (const [team, count] of teamTiles) {
const ratio = count / total;
const color = theme.teamColor(team).toRgbString();
this.ratios.push(ratio);
this.colors.push(color);
}
}
shouldTransform(): boolean {
@@ -46,18 +52,34 @@ export class SpawnTimer implements Layer {
}
renderLayer(context: CanvasRenderingContext2D) {
if (this.ratio === 0) {
return;
}
if (this.ratios === null) return;
if (this.ratios.length === 0) return;
if (this.colors.length === 0) return;
const barHeight = 10;
const barBackgroundWidth = this.transformHandler.width();
const barWidth = this.transformHandler.width();
// Draw bar background
context.fillStyle = this.rightColor;
context.fillRect(0, 0, barBackgroundWidth, barHeight);
let x = 0;
let filledRatio = 0;
for (let i = 0; i < this.ratios.length && i < this.colors.length; i++) {
const ratio = this.ratios[i];
const segmentWidth = barWidth * ratio;
context.fillStyle = this.leftColor;
context.fillRect(0, 0, barBackgroundWidth * this.ratio, barHeight);
context.fillStyle = this.colors[i];
context.fillRect(x, 0, segmentWidth, barHeight);
x += segmentWidth;
filledRatio += ratio;
}
}
}
function sumIterator(values: MapIterator<number>) {
// To use reduce, we'd need to allocate an array:
// return Array.from(values).reduce((sum, v) => sum + v, 0);
let total = 0;
for (const value of values) {
total += value;
}
return total;
}
+9 -1
View File
@@ -120,6 +120,14 @@ export class TerritoryLayer implements Layer {
if (!centerTile) {
continue;
}
let color = this.theme.spawnHighlightColor();
if (
this.game.myPlayer() != null &&
this.game.myPlayer() != human &&
this.game.myPlayer().isFriendly(human)
) {
color = this.theme.selfColor();
}
for (const tile of this.game.bfs(
centerTile,
euclDistFN(centerTile, 9, true),
@@ -127,7 +135,7 @@ export class TerritoryLayer implements Layer {
if (!this.game.hasOwner(tile)) {
this.paintHighlightCell(
new Cell(this.game.x(tile), this.game.y(tile)),
this.theme.spawnHighlightColor(),
color,
255,
);
}
+101 -234
View File
@@ -3,11 +3,7 @@ import { EventBus } from "../../../core/EventBus";
import { ClientID } from "../../../core/Schemas";
import { Theme } from "../../../core/configuration/Config";
import { UnitType } from "../../../core/game/Game";
import {
euclDistFN,
manhattanDistFN,
TileRef,
} from "../../../core/game/GameMap";
import { TileRef } from "../../../core/game/GameMap";
import { GameUpdateType } from "../../../core/game/GameUpdates";
import { GameView, PlayerView, UnitView } from "../../../core/game/GameView";
import {
@@ -19,6 +15,8 @@ import { MoveWarshipIntentEvent } from "../../Transport";
import { TransformHandler } from "../TransformHandler";
import { Layer } from "./Layer";
import { getColoredSprite, loadAllSprites } from "../SpriteLoader";
enum Relationship {
Self,
Ally,
@@ -81,6 +79,8 @@ export class UnitLayer implements Layer {
this.eventBus.on(MouseUpEvent, (e) => this.onMouseUp(e));
this.eventBus.on(UnitSelectionEvent, (e) => this.onUnitSelectionChange(e));
this.redraw();
loadAllSprites();
}
/**
@@ -204,14 +204,23 @@ export class UnitLayer implements Layer {
this.canvas.height = this.game.height();
this.transportShipTrailCanvas.width = this.game.width();
this.transportShipTrailCanvas.height = this.game.height();
const updates = this.game.updatesSinceLastTick();
const unitUpdates = updates?.[GameUpdateType.Unit] ?? [];
for (const u of unitUpdates) {
const unit = this.game.unit(u.id);
if (typeof unit === "undefined") continue;
this.onUnitEvent(unit);
}
this.game
?.updatesSinceLastTick()
?.[GameUpdateType.Unit]?.forEach((unit) => {
this.onUnitEvent(this.game.unit(unit.id));
});
this.boatToTrail.forEach((trail, unit) => {
for (const t of trail) {
this.paintCell(
this.game.x(t),
this.game.y(t),
this.relationship(unit),
this.theme.territoryColor(unit.owner()),
150,
this.transportShipTrailContext,
);
}
});
}
private relationship(unit: UnitView): Relationship {
@@ -261,65 +270,10 @@ export class UnitLayer implements Layer {
}
private handleWarShipEvent(unit: UnitView) {
const rel = this.relationship(unit);
// Clear previous area
for (const t of this.game.bfs(
unit.lastTile(),
euclDistFN(unit.lastTile(), 6, false),
)) {
this.clearCell(this.game.x(t), this.game.y(t));
}
if (!unit.isActive()) {
return;
}
let outerColor = this.theme.territoryColor(unit.owner());
if (unit.warshipTargetId()) {
const targetOwner = this.game
.units()
.find((u) => u.id() === unit.warshipTargetId())
?.owner();
if (targetOwner === this.myPlayer) {
outerColor = colord({ r: 200, b: 0, g: 0 });
}
}
// Paint outer territory
for (const t of this.game.bfs(
unit.tile(),
euclDistFN(unit.tile(), 5, false),
)) {
this.paintCell(this.game.x(t), this.game.y(t), rel, outerColor, 255);
}
// Paint border
for (const t of this.game.bfs(
unit.tile(),
manhattanDistFN(unit.tile(), 4),
)) {
this.paintCell(
this.game.x(t),
this.game.y(t),
rel,
this.theme.borderColor(unit.owner()),
255,
);
}
// Paint inner territory
for (const t of this.game.bfs(
unit.tile(),
euclDistFN(unit.tile(), 1, false),
)) {
this.paintCell(
this.game.x(t),
this.game.y(t),
rel,
this.theme.territoryColor(unit.owner()),
255,
);
this.drawSprite(unit, colord({ r: 200, b: 0, g: 0 }));
} else {
this.drawSprite(unit);
}
}
@@ -357,89 +311,11 @@ export class UnitLayer implements Layer {
// interception missle from SAM
private handleMissileEvent(unit: UnitView) {
const rel = this.relationship(unit);
const range = 2;
for (const t of this.game.bfs(
unit.lastTile(),
euclDistFN(unit.lastTile(), range, false),
)) {
this.clearCell(this.game.x(t), this.game.y(t));
}
if (unit.isActive()) {
for (const t of this.game.bfs(
unit.tile(),
euclDistFN(unit.tile(), range, false),
)) {
this.paintCell(
this.game.x(t),
this.game.y(t),
rel,
this.theme.spawnHighlightColor(),
255,
);
}
this.paintCell(
this.game.x(unit.tile()),
this.game.y(unit.tile()),
rel,
this.theme.borderColor(unit.owner()),
255,
);
}
this.drawSprite(unit);
}
private handleNuke(unit: UnitView) {
const rel = this.relationship(unit);
let range = 0;
switch (unit.type()) {
case UnitType.AtomBomb:
range = 4;
break;
case UnitType.HydrogenBomb:
range = 6;
break;
case UnitType.MIRV:
range = 9;
break;
}
// Clear previous area
for (const t of this.game.bfs(
unit.lastTile(),
euclDistFN(unit.lastTile(), range, false),
)) {
this.clearCell(this.game.x(t), this.game.y(t));
}
if (unit.isActive()) {
for (const t of this.game.bfs(
unit.tile(),
euclDistFN(unit.tile(), range, false),
)) {
this.paintCell(
this.game.x(t),
this.game.y(t),
rel,
this.theme.spawnHighlightColor(),
255,
);
}
for (const t of this.game.bfs(
unit.tile(),
euclDistFN(unit.tile(), 2, false),
)) {
this.paintCell(
this.game.x(t),
this.game.y(t),
rel,
this.theme.borderColor(unit.owner()),
255,
);
}
}
this.drawSprite(unit);
}
private handleMIRVWarhead(unit: UnitView) {
@@ -460,45 +336,7 @@ export class UnitLayer implements Layer {
}
private handleTradeShipEvent(unit: UnitView) {
const rel = this.relationship(unit);
// Clear previous area
for (const t of this.game.bfs(
unit.lastTile(),
euclDistFN(unit.lastTile(), 3, false),
)) {
this.clearCell(this.game.x(t), this.game.y(t));
}
if (unit.isActive()) {
// Paint territory
for (const t of this.game.bfs(
unit.tile(),
manhattanDistFN(unit.tile(), 2),
)) {
this.paintCell(
this.game.x(t),
this.game.y(t),
rel,
this.theme.territoryColor(unit.owner()),
255,
);
}
// Paint border
for (const t of this.game.bfs(
unit.tile(),
manhattanDistFN(unit.tile(), 1),
)) {
this.paintCell(
this.game.x(t),
this.game.y(t),
rel,
this.theme.borderColor(unit.owner()),
255,
);
}
}
this.drawSprite(unit);
}
private handleBoatEvent(unit: UnitView) {
@@ -511,53 +349,21 @@ export class UnitLayer implements Layer {
if (typeof trail === "undefined") return;
trail.push(unit.lastTile());
// Clear previous area
for (const t of this.game.bfs(
unit.lastTile(),
manhattanDistFN(unit.lastTile(), 2),
)) {
this.clearCell(this.game.x(t), this.game.y(t));
// Paint trail
for (const t of trail.slice(-1)) {
this.paintCell(
this.game.x(t),
this.game.y(t),
rel,
this.theme.territoryColor(unit.owner()),
150,
this.transportShipTrailContext,
);
}
if (unit.isActive()) {
// Paint trail
for (const t of trail.slice(-1)) {
this.paintCell(
this.game.x(t),
this.game.y(t),
rel,
this.theme.territoryColor(unit.owner()),
150,
this.transportShipTrailContext,
);
}
this.drawSprite(unit);
for (const t of this.game.bfs(
unit.tile(),
manhattanDistFN(unit.tile(), 2),
)) {
this.paintCell(
this.game.x(t),
this.game.y(t),
rel,
this.theme.borderColor(unit.owner()),
255,
);
}
for (const t of this.game.bfs(
unit.tile(),
manhattanDistFN(unit.tile(), 1),
)) {
this.paintCell(
this.game.x(t),
this.game.y(t),
rel,
this.theme.territoryColor(unit.owner()),
255,
);
}
} else {
if (!unit.isActive()) {
for (const t of trail) {
this.clearCell(
this.game.x(t),
@@ -620,4 +426,65 @@ export class UnitLayer implements Layer {
) {
context.clearRect(x, y, 1, 1);
}
drawSprite(unit: UnitView, customTerritoryColor?: Colord) {
const x = this.game.x(unit.tile());
const y = this.game.y(unit.tile());
const lastX = this.game.x(unit.lastTile());
const lastY = this.game.y(unit.lastTile());
let alternateViewColor = null;
if (this.alternateView) {
let rel = this.relationship(unit);
if (unit.type() == UnitType.TradeShip && unit.dstPortId() != null) {
const target = this.game.unit(unit.dstPortId())?.owner();
const myPlayer = this.game.myPlayer();
if (myPlayer != null && target != null) {
if (myPlayer == target) {
rel = Relationship.Self;
} else if (myPlayer.isFriendly(target)) {
rel = Relationship.Ally;
}
}
}
switch (rel) {
case Relationship.Self:
alternateViewColor = this.theme.selfColor();
break;
case Relationship.Ally:
alternateViewColor = this.theme.allyColor();
break;
case Relationship.Enemy:
alternateViewColor = this.theme.enemyColor();
break;
}
}
const sprite = getColoredSprite(
unit,
this.theme,
alternateViewColor ?? customTerritoryColor,
alternateViewColor,
);
const clearsize = sprite.width + 1;
this.context.clearRect(
lastX - clearsize / 2,
lastY - clearsize / 2,
clearsize,
clearsize,
);
if (unit.isActive()) {
this.context.drawImage(
sprite,
Math.round(x - sprite.width / 2),
Math.round(y - sprite.height / 2),
sprite.width,
sprite.width,
);
}
}
}
+35 -45
View File
@@ -1,38 +1,24 @@
import { LitElement, css, html } from "lit";
import { customElement, state } from "lit/decorators.js";
import mastersIcon from "../../../../resources/images/MastersIcon.png";
import { EventBus } from "../../../core/EventBus";
import { Team } from "../../../core/game/Game";
import { GameUpdateType } from "../../../core/game/GameUpdates";
import { GameView, PlayerView } from "../../../core/game/GameView";
import { PseudoRandom } from "../../../core/PseudoRandom";
import { simpleHash } from "../../../core/Util";
import { SendWinnerEvent } from "../../Transport";
import { Layer } from "./Layer";
// Add this at the top of your file
declare global {
interface Window {
adsbygoogle: unknown[];
}
}
// Add this at the top of your file
declare let adsbygoogle: unknown[];
@customElement("win-modal")
export class WinModal extends LitElement implements Layer {
public game: GameView;
public eventBus: EventBus;
private rand: PseudoRandom;
private hasShownDeathModal = false;
@state()
isVisible = false;
private _title: string;
private won: boolean;
// Override to prevent shadow DOM creation
createRenderRoot() {
@@ -53,7 +39,7 @@ export class WinModal extends LitElement implements Layer {
box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
backdrop-filter: blur(5px);
color: white;
width: 300px;
width: 350px;
transition:
opacity 0.3s ease-in-out,
visibility 0.3s ease-in-out;
@@ -77,7 +63,7 @@ export class WinModal extends LitElement implements Layer {
.win-modal h2 {
margin: 0 0 15px 0;
font-size: 24px;
font-size: 26px;
text-align: center;
color: white;
}
@@ -127,7 +113,7 @@ export class WinModal extends LitElement implements Layer {
}
.win-modal h2 {
font-size: 20px;
font-size: 26px;
}
.win-modal button {
@@ -160,29 +146,40 @@ export class WinModal extends LitElement implements Layer {
innerHtml() {
return html`
<div style="text-align: center; margin: 15px 0; line-height: 1.5;">
<p>
<span style="color: red;">Time's running out!</span> <br />
I need your support to continue working on OpenFront full-time. Please
donate now to keep the updates, new features, and improvements coming.
</p>
<a
href="https://patreon.com/OpenFront"
target="_blank"
rel="noopener noreferrer"
<div
style="
text-align: center;
margin: 10px 0;
line-height: 1.5;
background-image: url(${mastersIcon});
background-size: 100px;
background-position: center;
background-repeat: no-repeat;
background-blend-mode: overlay;
position: relative;
"
>
<div
style="
display: inline-block;
padding: 10px 20px;
background-color: #FF424D;
color: white;
text-decoration: none;
margin: 10px 0;
padding: 14px;
background: rgba(0, 0, 0, 0.76);
border-radius: 5px;
font-weight: bold;
transition: background-color 0.2s;
position: relative;
z-index: 1;
font-size: 22px;
"
>
Support on Patreon
</a>
Watch the best compete in the
<br />
<a
href="https://openfrontmaster.com/"
target="_blank"
rel="noopener noreferrer"
style="color: #00bfff; font-weight: bold; text-decoration: underline;"
>OpenFront Masters</a
>
</div>
</div>
`;
}
@@ -202,9 +199,7 @@ export class WinModal extends LitElement implements Layer {
window.location.href = "/";
}
init() {
this.rand = new PseudoRandom(simpleHash(this.game.myClientID()));
}
init() {}
tick() {
const myPlayer = this.game.myPlayer();
@@ -217,7 +212,6 @@ export class WinModal extends LitElement implements Layer {
) {
this.hasShownDeathModal = true;
this._title = "You died";
this.won = false;
this.show();
}
const updates = this.game.updatesSinceLastTick();
@@ -229,10 +223,8 @@ export class WinModal extends LitElement implements Layer {
);
if (wu.winner === this.game.myPlayer()?.team()) {
this._title = "Your team won!";
this.won = true;
} else {
this._title = `${wu.winner} team has won!`;
this.won = false;
}
this.show();
} else {
@@ -247,10 +239,8 @@ export class WinModal extends LitElement implements Layer {
}
if (winner === this.game.myPlayer()) {
this._title = "You Won!";
this.won = true;
} else {
this._title = `${winner.name()} has won!`;
this.won = false;
}
this.show();
}
+59 -38
View File
@@ -48,8 +48,10 @@
.left-gutter-ad {
position: fixed;
left: 0;
top: 200px; /* Changed from top: 50% */
transform: none; /* Removed translateY(-50%) since we don't need to center anymore */
top: 200px;
/* Changed from top: 50% */
transform: none;
/* Removed translateY(-50%) since we don't need to center anymore */
z-index: 40;
width: 300px;
height: 600px;
@@ -68,8 +70,10 @@
.right-gutter-ad {
position: fixed;
right: 0;
top: 200px; /* Changed from top: 50% */
transform: none; /* Removed translateY(-50%) since we don't need to center anymore */
top: 200px;
/* Changed from top: 50% */
transform: none;
/* Removed translateY(-50%) since we don't need to center anymore */
z-index: 40;
width: 300px;
height: 600px;
@@ -137,6 +141,7 @@
gtag("config", "G-WQGQQ8RDN4");
</script>
</head>
<body
class="h-full select-none font-sans min-h-screen bg-opacity-0 bg-cover bg-center bg-fixed transition-opacity duration-300 ease-in-out flex flex-col"
>
@@ -198,47 +203,35 @@
/>
</g>
</svg>
<div class="l-header__highlightText">v21.2</div>
<div class="l-header__highlightText">v22.0</div>
</div>
</header>
<div class="bg-image"></div>
<!-- Left gutter ad placement - full height, no empty space -->
<div class="left-gutter-ad ad">
<google-ad
adSlot="5220834834"
adFormat="vertical"
fullWidthResponsive="false"
></google-ad>
</div>
<div class="right-gutter-ad ad">
<google-ad
adSlot="1814331462"
adFormat="vertical"
fullWidthResponsive="false"
></google-ad>
</div>
<dark-mode-button></dark-mode-button>
<!-- Main container with responsive padding -->
<main class="flex justify-center items-center flex-grow">
<div class="container">
<main class="flex justify-center flex-grow">
<div class="container pt-12">
<o-button
id="login-discord"
title="Initializing..."
disable="true"
block
></o-button>
<o-button
id="logout-discord"
title="Log out"
translationKey="main.log_out"
visible="false"
block
></o-button>
<div class="container__row">
<flag-input class="w-[20%] md:w-[15%]"></flag-input>
<username-input class="w-full"></username-input>
</div>
<div>
<a
target="_blank"
href="https://discord.gg/openfront"
class="w-full bg-[#5865F2] hover:bg-[#4752C4] text-white p-3 sm:p-4 lg:p-5 font-medium text-lg sm:text-xl lg:text-2xl rounded-lg border-none cursor-pointer transition-colors duration-300 flex justify-center items-center gap-5"
>
<img
style="height: 50px; width: 50px"
alt="Discord"
src="../../resources/icons/discord.svg"
/>
<span data-i18n="main.join_discord"> Join the Discord! </span>
</a>
</div>
<div></div>
<div>
<public-lobby class="w-full"></public-lobby>
</div>
@@ -279,6 +272,20 @@
</div>
</main>
<!-- User Setting -->
<button
id="settings-button"
title="Settings"
class="fixed bottom-4 right-4 z-50 rounded-full p-2 shadow-lg transition-colors duration-300 flex items-center justify-center"
style="width: 80px; height: 80px; background-color: #0075ff"
>
<img
src="../../resources/images/SettingIconWhite.svg"
alt="Settings"
style="width: 72px; height: 72px"
/>
</button>
<!-- Game components -->
<div id="customMenu" class="mt-4 sm:mt-6 lg:mt-8">
<ul></ul>
@@ -327,15 +334,27 @@
>
Wiki
</a>
<a
target="_blank"
href="https://discord.gg/jRpxXvG42t"
class="t-link"
>
<span data-i18n="main.join_discord"> Join the Discord! </span>
</a>
</div>
<div class="l-footer__col t-text-white">
© 2025
<a
href="https://github.com/openfrontio/OpenFrontIO"
class="t-link"
target="_blank"
>
OpenFront.io
©2025 OpenFront
</a>
<a href="/privacy-policy.html" class="t-link" target="_blank">
Privacy Policy
</a>
<a href="/terms-of-service.html" class="t-link" target="_blank">
Terms of Service
</a>
</div>
</div>
@@ -353,6 +372,8 @@
<player-panel></player-panel>
<help-modal></help-modal>
<dark-mode-button></dark-mode-button>
<user-setting></user-setting>
<multi-tab-modal></multi-tab-modal>
<div
id="language-modal"
class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex justify-center items-center"
+210
View File
@@ -0,0 +1,210 @@
import { decodeJwt } from "jose";
import {
RefreshResponseSchema,
TokenPayload,
TokenPayloadSchema,
UserMeResponse,
UserMeResponseSchema,
} from "./ApiSchemas";
function getAudience() {
const { hostname } = new URL(window.location.href);
const domainname = hostname.split(".").slice(-2).join(".");
return domainname;
}
function getApiBase() {
const domainname = getAudience();
return domainname === "localhost"
? (localStorage.getItem("apiHost") ?? "http://localhost:8787")
: `https://api.${domainname}`;
}
function getToken(): string | null {
const { hash } = window.location;
if (hash.startsWith("#")) {
const params = new URLSearchParams(hash.slice(1));
const token = params.get("token");
if (token) {
localStorage.setItem("token", token);
}
// Clean the URL
history.replaceState(
null,
"",
window.location.pathname + window.location.search,
);
}
return localStorage.getItem("token");
}
export function discordLogin() {
window.location.href = `${getApiBase()}/login/discord?redirect_uri=${window.location.href}`;
}
export async function logOut(allSessions: boolean = false) {
const token = localStorage.getItem("token");
if (token === null) return;
localStorage.removeItem("token");
__isLoggedIn = false;
const response = await fetch(
getApiBase() + allSessions ? "/revoke" : "/logout",
{
method: "POST",
headers: {
authorization: `Bearer ${token}`,
},
},
);
if (response.ok === false) {
console.error("Logout failed", response);
return false;
}
return true;
}
let __isLoggedIn: TokenPayload | false | undefined = undefined;
export function isLoggedIn(): TokenPayload | false {
if (__isLoggedIn === undefined) {
__isLoggedIn = _isLoggedIn();
}
return __isLoggedIn;
}
export function _isLoggedIn(): TokenPayload | false {
try {
const token = getToken();
if (!token) {
// console.log("No token found");
return false;
}
// Verify the JWT (requires browser support)
// const jwks = createRemoteJWKSet(
// new URL(getApiBase() + "/.well-known/jwks.json"),
// );
// const { payload, protectedHeader } = await jwtVerify(token, jwks, {
// issuer: getApiBase(),
// audience: getAudience(),
// });
// Decode the JWT
const payload = decodeJwt(token);
const { iss, aud, exp, iat } = payload;
if (iss !== getApiBase()) {
// JWT was not issued by the correct server
console.error(
'unexpected "iss" claim value',
// JSON.stringify(payload, null, 2),
);
logOut();
return false;
}
if (aud !== getAudience()) {
// JWT was not issued for this website
console.error(
'unexpected "aud" claim value',
// JSON.stringify(payload, null, 2),
);
logOut();
return false;
}
const now = Math.floor(Date.now() / 1000);
if (exp !== undefined && now >= exp) {
// JWT expired
console.error(
'after "exp" claim value',
// JSON.stringify(payload, null, 2),
);
logOut();
return false;
}
const refreshAge: number = 6 * 3600; // 6 hours
if (iat !== undefined && now >= iat + refreshAge) {
console.log("Refreshing access token...");
postRefresh().then((success) => {
if (success) {
console.log("Refreshed access token successfully.");
} else {
console.error("Failed to refresh access token.");
}
});
}
const result = TokenPayloadSchema.safeParse(payload);
if (!result.success) {
// Invalid response
console.error(
"Invalid payload",
// JSON.stringify(payload),
JSON.stringify(result.error),
);
return false;
}
return result.data;
} catch (e) {
console.log(e);
return false;
}
}
export async function postRefresh(): Promise<boolean> {
try {
const token = getToken();
if (!token) return false;
// Refresh the JWT
const response = await fetch(getApiBase() + "/refresh", {
method: "POST",
headers: {
authorization: `Bearer ${token}`,
},
});
if (response.status !== 200) return false;
const body = await response.json();
const result = RefreshResponseSchema.safeParse(body);
if (!result.success) {
console.error(
"Invalid response",
JSON.stringify(body),
JSON.stringify(result.error),
);
return false;
}
localStorage.setItem("token", result.data.token);
return true;
} catch (e) {
return false;
}
}
export async function getUserMe(): Promise<UserMeResponse | false> {
try {
const token = getToken();
if (!token) return false;
// Get the user object
const response = await fetch(getApiBase() + "/users/@me", {
headers: {
authorization: `Bearer ${token}`,
},
});
if (response.status !== 200) return false;
const body = await response.json();
const result = UserMeResponseSchema.safeParse(body);
if (!result.success) {
console.error(
"Invalid response",
JSON.stringify(body),
JSON.stringify(result.error),
);
return false;
}
return result.data;
} catch (e) {
return false;
}
}
+6
View File
@@ -8,6 +8,7 @@
@import url("./styles/layout/container.css");
@import url("./styles/components/button.css");
@import url("./styles/components/modal.css");
@import url("./styles/components/setting.css");
@import url("./styles/components/controls.css");
* {
-webkit-box-sizing: border-box;
@@ -193,6 +194,11 @@ label.option-card:hover {
margin: 8px 0px 0px 0px;
}
#lobbyIdInput {
font-family: monospace;
font-weight: 600;
}
.lobby-id-button {
display: flex;
align-items: center;
+11
View File
@@ -78,3 +78,14 @@
font-size: 14px;
color: #ccc;
}
.setting-input.keybind:hover .key,
.setting-input.keybind:focus .key {
background-color: #333;
box-shadow: 0 2px 0 #222;
}
.setting-input.keybind.listening .key {
background-color: #1d4ed8; /* blue-700 */
box-shadow: 0 2px 0 #0f172a; /* darker blue */
}
+326
View File
@@ -0,0 +1,326 @@
.settings-list {
display: flex;
flex-direction: column;
gap: 16px;
padding: 12px;
align-items: center;
}
.setting-item {
display: flex;
justify-content: space-between;
align-items: flex-start;
background: #1e1e1e;
border: 1px solid #333;
border-radius: 10px;
padding: 12px 20px;
width: 360px !important;
max-width: 360px !important;
min-width: 360px !important;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.4);
transition: background 0.3s ease;
gap: 12px;
}
.setting-item.column {
flex-direction: column;
}
@keyframes rainbow-background {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
.setting-item.easter-egg {
background: linear-gradient(
270deg,
#990033,
#996600,
#336600,
#008080,
#1c3f99,
#5e0099,
#990033
);
background-size: 1400% 1400%;
animation: rainbow-background 10s ease infinite;
color: #fff;
}
.easter-egg-popup {
position: fixed;
top: 40px;
left: 50%;
transform: translate(-50%, -50%) scale(0.9);
padding: 16px 24px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
font-size: 20px;
border-radius: 12px;
animation: fadePop 5s ease-out forwards;
z-index: 9999;
}
.setting-popup {
position: fixed;
top: 40px;
left: 50%;
transform: translate(-50%, -50%) scale(0.9);
padding: 16px 24px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
font-size: 20px;
border-radius: 12px;
animation: fadePop_2 10s ease-out forwards;
z-index: 9999;
}
@keyframes fadePop {
0% {
opacity: 0;
transform: translate(-50%, -50%) scale(0.6);
}
30% {
opacity: 1;
transform: translate(-50%, -50%) scale(1.05);
}
70% {
transform: translate(-50%, -50%) scale(1);
}
100% {
opacity: 0;
transform: translate(-50%, -50%) scale(0.9);
}
}
@keyframes fadePop_2 {
0% {
opacity: 0;
transform: translate(-50%, -50%) scale(0.6);
}
5% {
opacity: 1;
transform: translate(-50%, -50%) scale(1.05);
}
95% {
opacity: 1;
transform: translate(-50%, -50%) scale(1.05);
}
100% {
opacity: 0;
transform: translate(-50%, -50%) scale(0.9);
}
}
.setting-item:hover {
background: #2a2a2a;
}
.setting-item.easter-egg:hover {
background: linear-gradient(
270deg,
#990033,
#996600,
#336600,
#008080,
#1c3f99,
#5e0099,
#990033
);
background-size: 1400% 1400%;
animation: rainbow-background 10s ease infinite;
color: #fff;
}
.setting-label {
color: #f0f0f0;
font-size: 15px;
font-weight: 500;
}
.setting-input {
margin-left: 16px;
flex-shrink: 0;
}
.setting-item.vertical {
flex-direction: column;
align-items: stretch;
gap: 8px;
overflow: hidden;
}
.toggle-row {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
}
.slider-row {
display: flex;
justify-content: space-between;
align-items: center;
}
.setting-input.slider.full-width {
width: 90%;
}
.setting-input.slider {
-webkit-appearance: none;
width: 180px;
height: 10px;
background: linear-gradient(to right, #2196f3 50%, #444 50%);
border-radius: 5px;
outline: none;
transition: background 0.3s;
}
.setting-input.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 18px;
height: 18px;
border-radius: 50%;
background: #fff;
border: 2px solid #2196f3;
cursor: pointer;
}
.setting-input.slider::-moz-range-track {
background-color: #444;
height: 10px;
border-radius: 5px;
}
.setting-input.slider::-moz-range-progress {
background-color: #2196f3;
height: 10px;
border-radius: 5px;
}
.setting-input.slider:focus {
outline: none;
}
.slider-value {
width: 100%;
text-align: center;
font-size: 13px;
color: #aaa;
}
.setting-input.number {
width: 80px;
padding: 6px 8px;
border: 1px solid #aaa;
border-radius: 6px;
background-color: #ffffff;
color: #000000;
}
.switch {
position: relative;
display: inline-block;
width: 50px;
height: 26px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.switch.switch-right {
display: block;
margin-left: auto;
}
.slider-round {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #d9534f;
transition: 0.4s;
border-radius: 34px;
}
.slider-round::before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 3px;
background-color: white;
transition: 0.4s;
border-radius: 50%;
}
.switch input:checked + .slider-round {
background-color: #4caf50;
}
.switch input:checked + .slider-round::before {
transform: translateX(24px);
}
.setting-label-group {
display: flex;
flex-direction: column;
}
.setting-description {
font-size: 12px;
color: #888;
margin-top: 2px;
white-space: normal;
word-break: break-word;
}
.setting-keybind-box {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
}
.setting-keybind-description {
flex: 1;
font-size: 0.75rem;
color: #e5e5e5;
word-break: break-word;
overflow-wrap: break-word;
min-width: 0;
}
.setting-key {
background-color: black;
color: white;
font-weight: 600;
padding: 4px 12px;
border-radius: 6px;
font-family: monospace;
font-size: 0.875rem;
box-shadow: 0 2px 0 #444;
white-space: nowrap;
user-select: none;
outline: none;
}
.setting-key:focus {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
+1 -1
View File
@@ -20,5 +20,5 @@
.l-footer__col {
display: flex;
gap: 10px;
gap: 20px;
}
+9
View File
@@ -4,7 +4,10 @@ import australia from "../../../resources/maps/AustraliaThumb.webp";
import betweenTwoSeas from "../../../resources/maps/BetweenTwoSeasThumb.webp";
import blackSea from "../../../resources/maps/BlackSeaThumb.webp";
import britannia from "../../../resources/maps/BritanniaThumb.webp";
import deglaciatedAntarctica from "../../../resources/maps/DeglaciatedAntarcticaThumb.webp";
import europeClassic from "../../../resources/maps/EuropeClassicThumb.webp";
import europe from "../../../resources/maps/EuropeThumb.webp";
import faroeislands from "../../../resources/maps/FaroeIslandsThumb.webp";
import gatewayToTheAtlantic from "../../../resources/maps/GatewayToTheAtlanticThumb.webp";
import iceland from "../../../resources/maps/IcelandThumb.webp";
import japan from "../../../resources/maps/JapanThumb.webp";
@@ -27,6 +30,8 @@ export function getMapsImage(map: GameMapType): string {
return oceania;
case GameMapType.Europe:
return europe;
case GameMapType.EuropeClassic:
return europeClassic;
case GameMapType.Mena:
return mena;
case GameMapType.NorthAmerica:
@@ -57,6 +62,10 @@ export function getMapsImage(map: GameMapType): string {
return betweenTwoSeas;
case GameMapType.KnownWorld:
return knownworld;
case GameMapType.FaroeIslands:
return faroeislands;
case GameMapType.DeglaciatedAntarctica:
return deglaciatedAntarctica;
default:
return "";
}