Pause when tab is hidden, using visibility change api

This commit is contained in:
Renan LE CARO 2025-03-15 10:34:01 +01:00
parent 1a56b5f1d1
commit 33d74e8c84
68 changed files with 7290 additions and 6933 deletions

View file

@ -1,58 +1,69 @@
import {GameState} from "./types";
import {sounds} from "./sounds";
import { GameState } from "./types";
import { sounds } from "./sounds";
export function baseCombo(gameState: GameState) {
return 1 + gameState.perks.base_combo * 3 + gameState.perks.smaller_puck * 5;
return 1 + gameState.perks.base_combo * 3 + gameState.perks.smaller_puck * 5;
}
export function resetCombo(gameState: GameState, x: number | undefined, y: number | undefined) {
const prev = gameState.combo;
gameState.combo = baseCombo(gameState);
if (!gameState.levelTime) {
gameState.combo += gameState.perks.hot_start * 15;
export function resetCombo(
gameState: GameState,
x: number | undefined,
y: number | undefined,
) {
const prev = gameState.combo;
gameState.combo = baseCombo(gameState);
if (!gameState.levelTime) {
gameState.combo += gameState.perks.hot_start * 15;
}
if (prev > gameState.combo && gameState.perks.soft_reset) {
gameState.combo += Math.floor(
(prev - gameState.combo) / (1 + gameState.perks.soft_reset),
);
}
const lost = Math.max(0, prev - gameState.combo);
if (lost) {
for (let i = 0; i < lost && i < 8; i++) {
setTimeout(() => sounds.comboDecrease(), i * 100);
}
if (prev > gameState.combo && gameState.perks.soft_reset) {
gameState.combo += Math.floor((prev - gameState.combo) / (1 + gameState.perks.soft_reset));
if (typeof x !== "undefined" && typeof y !== "undefined") {
gameState.flashes.push({
type: "text",
text: "-" + lost,
time: gameState.levelTime,
color: "red",
x: x,
y: y,
duration: 150,
size: gameState.puckHeight,
});
}
const lost = Math.max(0, prev - gameState.combo);
if (lost) {
for (let i = 0; i < lost && i < 8; i++) {
setTimeout(() => sounds.comboDecrease(), i * 100);
}
if (typeof x !== "undefined" && typeof y !== "undefined") {
gameState.flashes.push({
type: "text",
text: "-" + lost,
time: gameState.levelTime,
color: "red",
x: x,
y: y,
duration: 150,
size: gameState.puckHeight,
});
}
}
return lost;
}
return lost;
}
export function decreaseCombo(gameState: GameState, by: number, x: number, y: number) {
const prev = gameState.combo;
gameState.combo = Math.max(baseCombo(gameState), gameState.combo - by);
const lost = Math.max(0, prev - gameState.combo);
export function decreaseCombo(
gameState: GameState,
by: number,
x: number,
y: number,
) {
const prev = gameState.combo;
gameState.combo = Math.max(baseCombo(gameState), gameState.combo - by);
const lost = Math.max(0, prev - gameState.combo);
if (lost) {
sounds.comboDecrease();
if (typeof x !== "undefined" && typeof y !== "undefined") {
gameState.flashes.push({
type: "text",
text: "-" + lost,
time: gameState.levelTime,
color: "red",
x: x,
y: y,
duration: 300,
size: gameState.puckHeight,
});
}
if (lost) {
sounds.comboDecrease();
if (typeof x !== "undefined" && typeof y !== "undefined") {
gameState.flashes.push({
type: "text",
text: "-" + lost,
time: gameState.levelTime,
color: "red",
x: x,
y: y,
duration: 300,
size: gameState.puckHeight,
});
}
}
}
}

View file

@ -1,9 +1,10 @@
* {
font-family: Courier New,
Courier,
Lucida Sans Typewriter,
Lucida Typewriter,
monospace;
font-family:
Courier New,
Courier,
Lucida Sans Typewriter,
Lucida Typewriter,
monospace;
box-sizing: border-box;
}
@ -50,7 +51,6 @@ body {
background: rgba(0, 0, 0, 0.3);
cursor: pointer;
}
}
#score {
@ -66,7 +66,6 @@ body {
}
}
.popup {
position: fixed;
inset: 0;
@ -199,7 +198,6 @@ body {
}
}
/*Unlocks progress bar*/
.progress {
display: block;
@ -239,7 +237,6 @@ body {
}
}
#level-recording-container {
max-width: 400px;
text-align: center;
@ -270,7 +267,6 @@ body {
}
}
.histogram {
display: flex;
gap: 10px;
@ -311,10 +307,9 @@ body {
left: 50%;
transform: translate(-50%, 0);
}
}
}
&> span:not(:hover):not(.active) > span > span {
& > span:not(:hover):not(.active) > span > span {
opacity: 0;
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,49 +1,54 @@
import {getMajorityValue, makeEmptyPerksMap, sample, sumOfKeys} from "./game_utils";
import {Upgrade} from "./types";
import {
getMajorityValue,
makeEmptyPerksMap,
sample,
sumOfKeys,
} from "./game_utils";
import { Upgrade } from "./types";
describe('getMajorityValue', ()=>{
it('returns the most common string',()=>{
expect(getMajorityValue(['1','1','2','2','3','2','3','2','2','1'])).toStrictEqual('2')
})
it('returns the only string',()=>{
expect(getMajorityValue(['1'])).toStrictEqual('1')
})
it('returns nothing for empty array',()=>{
expect(getMajorityValue([])).toStrictEqual(undefined)
})
})
describe('sample', ()=>{
it('returns a random pick from the array',()=>{
expect(['1','2','3'].includes(sample(['1','2','3']))).toBeTruthy()
})
it('returns the only item if there is just one',()=>{
expect(sample(['1'])).toStrictEqual('1')
})
it('returns nothing for empty array',()=>{
expect(sample([])).toStrictEqual(undefined)
})
})
describe('sumOfKeys', ()=>{
it('returns the sum of the keys of an array',()=>{
expect(sumOfKeys({a:1,b:2})).toEqual(3)
})
it('returns 0 for an empty object',()=>{
expect(sumOfKeys({})).toEqual(0)
})
it('returns 0 for undefined',()=>{
expect(sumOfKeys(undefined)).toEqual(0)
})
it('returns 0 for null',()=>{
expect(sumOfKeys(null)).toEqual(0)
})
})
describe('makeEmptyPerksMap', ()=>{
it('returns an object',()=>{
expect(makeEmptyPerksMap([{id:"ball_attract_ball"}])).toEqual({ball_attract_ball:0})
expect(makeEmptyPerksMap([])).toEqual({})
})
})
describe("getMajorityValue", () => {
it("returns the most common string", () => {
expect(
getMajorityValue(["1", "1", "2", "2", "3", "2", "3", "2", "2", "1"]),
).toStrictEqual("2");
});
it("returns the only string", () => {
expect(getMajorityValue(["1"])).toStrictEqual("1");
});
it("returns nothing for empty array", () => {
expect(getMajorityValue([])).toStrictEqual(undefined);
});
});
describe("sample", () => {
it("returns a random pick from the array", () => {
expect(["1", "2", "3"].includes(sample(["1", "2", "3"]))).toBeTruthy();
});
it("returns the only item if there is just one", () => {
expect(sample(["1"])).toStrictEqual("1");
});
it("returns nothing for empty array", () => {
expect(sample([])).toStrictEqual(undefined);
});
});
describe("sumOfKeys", () => {
it("returns the sum of the keys of an array", () => {
expect(sumOfKeys({ a: 1, b: 2 })).toEqual(3);
});
it("returns 0 for an empty object", () => {
expect(sumOfKeys({})).toEqual(0);
});
it("returns 0 for undefined", () => {
expect(sumOfKeys(undefined)).toEqual(0);
});
it("returns 0 for null", () => {
expect(sumOfKeys(null)).toEqual(0);
});
});
describe("makeEmptyPerksMap", () => {
it("returns an object", () => {
expect(makeEmptyPerksMap([{ id: "ball_attract_ball" }])).toEqual({
ball_attract_ball: 0,
});
expect(makeEmptyPerksMap([])).toEqual({});
});
});

View file

@ -1,26 +1,24 @@
import {PerkId, PerksMap, Upgrade} from "./types";
import { PerkId, PerksMap, Upgrade } from "./types";
export function getMajorityValue(arr: string[]): string {
const count: { [k: string]: number } = {};
arr.forEach((v) => (count[v] = (count[v] || 0) + 1));
// Object.values inline polyfill
const max = Math.max(...Object.keys(count).map((k) => count[k]));
return sample(Object.keys(count).filter((k) => count[k] == max));
const count: { [k: string]: number } = {};
arr.forEach((v) => (count[v] = (count[v] || 0) + 1));
// Object.values inline polyfill
const max = Math.max(...Object.keys(count).map((k) => count[k]));
return sample(Object.keys(count).filter((k) => count[k] == max));
}
export function sample<T>(arr: T[]): T {
return arr[Math.floor(arr.length * Math.random())];
return arr[Math.floor(arr.length * Math.random())];
}
export function sumOfKeys(obj:{[key:string]:number} | undefined | null){
if(!obj) return 0
return Object.values(obj)?.reduce((a,b)=>a+b,0) ||0
export function sumOfKeys(obj: { [key: string]: number } | undefined | null) {
if (!obj) return 0;
return Object.values(obj)?.reduce((a, b) => a + b, 0) || 0;
}
export const makeEmptyPerksMap = (upgrades: { id:PerkId }[]) => {
const p = {} as any;
upgrades.forEach((u) => (p[u.id] = 0));
return p as PerksMap;
};
export const makeEmptyPerksMap = (upgrades: { id: PerkId }[]) => {
const p = {} as any;
upgrades.forEach((u) => (p[u.id] = 0));
return p as PerksMap;
};

View file

@ -1,19 +1,17 @@
import {RawLevel} from "./types";
import { RawLevel } from "./types";
import _backgrounds from "./backgrounds.json";
const backgrounds = _backgrounds as string[];
export function getLevelBackground(level:RawLevel){
export function getLevelBackground(level: RawLevel) {
let svg = level.svg !== null && backgrounds[level.svg % backgrounds.length];
let svg = level.svg !== null && backgrounds[level.svg % backgrounds.length];
if (!level.color && !svg) {
svg = backgrounds[hashCode(level.name) % backgrounds.length];
}
return svg
if (!level.color && !svg) {
svg = backgrounds[hashCode(level.name) % backgrounds.length];
}
return svg;
}
export function hashCode(string: string) {
let hash = 0;
for (let i = 0; i < string.length; i++) {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 749 B

After

Width:  |  Height:  |  Size: 715 B

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 479 B

After

Width:  |  Height:  |  Size: 445 B

Before After
Before After

View file

@ -1,47 +1,47 @@
import {moveLevel, resizeLevel, setBrick} from "./levels_editor_util";
import { moveLevel, resizeLevel, setBrick } from "./levels_editor_util";
const baseLevel = {
name: '',
bricks: 'AAAA',
size: 2,
svg: null,
color: ''
}
describe('resizeLevel', () => {
it('should expand levels', () => {
expect(resizeLevel(baseLevel, 1)).toStrictEqual({bricks: 'AA_AA____', size: 3});
})
it('should shrink levels', () => {
expect(resizeLevel(baseLevel, -1)).toStrictEqual({bricks: 'A', size: 1});
})
})
name: "",
bricks: "AAAA",
size: 2,
svg: null,
color: "",
};
describe("resizeLevel", () => {
it("should expand levels", () => {
expect(resizeLevel(baseLevel, 1)).toStrictEqual({
bricks: "AA_AA____",
size: 3,
});
});
it("should shrink levels", () => {
expect(resizeLevel(baseLevel, -1)).toStrictEqual({ bricks: "A", size: 1 });
});
});
describe('moveLevel', () => {
describe("moveLevel", () => {
it("should do nothing when coords are 0/0", () => {
expect(moveLevel(baseLevel, 0, 0)).toStrictEqual({ bricks: "AAAA" });
});
it("should move right", () => {
expect(moveLevel(baseLevel, 1, 0)).toStrictEqual({ bricks: "_A_A" });
});
it("should move left", () => {
expect(moveLevel(baseLevel, -1, 0)).toStrictEqual({ bricks: "A_A_" });
});
it("should move up", () => {
expect(moveLevel(baseLevel, 0, -1)).toStrictEqual({ bricks: "AA__" });
});
it("should move down", () => {
expect(moveLevel(baseLevel, 0, 1)).toStrictEqual({ bricks: "__AA" });
});
});
it('should do nothing when coords are 0/0', () => {
expect(moveLevel(baseLevel, 0, 0)).toStrictEqual({bricks: 'AAAA'});
})
it('should move right', () => {
expect(moveLevel(baseLevel, 1, 0)).toStrictEqual({bricks: '_A_A'});
})
it('should move left', () => {
expect(moveLevel(baseLevel, -1, 0)).toStrictEqual({bricks: 'A_A_'});
})
it('should move up', () => {
expect(moveLevel(baseLevel, 0, -1)).toStrictEqual({bricks: 'AA__'});
})
it('should move down', () => {
expect(moveLevel(baseLevel, 0, 1)).toStrictEqual({bricks: '__AA'});
})
})
describe('setBrick', () => {
it('should set the first brick', () => {
expect(setBrick(baseLevel, 0, 'C')).toStrictEqual({bricks: 'CAAA'});
})
it('should any brick', () => {
expect(setBrick(baseLevel, 2, 'C')).toStrictEqual({bricks: 'AACA'});
})
})
describe("setBrick", () => {
it("should set the first brick", () => {
expect(setBrick(baseLevel, 0, "C")).toStrictEqual({ bricks: "CAAA" });
});
it("should any brick", () => {
expect(setBrick(baseLevel, 2, "C")).toStrictEqual({ bricks: "AACA" });
});
});

View file

@ -835,4 +835,4 @@
"bricks": "_W__W_WW__WW____________WW__WW_W__W_",
"svg": null
}
]
]

View file

@ -1,18 +1,17 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<head>
<meta charset="UTF-8" />
<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>"
/>
<link rel="stylesheet" href="./levels_editor.less"/>
<link rel="stylesheet" href="./levels_editor.less" />
</head>
<body>
<div id="app"></div>
</head>
<body>
<div id="app"></div>
<script type="module" src="levels_editor.tsx"></script>
</body>
<script type="module" src="levels_editor.tsx"></script>
</body>
</html>

View file

@ -1,4 +1,3 @@
body {
background: black;
color: white;
@ -15,7 +14,6 @@ body {
button.active {
transform: scale(1.2);
}
}
#levels {
@ -28,7 +26,7 @@ body {
.level-bricks-preview {
position: relative;
}
input[type="number"]{
input[type="number"] {
width: 50px;
}
@ -51,8 +49,5 @@ body {
& > div:nth-child(3) {
grid-area: bricks;
}
}
}

View file

@ -1,11 +1,11 @@
import {Palette, RawLevel} from "./types";
import _backgrounds from './backgrounds.json'
import _palette from './palette.json'
import _allLevels from './levels.json'
import {getLevelBackground, hashCode} from "./getLevelBackground";
import {createRoot} from 'react-dom/client';
import {useCallback, useEffect, useState} from "react";
import {moveLevel, resizeLevel, setBrick} from "./levels_editor_util";
import { Palette, RawLevel } from "./types";
import _backgrounds from "./backgrounds.json";
import _palette from "./palette.json";
import _allLevels from "./levels.json";
import { getLevelBackground, hashCode } from "./getLevelBackground";
import { createRoot } from "react-dom/client";
import { useCallback, useEffect, useState } from "react";
import { moveLevel, resizeLevel, setBrick } from "./levels_editor_util";
const backgrounds = _backgrounds as string[];
@ -13,148 +13,191 @@ const palette = _palette as Palette;
let allLevels = _allLevels as RawLevel[];
function App() {
const [selected, setSelected] = useState("W");
const [applying, setApplying] = useState("");
const [levels, setLevels] = useState(allLevels);
const updateLevel = useCallback(
(index: number, change: Partial<RawLevel>) => {
setLevels((list) =>
list.map((l, li) => (li === index ? { ...l, ...change } : l)),
);
},
[],
);
const [selected, setSelected] = useState('W')
const [applying, setApplying] = useState('')
const [levels, setLevels] = useState(allLevels)
const updateLevel = useCallback((index: number, change: Partial<RawLevel>) => {
setLevels(list => list.map((l, li) => li === index ? {...l, ...change} : l))
}, []);
const deleteLevel = useCallback((li: number) => {
if (confirm("Delete level")) {
setLevels(allLevels.filter((l, i) => i !== li));
}
}, []);
const deleteLevel = useCallback((li: number) => {
if (confirm('Delete level')) {
setLevels(allLevels.filter((l, i) => i !== li))
}
}, [])
useEffect(()=>{
const timoutId= setTimeout(()=>{
return fetch('http://localhost:4400/src/levels.json', {
method: 'POST',
headers: {
'Content-Type': 'text/plain'
},
body: JSON.stringify(levels, null, 2)
});
},500)
return ()=>clearTimeout(timoutId)
},[levels])
return <div onMouseUp={() => {
console.log('mouse up')
setApplying('')
}} >
<div id={"levels"}>
{
levels.map((level, li) => {
const {name, bricks, size, svg, color} = level
const brickButtons = []
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
const index = y * size + x
brickButtons.push(<button
key={index}
onMouseDown={() => {
if(!applying){
console.log(selected, bricks[index],applying)
const color = selected === bricks[index] ? '_' : selected
setApplying(color)
updateLevel(li, setBrick(level, index, color))
}
}}
onMouseEnter={() => {
if (applying) {
updateLevel(li, setBrick(level, index, applying))
}
}}
style={{
background: palette[bricks[index]] || 'transparent',
left: x * 40, top: y * 40, width: 40, height: 40, position: 'absolute'
}}></button>)
}
}
const background = color ? {backgroundImage: 'none', backgroundColor: color} : {
backgroundImage: `url("data:image/svg+xml;UTF8,${encodeURIComponent(getLevelBackground(level) as string)}")`,
backgroundColor: 'transparent'
}
return <div key={li}>
<input type="text" value={name} onChange={e => updateLevel(li, {name: e.target.value})}/>
<div>
<button onClick={() => deleteLevel(li)}>Delete</button>
<button onClick={() => updateLevel(li, resizeLevel(level, -1))}>-</button>
<button onClick={() => updateLevel(li, resizeLevel(level, +1))}>+</button>
<button onClick={() => updateLevel(li, moveLevel(level, -1, 0))}>L</button>
<button onClick={() => updateLevel(li, moveLevel(level, 1, 0))}>R</button>
<button onClick={() => updateLevel(li, moveLevel(level, 0, -1))}>U</button>
<button onClick={() => updateLevel(li, moveLevel(level, 0, 1))}>D</button>
<input type="color" value={level.color || ''}
onChange={e => e.target.value && updateLevel(li, {color: e.target.value})}/>
<input type="number" value={level.svg || (hashCode(level.name) % backgrounds.length)}
onChange={e => !isNaN(parseFloat(e.target.value)) && updateLevel(li, {
color: '',
svg: parseFloat(e.target.value)
})}
/>
</div>
<div className="level-bricks-preview" style={{
width: size * 40,
height: size * 40,
...background
}}>
{brickButtons}
</div>
</div>
useEffect(() => {
const timoutId = setTimeout(() => {
return fetch("http://localhost:4400/src/levels.json", {
method: "POST",
headers: {
"Content-Type": "text/plain",
},
body: JSON.stringify(levels, null, 2),
});
}, 500);
return () => clearTimeout(timoutId);
}, [levels]);
return (
<div
onMouseUp={() => {
setApplying("");
}}
>
<div id={"levels"}>
{levels.map((level, li) => {
const { name, bricks, size, svg, color } = level;
const brickButtons = [];
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
const index = y * size + x;
brickButtons.push(
<button
key={index}
onMouseDown={() => {
if (!applying) {
const color = selected === bricks[index] ? "_" : selected;
setApplying(color);
updateLevel(li, setBrick(level, index, color));
}
)
}}
onMouseEnter={() => {
if (applying) {
updateLevel(li, setBrick(level, index, applying));
}
}}
style={{
background: palette[bricks[index]] || "transparent",
left: x * 40,
top: y * 40,
width: 40,
height: 40,
position: "absolute",
}}
></button>,
);
}
}
</div>
<div id={"palette"}>
const background = color
? { backgroundImage: "none", backgroundColor: color }
: {
backgroundImage: `url("data:image/svg+xml;UTF8,${encodeURIComponent(getLevelBackground(level) as string)}")`,
backgroundColor: "transparent",
};
return (
<div key={li}>
<input
type="text"
value={name}
onChange={(e) => updateLevel(li, { name: e.target.value })}
/>
<div>
<button onClick={() => deleteLevel(li)}>Delete</button>
<button onClick={() => updateLevel(li, resizeLevel(level, -1))}>
-
</button>
<button onClick={() => updateLevel(li, resizeLevel(level, +1))}>
+
</button>
<button
onClick={() => updateLevel(li, moveLevel(level, -1, 0))}
>
L
</button>
<button onClick={() => updateLevel(li, moveLevel(level, 1, 0))}>
R
</button>
<button
onClick={() => updateLevel(li, moveLevel(level, 0, -1))}
>
U
</button>
<button onClick={() => updateLevel(li, moveLevel(level, 0, 1))}>
D
</button>
<input
type="color"
value={level.color || ""}
onChange={(e) =>
e.target.value && updateLevel(li, { color: e.target.value })
}
/>
<input
type="number"
value={level.svg || hashCode(level.name) % backgrounds.length}
onChange={(e) =>
!isNaN(parseFloat(e.target.value)) &&
updateLevel(li, {
color: "",
svg: parseFloat(e.target.value),
})
}
/>
</div>
<div
className="level-bricks-preview"
style={{
width: size * 40,
height: size * 40,
...background,
}}
>
{brickButtons}
</div>
</div>
);
})}
</div>
<div id={"palette"}>
{Object.entries(palette).map(([code, color]) => (
<button
key={code}
className={code === selected ? "active" : ""}
style={{
background: color || "linear-gradient(45deg,black,white)",
display: "inline-block",
width: "40px",
height: "40px",
border: "1px solid black",
}}
onClick={() => setSelected(code)}
></button>
))}
</div>
<button
id="new-level"
onClick={() => {
const name = prompt("Name ? ");
if (!name) return;
setLevels((l) => [
...l,
{
Object.entries(palette).map(([code, color]) => <button
key={code}
className={code === selected ? 'active' : ''}
style={{
background: color || 'linear-gradient(45deg,black,white)',
display: 'inline-block',
width: '40px',
height: '40px',
border: '1px solid black'
}}
onClick={() => setSelected(code)}></button>
)
}
</div>
<button id="new-level" onClick={() => {
const name = prompt("Name ? ")
if (!name) return;
setLevels(l => [...l, {
name,
size: 8,
bricks: '________________________________________________________________',
svg: null,
color: ''
}])
}}>new
</button>
</div>;
name,
size: 8,
bricks:
"________________________________________________________________",
svg: null,
color: "",
},
]);
}}
>
new
</button>
</div>
);
}
const root = createRoot(document.getElementById('app') as HTMLDivElement);
root.render(<App/>);
const root = createRoot(document.getElementById("app") as HTMLDivElement);
root.render(<App />);

View file

@ -1,48 +1,55 @@
import {RawLevel} from "./types";
import { RawLevel } from "./types";
export function resizeLevel(level: RawLevel, sizeDelta: number) {
const {size, bricks} = level
const newSize = Math.max(1, size + sizeDelta)
const newBricks = []
for (let x = 0; x < newSize; x++) {
for (let y = 0; y < newSize; y++) {
newBricks[y * newSize + x] = brickAt(level, x, y )
}
}
return {
size: newSize,
bricks: newBricks.join('')
const { size, bricks } = level;
const newSize = Math.max(1, size + sizeDelta);
const newBricks = [];
for (let x = 0; x < newSize; x++) {
for (let y = 0; y < newSize; y++) {
newBricks[y * newSize + x] = brickAt(level, x, y);
}
}
return {
size: newSize,
bricks: newBricks.join(""),
};
}
export function brickAt(level:RawLevel, x:number,y:number){
return x>=0 && x < level.size && y>= 0 && y< level.size && level.bricks.split('')[y * level.size + x] || '_'
export function brickAt(level: RawLevel, x: number, y: number) {
return (
(x >= 0 &&
x < level.size &&
y >= 0 &&
y < level.size &&
level.bricks.split("")[y * level.size + x]) ||
"_"
);
}
export function moveLevel(level: RawLevel, dx: number, dy: number) {
const {size} = level
const newBricks = new Array(size * size).fill('_')
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
newBricks[y * size + x] = brickAt(level, x - dx, y - dy)
}
}
return {
bricks: newBricks.join('')
const { size } = level;
const newBricks = new Array(size * size).fill("_");
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
newBricks[y * size + x] = brickAt(level, x - dx, y - dy);
}
}
return {
bricks: newBricks.join(""),
};
}
export function setBrick(level: RawLevel, index: number, colorCode: string) {
console.log('setBrick', level.name, index, colorCode)
const {size} = level
const newBricks=[]
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
const brickIndex=y * size + x
newBricks[brickIndex] = (brickIndex === index && colorCode ) || brickAt(level, x , y)
}
const { size } = level;
const newBricks = [];
for (let x = 0; x < size; x++) {
for (let y = 0; y < size; y++) {
const brickIndex = y * size + x;
newBricks[brickIndex] =
(brickIndex === index && colorCode) || brickAt(level, x, y);
}
return {
bricks: newBricks.join('')
}
}
}
return {
bricks: newBricks.join(""),
};
}

