This commit is contained in:
Renan LE CARO 2025-03-13 14:14:00 +01:00
parent d848ad511e
commit 78c8e154c6
17 changed files with 372 additions and 1521 deletions

459
dist/index.497c99a1.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

209
dist/index.c0fd3053.js vendored Normal file

File diff suppressed because one or more lines are too long

1
dist/index.c0fd3053.js.map vendored Normal file

File diff suppressed because one or more lines are too long

509
dist/index.html vendored
View file

@ -1,6 +1,6 @@
<!doctype html> <!doctype html>
<html lang="en"> <html lang="en">
<head><script src="/index.497c99a1.js"></script> <head><script src="/index.c0fd3053.js"></script>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta http-equiv="X-UA-Compatible" content="ie=edge">
@ -468,463 +468,10 @@ h2.histogram-title strong {
this[globalName] = mainExports; this[globalName] = mainExports;
} }
} }
})({"hhTAC":[function(require,module,exports,__globalThis) { })({"eBxNa":[function(require,module,exports,__globalThis) {
var global = arguments[3]; require("f4e3916d5ea9aa97")(require("c38567b56f7e0944").getBundleURL('gcK2a') + "index.c0fd3053.js");
var HMR_HOST = null;
var HMR_PORT = null;
var HMR_SECURE = false;
var HMR_ENV_HASH = "d6ea1d42532a7575";
var HMR_USE_SSE = false;
module.bundle.HMR_BUNDLE_ID = "bcc179bbafd39a7c";
"use strict";
/* global HMR_HOST, HMR_PORT, HMR_ENV_HASH, HMR_SECURE, HMR_USE_SSE, chrome, browser, __parcel__import__, __parcel__importScripts__, ServiceWorkerGlobalScope */ /*::
import type {
HMRAsset,
HMRMessage,
} from '@parcel/reporter-dev-server/src/HMRServer.js';
interface ParcelRequire {
(string): mixed;
cache: {|[string]: ParcelModule|};
hotData: {|[string]: mixed|};
Module: any;
parent: ?ParcelRequire;
isParcelRequire: true;
modules: {|[string]: [Function, {|[string]: string|}]|};
HMR_BUNDLE_ID: string;
root: ParcelRequire;
}
interface ParcelModule {
hot: {|
data: mixed,
accept(cb: (Function) => void): void,
dispose(cb: (mixed) => void): void,
// accept(deps: Array<string> | string, cb: (Function) => void): void,
// decline(): void,
_acceptCallbacks: Array<(Function) => void>,
_disposeCallbacks: Array<(mixed) => void>,
|};
}
interface ExtensionContext {
runtime: {|
reload(): void,
getURL(url: string): string;
getManifest(): {manifest_version: number, ...};
|};
}
declare var module: {bundle: ParcelRequire, ...};
declare var HMR_HOST: string;
declare var HMR_PORT: string;
declare var HMR_ENV_HASH: string;
declare var HMR_SECURE: boolean;
declare var HMR_USE_SSE: boolean;
declare var chrome: ExtensionContext;
declare var browser: ExtensionContext;
declare var __parcel__import__: (string) => Promise<void>;
declare var __parcel__importScripts__: (string) => Promise<void>;
declare var globalThis: typeof self;
declare var ServiceWorkerGlobalScope: Object;
*/ var OVERLAY_ID = '__parcel__error__overlay__';
var OldModule = module.bundle.Module;
function Module(moduleName) {
OldModule.call(this, moduleName);
this.hot = {
data: module.bundle.hotData[moduleName],
_acceptCallbacks: [],
_disposeCallbacks: [],
accept: function(fn) {
this._acceptCallbacks.push(fn || function() {});
},
dispose: function(fn) {
this._disposeCallbacks.push(fn);
}
};
module.bundle.hotData[moduleName] = undefined;
}
module.bundle.Module = Module;
module.bundle.hotData = {};
var checkedAssets /*: {|[string]: boolean|} */ , disposedAssets /*: {|[string]: boolean|} */ , assetsToDispose /*: Array<[ParcelRequire, string]> */ , assetsToAccept /*: Array<[ParcelRequire, string]> */ ;
function getHostname() {
return HMR_HOST || (location.protocol.indexOf('http') === 0 ? location.hostname : 'localhost');
}
function getPort() {
return HMR_PORT || location.port;
}
// eslint-disable-next-line no-redeclare
var parent = module.bundle.parent;
if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
var hostname = getHostname();
var port = getPort();
var protocol = HMR_SECURE || location.protocol == 'https:' && ![
'localhost',
'127.0.0.1',
'0.0.0.0'
].includes(hostname) ? 'wss' : 'ws';
var ws;
if (HMR_USE_SSE) ws = new EventSource('/__parcel_hmr');
else try {
ws = new WebSocket(protocol + '://' + hostname + (port ? ':' + port : '') + '/');
} catch (err) {
if (err.message) console.error(err.message);
ws = {};
}
// Web extension context
var extCtx = typeof browser === 'undefined' ? typeof chrome === 'undefined' ? null : chrome : browser;
// Safari doesn't support sourceURL in error stacks.
// eval may also be disabled via CSP, so do a quick check.
var supportsSourceURL = false;
try {
(0, eval)('throw new Error("test"); //# sourceURL=test.js');
} catch (err) {
supportsSourceURL = err.stack.includes('test.js');
}
// $FlowFixMe
ws.onmessage = async function(event /*: {data: string, ...} */ ) {
checkedAssets = {} /*: {|[string]: boolean|} */ ;
disposedAssets = {} /*: {|[string]: boolean|} */ ;
assetsToAccept = [];
assetsToDispose = [];
var data /*: HMRMessage */ = JSON.parse(event.data);
if (data.type === 'reload') fullReload();
else if (data.type === 'update') {
// Remove error overlay if there is one
if (typeof document !== 'undefined') removeErrorOverlay();
let assets = data.assets.filter((asset)=>asset.envHash === HMR_ENV_HASH);
// Handle HMR Update
let handled = assets.every((asset)=>{
return asset.type === 'css' || asset.type === 'js' && hmrAcceptCheck(module.bundle.root, asset.id, asset.depsByBundle);
});
if (handled) {
console.clear();
// Dispatch custom event so other runtimes (e.g React Refresh) are aware.
if (typeof window !== 'undefined' && typeof CustomEvent !== 'undefined') window.dispatchEvent(new CustomEvent('parcelhmraccept'));
await hmrApplyUpdates(assets);
hmrDisposeQueue();
// Run accept callbacks. This will also re-execute other disposed assets in topological order.
let processedAssets = {};
for(let i = 0; i < assetsToAccept.length; i++){
let id = assetsToAccept[i][1];
if (!processedAssets[id]) {
hmrAccept(assetsToAccept[i][0], id);
processedAssets[id] = true;
}
}
} else fullReload();
}
if (data.type === 'error') {
// Log parcel errors to console
for (let ansiDiagnostic of data.diagnostics.ansi){
let stack = ansiDiagnostic.codeframe ? ansiDiagnostic.codeframe : ansiDiagnostic.stack;
console.error("\uD83D\uDEA8 [parcel]: " + ansiDiagnostic.message + '\n' + stack + '\n\n' + ansiDiagnostic.hints.join('\n'));
}
if (typeof document !== 'undefined') {
// Render the fancy html overlay
removeErrorOverlay();
var overlay = createErrorOverlay(data.diagnostics.html);
// $FlowFixMe
document.body.appendChild(overlay);
}
}
};
if (ws instanceof WebSocket) {
ws.onerror = function(e) {
if (e.message) console.error(e.message);
};
ws.onclose = function() {
console.warn("[parcel] \uD83D\uDEA8 Connection to the HMR server was lost");
};
}
}
function removeErrorOverlay() {
var overlay = document.getElementById(OVERLAY_ID);
if (overlay) {
overlay.remove();
console.log("[parcel] \u2728 Error resolved");
}
}
function createErrorOverlay(diagnostics) {
var overlay = document.createElement('div');
overlay.id = OVERLAY_ID;
let errorHTML = '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; font-family: Menlo, Consolas, monospace; z-index: 9999;">';
for (let diagnostic of diagnostics){
let stack = diagnostic.frames.length ? diagnostic.frames.reduce((p, frame)=>{
return `${p}
<a href="/__parcel_launch_editor?file=${encodeURIComponent(frame.location)}" style="text-decoration: underline; color: #888" onclick="fetch(this.href); return false">${frame.location}</a>
${frame.code}`;
}, '') : diagnostic.stack;
errorHTML += `
<div>
<div style="font-size: 18px; font-weight: bold; margin-top: 20px;">
\u{1F6A8} ${diagnostic.message}
</div>
<pre>${stack}</pre>
<div>
${diagnostic.hints.map((hint)=>"<div>\uD83D\uDCA1 " + hint + '</div>').join('')}
</div>
${diagnostic.documentation ? `<div>\u{1F4DD} <a style="color: violet" href="${diagnostic.documentation}" target="_blank">Learn more</a></div>` : ''}
</div>
`;
}
errorHTML += '</div>';
overlay.innerHTML = errorHTML;
return overlay;
}
function fullReload() {
if ('reload' in location) location.reload();
else if (extCtx && extCtx.runtime && extCtx.runtime.reload) extCtx.runtime.reload();
}
function getParents(bundle, id) /*: Array<[ParcelRequire, string]> */ {
var modules = bundle.modules;
if (!modules) return [];
var parents = [];
var k, d, dep;
for(k in modules)for(d in modules[k][1]){
dep = modules[k][1][d];
if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) parents.push([
bundle,
k
]);
}
if (bundle.parent) parents = parents.concat(getParents(bundle.parent, id));
return parents;
}
function updateLink(link) {
var href = link.getAttribute('href');
if (!href) return;
var newLink = link.cloneNode();
newLink.onload = function() {
if (link.parentNode !== null) // $FlowFixMe
link.parentNode.removeChild(link);
};
newLink.setAttribute('href', // $FlowFixMe
href.split('?')[0] + '?' + Date.now());
// $FlowFixMe
link.parentNode.insertBefore(newLink, link.nextSibling);
}
var cssTimeout = null;
function reloadCSS() {
if (cssTimeout) return;
cssTimeout = setTimeout(function() {
var links = document.querySelectorAll('link[rel="stylesheet"]');
for(var i = 0; i < links.length; i++){
// $FlowFixMe[incompatible-type]
var href /*: string */ = links[i].getAttribute('href');
var hostname = getHostname();
var servedFromHMRServer = hostname === 'localhost' ? new RegExp('^(https?:\\/\\/(0.0.0.0|127.0.0.1)|localhost):' + getPort()).test(href) : href.indexOf(hostname + ':' + getPort());
var absolute = /^https?:\/\//i.test(href) && href.indexOf(location.origin) !== 0 && !servedFromHMRServer;
if (!absolute) updateLink(links[i]);
}
cssTimeout = null;
}, 50);
}
function hmrDownload(asset) {
if (asset.type === 'js') {
if (typeof document !== 'undefined') {
let script = document.createElement('script');
script.src = asset.url + '?t=' + Date.now();
if (asset.outputFormat === 'esmodule') script.type = 'module';
return new Promise((resolve, reject)=>{
var _document$head;
script.onload = ()=>resolve(script);
script.onerror = reject;
(_document$head = document.head) === null || _document$head === void 0 || _document$head.appendChild(script);
});
} else if (typeof importScripts === 'function') {
// Worker scripts
if (asset.outputFormat === 'esmodule') return import(asset.url + '?t=' + Date.now());
else return new Promise((resolve, reject)=>{
try {
importScripts(asset.url + '?t=' + Date.now());
resolve();
} catch (err) {
reject(err);
}
});
}
}
}
async function hmrApplyUpdates(assets) {
global.parcelHotUpdate = Object.create(null);
let scriptsToRemove;
try {
// If sourceURL comments aren't supported in eval, we need to load
// the update from the dev server over HTTP so that stack traces
// are correct in errors/logs. This is much slower than eval, so
// we only do it if needed (currently just Safari).
// https://bugs.webkit.org/show_bug.cgi?id=137297
// This path is also taken if a CSP disallows eval.
if (!supportsSourceURL) {
let promises = assets.map((asset)=>{
var _hmrDownload;
return (_hmrDownload = hmrDownload(asset)) === null || _hmrDownload === void 0 ? void 0 : _hmrDownload.catch((err)=>{
// Web extension fix
if (extCtx && extCtx.runtime && extCtx.runtime.getManifest().manifest_version == 3 && typeof ServiceWorkerGlobalScope != 'undefined' && global instanceof ServiceWorkerGlobalScope) {
extCtx.runtime.reload();
return;
}
throw err;
});
});
scriptsToRemove = await Promise.all(promises);
}
assets.forEach(function(asset) {
hmrApply(module.bundle.root, asset);
});
} finally{
delete global.parcelHotUpdate;
if (scriptsToRemove) scriptsToRemove.forEach((script)=>{
if (script) {
var _document$head2;
(_document$head2 = document.head) === null || _document$head2 === void 0 || _document$head2.removeChild(script);
}
});
}
}
function hmrApply(bundle /*: ParcelRequire */ , asset /*: HMRAsset */ ) {
var modules = bundle.modules;
if (!modules) return;
if (asset.type === 'css') reloadCSS();
else if (asset.type === 'js') {
let deps = asset.depsByBundle[bundle.HMR_BUNDLE_ID];
if (deps) {
if (modules[asset.id]) {
// Remove dependencies that are removed and will become orphaned.
// This is necessary so that if the asset is added back again, the cache is gone, and we prevent a full page reload.
let oldDeps = modules[asset.id][1];
for(let dep in oldDeps)if (!deps[dep] || deps[dep] !== oldDeps[dep]) {
let id = oldDeps[dep];
let parents = getParents(module.bundle.root, id);
if (parents.length === 1) hmrDelete(module.bundle.root, id);
}
}
if (supportsSourceURL) // Global eval. We would use `new Function` here but browser
// support for source maps is better with eval.
(0, eval)(asset.output);
// $FlowFixMe
let fn = global.parcelHotUpdate[asset.id];
modules[asset.id] = [
fn,
deps
];
}
// Always traverse to the parent bundle, even if we already replaced the asset in this bundle.
// This is required in case modules are duplicated. We need to ensure all instances have the updated code.
if (bundle.parent) hmrApply(bundle.parent, asset);
}
}
function hmrDelete(bundle, id) {
let modules = bundle.modules;
if (!modules) return;
if (modules[id]) {
// Collect dependencies that will become orphaned when this module is deleted.
let deps = modules[id][1];
let orphans = [];
for(let dep in deps){
let parents = getParents(module.bundle.root, deps[dep]);
if (parents.length === 1) orphans.push(deps[dep]);
}
// Delete the module. This must be done before deleting dependencies in case of circular dependencies.
delete modules[id];
delete bundle.cache[id];
// Now delete the orphans.
orphans.forEach((id)=>{
hmrDelete(module.bundle.root, id);
});
} else if (bundle.parent) hmrDelete(bundle.parent, id);
}
function hmrAcceptCheck(bundle /*: ParcelRequire */ , id /*: string */ , depsByBundle /*: ?{ [string]: { [string]: string } }*/ ) {
if (hmrAcceptCheckOne(bundle, id, depsByBundle)) return true;
// Traverse parents breadth first. All possible ancestries must accept the HMR update, or we'll reload.
let parents = getParents(module.bundle.root, id);
let accepted = false;
while(parents.length > 0){
let v = parents.shift();
let a = hmrAcceptCheckOne(v[0], v[1], null);
if (a) // If this parent accepts, stop traversing upward, but still consider siblings.
accepted = true;
else {
// Otherwise, queue the parents in the next level upward.
let p = getParents(module.bundle.root, v[1]);
if (p.length === 0) {
// If there are no parents, then we've reached an entry without accepting. Reload.
accepted = false;
break;
}
parents.push(...p);
}
}
return accepted;
}
function hmrAcceptCheckOne(bundle /*: ParcelRequire */ , id /*: string */ , depsByBundle /*: ?{ [string]: { [string]: string } }*/ ) {
var modules = bundle.modules;
if (!modules) return;
if (depsByBundle && !depsByBundle[bundle.HMR_BUNDLE_ID]) {
// If we reached the root bundle without finding where the asset should go,
// there's nothing to do. Mark as "accepted" so we don't reload the page.
if (!bundle.parent) return true;
return hmrAcceptCheck(bundle.parent, id, depsByBundle);
}
if (checkedAssets[id]) return true;
checkedAssets[id] = true;
var cached = bundle.cache[id];
assetsToDispose.push([
bundle,
id
]);
if (!cached || cached.hot && cached.hot._acceptCallbacks.length) {
assetsToAccept.push([
bundle,
id
]);
return true;
}
}
function hmrDisposeQueue() {
// Dispose all old assets.
for(let i = 0; i < assetsToDispose.length; i++){
let id = assetsToDispose[i][1];
if (!disposedAssets[id]) {
hmrDispose(assetsToDispose[i][0], id);
disposedAssets[id] = true;
}
}
assetsToDispose = [];
}
function hmrDispose(bundle /*: ParcelRequire */ , id /*: string */ ) {
var cached = bundle.cache[id];
bundle.hotData[id] = {};
if (cached && cached.hot) cached.hot.data = bundle.hotData[id];
if (cached && cached.hot && cached.hot._disposeCallbacks.length) cached.hot._disposeCallbacks.forEach(function(cb) {
cb(bundle.hotData[id]);
});
delete bundle.cache[id];
}
function hmrAccept(bundle /*: ParcelRequire */ , id /*: string */ ) {
// Execute the module.
bundle(id);
// Run the accept callbacks in the new version of the module.
var cached = bundle.cache[id];
if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
let assetsToAlsoAccept = [];
cached.hot._acceptCallbacks.forEach(function(cb) {
let additionalAssets = cb(function() {
return getParents(module.bundle.root, id);
});
if (Array.isArray(additionalAssets) && additionalAssets.length) assetsToAlsoAccept.push(...additionalAssets);
});
if (assetsToAlsoAccept.length) {
let handled = assetsToAlsoAccept.every(function(a) {
return hmrAcceptCheck(a[0], a[1]);
});
if (!handled) return fullReload();
hmrDisposeQueue();
}
}
}
},{}],"3UXKE":[function(require,module,exports,__globalThis) { },{"f4e3916d5ea9aa97":"61B45","c38567b56f7e0944":"lgJ39"}],"61B45":[function(require,module,exports,__globalThis) {
require("24fcd25505014b08")(require("6fd669fa965b6506").getBundleURL('gcK2a') + "index.497c99a1.js");
},{"24fcd25505014b08":"61B45","6fd669fa965b6506":"lgJ39"}],"61B45":[function(require,module,exports,__globalThis) {
"use strict"; "use strict";
var cacheLoader = require("ca2a84f7fa4a3bb0"); var cacheLoader = require("ca2a84f7fa4a3bb0");
module.exports = cacheLoader(function(bundle) { module.exports = cacheLoader(function(bundle) {
@ -1114,7 +661,8 @@ let running = false, puck = 400, pauseTimeout = null;
function play() { function play() {
if (running) return; if (running) return;
running = true; running = true;
(0, _sounds.getAudioContext)()?.resume().then(); startRecordingGame();
(0, _sounds.getAudioContext)()?.resume();
resumeRecording(); resumeRecording();
document.body.className = running ? " running " : " paused "; document.body.className = running ? " running " : " paused ";
} }
@ -1125,7 +673,7 @@ function pause(playerAskedForPause) {
running = false; running = false;
needsRender = true; needsRender = true;
setTimeout(()=>{ setTimeout(()=>{
if (!running) (0, _sounds.getAudioContext)()?.suspend().then(); if (!running) (0, _sounds.getAudioContext)()?.suspend();
}, 1000); }, 1000);
pauseRecording(); pauseRecording();
pauseTimeout = null; pauseTimeout = null;
@ -1360,8 +908,9 @@ async function openUpgradesPicker() {
resetBalls(); resetBalls();
} }
function setLevel(l) { function setLevel(l) {
stopRecording();
pause(false); pause(false);
if (l > 0) openUpgradesPicker().then(); if (l > 0) openUpgradesPicker();
currentLevel = l; currentLevel = l;
levelTime = 0; levelTime = 0;
level_skip_last_uses = 0; level_skip_last_uses = 0;
@ -1386,8 +935,6 @@ function setLevel(l) {
// This caused problems with accented characters like the ô of côte d'ivoire for odd reasons // This caused problems with accented characters like the ô of côte d'ivoire for odd reasons
// background.src = 'data:image/svg+xml;base64,' + btoa(lvl.svg) // background.src = 'data:image/svg+xml;base64,' + btoa(lvl.svg)
background.src = "data:image/svg+xml;UTF8," + lvl.svg; background.src = "data:image/svg+xml;UTF8," + lvl.svg;
stopRecording();
startRecordingGame();
} }
function currentLevelInfo() { function currentLevelInfo() {
return runLevels[currentLevel % runLevels.length]; return runLevels[currentLevel % runLevels.length];
@ -1478,7 +1025,7 @@ gameCanvas.addEventListener("mouseup", (e)=>{
if (running) pause(true); if (running) pause(true);
else { else {
play(); play();
if (isSettingOn("pointerLock")) gameCanvas.requestPointerLock().then(); if (isSettingOn("pointerLock")) gameCanvas.requestPointerLock();
} }
}); });
gameCanvas.addEventListener("mousemove", (e)=>{ gameCanvas.addEventListener("mousemove", (e)=>{
@ -2686,7 +2233,7 @@ function toggleSetting(key) {
} }
scoreDisplay.addEventListener("click", (e)=>{ scoreDisplay.addEventListener("click", (e)=>{
e.preventDefault(); e.preventDefault();
openScorePanel().then(); openScorePanel();
}); });
async function openScorePanel() { async function openScorePanel() {
pause(true); pause(true);
@ -2717,7 +2264,7 @@ async function openScorePanel() {
} }
document.getElementById("menu")?.addEventListener("click", (e)=>{ document.getElementById("menu")?.addEventListener("click", (e)=>{
e.preventDefault(); e.preventDefault();
openSettingsPanel().then(); openSettingsPanel();
}); });
async function openSettingsPanel() { async function openSettingsPanel() {
pause(true); pause(true);
@ -3012,6 +2559,7 @@ function drawMainCanvasOnSmallCanvas() {
} }
function startRecordingGame() { function startRecordingGame() {
if (!isSettingOn("record")) return; if (!isSettingOn("record")) return;
if (mediaRecorder) return;
if (!recordCanvas) { if (!recordCanvas) {
// Smaller canvas with fewer details // Smaller canvas with fewer details
recordCanvas = document.createElement("canvas"); recordCanvas = document.createElement("canvas");
@ -3088,11 +2636,11 @@ function findLast(arr, predicate) {
function toggleFullScreen() { function toggleFullScreen() {
try { try {
if (document.fullscreenElement !== null) { if (document.fullscreenElement !== null) {
if (document.exitFullscreen) document.exitFullscreen().then(); if (document.exitFullscreen) document.exitFullscreen();
else if (document.webkitCancelFullScreen) document.webkitCancelFullScreen(); else if (document.webkitCancelFullScreen) document.webkitCancelFullScreen();
} else { } else {
const docel = document.documentElement; const docel = document.documentElement;
if (docel.requestFullscreen) docel.requestFullscreen().then(); if (docel.requestFullscreen) docel.requestFullscreen();
else if (docel.webkitRequestFullscreen) docel.webkitRequestFullscreen(); else if (docel.webkitRequestFullscreen) docel.webkitRequestFullscreen();
} }
} catch (e) { } catch (e) {
@ -3124,8 +2672,8 @@ document.addEventListener("keyup", (e)=>{
else if (e.key === "ArrowUp" && focused?.previousElementSibling?.tagName === "BUTTON") focused?.previousElementSibling?.focus(); else if (e.key === "ArrowUp" && focused?.previousElementSibling?.tagName === "BUTTON") focused?.previousElementSibling?.focus();
else if (e.key === "Escape" && closeModal) closeModal(); else if (e.key === "Escape" && closeModal) closeModal();
else if (e.key === "Escape" && running) pause(true); else if (e.key === "Escape" && running) pause(true);
else if (e.key.toLowerCase() === "m" && !alertsOpen) openSettingsPanel().then(); else if (e.key.toLowerCase() === "m" && !alertsOpen) openSettingsPanel();
else if (e.key.toLowerCase() === "s" && !alertsOpen) openScorePanel().then(); else if (e.key.toLowerCase() === "s" && !alertsOpen) openScorePanel();
else return; else return;
e.preventDefault(); e.preventDefault();
}); });
@ -3157,9 +2705,7 @@ var _levelsJsonDefault = parcelHelpers.interopDefault(_levelsJson);
var _versionJson = require("./version.json"); var _versionJson = require("./version.json");
var _versionJsonDefault = parcelHelpers.interopDefault(_versionJson); var _versionJsonDefault = parcelHelpers.interopDefault(_versionJson);
var _rawUpgrades = require("./rawUpgrades"); var _rawUpgrades = require("./rawUpgrades");
var _backgroundsJson = require("./backgrounds.json"); var _getLevelBackground = require("./getLevelBackground");
var _backgroundsJsonDefault = parcelHelpers.interopDefault(_backgroundsJson);
const backgrounds = (0, _backgroundsJsonDefault.default);
const palette = (0, _paletteJsonDefault.default); const palette = (0, _paletteJsonDefault.default);
const rawLevelsList = (0, _levelsJsonDefault.default); const rawLevelsList = (0, _levelsJsonDefault.default);
const appVersion = (0, _versionJsonDefault.default); const appVersion = (0, _versionJsonDefault.default);
@ -3186,7 +2732,7 @@ function levelIconHTML(bricks, levelSize, levelName, color) {
ctx.fillRect(Math.floor(pxSize * x), Math.floor(pxSize * y), Math.ceil(pxSize), Math.ceil(pxSize)); ctx.fillRect(Math.floor(pxSize * x), Math.floor(pxSize * y), Math.ceil(pxSize), Math.ceil(pxSize));
} }
} }
// I don't think many blind people will benefit for this but it's nice to have something to put in "alt" // I don't think many blind people will benefit for this, but it's nice to have something to put in "alt"
return `<img alt="${levelName}" width="${size}" height="${size}" src="${c.toDataURL()}"/>`; return `<img alt="${levelName}" width="${size}" height="${size}" src="${c.toDataURL()}"/>`;
} }
const icons = {}; const icons = {};
@ -3194,13 +2740,11 @@ const allLevels = rawLevelsList.map((level)=>{
const bricks = level.bricks.split("").map((c)=>palette[c]).slice(0, level.size * level.size); const bricks = level.bricks.split("").map((c)=>palette[c]).slice(0, level.size * level.size);
const icon = levelIconHTML(bricks, level.size, level.name, level.color); const icon = levelIconHTML(bricks, level.size, level.name, level.color);
icons[level.name] = icon; icons[level.name] = icon;
let svg = level.svg !== null && backgrounds[level.svg];
if (!level.color && !svg) svg = backgrounds[hashCode(level.name) % backgrounds.length];
return { return {
...level, ...level,
bricks, bricks,
icon, icon,
svg svg: (0, _getLevelBackground.getLevelBackground)(level)
}; };
}).filter((l)=>!l.name.startsWith("icon:")).map((l, li)=>({ }).filter((l)=>!l.name.startsWith("icon:")).map((l, li)=>({
...l, ...l,
@ -3211,17 +2755,8 @@ const upgrades = (0, _rawUpgrades.rawUpgrades).map((u)=>({
...u, ...u,
icon: icons["icon:" + u.id] icon: icons["icon:" + u.id]
})); }));
function hashCode(string) {
let hash = 0;
for(let i = 0; i < string.length; i++){
let code = string.charCodeAt(i);
hash = (hash << 5) - hash + code;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash);
}
},{"./palette.json":"jhnsJ","./levels.json":"kqnNl","./version.json":"h1X9A","./rawUpgrades":"cvg5m","./backgrounds.json":"el6Kx","@parcel/transformer-js/src/esmodule-helpers.js":"gkKU3"}],"h1X9A":[function(require,module,exports,__globalThis) { },{"./palette.json":"jhnsJ","./levels.json":"kqnNl","./version.json":"h1X9A","./rawUpgrades":"cvg5m","@parcel/transformer-js/src/esmodule-helpers.js":"gkKU3","./getLevelBackground":"7OIPf"}],"h1X9A":[function(require,module,exports,__globalThis) {
module.exports = JSON.parse("\"29030875\""); module.exports = JSON.parse("\"29030875\"");
},{}],"cvg5m":[function(require,module,exports,__globalThis) { },{}],"cvg5m":[function(require,module,exports,__globalThis) {
@ -3837,7 +3372,7 @@ function createOscillator(context, frequency, type) {
return oscillator; return oscillator;
} }
},{"./game":"edeGs","@parcel/transformer-js/src/esmodule-helpers.js":"gkKU3"}]},["hhTAC","3UXKE","3qndx"], "3qndx", "parcelRequire94c2") },{"./game":"edeGs","@parcel/transformer-js/src/esmodule-helpers.js":"gkKU3"}]},["eBxNa","3qndx"], "3qndx", "parcelRequire94c2")
</script> </script>
</body> </body>

View file

@ -142,463 +142,10 @@
this[globalName] = mainExports; this[globalName] = mainExports;
} }
} }
})({"cv6W2":[function(require,module,exports,__globalThis) { })({"7tSz9":[function(require,module,exports,__globalThis) {
var global = arguments[3]; require("27eb2bc3af6e974d")(require("b23fa2c1e78907d1").getBundleURL('izxdV') + "index.c0fd3053.js");
var HMR_HOST = null;
var HMR_PORT = null;
var HMR_SECURE = false;
var HMR_ENV_HASH = "d6ea1d42532a7575";
var HMR_USE_SSE = false;
module.bundle.HMR_BUNDLE_ID = "d8554468227fd609";
"use strict";
/* global HMR_HOST, HMR_PORT, HMR_ENV_HASH, HMR_SECURE, HMR_USE_SSE, chrome, browser, __parcel__import__, __parcel__importScripts__, ServiceWorkerGlobalScope */ /*::
import type {
HMRAsset,
HMRMessage,
} from '@parcel/reporter-dev-server/src/HMRServer.js';
interface ParcelRequire {
(string): mixed;
cache: {|[string]: ParcelModule|};
hotData: {|[string]: mixed|};
Module: any;
parent: ?ParcelRequire;
isParcelRequire: true;
modules: {|[string]: [Function, {|[string]: string|}]|};
HMR_BUNDLE_ID: string;
root: ParcelRequire;
}
interface ParcelModule {
hot: {|
data: mixed,
accept(cb: (Function) => void): void,
dispose(cb: (mixed) => void): void,
// accept(deps: Array<string> | string, cb: (Function) => void): void,
// decline(): void,
_acceptCallbacks: Array<(Function) => void>,
_disposeCallbacks: Array<(mixed) => void>,
|};
}
interface ExtensionContext {
runtime: {|
reload(): void,
getURL(url: string): string;
getManifest(): {manifest_version: number, ...};
|};
}
declare var module: {bundle: ParcelRequire, ...};
declare var HMR_HOST: string;
declare var HMR_PORT: string;
declare var HMR_ENV_HASH: string;
declare var HMR_SECURE: boolean;
declare var HMR_USE_SSE: boolean;
declare var chrome: ExtensionContext;
declare var browser: ExtensionContext;
declare var __parcel__import__: (string) => Promise<void>;
declare var __parcel__importScripts__: (string) => Promise<void>;
declare var globalThis: typeof self;
declare var ServiceWorkerGlobalScope: Object;
*/ var OVERLAY_ID = '__parcel__error__overlay__';
var OldModule = module.bundle.Module;
function Module(moduleName) {
OldModule.call(this, moduleName);
this.hot = {
data: module.bundle.hotData[moduleName],
_acceptCallbacks: [],
_disposeCallbacks: [],
accept: function(fn) {
this._acceptCallbacks.push(fn || function() {});
},
dispose: function(fn) {
this._disposeCallbacks.push(fn);
}
};
module.bundle.hotData[moduleName] = undefined;
}
module.bundle.Module = Module;
module.bundle.hotData = {};
var checkedAssets /*: {|[string]: boolean|} */ , disposedAssets /*: {|[string]: boolean|} */ , assetsToDispose /*: Array<[ParcelRequire, string]> */ , assetsToAccept /*: Array<[ParcelRequire, string]> */ ;
function getHostname() {
return HMR_HOST || (location.protocol.indexOf('http') === 0 ? location.hostname : 'localhost');
}
function getPort() {
return HMR_PORT || location.port;
}
// eslint-disable-next-line no-redeclare
var parent = module.bundle.parent;
if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
var hostname = getHostname();
var port = getPort();
var protocol = HMR_SECURE || location.protocol == 'https:' && ![
'localhost',
'127.0.0.1',
'0.0.0.0'
].includes(hostname) ? 'wss' : 'ws';
var ws;
if (HMR_USE_SSE) ws = new EventSource('/__parcel_hmr');
else try {
ws = new WebSocket(protocol + '://' + hostname + (port ? ':' + port : '') + '/');
} catch (err) {
if (err.message) console.error(err.message);
ws = {};
}
// Web extension context
var extCtx = typeof browser === 'undefined' ? typeof chrome === 'undefined' ? null : chrome : browser;
// Safari doesn't support sourceURL in error stacks.
// eval may also be disabled via CSP, so do a quick check.
var supportsSourceURL = false;
try {
(0, eval)('throw new Error("test"); //# sourceURL=test.js');
} catch (err) {
supportsSourceURL = err.stack.includes('test.js');
}
// $FlowFixMe
ws.onmessage = async function(event /*: {data: string, ...} */ ) {
checkedAssets = {} /*: {|[string]: boolean|} */ ;
disposedAssets = {} /*: {|[string]: boolean|} */ ;
assetsToAccept = [];
assetsToDispose = [];
var data /*: HMRMessage */ = JSON.parse(event.data);
if (data.type === 'reload') fullReload();
else if (data.type === 'update') {
// Remove error overlay if there is one
if (typeof document !== 'undefined') removeErrorOverlay();
let assets = data.assets.filter((asset)=>asset.envHash === HMR_ENV_HASH);
// Handle HMR Update
let handled = assets.every((asset)=>{
return asset.type === 'css' || asset.type === 'js' && hmrAcceptCheck(module.bundle.root, asset.id, asset.depsByBundle);
});
if (handled) {
console.clear();
// Dispatch custom event so other runtimes (e.g React Refresh) are aware.
if (typeof window !== 'undefined' && typeof CustomEvent !== 'undefined') window.dispatchEvent(new CustomEvent('parcelhmraccept'));
await hmrApplyUpdates(assets);
hmrDisposeQueue();
// Run accept callbacks. This will also re-execute other disposed assets in topological order.
let processedAssets = {};
for(let i = 0; i < assetsToAccept.length; i++){
let id = assetsToAccept[i][1];
if (!processedAssets[id]) {
hmrAccept(assetsToAccept[i][0], id);
processedAssets[id] = true;
}
}
} else fullReload();
}
if (data.type === 'error') {
// Log parcel errors to console
for (let ansiDiagnostic of data.diagnostics.ansi){
let stack = ansiDiagnostic.codeframe ? ansiDiagnostic.codeframe : ansiDiagnostic.stack;
console.error("\uD83D\uDEA8 [parcel]: " + ansiDiagnostic.message + '\n' + stack + '\n\n' + ansiDiagnostic.hints.join('\n'));
}
if (typeof document !== 'undefined') {
// Render the fancy html overlay
removeErrorOverlay();
var overlay = createErrorOverlay(data.diagnostics.html);
// $FlowFixMe
document.body.appendChild(overlay);
}
}
};
if (ws instanceof WebSocket) {
ws.onerror = function(e) {
if (e.message) console.error(e.message);
};
ws.onclose = function() {
console.warn("[parcel] \uD83D\uDEA8 Connection to the HMR server was lost");
};
}
}
function removeErrorOverlay() {
var overlay = document.getElementById(OVERLAY_ID);
if (overlay) {
overlay.remove();
console.log("[parcel] \u2728 Error resolved");
}
}
function createErrorOverlay(diagnostics) {
var overlay = document.createElement('div');
overlay.id = OVERLAY_ID;
let errorHTML = '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; font-family: Menlo, Consolas, monospace; z-index: 9999;">';
for (let diagnostic of diagnostics){
let stack = diagnostic.frames.length ? diagnostic.frames.reduce((p, frame)=>{
return `${p}
<a href="/__parcel_launch_editor?file=${encodeURIComponent(frame.location)}" style="text-decoration: underline; color: #888" onclick="fetch(this.href); return false">${frame.location}</a>
${frame.code}`;
}, '') : diagnostic.stack;
errorHTML += `
<div>
<div style="font-size: 18px; font-weight: bold; margin-top: 20px;">
\u{1F6A8} ${diagnostic.message}
</div>
<pre>${stack}</pre>
<div>
${diagnostic.hints.map((hint)=>"<div>\uD83D\uDCA1 " + hint + '</div>').join('')}
</div>
${diagnostic.documentation ? `<div>\u{1F4DD} <a style="color: violet" href="${diagnostic.documentation}" target="_blank">Learn more</a></div>` : ''}
</div>
`;
}
errorHTML += '</div>';
overlay.innerHTML = errorHTML;
return overlay;
}
function fullReload() {
if ('reload' in location) location.reload();
else if (extCtx && extCtx.runtime && extCtx.runtime.reload) extCtx.runtime.reload();
}
function getParents(bundle, id) /*: Array<[ParcelRequire, string]> */ {
var modules = bundle.modules;
if (!modules) return [];
var parents = [];
var k, d, dep;
for(k in modules)for(d in modules[k][1]){
dep = modules[k][1][d];
if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) parents.push([
bundle,
k
]);
}
if (bundle.parent) parents = parents.concat(getParents(bundle.parent, id));
return parents;
}
function updateLink(link) {
var href = link.getAttribute('href');
if (!href) return;
var newLink = link.cloneNode();
newLink.onload = function() {
if (link.parentNode !== null) // $FlowFixMe
link.parentNode.removeChild(link);
};
newLink.setAttribute('href', // $FlowFixMe
href.split('?')[0] + '?' + Date.now());
// $FlowFixMe
link.parentNode.insertBefore(newLink, link.nextSibling);
}
var cssTimeout = null;
function reloadCSS() {
if (cssTimeout) return;
cssTimeout = setTimeout(function() {
var links = document.querySelectorAll('link[rel="stylesheet"]');
for(var i = 0; i < links.length; i++){
// $FlowFixMe[incompatible-type]
var href /*: string */ = links[i].getAttribute('href');
var hostname = getHostname();
var servedFromHMRServer = hostname === 'localhost' ? new RegExp('^(https?:\\/\\/(0.0.0.0|127.0.0.1)|localhost):' + getPort()).test(href) : href.indexOf(hostname + ':' + getPort());
var absolute = /^https?:\/\//i.test(href) && href.indexOf(location.origin) !== 0 && !servedFromHMRServer;
if (!absolute) updateLink(links[i]);
}
cssTimeout = null;
}, 50);
}
function hmrDownload(asset) {
if (asset.type === 'js') {
if (typeof document !== 'undefined') {
let script = document.createElement('script');
script.src = asset.url + '?t=' + Date.now();
if (asset.outputFormat === 'esmodule') script.type = 'module';
return new Promise((resolve, reject)=>{
var _document$head;
script.onload = ()=>resolve(script);
script.onerror = reject;
(_document$head = document.head) === null || _document$head === void 0 || _document$head.appendChild(script);
});
} else if (typeof importScripts === 'function') {
// Worker scripts
if (asset.outputFormat === 'esmodule') return import(asset.url + '?t=' + Date.now());
else return new Promise((resolve, reject)=>{
try {
importScripts(asset.url + '?t=' + Date.now());
resolve();
} catch (err) {
reject(err);
}
});
}
}
}
async function hmrApplyUpdates(assets) {
global.parcelHotUpdate = Object.create(null);
let scriptsToRemove;
try {
// If sourceURL comments aren't supported in eval, we need to load
// the update from the dev server over HTTP so that stack traces
// are correct in errors/logs. This is much slower than eval, so
// we only do it if needed (currently just Safari).
// https://bugs.webkit.org/show_bug.cgi?id=137297
// This path is also taken if a CSP disallows eval.
if (!supportsSourceURL) {
let promises = assets.map((asset)=>{
var _hmrDownload;
return (_hmrDownload = hmrDownload(asset)) === null || _hmrDownload === void 0 ? void 0 : _hmrDownload.catch((err)=>{
// Web extension fix
if (extCtx && extCtx.runtime && extCtx.runtime.getManifest().manifest_version == 3 && typeof ServiceWorkerGlobalScope != 'undefined' && global instanceof ServiceWorkerGlobalScope) {
extCtx.runtime.reload();
return;
}
throw err;
});
});
scriptsToRemove = await Promise.all(promises);
}
assets.forEach(function(asset) {
hmrApply(module.bundle.root, asset);
});
} finally{
delete global.parcelHotUpdate;
if (scriptsToRemove) scriptsToRemove.forEach((script)=>{
if (script) {
var _document$head2;
(_document$head2 = document.head) === null || _document$head2 === void 0 || _document$head2.removeChild(script);
}
});
}
}
function hmrApply(bundle /*: ParcelRequire */ , asset /*: HMRAsset */ ) {
var modules = bundle.modules;
if (!modules) return;
if (asset.type === 'css') reloadCSS();
else if (asset.type === 'js') {
let deps = asset.depsByBundle[bundle.HMR_BUNDLE_ID];
if (deps) {
if (modules[asset.id]) {
// Remove dependencies that are removed and will become orphaned.
// This is necessary so that if the asset is added back again, the cache is gone, and we prevent a full page reload.
let oldDeps = modules[asset.id][1];
for(let dep in oldDeps)if (!deps[dep] || deps[dep] !== oldDeps[dep]) {
let id = oldDeps[dep];
let parents = getParents(module.bundle.root, id);
if (parents.length === 1) hmrDelete(module.bundle.root, id);
}
}
if (supportsSourceURL) // Global eval. We would use `new Function` here but browser
// support for source maps is better with eval.
(0, eval)(asset.output);
// $FlowFixMe
let fn = global.parcelHotUpdate[asset.id];
modules[asset.id] = [
fn,
deps
];
}
// Always traverse to the parent bundle, even if we already replaced the asset in this bundle.
// This is required in case modules are duplicated. We need to ensure all instances have the updated code.
if (bundle.parent) hmrApply(bundle.parent, asset);
}
}
function hmrDelete(bundle, id) {
let modules = bundle.modules;
if (!modules) return;
if (modules[id]) {
// Collect dependencies that will become orphaned when this module is deleted.
let deps = modules[id][1];
let orphans = [];
for(let dep in deps){
let parents = getParents(module.bundle.root, deps[dep]);
if (parents.length === 1) orphans.push(deps[dep]);
}
// Delete the module. This must be done before deleting dependencies in case of circular dependencies.
delete modules[id];
delete bundle.cache[id];
// Now delete the orphans.
orphans.forEach((id)=>{
hmrDelete(module.bundle.root, id);
});
} else if (bundle.parent) hmrDelete(bundle.parent, id);
}
function hmrAcceptCheck(bundle /*: ParcelRequire */ , id /*: string */ , depsByBundle /*: ?{ [string]: { [string]: string } }*/ ) {
if (hmrAcceptCheckOne(bundle, id, depsByBundle)) return true;
// Traverse parents breadth first. All possible ancestries must accept the HMR update, or we'll reload.
let parents = getParents(module.bundle.root, id);
let accepted = false;
while(parents.length > 0){
let v = parents.shift();
let a = hmrAcceptCheckOne(v[0], v[1], null);
if (a) // If this parent accepts, stop traversing upward, but still consider siblings.
accepted = true;
else {
// Otherwise, queue the parents in the next level upward.
let p = getParents(module.bundle.root, v[1]);
if (p.length === 0) {
// If there are no parents, then we've reached an entry without accepting. Reload.
accepted = false;
break;
}
parents.push(...p);
}
}
return accepted;
}
function hmrAcceptCheckOne(bundle /*: ParcelRequire */ , id /*: string */ , depsByBundle /*: ?{ [string]: { [string]: string } }*/ ) {
var modules = bundle.modules;
if (!modules) return;
if (depsByBundle && !depsByBundle[bundle.HMR_BUNDLE_ID]) {
// If we reached the root bundle without finding where the asset should go,
// there's nothing to do. Mark as "accepted" so we don't reload the page.
if (!bundle.parent) return true;
return hmrAcceptCheck(bundle.parent, id, depsByBundle);
}
if (checkedAssets[id]) return true;
checkedAssets[id] = true;
var cached = bundle.cache[id];
assetsToDispose.push([
bundle,
id
]);
if (!cached || cached.hot && cached.hot._acceptCallbacks.length) {
assetsToAccept.push([
bundle,
id
]);
return true;
}
}
function hmrDisposeQueue() {
// Dispose all old assets.
for(let i = 0; i < assetsToDispose.length; i++){
let id = assetsToDispose[i][1];
if (!disposedAssets[id]) {
hmrDispose(assetsToDispose[i][0], id);
disposedAssets[id] = true;
}
}
assetsToDispose = [];
}
function hmrDispose(bundle /*: ParcelRequire */ , id /*: string */ ) {
var cached = bundle.cache[id];
bundle.hotData[id] = {};
if (cached && cached.hot) cached.hot.data = bundle.hotData[id];
if (cached && cached.hot && cached.hot._disposeCallbacks.length) cached.hot._disposeCallbacks.forEach(function(cb) {
cb(bundle.hotData[id]);
});
delete bundle.cache[id];
}
function hmrAccept(bundle /*: ParcelRequire */ , id /*: string */ ) {
// Execute the module.
bundle(id);
// Run the accept callbacks in the new version of the module.
var cached = bundle.cache[id];
if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
let assetsToAlsoAccept = [];
cached.hot._acceptCallbacks.forEach(function(cb) {
let additionalAssets = cb(function() {
return getParents(module.bundle.root, id);
});
if (Array.isArray(additionalAssets) && additionalAssets.length) assetsToAlsoAccept.push(...additionalAssets);
});
if (assetsToAlsoAccept.length) {
let handled = assetsToAlsoAccept.every(function(a) {
return hmrAcceptCheck(a[0], a[1]);
});
if (!handled) return fullReload();
hmrDisposeQueue();
}
}
}
},{}],"5iVMc":[function(require,module,exports,__globalThis) { },{"27eb2bc3af6e974d":"61B45","b23fa2c1e78907d1":"lgJ39"}],"61B45":[function(require,module,exports,__globalThis) {
require("b393ab0c6dc0c92d")(require("6acefb54a655961").getBundleURL('izxdV') + "index.497c99a1.js");
},{"b393ab0c6dc0c92d":"61B45","6acefb54a655961":"lgJ39"}],"61B45":[function(require,module,exports,__globalThis) {
"use strict"; "use strict";
var cacheLoader = require("ca2a84f7fa4a3bb0"); var cacheLoader = require("ca2a84f7fa4a3bb0");
module.exports = cacheLoader(function(bundle) { module.exports = cacheLoader(function(bundle) {
@ -703,6 +250,7 @@ var _paletteJson = require("./palette.json");
var _paletteJsonDefault = parcelHelpers.interopDefault(_paletteJson); var _paletteJsonDefault = parcelHelpers.interopDefault(_paletteJson);
var _levelsJson = require("./levels.json"); var _levelsJson = require("./levels.json");
var _levelsJsonDefault = parcelHelpers.interopDefault(_levelsJson); var _levelsJsonDefault = parcelHelpers.interopDefault(_levelsJson);
var _getLevelBackground = require("./getLevelBackground");
const backgrounds = (0, _backgroundsJsonDefault.default); const backgrounds = (0, _backgroundsJsonDefault.default);
const palette = (0, _paletteJsonDefault.default); const palette = (0, _paletteJsonDefault.default);
let allLevels = (0, _levelsJsonDefault.default); let allLevels = (0, _levelsJsonDefault.default);
@ -736,7 +284,7 @@ function addLevelEditorToList(level, levelIndex) {
const { name, bricks, size, svg, color } = level; const { name, bricks, size, svg, color } = level;
let div = document.createElement('div'); let div = document.createElement('div');
div.innerHTML = ` div.innerHTML = `
<button data-level="${levelIndex}" data-rename="yep">${name}</button> <input type="text" value="${level.name || ''}" data-level="${levelIndex}" data-text-val="name" />
<div> <div>
<button data-level="${levelIndex}" data-delete="yep">Delete</button> <button data-level="${levelIndex}" data-delete="yep">Delete</button>
<button data-offset-level-size="-1" data-level="${levelIndex}">-</button> <button data-offset-level-size="-1" data-level="${levelIndex}">-</button>
@ -745,10 +293,9 @@ function addLevelEditorToList(level, levelIndex) {
<button data-offset-x="1" data-offset-y="0" data-level="${levelIndex}">R</button> <button data-offset-x="1" data-offset-y="0" data-level="${levelIndex}">R</button>
<button data-offset-x="0" data-offset-y="-1" data-level="${levelIndex}">U</button> <button data-offset-x="0" data-offset-y="-1" data-level="${levelIndex}">U</button>
<button data-offset-x="0" data-offset-y="1" data-level="${levelIndex}">D</button> <button data-offset-x="0" data-offset-y="1" data-level="${levelIndex}">D</button>
<input type="color" value="${level.color || ''}" data-level="${levelIndex}" /> <input type="color" value="${level.color || ''}" data-level="${levelIndex}" data-text-val="color" />
<input type="number" value="${level.svg || hashCode(level.name) % backgrounds.length}" data-level="${levelIndex}" data-num-val="svg" /> <input type="number" value="${level.svg || (0, _getLevelBackground.hashCode)(level.name) % backgrounds.length}" data-level="${levelIndex}" data-num-val="svg" />
<button data-level="${levelIndex}" data-set-bg-svg="true" >${svg ? 'replace' : 'set'}</button>
</div> </div>
@ -769,9 +316,7 @@ function updateLevelBackground(levelIndex) {
backgroundColor: color backgroundColor: color
}); });
else { else {
const index = svg || hashCode(level.name) % backgrounds.length; const svgSource = (0, _getLevelBackground.getLevelBackground)(level);
const svgSource = backgrounds[index];
console.log(index);
div.setAttribute('data-svg', svgSource); div.setAttribute('data-svg', svgSource);
Object.assign(div.style, { Object.assign(div.style, {
backgroundImage: `url("data:image/svg+xml;UTF8,${encodeURIComponent(svgSource)}")`, backgroundImage: `url("data:image/svg+xml;UTF8,${encodeURIComponent(svgSource)}")`,
@ -796,16 +341,20 @@ function renderLevelBricks(levelIndex) {
levelsListEl.addEventListener('change', (e)=>{ levelsListEl.addEventListener('change', (e)=>{
const target = e.target; const target = e.target;
const levelIndexStr = target.getAttribute('data-level'); const levelIndexStr = target.getAttribute('data-level');
if (levelIndexStr) { if (!levelIndexStr) return;
const levelIndex = parseInt(levelIndexStr); const levelIndex = parseInt(levelIndexStr);
const level = allLevels[levelIndex]; const level = allLevels[levelIndex];
if (target.getAttribute('type') === 'color') { if (target.getAttribute('data-text-val') == 'name') level.name = target.value;
if (target.getAttribute('data-text-val') == 'color') {
level.color = target.value; level.color = target.value;
level.svg = null; level.svg = null;
}
if (target.getAttribute('data-num-val') == 'svg') {
level.color = '';
level.svg = parseFloat(target.value);
}
updateLevelBackground(levelIndex); updateLevelBackground(levelIndex);
}
save(); save();
}
}); });
levelsListEl.addEventListener('click', (e)=>{ levelsListEl.addEventListener('click', (e)=>{
const target = e.target; const target = e.target;
@ -912,16 +461,7 @@ function save() {
body: JSON.stringify(allLevels, null, 2) body: JSON.stringify(allLevels, null, 2)
}); });
} }
function hashCode(string) {
let hash = 0;
for(let i = 0; i < string.length; i++){
let code = string.charCodeAt(i);
hash = (hash << 5) - hash + code;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash);
}
},{"./backgrounds.json":"el6Kx","./palette.json":"jhnsJ","./levels.json":"kqnNl","@parcel/transformer-js/src/esmodule-helpers.js":"gkKU3"}]},["cv6W2","5iVMc","434tO"], "434tO", "parcelRequire94c2") },{"./backgrounds.json":"el6Kx","./palette.json":"jhnsJ","./levels.json":"kqnNl","@parcel/transformer-js/src/esmodule-helpers.js":"gkKU3","./getLevelBackground":"7OIPf"}]},["7tSz9","434tO"], "434tO", "parcelRequire94c2")
//# sourceMappingURL=levels_editor.227fd609.js.map //# sourceMappingURL=levels_editor.227fd609.js.map

File diff suppressed because one or more lines are too long

View file

@ -28,6 +28,10 @@ body {
position: relative; position: relative;
} }
#levels input[type="number"] {
width: 50px;
}
#levels > div { #levels > div {
grid-template-columns: auto auto; grid-template-columns: auto auto;
grid-template-areas: ". name" grid-template-areas: ". name"

View file

@ -1 +1 @@
{"mappings":"AACA;;;;;AAKA;;;;;;;;;AAAA;;;;AAcA;;;;;;;;AAAA;;;;AAWE;;;;;;;AAKE;;;;AAIA;;;;;;;AAOA","sources":["src/levels_editor.less"],"sourcesContent":["\nbody {\n background: black;\n color: white;\n}\n\n#palette {\n position: fixed;\n top: 0;\n right: 0;\n width: 80px;\n bottom: 0;\n overflow: auto;\n\n button.active {\n transform: scale(1.2);\n }\n\n}\n\n#levels {\n display: flex;\n gap: 40px;\n align-items: flex-start;\n flex-wrap: wrap;\n margin-right: 80px;\n\n .level-bricks-preview {\n position: relative;\n }\n\n & > div {\n display: grid;\n grid-template-columns: auto auto;\n grid-template-areas: \". name\" \"buttons bricks\";\n\n & > *:nth-child(1) {\n grid-area: name;\n }\n\n & > div:nth-child(2) {\n grid-area: buttons;\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n }\n\n & > div:nth-child(3) {\n grid-area: bricks;\n }\n\n }\n\n}\n\n"],"names":[],"version":3,"file":"levels_editor.de5e7f9b.css.map","sourceRoot":"/__parcel_source_root/"} {"mappings":"AACA;;;;;AAKA;;;;;;;;;AAAA;;;;AAcA;;;;;;;;AAAA;;;;AAAA;;;;AAcE;;;;;;;AAKE;;;;AAIA;;;;;;;AAOA","sources":["src/levels_editor.less"],"sourcesContent":["\nbody {\n background: black;\n color: white;\n}\n\n#palette {\n position: fixed;\n top: 0;\n right: 0;\n width: 80px;\n bottom: 0;\n overflow: auto;\n\n button.active {\n transform: scale(1.2);\n }\n\n}\n\n#levels {\n display: flex;\n gap: 40px;\n align-items: flex-start;\n flex-wrap: wrap;\n margin-right: 80px;\n\n .level-bricks-preview {\n position: relative;\n }\n input[type=\"number\"]{\n width: 50px;\n }\n\n & > div {\n display: grid;\n grid-template-columns: auto auto;\n grid-template-areas: \". name\" \"buttons bricks\";\n\n & > *:nth-child(1) {\n grid-area: name;\n }\n\n & > div:nth-child(2) {\n grid-area: buttons;\n display: flex;\n flex-direction: column;\n align-items: flex-end;\n }\n\n & > div:nth-child(3) {\n grid-area: bricks;\n }\n\n }\n\n}\n\n"],"names":[],"version":3,"file":"levels_editor.de5e7f9b.css.map","sourceRoot":"/__parcel_source_root/"}

View file

@ -1,6 +1,6 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head><script src="/index.497c99a1.js"></script> <head><script src="/index.c0fd3053.js"></script>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Level editor</title> <title>Level editor</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎨</text></svg>"> <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎨</text></svg>">

View file

@ -4,7 +4,7 @@
"description": "A roguelite take on the breakout genre, optimised for short runs and replayability.", "description": "A roguelite take on the breakout genre, optimised for short runs and replayability.",
"scripts": { "scripts": {
"start": "rm -rf .parcel-cache && run-p dev:*", "start": "rm -rf .parcel-cache && run-p dev:*",
"dev:game-fe": "parcel src/*.html --lazy", "dev:game-fe": "parcel src/*.html --lazy --no-hmr",
"dev:editor-be": "nodemon editserver.js --watch editserver.js", "dev:editor-be": "nodemon editserver.js --watch editserver.js",
"build": "rm -f dist/* && parcel build src/index.html" "build": "rm -f dist/* && parcel build src/index.html"
}, },

View file

@ -117,7 +117,9 @@ let running = false,
function play() { function play() {
if (running) return; if (running) return;
running = true; running = true;
getAudioContext()?.resume().then();
startRecordingGame();
getAudioContext()?.resume();
resumeRecording(); resumeRecording();
document.body.className = running ? " running " : " paused "; document.body.className = running ? " running " : " paused ";
} }
@ -132,7 +134,7 @@ function pause(playerAskedForPause: boolean) {
needsRender = true; needsRender = true;
setTimeout(() => { setTimeout(() => {
if (!running) getAudioContext()?.suspend().then(); if (!running) getAudioContext()?.suspend();
}, 1000); }, 1000);
pauseRecording(); pauseRecording();
@ -446,9 +448,10 @@ async function openUpgradesPicker() {
} }
function setLevel(l: number) { function setLevel(l: number) {
stopRecording();
pause(false); pause(false);
if (l > 0) { if (l > 0) {
openUpgradesPicker().then(); openUpgradesPicker();
} }
currentLevel = l; currentLevel = l;
@ -476,8 +479,6 @@ function setLevel(l: number) {
// This caused problems with accented characters like the ô of côte d'ivoire for odd reasons // This caused problems with accented characters like the ô of côte d'ivoire for odd reasons
// background.src = 'data:image/svg+xml;base64,' + btoa(lvl.svg) // background.src = 'data:image/svg+xml;base64,' + btoa(lvl.svg)
background.src = "data:image/svg+xml;UTF8," + lvl.svg; background.src = "data:image/svg+xml;UTF8," + lvl.svg;
stopRecording();
startRecordingGame();
} }
function currentLevelInfo() { function currentLevelInfo() {
@ -625,7 +626,7 @@ gameCanvas.addEventListener("mouseup", (e) => {
} else { } else {
play(); play();
if (isSettingOn("pointerLock")) { if (isSettingOn("pointerLock")) {
gameCanvas.requestPointerLock().then(); gameCanvas.requestPointerLock();
} }
} }
}); });
@ -2516,7 +2517,7 @@ export function toggleSetting(key: OptionId) {
scoreDisplay.addEventListener("click", (e) => { scoreDisplay.addEventListener("click", (e) => {
e.preventDefault(); e.preventDefault();
openScorePanel().then(); openScorePanel();
}); });
async function openScorePanel() { async function openScorePanel() {
@ -2551,7 +2552,7 @@ async function openScorePanel() {
document.getElementById("menu")?.addEventListener("click", (e) => { document.getElementById("menu")?.addEventListener("click", (e) => {
e.preventDefault(); e.preventDefault();
openSettingsPanel().then(); openSettingsPanel();
}); });
async function openSettingsPanel() { async function openSettingsPanel() {
@ -2941,6 +2942,7 @@ function startRecordingGame() {
if (!isSettingOn("record")) { if (!isSettingOn("record")) {
return; return;
} }
if(mediaRecorder) return;
if (!recordCanvas) { if (!recordCanvas) {
// Smaller canvas with fewer details // Smaller canvas with fewer details
recordCanvas = document.createElement("canvas"); recordCanvas = document.createElement("canvas");
@ -3058,14 +3060,14 @@ function toggleFullScreen() {
try { try {
if (document.fullscreenElement !== null) { if (document.fullscreenElement !== null) {
if (document.exitFullscreen) { if (document.exitFullscreen) {
document.exitFullscreen().then(); document.exitFullscreen();
} else if (document.webkitCancelFullScreen) { } else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen(); document.webkitCancelFullScreen();
} }
} else { } else {
const docel = document.documentElement; const docel = document.documentElement;
if (docel.requestFullscreen) { if (docel.requestFullscreen) {
docel.requestFullscreen().then(); docel.requestFullscreen();
} else if (docel.webkitRequestFullscreen) { } else if (docel.webkitRequestFullscreen) {
docel.webkitRequestFullscreen(); docel.webkitRequestFullscreen();
} }
@ -3127,9 +3129,9 @@ document.addEventListener("keyup", (e) => {
} else if (e.key === "Escape" && running) { } else if (e.key === "Escape" && running) {
pause(true); pause(true);
} else if (e.key.toLowerCase() === "m" && !alertsOpen) { } else if (e.key.toLowerCase() === "m" && !alertsOpen) {
openSettingsPanel().then(); openSettingsPanel();
} else if (e.key.toLowerCase() === "s" && !alertsOpen) { } else if (e.key.toLowerCase() === "s" && !alertsOpen) {
openScorePanel().then(); openScorePanel();
} else { } else {
return; return;
} }

24
src/getLevelBackground.ts Normal file
View file

@ -0,0 +1,24 @@
import {RawLevel} from "./types";
export function hashCode(string: string) {
let hash = 0;
for (let i = 0; i < string.length; i++) {
let code = string.charCodeAt(i);
hash = (hash << 5) - hash + code;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash);
}
import _backgrounds from "./backgrounds.json";
const backgrounds = _backgrounds as string[];
export function getLevelBackground(level:RawLevel){
let svg = level.svg !== null && backgrounds[level.svg % backgrounds.length];
if (!level.color && !svg) {
svg = backgrounds[hashCode(level.name) % backgrounds.length];
}
return svg
}

View file

@ -116,7 +116,7 @@
"name": "We come in peace", "name": "We come in peace",
"size": 13, "size": 13,
"bricks": "________________a_____a_______a___a_______aaaaaaa_____aaBaaaBaa___aaaaaaaaaaa__aaaaaaaaaaa__a_aaaaaaa_a__a_a_____a_a_____aa_aa_____________________________", "bricks": "________________a_____a_______a___a_______aaaaaaa_____aaBaaaBaa___aaaaaaaaaaa__aaaaaaaaaaa__a_aaaaaaa_a__a_a_____a_a_____aa_aa_____________________________",
"svg": 24, "svg": 29,
"color": "" "color": ""
}, },
{ {
@ -151,8 +151,8 @@
"name": "Enderman", "name": "Enderman",
"size": 10, "size": 10,
"bricks": "___________gggggggg__gggggggg__gggggggg__gggggggg__vvvggvvv__gggggggg__gggggggg__gggggggg_____________________", "bricks": "___________gggggggg__gggggggg__gggggggg__gggggggg__vvvggvvv__gggggggg__gggggggg__gggggggg_____________________",
"svg": "", "svg": null,
"color": "#26a269" "color": "#154b07"
}, },
{ {
"name": "Mushroom", "name": "Mushroom",
@ -165,7 +165,7 @@
"name": "Tulip", "name": "Tulip",
"size": 11, "size": 11,
"bricks": "______________R_R_R______RRRRR______RRRRR______RRRRR_______RRR_________k________k_k_k______k_k_k_______kkk_________k________________", "bricks": "______________R_R_R______RRRRR______RRRRR______RRRRR_______RRR_________k________k_k_k______k_k_k_______kkk_________k________________",
"svg": 29, "svg": 17,
"color": "" "color": ""
}, },
{ {
@ -179,7 +179,7 @@
"name": "Marion", "name": "Marion",
"size": 9, "size": 9,
"bricks": "rr_____rr_rr___rr__rrr_rrr__rrrrrrr__rr_r_rr__rr___rr__rr___rr__rr___rr_rrr___rrr", "bricks": "rr_____rr_rr___rr__rrr_rrr__rrrrrrr__rr_r_rr__rr___rr__rr___rr__rr___rr_rrr___rrr",
"svg": null, "svg": 27,
"color": "" "color": ""
}, },
{ {

View file

@ -28,6 +28,9 @@ body {
.level-bricks-preview { .level-bricks-preview {
position: relative; position: relative;
} }
input[type="number"]{
width: 50px;
}
& > div { & > div {
display: grid; display: grid;

View file

@ -1,11 +1,14 @@
import {Palette, RawLevel} from "./types"; import {Palette, RawLevel} from "./types";
import _backgrounds from './backgrounds.json' import _backgrounds from './backgrounds.json'
const backgrounds=_backgrounds as string[];
import _palette from './palette.json'
const palette=_palette as Palette;
import _allLevels from './levels.json'
let allLevels = _allLevels as RawLevel[];
const backgrounds = _backgrounds as string[];
import _palette from './palette.json'
const palette = _palette as Palette;
import _allLevels from './levels.json'
import {getLevelBackground, hashCode} from "./getLevelBackground";
let allLevels = _allLevels as RawLevel[];
let currentCode = '_' let currentCode = '_'
@ -38,14 +41,16 @@ function renderAllLevels() {
addLevelEditorToList(level, levelIndex) addLevelEditorToList(level, levelIndex)
}) })
} }
const levelsListEl = document?.getElementById('levels') as HTMLDivElement const levelsListEl = document?.getElementById('levels') as HTMLDivElement
function addLevelEditorToList(level:RawLevel, levelIndex:number) {
function addLevelEditorToList(level: RawLevel, levelIndex: number) {
const {name, bricks, size, svg, color} = level const {name, bricks, size, svg, color} = level
let div = document.createElement('div') let div = document.createElement('div')
div.innerHTML = ` div.innerHTML = `
<button data-level="${levelIndex}" data-rename="yep">${name}</button> <input type="text" value="${level.name || ''}" data-level="${levelIndex}" data-text-val="name" />
<div> <div>
<button data-level="${levelIndex}" data-delete="yep">Delete</button> <button data-level="${levelIndex}" data-delete="yep">Delete</button>
<button data-offset-level-size="-1" data-level="${levelIndex}">-</button> <button data-offset-level-size="-1" data-level="${levelIndex}">-</button>
@ -54,10 +59,9 @@ function addLevelEditorToList(level:RawLevel, levelIndex:number) {
<button data-offset-x="1" data-offset-y="0" data-level="${levelIndex}">R</button> <button data-offset-x="1" data-offset-y="0" data-level="${levelIndex}">R</button>
<button data-offset-x="0" data-offset-y="-1" data-level="${levelIndex}">U</button> <button data-offset-x="0" data-offset-y="-1" data-level="${levelIndex}">U</button>
<button data-offset-x="0" data-offset-y="1" data-level="${levelIndex}">D</button> <button data-offset-x="0" data-offset-y="1" data-level="${levelIndex}">D</button>
<input type="color" value="${level.color || ''}" data-level="${levelIndex}" /> <input type="color" value="${level.color || ''}" data-level="${levelIndex}" data-text-val="color" />
<input type="number" value="${level.svg || (hashCode(level.name) % backgrounds.length)}" data-level="${levelIndex}" data-num-val="svg" /> <input type="number" value="${level.svg || (hashCode(level.name) % backgrounds.length)}" data-level="${levelIndex}" data-num-val="svg" />
<button data-level="${levelIndex}" data-set-bg-svg="true" >${svg ? 'replace' : 'set'}</button>
</div> </div>
@ -74,17 +78,16 @@ function addLevelEditorToList(level:RawLevel, levelIndex:number) {
} }
function updateLevelBackground(levelIndex:number) { function updateLevelBackground(levelIndex: number) {
const div = document.getElementById("bricks-of-" + levelIndex) as HTMLDivElement const div = document.getElementById("bricks-of-" + levelIndex) as HTMLDivElement
const level = allLevels[levelIndex] const level = allLevels[levelIndex]
const {svg, color} = level const {svg, color} = level
if (color) { if (color) {
Object.assign(div.style, {backgroundImage: 'none', backgroundColor: color}) Object.assign(div.style, {backgroundImage: 'none', backgroundColor: color})
} else { } else {
const index = svg || (hashCode(level.name) % backgrounds.length) const svgSource = getLevelBackground(level) as string
const svgSource=backgrounds[index]
console.log(index) div.setAttribute('data-svg', svgSource)
div.setAttribute('data-svg',svgSource)
Object.assign(div.style, { Object.assign(div.style, {
backgroundImage: `url("data:image/svg+xml;UTF8,${encodeURIComponent(svgSource)}")`, backgroundImage: `url("data:image/svg+xml;UTF8,${encodeURIComponent(svgSource)}")`,
backgroundColor: 'transparent' backgroundColor: 'transparent'
@ -93,7 +96,7 @@ function updateLevelBackground(levelIndex:number) {
} }
function renderLevelBricks(levelIndex:number) { function renderLevelBricks(levelIndex: number) {
const {size, bricks} = allLevels[levelIndex] const {size, bricks} = allLevels[levelIndex]
const buttons = [] const buttons = []
@ -114,22 +117,30 @@ function renderLevelBricks(levelIndex:number) {
levelsListEl.addEventListener('change', e => { levelsListEl.addEventListener('change', e => {
const target= e.target as HTMLInputElement const target = e.target as HTMLInputElement
const levelIndexStr = target.getAttribute('data-level') const levelIndexStr = target.getAttribute('data-level')
if (levelIndexStr) { if (!levelIndexStr) return
const levelIndex = parseInt(levelIndexStr) const levelIndex = parseInt(levelIndexStr)
const level = allLevels[levelIndex] const level = allLevels[levelIndex]
if (target.getAttribute('type') === 'color') {
if (target.getAttribute('data-text-val') == 'name') {
level.name = target.value
}
if (target.getAttribute('data-text-val') == 'color') {
level.color = target.value level.color = target.value
level.svg = null level.svg = null
}
if (target.getAttribute('data-num-val') == 'svg') {
level.color = ''
level.svg = parseFloat(target.value)
}
updateLevelBackground(levelIndex) updateLevelBackground(levelIndex)
}
save() save()
}
}) })
levelsListEl.addEventListener('click', e => { levelsListEl.addEventListener('click', e => {
const target= e.target as HTMLButtonElement const target = e.target as HTMLButtonElement
if (target.tagName !== 'BUTTON') return if (target.tagName !== 'BUTTON') return
const resize = target.getAttribute('data-offset-level-size') const resize = target.getAttribute('data-offset-level-size')
@ -181,8 +192,8 @@ levelsListEl.addEventListener('click', e => {
let applying = '' let applying = ''
function colorPixel(e:Event) { function colorPixel(e: Event) {
const target= e.target as HTMLButtonElement const target = e.target as HTMLButtonElement
if (applying === '') return if (applying === '') return
console.log('colorPixel', applying) console.log('colorPixel', applying)
const index = target.getAttribute('data-set-color-of') const index = target.getAttribute('data-set-color-of')
@ -194,18 +205,18 @@ function colorPixel(e:Event) {
} }
} }
function setBrick(levelIndex:number, index:number, chr:string) { function setBrick(levelIndex: number, index: number, chr: string) {
const bricks = allLevels[levelIndex].bricks const bricks = allLevels[levelIndex].bricks
allLevels[levelIndex].bricks = bricks.substring(0, index) + chr + bricks.substring(index + 1); allLevels[levelIndex].bricks = bricks.substring(0, index) + chr + bricks.substring(index + 1);
} }
let changed=0 let changed = 0
levelsListEl.addEventListener('mousedown', e => { levelsListEl.addEventListener('mousedown', e => {
const target= e.target as HTMLButtonElement const target = e.target as HTMLButtonElement
const index = target.getAttribute('data-set-color-of') const index = target.getAttribute('data-set-color-of')
const level = target.getAttribute('data-level') const level = target.getAttribute('data-level')
if ( index && level) { if (index && level) {
changed=0 changed = 0
const before = allLevels[parseInt(level)].bricks[parseInt(index)] || '' const before = allLevels[parseInt(level)].bricks[parseInt(index)] || ''
applying = before === currentCode ? '_' : currentCode applying = before === currentCode ? '_' : currentCode
console.log({before, applying, currentCode}) console.log({before, applying, currentCode})
@ -220,15 +231,16 @@ levelsListEl.addEventListener('mouseenter', e => {
} }
}, true); }, true);
document.addEventListener('mouseup', (e:Event) => { document.addEventListener('mouseup', (e: Event) => {
applying = ''; applying = '';
if(changed) { if (changed) {
save() save()
}; }
;
}); });
(document.getElementById('new-level') as HTMLButtonElement).addEventListener('click', (e:Event) => { (document.getElementById('new-level') as HTMLButtonElement).addEventListener('click', (e: Event) => {
const name = prompt("Name ? ") const name = prompt("Name ? ")
if (!name) return; if (!name) return;
@ -238,7 +250,7 @@ document.addEventListener('mouseup', (e:Event) => {
size: 8, size: 8,
bricks: '________________________________________________________________', bricks: '________________________________________________________________',
svg: null, svg: null,
color:'' color: ''
}) })
const levelIndex = allLevels.length - 1 const levelIndex = allLevels.length - 1
addLevelEditorToList(allLevels[levelIndex], levelIndex) addLevelEditorToList(allLevels[levelIndex], levelIndex)
@ -256,13 +268,3 @@ function save() {
body: JSON.stringify(allLevels, null, 2) body: JSON.stringify(allLevels, null, 2)
}) })
} }
function hashCode(string:string) {
let hash = 0;
for (let i = 0; i < string.length; i++) {
let code = string.charCodeAt(i);
hash = ((hash << 5) - hash) + code;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash);
}

View file

@ -3,8 +3,7 @@ import _palette from "./palette.json";
import _rawLevelsList from "./levels.json"; import _rawLevelsList from "./levels.json";
import _appVersion from "./version.json"; import _appVersion from "./version.json";
import { rawUpgrades } from "./rawUpgrades"; import { rawUpgrades } from "./rawUpgrades";
import _backgrounds from "./backgrounds.json"; import {getLevelBackground} from "./getLevelBackground";
const backgrounds = _backgrounds as string[];
const palette = _palette as Palette; const palette = _palette as Palette;
const rawLevelsList = _rawLevelsList as RawLevel[]; const rawLevelsList = _rawLevelsList as RawLevel[];
@ -50,7 +49,7 @@ function levelIconHTML(
} }
} }
} }
// I don't think many blind people will benefit for this but it's nice to have something to put in "alt" // I don't think many blind people will benefit for this, but it's nice to have something to put in "alt"
return `<img alt="${levelName}" width="${size}" height="${size}" src="${c.toDataURL()}"/>`; return `<img alt="${levelName}" width="${size}" height="${size}" src="${c.toDataURL()}"/>`;
} }
@ -64,16 +63,11 @@ export const allLevels = rawLevelsList
.slice(0, level.size * level.size); .slice(0, level.size * level.size);
const icon = levelIconHTML(bricks, level.size, level.name, level.color); const icon = levelIconHTML(bricks, level.size, level.name, level.color);
icons[level.name] = icon; icons[level.name] = icon;
let svg = level.svg !== null && backgrounds[level.svg];
if (!level.color && !svg) {
svg = backgrounds[hashCode(level.name) % backgrounds.length];
}
return { return {
...level, ...level,
bricks, bricks,
icon, icon,
svg, svg:getLevelBackground(level),
}; };
}) })
.filter((l) => !l.name.startsWith("icon:")) .filter((l) => !l.name.startsWith("icon:"))
@ -92,13 +86,3 @@ export const upgrades = rawUpgrades.map((u) => ({
...u, ...u,
icon: icons["icon:" + u.id], icon: icons["icon:" + u.id],
})) as Upgrade[]; })) as Upgrade[];
function hashCode(string: string) {
let hash = 0;
for (let i = 0; i < string.length; i++) {
let code = string.charCodeAt(i);
hash = (hash << 5) - hash + code;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash);
}