Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 | 124x 124x 124x 124x 124x 124x 124x | import { DateTime } from 'luxon';
import { Plugin } from '../../model/plugin';
import { Mod } from '../../model/tag';
import { Template } from '../../model/template';
import { RootConfig } from '../root';
const jezzballLabels = {
savedExample: $localize`Saved example`,
savedExampleTitle: $localize`This Ref is read-only; progress will not be saved.`,
pause: $localize`βΈοΈ`,
resume: $localize`β―οΈ`,
slow: $localize`π’`,
fast: $localize`π`,
soundOn: $localize`π`,
soundOff: $localize`π`,
newGame: $localize`New game`,
continue: $localize`Continue`,
confirmNewGame: $localize`This will clear your high score of {score}. Start a new game?`,
level: $localize`Level: {level}`,
lives: $localize`Lives: {lives}`,
filled: $localize`Area Cleared: {filled}%`,
time: $localize`Time Left: {time}`,
score: $localize`Score: {score}`,
wallVertical: $localize`β`,
wallHorizontal: $localize`β`,
levelComplete: $localize`Level {level} complete`,
gameOver: $localize`Game over Β· score {score}`,
finalScore: $localize`Final score {score}`,
help: $localize`Click, press Enter, or tap with two fingers to build a wall. Two-finger alignment sets its direction. Use the arrow keys to move the keyboard cursor. Right-click, Space, or the direction button changes direction. Press P to pause.`,
};
const jezzballLabelsSource = JSON.stringify(jezzballLabels).replace(/</g, '\\u003c');
const scorePlugin: Plugin = {
tag: 'plugin/score',
name: $localize`ποΈ Score`,
config: {
mod: $localize`π£οΈ JezzBall`,
version: 1,
type: 'plugin',
generated: $localize`Generated by jasper-ui ${DateTime.now().toISO()}`,
description: $localize`Store a numeric score on a Ref.`,
sorts: [
{ sort: 'plugins->plugin/score:num', label: $localize`ποΈ score`, title: $localize`Score` },
],
},
defaults: 0,
schema: { type: 'float64' },
};
export const jezzballPlugin: Plugin = {
tag: 'plugin/jezzball',
name: $localize`π£οΈ JezzBall`,
config: {
mod: $localize`π£οΈ JezzBall`,
version: 1,
type: 'plugin',
editingViewer: true,
experimental: true,
submitText: true,
add: true,
genId: true,
export: true,
generated: $localize`Generated by jasper-ui ${DateTime.now().toISO()}`,
description: $localize`Play a faithful remake of the classic JezzBall game.`,
icons: [{ label: $localize`π£οΈ`, order: 2 }],
filters: [
{ query: 'plugin/jezzball', label: $localize`π£οΈ JezzBall`, title: $localize`JezzBall games`, group: $localize`Games πΉοΈ` },
],
// language=Handlebars
infoUi: `{{#if final}}{{#if (lookup ref.plugins "plugin/score")}}<span class="jezzball-final-score">ποΈ {{number (lookup ref.plugins "plugin/score")}}</span>{{/if}}{{/if}}`,
// language=CSS
css: `
.jezzball-game {
display: block;
width: min(100%, 850px);
margin: 0 auto;
color: var(--text, #ddd);
font: 14px system-ui, sans-serif;
font-weight: bold;
outline: none;
}
.jezzball-game * {
box-sizing: border-box;
}
.jezzball-toolbar {
display: flex;
align-items: center;
gap: 12px;
min-height: 46px;
padding: 8px 4px;
}
.jezzball-toolbar .jezzball-level {
font-weight: 600;
white-space: nowrap;
}
.jezzball-level, .jezzball-stat, .jezzball-final-score {
font-variant-numeric: tabular-nums;
}
.jezzball-stat {
position: absolute;
z-index: 1;
color: #eee;
white-space: nowrap;
pointer-events: none;
text-shadow: 0 1px 2px #000;
}
.jezzball-lives {
top: 8px;
left: 10px;
}
.jezzball-center {
position: absolute;
z-index: 1;
top: 8px;
left: 50%;
display: flex;
transform: translateX(-50%);
}
.jezzball-center .jezzball-stat {
position: static;
}
.jezzball-time {
top: 8px;
right: 10px;
}
.jezzball-filled {
bottom: 8px;
left: 50%;
transform: translateX(-50%);
}
.jezzball-example {
color: #e7b85b;
font-weight: 600;
}
.jezzball-controls {
display: flex;
gap: 8px;
margin-left: auto;
}
.jezzball-controls button, .jezzball-overlay button {
border: 1px solid var(--border, #777);
border-radius: 4px;
background: var(--card, #333);
color: var(--text, #eee);
padding: 5px 9px;
cursor: pointer;
}
.jezzball-controls button:hover, .jezzball-overlay button:hover {
background: var(--active, #4a4a4a);
}
.jezzball-stage {
position: relative;
width: 100%;
padding: 34px;
overflow: hidden;
filter: drop-shadow(0px 0px .5px #ffffff);
border-radius: 8px;
background: #000;
touch-action: none;
}
.jezzball-canvas {
display: block;
width: 100%;
height: auto;
aspect-ratio: 4 / 3;
}
.jezzball-canvas.vertical {
cursor: ns-resize;
}
.jezzball-canvas.horizontal {
cursor: ew-resize;
}
.jezzball-overlay {
position: absolute;
inset: 0;
display: none;
place-content: center;
text-align: center;
background: rgba(0, 0, 0, .72);
color: white;
}
.jezzball-overlay.visible {
display: grid;
}
.jezzball-overlay strong {
display: block;
margin-bottom: 12px;
font-size: 24px;
}
.embed:fullscreen > .plugin_jezzball {
zoom: 50%;
margin: 0 auto;
}
:fullscreen .jezzball-game {
width: min(100vw, calc((100vh - 114px) * 4 / 3 + 68px));
max-width: none;
}
:fullscreen .jezzball-controls {
display: none;
}
@media (prefers-color-scheme: light) {
.jezzball-game {
color: var(--text, #333);
}
.jezzball-controls button, .jezzball-overlay button {
background: var(--card, #eee);
color: var(--text, #222);
border-color: var(--border, #999);
}
.jezzball-controls button:hover, .jezzball-overlay button:hover {
background: var(--active, #ddd);
}
}
`,
// language=HTML
snippet: `
<script>
function jezzballApp(root, api) {
if (!root) return function() {};
if (root._jezzballDestroy) {
root._jezzballDestroy();
root.removeAttribute('data-game-session');
}
const COLS = 32;
const ROWS = 24;
const CELL = 25;
const TARGET = 75;
const MAX_BALLS = 50;
const WALL_STEP_SLOW = 0.1;
const WALL_STEP_FAST = 0.05;
const BALL_RADIUS = 0.34;
const LEVEL_SECONDS = 120;
const labels = ${jezzballLabelsSource};
const initial = api && api.initial && typeof api.initial === 'object' ? api.initial : {};
const writable = !api || api.writable !== false;
let savedMap = api.comment;
let level = Number.isSafeInteger(initial.level) && initial.level > 0 ? initial.level : 1;
let score = Number.isFinite(api.score) && api.score >= 0 ? Math.floor(api.score) : 0;
let lives = Number.isSafeInteger(initial.lives) && initial.lives >= 0 ? initial.lives : 3;
let remaining = Number.isFinite(initial.time) && initial.time >= 0 ?
Math.min(initial.time, LEVEL_SECONDS) : LEVEL_SECONDS;
let checkpoint = {
level: level,
lives: lives,
time: remaining,
area: Number.isSafeInteger(initial.area) && initial.area >= 0 && initial.area <= 100 ? initial.area : 0,
final: !!initial.final,
};
let occupied = new Uint8Array(COLS * ROWS);
let balls = [];
let wall = null;
let orientation = 'vertical';
let wallSpeed = 'fast';
let sound = true;
let audioContext = null;
let running = !checkpoint.final;
let paused = false;
let last = 0;
let wallClock = 0;
let frame = 0;
let finalSaved = false;
let keyboardMode = false;
const keyboardCursor = { x: Math.floor(COLS / 2), y: Math.floor(ROWS / 2) };
const canvas = root.querySelector('.jezzball-canvas');
const g = canvas.getContext('2d', { alpha: false });
const levelEl = root.querySelector('.jezzball-level');
const livesEl = root.querySelector('.jezzball-lives');
const filledEl = root.querySelector('.jezzball-filled');
const timeEl = root.querySelector('.jezzball-time');
const scoreEl = root.querySelector('.jezzball-score');
const exampleEl = root.querySelector('.jezzball-example');
const directionButton = root.querySelector('.jezzball-direction');
const speedButton = root.querySelector('.jezzball-speed');
const soundButton = root.querySelector('.jezzball-sound');
const pauseButton = root.querySelector('.jezzball-pause');
const overlay = root.querySelector('.jezzball-overlay');
const overlayMessage = overlay.querySelector('strong');
const newGameButton = overlay.querySelector('.jezzball-new-game');
root.setAttribute('aria-label', labels.help);
exampleEl.textContent = labels.savedExample;
exampleEl.title = labels.savedExampleTitle;
exampleEl.hidden = writable;
pauseButton.textContent = labels.pause;
function format(label, values) {
return label.replace(/\\{(\\w+)\\}/g, function(match, key) {
return Object.prototype.hasOwnProperty.call(values, key) ? values[key] : match;
});
}
function id(x, y) {
return x + y * COLS;
}
function parseMap(map) {
if (typeof map !== 'string') return null;
const rows = map.split('\\n');
if (rows.length !== ROWS || rows.some(row => row.length !== COLS || /[^.#12o]/.test(row))) return null;
return rows;
}
function serializeMap(includeWall) {
const cells = Array.from({ length: ROWS }, function(_, y) {
return Array.from({ length: COLS }, function(_, x) {
return occupied[id(x, y)] ? '#' : '.';
});
});
if (includeWall && wall) {
for (const half of [wall.negative, wall.positive]) {
if (half.destroyed) continue;
for (const cellId of half.cells) {
cells[Math.floor(cellId / COLS)][cellId % COLS] = String(half.color);
}
}
}
for (const ball of balls) {
const ballX = Math.max(0, Math.min(COLS - 1, Math.floor(ball.x)));
const ballY = Math.max(0, Math.min(ROWS - 1, Math.floor(ball.y)));
let saved = false;
for (let radius = 0; radius < Math.max(COLS, ROWS) && !saved; radius++) {
for (let y = Math.max(0, ballY - radius); y <= Math.min(ROWS - 1, ballY + radius) && !saved; y++) {
for (let x = Math.max(0, ballX - radius); x <= Math.min(COLS - 1, ballX + radius); x++) {
if (Math.max(Math.abs(x - ballX), Math.abs(y - ballY)) !== radius || cells[y][x] !== '.') continue;
cells[y][x] = 'o';
saved = true;
break;
}
}
}
}
return cells.map(row => row.join('')).join('\\n');
}
function emptyMap() {
return Array(ROWS).fill('.'.repeat(COLS)).join('\\n');
}
function isOccupied(x, y) {
return x < 0 || y < 0 || x >= COLS || y >= ROWS || occupied[id(x, y)] !== 0;
}
function cellBlocked(x, y) {
if (isOccupied(x, y)) return true;
const cellId = id(x, y);
return !!(wall && (wall.negative.cells.has(cellId) || wall.positive.cells.has(cellId)));
}
function randomVelocity() {
const component = ballSpeed() / Math.SQRT2;
return {
vx: component * (Math.random() < 0.5 ? -1 : 1),
vy: component * (Math.random() < 0.5 ? -1 : 1),
};
}
function ballSpeed() {
const wallStep = wallSpeed === 'slow' ? WALL_STEP_SLOW : WALL_STEP_FAST;
return 1 / (wallStep * 2);
}
function placeBalls() {
balls = [];
for (let i = 0; i < Math.min(level + 1, MAX_BALLS); i++) {
const velocity = randomVelocity();
let x;
let y;
let attempts = 0;
do {
x = 2 + Math.random() * (COLS - 4);
y = 2 + Math.random() * (ROWS - 4);
attempts++;
} while (balls.some(ball => Math.hypot(ball.x - x, ball.y - y) < 2) && attempts < 100);
balls.push({ x: x, y: y, vx: velocity.vx, vy: velocity.vy, spin: Math.random() * Math.PI * 2 });
}
}
function restoreBalls() {
const map = parseMap(savedMap);
if (!map) return false;
const positions = [];
for (let y = 0; y < ROWS; y++) {
for (let x = 0; x < COLS; x++) {
if (map[y][x] === 'o') positions.push({ x: x + 0.5, y: y + 0.5 });
}
}
if (!positions.length) return false;
balls = positions.map(function(position) {
const velocity = randomVelocity();
return { x: position.x, y: position.y, vx: velocity.vx, vy: velocity.vy, spin: Math.random() * Math.PI * 2 };
});
return true;
}
function resetLevel() {
occupied = new Uint8Array(COLS * ROWS);
savedMap = emptyMap();
wall = null;
remaining = LEVEL_SECONDS;
paused = false;
running = true;
finalSaved = false;
overlay.classList.remove('visible');
pauseButton.textContent = labels.pause;
placeBalls();
lives = balls.length;
updateHud();
}
function percentFilled() {
if (checkpoint.final || overlay.classList.contains('visible')) return checkpoint.area;
let count = 0;
for (const value of occupied) {
if (value) count++;
}
return Math.floor(count * 100 / occupied.length);
}
function updateHud() {
levelEl.textContent = format(labels.level, { level: level });
livesEl.textContent = format(labels.lives, { lives: Math.max(0, lives) });
filledEl.textContent = format(labels.filled, { filled: percentFilled() });
timeEl.textContent = format(labels.time, { time: Math.max(0, Math.ceil(remaining)) });
scoreEl.textContent = format(labels.score, { score: score });
directionButton.textContent = orientation === 'vertical' ? labels.wallVertical : labels.wallHorizontal;
speedButton.textContent = wallSpeed === 'slow' ? labels.slow : labels.fast;
soundButton.textContent = sound ? labels.soundOn : labels.soundOff;
canvas.classList.toggle('vertical', orientation === 'vertical');
canvas.classList.toggle('horizontal', orientation === 'horizontal');
}
function toggleOrientation() {
orientation = orientation === 'vertical' ? 'horizontal' : 'vertical';
updateHud();
}
function toggleSpeed() {
wallSpeed = wallSpeed === 'slow' ? 'fast' : 'slow';
const component = ballSpeed() / Math.SQRT2;
for (const ball of balls) {
ball.vx = Math.sign(ball.vx) * component;
ball.vy = Math.sign(ball.vy) * component;
}
updateHud();
}
function toggleSound() {
sound = !sound;
updateHud();
}
function playSound(frequency, duration) {
if (!sound) return;
const AudioContext = window.AudioContext || window.webkitAudioContext;
if (!AudioContext) return;
audioContext = audioContext || new AudioContext();
if (audioContext.state === 'suspended') audioContext.resume();
const oscillator = audioContext.createOscillator();
const gain = audioContext.createGain();
oscillator.frequency.value = frequency;
gain.gain.setValueAtTime(0.04, audioContext.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, audioContext.currentTime + duration);
oscillator.connect(gain);
gain.connect(audioContext.destination);
oscillator.start();
oscillator.stop(audioContext.currentTime + duration);
}
function startWall(x, y) {
x = Math.floor(x);
y = Math.floor(y);
if (!running || paused || wall || cellBlocked(x, y)) return;
if (balls.some(ball => circleTouchesCell(ball.x, ball.y, x, y))) return;
wall = {
orientation: orientation,
origin: { x: x, y: y },
negative: { x: x, y: y, done: false, destroyed: false, color: 2, cells: new Set([id(x, y)]) },
positive: { x: x, y: y, done: false, destroyed: false, color: 1, cells: new Set([id(x, y)]) },
};
wallClock = 0;
playSound(260, 0.04);
}
function circleTouchesCell(x, y, cellX, cellY) {
const closestX = Math.max(cellX, Math.min(x, cellX + 1));
const closestY = Math.max(cellY, Math.min(y, cellY + 1));
return Math.hypot(x - closestX, y - closestY) <= BALL_RADIUS;
}
function extendEnd(end, direction) {
if (!wall || end.done || end.destroyed) return false;
const dx = wall.orientation === 'horizontal' ? direction : 0;
const dy = wall.orientation === 'vertical' ? direction : 0;
const nx = end.x + dx;
const ny = end.y + dy;
if (isOccupied(nx, ny)) {
end.done = true;
const sibling = end === wall.negative ? wall.positive : wall.negative;
for (const cellId of end.cells) {
occupied[cellId] = 3;
sibling.cells.delete(cellId);
}
end.cells.clear();
return false;
}
end.x = nx;
end.y = ny;
end.cells.add(id(nx, ny));
return true;
}
function fillCapturedAreas() {
const reachable = new Uint8Array(COLS * ROWS);
const queue = [];
for (const ball of balls) {
const minX = Math.max(0, Math.floor(ball.x - BALL_RADIUS));
const maxX = Math.min(COLS - 1, Math.floor(ball.x + BALL_RADIUS));
const minY = Math.max(0, Math.floor(ball.y - BALL_RADIUS));
const maxY = Math.min(ROWS - 1, Math.floor(ball.y + BALL_RADIUS));
for (let y = minY; y <= maxY; y++) {
for (let x = minX; x <= maxX; x++) {
const ballId = id(x, y);
if (!occupied[ballId] && !reachable[ballId] && circleTouchesCell(ball.x, ball.y, x, y)) {
reachable[ballId] = 1;
queue.push(ballId);
}
}
}
}
for (let head = 0; head < queue.length; head++) {
const current = queue[head];
const x = current % COLS;
const y = Math.floor(current / COLS);
const neighbors = [[x - 1, y], [x + 1, y], [x, y - 1], [x, y + 1]];
for (const neighbor of neighbors) {
const nx = neighbor[0];
const ny = neighbor[1];
if (nx < 0 || ny < 0 || nx >= COLS || ny >= ROWS) continue;
const neighborId = id(nx, ny);
if (!occupied[neighborId] && !reachable[neighborId]) {
reachable[neighborId] = 1;
queue.push(neighborId);
}
}
}
for (let i = 0; i < occupied.length; i++) {
if (!occupied[i] && !reachable[i]) occupied[i] = 3;
}
}
function pushBallsOutOfWalls() {
for (const ball of balls) {
if (!hitsBoard(ball.x, ball.y)) continue;
const candidates = [];
const minX = Math.max(0, Math.floor(ball.x - BALL_RADIUS));
const maxX = Math.min(COLS - 1, Math.floor(ball.x + BALL_RADIUS));
const minY = Math.max(0, Math.floor(ball.y - BALL_RADIUS));
const maxY = Math.min(ROWS - 1, Math.floor(ball.y + BALL_RADIUS));
for (let y = minY; y <= maxY; y++) {
for (let x = minX; x <= maxX; x++) {
if (!occupied[id(x, y)] || !circleTouchesCell(ball.x, ball.y, x, y)) continue;
candidates.push(
{ x: x - BALL_RADIUS - 0.001, y: ball.y },
{ x: x + 1 + BALL_RADIUS + 0.001, y: ball.y },
{ x: ball.x, y: y - BALL_RADIUS - 0.001 },
{ x: ball.x, y: y + 1 + BALL_RADIUS + 0.001 },
{ x: x - BALL_RADIUS - 0.001, y: y - BALL_RADIUS - 0.001 },
{ x: x + 1 + BALL_RADIUS + 0.001, y: y - BALL_RADIUS - 0.001 },
{ x: x - BALL_RADIUS - 0.001, y: y + 1 + BALL_RADIUS + 0.001 },
{ x: x + 1 + BALL_RADIUS + 0.001, y: y + 1 + BALL_RADIUS + 0.001 },
);
}
}
const available = candidates.filter(position =>
position.x >= BALL_RADIUS && position.x <= COLS - BALL_RADIUS &&
position.y >= BALL_RADIUS && position.y <= ROWS - BALL_RADIUS &&
!hitsBoard(position.x, position.y));
available.sort((a, b) =>
Math.hypot(a.x - ball.x, a.y - ball.y) - Math.hypot(b.x - ball.x, b.y - ball.y));
if (available.length) {
ball.x = available[0].x;
ball.y = available[0].y;
}
}
}
function completeWall() {
if (!wall) return;
if ([wall.negative, wall.positive].every(half => half.destroyed)) {
wall = null;
return;
}
wall = null;
playSound(480, 0.08);
fillCapturedAreas();
pushBallsOutOfWalls();
const filled = percentFilled();
if (filled >= TARGET) {
score += level * 100 + filled * 5 + Math.ceil(remaining) + lives * 25;
level++;
checkpoint = {
level: level,
lives: lives,
time: remaining,
area: filled,
final: false,
};
if (api && typeof api.save === 'function') api.save(serializeMap(false), checkpoint, score);
playSound(720, 0.16);
showMessage(format(labels.levelComplete, { level: level - 1 }), labels.continue, resetLevel);
}
updateHud();
}
function destroyHalf(half) {
half.destroyed = true;
half.cells.clear();
lives--;
playSound(120, 0.18);
if (lives <= 0) {
finishGame();
}
updateHud();
}
function finishGame() {
if (!running) return;
running = false;
paused = false;
playSound(80, 0.3);
const died = lives <= 0;
if (!died) wall = null;
savedMap = serializeMap(died);
checkpoint = {
level: level,
lives: Math.max(0, lives),
time: Math.max(0, remaining),
area: percentFilled(),
final: true,
};
if (!finalSaved && api && typeof api.save === 'function') {
finalSaved = true;
api.save(savedMap, checkpoint, score);
}
showMessage(format(labels.gameOver, { score: score }), labels.newGame, function() {
if (writable && score > 0 && !window.confirm(format(labels.confirmNewGame, { score: score }))) {
overlay.classList.add('visible');
return;
}
level = 1;
score = 0;
checkpoint = {
level: 1,
lives: 2,
time: LEVEL_SECONDS,
area: 0,
final: false,
};
if (writable && api && typeof api.save === 'function') api.save(emptyMap(), checkpoint, score);
resetLevel();
});
}
function showMessage(message, button, callback) {
running = false;
overlayMessage.textContent = message;
newGameButton.textContent = button;
overlay.classList.add('visible');
newGameButton.onclick = function() {
overlay.classList.remove('visible');
callback();
root.focus();
};
}
function ballTouchesHalf(ball, half, direction) {
if (!wall) return false;
const originCell = id(wall.origin.x, wall.origin.y);
for (const cellId of half.cells) {
const x = cellId % COLS;
const y = Math.floor(cellId / COLS);
if (cellId === originCell) {
const sibling = direction < 0 ? wall.positive : wall.negative;
if (!sibling.destroyed) {
const position = wall.orientation === 'horizontal' ? ball.x : ball.y;
const center = (wall.orientation === 'horizontal' ? wall.origin.x : wall.origin.y) + 0.5;
if ((direction < 0) !== (position < center)) continue;
}
}
if (circleTouchesCell(ball.x, ball.y, x, y)) return true;
}
return false;
}
function hitsBoard(x, y) {
const minX = Math.floor(x - BALL_RADIUS);
const maxX = Math.floor(x + BALL_RADIUS);
const minY = Math.floor(y - BALL_RADIUS);
const maxY = Math.floor(y + BALL_RADIUS);
for (let cy = minY; cy <= maxY; cy++) {
for (let cx = minX; cx <= maxX; cx++) {
if (cx < 0 || cy < 0 || cx >= COLS || cy >= ROWS) continue;
if (occupied[id(cx, cy)] && circleTouchesCell(x, y, cx, cy)) return true;
}
}
return false;
}
function updateBalls(dt) {
for (const ball of balls) {
const cellX = Math.floor(ball.x);
const cellY = Math.floor(ball.y);
if (!cellBlocked(cellX, cellY) &&
cellBlocked(cellX - 1, cellY) && cellBlocked(cellX + 1, cellY) &&
cellBlocked(cellX, cellY - 1) && cellBlocked(cellX, cellY + 1)) {
ball.x = cellX + 0.5;
ball.y = cellY + 0.5;
ball.spin -= dt * 7;
continue;
}
const targetX = ball.x + ball.vx * dt;
const targetY = ball.y + ball.vy * dt;
const bouncedX = targetX - BALL_RADIUS < 0 || targetX + BALL_RADIUS > COLS ||
hitsBoard(targetX, ball.y);
const bouncedY = targetY - BALL_RADIUS < 0 || targetY + BALL_RADIUS > ROWS ||
hitsBoard(ball.x, targetY);
if (bouncedX) ball.vx *= -1;
if (bouncedY) ball.vy *= -1;
if (!bouncedX && !bouncedY && hitsBoard(targetX, targetY)) {
ball.vx *= -1;
ball.vy *= -1;
}
ball.x = Math.max(BALL_RADIUS, Math.min(COLS - BALL_RADIUS, ball.x + ball.vx * dt));
ball.y = Math.max(BALL_RADIUS, Math.min(ROWS - BALL_RADIUS, ball.y + ball.vy * dt));
ball.spin -= dt * 7;
}
}
function update(dt) {
updateBalls(dt);
if (wall) {
wallClock += dt;
const wallStep = wallSpeed === 'slow' ? WALL_STEP_SLOW : WALL_STEP_FAST;
while (wall && wallClock >= wallStep) {
wallClock -= wallStep;
extendEnd(wall.negative, -1);
extendEnd(wall.positive, 1);
const hitHalves = [[wall.negative, -1], [wall.positive, 1]].filter(([half, direction]) =>
!half.done && !half.destroyed && balls.some(ball => ballTouchesHalf(ball, half, direction)));
for (const [half] of hitHalves) {
destroyHalf(half);
}
if (!running || !wall) break;
if (wall && [wall.negative, wall.positive].every(half => half.done || half.destroyed)) completeWall();
}
}
remaining -= dt;
if (remaining <= 0) finishGame();
}
function draw() {
g.fillStyle = '#777';
g.fillRect(0, 0, canvas.width, canvas.height);
g.strokeStyle = 'rgba(255,255,255,.08)';
g.lineWidth = 1;
for (let x = 0; x < COLS; x++) {
g.beginPath();
g.moveTo((x + 0.5) * CELL, 0);
g.lineTo((x + 0.5) * CELL, canvas.height);
g.stroke();
}
for (let y = 0; y < ROWS; y++) {
g.beginPath();
g.moveTo(0, (y + 0.5) * CELL);
g.lineTo(canvas.width, (y + 0.5) * CELL);
g.stroke();
}
const background = parseMap(savedMap);
if (background) {
for (let y = 0; y < ROWS; y++) {
for (let x = 0; x < COLS; x++) {
const cell = background[y][x];
if (cell === '.' || cell === 'o') continue;
g.fillStyle = cell === '1' ? '#e3424f' : cell === '2' ? '#2f8ee5' : '#000';
g.fillRect(x * CELL, y * CELL, CELL, CELL);
}
}
for (let y = 0; y < ROWS; y++) {
for (let x = 0; x < COLS; x++) {
const color = background[y][x];
if (color !== '1' && color !== '2') continue;
const direction = color === '1' ? 1 : -1;
const horizontal = [x - 1, x + 1].some(nx =>
nx >= 0 && nx < COLS && (background[y][nx] === '1' || background[y][nx] === '2'));
const vertical = [y - 1, y + 1].some(ny =>
ny >= 0 && ny < ROWS && (background[ny][x] === '1' || background[ny][x] === '2'));
const next = horizontal && !vertical ? background[y][x + direction] :
vertical && !horizontal && background[y + direction] ? background[y + direction][x] : null;
if (next === color) continue;
g.strokeStyle = '#ececf2';
g.lineWidth = 2;
g.strokeRect(x * CELL + 2, y * CELL + 2, CELL - 4, CELL - 4);
g.fillStyle = '#fff';
for (const offsetX of [8, 17]) {
for (const offsetY of [8, 17]) {
g.beginPath();
g.arc(x * CELL + offsetX, y * CELL + offsetY, 2, 0, Math.PI * 2);
g.fill();
}
}
}
}
}
for (let y = 0; y < ROWS; y++) {
for (let x = 0; x < COLS; x++) {
const color = occupied[id(x, y)];
if (color) {
g.fillStyle = '#000';
g.fillRect(x * CELL, y * CELL, CELL, CELL);
}
}
}
if (wall) {
for (const half of [wall.negative, wall.positive]) {
if (half.destroyed) continue;
g.fillStyle = half.color === 1 ? '#e3424f' : '#2f8ee5';
for (const cellId of half.cells) {
const x = cellId % COLS;
const y = Math.floor(cellId / COLS);
g.fillRect(x * CELL + 3, y * CELL + 3, CELL - 6, CELL - 6);
}
if (!half.done) {
g.strokeStyle = '#ececf2';
g.lineWidth = 2;
g.strokeRect(half.x * CELL + 2, half.y * CELL + 2, CELL - 4, CELL - 4);
g.fillStyle = '#fff';
for (const offsetX of [8, 17]) {
for (const offsetY of [8, 17]) {
g.beginPath();
g.arc(half.x * CELL + offsetX, half.y * CELL + offsetY, 2, 0, Math.PI * 2);
g.fill();
}
}
}
}
}
for (const ball of balls) {
const x = ball.x * CELL;
const y = ball.y * CELL;
const radius = BALL_RADIUS * CELL;
const phase = ((ball.spin % (Math.PI * 2)) + Math.PI * 2) % (Math.PI * 2);
const swapped = phase >= Math.PI;
const curve = Math.cos(phase % Math.PI) * radius * 4 / 3;
g.save();
g.beginPath();
g.arc(x, y, radius, 0, 7);
g.clip();
g.fillStyle = swapped ? '#d93643' : '#f4f1e8';
g.fillRect(x - radius, y - radius, radius * 2, radius * 2);
g.fillStyle = swapped ? '#f4f1e8' : '#d93643';
g.beginPath();
g.moveTo(x, y - radius);
g.bezierCurveTo(x + curve, y - radius, x + curve, y + radius, x, y + radius);
g.arc(x, y, radius, Math.PI / 2, -Math.PI / 2, true);
g.fill();
g.restore();
g.strokeStyle = '#000';
g.lineWidth = 0.5;
g.beginPath();
g.arc(x, y, radius, 0, 7);
g.stroke();
}
if (keyboardMode && root.matches(':focus-visible')) {
const x = keyboardCursor.x * CELL;
const y = keyboardCursor.y * CELL;
g.strokeStyle = '#ffd54f';
g.lineWidth = 3;
g.strokeRect(x + 2, y + 2, CELL - 4, CELL - 4);
}
}
function loop(now) {
if (!root.isConnected) {
root._jezzballDestroy();
return;
}
if (!last) last = now;
const dt = Math.min((now - last) / 1000, 0.05);
last = now;
if (running && !paused) update(dt);
draw();
updateHud();
frame = requestAnimationFrame(loop);
}
function canvasPoint(event) {
const rect = canvas.getBoundingClientRect();
return {
x: (event.clientX - rect.left) * COLS / rect.width,
y: (event.clientY - rect.top) * ROWS / rect.height,
};
}
const touchPoints = new Map();
let multitouchSeen = false;
function onPointerDown(event) {
root.focus();
keyboardMode = false;
if (event.pointerType === 'touch') {
event.preventDefault();
touchPoints.set(event.pointerId, canvasPoint(event));
if (touchPoints.size !== 2) return;
multitouchSeen = true;
const points = Array.from(touchPoints.values());
const dx = Math.abs(points[1].x - points[0].x);
const dy = Math.abs(points[1].y - points[0].y);
if (dx > dy * Math.sqrt(3)) {
orientation = 'horizontal';
} else if (dy > dx * Math.sqrt(3)) {
orientation = 'vertical';
} else {
return;
}
updateHud();
startWall((points[0].x + points[1].x) / 2, (points[0].y + points[1].y) / 2);
return;
}
if (event.button === 2) {
event.preventDefault();
toggleOrientation();
return;
}
const point = canvasPoint(event);
startWall(point.x, point.y);
}
function onPointerUp(event) {
const point = touchPoints.get(event.pointerId);
const singleTouch = touchPoints.size === 1;
touchPoints.delete(event.pointerId);
if (event.type === 'pointerup' && !multitouchSeen && singleTouch && point) {
startWall(point.x, point.y);
}
}
function onKeyDown(event) {
if (event.target.closest('input, textarea, select, button, [contenteditable="true"]')) return;
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight' ||
event.key === 'ArrowUp' || event.key === 'ArrowDown') {
event.preventDefault();
keyboardMode = true;
if (event.key === 'ArrowLeft') keyboardCursor.x = Math.max(0, keyboardCursor.x - 1);
if (event.key === 'ArrowRight') keyboardCursor.x = Math.min(COLS - 1, keyboardCursor.x + 1);
if (event.key === 'ArrowUp') keyboardCursor.y = Math.max(0, keyboardCursor.y - 1);
if (event.key === 'ArrowDown') keyboardCursor.y = Math.min(ROWS - 1, keyboardCursor.y + 1);
} else if (event.key === 'Enter') {
event.preventDefault();
keyboardMode = true;
startWall(keyboardCursor.x, keyboardCursor.y);
} else if (event.code === 'Space') {
event.preventDefault();
toggleOrientation();
} else if (event.key.toLowerCase() === 'p') {
event.preventDefault();
togglePause();
}
}
function togglePause() {
if (!running) return;
paused = !paused;
pauseButton.textContent = paused ? labels.resume : labels.pause;
}
function preventContextMenu(event) { event.preventDefault(); }
canvas.addEventListener('pointerdown', onPointerDown);
canvas.addEventListener('pointerup', onPointerUp);
canvas.addEventListener('pointercancel', onPointerUp);
canvas.addEventListener('contextmenu', preventContextMenu);
directionButton.addEventListener('click', toggleOrientation);
speedButton.addEventListener('click', toggleSpeed);
soundButton.addEventListener('click', toggleSound);
pauseButton.addEventListener('click', togglePause);
root.addEventListener('keydown', onKeyDown);
root._jezzballDestroy = function() {
cancelAnimationFrame(frame);
canvas.removeEventListener('pointerdown', onPointerDown);
canvas.removeEventListener('pointerup', onPointerUp);
canvas.removeEventListener('pointercancel', onPointerUp);
canvas.removeEventListener('contextmenu', preventContextMenu);
directionButton.removeEventListener('click', toggleOrientation);
speedButton.removeEventListener('click', toggleSpeed);
soundButton.removeEventListener('click', toggleSound);
pauseButton.removeEventListener('click', togglePause);
root.removeEventListener('keydown', onKeyDown);
if (audioContext) audioContext.close();
root._jezzballDestroy = null;
};
if (checkpoint.final) {
if (!restoreBalls()) placeBalls();
if (!Number.isSafeInteger(initial.lives)) lives = balls.length;
showMessage(format(labels.finalScore, { score: score }), labels.newGame, function() {
if (writable && score > 0 && !window.confirm(format(labels.confirmNewGame, { score: score }))) {
overlay.classList.add('visible');
return;
}
level = 1;
score = 0;
checkpoint = {
level: 1,
lives: 2,
time: LEVEL_SECONDS,
area: 0,
final: false,
};
if (writable && api && typeof api.save === 'function') api.save(emptyMap(), checkpoint, score);
resetLevel();
});
} else {
restoreBalls();
showMessage(format(labels.level, { level: level }), labels.continue, resetLevel);
}
frame = requestAnimationFrame(loop);
return root._jezzballDestroy;
}
Handlebars.registerHelper('jezzball', function(ref, actions, el) {
return function() {
jezzballApp(el.querySelector('.jezzball-game'), {
url: ref && ref.url,
comment: ref && ref.comment,
initial: ref && ref.plugins && ref.plugins['plugin/jezzball'] || {},
score: ref && ref.plugins && ref.plugins['plugin/score'],
writable: !actions || !!actions.patch,
save: actions && actions.patch ? function(comment, state, score) {
actions.patch({
comment: comment,
plugins: {
'plugin/jezzball': state,
'plugin/score': score,
},
});
} : undefined,
});
};
});
</script>
`,
// language=Handlebars
ui: `
<div class="jezzball-game" tabindex="0">
<div class="jezzball-toolbar">
<span class="jezzball-level"></span>
<span class="jezzball-example"></span>
<span class="jezzball-controls">
<button class="jezzball-direction" type="button"></button>
<button class="jezzball-speed" type="button"></button>
<button class="jezzball-sound" type="button"></button>
<button class="jezzball-pause" type="button"></button>
</span>
</div>
<div class="jezzball-stage">
<canvas class="jezzball-canvas" width="800" height="600"></canvas>
<span class="jezzball-stat jezzball-lives"></span>
<span class="jezzball-center">
<span class="jezzball-stat jezzball-score"></span>
</span>
<span class="jezzball-stat jezzball-time"></span>
<span class="jezzball-stat jezzball-filled"></span>
<div class="jezzball-overlay"><div><strong></strong><button class="jezzball-new-game" type="button"></button></div></div>
</div>
{{defer el (jezzball ref actions el)}}
</div>
`,
},
schema: {
optionalProperties: {
level: { type: 'uint32' },
lives: { type: 'uint8' },
time: { type: 'float64' },
area: { type: 'uint8' },
final: { type: 'boolean' },
},
},
};
export const jezzballTemplate: Template = {
tag: 'plugin/jezzball',
name: $localize`π£οΈ JezzBall`,
config: {
mod: $localize`π£οΈ JezzBall`,
version: 1,
type: 'plugin',
generated: $localize`Generated by jasper-ui ${DateTime.now().toISO()}`,
view: $localize`π£οΈ`,
// language=CSS
css: `
app-ref-list.plugin_jezzball {
.list-container {
grid-auto-flow: row dense;
padding: 4px;
gap: 8px;
grid-template-columns: minmax(0, 1fr);
.list-number {
display: none;
}
.ref {
min-width: 0;
break-inside: avoid;
.toggle {
display: none;
}
}
}
}
`,
advancedForm: [{
key: 'defaultExpanded',
type: 'boolean',
defaultValue: true,
props: {
label: $localize`Default Expanded:`,
},
}],
},
defaults: <RootConfig> {
submitText: true,
defaultSort: ['plugins->plugin/score:num,DESC', 'modified,DESC'],
defaultCols: 1,
},
};
export const jezzballMod: Mod = {
plugin: [
scorePlugin,
jezzballPlugin,
],
template: [
jezzballTemplate,
],
};
|