View file

@ -1,28 +1,35 @@
import _palette from "./palette.json";
import _rawLevelsList from "./levels.json";
import _appVersion from "./version.json";
describe('json data checks', ()=>{
it('_rawLevelsList has icon levels', ()=>{
expect(_rawLevelsList.filter(l=>l.name.startsWith('icon:')).length).toBeGreaterThan(10)
})
it('_rawLevelsList has non-icon few levels', ()=>{
expect(_rawLevelsList.filter(l=>!l.name.startsWith('icon:')).length).toBeGreaterThan(10)
})
describe("json data checks", () => {
it("_rawLevelsList has icon levels", () => {
expect(
_rawLevelsList.filter((l) => l.name.startsWith("icon:")).length,
).toBeGreaterThan(10);
});
it("_rawLevelsList has non-icon few levels", () => {
expect(
_rawLevelsList.filter((l) => !l.name.startsWith("icon:")).length,
).toBeGreaterThan(10);
});
it('_rawLevelsList has max 5 colors per level', ()=>{
const levelsWithManyBrickColors=_rawLevelsList.filter(l=>{
const uniqueBricks = l.bricks.split('').filter(b=>b!=='_' && b!=='black').filter((a,b,c)=>c.indexOf(a)===b)
return uniqueBricks.length>5
}).map(l=>l.name)
expect(levelsWithManyBrickColors).toEqual([])
})
it('Has a few colors', ()=>{
expect(Object.keys(_palette).length).toBeGreaterThan(10)
})
it('Has an _appVersion', ()=>{
expect(parseInt(_appVersion)).toBeGreaterThan(2000)
})
})
it("_rawLevelsList has max 5 colors per level", () => {
const levelsWithManyBrickColors = _rawLevelsList
.filter((l) => {
const uniqueBricks = l.bricks
.split("")
.filter((b) => b !== "_" && b !== "black")
.filter((a, b, c) => c.indexOf(a) === b);
return uniqueBricks.length > 5;
})
.map((l) => l.name);
expect(levelsWithManyBrickColors).toEqual([]);
});
it("Has a few colors", () => {
expect(Object.keys(_palette).length).toBeGreaterThan(10);
});
it("Has an _appVersion", () => {
expect(parseInt(_appVersion)).toBeGreaterThan(2000);
});
});

