main init
This commit is contained in:
114
Library/mobile/kit/ads.ts
Normal file
114
Library/mobile/kit/ads.ts
Normal file
@@ -0,0 +1,114 @@
|
||||
// Kit ads (v1) - AdMob rewarded ads with Google UMP consent (EEA/UK).
|
||||
// From _Tools\Library\mobile\kit (XP-Battleship/src/ads.ts). Needs @capacitor-community/admob.
|
||||
//
|
||||
// configureAds({ testing: false, rewarded: { revive: "ca-app-pub-xxx/yyy", double: "..." } });
|
||||
// await initAds(); // at boot (native only, no-op on web)
|
||||
// if (await showRewarded("revive")) grant();
|
||||
// if (needsPrivacyOptions()) show an "Ad settings" button -> showPrivacyOptions()
|
||||
//
|
||||
// Consent gathering is inert until a GDPR message AND a privacy-options form are published for
|
||||
// the app in the AdMob console. TESTING must be false in the Play-Store build.
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
import { resumeAudio, suspendAudio } from "./audio";
|
||||
|
||||
const TEST_REWARDED_ID = "ca-app-pub-3940256099942544/5224354917"; // Google's official test unit
|
||||
|
||||
const cfg: { testing: boolean; rewarded: Record<string, string> } = { testing: true, rewarded: {} };
|
||||
|
||||
export function configureAds(c: { testing: boolean; rewarded: Record<string, string> }): void {
|
||||
cfg.testing = c.testing;
|
||||
cfg.rewarded = c.rewarded;
|
||||
}
|
||||
|
||||
let initialized = false;
|
||||
let adShowing = false;
|
||||
let privacyOptionsRequired = false;
|
||||
|
||||
/** Fails open on purpose (no network, no published message) - only an explicit
|
||||
* canRequestAds:false (user declined) disables ads. */
|
||||
async function gatherConsent(): Promise<boolean> {
|
||||
const { AdMob, AdmobConsentStatus } = await import("@capacitor-community/admob");
|
||||
try {
|
||||
let info = await AdMob.requestConsentInfo();
|
||||
if (info.isConsentFormAvailable && info.status === AdmobConsentStatus.REQUIRED) {
|
||||
info = await AdMob.showConsentForm();
|
||||
}
|
||||
// enum not re-exported from the plugin entry point - compare the string value
|
||||
privacyOptionsRequired = String(info.privacyOptionsRequirementStatus) === "REQUIRED";
|
||||
return info.canRequestAds !== false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export function needsPrivacyOptions(): boolean {
|
||||
return privacyOptionsRequired;
|
||||
}
|
||||
|
||||
/** Google requires this entry point to stay reachable after the first consent decision. */
|
||||
export async function showPrivacyOptions(): Promise<void> {
|
||||
if (!Capacitor.isNativePlatform()) return;
|
||||
const { AdMob } = await import("@capacitor-community/admob");
|
||||
await AdMob.showPrivacyOptionsForm();
|
||||
}
|
||||
|
||||
/** True while an ad covers the game - pause the game loop. */
|
||||
export function isAdShowing(): boolean {
|
||||
return adShowing;
|
||||
}
|
||||
|
||||
export async function initAds(): Promise<void> {
|
||||
if (!Capacitor.isNativePlatform() || initialized) return;
|
||||
if (!(await gatherConsent())) return; // consent BEFORE any ad request
|
||||
const { AdMob } = await import("@capacitor-community/admob");
|
||||
await AdMob.initialize({ initializeForTesting: cfg.testing });
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
/** Resolves true if the reward was earned. On web (dev) always grants after a short delay. */
|
||||
export async function showRewarded(placement: string): Promise<boolean> {
|
||||
if (!Capacitor.isNativePlatform()) {
|
||||
await new Promise((r) => setTimeout(r, 600));
|
||||
return true;
|
||||
}
|
||||
if (!initialized) {
|
||||
// a transient failure at boot must not disable ads for the whole session
|
||||
await initAds().catch(() => {});
|
||||
if (!initialized) return false;
|
||||
}
|
||||
const adId = cfg.testing ? TEST_REWARDED_ID : cfg.rewarded[placement];
|
||||
if (!adId) return false;
|
||||
const { AdMob, RewardAdPluginEvents } = await import("@capacitor-community/admob");
|
||||
// the ad is a native activity above the WebView: the page never sees visibilitychange
|
||||
adShowing = true;
|
||||
suspendAudio();
|
||||
try {
|
||||
await AdMob.prepareRewardVideoAd({ adId });
|
||||
return await new Promise<boolean>((resolve) => {
|
||||
let rewarded = false;
|
||||
let settled = false;
|
||||
const subs: Array<Promise<{ remove: () => Promise<void> }>> = [];
|
||||
// single exit, runs once - a path that never clears adShowing freezes the game for good
|
||||
const done = (result: boolean): void => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(watchdog);
|
||||
for (const s of subs) void s.then((h) => h.remove()).catch(() => {});
|
||||
adShowing = false;
|
||||
resumeAudio();
|
||||
resolve(result);
|
||||
};
|
||||
subs.push(AdMob.addListener(RewardAdPluginEvents.Rewarded, () => { rewarded = true; }));
|
||||
subs.push(AdMob.addListener(RewardAdPluginEvents.Dismissed, () => done(rewarded)));
|
||||
subs.push(AdMob.addListener(RewardAdPluginEvents.FailedToShow, () => done(rewarded)));
|
||||
// backstop for a Dismissed event the SDK never delivers - un-freezes, never cuts an ad short
|
||||
const watchdog = setTimeout(() => done(rewarded), 300_000);
|
||||
AdMob.showRewardVideoAd().catch(() => done(false));
|
||||
});
|
||||
} catch {
|
||||
adShowing = false;
|
||||
resumeAudio();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
196
Library/mobile/kit/audio.ts
Normal file
196
Library/mobile/kit/audio.ts
Normal file
@@ -0,0 +1,196 @@
|
||||
// Kit audio (v1) - WebAudio music + SFX for Vite/Capacitor apps. From _Tools\Library\mobile\kit.
|
||||
// Generalised from XP-Battleship/src/audio.ts. Everything is best effort: missing files or a
|
||||
// locked AudioContext never throw.
|
||||
//
|
||||
// configureAudio({ base: "/assets/audio/", storageKey: "mygame", preload: ["sfx_click"],
|
||||
// throttle: { sfx_laser: 90 } });
|
||||
// initAudio(); // from the first user gesture (autoplay policy)
|
||||
// playMusic("music_game"); playSfx("sfx_click", 0.8); toggleMute(); setVolumes(0.35, 1);
|
||||
|
||||
interface AudioConfig {
|
||||
base: string;
|
||||
ext: string;
|
||||
storageKey: string;
|
||||
preload: string[];
|
||||
throttle: Record<string, number>;
|
||||
}
|
||||
|
||||
const cfg: AudioConfig = { base: "/assets/audio/", ext: ".mp3", storageKey: "app", preload: [], throttle: {} };
|
||||
|
||||
let ctx: AudioContext | null = null;
|
||||
let musicGain: GainNode | null = null;
|
||||
let sfxGain: GainNode | null = null;
|
||||
let musicSource: AudioBufferSourceNode | null = null;
|
||||
let currentMusic: string | null = null;
|
||||
let muted = false;
|
||||
let musicVol = 0.35;
|
||||
let sfxVol = 1;
|
||||
|
||||
const buffers = new Map<string, AudioBuffer>();
|
||||
const loading = new Map<string, Promise<AudioBuffer | null>>();
|
||||
const lastPlayed = new Map<string, number>();
|
||||
|
||||
function muteKey(): string {
|
||||
return `${cfg.storageKey}_muted`;
|
||||
}
|
||||
|
||||
export function configureAudio(c: Partial<AudioConfig>): void {
|
||||
Object.assign(cfg, c);
|
||||
try {
|
||||
muted = localStorage.getItem(muteKey()) === "1";
|
||||
} catch {
|
||||
muted = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Suspend while hidden, resume on return - Android otherwise leaves the context suspended
|
||||
// after backgrounding, silencing the game for good.
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!ctx) return;
|
||||
if (document.hidden) void ctx.suspend().catch(() => {});
|
||||
else void ctx.resume().catch(() => {});
|
||||
});
|
||||
|
||||
function loadBuffer(name: string): Promise<AudioBuffer | null> {
|
||||
if (!ctx) return Promise.resolve(null);
|
||||
const done = buffers.get(name);
|
||||
if (done) return Promise.resolve(done);
|
||||
const inflight = loading.get(name); // parallel callers share one fetch
|
||||
if (inflight) return inflight;
|
||||
const p = (async (): Promise<AudioBuffer | null> => {
|
||||
try {
|
||||
const res = await fetch(`${cfg.base}${name}${cfg.ext}`);
|
||||
if (!res.ok) return null;
|
||||
const buf = await ctx!.decodeAudioData(await res.arrayBuffer());
|
||||
buffers.set(name, buf);
|
||||
return buf;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
loading.delete(name);
|
||||
}
|
||||
})();
|
||||
loading.set(name, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Call from a user gesture. Safe to call repeatedly. */
|
||||
export function initAudio(): void {
|
||||
if (ctx) {
|
||||
void ctx.resume().catch(() => {});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
ctx = new AudioContext();
|
||||
musicGain = ctx.createGain();
|
||||
musicGain.gain.value = muted ? 0 : musicVol;
|
||||
musicGain.connect(ctx.destination);
|
||||
sfxGain = ctx.createGain();
|
||||
sfxGain.gain.value = muted ? 0 : sfxVol;
|
||||
sfxGain.connect(ctx.destination);
|
||||
for (const n of cfg.preload) void loadBuffer(n);
|
||||
} catch {
|
||||
ctx = null;
|
||||
}
|
||||
}
|
||||
|
||||
export function playMusic(name: string): void {
|
||||
if (!ctx || !musicGain || currentMusic === name) return;
|
||||
currentMusic = name;
|
||||
void ctx.resume().catch(() => {});
|
||||
void loadBuffer(name).then((buf) => {
|
||||
if (!ctx || !musicGain || currentMusic !== name) return; // another track requested meanwhile
|
||||
if (!buf) {
|
||||
currentMusic = null; // allow a retry later
|
||||
return;
|
||||
}
|
||||
musicSource?.stop();
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf;
|
||||
src.loop = true;
|
||||
src.connect(musicGain);
|
||||
src.start();
|
||||
musicSource = src;
|
||||
});
|
||||
}
|
||||
|
||||
export function stopMusic(): void {
|
||||
currentMusic = null;
|
||||
musicSource?.stop();
|
||||
musicSource = null;
|
||||
}
|
||||
|
||||
export function playSfx(name: string, volume = 1): void {
|
||||
if (!ctx || !sfxGain || muted) return;
|
||||
// mobile browsers suspend the context between plays far more readily than desktop
|
||||
void ctx.resume().catch(() => {});
|
||||
const gap = cfg.throttle[name] ?? 0;
|
||||
const now = performance.now();
|
||||
if (gap && now - (lastPlayed.get(name) ?? 0) < gap) return;
|
||||
lastPlayed.set(name, now);
|
||||
const buf = buffers.get(name);
|
||||
if (buf) {
|
||||
playBuffer(buf, volume);
|
||||
return;
|
||||
}
|
||||
// not preloaded: decode once, THEN play - otherwise the first use of a rare clip is silent
|
||||
void loadBuffer(name).then((decoded) => {
|
||||
if (decoded && ctx && sfxGain && !muted) playBuffer(decoded, volume);
|
||||
});
|
||||
}
|
||||
|
||||
function playBuffer(buf: AudioBuffer, volume: number): void {
|
||||
if (!ctx || !sfxGain) return;
|
||||
const src = ctx.createBufferSource();
|
||||
src.buffer = buf;
|
||||
const g = ctx.createGain();
|
||||
g.gain.value = volume;
|
||||
src.connect(g);
|
||||
g.connect(sfxGain);
|
||||
src.start();
|
||||
}
|
||||
|
||||
/** Hard pause (rewarded ad showing, app hidden). */
|
||||
export function suspendAudio(): void {
|
||||
if (ctx) void ctx.suspend().catch(() => {});
|
||||
}
|
||||
|
||||
export function resumeAudio(): void {
|
||||
if (ctx && !document.hidden) void ctx.resume().catch(() => {});
|
||||
}
|
||||
|
||||
export function isMuted(): boolean {
|
||||
return muted;
|
||||
}
|
||||
|
||||
export function toggleMute(): boolean {
|
||||
muted = !muted;
|
||||
try {
|
||||
localStorage.setItem(muteKey(), muted ? "1" : "0");
|
||||
} catch {
|
||||
// storage unavailable - setting lasts for this session only
|
||||
}
|
||||
applyGains();
|
||||
return muted;
|
||||
}
|
||||
|
||||
export function setVolumes(music: number, sfx: number): void {
|
||||
musicVol = music;
|
||||
sfxVol = sfx;
|
||||
applyGains();
|
||||
}
|
||||
|
||||
function applyGains(): void {
|
||||
if (musicGain) musicGain.gain.value = muted ? 0 : musicVol;
|
||||
if (sfxGain) sfxGain.gain.value = muted ? 0 : sfxVol;
|
||||
}
|
||||
|
||||
/** Fade music out under a big moment; unduck targets the CURRENT volume/mute state. */
|
||||
export function duckMusic(on: boolean): void {
|
||||
if (!ctx || !musicGain) return;
|
||||
void ctx.resume().catch(() => {});
|
||||
const now = ctx.currentTime;
|
||||
musicGain.gain.cancelScheduledValues(now);
|
||||
musicGain.gain.setValueAtTime(musicGain.gain.value, now);
|
||||
musicGain.gain.linearRampToValueAtTime(on ? 0 : muted ? 0 : musicVol, now + (on ? 0.15 : 0.3));
|
||||
}
|
||||
58
Library/mobile/kit/haptics.ts
Normal file
58
Library/mobile/kit/haptics.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
// Kit haptics (v1) - vibration pulses, silent no-op outside the native app.
|
||||
// From _Tools\Library\mobile\kit (XP-Battleship/src/haptics.ts). Needs @capacitor/haptics.
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
import { Haptics, ImpactStyle } from "@capacitor/haptics";
|
||||
|
||||
let storageKey = "app_haptics_off";
|
||||
let off = false;
|
||||
|
||||
/** Per-device preference (like mute) - not part of the save / cloud sync. */
|
||||
export function configureHaptics(key: string): void {
|
||||
storageKey = `${key}_haptics_off`;
|
||||
try {
|
||||
off = localStorage.getItem(storageKey) === "1";
|
||||
} catch {
|
||||
off = false;
|
||||
}
|
||||
}
|
||||
|
||||
export function isHapticsEnabled(): boolean {
|
||||
return !off;
|
||||
}
|
||||
|
||||
export function toggleHaptics(): boolean {
|
||||
off = !off;
|
||||
try {
|
||||
localStorage.setItem(storageKey, off ? "1" : "0");
|
||||
} catch {
|
||||
// session only
|
||||
}
|
||||
return !off;
|
||||
}
|
||||
|
||||
async function impact(style: ImpactStyle): Promise<void> {
|
||||
if (!Capacitor.isNativePlatform() || off) return;
|
||||
try {
|
||||
await Haptics.impact({ style });
|
||||
} catch {
|
||||
// unsupported device
|
||||
}
|
||||
}
|
||||
|
||||
let lastLight = 0;
|
||||
/** Frequent events - throttled so fast gameplay does not become constant buzzing. */
|
||||
export function hapticLight(throttleMs = 150): void {
|
||||
const now = performance.now();
|
||||
if (now - lastLight < throttleMs) return;
|
||||
lastLight = now;
|
||||
void impact(ImpactStyle.Light);
|
||||
}
|
||||
|
||||
export function hapticMedium(): void {
|
||||
void impact(ImpactStyle.Medium);
|
||||
}
|
||||
|
||||
export function hapticHeavy(): void {
|
||||
void impact(ImpactStyle.Heavy);
|
||||
}
|
||||
46
Library/mobile/kit/i18n.ts
Normal file
46
Library/mobile/kit/i18n.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
// Kit i18n (v1) - tiny translation helper. From _Tools\Library\mobile\kit.
|
||||
//
|
||||
// const en = { hello: "Hello {name}!", coins: "{n} coins" };
|
||||
// const de: Partial<typeof en> = { hello: "Hallo {name}!" }; // missing keys fall back to en
|
||||
// export const { t, lang, setLang, langs } = createI18n({ en, de }, "mygame_lang");
|
||||
// t("hello", { name: "Ana" })
|
||||
//
|
||||
// Language: saved choice, else the device language if available, else the first dictionary.
|
||||
// setLang() saves and reloads the page (all UI re-renders from scratch).
|
||||
|
||||
export function createI18n<D extends Record<string, string>>(
|
||||
dicts: { [lang: string]: Partial<D> } & { en: D },
|
||||
storageKey: string
|
||||
) {
|
||||
const langs = Object.keys(dicts);
|
||||
const pick = (): string => {
|
||||
try {
|
||||
const saved = localStorage.getItem(storageKey);
|
||||
if (saved && langs.includes(saved)) return saved;
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
const device = (navigator.language || "en").slice(0, 2).toLowerCase();
|
||||
return langs.includes(device) ? device : langs[0];
|
||||
};
|
||||
const lang = pick();
|
||||
const dict = dicts[lang] as Partial<D>;
|
||||
|
||||
function t(key: keyof D & string, vars?: Record<string, string | number>): string {
|
||||
let s = (dict[key] ?? dicts.en[key] ?? key) as string;
|
||||
if (vars) for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v));
|
||||
return s;
|
||||
}
|
||||
|
||||
function setLang(l: string): void {
|
||||
if (!langs.includes(l)) return;
|
||||
try {
|
||||
localStorage.setItem(storageKey, l);
|
||||
} catch {
|
||||
// session only
|
||||
}
|
||||
location.reload();
|
||||
}
|
||||
|
||||
return { t, lang, setLang, langs };
|
||||
}
|
||||
99
Library/mobile/kit/iap.ts
Normal file
99
Library/mobile/kit/iap.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
// Kit IAP (v1) - Google Play one-off purchases via cordova-plugin-purchase (CdvPurchase v13).
|
||||
// From _Tools\Library\mobile\kit (XP-Battleship/src/iap.ts). Native only; on web every call
|
||||
// resolves to "not bought".
|
||||
//
|
||||
// configureIap({ nonConsumable: ["premium_ship_1", "remove_ads"] });
|
||||
// const owned = await restorePurchases(); // every app start
|
||||
// const r = await purchase("remove_ads"); // "owned" | "failed" | "pending"
|
||||
// productPrice("remove_ads") ?? "2,99 €" // Play's localized price, or your fallback
|
||||
//
|
||||
// SKUs must exist as ACTIVE in-app products in the Play Console. Purchases only work in builds
|
||||
// installed from Play (internal test track and up) - sideloaded debug builds get an empty store.
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
type Cdv = any; // runtime global from the plugin
|
||||
|
||||
let skus: string[] = [];
|
||||
export function configureIap(c: { nonConsumable: string[] }): void {
|
||||
skus = c.nonConsumable;
|
||||
}
|
||||
|
||||
function cdv(): Cdv | null {
|
||||
return (window as unknown as Record<string, unknown>).CdvPurchase ?? null;
|
||||
}
|
||||
|
||||
let initPromise: Promise<boolean> | null = null;
|
||||
|
||||
function ensureStore(): Promise<boolean> {
|
||||
if (!Capacitor.isNativePlatform() || !cdv() || !skus.length) return Promise.resolve(false);
|
||||
if (!initPromise) {
|
||||
initPromise = (async (): Promise<boolean> => {
|
||||
const { store, ProductType, Platform } = cdv();
|
||||
store.register(skus.map((id) => ({ id, type: ProductType.NON_CONSUMABLE, platform: Platform.GOOGLE_PLAY })));
|
||||
store.when().approved((tx: Cdv) => tx.finish()); // Play already guarantees payment
|
||||
store.error(() => { initPromise = null; }); // billing disconnect: re-register next call
|
||||
await store.initialize([Platform.GOOGLE_PLAY]);
|
||||
return true;
|
||||
})().catch(() => {
|
||||
// never cache a failure: one offline launch must not disable buying for the session
|
||||
initPromise = null;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
return initPromise;
|
||||
}
|
||||
|
||||
/** `pending` = Play accepted the order but ownership has not arrived yet. Do NOT report it as
|
||||
* a failure - that is how paying customers get told "not completed" and ask for refunds. */
|
||||
export type PurchaseResult = "owned" | "failed" | "pending";
|
||||
|
||||
export async function purchase(sku: string): Promise<PurchaseResult> {
|
||||
if (!(await ensureStore())) return "failed";
|
||||
const { store, Platform } = cdv();
|
||||
try {
|
||||
const offer = store.get(sku, Platform.GOOGLE_PLAY)?.getOffer();
|
||||
if (!offer) return "failed";
|
||||
const err = await offer.order();
|
||||
if (err) return "failed"; // cancelled or declined
|
||||
const t0 = Date.now();
|
||||
while (Date.now() - t0 < 60_000) {
|
||||
if (store.get(sku, Platform.GOOGLE_PLAY)?.owned) return "owned";
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
}
|
||||
try {
|
||||
await store.restorePurchases();
|
||||
if (store.get(sku, Platform.GOOGLE_PLAY)?.owned) return "owned";
|
||||
} catch {
|
||||
// offline
|
||||
}
|
||||
return "pending";
|
||||
} catch {
|
||||
return "failed";
|
||||
}
|
||||
}
|
||||
|
||||
/** Play's localized price ("2,99 €", "$3.49"), or null while unknown. */
|
||||
export function productPrice(sku: string): string | null {
|
||||
if (!Capacitor.isNativePlatform() || !cdv()) return null;
|
||||
try {
|
||||
const { store, Platform } = cdv();
|
||||
const product = store.get(sku, Platform.GOOGLE_PLAY);
|
||||
return product?.getOffer()?.pricingPhases?.[0]?.price ?? product?.pricing?.price ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** SKUs the player owns (restore flow - run on every app start). */
|
||||
export async function restorePurchases(): Promise<string[]> {
|
||||
if (!(await ensureStore())) return [];
|
||||
const { store, Platform } = cdv();
|
||||
try {
|
||||
await store.restorePurchases();
|
||||
} catch {
|
||||
// offline - Play's local cache still answers below
|
||||
}
|
||||
return skus.filter((sku) => store.get(sku, Platform.GOOGLE_PLAY)?.owned);
|
||||
}
|
||||
53
Library/mobile/kit/lifecycle.ts
Normal file
53
Library/mobile/kit/lifecycle.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
// Kit lifecycle (v1) - Android back button and app pause/resume. From _Tools\Library\mobile\kit.
|
||||
// Needs @capacitor/app. On web: back = Escape key, pause/resume = visibilitychange.
|
||||
//
|
||||
// onBack(() => closeTopPanel() || confirmExit()); // return true when handled
|
||||
// onPause(() => { persist(); }); onResume(() => { ... });
|
||||
// exitApp();
|
||||
|
||||
import { Capacitor } from "@capacitor/core";
|
||||
import { App } from "@capacitor/app";
|
||||
|
||||
const backHandlers: Array<() => boolean> = [];
|
||||
|
||||
/** Handlers run newest first; the first that returns true stops the chain.
|
||||
* If none handles it, the app is minimised (Android convention) instead of closed. */
|
||||
export function onBack(fn: () => boolean): () => void {
|
||||
backHandlers.push(fn);
|
||||
return () => {
|
||||
const i = backHandlers.indexOf(fn);
|
||||
if (i >= 0) backHandlers.splice(i, 1);
|
||||
};
|
||||
}
|
||||
|
||||
function runBack(): void {
|
||||
for (let i = backHandlers.length - 1; i >= 0; i--) if (backHandlers[i]()) return;
|
||||
if (Capacitor.isNativePlatform()) void App.minimizeApp().catch(() => {});
|
||||
}
|
||||
|
||||
if (Capacitor.isNativePlatform()) {
|
||||
void App.addListener("backButton", runBack);
|
||||
} else {
|
||||
addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape") runBack();
|
||||
});
|
||||
}
|
||||
|
||||
/** App goes to background: SAVE HERE - Android may kill the process without another event. */
|
||||
export function onPause(fn: () => void): void {
|
||||
if (Capacitor.isNativePlatform()) void App.addListener("pause", fn);
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.hidden) fn();
|
||||
});
|
||||
}
|
||||
|
||||
export function onResume(fn: () => void): void {
|
||||
if (Capacitor.isNativePlatform()) void App.addListener("resume", fn);
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!document.hidden) fn();
|
||||
});
|
||||
}
|
||||
|
||||
export function exitApp(): void {
|
||||
if (Capacitor.isNativePlatform()) void App.exitApp();
|
||||
}
|
||||
112
Library/mobile/kit/save.ts
Normal file
112
Library/mobile/kit/save.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
// Kit save (v1) - versioned localStorage save with backup slot. From _Tools\Library\mobile\kit.
|
||||
// Generalised from XP-Battleship/src/game/save.ts (lessons: cloud/RTDB drops empty arrays,
|
||||
// NaN poisons everything, a truncated write must not wipe progress, failures must be visible).
|
||||
//
|
||||
// interface Save { v: number; coins: number; owned: string[]; stats: { runs: number } }
|
||||
// const saves = createSaveStore<Save>({
|
||||
// key: "mygame_save", version: 2,
|
||||
// defaults: () => ({ v: 2, coins: 0, owned: [], stats: { runs: 0 } }),
|
||||
// normalize: (s, d) => ({ ...s, coins: num(s.coins, d.coins), owned: arr(s.owned, d.owned),
|
||||
// stats: { ...d.stats, ...s.stats } }),
|
||||
// migrate: (s, from) => { if (from < 2) { /* repair */ } return s; },
|
||||
// });
|
||||
// const save = saves.load(); ... saves.persist(save); if (saves.failed()) showWarningOnce();
|
||||
|
||||
/** Coerce to an array. RTDB drops empty arrays and returns sparse ones as key-indexed objects. */
|
||||
export function arr<T>(v: unknown, fallback: T[]): T[] {
|
||||
if (Array.isArray(v)) return v as T[];
|
||||
if (v && typeof v === "object") return Object.values(v as Record<string, T>);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/** Number that must stay a finite number. */
|
||||
export function num(v: unknown, fallback: number): number {
|
||||
return typeof v === "number" && Number.isFinite(v) ? v : fallback;
|
||||
}
|
||||
|
||||
/** Shallow merge of a nested record over its defaults (stats, settings, ...). */
|
||||
export function rec<T extends object>(v: unknown, fallback: T): T {
|
||||
return { ...fallback, ...(v && typeof v === "object" && !Array.isArray(v) ? (v as Partial<T>) : {}) };
|
||||
}
|
||||
|
||||
export interface SaveStoreOptions<T extends { v: number }> {
|
||||
key: string;
|
||||
version: number;
|
||||
defaults: () => T;
|
||||
/** Fill a partial save (local OR cloud) out to a complete one. Default: shallow merge. */
|
||||
normalize?: (parsed: Partial<T>, defaults: T) => T;
|
||||
/** Repair saves from older versions; `from` is the stored version (1 if never stamped). */
|
||||
migrate?: (s: T, from: number) => T;
|
||||
/** Every Nth persist() also writes the backup slot. */
|
||||
backupEvery?: number;
|
||||
}
|
||||
|
||||
export interface SaveStore<T> {
|
||||
load(): T;
|
||||
persist(data: T): void;
|
||||
/** Normalize foreign data (cloud copy) the same way as a local load. */
|
||||
normalize(parsed: Partial<T>): T;
|
||||
clear(): void;
|
||||
failed(): boolean;
|
||||
}
|
||||
|
||||
export function createSaveStore<T extends { v: number }>(o: SaveStoreOptions<T>): SaveStore<T> {
|
||||
const backupKey = `${o.key}_bak`;
|
||||
const every = o.backupEvery ?? 12;
|
||||
let since = 0;
|
||||
let saveFailed = false;
|
||||
|
||||
function normalize(parsed: Partial<T>): T {
|
||||
const d = o.defaults();
|
||||
const from = num(parsed.v, 1);
|
||||
let s = o.normalize ? o.normalize(parsed, d) : ({ ...d, ...parsed } as T);
|
||||
if (from < o.version && o.migrate) s = o.migrate(s, from);
|
||||
s.v = o.version;
|
||||
return s;
|
||||
}
|
||||
|
||||
function readSlot(key: string): T | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(key);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
return normalize(parsed as Partial<T>);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
load: () => readSlot(o.key) ?? readSlot(backupKey) ?? o.defaults(),
|
||||
persist(data: T): void {
|
||||
try {
|
||||
const json = JSON.stringify(data);
|
||||
localStorage.setItem(o.key, json);
|
||||
if (++since >= every) {
|
||||
since = 0;
|
||||
localStorage.setItem(backupKey, json);
|
||||
}
|
||||
} catch {
|
||||
saveFailed = true; // quota / storage disabled - caller tells the player once
|
||||
}
|
||||
},
|
||||
normalize,
|
||||
clear(): void {
|
||||
try {
|
||||
localStorage.removeItem(o.key);
|
||||
localStorage.removeItem(backupKey); // a deletion that left the backup would resurrect it
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
},
|
||||
failed: () => saveFailed,
|
||||
};
|
||||
}
|
||||
|
||||
/** Offline earnings. Pass the timestamp captured at BOOT, not save.lastSeen read later -
|
||||
* autosave restamps lastSeen within seconds and the gain silently becomes zero. */
|
||||
export function offlineSeconds(since: number, capHours = 8): number {
|
||||
const elapsed = (Date.now() - num(since, Date.now())) / 1000;
|
||||
return Math.min(Math.max(elapsed, 0), capHours * 3600);
|
||||
}
|
||||
17
Library/mobile/template/.gitignore
vendored
Normal file
17
Library/mobile/template/.gitignore
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
node_modules/
|
||||
dist/
|
||||
sprite-generator/output/
|
||||
sprite-generator/__pycache__/
|
||||
*.log
|
||||
|
||||
# build artefacts
|
||||
*.aab
|
||||
*.apk
|
||||
android/app/build/
|
||||
android/build/
|
||||
android/.gradle/
|
||||
|
||||
# signing (never commit)
|
||||
android/keystore.properties
|
||||
*.jks
|
||||
*.keystore
|
||||
26
Library/mobile/template/CLAUDE.md
Normal file
26
Library/mobile/template/CLAUDE.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# {{NAME}}
|
||||
|
||||
Vite + TypeScript + Capacitor (Android), angelegt aus `D:\Oculusquest\Projekt\_Tools\Library` (Vorlage `mobile`).
|
||||
Aufbau und Befehle: `README.md`.
|
||||
|
||||
## Spielkonzept
|
||||
|
||||
<!-- KONZEPT: wird beim Anlegen (Skill neues-projekt) ausgefüllt, danach aktuell halten -->
|
||||
|
||||
## Arbeitsweise
|
||||
|
||||
- Antworten auf Deutsch, knapp. Code und Kommentare auf Englisch.
|
||||
- **Jeder sichtbare Text** steht in `src/lang.ts`, immer **Englisch und Deutsch**; im Code nur `t("key")`.
|
||||
- **Credits bleiben drin:** „© Jahr Michael Media“ + Discord-Link (`CREDITS` in `src/main.ts`) sichtbar,
|
||||
später z. B. im Einstellungs-/Info-Bildschirm; README ebenso.
|
||||
- `src/kit/` ist eine Kopie aus `_Tools\Library\mobile\kit`. Änderungen **dort** machen, dann
|
||||
`new-project.ps1 -UpdateKit -Path .`.
|
||||
- Vor jedem „fertig“: `npm run typecheck` muss sauber sein.
|
||||
- Alles Native (Werbung, Käufe, Vibration) ist im Browser eine Attrappe – Logik so bauen, dass `npm start` voll spielbar ist.
|
||||
- Spielstand: jedes neue Feld in `defaults()` UND in `normalize` absichern (`num`, `arr`); bei
|
||||
Formänderung `version` hoch + `migrate`.
|
||||
- Kleine Dateien mit sprechenden Namen (`src/game/*.ts`, `src/ui/*.ts`), kein `main.ts` mit 5000 Zeilen.
|
||||
- Grafik/Sound nur über `sprite-generator/` (ComfyGen, Katalog `_Tools\README.md`), Stilblock aus dem
|
||||
Spielkonzept. App-Icon: `gen adopt --size 1024 icon` → `public/assets/Sprites/icon.png`; Android-Icons siehe README.
|
||||
- Git nur lokal (kein Remote). Commit nur, wenn Michael es sagt.
|
||||
- Referenzprojekt mit allem (Cloud-Save, Bestenliste, Skilltree, Store-Screenshots): `D:\Oculusquest\Projekt\XP-Battleship`.
|
||||
55
Library/mobile/template/README.md
Normal file
55
Library/mobile/template/README.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# {{NAME}}
|
||||
|
||||
Mobile-Spiel/App: Vite + TypeScript, Android über Capacitor. Angelegt am {{DATE}} aus `_Tools\Library` (Vorlage `mobile`).
|
||||
Sprachen: Englisch, Deutsch (Gerätesprache, 🌐-Knopf schaltet um).
|
||||
|
||||
© {{YEAR}} Michael Media · Discord: https://discord.gg/Ej4JPmCZva
|
||||
|
||||
## Erste Schritte
|
||||
|
||||
```powershell
|
||||
npm install
|
||||
npm start # Browser, http://localhost:5173 (Werbung/Kauf/Vibration = Attrappen)
|
||||
npx cap add android # einmal: erzeugt android\
|
||||
npm run android # bauen, sync, Android Studio öffnen
|
||||
```
|
||||
|
||||
## App-Icon
|
||||
|
||||
1. `cd sprite-generator` → `gen generate icon` → `gen adopt --size 1024 icon` (→ `public/assets/Sprites/icon.png`, auch Browser-Favicon).
|
||||
2. Android: Datei als `assets\icon-only.png` (1024×1024) ablegen, dann
|
||||
`npx @capacitor/assets generate --android --iconBackgroundColor "#0b0f1a"` (erzeugt alle mipmap-Icons).
|
||||
|
||||
## Aufbau
|
||||
|
||||
```
|
||||
index.html, src/main.ts Einstieg
|
||||
src/lang.ts alle sichtbaren Texte, Englisch + Deutsch → t("key")
|
||||
src/kit/ Bausteine aus _Tools\Library\mobile\kit – hier NICHT ändern
|
||||
audio.ts Musik + SFX (WebAudio), Mute, Ducking
|
||||
save.ts Spielstand mit Version, Backup-Slot, arr()/num()-Reparatur
|
||||
haptics.ts Vibration (nur nativ)
|
||||
ads.ts AdMob Rewarded + UMP-Einwilligung (EU)
|
||||
iap.ts Play-Käufe (einmalig, nicht verbrauchbar)
|
||||
i18n.ts Übersetzungen t("key", {n})
|
||||
lifecycle.ts Zurück-Taste, Pause/Resume (beim Pausieren speichern!)
|
||||
public/assets/ Sprites/, Audio/ – von sprite-generator (ComfyGen adopt)
|
||||
sprite-generator/ gen generate <name>, gen adopt <name>, gen generate_audio <name>
|
||||
```
|
||||
|
||||
## Vor dem Play-Store-Release
|
||||
|
||||
- `configureAds({ testing: false, ... })` mit echten Anzeigenblock-IDs; AdMob-App-ID in
|
||||
`android/app/src/main/AndroidManifest.xml` (`com.google.android.gms.ads.APPLICATION_ID`).
|
||||
- In der AdMob-Konsole DSGVO-Nachricht **und** Datenschutzoptionen veröffentlichen (sonst bleibt UMP stumm),
|
||||
Knopf „Werbe-Einstellungen“ zeigen, wenn `needsPrivacyOptions()`.
|
||||
- IAP-Produkte in der Play Console aktiv; Käufe nur in Builds aus Play (interner Test reicht).
|
||||
- `versionCode`/`versionName` in `android/app/build.gradle` + `version` in `package.json` erhöhen.
|
||||
- Signier-Schlüssel (`*.jks`, `keystore.properties`) nie committen – siehe `.gitignore`.
|
||||
|
||||
Ausführliche Checkliste aus der Praxis: `D:\Oculusquest\Projekt\XP-Battleship\RELEASE-CHECKLIST.md`.
|
||||
|
||||
## Kit aktualisieren
|
||||
|
||||
Verbesserungen an `src/kit/*` gehören nach `D:\Oculusquest\Projekt\_Tools\Library\mobile\kit`, dann:
|
||||
`D:\Oculusquest\Projekt\_Tools\Library\new-project.ps1 -UpdateKit -Path .`
|
||||
12
Library/mobile/template/capacitor.config.json
Normal file
12
Library/mobile/template/capacitor.config.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"appId": "com.michaelmedia.{{SLUG}}",
|
||||
"appName": "{{NAME}}",
|
||||
"webDir": "dist",
|
||||
"server": {
|
||||
"androidScheme": "https"
|
||||
},
|
||||
"android": {
|
||||
"captureInput": true,
|
||||
"webContentsDebuggingEnabled": false
|
||||
}
|
||||
}
|
||||
26
Library/mobile/template/index.html
Normal file
26
Library/mobile/template/index.html
Normal file
@@ -0,0 +1,26 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#0b0f1a" />
|
||||
<link rel="icon" href="/assets/Sprites/icon.png" />
|
||||
<title>{{NAME}}</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
<header id="hud">
|
||||
<span><span id="lCoins">Coins</span> <b id="coins">0</b></span>
|
||||
<span class="grow"></span>
|
||||
<button id="bLang" type="button">🌐</button>
|
||||
<button id="bMute" type="button">Sound</button>
|
||||
</header>
|
||||
<canvas id="cv"></canvas>
|
||||
<footer>
|
||||
<button id="bAd" type="button">2x coins (ad)</button>
|
||||
</footer>
|
||||
<p class="credits" id="credits"></p>
|
||||
</div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
27
Library/mobile/template/package.json
Normal file
27
Library/mobile/template/package.json
Normal file
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "{{SLUG}}",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "vite",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview --port 5174",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"android": "npm run build && npx cap sync android && npx cap open android",
|
||||
"cap:sync": "npm run build && npx cap sync"
|
||||
},
|
||||
"dependencies": {
|
||||
"@capacitor-community/admob": "^8.0.0",
|
||||
"@capacitor/android": "^8.3.0",
|
||||
"@capacitor/app": "^8.1.1",
|
||||
"@capacitor/cli": "^8.3.0",
|
||||
"@capacitor/core": "^8.3.0",
|
||||
"@capacitor/haptics": "^8.0.2",
|
||||
"cordova-plugin-purchase": "^13.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.5.0",
|
||||
"vite": "^5.4.0"
|
||||
}
|
||||
}
|
||||
26
Library/mobile/template/src/lang.ts
Normal file
26
Library/mobile/template/src/lang.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
// {{NAME}} - all visible texts, English + German (kit/i18n.ts). A new text always gets BOTH
|
||||
// languages; German may leave a key out only by mistake (it then falls back to English).
|
||||
import { createI18n } from "./kit/i18n";
|
||||
|
||||
const en = {
|
||||
lang_self: "English",
|
||||
coins: "Coins",
|
||||
sound_on: "Sound on",
|
||||
sound_off: "Sound off",
|
||||
double_ad: "2x coins (ad)",
|
||||
};
|
||||
|
||||
const de: Partial<typeof en> = {
|
||||
lang_self: "Deutsch",
|
||||
coins: "Münzen",
|
||||
sound_on: "Sound an",
|
||||
sound_off: "Sound aus",
|
||||
double_ad: "2x Münzen (Werbung)",
|
||||
};
|
||||
|
||||
export const { t, lang, setLang, langs } = createI18n({ en, de }, "{{SLUG}}_lang");
|
||||
|
||||
/** Next language (one button cycles through all); reloads the page. */
|
||||
export function nextLang(): void {
|
||||
setLang(langs[(langs.indexOf(lang) + 1) % langs.length]);
|
||||
}
|
||||
100
Library/mobile/template/src/main.ts
Normal file
100
Library/mobile/template/src/main.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
// {{NAME}} - entry. Demo from the Library template: tap the orb for coins, watch an ad to
|
||||
// double them. Replace the demo; keep the wiring (save, audio, haptics, ads, lifecycle,
|
||||
// texts via t() from lang.ts, credits line).
|
||||
import "./style.css";
|
||||
import { configureAudio, initAudio, playMusic, playSfx, toggleMute, isMuted } from "./kit/audio";
|
||||
import { createSaveStore, num } from "./kit/save";
|
||||
import { configureHaptics, hapticLight } from "./kit/haptics";
|
||||
import { configureAds, initAds, showRewarded } from "./kit/ads";
|
||||
import { onBack, onPause } from "./kit/lifecycle";
|
||||
import { t, lang, nextLang } from "./lang";
|
||||
|
||||
const ID = "{{SLUG}}";
|
||||
// Credits (standard for every app); external links open in the system browser
|
||||
const DISCORD = "https://discord.gg/Ej4JPmCZva";
|
||||
const CREDITS = `© {{YEAR}} Michael Media · <a href="${DISCORD}" target="_blank" rel="noopener">Discord</a>`;
|
||||
|
||||
// ---- save -------------------------------------------------------------------------------
|
||||
interface Save {
|
||||
v: number;
|
||||
coins: number;
|
||||
taps: number;
|
||||
}
|
||||
const saves = createSaveStore<Save>({
|
||||
key: `${ID}_save`,
|
||||
version: 1,
|
||||
defaults: () => ({ v: 1, coins: 0, taps: 0 }),
|
||||
normalize: (s, d) => ({ ...d, ...s, coins: num(s.coins, d.coins), taps: num(s.taps, d.taps) }),
|
||||
});
|
||||
const save = saves.load();
|
||||
setInterval(() => saves.persist(save), 5000);
|
||||
onPause(() => saves.persist(save));
|
||||
|
||||
// ---- services ---------------------------------------------------------------------------
|
||||
configureAudio({ base: "/assets/Audio/", storageKey: ID, preload: ["sfx_tap", "music_game"], throttle: { sfx_tap: 50 } });
|
||||
configureHaptics(ID);
|
||||
// Ad unit ids from the AdMob console; testing:true uses Google's test unit (set false for release)
|
||||
configureAds({ testing: true, rewarded: { double: "" } });
|
||||
void initAds();
|
||||
|
||||
// ---- view -------------------------------------------------------------------------------
|
||||
const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
|
||||
const cv = $<HTMLCanvasElement>("cv");
|
||||
const ctx = cv.getContext("2d")!;
|
||||
let W = 0, H = 0;
|
||||
function fit(): void {
|
||||
const r = cv.getBoundingClientRect(), k = devicePixelRatio || 1;
|
||||
W = r.width; H = r.height;
|
||||
cv.width = Math.round(W * k); cv.height = Math.round(H * k);
|
||||
ctx.setTransform(k, 0, 0, k, 0, 0);
|
||||
}
|
||||
addEventListener("resize", fit);
|
||||
fit();
|
||||
|
||||
let pulse = 0;
|
||||
cv.addEventListener("pointerdown", (e) => {
|
||||
initAudio();
|
||||
playMusic("music_game");
|
||||
const r = cv.getBoundingClientRect();
|
||||
const x = e.clientX - r.left, y = e.clientY - r.top;
|
||||
if (Math.hypot(x - W / 2, y - H / 2) < Math.min(W, H) * 0.22) {
|
||||
save.coins += 1; save.taps += 1; pulse = 1;
|
||||
playSfx("sfx_tap"); hapticLight();
|
||||
hud();
|
||||
}
|
||||
});
|
||||
|
||||
$("bAd").onclick = async () => {
|
||||
initAudio();
|
||||
if (await showRewarded("double")) { save.coins *= 2; saves.persist(save); hud(); }
|
||||
};
|
||||
$("bMute").onclick = () => { initAudio(); toggleMute(); hud(); };
|
||||
$("bLang").onclick = nextLang;
|
||||
onBack(() => false); // nothing to close -> app minimises
|
||||
|
||||
// static texts (language is fixed per page load - nextLang() reloads)
|
||||
document.documentElement.lang = lang;
|
||||
$("lCoins").textContent = t("coins");
|
||||
$("bAd").textContent = t("double_ad");
|
||||
$("bLang").textContent = `🌐 ${t("lang_self")}`;
|
||||
$("credits").innerHTML = CREDITS;
|
||||
|
||||
function hud(): void {
|
||||
$("coins").textContent = String(save.coins);
|
||||
$("bMute").textContent = isMuted() ? t("sound_off") : t("sound_on");
|
||||
}
|
||||
|
||||
function frame(): void {
|
||||
pulse *= 0.9;
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
const r = Math.min(W, H) * 0.2 * (1 + pulse * 0.12);
|
||||
const g = ctx.createRadialGradient(W / 2, H / 2, r * 0.1, W / 2, H / 2, r);
|
||||
g.addColorStop(0, "#bff3ff"); g.addColorStop(1, "#1a6d9a");
|
||||
ctx.fillStyle = g;
|
||||
ctx.beginPath(); ctx.arc(W / 2, H / 2, r, 0, Math.PI * 2); ctx.fill();
|
||||
ctx.fillStyle = "#8b97bd"; ctx.font = "12px system-ui"; ctx.textAlign = "center";
|
||||
ctx.fillText(`v${__APP_VERSION__}`, W / 2, H - 10);
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
hud();
|
||||
frame();
|
||||
20
Library/mobile/template/src/style.css
Normal file
20
Library/mobile/template/src/style.css
Normal file
@@ -0,0 +1,20 @@
|
||||
:root {
|
||||
--bg: #0b0f1a; --panel: #141b2d; --line: #2a3658; --text: #e3e9ff; --accent: #4fd8ff;
|
||||
/* safe areas (notch, gesture bar) */
|
||||
--sat: env(safe-area-inset-top); --sab: env(safe-area-inset-bottom);
|
||||
}
|
||||
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
||||
html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--text);
|
||||
font: 16px/1.4 system-ui, sans-serif; user-select: none; -webkit-user-select: none; touch-action: manipulation; }
|
||||
#app { display: flex; flex-direction: column; height: 100%; padding: calc(8px + var(--sat)) 12px calc(8px + var(--sab)); gap: 8px; }
|
||||
#hud, footer { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
|
||||
#hud b { color: var(--accent); font-variant-numeric: tabular-nums; }
|
||||
canvas { flex: 1; width: 100%; min-height: 0; border-radius: 12px; background: #050913; display: block; }
|
||||
button { font: inherit; color: var(--text); background: var(--panel); border: 1px solid var(--line);
|
||||
border-radius: 10px; padding: 10px 16px; }
|
||||
button:active { transform: scale(.97); }
|
||||
footer button { flex: 1; }
|
||||
.grow { flex: 1; }
|
||||
/* credits (standard for every app: © year Michael Media + Discord) */
|
||||
.credits { margin: 0; text-align: center; font-size: 12px; color: #8b97bd; }
|
||||
.credits a { color: var(--accent); text-decoration: none; }
|
||||
2
Library/mobile/template/src/vite-env.d.ts
vendored
Normal file
2
Library/mobile/template/src/vite-env.d.ts
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/// <reference types="vite/client" />
|
||||
declare const __APP_VERSION__: string;
|
||||
15
Library/mobile/template/tsconfig.json
Normal file
15
Library/mobile/template/tsconfig.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noEmit": true,
|
||||
"isolatedModules": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
11
Library/mobile/template/vite.config.ts
Normal file
11
Library/mobile/template/vite.config.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
// The version shown in-game comes from package.json. Keep versionName in
|
||||
// android/app/build.gradle in step - a bug report is only useful if it names a build.
|
||||
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) as { version: string };
|
||||
|
||||
export default defineConfig({
|
||||
define: { __APP_VERSION__: JSON.stringify(pkg.version) },
|
||||
build: { target: "es2020" },
|
||||
});
|
||||
Reference in New Issue
Block a user