View file

@ -3,7 +3,7 @@ import _palette from "./palette.json";
import _rawLevelsList from "./levels.json";
import _appVersion from "./version.json";
import { rawUpgrades } from "./rawUpgrades";
import {getLevelBackground} from "./getLevelBackground";
import { getLevelBackground } from "./getLevelBackground";
const palette = _palette as Palette;
const rawLevelsList = _rawLevelsList as RawLevel[];
@ -16,11 +16,7 @@ const levelIconHTMLCanvasCtx = levelIconHTMLCanvas.getContext("2d", {
alpha: true,
}) as CanvasRenderingContext2D;
function levelIconHTML(
bricks: string[],
levelSize: number,
color: string,
) {
function levelIconHTML(bricks: string[], levelSize: number, color: string) {
const size = 40;
const c = levelIconHTMLCanvas;
const ctx = levelIconHTMLCanvasCtx;
@ -60,13 +56,13 @@ export const allLevels = rawLevelsList
.split("")
.map((c) => palette[c])
.slice(0, level.size * level.size);
const icon = levelIconHTML(bricks, level.size, level.color);
const icon = levelIconHTML(bricks, level.size, level.color);
icons[level.name] = icon;
return {
...level,
bricks,
icon,
svg:getLevelBackground(level),
svg: getLevelBackground(level),
};
})
.filter((l) => !l.name.startsWith("icon:"))

View file

@ -3,17 +3,17 @@
"name": "Breakout 71",
"icons": [
{
"src": "/icon-512.png",
"src": "icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "/icon-128.png",
"src": "icon-128.png",
"sizes": "128x128",
"type": "image/png"
},
{
"src": "/icon-64.png",
"src": "icon-64.png",
"sizes": "64x64",
"type": "image/png"
}

View file

@ -46,7 +46,7 @@ export const options = {
disabled() {
return window.location.search.includes("isInWebView=true");
},
}
},
} as const satisfies { [k: string]: OptionDef };
export type OptionDef = {

View file

@ -1,58 +1,61 @@
import {GameState} from "./types";
import {getMajorityValue} from "./game_utils";
import { GameState } from "./types";
import { getMajorityValue } from "./game_utils";
export function resetBalls(gameState: GameState) {
const count = 1 + (gameState.perks?.multiball || 0);
const perBall = gameState.puckWidth / (count + 1);
gameState.balls = [];
gameState.ballsColor = "#FFF";
if (gameState.perks.picky_eater || gameState.perks.pierce_color) {
gameState.ballsColor = getMajorityValue(gameState.bricks.filter((i) => i)) || "#FFF";
}
for (let i = 0; i < count; i++) {
const x = gameState.puckPosition - gameState.puckWidth / 2 + perBall * (i + 1);
const vx = Math.random() > 0.5 ? gameState.baseSpeed : -gameState.baseSpeed;
const count = 1 + (gameState.perks?.multiball || 0);
const perBall = gameState.puckWidth / (count + 1);
gameState.balls = [];
gameState.ballsColor = "#FFF";
if (gameState.perks.picky_eater || gameState.perks.pierce_color) {
gameState.ballsColor =
getMajorityValue(gameState.bricks.filter((i) => i)) || "#FFF";
}
for (let i = 0; i < count; i++) {
const x =
gameState.puckPosition - gameState.puckWidth / 2 + perBall * (i + 1);
const vx = Math.random() > 0.5 ? gameState.baseSpeed : -gameState.baseSpeed;
gameState.balls.push({
x,
previousX: x,
y: gameState.gameZoneHeight - 1.5 * gameState.ballSize,
previousY: gameState.gameZoneHeight - 1.5 * gameState.ballSize,
vx,
previousVX: vx,
vy: -gameState.baseSpeed,
previousVY: -gameState.baseSpeed,
gameState.balls.push({
x,
previousX: x,
y: gameState.gameZoneHeight - 1.5 * gameState.ballSize,
previousY: gameState.gameZoneHeight - 1.5 * gameState.ballSize,
vx,
previousVX: vx,
vy: -gameState.baseSpeed,
previousVY: -gameState.baseSpeed,
sx: 0,
sy: 0,
sparks: 0,
piercedSinceBounce: 0,
hitSinceBounce: 0,
hitItem: [],
bouncesList: [],
sapperUses: 0,
});
}
sx: 0,
sy: 0,
sparks: 0,
piercedSinceBounce: 0,
hitSinceBounce: 0,
hitItem: [],
bouncesList: [],
sapperUses: 0,
});
}
}
export function putBallsAtPuck(gameState: GameState) {
// This reset could be abused to cheat quite easily
const count = gameState.balls.length;
const perBall = gameState.puckWidth / (count + 1);
gameState.balls.forEach((ball, i) => {
const x = gameState.puckPosition - gameState.puckWidth / 2 + perBall * (i + 1);
ball.x = x;
ball.previousX = x;
ball.y = gameState.gameZoneHeight - 1.5 * gameState.ballSize;
ball.previousY = ball.y;
ball.vx = Math.random() > 0.5 ? gameState.baseSpeed : -gameState.baseSpeed;
ball.previousVX = ball.vx;
ball.vy = -gameState.baseSpeed;
ball.previousVY = ball.vy;
ball.sx = 0;
ball.sy = 0;
ball.hitItem = [];
ball.hitSinceBounce = 0;
ball.piercedSinceBounce = 0;
});
}
// This reset could be abused to cheat quite easily
const count = gameState.balls.length;
const perBall = gameState.puckWidth / (count + 1);
gameState.balls.forEach((ball, i) => {
const x =
gameState.puckPosition - gameState.puckWidth / 2 + perBall * (i + 1);
ball.x = x;
ball.previousX = x;
ball.y = gameState.gameZoneHeight - 1.5 * gameState.ballSize;
ball.previousY = ball.y;
ball.vx = Math.random() > 0.5 ? gameState.baseSpeed : -gameState.baseSpeed;
ball.previousVX = ball.vx;
ball.vy = -gameState.baseSpeed;
ball.previousVY = ball.vy;
ball.sx = 0;
ball.sy = 0;
ball.hitItem = [];
ball.hitSinceBounce = 0;
ball.piercedSinceBounce = 0;
});
}

View file

@ -1,237 +1,237 @@
import {
gameState,
isSettingOn,
} from "./game";
import { gameState, isSettingOn } from "./game";
export const sounds = {
wallBeep: (pan: number) => {
if (!isSettingOn("sound")) return;
createSingleBounceSound(800, pixelsToPan(pan));
},
wallBeep: (pan: number) => {
if (!isSettingOn("sound")) return;
createSingleBounceSound(800, pixelsToPan(pan));
},
comboIncreaseMaybe: (combo: number, x: number, volume: number) => {
if (!isSettingOn("sound")) return;
let delta = 0;
if (!isNaN(lastComboPlayed)) {
if (lastComboPlayed < combo) delta = 1;
if (lastComboPlayed > combo) delta = -1;
}
playShepard(delta, pixelsToPan(x), volume);
lastComboPlayed = combo;
},
comboDecrease() {
if (!isSettingOn("sound")) return;
playShepard(-1, 0.5, 0.5);
},
coinBounce: (pan: number, volume: number) => {
if (!isSettingOn("sound")) return;
createSingleBounceSound(1200, pixelsToPan(pan), volume, 0.1, "triangle");
},
explode: (pan: number) => {
if (!isSettingOn("sound")) return;
createExplosionSound(pixelsToPan(pan));
},
lifeLost(pan: number) {
if (!isSettingOn("sound")) return;
createShatteredGlassSound(pixelsToPan(pan));
},
coinCatch(pan: number) {
if (!isSettingOn("sound")) return;
createSingleBounceSound(900, pixelsToPan(pan), 0.8, 0.1, "triangle");
},
colorChange(pan: number, volume: number) {
createSingleBounceSound(400, pixelsToPan(pan), volume , 0.5, "sine")
createSingleBounceSound(800, pixelsToPan(pan), volume * 0.5, 0.2, "square")
comboIncreaseMaybe: (combo: number, x: number, volume: number) => {
if (!isSettingOn("sound")) return;
let delta = 0;
if (!isNaN(lastComboPlayed)) {
if (lastComboPlayed < combo) delta = 1;
if (lastComboPlayed > combo) delta = -1;
}
playShepard(delta, pixelsToPan(x), volume);
lastComboPlayed = combo;
},
comboDecrease() {
if (!isSettingOn("sound")) return;
playShepard(-1, 0.5, 0.5);
},
coinBounce: (pan: number, volume: number) => {
if (!isSettingOn("sound")) return;
createSingleBounceSound(1200, pixelsToPan(pan), volume, 0.1, "triangle");
},
explode: (pan: number) => {
if (!isSettingOn("sound")) return;
createExplosionSound(pixelsToPan(pan));
},
lifeLost(pan: number) {
if (!isSettingOn("sound")) return;
createShatteredGlassSound(pixelsToPan(pan));
},
coinCatch(pan: number) {
if (!isSettingOn("sound")) return;
createSingleBounceSound(900, pixelsToPan(pan), 0.8, 0.1, "triangle");
},
colorChange(pan: number, volume: number) {
createSingleBounceSound(400, pixelsToPan(pan), volume, 0.5, "sine");
createSingleBounceSound(800, pixelsToPan(pan), volume * 0.5, 0.2, "square");
},
};
// How to play the code on the leftconst context = new window.AudioContext();
let audioContext: AudioContext,
audioRecordingTrack: MediaStreamAudioDestinationNode;
audioRecordingTrack: MediaStreamAudioDestinationNode;
export function getAudioContext() {
if (!audioContext) {
if (!isSettingOn("sound")) return null;
audioContext = new (window.AudioContext || window.webkitAudioContext)();
audioRecordingTrack = audioContext.createMediaStreamDestination();
}
return audioContext;
if (!audioContext) {
if (!isSettingOn("sound")) return null;
audioContext = new (window.AudioContext || window.webkitAudioContext)();
audioRecordingTrack = audioContext.createMediaStreamDestination();
}
return audioContext;
}
export function getAudioRecordingTrack() {
getAudioContext();
return audioRecordingTrack;
getAudioContext();
return audioRecordingTrack;
}
function createSingleBounceSound(
baseFreq = 800,
pan = 0.5,
volume = 1,
duration = 0.1,
type: OscillatorType = "sine",
baseFreq = 800,
pan = 0.5,
volume = 1,
duration = 0.1,
type: OscillatorType = "sine",
) {
const context = getAudioContext();
if (!context) return;
const oscillator = createOscillator(context, baseFreq, type);
const context = getAudioContext();
if (!context) return;
const oscillator = createOscillator(context, baseFreq, type);
// Create a gain node to control the volume
const gainNode = context.createGain();
oscillator.connect(gainNode);
// Create a gain node to control the volume
const gainNode = context.createGain();
oscillator.connect(gainNode);
// Create a stereo panner node for left-right panning
const panner = context.createStereoPanner();
panner.pan.setValueAtTime(pan * 2 - 1, context.currentTime);
gainNode.connect(panner);
panner.connect(context.destination);
panner.connect(audioRecordingTrack);
// Create a stereo panner node for left-right panning
const panner = context.createStereoPanner();
panner.pan.setValueAtTime(pan * 2 - 1, context.currentTime);
gainNode.connect(panner);
panner.connect(context.destination);
panner.connect(audioRecordingTrack);
// Set up the gain envelope to simulate the impact and quick decay
gainNode.gain.setValueAtTime(0.8 * volume, context.currentTime); // Initial impact
gainNode.gain.exponentialRampToValueAtTime(
0.001,
context.currentTime + duration,
); // Quick decay
// Set up the gain envelope to simulate the impact and quick decay
gainNode.gain.setValueAtTime(0.8 * volume, context.currentTime); // Initial impact
gainNode.gain.exponentialRampToValueAtTime(
0.001,
context.currentTime + duration,
); // Quick decay
// Start the oscillator
oscillator.start(context.currentTime);
// Start the oscillator
oscillator.start(context.currentTime);
// Stop the oscillator after the decay
oscillator.stop(context.currentTime + duration);
// Stop the oscillator after the decay
oscillator.stop(context.currentTime + duration);
}
let noiseBuffer: AudioBuffer;
function getNoiseBuffer(context: AudioContext) {
if (!noiseBuffer) {
const bufferSize = context.sampleRate * 2; // 2 seconds
noiseBuffer = context.createBuffer(1, bufferSize, context.sampleRate);
const output = noiseBuffer.getChannelData(0);
if (!noiseBuffer) {
const bufferSize = context.sampleRate * 2; // 2 seconds
noiseBuffer = context.createBuffer(1, bufferSize, context.sampleRate);
const output = noiseBuffer.getChannelData(0);
// Fill the buffer with random noise
for (let i = 0; i < bufferSize; i++) {
output[i] = Math.random() * 2 - 1;
}
// Fill the buffer with random noise
for (let i = 0; i < bufferSize; i++) {
output[i] = Math.random() * 2 - 1;
}
return noiseBuffer;
}
return noiseBuffer;
}
function createExplosionSound(pan = 0.5) {
const context = getAudioContext();
if (!context) return;
// Create an audio buffer
const context = getAudioContext();
if (!context) return;
// Create an audio buffer
// Create a noise source
const noiseSource = context.createBufferSource();
noiseSource.buffer = getNoiseBuffer(context);
// Create a noise source
const noiseSource = context.createBufferSource();
noiseSource.buffer = getNoiseBuffer(context);
// Create a gain node to control the volume
const gainNode = context.createGain();
noiseSource.connect(gainNode);
// Create a gain node to control the volume
const gainNode = context.createGain();
noiseSource.connect(gainNode);
// Create a filter to shape the explosion sound
const filter = context.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.setValueAtTime(1000, context.currentTime); // Set the initial frequency
gainNode.connect(filter);
// Create a filter to shape the explosion sound
const filter = context.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.setValueAtTime(1000, context.currentTime); // Set the initial frequency
gainNode.connect(filter);
// Create a stereo panner node for left-right panning
const panner = context.createStereoPanner();
panner.pan.setValueAtTime(pan * 2 - 1, context.currentTime); // pan 0 to 1 maps to -1 to 1
// Create a stereo panner node for left-right panning
const panner = context.createStereoPanner();
panner.pan.setValueAtTime(pan * 2 - 1, context.currentTime); // pan 0 to 1 maps to -1 to 1
// Connect filter to panner and then to the destination (speakers)
filter.connect(panner);
panner.connect(context.destination);
panner.connect(audioRecordingTrack);
// Connect filter to panner and then to the destination (speakers)
filter.connect(panner);
panner.connect(context.destination);
panner.connect(audioRecordingTrack);
// Ramp down the gain to simulate the explosion's fade-out
gainNode.gain.setValueAtTime(1, context.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, context.currentTime + 1);
// Ramp down the gain to simulate the explosion's fade-out
gainNode.gain.setValueAtTime(1, context.currentTime);
gainNode.gain.exponentialRampToValueAtTime(0.01, context.currentTime + 1);
// Lower the filter frequency over time to create the "explosive" effect
filter.frequency.exponentialRampToValueAtTime(60, context.currentTime + 1);
// Lower the filter frequency over time to create the "explosive" effect
filter.frequency.exponentialRampToValueAtTime(60, context.currentTime + 1);
// Start the noise source
noiseSource.start(context.currentTime);
// Start the noise source
noiseSource.start(context.currentTime);
// Stop the noise source after the sound has played
noiseSource.stop(context.currentTime + 1);
// Stop the noise source after the sound has played
noiseSource.stop(context.currentTime + 1);
}
function pixelsToPan(pan: number) {
return Math.max(
0,
Math.min(1, (pan - gameState.offsetXRoundedDown) / gameState.gameZoneWidthRoundedUp),
);
return Math.max(
0,
Math.min(
1,
(pan - gameState.offsetXRoundedDown) / gameState.gameZoneWidthRoundedUp,
),
);
}
let lastComboPlayed = NaN,
shepard = 6;
shepard = 6;
function playShepard(delta: number, pan: number, volume: number) {
const shepardMax = 11,
factor = 1.05945594920268,
baseNote = 392;
shepard += delta;
if (shepard > shepardMax) shepard = 0;
if (shepard < 0) shepard = shepardMax;
const shepardMax = 11,
factor = 1.05945594920268,
baseNote = 392;
shepard += delta;
if (shepard > shepardMax) shepard = 0;
if (shepard < 0) shepard = shepardMax;
const play = (note: number) => {
const freq = baseNote * Math.pow(factor, note);
const diff = Math.abs(note - shepardMax * 0.5);
const maxDistanceToIdeal = 1.5 * shepardMax;
const vol = Math.max(0, volume * (1 - diff / maxDistanceToIdeal));
createSingleBounceSound(freq, pan, vol);
return freq.toFixed(2) + " at " + Math.floor(vol * 100) + "% diff " + diff;
};
const play = (note: number) => {
const freq = baseNote * Math.pow(factor, note);
const diff = Math.abs(note - shepardMax * 0.5);
const maxDistanceToIdeal = 1.5 * shepardMax;
const vol = Math.max(0, volume * (1 - diff / maxDistanceToIdeal));
createSingleBounceSound(freq, pan, vol);
return freq.toFixed(2) + " at " + Math.floor(vol * 100) + "% diff " + diff;
};
play(1 + shepardMax + shepard);
play(shepard);
play(-1 - shepardMax + shepard);
play(1 + shepardMax + shepard);
play(shepard);
play(-1 - shepardMax + shepard);
}
function createShatteredGlassSound(pan: number) {
const context = getAudioContext();
if (!context) return;
const oscillators = [
createOscillator(context, 3000, "square"),
createOscillator(context, 4500, "square"),
createOscillator(context, 6000, "square"),
];
const gainNode = context.createGain();
const noiseSource = context.createBufferSource();
noiseSource.buffer = getNoiseBuffer(context);
const context = getAudioContext();
if (!context) return;
const oscillators = [
createOscillator(context, 3000, "square"),
createOscillator(context, 4500, "square"),
createOscillator(context, 6000, "square"),
];
const gainNode = context.createGain();
const noiseSource = context.createBufferSource();
noiseSource.buffer = getNoiseBuffer(context);
oscillators.forEach((oscillator) => oscillator.connect(gainNode));
noiseSource.connect(gainNode);
gainNode.gain.setValueAtTime(0.2, context.currentTime);
oscillators.forEach((oscillator) => oscillator.start());
noiseSource.start();
oscillators.forEach((oscillator) =>
oscillator.stop(context.currentTime + 0.2),
);
noiseSource.stop(context.currentTime + 0.2);
gainNode.gain.exponentialRampToValueAtTime(0.001, context.currentTime + 0.2);
oscillators.forEach((oscillator) => oscillator.connect(gainNode));
noiseSource.connect(gainNode);
gainNode.gain.setValueAtTime(0.2, context.currentTime);
oscillators.forEach((oscillator) => oscillator.start());
noiseSource.start();
oscillators.forEach((oscillator) =>
oscillator.stop(context.currentTime + 0.2),
);
noiseSource.stop(context.currentTime + 0.2);
gainNode.gain.exponentialRampToValueAtTime(0.001, context.currentTime + 0.2);
// Create a stereo panner node for left-right panning
const panner = context.createStereoPanner();
panner.pan.setValueAtTime(pan * 2 - 1, context.currentTime);
gainNode.connect(panner);
panner.connect(context.destination);
panner.connect(audioRecordingTrack);
// Create a stereo panner node for left-right panning
const panner = context.createStereoPanner();
panner.pan.setValueAtTime(pan * 2 - 1, context.currentTime);
gainNode.connect(panner);
panner.connect(context.destination);
panner.connect(audioRecordingTrack);
gainNode.connect(panner);
gainNode.connect(panner);
}
// Helper function to create an oscillator with a specific frequency
function createOscillator(
context: AudioContext,
frequency: number,
type: OscillatorType,
context: AudioContext,
frequency: number,
type: OscillatorType,
) {
const oscillator = context.createOscillator();
oscillator.type = type;
oscillator.frequency.setValueAtTime(frequency, context.currentTime);
return oscillator;
const oscillator = context.createOscillator();
oscillator.type = type;
oscillator.frequency.setValueAtTime(frequency, context.currentTime);
return oscillator;
}

View file

@ -1,13 +1,11 @@
// The version of the cache.
const VERSION = '29032991'
const VERSION = "29033834";
// The name of the cache
const CACHE_NAME = `breakout-71-${VERSION}`;
// The static resources that the app needs to function.
const APP_STATIC_RESOURCES = [
"/"
];
const APP_STATIC_RESOURCES = ["/"];
// On install, cache the static resources
self.addEventListener("install", (event) => {
@ -37,7 +35,10 @@ self.addEventListener("activate", (event) => {
});
self.addEventListener("fetch", (event) => {
if (event.request.mode === "navigate" && event.request.url.endsWith('/index.html?isPWA=true')) {
if (
event.request.mode === "navigate" &&
event.request.url.endsWith("/index.html?isPWA=true")
) {
event.respondWith(caches.match("/"));
return;
}

View file

@ -1,5 +1,7 @@
if ("serviceWorker" in navigator &&
window.location.search.includes("isPWA=true")) {
// @ts-ignore
navigator.serviceWorker.register(new URL('sw-b71.js', import.meta.url));
}
if (
"serviceWorker" in navigator &&
window.location.search.includes("isPWA=true")
) {
// @ts-ignore
navigator.serviceWorker.register(new URL("sw-b71.js", import.meta.url));
}

374
src/types.d.ts vendored
View file

@ -1,243 +1,243 @@
import {rawUpgrades} from "./rawUpgrades";
import { rawUpgrades } from "./rawUpgrades";
export type colorString = string;
export type RawLevel = {
name: string;
size: number;
bricks: string;
svg: number | null;
color: string;
name: string;
size: number;
bricks: string;
svg: number | null;
color: string;
};
export type Level = {
name: string;
size: number;
bricks: colorString[];
svg: string;
color: string;
threshold: number;
sortKey: number;
name: string;
size: number;
bricks: colorString[];
svg: string;
color: string;
threshold: number;
sortKey: number;
};
export type Palette = { [k: string]: string };
export type Upgrade = {
threshold: number;
giftable: boolean;
id: PerkId;
name: string;
icon: string;
max: number;
help: (lvl: number) => string;
fullHelp: string;
requires: PerkId | "";
threshold: number;
giftable: boolean;
id: PerkId;
name: string;
icon: string;
max: number;
help: (lvl: number) => string;
fullHelp: string;
requires: PerkId | "";
};
export type PerkId = (typeof rawUpgrades)[number]["id"];
declare global {
interface Window {
webkitAudioContext?: typeof AudioContext;
}
interface Window {
webkitAudioContext?: typeof AudioContext;
}
interface Document {
webkitFullscreenEnabled?: boolean;
webkitCancelFullScreen?: () => void;
}
interface Document {
webkitFullscreenEnabled?: boolean;
webkitCancelFullScreen?: () => void;
}
interface Element {
webkitRequestFullscreen: typeof Element.requestFullscreen;
}
interface Element {
webkitRequestFullscreen: typeof Element.requestFullscreen;
}
interface MediaStream {
// https://devdoc.net/web/developer.mozilla.org/en-US/docs/Web/API/CanvasCaptureMediaStream.html
// On firefox, the capture stream has the requestFrame option
// instead of the track, go figure
requestFrame?: () => void;
}
interface MediaStream {
// https://devdoc.net/web/developer.mozilla.org/en-US/docs/Web/API/CanvasCaptureMediaStream.html
// On firefox, the capture stream has the requestFrame option
// instead of the track, go figure
requestFrame?: () => void;
}
}
export type BallLike = {
x: number;
y: number;
vx?: number;
vy?: number;
x: number;
y: number;
vx?: number;
vy?: number;
};
export type Coin = {
points: number;
color: colorString;
x: number;
y: number;
size: number;
previousX: number;
previousY: number;
vx: number;
vy: number;
sx: number;
sy: number;
a: number;
sa: number;
weight: number;
destroyed?: boolean;
coloredABrick?: boolean;
points: number;
color: colorString;
x: number;
y: number;
size: number;
previousX: number;
previousY: number;
vx: number;
vy: number;
sx: number;
sy: number;
a: number;
sa: number;
weight: number;
destroyed?: boolean;
coloredABrick?: boolean;
};
export type Ball = {
x: number;
previousX: number;
y: number;
previousY: number;
vx: number;
vy: number;
previousVX: number;
previousVY: number;
sx: number;
sy: number;
sparks: number;
piercedSinceBounce: number;
hitSinceBounce: number;
hitItem: { index: number; color: string }[];
bouncesList: { x: number; y: number }[];
sapperUses: number;
destroyed?: boolean;
x: number;
previousX: number;
y: number;
previousY: number;
vx: number;
vy: number;
previousVX: number;
previousVY: number;
sx: number;
sy: number;
sparks: number;
piercedSinceBounce: number;
hitSinceBounce: number;
hitItem: { index: number; color: string }[];
bouncesList: { x: number; y: number }[];
sapperUses: number;
destroyed?: boolean;
};
interface BaseFlash {
time: number;
color: colorString;
duration: number;
size: number;
destroyed?: boolean;
x: number;
y: number;
time: number;
color: colorString;
duration: number;
size: number;
destroyed?: boolean;
x: number;
y: number;
}
interface ParticleFlash extends BaseFlash {
type: "particle";
vx: number;
vy: number;
ethereal: boolean;
type: "particle";
vx: number;
vy: number;
ethereal: boolean;
}
interface TextFlash extends BaseFlash {
type: "text";
text: string;
type: "text";
text: string;
}
interface BallFlash extends BaseFlash {
type: "ball";
type: "ball";
}
export type Flash = ParticleFlash | TextFlash | BallFlash;
export type RunStats = {
started: number;
levelsPlayed: number;
runTime: number;
coins_spawned: number;
score: number;
bricks_broken: number;
misses: number;
balls_lost: number;
puck_bounces: number;
upgrades_picked: number;
max_combo: number;
max_level: number;
started: number;
levelsPlayed: number;
runTime: number;
coins_spawned: number;
score: number;
bricks_broken: number;
misses: number;
balls_lost: number;
puck_bounces: number;
upgrades_picked: number;
max_combo: number;
max_level: number;
};
export type PerksMap = {
[k in PerkId]: number;
[k in PerkId]: number;
};
export type RunHistoryItem = RunStats & {
perks?: PerksMap;
appVersion?: string;
perks?: PerksMap;
appVersion?: string;
};
export type GameState = {
// Width of the canvas element in pixels
canvasWidth: number;
// Height of the canvas element in pixels
canvasHeight: number;
// Distance between the left of the canvas and the left of the leftmost brick, in pixels
offsetX: number;
// Distance between the left of the canvas and the left border of the game area, in pixels.
// Can be 0 when no border is shown
offsetXRoundedDown: number;
// Width of the bricks area, in pixels
gameZoneWidth: number;
// Width of the game area between the left and right borders, in pixels
gameZoneWidthRoundedUp: number;
// Height of the play area, between the top of the canvas and the bottom of the puck.
// Does not include the finger zone on mobile.
gameZoneHeight: number;
// Size of one brick in pixels
brickWidth: number;
// Size of the current level's grid
gridSize: number;
// 0 based index of the current level in the run (level X / 7)
currentLevel: number;
export type GameState = {
// Width of the canvas element in pixels
canvasWidth: number;
// Height of the canvas element in pixels
canvasHeight: number;
// Distance between the left of the canvas and the left of the leftmost brick, in pixels
offsetX: number;
// Distance between the left of the canvas and the left border of the game area, in pixels.
// Can be 0 when no border is shown
offsetXRoundedDown: number;
// Width of the bricks area, in pixels
gameZoneWidth: number;
// Width of the game area between the left and right borders, in pixels
gameZoneWidthRoundedUp: number;
// Height of the play area, between the top of the canvas and the bottom of the puck.
// Does not include the finger zone on mobile.
gameZoneHeight: number;
// Size of one brick in pixels
brickWidth: number;
// Size of the current level's grid
gridSize: number;
// 0 based index of the current level in the run (level X / 7)
currentLevel: number;
// 10 levels selected randomly at start for the run
runLevels: Level[];
// Width of the puck in pixels, changed by some perks and resizes
puckWidth: number;
// perks the user currently has
perks: PerksMap;
// Base speed of the ball in pixels/tick
baseSpeed: number;
// Score multiplier
combo: number;
// Whether the game is running or paused
running: boolean;
// Position of the center of the puck on the canvas in pixels, from the left of the canvas.
puckPosition: number;
// Will be set if the game is about to be paused. Game pause is delayed by a few milliseconds if you pause a few times in a run,
// to avoid abuse of the "release to pause" feature on mobile.
pauseTimeout: NodeJS.Timeout | null;
// Whether the game should be rendered at the next tick, even if the game is paused
needsRender: boolean;
// Current run score
score: number;
// levelTime of the last time the score increase, to render the score differently
lastScoreIncrease: number;
// levelTime of the last explosion, for screen shake
lastExplosion: number;
// High score at the beginning of the run
highScore: number;
// Balls currently in game, game over if it's empty
balls: Ball[];
// Color of the balls, can be changed by some perks
ballsColor: colorString;
// Array of bricks to display. 'black' means bomb. '' means no brick.
bricks: colorString[];
// 10 levels selected randomly at start for the run
runLevels: Level[];
// Width of the puck in pixels, changed by some perks and resizes
puckWidth: number;
// perks the user currently has
perks: PerksMap;
// Base speed of the ball in pixels/tick
baseSpeed: number;
// Score multiplier
combo: number;
// Whether the game is running or paused
running: boolean;
// Position of the center of the puck on the canvas in pixels, from the left of the canvas.
puckPosition: number;
// Will be set if the game is about to be paused. Game pause is delayed by a few milliseconds if you pause a few times in a run,
// to avoid abuse of the "release to pause" feature on mobile.
pauseTimeout: NodeJS.Timeout | null;
// Whether the game should be rendered at the next tick, even if the game is paused
needsRender: boolean;
// Current run score
score: number;
// levelTime of the last time the score increase, to render the score differently
lastScoreIncrease: number;
// levelTime of the last explosion, for screen shake
lastExplosion: number;
// High score at the beginning of the run
highScore: number;
// Balls currently in game, game over if it's empty
balls: Ball[];
// Color of the balls, can be changed by some perks
ballsColor: colorString;
// Array of bricks to display. 'black' means bomb. '' means no brick.
bricks: colorString[];
flashes: Flash[];
coins: Coin[];
levelStartScore: number;
levelMisses: number;
levelSpawnedCoins: number;
lastPlayedCoinGrab: number;
flashes: Flash[];
coins: Coin[];
levelStartScore: number;
levelMisses: number;
levelSpawnedCoins: number;
lastPlayedCoinGrab: number;
MAX_COINS: number;
MAX_PARTICLES: number;
puckColor: colorString;
ballSize: number;
coinSize: number;
puckHeight: number;
totalScoreAtRunStart: number;
isCreativeModeRun: boolean;
pauseUsesDuringRun: number;
keyboardPuckSpeed: number;
lastTick: number;
lastTickDown: number;
runStatistics: RunStats;
lastOffered: Partial<{ [k in PerkId]: number }>;
levelTime: number;
autoCleanUses: number;
}
MAX_COINS: number;
MAX_PARTICLES: number;
puckColor: colorString;
ballSize: number;
coinSize: number;
puckHeight: number;
totalScoreAtRunStart: number;
isCreativeModeRun: boolean;
pauseUsesDuringRun: number;
keyboardPuckSpeed: number;
lastTick: number;
lastTickDown: number;
runStatistics: RunStats;
lastOffered: Partial<{ [k in PerkId]: number }>;
levelTime: number;
autoCleanUses: number;
};
export type RunParams = {
level?: string;
levelToAvoid?: string;
perks?: Partial<PerksMap>
}
level?: string;
levelToAvoid?: string;
perks?: Partial<PerksMap>;
};

View file

@ -1 +1 @@
"29030875"
"29033834"