Versus mode: attack vs defend (sim, bots, server, client)

One player defends, the other plays the Internet: earns credits over time and
spends them on packets, upgrades and sabotage. Two rounds with swapped roles,
timed (the faster fall wins). Built end to end, NOT yet QA'd or balanced.

Sim (public/js/sim.js, TD.VS table): attacker economy (income, lifetime bonus,
leak payback), spawn / stage / launch convoys, 7 tech tracks, abilities (EMP,
decoy, surge, DDoS), defender tools (scan, patch, repair, quarantine), role-checked
commands, round result, role-private state. Co-op/solo unchanged (24 scripted
games replay identically).

Bots (public/js/bot.js, tools/versus.js): defender (maze + turrets) and attacker
(budgeted spender reading the tower mix); headless bot-vs-bot runner.

Server (server/versus.js, protocol doc): versus rooms with lobby / countdown /
playing / roundover / matchover, role stamping, cross-role refusal, role-private
priv messages at 4 Hz, computer seat, freeze/forfeit rules, no pause/speed.

Client (public/js/versus.js): setup dialog (role, length, vs computer or online),
countdown, defender tools row, attacker unit shop with convoy + launch, tech and
abilities, gateway choice, round/match screens, sounds, phone-first dock rows.

Status and next steps (balance: the attacker currently wins ~100% of bot rounds;
QA with two browsers; layout matrix rerun) are in docs/NEXT.md and docs/VERSUS.md.
The full planned workflow incl. balance/QA prompts is in docs/workflows/versus-full.js.

253 unit tests pass; one smoke e2e run; no other e2e per the user's request.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
This commit is contained in:
Claude 2026-10-11 10:22:29 +00:00
parent b4ae6cb57d
commit 2098d59c1f
23 changed files with 6166 additions and 90 deletions

View file

@ -445,3 +445,134 @@ input.code { text-align: center; letter-spacing: .5em; font-family: var(--mono);
.overlay { background: Canvas; }
#side { border-color: CanvasText; }
}
/* ================================================================ versus (attack vs defend), see js/versus.js
* #app[data-mode="versus"] is set while a versus game runs, data-role="attacker|defender" for the current round. Nothing below applies to solo or co-op. */
.vs-only { display: none; }
#app[data-mode="versus"] #statTime { display: flex; }
#app[data-mode="versus"] #vIncome { display: inline; }
#app[data-mode="versus"] #statWave, #app[data-mode="versus"] #btnWave, #app[data-mode="versus"] #btnAuto, #app[data-mode="versus"] #btnSpeed,
#app[data-mode="versus"] #btnPause, #app[data-mode="versus"] #netChip { display: none !important; } /* no waves, no pause, no speed in versus; nobody to invite mid-match */
#statTime { font-variant-numeric: tabular-nums; }
#statTime.low { border-color: var(--red); color: var(--red); background: #2a0e18; animation: pulse 0.8s infinite; }
#vIncome { color: var(--green); font-size: 11px; margin-left: 2px; }
@media (max-width: 420px) { #app[data-mode="versus"] #vIncome { display: none; } }
#app[data-mode="versus"] #nextwave { display: none; }
/* stage overlays */
.vshud { position: absolute; left: 8px; bottom: 8px; max-width: calc(100% - 64px); padding: 3px 10px; border-radius: 999px; background: rgba(8, 13, 26, .82); border: 1px solid var(--line); font: 11.5px/1.4 var(--mono); color: var(--dim); pointer-events: none; z-index: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.vsfx { position: absolute; right: 8px; top: 8px; display: flex; flex-direction: column; align-items: flex-end; gap: 4px; pointer-events: none; z-index: 2; }
.fxchip { padding: 3px 10px; border-radius: 999px; font: 700 11px/1.4 var(--mono); background: rgba(8, 13, 26, .92); border: 1px solid; }
.fxchip.surge { color: var(--amber); border-color: #8a6a1a; } .fxchip.ddos { color: #c9a2ff; border-color: #5b3a8a; } .fxchip.freeze { color: #bfeaff; border-color: #3a7a9a; }
.vscount { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; gap: 2px; padding: 10px 14px; background: rgba(4, 7, 14, .6); pointer-events: none; z-index: 3; }
.vsc-top { font-size: 12px; letter-spacing: .22em; color: var(--dim); }
.vsc-role { font-size: clamp(22px, 6vw, 38px); font-weight: 800; letter-spacing: .12em; }
.vsc-role.att { color: var(--red); text-shadow: 0 0 22px rgba(255, 92, 122, .6); } .vsc-role.def { color: var(--cyan); text-shadow: 0 0 22px rgba(77, 227, 255, .6); }
.vsc-sub { max-width: 30em; font-size: 13px; color: #bcd3f5; margin: 2px 0 4px; }
.vsc-num { font: 800 clamp(40px, 12vw, 72px)/1 var(--mono); color: #fff; }
.vsc-big { font-size: clamp(22px, 6vw, 34px); font-weight: 800; letter-spacing: .2em; color: var(--amber); }
#vsNote { z-index: 4; }
/* the dock under the board: unit shop (the palette), convoy row, abilities / tools, tech */
.vsbar { display: flex; flex-direction: column; gap: 6px; }
.vsrow { display: flex; gap: 6px; align-items: stretch; }
.vsctlrow { flex-wrap: wrap; }
.vsctl { flex: 0 0 auto; min-height: 46px; padding: 0 7px; font: 700 13px var(--mono); white-space: nowrap; }
.vsctl.on { background: #0f3550; border-color: var(--cyan); color: var(--cyan); }
.vslaunch { flex: 1 1 112px; min-width: 0; min-height: 46px; padding: 0 10px; gap: 8px; font-size: 14px; justify-content: flex-start; }
.vslaunch .lt { display: flex; flex-direction: column; align-items: flex-start; min-width: 0; line-height: 1.15; }
.vslaunch small { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 10.5px; font-weight: 500; opacity: .9; }
.vslaunch:not(:disabled) { animation: glow 1.6s infinite; }
.vslaunch:disabled, #vsSetup button.primary:disabled, #vsRoom button.primary:disabled, #vsEnd button.primary:disabled { background: #0c1426; border-color: #172540; color: #8da3c8; animation: none; }
.vsabil { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }
.vsbtn { position: relative; flex-direction: column; gap: 1px; padding: 4px 2px 3px; min-height: 48px; line-height: 1.1; overflow: hidden; }
.vsbtn .ic { width: 18px; height: 18px; }
.vsbtn .nm { font-size: 11px; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
.vsbtn .cost { font: 11.5px var(--mono); color: var(--amber); }
.vsbtn::after { content: ""; position: absolute; inset: 0; background: conic-gradient(rgba(4, 8, 16, .74) calc(var(--p, 0) * 1turn), transparent 0); pointer-events: none; }
.vsbtn .cd { position: absolute; inset: 0; z-index: 1; display: flex; align-items: center; justify-content: center; font: 700 15px var(--mono); color: #fff; text-shadow: 0 0 4px #000, 0 0 2px #000; pointer-events: none; }
.vsbtn.poor { color: #9fb2d4; } .vsbtn.poor .cost { color: #ff8fa3; } .vsbtn.idle { opacity: .55; }
.vsbtn.live { border-color: var(--amber); box-shadow: 0 0 0 2px rgba(255, 210, 77, .3); }
.vsbtn.armed { border-color: var(--cyan); background: #0f3550; box-shadow: inset 0 0 0 1px var(--cyan); }
.vsbtn.ready { border-color: var(--green); }
.vsbtn.confirm { border-color: var(--amber); background: #3a2c08; animation: glow 0.7s infinite; }
.vstech { display: block; }
.vshead { display: flex; align-items: baseline; gap: 8px; margin-bottom: 4px; font-size: 11px; letter-spacing: .14em; color: var(--dim); text-transform: uppercase; font-weight: 600; }
.vshead small { text-transform: none; letter-spacing: 0; font-weight: 400; font-size: 11px; opacity: .85; }
.vstiles { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }
.techbtn { flex-direction: column; gap: 0; padding: 4px 2px 3px; min-height: 56px; }
.techbtn .ic { width: 18px; height: 18px; color: var(--cyan); }
.techbtn .nm { font-size: 11.5px; } .techbtn .pips { font-size: 9px; letter-spacing: 1px; color: var(--cyan); line-height: 1; min-height: 9px; }
.techbtn.maxed { border-color: #1c6a55; } .techbtn.maxed .cost { color: var(--green); }
.techbtn.poor .cost { color: #ff8fa3; } .techbtn.poor .ic { opacity: .6; }
.ubtn.hit { background: #0f3550; border-color: var(--cyan); }
#info .actions [data-act="emp"].poor .cost { color: #ff8fa3; }
/* a tower's panel for the attacker: just EMP and close */
#app[data-role="attacker"] #info .actions [data-act="emp"] { flex-grow: 2; }
/* stacked layouts: the dock is pinned to the bottom of the side panel (thumb reach), the tech row scrolls like the shop */
@media (orientation: portrait), (max-width: 760px) and (min-height: 521px) {
#vsbar { position: sticky; bottom: 0; z-index: 2; margin: 0 -10px; padding: 6px 10px 8px; background: #0a101f; border-top: 1px solid var(--line); }
.vstiles { display: flex; overflow-x: auto; scrollbar-width: none; scroll-snap-type: x proximity; margin: 0 -10px; padding: 0 10px; }
.vstiles::-webkit-scrollbar { display: none; }
.techbtn { flex: 0 0 76px; scroll-snap-align: start; }
#palette.shop .tbtn { flex: 0 0 72px; min-height: 66px; }
#palette.shop { padding-top: 6px; padding-bottom: 4px; }
#palette.shop .tbtn canvas { width: 30px; height: 30px; }
}
@media (min-width: 640px) and (orientation: portrait), (min-width: 640px) and (max-width: 760px) and (min-height: 521px) {
.vstiles { display: grid; overflow: visible; margin: 0; padding: 0; grid-template-columns: repeat(auto-fill, minmax(84px, 1fr)); }
.techbtn { flex: none; }
}
/* short landscape: a 200 px column. Convoy controls wrap (Launch on its own row), abilities keep their four columns as icons + cost, the shop scrolls */
@media (orientation: landscape) and (max-height: 520px) {
#vsbar { position: sticky; bottom: 0; z-index: 2; margin: 0 -6px; padding: 5px 6px 6px; background: #0a101f; border-top: 1px solid var(--line); gap: 4px; }
.vsctlrow { flex-wrap: wrap; } .vsctl { min-height: 44px; flex: 1 1 0; padding: 0 4px; font-size: 12px; } .vslaunch { flex: 1 1 100%; min-height: 44px; }
.vsbtn { min-height: 44px; padding: 3px 1px; } .vsbtn .nm { display: none; } .vsbtn .cost { font-size: 11px; }
#palette.shop { max-height: calc(var(--tile-h) * 2.6 + 10px); }
.techbtn { min-height: 52px; padding: 3px 1px; } .techbtn .nm { font-size: 10px; } .vshead small { display: none; }
.vsfx { top: 4px; right: 4px; } .vshud { font-size: 10.5px; }
.vsc-sub { font-size: 12px; } .vsc-top { font-size: 10.5px; }
}
@media (max-width: 340px) { .vsctl { padding: 0 6px; font-size: 12px; } .vslaunch { padding: 0 8px; } }
/* dialogs */
.vsfield { display: flex; align-items: center; gap: 10px; margin: 10px 0; }
.vsfield .seg { flex: 1 1 auto; max-width: none; }
.flabel { flex: 0 0 104px; font-size: 12px; letter-spacing: .06em; color: var(--dim); }
@media (max-width: 480px) { .vsfield { flex-direction: column; align-items: stretch; gap: 3px; margin: 8px 0; } .flabel { flex: none; } }
.vsonline { margin-top: 12px; padding: 4px 12px 12px; border: 1px solid var(--line); border-radius: 12px; background: rgba(255, 255, 255, .02); }
.vsonline h3 { margin-top: 10px; }
@media (max-height: 640px) { .vsonline .field { margin: 6px 0; } #vsMapName { display: none; } .vsfield { margin: 6px 0; } } /* small phones: the map is the one picked in the menu (and visible behind) */
.vsroomhead { display: flex; align-items: center; gap: 10px; margin: 0 0 8px; flex-wrap: wrap; }
.vsroomhead .rc { font: 800 22px var(--mono); letter-spacing: .2em; color: var(--cyan); }
.vsroomhead .link { margin-left: auto; }
.vsseat { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 8px 10px; margin-bottom: 6px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); }
.vsseat.empty { border-style: dashed; color: var(--dim); }
.vsseat .sn { flex: 1 1 80px; min-width: 0; font-weight: 700; overflow: hidden; text-overflow: ellipsis; }
.vsseat .you, #players .pl .you { color: var(--dim); font-size: 12px; } .vsseat .off { color: var(--red); font-size: 12px; }
.vsseat .rdy { font-size: 12px; color: var(--dim); } .vsseat .rdy.ok { color: var(--green); }
.rolebadge { font: 700 10.5px/1.5 var(--mono); letter-spacing: .1em; padding: 1px 7px; border-radius: 6px; border: 1px solid; margin-left: auto; }
.rolebadge.attacker { color: var(--red); border-color: #6a2336; } .rolebadge.defender { color: var(--cyan); border-color: #1c5a70; }
#players .pl .rolebadge { margin-left: auto; }
#btnVsReady.on { background: #0f3550; border-color: var(--cyan); color: var(--cyan); }
.vscols { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 10px; margin-top: 8px; }
.vsround { padding: 10px 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--panel); }
.vsround.pending { border-style: dashed; opacity: .75; }
.vsround h4, .vsscore h4 { margin: 0 0 6px; font-size: 11px; letter-spacing: .14em; color: var(--dim); text-transform: uppercase; font-weight: 600; }
.vsrow2 { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; padding: 3px 0; border-bottom: 1px solid var(--line); font-size: 13px; }
.vsrow2:last-child { border-bottom: 0; }
.vsrow2 > span { color: var(--dim); flex: none; } .vsrow2 > b { font-family: var(--mono); text-align: right; font-size: 12.5px; }
.vsrow2 .good { color: var(--green); } .vsrow2 .bad { color: var(--red); }
.vsrow2 .rolebadge { margin-left: 0; }
.vsscore { margin-top: 12px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 12px; }
@media (orientation: landscape) and (max-height: 520px) { .vsfield { margin: 4px 0; } .vsonline { margin-top: 6px; padding: 2px 10px 8px; } .vsroomhead .rc { font-size: 18px; } .vsseat { padding: 5px 8px; margin-bottom: 4px; } }
@media (prefers-reduced-motion: reduce) { .vslaunch:not(:disabled), .vsbtn.confirm, #statTime.low { animation: none; } }
/* the menu's three modes: one row where it fits; on a phone Play solo has the row to itself and Co-op / Versus share the next one (the foot stays two rows tall) */
.row.modes > .big { flex: 1 1 150px; padding: 0 10px; white-space: nowrap; }
@media (max-width: 560px) {
.row.modes > #btnSolo { flex-basis: 100%; }
.row.modes > #btnCoop, .row.modes > #btnVersus { flex: 1 1 120px; font-size: 15px; }
.row.modes > #btnCoop .ic, .row.modes > #btnVersus .ic { display: none; }
}

View file

@ -8,7 +8,7 @@
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="Netwall">
<meta name="description" content="Netwall: build firewalls, stretch the route, protect the server. A maze tower defence game with two-player co-op.">
<meta name="description" content="Netwall: build firewalls, stretch the route, protect the server. A maze tower defence game with two-player co-op and attack-vs-defend versus.">
<title>Netwall</title>
<link rel="manifest" href="manifest.webmanifest">
<link rel="icon" href="icons/icon.svg" type="image/svg+xml">
@ -36,6 +36,23 @@
<symbol id="i-trash" viewBox="0 0 24 24"><path d="M5 7h14M10 7V4.5h4V7M7 7l1 12.5h8L17 7M10.5 11v5M13.5 11v5" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-users" viewBox="0 0 24 24"><circle cx="9" cy="8.5" r="3.3" fill="currentColor"/><path d="M2.5 19.5c0-3.6 2.9-5.6 6.5-5.6s6.5 2 6.5 5.6z" fill="currentColor"/><circle cx="17" cy="9.5" r="2.5" fill="currentColor" opacity=".7"/><path d="M16.5 14.2c3 0 5 1.6 5 4.6h-4.2" fill="currentColor" opacity=".7"/></symbol>
<symbol id="i-target" viewBox="0 0 24 24"><circle cx="12" cy="12" r="7.5" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="12" cy="12" r="2.2" fill="currentColor"/><path d="M12 2.5v4M12 17.5v4M2.5 12h4M17.5 12h4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></symbol>
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M12 7v5.2l3.4 2" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-launch" viewBox="0 0 24 24"><path d="M6 18L18 6M9 6h9v9" fill="none" stroke="currentColor" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-ab-emp" viewBox="0 0 24 24"><path d="M13.5 3L5.5 13.5h5.5L10 21l8.5-11h-5.5z" fill="currentColor"/></symbol>
<symbol id="i-ab-decoy" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8" fill="none" stroke="currentColor" stroke-width="2" stroke-dasharray="3.2 3"/><circle cx="12" cy="12" r="3" fill="currentColor"/></symbol>
<symbol id="i-ab-surge" viewBox="0 0 24 24"><path d="M5 18l7-7 7 7M5 11.5l7-7 7 7" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-ab-ddos" viewBox="0 0 24 24"><path d="M4.5 15a7.5 7.5 0 0115 0M8 15a4 4 0 018 0" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/><circle cx="12" cy="17.5" r="1.8" fill="currentColor"/><path d="M4 21h16" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-dasharray="1 3.2"/></symbol>
<symbol id="i-tl-scan" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="5.8" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M15 15l5 5" stroke="currentColor" stroke-width="2.6" stroke-linecap="round"/></symbol>
<symbol id="i-tl-patch" viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="4" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M12 8v8M8 12h8" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/></symbol>
<symbol id="i-tl-repair" viewBox="0 0 24 24"><path d="M4.5 19.5L13 11" stroke="currentColor" stroke-width="3" stroke-linecap="round"/><circle cx="16.2" cy="7.8" r="4" fill="none" stroke="currentColor" stroke-width="2.2"/></symbol>
<symbol id="i-tl-quarantine" viewBox="0 0 24 24"><rect x="5.5" y="11" width="13" height="9.5" rx="2.2" fill="currentColor"/><path d="M8.5 11V8a3.5 3.5 0 017 0v3" fill="none" stroke="currentColor" stroke-width="2.2"/></symbol>
<symbol id="i-te-armor" viewBox="0 0 24 24"><path d="M12 3l7 3v5.5c0 4.6-3 7.6-7 9.5-4-1.9-7-4.9-7-9.5V6z" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linejoin="round"/></symbol>
<symbol id="i-te-speed" viewBox="0 0 24 24"><path d="M5.5 6l6 6-6 6M12.5 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-te-health" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14" stroke="currentColor" stroke-width="3.4" stroke-linecap="round"/></symbol>
<symbol id="i-te-regen" viewBox="0 0 24 24"><path d="M19 12a7 7 0 11-2.2-5.1M19 4.5v4.3h-4.3" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/></symbol>
<symbol id="i-te-shield" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M7.8 12a4.2 4.2 0 014.2-4.2" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></symbol>
<symbol id="i-te-stealth" viewBox="0 0 24 24"><path d="M2.5 12s3.6-6 9.5-6 9.5 6 9.5 6-3.6 6-9.5 6-9.5-6-9.5-6z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/><circle cx="12" cy="12" r="2.6" fill="currentColor"/><path d="M4.5 20L19.5 4" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/></symbol>
<symbol id="i-te-crypt" viewBox="0 0 24 24"><circle cx="8" cy="12" r="3.6" fill="none" stroke="currentColor" stroke-width="2.2"/><path d="M11.6 12H21M17.5 12v3.2M20.5 12v2.2" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></symbol>
<symbol id="i-fs" viewBox="0 0 24 24"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></symbol>
</defs>
</svg>
@ -44,9 +61,10 @@
<header id="topbar">
<button id="btnMenu" class="icon" aria-label="Menu"><svg class="ic"><use href="#i-menu"/></svg></button>
<div class="stat vs-only" id="statTime" title="Round time left"><svg class="ic"><use href="#i-clock"/></svg><b id="vTime">0:00</b></div>
<div class="stat" id="statWave" title="Wave"><span class="lbl">WAVE</span><b id="vWave">0</b><small id="vWaveMax"></small></div>
<div class="stat" id="statLives" title="Server integrity"><svg class="ic"><use href="#i-heart"/></svg><b id="vLives">20</b></div>
<div class="stat" id="statGold" title="Credits"><svg class="ic"><use href="#i-coin"/></svg><b id="vGold">0</b></div>
<div class="stat" id="statGold" title="Credits"><svg class="ic"><use href="#i-coin"/></svg><b id="vGold">0</b><small id="vIncome" class="vs-only"></small></div>
<button id="netChip" class="chip" type="button" hidden title="Co-op room: tap to invite your partner" aria-label="Co-op room. Tap to invite your partner"><svg class="ic"><use href="#i-users"/></svg><span id="netRoom"></span><span id="netPing"></span><svg class="ic share"><use href="#i-share"/></svg></button>
<div class="spacer"></div>
<button id="btnWave" class="primary" aria-label="Start next wave"><svg class="ic"><use href="#i-play"/></svg><span id="btnWaveText">Wave 1</span></button>
@ -61,6 +79,10 @@
<div id="hint" class="hint" hidden></div>
<div id="banner" class="banner" aria-live="polite"></div>
<button id="pausedTag" class="paused-tag" type="button" hidden><svg class="ic"><use href="#i-play"/></svg><span>PAUSED<small>tap to resume</small></span></button>
<div id="vsHud" class="vshud" hidden></div>
<div id="vsNote" class="hint info" hidden></div>
<div id="vsFx" class="vsfx" aria-live="polite"></div>
<div id="vsCount" class="vscount" hidden></div>
<div id="toasts" aria-live="polite"></div>
<button id="btnFit" class="icon floating" aria-label="Reset zoom" hidden><svg class="ic"><use href="#i-fit"/></svg></button>
<div id="confirm" class="confirm" hidden>
@ -79,6 +101,8 @@
<aside id="side">
<section id="palette" aria-label="Build"></section>
<section id="vsbar" class="vsbar" aria-label="Versus controls" hidden></section>
<section id="vstech" class="vstech" aria-label="Tech upgrades" hidden></section>
<section id="info" aria-live="polite"></section>
<section id="nextwave"></section>
<section id="players" hidden></section>
@ -98,9 +122,10 @@
<div id="diffPick" class="seg" role="radiogroup" aria-label="Difficulty"></div><!-- Easy / Normal / Hard, built by main.js from TD.DIFFICULTIES -->
<p id="diffNote" class="diffnote"></p>
</div>
<div class="row">
<div class="row modes">
<button id="btnSolo" class="primary big"><svg class="ic"><use href="#i-play"/></svg>Play solo</button>
<button id="btnCoop" class="big"><svg class="ic"><use href="#i-users"/></svg>Co-op online</button>
<button id="btnVersus" class="big"><svg class="ic"><use href="#i-ab-emp"/></svg>Versus</button>
</div>
<button id="btnResume" class="big resume" hidden></button>
<div class="row small">
@ -144,6 +169,77 @@
</div>
</div>
<!-- ===== versus setup (solo against the computer, or create / join an online room) ===== -->
<div id="vsSetup" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="vsSetupTitle">
<div class="card">
<div class="card-body">
<h2 id="vsSetupTitle">Versus</h2>
<p class="muted lead">One of you builds the maze, the other sends the packets. Two rounds, the roles swap. Whoever breaks the server fastest wins.</p>
<p class="muted small" id="vsMapName"></p>
<div class="vsfield"><span class="flabel">You play</span><div id="vsRolePick" class="seg" role="radiogroup" aria-label="Your role"></div></div>
<div class="vsfield"><span class="flabel">Round length</span><div id="vsLimitPick" class="seg" role="radiogroup" aria-label="Round length"></div></div>
<div class="vsfield"><span class="flabel">Computer skill</span><div id="vsSkillPick" class="seg" role="radiogroup" aria-label="Computer skill"></div></div>
<div class="vsonline">
<h3>Online</h3>
<label class="field"><span>Your name</span><input id="vsName" maxlength="16" autocomplete="nickname" autocapitalize="words" spellcheck="false" placeholder="Player"></label>
<div class="joinrow">
<input id="vsCode" class="code" maxlength="4" autocomplete="off" autocapitalize="characters" spellcheck="false" inputmode="text" placeholder="ABCD" aria-label="Room code">
<button id="btnVsJoin" class="big">Join</button>
</div>
</div>
</div>
<div class="card-foot">
<p id="vsMsg" class="msg" role="status"></p>
<div class="row">
<button id="btnVsComputer" class="primary big">Play the computer</button>
<button id="btnVsCreate" class="big"><svg class="ic"><use href="#i-users"/></svg>Create room</button>
</div>
<div class="row small"><button id="btnVsBack" class="link">&larr; Back</button></div>
</div>
</div>
</div>
<!-- ===== versus room: roles, ready, computer seat, start ===== -->
<div id="vsRoom" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="vsRoomTitle">
<div class="card">
<div class="card-body">
<h2 id="vsRoomTitle">Versus room</h2>
<div class="vsroomhead"><span class="rc" id="vsRoomCode"></span><span id="vsRoomLimit" class="muted small"></span><button id="btnVsInvite" type="button" class="link">Invite</button></div>
<div id="vsSeats" class="vsseats"></div>
<div class="vsfield"><span class="flabel">Your role</span><div id="vsRoomRole" class="seg" role="radiogroup" aria-label="Your role"></div></div>
<div class="vsfield" id="vsOppField"><span class="flabel">Opponent</span><div id="vsRoomOpp" class="seg" role="radiogroup" aria-label="Opponent"></div></div>
<p id="vsRoomNote" class="muted small"></p>
</div>
<div class="card-foot">
<p id="vsRoomMsg" class="msg" role="status"></p>
<div class="row">
<button id="btnVsReady" class="big">I'm ready</button>
<button id="btnVsStart" class="primary big">Start match</button>
</div>
<div class="row small"><button id="btnVsLeave" class="link">Leave room</button></div>
</div>
</div>
</div>
<!-- ===== versus: round over / match over ===== -->
<div id="vsEnd" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="vsEndTitle" aria-describedby="vsEndText">
<div class="card wide">
<div class="card-body">
<h2 id="vsEndTitle"></h2>
<p id="vsEndText" class="muted"></p>
<div id="vsEndRounds" class="vsrounds"></div>
</div>
<div class="card-foot">
<p id="vsEndWait" class="msg" role="status" hidden></p>
<div class="row">
<button id="btnVsNext" class="primary big">Next round</button>
<button id="btnVsRematch" class="primary big">Rematch</button>
<button id="btnVsEndMenu" class="big">Menu</button>
</div>
</div>
</div>
</div>
<!-- ===== help ===== -->
<div id="help" class="overlay" hidden role="dialog" aria-modal="true" aria-labelledby="helpTitle">
<div class="card wide">
@ -156,6 +252,7 @@
<li><b>Credits.</b> Earned from kills and every cleared wave. Upgrade turrets up to level 3. Sell for 70% back (walls refund in full).</li>
<li><b>Controls.</b> <span class="kbd-only">Click to build, drag to paint walls, right-click to cancel. Keys <span id="helpKeys">1&ndash;6</span> pick a tower, Space starts a wave, U upgrades, X sells, T changes targeting, P pauses, F changes speed, M mutes, wheel zooms.</span>
<span class="touch-only">Tap a tower type, then tap the map to preview; nudge the cell with the arrows and tap &#10003; to build. Walls paint as you drag. Pinch to zoom, two fingers to pan, long-press to ping your partner.</span></li>
<li><b>Versus.</b> One player <b>defends</b> (builds the maze and turrets as usual, with counter-tools: Scan, Patch, Repair, Quarantine) and the other <b>attacks</b>: spend credits on packets (tap a unit to buy; <i>Stage</i> pays now and holds them for one <b>Launch</b>), buy tech upgrades, and sabotage the defence (EMP a turret, Decoy, Surge, DDoS). Tap a gateway to choose where packets enter. A round ends when the server falls or the clock runs out; then the roles swap. Whoever breaks the server fastest wins the match. No pause, no speed control. Play a friend online or the computer.</li>
<li><b>Co-op.</b> Both players share everything and can build, sell and upgrade at the same time. You see each other's cursors; long-press / Alt-click pings the map.</li>
</ul>
</div>
@ -186,9 +283,11 @@
</div>
<script src="js/sim.js"></script>
<script src="js/bot.js"></script>
<script src="js/audio.js"></script>
<script src="js/controllers.js"></script>
<script src="js/render.js"></script>
<script src="js/versus.js"></script>
<script src="js/main.js"></script>
</body>
</html>

View file

@ -95,8 +95,24 @@
clear: () => { tone(660, 0.09, 'triangle', 0.2); tone(880, 0.09, 'triangle', 0.2, 0, 0.09); tone(1320, 0.2, 'triangle', 0.2, 0, 0.18); },
ping: () => { tone(1320, 0.18, 'sine', 0.25, 1760); tone(1760, 0.3, 'sine', 0.12, 0, 0.12); },
join: () => { tone(660, 0.1, 'triangle', 0.2); tone(990, 0.16, 'triangle', 0.2, 0, 0.1); },
// versus: attacker purchases, abilities, defender tools, the round countdown
buy: () => { tone(500, 0.06, 'square', 0.16, 760); noise(0.04, 0.08, 'highpass', 4000); },
stage: () => { tone(380, 0.07, 'triangle', 0.2, 300); tone(300, 0.08, 'triangle', 0.18, 0, 0.06); },
launch: () => { tone(220, 0.5, 'sawtooth', 0.2, 880); noise(0.4, 0.2, 'bandpass', 600, 3000); tone(880, 0.2, 'square', 0.12, 1320, 0.4); },
tech: () => { tone(440, 0.07, 'triangle', 0.2); tone(660, 0.07, 'triangle', 0.2, 0, 0.07); tone(880, 0.07, 'triangle', 0.2, 0, 0.14); tone(1320, 0.18, 'triangle', 0.18, 0, 0.21); },
emp: () => { noise(0.35, 0.3, 'bandpass', 4000, 200); tone(1800, 0.3, 'sawtooth', 0.14, 90); },
decoy: () => { tone(900, 0.08, 'sine', 0.22, 1400); tone(1400, 0.1, 'sine', 0.18, 900, 0.09); },
surge: () => { tone(200, 0.5, 'sawtooth', 0.2, 700); tone(300, 0.5, 'square', 0.1, 1000, 0.05); },
ddos: () => { noise(0.6, 0.28, 'lowpass', 2500, 120); tone(90, 0.6, 'sawtooth', 0.3, 40); },
scan: () => { tone(1500, 0.16, 'sine', 0.2, 900); tone(1500, 0.16, 'sine', 0.15, 900, 0.18); },
patch: () => { tone(520, 0.08, 'triangle', 0.22); tone(780, 0.12, 'triangle', 0.22, 0, 0.08); },
repair: () => { tone(440, 0.12, 'triangle', 0.2, 660); tone(660, 0.2, 'triangle', 0.2, 990, 0.1); },
quarantine: () => { tone(1200, 0.5, 'sine', 0.2, 200); noise(0.5, 0.15, 'highpass', 5000, 1500); },
breach: () => { tone(600, 0.08, 'triangle', 0.18, 900); tone(150, 0.2, 'sine', 0.35, 70); }, // what a leak sounds like to the attacker: the server took a hit
tick: () => tone(880, 0.06, 'square', 0.12),
go: () => { tone(660, 0.1, 'square', 0.18); tone(990, 0.25, 'square', 0.2, 0, 0.1); },
};
const MIN_GAP = { shot_uplink: 0.12, shot_filter: 0.06, kill: 0.05, arc: 0.07, boom: 0.08, shot_mortar: 0.1, shot_ids: 0.08, wall: 0.03 };
const MIN_GAP = { buy: 0.03, breach: 0.08, shot_uplink: 0.12, shot_filter: 0.06, kill: 0.05, arc: 0.07, boom: 0.08, shot_mortar: 0.1, shot_ids: 0.08, wall: 0.03 };
function sfx(name) {
if (muted || !unlocked || !ctx || !SFX[name]) return;

520
public/js/bot.js Normal file
View file

@ -0,0 +1,520 @@
/*
* NETWALL versus bots: a computer opponent for either side (docs/VERSUS.md).
*
* const bot = NWBot.create(sim, 'defender' | 'attacker', { seed, skill, by });
* bot.think(dt); // call it with the sim seconds that passed (every tick is fine); it decides about once per sim second
*
* Loaded as a classic <script> in the browser (window.NWBot, needs window.TD from sim.js first) and with require() in Node (the server and
* tools/versus.js). It drives the game ONLY the way a human does: sim.cmd({ role, by, ... }) for every action, sim.preview / the public
* board and tower list to look, and sim.privateState(its own role) for what only its own side may see. The defender never looks at the
* attacker's convoy, tech or credits; the attacker never looks at the defender's cooldowns. All randomness is a seeded PRNG (no
* Math.random: the same seed plays the same game). `skill` 0..1 (default 1) slows its decisions, adds noise and drops the clever parts
* (maze, tools, tech, abilities) for the weakest settings. Every command is checked against affordability and cooldowns first, so a bot
* never sends a command the sim would refuse for a reason a human's UI would have prevented (it can still meet 'monster' / 'blocks' /
* 'occupied' when the board changes under a wall or turret placement, exactly like a human).
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory(require('./sim.js'));
else root.NWBot = factory(root.TD);
})(typeof self !== 'undefined' ? self : this, function (TD) {
'use strict';
const { VS, TOWERS, ENEMIES, ENEMY_ORDER } = TD;
const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
const perHit = (d, armor) => Math.max(d - armor, d * 0.25);
function prng(seed) { // mulberry32
let a = seed >>> 0;
return function () {
a = (a + 0x6D2B79F5) >>> 0;
let t = a;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
class Base {
constructor(sim, role, o) {
o = o || {};
this.sim = sim; this.role = role;
this.by = o.by | 0;
this.skill = clamp(o.skill === undefined || o.skill === null ? 1 : +o.skill, 0, 1);
this.rng = prng((o.seed === undefined ? 1 : o.seed) * 7919 + (role === 'defender' ? 13 : 29));
this.interval = 1 + (1 - this.skill) * 3; // sim seconds between decisions
this.clock = this.rng() * this.interval; // two bots do not wake on the same tick
this.refused = []; // the last few refusals (for the tools that watch the bots)
}
// the one door to the sim: carries the role and the seat
cmd(c) {
const r = this.sim.cmd(Object.assign({ role: this.role, by: this.by }, c));
if (!r.ok && this.refused.length < 20) this.refused.push({ c: c.c, id: c.id || c.type || c.kind, reason: r.reason });
return r;
}
think(dt) {
if (this.sim.state !== 'playing') return;
this.clock += dt;
if (this.clock < this.interval) return;
this.clock = 0;
this.act();
}
}
// ====================================================================================================================
// The defender: turrets where the route is, a maze of wall lines, upgrades, and the counter-tools.
// ====================================================================================================================
const TURRETS = TD.TOWER_ORDER.filter((t) => TOWERS[t].role !== 'wall'); // whatever the table holds (a new tower type is simply another candidate)
const DIRS = [[1, 0], [-1, 0], [0, 1], [0, -1]];
// Until it has a few turrets the defender does not know what is coming; a crowd (ground or air) at the very start is what loses a round
// fastest, and cheap rapid fire stops that best per credit. After the opening the scores below follow what it has actually seen.
const OPENING = { filter: 3, arc: 1.2, throttle: 0.6, mortar: 0.5, ids: 0.4, sandbox: 0.3, balancer: 0.1, uplink: 0.1 };
class Defender extends Base {
constructor(sim, o) {
super(sim, 'defender', o);
const r = this.rng, s = this.skill;
this.share = (0.12 + 0.2 * r()) * (s < 0.3 ? 0 : s); // the share of all the credits it has seen that may go into walls
this.openN = 7 + Math.floor(r() * 4); // turrets that count as the opening (and come before the first wall)
this.jitter = 0.1 + (1 - s) * 0.5; // relative noise on every score
this.fav = {}; // every player has favourites
for (const t of TURRETS) this.fav[t] = 0.85 + 0.3 * r();
this.types = TURRETS.filter((t) => s > 0.5 || (TOWERS[t].role !== 'control' && TOWERS[t].role !== 'support')); // the fiddly ones are for the better players
this.plan = []; // wall cells still to place
this.spentWalls = 0; this.spentOther = 0;
this.nextSeg = 0; this.noSegRev = -1;
this.th = { air: 0.15, armor: 0.1, swarm: 0.5 }; // what it has been seeing (moving averages); the start is a guess: expect a crowd, mostly on the ground
this.clock = this.interval; // the defender builds at once: a round starts with the attacker's credits in hand
this.geo = null; this.tables = {};
this.badUntil = new Map(); // cells where a turret just failed to go up (a packet in the way): not again for a while
}
act() {
this.observe();
if (this.skill >= 0.3) this.tools();
for (let n = 0; n < 10; n++) if (!this.step()) break; // (the opening spends the whole start purse in one go)
}
// ---- what is coming: the share of flyers / armoured / tiny units among what is on the board (judged by kind and hit points, as the screen shows them)
observe() {
const ms = this.sim.monsters.filter((m) => !m.dead);
if (!ms.length) return;
let air = 0, armor = 0, small = 0;
for (const m of ms) {
const d = ENEMIES[m.kind];
if (d.air) air++;
if (d.armor >= 3 || d.shield || m.maxhp >= 300) armor++;
if (m.maxhp <= 20) small++;
}
const a = 0.25, n = ms.length;
this.th.air += a * (air / n - this.th.air);
this.th.armor += a * (armor / n - this.th.armor);
this.th.swarm += a * (Math.min(1, (small + Math.max(0, n - 12)) / n) - this.th.swarm);
}
// ---- counter-tools: patch / scan EMPed towers, scan stealth, repair, quarantine
tools() {
const sim = this.sim, T = VS.TOOLS, cd = sim.privateState('defender').cd, rng = this.rng;
const can = (id) => cd[id] <= 0 && sim.gold >= T[id].cost;
const awake = rng() < 0.45 + 0.55 * this.skill; // a slower player reacts a decision later
const emped = sim.towers.filter((t) => t.empT > 0);
if (emped.length && awake) {
const r2 = T.scan.radius * T.scan.radius, near = (a, b) => (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y) <= r2 * 0.5;
const group = emped.filter((t) => near(t, emped[0]));
if (group.length >= 2 && can('scan')) {
const cx = group.reduce((s, t) => s + t.x + 0.5, 0) / group.length, cy = group.reduce((s, t) => s + t.y + 0.5, 0) / group.length;
this.cmd({ c: 'tool', id: 'scan', x: cx, y: cy });
} else if (can('patch') && sim.gold >= T.patch.cost + 20) this.cmd({ c: 'tool', id: 'patch', tid: emped[0].id });
}
const hidden = this.silent();
if (hidden.length >= 2 && awake && can('scan') && sim.gold >= T.scan.cost + 60) {
const core = sim.board.core, h = hidden.reduce((a, b) => (Math.hypot(a.x - core.x, a.y - core.y) < Math.hypot(b.x - core.x, b.y - core.y) ? a : b));
this.cmd({ c: 'tool', id: 'scan', x: h.x, y: h.y });
}
if (can('repair') && sim.lives <= sim.maxLives - T.repair.amount && sim.gold >= T.repair.cost + 40) this.cmd({ c: 'tool', id: 'repair' });
if (can('quarantine') && awake && sim.gold >= T.quarantine.cost) {
const core = sim.board.core; // units about to reach the server, by the integrity they would cost
let danger = 0;
for (const m of sim.monsters) if (!m.dead && Math.hypot(m.x - core.x - 0.5, m.y - core.y - 0.5) <= 5) danger += ENEMIES[m.kind].leak;
if (danger >= Math.max(4, sim.lives * 0.35)) this.cmd({ c: 'tool', id: 'quarantine' });
}
}
// Units standing inside the reach of an attack tower that is working and could hit them, while that tower has no target: something is hiding
// them (stealth). Only what a screen shows: the tower list, whether a tower is out (EMP) and what it is aiming at.
silent() {
const out = [];
for (const m of this.sim.monsters) {
if (m.dead) continue;
for (const t of this.sim.towers) {
const d = TOWERS[t.type];
if (d.role !== 'attack' || t.empT > 0 || t.tgt !== 0 || (m.air ? !d.air : !d.ground)) continue;
const r = d.levels[t.level - 1].range, dx = m.x - t.x - 0.5, dy = m.y - t.y - 0.5;
if (dx * dx + dy * dy <= r * r) { out.push(m); break; }
}
}
return out;
}
turretCount() { let n = 0; for (const t of this.sim.towers) if (TOWERS[t.type].role !== 'wall') n++; return n; }
step() {
if (this.turretCount() >= this.openN && this.mazeStep()) return true;
return this.buyBest();
}
// ---- the maze: wall lines that lengthen the route, under a budget that is a share of everything it has been paid
wallBudget() {
const sim = this.sim, total = this.spentWalls + this.spentOther + sim.gold;
const ramp = clamp((sim.time - 15) / 45, 0, 1); // the first minute belongs to the turrets
return this.share * ramp * total + (ramp > 0 ? 10 : 0) - this.spentWalls;
}
mazeStep() {
const sim = this.sim, wc = TOWERS.wall.levels[0].cost;
if (!this.plan.length) {
if (this.share <= 0 || sim.time < this.nextSeg || this.noSegRev === sim.rev) return false;
if (this.wallBudget() < 2 * wc || sim.gold < 2 * wc) return false;
this.nextSeg = sim.time + 4;
const seg = this.bestSegment();
if (!seg) { this.noSegRev = sim.rev; return false; }
this.plan = seg;
}
let placed = 0;
while (this.plan.length && sim.gold >= wc && this.wallBudget() >= wc) {
const c = this.plan[0], r = this.cmd({ c: 'place', type: 'wall', x: c[0], y: c[1] });
if (r.ok) { placed++; this.spentWalls += wc; this.plan.shift(); }
else if (r.reason === 'monster') break; // a packet is in the way: try again next time
else if (r.reason === 'occupied') this.plan.shift();
else { this.plan = []; break; }
}
return placed > 0;
}
// The wall line (from a border / a solid cell, straight, up to 14 cells) that adds the most route length per credit. A sample of
// the possible lines, a path field per candidate: the cost is bounded (about 700 fields).
bestSegment() {
const sim = this.sim, b = sim.board, cols = b.cols, rows = b.rows, rng = this.rng, wc = TOWERS.wall.levels[0].cost;
const mc = sim.monsterCells(), solid = Uint8Array.from(b.solid), base = b.routeLen, geo = this.geometry();
const starts = [];
for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) {
const i = y * cols + x;
if (solid[i] || b.isSpecial(x, y) || mc.reserved.has(i)) continue;
for (const d of DIRS) {
const px = x - d[0], py = y - d[1];
if (px < 0 || py < 0 || px >= cols || py >= rows || solid[py * cols + px]) starts.push([x, y, d]);
}
}
for (let i = starts.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)), t = starts[i]; starts[i] = starts[j]; starts[j] = t; }
let best = null;
for (const [x0, y0, d] of starts.slice(0, 120)) {
let cx = x0, cy = y0, touched = false;
const added = [];
for (let l = 1; l <= 14; l++) {
if (cx < 0 || cy < 0 || cx >= cols || cy >= rows) break;
const ci = cy * cols + cx;
if (solid[ci] || b.isSpecial(cx, cy) || mc.reserved.has(ci)) break;
solid[ci] = 1; added.push(ci);
if (geo.onRoute[ci]) touched = true;
if (touched && l >= 3 && l % 2 === 1) {
const f = TD.buildField(cols, rows, solid, b.coreIdx);
let after = 0, blocked = false;
for (const sp of b.spawns) { const v = f[sp.y * cols + sp.x]; if (!isFinite(v)) { blocked = true; break; } after += v; }
if (!blocked) for (const m of mc.must) if (!isFinite(f[m])) { blocked = true; break; }
if (blocked) break;
const gain = after - base, near = 1 - clamp(Math.hypot(cx - b.core.x, cy - b.core.y) / 18, 0, 1);
const ratio = gain / (wc * l) * (1 + 0.8 * near);
if (gain >= 3 && (!best || ratio > best.ratio)) best = { ratio, x: x0, y: y0, d, l };
}
cx += d[0]; cy += d[1];
}
for (const ci of added) solid[ci] = 0;
}
if (!best) return null;
const cells = [];
for (let k = 0; k < best.l; k++) cells.push([best.x + best.d[0] * k, best.y + best.d[1] * k]);
return cells;
}
// ---- turrets and upgrades, scored by (damage x what the route lets the turret reach x what is coming) per credit
geometry() {
const sim = this.sim, b = sim.board;
if (this.geo && this.geo.rev === sim.rev) return this.geo;
const gx = [], gy = [], onRoute = new Uint8Array(b.cols * b.rows);
for (const route of b.routes) for (const c of route) { gx.push(c[0] + 0.5); gy.push(c[1] + 0.5); onRoute[c[1] * b.cols + c[0]] = 1; }
const ax = [], ay = []; // flyers go straight from each gateway to the server
for (const sp of b.spawns) {
const x0 = sp.x + 0.5, y0 = sp.y + 0.5, x1 = b.core.x + 0.5, y1 = b.core.y + 0.5, n = Math.max(2, Math.ceil(Math.hypot(x1 - x0, y1 - y0)));
for (let i = 0; i <= n; i++) { ax.push(x0 + (x1 - x0) * i / n); ay.push(y0 + (y1 - y0) * i / n); }
}
this.geo = { rev: sim.rev, gx, gy, ax, ay, onRoute };
this.tables = {};
return this.geo;
}
cover(x, y, r, air) { // how much route (and flight line) is within r of the point
const g = this.geometry(), r2 = r * r, wa = 0.3 + 1.5 * this.th.air;
let s = 0;
for (let i = 0; i < g.gx.length; i++) { const dx = g.gx[i] - x, dy = g.gy[i] - y; if (dx * dx + dy * dy <= r2) s++; }
if (air) for (let i = 0; i < g.ax.length; i++) { const dx = g.ax[i] - x, dy = g.ay[i] - y; if (dx * dx + dy * dy <= r2) s += wa * 0.5; }
return s;
}
// the best free cells for a tower of range r (cached until the board changes)
sites(r, air) {
const key = r + (air ? 'a' : 'g'), g = this.geometry(); // (the geometry drops the cached tables when the board has changed)
if (this.tables[key]) return this.tables[key];
const sim = this.sim, b = sim.board, res = sim.monsterCells().reserved, list = [];
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) {
const i = y * b.cols + x;
if (b.solid[i] || b.obst[i] || g.onRoute[i] || res.has(i) || b.isSpecial(x, y) || (this.badUntil.get(i) || 0) > sim.time) continue;
const c = this.cover(x + 0.5, y + 0.5, r, air);
if (c > 0) list.push({ x, y, c });
}
list.sort((p, q) => q.c - p.c);
return (this.tables[key] = list.slice(0, 8));
}
// a turret's worth in "damage per second against what is coming"
power(type, st) {
const def = TOWERS[type], th = this.th, arm = 1 + 3 * th.armor;
if (def.role === 'attack') {
let p = (type === 'uplink' ? st.dmg : perHit(st.dmg, arm)) * st.rate;
if (type === 'mortar') p *= 1.2 * (1 + th.swarm) * (1 - 0.9 * th.air);
else if (type === 'arc') { let c = 0, m = 1; for (let i = 0; i < st.chains; i++) { m *= st.falloff; c += m; } p *= 1 + c * (0.3 + th.swarm); }
else if (type === 'uplink') p *= 2.5;
else if (type === 'ids') p *= (1 + 0.5 * th.armor) * (1 - 0.6 * th.swarm); // one big shot at a time: poor against a crowd
return p;
}
if (def.role === 'aura') return st.slow * 60;
if (def.role === 'control') return (st.stun / st.pulse) * 70;
return 0;
}
options() {
const sim = this.sim, opts = [], count = {};
for (const t of sim.towers) count[t.type] = (count[t.type] || 0) + 1;
const jit = (v) => v * (1 + this.jitter * (this.rng() - 0.5) * 2);
const opening = this.turretCount() < this.openN;
const diversity = (type) => (opening && OPENING[type] !== undefined ? OPENING[type] : 1) / (1 + 0.2 * (count[type] || 0));
for (const type of this.types) {
const def = TOWERS[type], st = def.levels[0], price = TD.priceFor(type, sim.towers);
if (price > sim.gold * 3) continue;
if (def.role === 'support') { // a booster: next to several attackers
const att = sim.towers.filter((t) => TOWERS[t.type].role === 'attack');
if (att.length < 3) continue;
const b = sim.board, res = sim.monsterCells().reserved;
let bestN = 0, bestC = null;
for (let y = 0; y < b.rows; y++) for (let x = 0; x < b.cols; x++) {
const i = y * b.cols + x;
if (b.solid[i] || b.obst[i] || res.has(i) || b.isSpecial(x, y) || this.geometry().onRoute[i]) continue;
let n = 0;
for (const t of att) if ((t.x - x) * (t.x - x) + (t.y - y) * (t.y - y) <= st.range * st.range) n += this.power(t.type, TOWERS[t.type].levels[t.level - 1]);
if (n > bestN) { bestN = n; bestC = { x, y }; }
}
if (bestC) opts.push({ kind: 'new', type, x: bestC.x, y: bestC.y, cost: price, ratio: jit(st.boost * bestN * 0.6 / price * this.fav[type]) });
continue;
}
const air = !!def.air, sites = this.sites(st.range, air);
for (const site of sites.slice(0, 4)) {
const v = this.power(type, st) * site.c / price * this.fav[type] * diversity(type);
opts.push({ kind: 'new', type, x: site.x, y: site.y, cost: price, ratio: jit(v) });
}
}
for (const t of sim.towers) {
const def = TOWERS[t.type], nx = def.levels[t.level];
if (!nx || def.role === 'wall' || def.role === 'support' || !this.types.includes(t.type)) continue;
const cost = sim.upgradeCost(t);
if (cost === null || cost > sim.gold * 3) continue;
const cur = def.levels[t.level - 1], c = this.cover(t.x + 0.5, t.y + 0.5, nx.range, !!def.air);
const v = (this.power(t.type, nx) * c - this.power(t.type, cur) * this.cover(t.x + 0.5, t.y + 0.5, cur.range, !!def.air)) / cost * this.fav[t.type];
if (v > 0) opts.push({ kind: 'up', id: t.id, type: t.type, cost, ratio: jit(v) * (opening ? 0.5 : 1.1) });
}
return opts;
}
buyBest() {
const sim = this.sim;
if (sim.gold < 25) return false;
const opts = this.options().filter((o) => o.ratio > 0).sort((p, q) => q.ratio - p.ratio);
if (!opts.length) return false;
const best = opts[0], aff = opts.find((o) => o.cost <= sim.gold);
if (!aff) return false;
if (aff !== best && best.cost <= sim.gold * 3 && aff.ratio < 0.6 * best.ratio) return false; // rather save for the clearly better one
const r = aff.kind === 'up' ? this.cmd({ c: 'upgrade', id: aff.id }) : this.cmd({ c: 'place', type: aff.type, x: aff.x, y: aff.y });
if (r.ok) this.spentOther += aff.cost;
else if (aff.kind === 'new') { this.badUntil.set(aff.y * sim.board.cols + aff.x, sim.time + 6); this.tables = {}; }
return r.ok;
}
}
// ====================================================================================================================
// The attacker: reads the tower mix, buys what the defence is worst at per credit, saves a convoy, buys tech, plays the abilities.
// ====================================================================================================================
const TECH_WEIGHT = { armor: 1.0, health: 1.0, speed: 0.8, regen: 0.45, shield: 0.7, stealth: 0.7, crypt: 0.5 };
class Attacker extends Base {
constructor(sim, o) {
super(sim, 'attacker', o);
const r = this.rng, s = this.skill;
this.interval = 1 + (1 - s) * 2.5;
this.aggr = 0.75 + 0.6 * r(); // how big a convoy it wants before it launches
this.techShare = (0.15 + 0.2 * r()) * (s < 0.3 ? 0 : s); // the share of everything it has seen that may go into tech
this.spent = { tech: 0, units: 0, abilities: 0 };
this.lastLaunch = 0;
this.want = null; this.wantAt = 0; // the kind it is saving for
this.p = null;
}
act() {
const sim = this.sim, p = this.p = sim.privateState('attacker');
const def = this.assess();
this.def = def;
if (this.skill >= 0.3) { this.abilities(p, def); this.tech(this.p = sim.privateState('attacker'), def); }
this.units(this.p = sim.privateState('attacker'), def); // (what it has left after what it just bought)
}
// ---- the defence, in numbers
assess() {
const sim = this.sim, towers = [], hits = [];
let dps = 0, airDps = 0, splash = 0, slowers = 0, best = null;
for (const t of sim.towers) {
const def = TOWERS[t.type], st = def.levels[t.level - 1];
if (t.empT > 0) continue;
if (def.role === 'aura' || def.role === 'control') { slowers++; continue; }
if (def.role !== 'attack') continue;
const d = st.dmg * st.rate;
towers.push(t);
dps += d; if (def.air) airDps += d;
if (t.type === 'mortar' || t.type === 'arc' || t.type === 'uplink') splash += d;
hits.push({ dmg: st.dmg, w: d, ignore: t.type === 'uplink', air: !!def.air });
if (!best || d > best.d) best = { t, d };
}
return { n: towers.length, dps, airDps, splashShare: dps ? splash / dps : 0, slowers, hits, best: best && best.t };
}
// the part of the defence's damage that gets through to a unit with this much armour (and that can reach it at all)
bite(def, armor, air) {
let tot = 0, got = 0;
for (const h of def.hits) {
if (air && !h.air) continue;
tot += h.w; got += h.w * (h.ignore ? 1 : perHit(h.dmg, armor) / h.dmg);
}
return got;
}
// value per credit of a unit kind against this defence: leak damage x the chance to get through / price
kindValue(kind, def) {
const d = ENEMIES[kind], T = this.p.tech, X = VS.TECH;
const hp = d.hp * (1 + X.health.per * T.health) + (d.shield || 0) + X.shield.per * T.shield;
const dps = Math.max(1, this.bite(def, d.armor + X.armor.per * T.armor, d.air));
let dur = hp / dps; // seconds of the whole defence's fire to kill one
if (d.hp <= 20 && !d.air) dur *= 1 - 0.5 * def.splashShare; // little ones die in groups to splash
if (d.heal) dur *= 1.4; // a healer keeps the others alive
const speed = d.speed * (1 + X.speed.per * T.speed);
const escape = 1 - Math.exp(-dur * speed / 3);
return d.leak * escape / d.buyCost;
}
// ---- units: rush a weak defence, otherwise save a convoy and launch it
units(p, def) {
const sim = this.sim, rng = this.rng, left = sim.vs.limit - sim.time;
const price = (k) => ENEMIES[k].buyCost;
const weak = def.dps < 40; // (almost) nothing shoots yet: units that leak pay themselves back, so go now
const endgame = left < 50; // the clock is about to decide it: nothing is worth saving any more
const direct = weak || endgame;
const mix = this.mix(def);
// the money it can spend on units now: a share is kept for tech while that is still worth it
let budget = p.credits - this.techReserve(p);
if (direct && budget < price(mix[0].k)) budget = p.credits;
let room = direct ? VS.MAX_ALIVE - sim.vsAlive() : VS.MAX_STAGED - p.staged.reduce((s, e) => s + e[1], 0);
// a shopping list of one: draw a kind by its share, SAVE until it is affordable (not "spend on whatever is cheap meanwhile": a
// trojan would never get bought), then buy a chunk of it
for (let guard = 0; guard < 6 && room > 0; guard++) {
if (!this.want || sim.time - this.wantAt > 20 || !mix.some((m) => m.k === this.want)) { this.want = this.draw(mix); this.wantAt = sim.time; }
const cost = price(this.want);
if (budget < cost) break;
const n = Math.min(Math.max(1, Math.floor(Math.min(budget, 40 + 60 * rng()) / cost)), room);
const r = this.cmd({ c: direct ? 'spawn' : 'stage', kind: this.want, n });
if (!r.ok) break;
this.spent.units += n * cost; budget -= n * cost; room -= n; this.want = null;
}
// launch the convoy when it is big enough for this defence, when waiting has gone on long enough, or when the round is nearly over
const staged = sim.privateState('attacker').staged, value = staged.reduce((s, e) => s + e[1] * price(e[0]), 0);
if (!value) return;
const need = this.aggr * (60 + 22 * def.n + 0.5 * def.dps) * (0.8 + 0.4 * rng());
const waited = sim.time - this.lastLaunch;
if (value >= need || (waited > 90 && value >= 80) || (endgame && waited > 5)) {
if (this.cmd({ c: 'launch' }).ok) this.lastLaunch = sim.time;
}
}
draw(mix) { // a kind, with the probability of its share
let x = this.rng();
for (const m of mix) { x -= m.share; if (x <= 0) return m.k; }
return mix[0].k;
}
// the kinds worth buying, best first, with the share of the money each gets
mix(def) {
const rng = this.rng, noise = 0.1 + (1 - this.skill) * 0.6;
const kinds = ENEMY_ORDER.map((k) => ({ k, v: this.kindValue(k, def) * (1 + noise * (rng() - 0.5) * 2) })).sort((a, b) => b.v - a.v);
const top = kinds.slice(0, 3).filter((e, i) => i === 0 || e.v > 0.45 * kinds[0].v);
const sum = top.reduce((s, e) => s + e.v * e.v, 0) || 1;
const out = top.map((e) => ({ k: e.k, share: e.v * e.v / sum }));
if (out[0].k === 'trojan' && !out.some((e) => e.k === 'daemon')) { out[0].share *= 0.85; out.push({ k: 'daemon', share: 0.15 }); } // a healer behind the armour
return out;
}
// ---- tech: a share of everything seen, on whatever the defence is worst at stopping
techReserve(p) {
if (this.skill < 0.3) return 0;
const seen = p.credits + this.spent.tech + this.spent.units + this.spent.abilities;
const owed = this.techShare * seen - this.spent.tech;
return owed > 0 ? Math.min(owed, 400) : 0;
}
tech(p, def) {
const sim = this.sim, T = p.tech, reserve = this.techReserve(p);
if (reserve <= 0) return;
const wArmor = def.dps ? 1 - this.bite(def, 3, false) / def.dps : 0.3; // how much a few points of armour would cut the defence
const want = {
armor: TECH_WEIGHT.armor * (0.3 + wArmor), health: TECH_WEIGHT.health, speed: TECH_WEIGHT.speed, regen: TECH_WEIGHT.regen,
shield: TECH_WEIGHT.shield * (def.dps > 150 ? 1 : 0.6), stealth: TECH_WEIGHT.stealth * Math.min(1.5, 0.3 + def.n / 8),
crypt: TECH_WEIGHT.crypt * (def.slowers ? 1.6 : 0.2),
};
let bestId = null, bestV = 0, bestCost = 0;
for (const id of VS.TECH_ORDER) {
const cost = sim.techCost(id);
if (cost === null || cost > p.credits || cost > reserve * 1.6 + 1) continue; // (only when its share of the money has built up)
const v = want[id] / Math.pow(1.5, T[id]) * (1 + 0.2 * (this.rng() - 0.5)) / cost;
if (v > bestV) { bestV = v; bestId = id; bestCost = cost; }
}
if (bestId && this.cmd({ c: 'tech', id: bestId }).ok) this.spent.tech += bestCost;
}
// ---- abilities: only when there is a convoy on the map worth the money
abilities(p, def) {
const sim = this.sim, A = VS.ABILITIES, rng = this.rng;
const mine = sim.monsters.filter((m) => !m.dead && !m.decoy);
if (mine.length < 3 || !def.n) return;
const value = mine.reduce((s, m) => s + m.buyCost, 0);
const ready = (id) => p.cd[id] <= 0 && p.credits >= A[id].cost && value >= 2.2 * A[id].cost;
const inReach = (m) => def.best && (m.x - def.best.x - 0.5) * (m.x - def.best.x - 0.5) + (m.y - def.best.y - 0.5) * (m.y - def.best.y - 0.5) <= 100;
const pay = (id, extra) => { if (this.cmd(Object.assign({ c: 'ability', id }, extra)).ok) this.spent.abilities += A[id].cost; };
const underFire = mine.filter((m) => this.inRange(m)).length;
if (ready('emp') && def.best && mine.some(inReach) && rng() < 0.7) pay('emp', { tid: def.best.id });
else if (ready('ddos') && underFire >= Math.max(5, mine.length * 0.4) && value >= 400) pay('ddos');
else if (ready('surge') && mine.length >= 8 && underFire >= 2) pay('surge');
else if (ready('decoy') && def.best && underFire >= 3 && rng() < 0.5) pay('decoy', { tid: def.best.id });
}
inRange(m) { // is any attack tower reaching this unit now?
for (const t of this.sim.towers) {
const d = TOWERS[t.type];
if (d.role !== 'attack' || t.empT > 0) continue;
const r = d.levels[t.level - 1].range;
if ((m.x - t.x - 0.5) * (m.x - t.x - 0.5) + (m.y - t.y - 0.5) * (m.y - t.y - 0.5) <= r * r) return true;
}
return false;
}
}
function create(sim, role, opts) {
if (!sim || !sim.vs) throw new Error('NWBot needs a versus sim');
if (role === 'defender') return new Defender(sim, opts);
if (role === 'attacker') return new Attacker(sim, opts);
throw new Error('NWBot role must be "defender" or "attacker"');
}
return { create, Defender, Attacker, prng };
});

View file

@ -15,6 +15,24 @@
* ctrl.difficulty the game's difficulty id (TD.DIFFICULTIES); `newGame(map, difficulty)` keeps the current one when none is given
* ctrl.preview(x,y,routes) would a block there be legal, and what does it do to the route?
* events ctrl.on('events', list) | 'reject' | 'mark' | 'players' | 'status' | 'joined' | 'newgame' | 'fatal' | 'rtt'
*
* VERSUS (attack vs defend, docs/VERSUS.md and docs/PROTOCOL.md "Versus"). Both controllers speak the same language to the UI, so the UI code
* does not care whether the other seat is a person on the server or the computer in this tab:
* ctrl.mode 'solo' (LocalController), 'coop' or 'versus' (what the room was created as; RemoteController learns it from the server's state)
* ctrl.vs the newest match message { phase, round, rounds, roles:{slot:'attacker'|'defender'}, random, bot, limit, ready, frozen, countdown?, next?,
* result?, history?, scores?, winner?, forfeit?, rematch? }, or null (not versus); event 'vs' fires on every change.
* phase: lobby | countdown | playing | roundover | matchover (a LocalController starts in the countdown: there is no lobby)
* ctrl.priv the newest role-private data { role, ...privateState }: attacker { credits, income, tech, staged, cd, active }, defender { cd };
* event 'priv'. Compare priv.role with ctrl.role after a role swap (the first priv of a round replaces the old one).
* ctrl.role my role in the current round ('attacker' | 'defender') or null
* ctrl.view.vs the SHARED round block { t, lim, st } (round clock, limit, staged convoy size) or null; ctrl.view.mode as ctrl.mode
* view.towers[].empT seconds of EMP left on a tower (0 when none), versus only
* ctrl.send(cmd) also the versus commands: spawn | stage | launch | tech | ability | tool (see the protocol); the role is the controller's, never the caller's
* ctrl.vsSend(c, v, extra) lobby / match control: 'role' | 'ready' | 'bot' | 'start' | 'next' | 'rematch'; wrappers vsRole(v) vsReady(v) vsBot(v, skill)
* vsStart() vsNext() vsRematch(). A LocalController has no lobby: role / ready / bot / start are refused ('phase'),
* `next` starts round 2 and `rematch` a new match with the first roles swapped.
* ctrl.ctl(c, v) does nothing in versus (no pause, no speed); `new LocalController({ map, mode:'versus', role:'attacker'|'defender'|'random', limit, skill })`
* plays against NWBot (js/bot.js must be loaded), `new RemoteController({ ..., mode:'versus', limit })` creates a versus room.
*/
(function (root) {
'use strict';
@ -42,6 +60,32 @@
return c;
}
// ---- match rules (the same rules as server/versus.js: test/controllers.test.js feeds both the same rounds) ----
const vsOpposite = (r) => (r === 'attacker' ? 'defender' : 'attacker');
const vsSwap = (roles) => ({ 0: vsOpposite(roles[0]), 1: vsOpposite(roles[1]) });
// history entry: { round, roles:{0,1}, result:{ winner, t, integrityLost, attacker:slot, defender:slot, forfeit? } }
function matchScores(history, names) {
return [0, 1].map((slot) => {
let fellAt = null, lost = 0;
for (const h of history) {
if (h.roles[slot] !== 'attacker') continue;
lost += h.result.integrityLost || 0;
if (h.result.winner === 'attacker' && !h.result.forfeit && (fellAt === null || h.result.t < fellAt)) fellAt = h.result.t;
}
return { slot, name: names[slot], fellAt, integrityLost: lost };
});
}
function matchWinner(scores) {
const a = scores[0], b = scores[1];
if (a.fellAt !== null && b.fellAt !== null) return a.fellAt === b.fellAt ? null : a.fellAt < b.fellAt ? a.slot : b.slot;
if (a.fellAt !== null) return a.slot;
if (b.fellAt !== null) return b.slot;
return a.integrityLost === b.integrityLost ? null : a.integrityLost > b.integrityLost ? a.slot : b.slot;
}
const VS_COUNTDOWN_MS = 3000; // a local match: the pause before each round (the server's default too)
const VS_BOT_STEP = 0.25; // the computer is asked to think at about 4 Hz of game time
const VS_PRIV_MS = 250; // role-private data at 4 Hz
// ws(s)://<same host>/ws, relative to the page so it also works under a proxy path prefix
function wsUrl() {
const u = new URL('ws', root.location.href);
@ -60,19 +104,132 @@
this.speed = 1; this.paused = false;
this.players = [{ slot: 0, name: 'You', online: true, host: true }];
this.you = { slot: 0, host: true };
this._fresh();
this.versus = !!(opts && opts.mode === 'versus');
this.mode = this.versus ? 'versus' : 'solo';
this.vs = null; this.priv = null; this.bot = null;
if (this.versus) { this._vsInit(opts); this._vsRound(); } else this._fresh();
}
get role() { return this.vs ? this.vs.roles[0] : null; }
_fresh() {
this.sim = new TD.Sim({ map: this.mapId, difficulty: this.difficulty });
this.sim = this.versus ? new TD.Sim({ map: this.mapId, mode: 'versus', limit: this.limit }) : new TD.Sim({ map: this.mapId, difficulty: this.difficulty });
this.board = this.sim.board;
this.acc = 0; this.last = 0;
this.view = {
gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0,
speed: this.speed, paused: this.paused, time: 0, difficulty: this.difficulty,
speed: this.speed, paused: this.paused, time: 0, difficulty: this.difficulty, mode: this.mode, vs: null,
towers: this.sim.towers, monsters: this.sim.monsters, bullets: this.sim.bullets, cursors: [],
};
this._sync();
}
// ---- versus against the computer (the human is seat 0, NWBot seat 1) ----
_vsInit(opts) {
if (!root.NWBot) throw new Error('A versus game against the computer needs js/bot.js (NWBot) to be loaded before it is created.');
const V = TD.VS;
this.limit = Number.isFinite(opts.limit) && opts.limit > 0 ? opts.limit : V.DEFAULT_LIMIT;
this.skill = Number.isFinite(opts.skill) ? clamp(opts.skill, 0, 1) : 1;
this.rounds = V.ROUNDS;
this.countdownMs = Number.isFinite(opts.countdownMs) ? opts.countdownMs : VS_COUNTDOWN_MS;
this.seed = Number.isInteger(opts.seed) ? opts.seed : Math.floor(Math.random() * 0x7fffffff);
const mine = opts.role === 'attacker' || opts.role === 'defender' ? opts.role : (Math.random() < 0.5 ? 'attacker' : 'defender');
this.firstRoles = { 0: mine, 1: vsOpposite(mine) };
this.players = [{ slot: 0, name: 'You', online: true, host: true }];
this._privAt = -Infinity;
this._vsStartMatch(this.firstRoles);
}
_vsStartMatch(roles) {
this.firstRoles = { 0: roles[0], 1: roles[1] };
this.vsm = { phase: 'countdown', round: 1, roles: { 0: roles[0], 1: roles[1] }, history: [], result: null, scores: null, winner: null, cdMs: 0, cdSent: -1, botAcc: 0 };
}
// The sim and the computer of the current round (called when a round's countdown starts).
_vsRound() {
const m = this.vsm;
this._fresh();
m.phase = 'countdown'; m.cdMs = this.countdownMs; m.cdSent = Math.ceil(m.cdMs / 1000); m.botAcc = 0; m.result = null;
this.bot = root.NWBot.create(this.sim, m.roles[1], { seed: this.seed + m.round * 101, skill: this.skill, by: 1 });
this._vsEmit();
this._vsPriv();
}
_vsNames() { return [this.players[0].name, 'Computer']; }
_vsMsg() {
const m = this.vsm;
const out = {
t: 'vs', phase: m.phase, round: m.round, rounds: this.rounds, roles: { 0: m.roles[0], 1: m.roles[1] }, random: false,
bot: { slot: 1, role: m.roles[1], skill: this.skill, name: 'Computer' }, limit: this.limit, ready: { 0: true, 1: true }, frozen: false,
};
if (m.phase === 'countdown') out.countdown = Math.max(0, Math.ceil(m.cdMs / 1000));
if (m.phase === 'roundover') out.next = { 0: false, 1: true };
if (m.phase === 'roundover' || m.phase === 'matchover') out.result = m.result;
if (m.history.length) out.history = m.history;
if (m.phase === 'matchover') { out.scores = m.scores; out.winner = m.winner; out.forfeit = null; out.rematch = { 0: false, 1: true }; }
return out;
}
_vsEmit() { this.vs = this._vsMsg(); this.emit('vs', this.vs); }
_vsPriv() {
const role = this.vsm.roles[0], ps = this.sim.privateState(role);
if (!ps) return;
this.priv = Object.assign({ t: 'priv', role }, ps);
this.emit('priv', this.priv);
}
_vsRoundEnd() {
const m = this.vsm, res = this.sim.vs.result;
const attacker = m.roles[0] === 'attacker' ? 0 : 1;
const entry = { round: m.round, roles: { 0: m.roles[0], 1: m.roles[1] }, result: { winner: res.winner, t: res.t, integrityLost: res.integrityLost, attacker, defender: 1 - attacker } };
m.history.push(entry); m.result = entry.result;
this.bot = null;
if (m.round < this.rounds) m.phase = 'roundover';
else { m.phase = 'matchover'; m.scores = matchScores(m.history, this._vsNames()); m.winner = matchWinner(m.scores); }
this._vsEmit();
this._vsPriv();
}
_vsUpdate(now) {
const m = this.vsm;
if (!this.last) this.last = now;
const dt = Math.min(0.25, Math.max(0, (now - this.last) / 1000));
this.last = now;
if (m.phase === 'countdown') {
m.cdMs -= dt * 1000;
if (m.cdMs <= 0) { m.phase = 'playing'; this.acc = 0; this._vsEmit(); this._vsPriv(); }
else if (Math.ceil(m.cdMs / 1000) !== m.cdSent) { m.cdSent = Math.ceil(m.cdMs / 1000); this._vsEmit(); }
} else if (m.phase === 'playing') {
this.acc = Math.min(0.6, this.acc + dt);
let ticked = 0;
while (this.acc >= TD.STEP && this.sim.state === 'playing') { this.sim.tick(TD.STEP); this.acc -= TD.STEP; ticked += TD.STEP; }
m.botAcc += ticked;
if (this.bot && m.botAcc >= VS_BOT_STEP) { const d = m.botAcc; m.botAcc = 0; try { this.bot.think(d); } catch (e) { console.error(e); this.bot = null; } }
if (this.sim.state !== 'playing') this._vsRoundEnd();
}
const ev = this.sim.drainEvents();
this._sync();
if (ev.length) this.emit('events', ev);
if ((m.phase === 'countdown' || m.phase === 'playing') && now - this._privAt >= VS_PRIV_MS) { this._privAt = now; this._vsPriv(); }
}
_vsSend(cmd) {
const m = this.vsm;
let res;
if (m.phase !== 'playing') res = { ok: false, reason: m.phase === 'roundover' || m.phase === 'matchover' ? 'over' : 'phase' };
else {
const c = Object.assign({}, cmd, { by: 0, role: m.roles[0] });
res = this.sim.cmd(stampCmd(c, this.view));
}
if (!res.ok) this.emit('reject', { c: cmd.c, reason: res.reason, x: cmd.x, y: cmd.y, id: cmd.id, tid: cmd.tid });
else { this._vsPriv(); this._sync(); }
return res;
}
// lobby / match control; a local game has no lobby, so only `next` and `rematch` do anything
vsSend(c, v) {
const m = this.vsm;
if (!this.versus) return { ok: false, reason: 'versus' };
if (c === 'next' && m.phase === 'roundover') { m.round++; m.roles = vsSwap(m.roles); this._vsRound(); return { ok: true }; }
if (c === 'rematch' && m.phase === 'matchover') { this._vsStartMatch(vsSwap(this.firstRoles)); this._vsRound(); return { ok: true }; }
this.emit('reject', { c, reason: 'phase' });
return { ok: false, reason: 'phase' };
}
vsRole(v) { return this.vsSend('role', v); }
vsReady(v) { return this.vsSend('ready', v); }
vsBot(v, skill) { return this.vsSend('bot', v, { skill }); }
vsStart() { return this.vsSend('start'); }
vsNext() { return this.vsSend('next'); }
vsRematch() { return this.vsSend('rematch'); }
_sync() {
const s = this.sim, v = this.view;
v.gold = s.gold; v.lives = s.lives; v.maxLives = s.maxLives; v.wave = s.wave; v.state = s.state;
@ -80,8 +237,10 @@
v.winWave = isFinite(s.winWave) ? s.winWave : 0; v.rev = s.rev; v.queued = s.spawnQ.length;
v.speed = this.speed; v.paused = this.paused; v.time = s.time; v.difficulty = s.difficulty;
v.towers = s.towers; v.monsters = s.monsters; v.bullets = s.bullets;
if (s.vs) v.vs = { t: TD.round2(s.time), lim: s.vs.limit, st: s.vsStaged() };
}
update(now) {
if (this.versus) { this._vsUpdate(now); return; }
if (!this.last) this.last = now;
const dt = Math.min(0.25, Math.max(0, (now - this.last) / 1000));
this.last = now;
@ -94,11 +253,13 @@
if (ev.length) this.emit('events', ev);
}
send(cmd) {
if (this.versus) return this._vsSend(cmd);
const res = this.sim.cmd(stampCmd(Object.assign({}, cmd, { by: 0 }), this.view));
if (!res.ok) this.emit('reject', { c: cmd.c, reason: res.reason, x: cmd.x, y: cmd.y, id: cmd.id });
return res;
}
ctl(c, v) {
if (this.versus) return; // no pause, no speed in versus
if (c === 'pause') this.paused = !!v;
else if (c === 'speed') this.speed = clamp(v | 0, 1, 3);
this._sync();
@ -106,6 +267,11 @@
preview(x, y, routes) { return this.sim.preview(x, y, routes); }
// `difficulty` absent: the same one again ("Play again"); an unknown one is normal (the sim's rule)
newGame(map, difficulty) {
if (this.versus) { // a new match (the first roles swapped), at once, whatever the phase
if (map) this.mapId = map;
this._vsStartMatch(vsSwap(this.firstRoles)); this._vsRound(); this.emit('newgame');
return;
}
if (map) this.mapId = map;
if (difficulty !== undefined && difficulty !== null) this.difficulty = TD.difficultyId(difficulty);
this._fresh(); this.emit('newgame');
@ -125,6 +291,9 @@
this.pid = opts.pid; this.name = opts.name || 'Player';
this.room = opts.room || null; // null => create a room on first connect
this.mapId = opts.map || 'open';
this.mode = opts.mode === 'versus' ? 'versus' : 'coop'; // what a CREATING join asks for; afterwards whatever the server's state says
this.limit = opts.limit; // versus round limit (seconds) of a creating join
this.vs = null; this.priv = null; // the newest 'vs' / 'priv' messages (see the header)
this.difficulty = TD.difficultyId(opts.difficulty); // what a CREATING join asks for; afterwards whatever the server's state says
this.status = 'idle'; // idle | connecting | joined | reconnecting | closed
this.ws = null; this.players = []; this.you = null; this.board = null;
@ -140,13 +309,14 @@
this.speed = 1; this.paused = false;
this.view = {
gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0,
speed: 1, paused: false, time: 0, difficulty: this.difficulty, towers: [], monsters: [], bullets: [], cursors: [],
speed: 1, paused: false, time: 0, difficulty: this.difficulty, mode: this.mode, vs: null, towers: [], monsters: [], bullets: [], cursors: [],
};
this._onVis = () => { if (!document.hidden) this._wake(); };
document.addEventListener('visibilitychange', this._onVis);
root.addEventListener('online', this._onVis);
this._timers = [];
}
get role() { return this.vs && this.you ? this.vs.roles[this.you.slot] || null : null; }
// The document / window listeners must not outlive the controller (code-19): called when it dies and when it is closed.
_dispose() {
document.removeEventListener('visibilitychange', this._onVis);
@ -162,7 +332,11 @@
this.ws = ws;
ws.onopen = () => {
const j = { t: 'join', pid: this.pid, name: this.name };
if (this.room) j.room = this.room; else { j.map = this.mapId; j.difficulty = this.difficulty; } // only a creating join carries them: a joiner takes the room's
if (this.room) j.room = this.room;
else { // only a creating join carries these: a joiner takes the room's
j.map = this.mapId; j.difficulty = this.difficulty;
if (this.mode === 'versus') { j.mode = 'versus'; if (this.limit) j.limit = this.limit; }
}
this._send(j);
};
ws.onmessage = (e) => { this.lastMsg = performance.now(); this._onMsg(e.data); };
@ -242,10 +416,12 @@
this.everJoined = true;
this.retry = 0; this.speed = m.speed || 1; this.paused = !!m.paused;
this._applyState(m.state, m.snap);
if (m.vs) this.vs = m.vs;
this._setStatus('joined');
this._startRtt();
this.emit('joined', m);
this.emit('players', this.players);
if (m.vs) this.emit('vs', m.vs);
break;
case 'state':
this.speed = m.speed || 1; this.paused = !!m.paused;
@ -257,6 +433,8 @@
{ const me = this.players.find((p) => this.you && p.pid === this.you.pid); if (me) this.you = Object.assign({}, this.you, { host: me.host, slot: me.slot }); }
this.emit('players', this.players);
break;
case 'vs': this.vs = m; this.emit('vs', m); break;
case 'priv': this.priv = m; this.emit('priv', m); break;
case 'reject': this.emit('reject', m); break;
case 'mark': this.emit('mark', m); break;
case 'rtt':
@ -268,7 +446,7 @@
this._die('restarted', this.everJoined ? 'The server restarted, your game was lost.' : 'That co-op game is gone: the server restarted or the room timed out.');
break;
}
const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', bad_request: 'The server did not understand the request.', too_many_rooms: 'The server is full right now. Try again in a minute.', bad_map: 'Unknown map.', bad_difficulty: 'Unknown difficulty.' };
const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', bad_mode: 'Unknown game mode.', bad_limit: 'Unknown round length.', bad_rounds: 'Unsupported number of rounds.', bad_request: 'The server did not understand the request.', too_many_rooms: 'The server is full right now. Try again in a minute.', bad_map: 'Unknown map.', bad_difficulty: 'Unknown difficulty.' };
this._die(m.code || 'error', msgs[m.code] || m.msg || 'Server error.');
break;
}
@ -292,6 +470,8 @@
this.maxLives = state.maxLives; this.winWave = state.winWave;
this.difficulty = TD.isDifficulty(state.difficulty) ? state.difficulty : 'normal'; // (a server from before difficulties sends none)
this.view.difficulty = this.difficulty;
this.mode = state.mode === 'versus' ? 'versus' : 'coop'; this.limit = state.limit || this.limit;
this.view.mode = this.mode;
this.buf.length = 0; this._carryTw = null; this.monCache.clear(); this.bulCache.clear();
if (snap) this._push(snap, true);
}
@ -345,6 +525,7 @@
v.rev = s.rev; v.queued = s.q || 0; v.time = s.time;
v.maxLives = this.maxLives; v.winWave = this.winWave;
v.speed = s.sp || 1; v.paused = !!s.pa;
v.vs = s.vs || null; // versus: the shared round block { t, lim, st }
const gen = ++this._gen;
const kinds = TD.ENEMY_ORDER;
@ -375,6 +556,7 @@
for (const t of this.towers) {
const r = a.tt.get(t.id);
t.tgt = r ? r[1] : 0; t.kills = r ? r[2] : 0;
if (this.mode === 'versus') t.empT = r && r[3] ? r[3] : 0; // versus rows carry a 4th field: seconds of EMP left
}
v.towers = this.towers;
const mySlot = this.you ? this.you.slot : -1;
@ -382,12 +564,19 @@
}
send(cmd) {
const c = Object.assign({}, cmd); delete c.by;
const c = Object.assign({}, cmd); delete c.by; delete c.role; // the server knows the seat and its role
stampCmd(c, this.view);
this._send(Object.assign({ t: 'cmd' }, c));
return { ok: true, pending: true };
}
ctl(c, v) { this._send({ t: 'ctl', c, v }); }
ctl(c, v) { if (this.mode !== 'versus') this._send({ t: 'ctl', c, v }); } // versus has no pause and no speed (the server refuses them)
vsSend(c, v, extra) { this._send(Object.assign({ t: 'vs', c, v }, extra)); return { ok: true, pending: true }; }
vsRole(v) { return this.vsSend('role', v); }
vsReady(v) { return this.vsSend('ready', v); }
vsBot(v, skill) { return this.vsSend('bot', v, skill === undefined ? undefined : { skill }); }
vsStart() { return this.vsSend('start'); }
vsNext() { return this.vsSend('next'); }
vsRematch() { return this.vsSend('rematch'); }
preview(x, y, routes) {
if (!this.board) return { ok: false, reason: 'bounds' };
const reserved = new Set();
@ -423,5 +612,7 @@
NW.LocalController = LocalController;
NW.RemoteController = RemoteController;
NW.matchScores = matchScores; // the match rules (shared with the server by a parity test): also handy for the end screen
NW.matchWinner = matchWinner;
NW.wsUrl = wsUrl;
})(typeof self !== 'undefined' ? self : this);

View file

@ -97,6 +97,14 @@
syncModal();
}
// ------------------------------------------------------------------ versus (js/versus.js): the mode's dialogs, HUD and sounds. With no versus game running (V.active false) it does nothing.
const V = NW.Versus.create({
$, app, renderer, Audio, store, esc, toast, banner, showOverlay, slotColor,
buildPalette, selectType, renderInfo, updatePaletteHint, setScreen, renderPlayers, adoptBoard, resetSelection,
resize: () => scheduleResize(), startLocal: startVersusLocal, connect: connectRemote, cancelPending, invite, exitToMenu, openMenu, closeOverlayToGame,
});
for (const k in V.REASONS) if (!(k in REASONS)) REASONS[k] = V.REASONS[k]; // the versus refusals get words (existing ones keep theirs)
// ------------------------------------------------------------------ dialogs (menu, lobby, help, end are role=dialog)
// While one is open the page behind it is inert (not focusable, not clickable, hidden from screen readers), focus moves into the
// dialog onto its primary button, Tab stays inside it, and focus goes back to where it was when the dialog closes (code-8).
@ -113,7 +121,7 @@
if (ov) {
const btns = [...ov.querySelectorAll('button')].filter(isShown);
const first = btns.find((b) => b.classList.contains('primary')) || btns[0]; // never a text field: on a phone that would raise the keyboard
if (ov.id === 'end') modal.guard = performance.now() + 600; // (see the click guard below)
if (ov.id === 'end' || ov.id === 'vsEnd') modal.guard = performance.now() + 600; // (see the click guard below)
if (first) first.focus({ preventScroll: true });
} else if (was) {
const o = modal.opener; modal.opener = null;
@ -132,7 +140,7 @@
{ const mo = new MutationObserver(syncModal); for (const o of document.querySelectorAll('.overlay')) mo.observe(o, { attributes: true, attributeFilter: ['hidden'] }); }
// The game-over dialog takes focus the moment the game ends, and a player who was tapping Space / Enter to start waves would
// press its focused "Play again" with the next key and never see the result. For the first 0.6 s only a pointer can press its buttons.
$('end').addEventListener('click', (e) => { if (e.detail === 0 && performance.now() < modal.guard) { e.stopPropagation(); e.preventDefault(); } }, true);
for (const id of ['end', 'vsEnd']) $(id).addEventListener('click', (e) => { if (e.detail === 0 && performance.now() < modal.guard) { e.stopPropagation(); e.preventDefault(); } }, true);
function setScreen(name) {
app.screen = name;
$('app').dataset.screen = name;
@ -148,11 +156,13 @@
ctrl.on('reject', onReject);
ctrl.on('mark', (m) => { renderer.addMark(m.x, m.y, m.slot); Audio.sfx('ping'); });
ctrl.on('players', onPlayers);
ctrl.on('vs', () => { if (ctrl === app.ctrl && ctrl.kind === 'remote') renderPlayers(); }); // the roles are part of the players panel
ctrl.on('newgame', () => {
resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true;
app.bossMusic = false; if (app.inGame) Audio.music('battle'); // a new game starts its music on every client, not only on the one that pressed Play again (code-5)
if (ctrl.kind === 'remote') renderPlayers(); // (the room header names the difficulty, which a new game may have changed)
});
V.attach(ctrl); // a versus controller switches the HUD to versus, any other one switches it back
adoptBoard(true);
}
function adoptBoard(force) {
@ -184,6 +194,21 @@
requestWakeLock();
firstRunHelp();
}
// A versus match against the computer: no server, no lobby (the controller starts in its countdown). opts: { role, limit, skill, countdownMs?, seed? }
function startVersusLocal(opts) {
cancelPending();
leaveRemote(true);
store.set('nw.map', app.mapId);
const c = new NW.LocalController({ map: app.mapId, mode: 'versus', role: opts.role, limit: opts.limit, skill: opts.skill, countdownMs: opts.countdownMs, seed: opts.seed });
useController(c);
app.inGame = true; app.started = true; app.endShown = false; app.last = {};
resetSelection(); setScreen('playing'); showOverlay(null);
$('players').hidden = true; $('netChip').hidden = true; $('reconnect').hidden = true;
renderInfo(true);
app.bossMusic = false; Audio.music('battle');
requestWakeLock();
return c;
}
// The first-run help opens once per install (storage) and at most once per page load, so a browser whose storage throws does not get it on every start (code-26).
function firstRunHelp() {
if (app.helpSeen) return;
@ -221,10 +246,10 @@
case 'arc': Audio.sfx('arc'); break;
case 'boom': Audio.sfx('boom'); break;
case 'kill': Audio.sfx('kill'); break;
case 'leak': Audio.sfx('leak'); break;
case 'leak': Audio.sfx(V.leakSfx()); break;
case 'wave': banner(e.boss ? 'BOSS WAVE ' + e.n : 'WAVE ' + e.n, e.boss); Audio.sfx(e.boss ? 'boss' : 'wave'); break;
case 'clear': toast('Wave ' + e.n + ' cleared +' + e.bonus + ' credits', 'good'); Audio.sfx('clear'); break;
default: break;
default: if (V.active) V.onEvent(e); break; // versus: emp, decoy, surge, ddos, quarantine, scan, repair
}
}
}
@ -243,7 +268,7 @@
function priceOf(type) { return TD.priceFor(type, app.ctrl && app.ctrl.view ? app.ctrl.view.towers : 0); }
function buildPalette() {
const pal = $('palette');
pal.textContent = '';
pal.textContent = ''; pal.classList.remove('shop');
pal.classList.toggle('many', TD.TOWER_ORDER.length > 6);
for (const type of TD.TOWER_ORDER) {
const def = TD.TOWERS[type];
@ -279,9 +304,11 @@
}
$('palette').addEventListener('scroll', updatePaletteHint, { passive: true });
function drawPaletteIcons() {
if (V.shopOn) { V.drawShopIcons(); return; } // the attacker's palette is the unit shop
for (const b of $('palette').children) NW.drawIcon(b.querySelector('canvas'), b.dataset.type, 1);
}
function syncPalette() {
if (V.shopOn) return; // (the attacker's unit shop has nothing to select)
for (const b of $('palette').children) {
const sel = b.dataset.type === app.selType;
b.classList.toggle('sel', sel);
@ -290,6 +317,7 @@
}
}
function selectType(type) {
if (type && V.active) V.disarm();
app.selType = type; app.selTower = 0; app.pending = null; app.previewDirty = true;
syncPalette(); renderInfo(true); updateConfirm();
if (!type) { ui.preview = null; hint(null); }
@ -329,7 +357,7 @@
if (!tower) app.selTower = 0;
}
if (tower) {
if (ctrl.kind === 'remote' && ctrl.players.length > 1) ownerP = ctrl.players.find((p) => p.slot === tower.owner) || null;
if (ctrl.kind === 'remote' && ctrl.players.length > 1 && !V.active) ownerP = ctrl.players.find((p) => p.slot === tower.owner) || null;
shape = 't' + tower.id + tower.type + ':' + (ownerP ? ownerP.slot + ownerP.name : '');
} else if (app.selType) shape = 'b' + app.selType + ':' + priceOf(app.selType); // the price can change while armed (Orbital Uplink)
if (!force && shape === info.shape) { if (tower) syncInfo(); return; }
@ -337,12 +365,13 @@
info.shape = shape; info.sig = ''; info.lv = 0; info.dirty = false;
if (!shape) { box.textContent = ''; return; }
if (tower) {
const def = TD.TOWERS[tower.type], wall = tower.type === 'wall', aim = aimsAtTargets(def);
const def = TD.TOWERS[tower.type], wall = tower.type === 'wall', att = V.active && V.role === 'attacker', aim = aimsAtTargets(def) && !att;
const empBtn = att && !wall ? '<button type="button" data-act="emp" title="Disable this tower for a few seconds"><svg class="ic"><use href="#i-ab-emp"/></svg><span class="w">EMP</span><span class="cost"></span></button>' : '';
box.innerHTML =
'<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div>' +
'<div class="desc"></div><div class="kv"></div><div class="actions">' +
(wall ? '' : '<button type="button" data-act="up"><svg class="ic"><use href="#i-up"/></svg><span class="w"></span><span class="cost" id="upCost"></span></button>') +
'<button type="button" data-act="sell" class="danger"><svg class="ic"><use href="#i-trash"/></svg><span class="w">Sell</span><span class="cost"></span></button>' +
(wall || att ? '' : '<button type="button" data-act="up"><svg class="ic"><use href="#i-up"/></svg><span class="w"></span><span class="cost" id="upCost"></span></button>') +
(att ? empBtn : '<button type="button" data-act="sell" class="danger"><svg class="ic"><use href="#i-trash"/></svg><span class="w">Sell</span><span class="cost"></span></button>') +
(aim ? '<button type="button" data-act="mode" title="Which packet to shoot"><svg class="ic"><use href="#i-target"/></svg><span class="w">Target:</span><span class="mv"></span></button>' : '') +
'<button type="button" data-act="close" class="icon" aria-label="Close" title="Close"><svg class="ic"><use href="#i-x"/></svg></button></div>' +
'<div class="byline">' + (aim ? '<span id="infoKills"></span>' : '') + (ownerP ? '<span class="dot" style="background:' + slotColor(ownerP.slot) + '"></span><span id="infoOwner"></span>' : '') + '</div></div>';
@ -396,8 +425,7 @@
up.setAttribute('aria-label', canUp ? 'Upgrade for ' + upCost + ' credits' : 'Max level');
}
const sell = box.querySelector('[data-act="sell"]');
setText(sell.querySelector('.cost'), String(sellVal));
sell.setAttribute('aria-label', 'Sell for ' + sellVal + ' credits');
if (sell) { setText(sell.querySelector('.cost'), String(sellVal)); sell.setAttribute('aria-label', 'Sell for ' + sellVal + ' credits'); } // (the attacker's panel has no Sell)
const mode = box.querySelector('[data-act="mode"]');
if (mode) { setText(mode.querySelector('.mv'), MODE_NAMES[t.mode]); mode.setAttribute('aria-label', 'Target: ' + MODE_NAMES[t.mode] + '. Tap to change'); }
setText(box.querySelector('#infoKills'), t.kills + (t.kills === 1 ? ' kill' : ' kills'));
@ -421,6 +449,7 @@
case 'up': ctrl.send({ c: 'upgrade', id: tower.id }); break;
case 'sell': ctrl.send({ c: 'sell', id: tower.id }); app.selTower = 0; renderInfo(true); app.previewDirty = true; break;
case 'close': selectTower(0); break;
case 'emp': V.castEmp(tower.id); break;
case 'mode': {
const modes = TD.TARGET_MODES; ctrl.send({ c: 'target', id: tower.id, mode: modes[(modes.indexOf(tower.mode) + 1) % modes.length] });
break;
@ -430,6 +459,7 @@
});
function renderWavePanel(view) {
if (V.active) { if (app.last.waveKey !== 'vs') { app.last.waveKey = 'vs'; $('nextwave').textContent = ''; } return; } // versus has no waves
const n = view.wave + 1;
const dif = viewDifficulty(view);
const key = n + ':' + view.state + ':' + dif;
@ -455,7 +485,7 @@
function onPlayers(list) {
const ctrl = app.ctrl;
ui.names = {}; for (const p of list) ui.names[p.slot] = p.name;
ui.coop = list.length > 1;
ui.coop = list.length > 1 && !V.active; // (owner flags on the towers are for co-op: in versus one side builds everything)
// join / leave toasts
if (app.prevPlayers) {
for (const p of list) if (!app.prevPlayers.find((q) => q.pid === p.pid)) { toast(p.name + ' joined', 'good'); Audio.sfx('join'); }
@ -472,12 +502,13 @@
if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; }
box.hidden = false;
const dif = viewDifficulty(ctrl.view);
let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + '<span class="dtag" data-d="' + dif + '" title="Difficulty">' + esc(diffName(dif)) + '</span> <span id="plPing" class="muted"></span></h4>'; // (every server string is escaped before it goes into HTML, code-28)
let html = '<div class="panel"><h4>Room ' + esc(ctrl.room || '') + (V.active ? '<span class="dtag" title="Attack versus defend">VERSUS</span>' : '<span class="dtag" data-d="' + dif + '" title="Difficulty">' + esc(diffName(dif)) + '</span>') + ' <span id="plPing" class="muted"></span></h4>'; // (every server string is escaped before it goes into HTML, code-28)
for (const p of ctrl.players) {
html += '<div class="pl"><span class="dot" style="background:' + slotColor(p.slot) + '"></span><span class="pn"></span>' +
(ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') + '</div>';
(ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') +
(V.active && ctrl.vs && ctrl.vs.roles && ctrl.vs.roles[p.slot] ? (ctrl.vs.roles[p.slot] === 'attacker' ? '<span class="rolebadge attacker">ATTACK</span>' : '<span class="rolebadge defender">DEFEND</span>') : '') + '</div>';
}
if (ctrl.players.length < 2) html += '<div class="muted small">Waiting for a partner&hellip; share the invite link.</div>';
if (ctrl.players.length < 2 && !(V.active && ctrl.vs && ctrl.vs.bot)) html += '<div class="muted small">Waiting for ' + (V.active ? 'an opponent' : 'a partner') + '&hellip; share the invite link.</div>';
html += '<div class="actions"><button type="button" data-act="invite"><svg class="ic"><use href="#i-share"/></svg>Invite</button><button type="button" data-act="leave" class="danger">Leave</button></div></div>';
box.innerHTML = html;
const names = box.querySelectorAll('.pn');
@ -500,7 +531,7 @@
// ------------------------------------------------------------------ HUD
function updateHud(view) {
const L = app.last, ctrl = app.ctrl;
if (L.gold !== view.gold) { L.gold = view.gold; $('vGold').textContent = String(view.gold); }
if (!(V.active && V.role === 'attacker') && L.gold !== view.gold) { L.gold = view.gold; $('vGold').textContent = String(view.gold); } // (the attacker's top bar shows its own purse: versus.js)
if (L.lives !== view.lives) {
L.lives = view.lives; $('vLives').textContent = String(view.lives);
$('statLives').classList.toggle('low', view.maxLives > 0 && view.lives <= view.maxLives * 0.25);
@ -526,7 +557,7 @@
// palette affordability
const gold = view.gold;
const palKey = gold + ':' + view.towers.length; // prices can change when the tower count does (Orbital Uplink)
if (L.palGold !== palKey) {
if (!V.shopOn && L.palGold !== palKey) {
L.palGold = palKey;
for (const b of $('palette').children) {
const def = TD.TOWERS[b.dataset.type], price = priceOf(b.dataset.type), poor = gold < price;
@ -537,7 +568,7 @@
}
if (ctrl.kind === 'remote') {
const chip = $('netChip');
chip.hidden = false;
chip.hidden = V.active; // (a running versus match has nobody to invite: the room code is in the players panel)
$('netRoom').textContent = ctrl.room || '';
const alone = ctrl.players.length < 2;
if (L.alone !== alone || L.room !== ctrl.room) {
@ -744,6 +775,7 @@
return app.ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y) || null;
}
function tapSelect(cell) {
if (V.active && V.tapCell(cell)) return; // versus: a tapped gateway (attacker), an armed Scan / EMP
const ctrl = app.ctrl;
if (!ctrl.board.inBounds(cell.x, cell.y)) { selectTower(0); return; }
const t = ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y);
@ -917,11 +949,12 @@
if (e.repeat) return; // holding a key is one press: Space must not start 20 waves (code-6)
if (e.key && e.key.toLowerCase() === 'm' && !e.altKey) { Audio.toggleMuted(); return; } // M mutes anywhere: in the menu, behind a dialog, on the end screen (code-13)
if (!app.inGame) return;
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape' && $('end').hidden) closeOverlayToGame(); return; } // (the game-over dialog is left with its buttons, never dismissed: Escape there would leave a dead board, code-9)
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape' && $('end').hidden && !V.holdsOverlay()) closeOverlayToGame(); return; } // (the game-over dialog is left with its buttons, never dismissed: Escape there would leave a dead board, code-9)
const ctrl = app.ctrl, view = ctrl.view;
const k = e.key.toLowerCase();
// Space / Enter on a focused button or link press THAT control (keyboard users), not the next-wave hotkey (code-8)
if ((k === ' ' || k === 'enter') && e.target && e.target.closest && e.target.closest('button, a, select, [role="button"]')) return;
if (V.active && V.key(k, e)) return; // versus: attacker digits buy units, Space launches; waves, pause and speed do nothing
const keyType = k.length === 1 ? TD.TOWER_ORDER.find((t) => TD.TOWERS[t].key === k) : null; // 1-9, 0: one key per tower in the palette
if (keyType) { selectType(app.selType === keyType ? null : keyType); Audio.sfx('click'); e.preventDefault(); return; }
switch (k) {
@ -1058,9 +1091,10 @@
}
function closeOverlayToGame() {
if (!app.inGame) return;
if (!$('lobby').hidden) cancelPending(); // leaving the lobby abandons a join that is still connecting (code-3)
if (!$('lobby').hidden || !$('vsSetup').hidden) cancelPending(); // leaving the lobby abandons a join that is still connecting (code-3)
showOverlay(null);
if (app.menuPaused) { app.menuPaused = false; if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false); }
if (V.active) V.refreshOverlay(); // a versus lobby / result dialog that was waiting behind the menu comes back
}
function leaveToMenu(keep) {
cancelPending();
@ -1073,6 +1107,7 @@
}
$('btnSolo').addEventListener('click', () => { Audio.unlock(); startSolo(app.mapId); });
$('btnVersus').addEventListener('click', () => { Audio.unlock(); V.openSetup(); });
$('btnCloseMenu').addEventListener('click', closeOverlayToGame);
$('btnHelp').addEventListener('click', () => showOverlay('help'));
$('btnHelpClose').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else showOverlay('menu'); });
@ -1089,7 +1124,8 @@
else { app.ctrl.newGame(app.ctrl.board.mapId, app.ctrl.difficulty); }
});
$('btnContinue').addEventListener('click', () => { app.ctrl.send({ c: 'continue' }); $('end').hidden = true; app.endShown = false; Audio.music('battle'); });
$('btnEndMenu').addEventListener('click', () => { if (app.ctrl.kind === 'remote') leaveToMenu(); else { app.inGame = false; previewMap(app.mapId); setScreen('menu'); openMenu(); } });
function exitToMenu() { if (app.ctrl.kind === 'remote') leaveToMenu(); else { app.inGame = false; previewMap(app.mapId); setScreen('menu'); openMenu(); } }
$('btnEndMenu').addEventListener('click', exitToMenu);
// lobby
function lobbyMsg(text, bad) { const m = $('lobbyMsg'); m.textContent = text || ''; m.className = 'msg' + (bad ? ' bad' : ''); }
@ -1114,24 +1150,25 @@
// leaves the game that is running untouched (coop-4), Back / Play solo can cancel it (code-3), and only one attempt runs at a time (code-4).
let pendingRc = null;
const KEEP_SESSION = { connect: 1, lost: 1, replaced: 1 }; // after these the saved room is still worth another try; any other failure means it is gone
function setLobbyBusy(b) { for (const id of ['btnCreate', 'btnJoin', 'btnResume']) $(id).disabled = b; }
function setLobbyBusy(b) { for (const id of ['btnCreate', 'btnJoin', 'btnResume', 'btnVsCreate', 'btnVsJoin']) $(id).disabled = b; }
function cancelPending() {
const rc = pendingRc; pendingRc = null;
if (rc) rc.close();
setLobbyBusy(false);
}
// opts: { room, map, resume }. `resume` is a rejoin of a game left earlier (reload, "Resume"): it says "gone" instead of "does not exist".
// opts: { room, map, resume, difficulty, mode:'versus'?, limit?, name?, say?(text, bad) }. `resume` is a rejoin of a game left earlier (reload, "Resume"): it says "gone" instead of "does not exist".
function connectRemote(opts) {
if (root.location.protocol === 'file:') { lobbyMsg('Open the game through the Netwall server to play online.', true); return; }
const say = opts.say || lobbyMsg; // where the connecting / failure text goes (the co-op lobby, or the versus dialog)
if (root.location.protocol === 'file:') { say('Open the game through the Netwall server to play online.', true); return; }
if (pendingRc) return; // a double click must not open two rooms and an orphan socket
const live = app.inGame && app.ctrl && app.ctrl.kind === 'remote' ? app.ctrl : null;
if (live && opts.room && live.room === opts.room) { closeOverlayToGame(); return; } // that is the room we are in
const name = ($('inName').value || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player';
const name = ((opts.name !== undefined ? opts.name : $('inName').value) || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player';
store.set('nw.name', name);
lobbyMsg('Connecting…');
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, difficulty: opts.difficulty, resume: !!opts.resume });
say('Connecting…');
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map, difficulty: opts.difficulty, mode: opts.mode, limit: opts.limit, resume: !!opts.resume });
pendingRc = rc; setLobbyBusy(true);
const saveSession = () => { sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() }); };
const saveSession = () => { sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now(), mode: rc.mode }); };
let first = true;
rc.on('joined', () => {
if (first && pendingRc !== rc) { rc.close(); return; } // cancelled while connecting: never take anything over
@ -1145,11 +1182,15 @@
resetSelection(); setScreen('playing'); showOverlay(null);
onPlayers(rc.players);
try { root.history.replaceState(null, '', root.location.pathname + '?room=' + encodeURIComponent(rc.room)); } catch (e) { /* ignore */ }
toast('Room ' + rc.room + ' \u00b7 ' + diffName(viewDifficulty(rc.view)) + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good'); // (a joiner learns the host's difficulty here)
Audio.music('battle'); requestWakeLock();
firstRunHelp(); // an invited player is new to the game too (code-26)
if (rc.mode === 'versus') { // a versus room opens on its lobby dialog (or straight into the round that is running)
V.refreshOverlay(); Audio.music(V.phase === 'lobby' ? 'theme' : 'battle'); requestWakeLock();
} else {
toast('Room ' + rc.room + ' \u00b7 ' + diffName(viewDifficulty(rc.view)) + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good'); // (a joiner learns the host's difficulty here)
Audio.music('battle'); requestWakeLock();
firstRunHelp(); // an invited player is new to the game too (code-26)
}
} else { toast('Reconnected', 'good'); adoptBoard(); }
lobbyMsg('');
say('');
});
rc.on('status', (s) => {
if (app.ctrl !== rc || !app.inGame) return;
@ -1161,12 +1202,14 @@
const keep = !!KEEP_SESSION[f.code];
if (app.ctrl === rc && app.inGame) { // the game we were playing is gone
if (!keep) { sess.del('nw.room'); store.del('nw.session'); }
toast(f.msg, 'bad'); leaveToMenu(keep); openLobby(); lobbyMsg(f.msg, true);
const vsGame = rc.mode === 'versus';
toast(f.msg, 'bad'); leaveToMenu(keep);
if (vsGame) { V.openSetup(); V.msg(f.msg, true); } else { openLobby(); lobbyMsg(f.msg, true); }
return;
}
if (opts.resume && !keep) { sess.del('nw.room'); store.del('nw.session'); } // the saved game cannot be rejoined: forget it
lobbyMsg(f.msg, true);
if ($('lobby').hidden) toast(f.msg, 'bad'); // a Resume / reload rejoin has no lobby on screen: tell the player where they look (code-24)
say(f.msg, true);
if ((opts.say ? $('vsSetup') : $('lobby')).hidden) toast(f.msg, 'bad'); // a Resume / reload rejoin has no lobby on screen: tell the player where they look (code-24)
updateResumeButton();
});
rc.connect();
@ -1176,7 +1219,7 @@
const s = store.get('nw.session', null), b = $('btnResume');
const fresh = s && s.room && Date.now() - s.ts < 15 * 60 * 1000 && !(app.ctrl && app.ctrl.kind === 'remote');
b.hidden = !fresh || root.location.protocol === 'file:';
if (fresh) b.textContent = 'Resume co-op game · room ' + s.room;
if (fresh) b.textContent = 'Resume ' + (s.mode === 'versus' ? 'versus' : 'co-op') + ' game · room ' + s.room;
}
$('btnResume').addEventListener('click', () => {
const s = store.get('nw.session', null); if (!s) return;
@ -1221,7 +1264,7 @@
const W = a.clientWidth - (parseFloat(cs.paddingLeft) || 0) - (parseFloat(cs.paddingRight) || 0);
const H = a.clientHeight - (parseFloat(cs.paddingTop) || 0) - (parseFloat(cs.paddingBottom) || 0) - $('topbar').offsetHeight;
const mg = (NW.BOARD_MARGIN || 0) * 2, dw = b.cols * NW.CELL + mg, dh = b.rows * NW.CELL + mg, pad = 8;
const minSide = clamp(Math.round(H * 0.25), 140, 210); // room for the palette row and a window onto the info panel
const minSide = V.minSide(H) || clamp(Math.round(H * 0.25), 140, 210); // room for the palette row and a window onto the info panel (versus: the dock too)
const maxStage = Math.max(120, H - minSide);
const sU = Math.min((W - pad) / dw, (maxStage - pad) / dh), sR = Math.min((W - pad) / dh, (maxStage - pad) / dw);
const rot = sR > sU * 1.08;
@ -1272,6 +1315,7 @@
}
if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower || app.selType) renderInfo(false); }
updateHud(view);
V.tick(now, view); // versus: clock, credits, cooldown rings, shop affordability
layoutBars(false);
updateFit(); // the Reset-zoom button always follows the camera, however it was reset (code-18, coop-8)
if (now - app.lastBossCheck > 600 && view.state === 'playing') {
@ -1280,7 +1324,7 @@
if (boss !== app.bossMusic) { app.bossMusic = boss; if (!app.endShown) Audio.music(boss ? 'boss' : 'battle'); }
}
}
ui.hover = app.pending || app.hover; ui.selType = app.selType; ui.selTower = app.selTower;
ui.hover = app.pending || app.hover; ui.selType = app.selType; ui.selTower = app.selTower; ui.vs = V.uiState();
// hovering an existing tower while a build type is active: a click selects it, so show no ghost
ui.noGhost = !!(ui.hover && app.selType && view.towers.some((t) => t.x === ui.hover.x && t.y === ui.hover.y));
refreshPreview(false);
@ -1317,5 +1361,7 @@
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
app.startVersus = startVersusLocal; // (tests: a local versus game with its own limit and countdown)
app.vs = V;
NW.app = app; // handy for debugging and automated tests
})(typeof self !== 'undefined' ? self : this);

View file

@ -329,6 +329,8 @@
this.rot = 0; // 0, or PI/2 when the board is drawn rotated for portrait screens
this.fx = (root.matchMedia && root.matchMedia('(pointer: coarse)').matches) ? 0.55 : 1; // fewer particles on phones
this.names = {};
// versus cues (all stay empty in solo / co-op): screen effects with seconds left, Scan zones, gateway pulses, the tower list for events that name a tower
this.fxT = { surge: 0, ddos: 0, freeze: 0 }; this.scans = []; this.gatePulse = new Map(); this._towers = [];
}
setBoard(board) {
@ -336,6 +338,7 @@
this.wallGrid = new Uint8Array(board.cols * board.rows);
this.parts.length = 0; this.rings.length = 0; this.lines.length = 0; this.texts.length = 0; this.marks.length = 0; this.pulses.length = 0;
this.aim.clear(); this.trk.clear(); this.glow.clear();
this.fxT.surge = this.fxT.ddos = this.fxT.freeze = 0; this.scans.length = 0; this.gatePulse.clear();
this.resetCamera();
}
resize(w, h, dpr) {
@ -453,6 +456,22 @@
break;
}
case 'heal': this._pulse(e.x * C, e.y * C, 10, (e.r || 2.2) * C, '#7ee08a', 0.7, 2.2, 0.07); break; // soft green wave out to the daemon's range
// ---- versus
case 'emp': { // the attacker disabled a tower: a yellow burst on it (the disabled look itself follows tower.empT)
const tw = this._towers.find((x) => x.id === e.id);
if (tw) { const cx = (tw.x + 0.5) * C, cy = (tw.y + 0.5) * C; this._ring(cx, cy, 6, 44, '#ffe27a', 0.55, 3); this._ring(cx, cy, 4, 26, '#ffffff', 0.3, 2); this._burst(cx, cy, '#ffe27a', 12, 120, 0.5); this.shake = Math.min(2, this.shake + 0.3); }
break;
}
case 'surge': this.fxT.surge = e.d || 6; break;
case 'ddos': this.fxT.ddos = e.d || 4; break;
case 'quarantine': this.fxT.freeze = e.d || 2; break;
case 'scan': {
const sc = TD.VS && TD.VS.TOOLS.scan, rd = (sc ? sc.radius : 4), rv = sc ? sc.reveal : 3;
this.scans.push({ x: e.x, y: e.y, t: rv, max: rv, r: rd });
this._pulse(e.x * C, e.y * C, 8, rd * C, '#7ee8ff', 0.6, 3, 0.1);
break;
}
case 'repair': { const b = this.board; if (b) { this._ring((b.core.x + 0.5) * C, (b.core.y + 0.5) * C, 10, 52, '#35e0a1', 0.6, 3); this._burst((b.core.x + 0.5) * C, (b.core.y + 0.5) * C, '#35e0a1', 8, 80, 0.5); } break; }
default: break;
}
}
@ -466,6 +485,7 @@
const t = now / 1000;
const dt = clamp((now - (this.lastNow || now)) / 1000, 0, 0.1); this.lastNow = now;
const sc = this.scale;
const vsui = ui && ui.vs ? ui.vs : null; // versus-only cues (null in solo / co-op)
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.fillStyle = BG; ctx.fillRect(0, 0, this.W, this.H);
@ -502,11 +522,11 @@
}
this._drawRoutes(ctx, b, ui, t);
this._drawEndpoints(ctx, b, view, t, dt, rot);
this._drawEndpoints(ctx, b, view, t, dt, rot, vsui);
// walls (with trace links) then turrets
const wg = this.wallGrid; wg.fill(0);
const towers = view.towers;
const towers = view.towers; this._towers = towers;
for (let i = 0; i < towers.length; i++) if (towers[i].type === 'wall') wg[towers[i].y * cols + towers[i].x] = 1;
ctx.lineCap = 'round';
ctx.strokeStyle = 'rgba(90,169,255,.55)'; ctx.lineWidth = 3.2;
@ -545,6 +565,8 @@
const cx = (tw.x + 0.5) * C, cy = (tw.y + 0.5) * C;
const gl = tw.type === 'sandbox' && this.glow.size ? this.glow.get(tw.y * cols + tw.x) : 0;
drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot, gl ? Math.min(1, gl / 0.25) : 0);
if (tw.empT > 0) this._drawEmp(ctx, tw, cx, cy, t); // versus: disabled by an EMP
else if (vsui && vsui.empArm && tw.type !== 'wall') { ctx.strokeStyle = 'rgba(255,226,122,' + (0.5 + 0.4 * Math.sin(t * 8)) + ')'; ctx.lineWidth = 2.5; rr(ctx, tw.x * C + 2, tw.y * C + 2, C - 4, C - 4, 6); ctx.stroke(); } // EMP armed: every tower it can hit
if (coop && tw.type !== 'wall') { // owner corner flag: at least ~5 CSS px, dark outline so it shows on a tile of the same colour
const k = Math.max(12, 5.5 / sc), x0 = cx - C * 0.46, y0 = cy - C * 0.46;
ctx.beginPath(); ctx.moveTo(x0, y0); ctx.lineTo(x0 + k, y0); ctx.lineTo(x0, y0 + k); ctx.closePath();
@ -569,8 +591,8 @@
}
// ground monsters, then flyers on top
this._drawMonsters(ctx, view, t, dt, false, rot);
this._drawMonsters(ctx, view, t, dt, true, rot);
this._drawMonsters(ctx, view, t, dt, false, rot, vsui);
this._drawMonsters(ctx, view, t, dt, true, rot, vsui);
// bullets
for (const bu of view.bullets) {
@ -584,6 +606,7 @@
}
this._drawFx(ctx, dt, sc, rot);
if (vsui || this.scans.length || this.fxT.surge > 0 || this.fxT.ddos > 0 || this.fxT.freeze > 0) this._drawVsFx(ctx, dt, sc, cols, rows, t, ui);
// placement ghost
if (ui.hover && ui.selType && !ui.noGhost && b.inBounds(ui.hover.x, ui.hover.y)) {
@ -692,15 +715,17 @@
ctx.setLineDash([]);
}
_drawEndpoints(ctx, b, view, t, dt, rot) {
_drawEndpoints(ctx, b, view, t, dt, rot, vsui) {
// spawns: red gateways
for (const sp of b.spawns) {
for (let gi = 0; gi < b.spawns.length; gi++) {
const sp = b.spawns[gi];
const p = (t * 0.7) % 1;
ctx.save(); ctx.translate((sp.x + 0.5) * C, (sp.y + 0.5) * C); if (rot) ctx.rotate(-rot);
ctx.strokeStyle = rgba('#ff5c7a', 0.5 * (1 - p)); ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(0, 0, 12 + p * 16, 0, TAU); ctx.stroke();
ctx.fillStyle = '#2a0c18'; ctx.beginPath(); ctx.arc(0, 0, 13, 0, TAU); ctx.fill();
ctx.strokeStyle = '#ff5c7a'; ctx.lineWidth = 2; ctx.stroke();
ctx.lineWidth = 1.3; ctx.beginPath(); ctx.ellipse(0, 0, 5.5, 13, 0, 0, TAU); ctx.moveTo(-13, 0); ctx.lineTo(13, 0); ctx.stroke();
if (vsui) this._vsGate(ctx, gi, vsui, t, dt, b.spawns.length);
ctx.restore();
}
// core: server rack with an integrity ring
@ -721,7 +746,7 @@
ctx.restore();
}
_drawMonsters(ctx, view, t, dt, air, rot) {
_drawMonsters(ctx, view, t, dt, air, rot, vsui) {
const trk = this.trk;
if (!air) { // a Daemon's heal range, faint, all in one stroke
let any = false;
@ -737,7 +762,10 @@
if (!!m.air !== air) continue;
const def = TD.ENEMIES[m.kind];
let k = trk.get(m.id);
if (!k) { k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0, still: 0, sv: null }; trk.set(m.id, k); }
if (!k) {
k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0, still: 0, sv: null }; trk.set(m.id, k);
if (vsui) this._vsBorn(k, m, vsui, t);
}
const dm = def.shield && m.maxShield === undefined ? this._shieldView(k, m, def, dt) : m; // co-op: tell hp and shield apart (see there)
const v = vitals(dm, def), cur = v.hp + v.sh;
const dx = m.x - k.x, dy = m.y - k.y;
@ -749,6 +777,7 @@
// stunned: solo knows (stunT); in co-op the wire only says "slowed or stunned", and a slowed packet still moves, so a flagged packet that stands still is stunned
const stun = m.stunT !== undefined ? m.stunT > 0 : m.slow > 0 && k.still > 0.2 && !view.paused;
if (air && !SWARM[m.kind]) { const er = def.r * C; ctx.fillStyle = 'rgba(0,0,0,.28)'; ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); ctx.beginPath(); ctx.ellipse(0, 5, er, er * 0.45, 0, 0, TAU); ctx.fill(); ctx.restore(); }
if (vsui) { this._vsUnit(ctx, dm, k, def, vsui, t, rot, stun); continue; }
drawMonster(ctx, dm, k.ang, t, k.flash, rot, stun);
}
if (air && trk.size > view.monsters.length + 60) { // drop stale trackers
@ -778,6 +807,114 @@
return s;
}
// ---------------------------------------------------------------- versus cues
// a tower an EMP has switched off: dimmed, hazard stripes, flickering sparks and an arc that runs out with the time left
_drawEmp(ctx, tw, cx, cy, t) {
const total = (TD.VS && TD.VS.ABILITIES.emp.dur) || 6, h = C * 0.43;
ctx.save(); ctx.translate(cx, cy);
ctx.fillStyle = 'rgba(4,7,14,.66)'; rr(ctx, -h, -h, h * 2, h * 2, C * 0.12); ctx.fill();
ctx.save(); ctx.clip();
ctx.strokeStyle = 'rgba(255,210,77,.5)'; ctx.lineWidth = 3;
for (let i = -3; i <= 3; i++) { ctx.beginPath(); ctx.moveTo(i * 9 - 18, 18); ctx.lineTo(i * 9 + 18, -18); ctx.stroke(); }
ctx.restore();
ctx.strokeStyle = '#ffe27a'; ctx.lineWidth = 3; ctx.lineCap = 'round';
ctx.beginPath(); ctx.arc(0, 0, C * 0.5, -Math.PI / 2, -Math.PI / 2 + TAU * clamp(tw.empT / total, 0, 1)); ctx.stroke();
if (Math.sin(t * 26 + tw.id * 3) > 0.2) { // a spark
ctx.strokeStyle = '#fff6c9'; ctx.lineWidth = 2; ctx.beginPath();
const a = (Math.floor(t * 9 + tw.id) % 4) * 1.57;
ctx.moveTo(Math.cos(a) * 6, Math.sin(a) * 6); ctx.lineTo(Math.cos(a + 0.4) * 12, Math.sin(a + 0.4) * 12); ctx.lineTo(Math.cos(a - 0.1) * 15, Math.sin(a - 0.1) * 15); ctx.stroke();
}
ctx.restore();
}
// the gateway the attacker picked (amber ring), numbers on the gateways when there is a choice, and a pulse where a unit has just entered
_vsGate(ctx, gi, vsui, t, dt, n) {
const pl = this.gatePulse.get(gi);
if (pl > 0) {
const k = 1 - pl / 0.7;
ctx.strokeStyle = rgba('#ffffff', 0.85 * (1 - k)); ctx.lineWidth = 3; ctx.beginPath(); ctx.arc(0, 0, 13 + k * 26, 0, TAU); ctx.stroke();
this.gatePulse.set(gi, pl - dt); if (pl - dt <= 0) this.gatePulse.delete(gi);
}
if (vsui.gates > 1 && vsui.role === 'attacker') {
const on = vsui.gate === gi;
if (on) { ctx.strokeStyle = '#ffd24d'; ctx.lineWidth = 3.5; ctx.beginPath(); ctx.arc(0, 0, 18 + Math.sin(t * 6) * 1.5, 0, TAU); ctx.stroke(); }
ctx.fillStyle = on ? '#ffd24d' : 'rgba(8,13,26,.9)'; ctx.beginPath(); ctx.arc(11, -11, 7.5, 0, TAU); ctx.fill();
ctx.lineWidth = 1.5; ctx.strokeStyle = on ? '#ffd24d' : '#ff5c7a'; ctx.stroke();
ctx.fillStyle = on ? '#241a02' : '#ffd1da'; ctx.font = '700 10px system-ui, sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(String(gi + 1), 11, -10.5); ctx.textAlign = 'start';
}
}
// what the attacker knows about its own units, remembered when a unit first shows up (the wire carries neither stealth nor tech): stealth seconds and shield capacity
_vsBorn(k, m, vsui, t) {
k.born = t; k.stl = 0; k.shl = 0;
// a spawn pulse at the gateway it enters from (every client sees it: the defender too)
const b = this.board;
if (b) for (let i = 0; i < b.spawns.length; i++) { const sp = b.spawns[i], dx = m.x - (sp.x + 0.5), dy = m.y - (sp.y + 0.5); if (dx * dx + dy * dy < 1.6) { this.gatePulse.set(i, 0.7); break; } }
if (vsui.role === 'attacker' && vsui.tech && TD.VS) {
const X = TD.VS.TECH;
if (vsui.tech.stealth) k.stl = X.stealth.secs[vsui.tech.stealth - 1] || 0;
if (vsui.tech.shield) k.shl = X.shield.per * vsui.tech.shield;
}
}
_vsUnit(ctx, m, k, def, vsui, t, rot, stun) {
const r = def.r * C, now = t * 1000;
const dec = !!m.decoy || (vsui.decoys && vsui.decoys.size > 0 && (vsui.decoys.get(m.id) || 0) > now);
const hid = vsui.role === 'attacker' && (m.stealthT !== undefined ? m.stealthT > 0 : k.stl > 0 && t - k.born < k.stl);
const lift = m.kind === 'ghost' ? -7 : 0;
ctx.save();
if (dec) ctx.globalAlpha = 0.5; else if (hid) ctx.globalAlpha = 0.38;
drawMonster(ctx, m, k.ang, t, k.flash, rot, stun);
ctx.restore();
if (dec || hid || k.shl > 0 || (m.maxShield > 0 && vsui.role === 'attacker' && !def.shield)) {
ctx.save(); ctx.translate(m.x * C, m.y * C + lift); if (rot) ctx.rotate(-rot);
if (dec) { // bait: a spinning dashed ring
ctx.strokeStyle = 'rgba(126,232,255,.95)'; ctx.lineWidth = 2; ctx.setLineDash([5, 4]); ctx.lineDashOffset = -t * 20;
ctx.beginPath(); ctx.arc(0, 0, r + 7, 0, TAU); ctx.stroke(); ctx.setLineDash([]);
}
if (hid) { // cloaked: a faint shimmer ring
ctx.strokeStyle = 'rgba(190,200,255,' + (0.35 + 0.25 * Math.sin(t * 12 + m.id)) + ')'; ctx.lineWidth = 1.5; ctx.setLineDash([3, 4]); ctx.lineDashOffset = t * 10;
ctx.beginPath(); ctx.arc(0, 0, r + 4, 0, TAU); ctx.stroke(); ctx.setLineDash([]);
}
const ms = m.maxShield !== undefined && !def.shield ? m.maxShield : k.shl; // tech shield (kinds that carry their own shield draw it themselves)
if (ms > 0 && vsui.role === 'attacker' && !def.shield) {
const sh = m.shield !== undefined ? m.shield : clamp(m.hp - (m.maxhp - ms), 0, ms);
if (sh > 0.5) { ctx.strokeStyle = 'rgba(150,200,255,' + (0.3 + 0.55 * clamp(sh / ms, 0, 1)) + ')'; ctx.lineWidth = 1.2 + 1.8 * clamp(sh / ms, 0, 1); ctx.beginPath(); ctx.arc(0, 0, r + 3, 0, TAU); ctx.stroke(); }
}
ctx.restore();
}
}
// screen cues in board space: Quarantine (icy), DDoS (violet scan lines), Surge (hot edge), Scan zones, and the ring of an armed Scan
_drawVsFx(ctx, dt, sc, cols, rows, t, ui) {
const f = this.fxT, W = cols * C, H = rows * C;
if (f.freeze > 0) {
f.freeze -= dt;
ctx.fillStyle = 'rgba(160,220,255,' + (0.1 + 0.05 * Math.sin(t * 9)) + ')'; ctx.fillRect(0, 0, W, H);
ctx.strokeStyle = 'rgba(225,246,255,.85)'; ctx.lineWidth = 6 / sc; ctx.strokeRect(0, 0, W, H);
}
if (f.ddos > 0) {
f.ddos -= dt;
ctx.fillStyle = 'rgba(150,80,255,.07)'; ctx.fillRect(0, 0, W, H);
ctx.strokeStyle = 'rgba(190,130,255,.35)'; ctx.lineWidth = 1.5 / sc; ctx.beginPath();
for (let y = (t * 60) % 24; y < H; y += 24) { ctx.moveTo(0, y); ctx.lineTo(W, y); }
ctx.stroke();
}
if (f.surge > 0) {
f.surge -= dt;
ctx.strokeStyle = 'rgba(255,150,60,' + (0.45 + 0.3 * Math.sin(t * 14)) + ')'; ctx.lineWidth = 8 / sc; ctx.strokeRect(0, 0, W, H);
}
for (let i = this.scans.length - 1; i >= 0; i--) {
const z = this.scans[i]; z.t -= dt;
if (z.t <= 0) { this.scans.splice(i, 1); continue; }
const a = clamp(z.t / z.max, 0, 1), cx = z.x * C, cy = z.y * C;
ctx.fillStyle = 'rgba(126,232,255,' + 0.07 * a + ')'; ctx.beginPath(); ctx.arc(cx, cy, z.r * C, 0, TAU); ctx.fill();
ctx.strokeStyle = 'rgba(126,232,255,' + (0.35 + 0.4 * a) + ')'; ctx.lineWidth = 2; ctx.setLineDash([8, 6]); ctx.lineDashOffset = -t * 18;
ctx.beginPath(); ctx.arc(cx, cy, z.r * C, 0, TAU); ctx.stroke(); ctx.setLineDash([]);
}
const v = ui && ui.vs;
if (v && v.scanArm && ui.hover && this.board && this.board.inBounds(ui.hover.x, ui.hover.y)) {
const rd = (TD.VS && TD.VS.TOOLS.scan.radius) || 4;
this._rangeRing(ctx, (ui.hover.x + 0.5) * C, (ui.hover.y + 0.5) * C, rd * C, '#7ee8ff');
}
}
_drawFx(ctx, dt, sc, rot) {
// lines (tracers, arcs)
ctx.lineCap = 'round'; ctx.lineJoin = 'round';

View file

@ -26,6 +26,69 @@
const CLEAR_BONUS_PER_WAVE = 1;
function clearBonus(n) { return CLEAR_BONUS + CLEAR_BONUS_PER_WAVE * n; }
// ---------------------------------------------------------------- versus mode: every number in ONE table
// new Sim({ mode: 'versus' }) is attack-vs-defend (docs/VERSUS.md). One player defends (builds, as in co-op, with the credits in `sim.gold`),
// the other attacks (buys units with `vs.credits`). The table is exported as TD.VS and read at the moment a rule runs, never cached,
// so the balance pass edits numbers HERE and nothing else (tests and the bots derive their expectations from it).
// defender DEF_GOLD start credits (an explicit `gold` option wins), DEF_TRICKLE credits/s on top of kill rewards, a kill pays
// round(buyCost * KILL_REWARD) [no wave scaling: versus units are base stats x the attacker's tech]
// attacker ATT_CREDITS start credits; income ATT_INCOME/s + ATT_INCOME_GROWTH/s per second elapsed; every living unit pays
// buyCost * LIFE_RATE per second alive up to LIFE_CAP of its price in total; a leak pays the price back
// caps MAX_ALIVE units on the map (a release still queued counts), MAX_STAGED waiting in the convoy
// release a convoy / a multi-unit buy is let out as a stream: RELEASE_GAP s apart, but the whole stream takes at most LAUNCH_SPAN s
// tech level L (1..max) costs TECH_COST * 2^(L-1): armor +per armour, speed +per x base, health +per x base hp,
// regen +per x max hp per second, shield +per hit points, stealth: towers cannot acquire the unit for secs[L-1] s after it
// enters the map, crypt: slows (Rate Limiter, Uplink) work res[L-1] weaker. Tech applies to units that enter the map afterwards.
// abilities attacker, cost credits, cooldown cd s, effect lasts dur s; tools: defender, cost gold, same shape
const VS = {
LIMITS: [480, 720, 960], DEFAULT_LIMIT: 720, ROUNDS: 2,
ATT_CREDITS: 150, ATT_INCOME: 4, ATT_INCOME_GROWTH: 0.02, LIFE_RATE: 0.004, LIFE_CAP: 0.5,
MAX_ALIVE: 250, MAX_STAGED: 200, RELEASE_GAP: 0.5, LAUNCH_SPAN: 3,
DEF_GOLD: 250, DEF_TRICKLE: 2, KILL_REWARD: 0.4,
TECH_COST: 100,
TECH_ORDER: ['armor', 'speed', 'health', 'regen', 'shield', 'stealth', 'crypt'],
TECH: {
armor: { max: 5, per: 1 },
speed: { max: 5, per: 0.08 },
health: { max: 5, per: 0.15 },
regen: { max: 3, per: 0.01 },
shield: { max: 3, per: 40 },
stealth: { max: 3, secs: [1, 1.5, 2] },
crypt: { max: 3, res: [0.2, 0.4, 0.6] },
},
ABILITY_ORDER: ['emp', 'decoy', 'surge', 'ddos'],
ABILITIES: {
emp: { cost: 80, cd: 20, dur: 6 }, // one tower (tid) does nothing for dur s
decoy: { cost: 60, cd: 25, dur: 5 }, // a harmless, unkillable unit that every tower that can reach it prefers, for dur s
surge: { cost: 120, cd: 40, dur: 6, speed: 0.4 }, // every unit +speed x base speed
ddos: { cost: 200, cd: 70, dur: 4, slow: 0.4 }, // every tower's cooldown runs `slow` slower
},
TOOL_ORDER: ['scan', 'patch', 'repair', 'quarantine'],
TOOLS: {
scan: { cost: 40, cd: 15, radius: 4, reveal: 3 }, // at (x, y): clears EMP on towers within radius, units within radius can be targeted for reveal s
patch: { cost: 30, cd: 8 }, // tower tid is re-enabled at once
repair: { cost: 120, cd: 30, amount: 3 }, // +amount integrity, never above the maximum
quarantine: { cost: 150, cd: 60, dur: 2 }, // every unit on the board is frozen for dur s
},
// one-tap convoys for the shop UI and the attacker bot: [[kind, n], ...]
PRESETS: {
rush: [['ping', 20]],
swarm: [['spam', 60]],
siege: [['trojan', 4], ['daemon', 1]],
air: [['ghost', 10]],
boss: [['rootkit', 1]],
},
};
const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
// Float credits and cooldowns drift by ~1e-12 over thousands of ticks: "can pay" and "on cooldown" tolerate EPS, and the numbers the sim
// REPORTS are rounded the careful way (credits down, cooldowns up), so a side never sees "9.00 credits" or "0 s left" and then gets a refusal.
const EPS = 1e-6;
const cooling = (x) => x > EPS;
const down2 = (x) => Math.floor((x + EPS) * 100) / 100;
const up2 = (x) => (x > EPS ? Math.ceil(x * 100) / 100 : 0);
const DEFENDER_CMDS = { place: 1, sell: 1, upgrade: 1, target: 1, tool: 1 };
const ATTACKER_CMDS = { spawn: 1, stage: 1, launch: 1, tech: 1, ability: 1 };
// ---------------------------------------------------------------- difficulty
// One row per difficulty; every number is a multiplier on the base tables below (normal is all 1, so it plays exactly the tuned base game):
// gold the starting credits (START_GOLD) lives the starting integrity (START_LIVES), at least 1
@ -614,6 +677,37 @@
this.bullets = [];
this.spawnQ = [];
this.events = [];
this.vs = null; // versus state (null in solo / co-op, which then run exactly as before)
if (opts.mode === 'versus') this.initVersus(opts);
}
// Versus: no waves, no difficulty (units are base stats x the attacker's tech), the defender's credits are `gold`, the integrity is
// `lives`; the round ends when it hits 0 (attacker wins) or `limit` seconds pass (defender wins). state: 'playing' -> 'over'.
initVersus(opts) {
this.difficulty = DEFAULT_DIFFICULTY;
this.diff = DIFFICULTIES[DEFAULT_DIFFICULTY];
this.gold = opts.gold === undefined ? VS.DEF_GOLD : opts.gold;
this.lives = opts.lives === undefined ? START_LIVES : opts.lives;
this.maxLives = this.lives;
this.winWave = Infinity;
const tech = {}, acd = {}, dcd = {};
for (const k of VS.TECH_ORDER) tech[k] = 0;
for (const k of VS.ABILITY_ORDER) acd[k] = 0;
for (const k of VS.TOOL_ORDER) dcd[k] = 0;
this.vs = {
limit: Number.isFinite(opts.limit) && opts.limit > 0 ? opts.limit : VS.DEFAULT_LIMIT,
credits: opts.credits === undefined ? VS.ATT_CREDITS : opts.credits, // the attacker's (role-private)
tech, acd, dcd,
staged: [], // the convoy: [[kind, n], ...] in the order it was bought (paid, not on the map yet)
rel: [], // units being let out: { t, kind, gate } (paid, count towards the alive cap)
surgeT: 0, ddosT: 0, freezeT: 0,
scans: [], // Scan reveal zones: { x, y, t }
trickle: 0, // the defender's fractional income (gold stays a whole number)
lost: 0, // integrity taken off in total (repairs do not give it back)
result: null, // { winner, t, integrityLost } once the round is over
stats: { spawned: 0, unitsSpent: 0, techSpent: 0, abilitySpent: 0, toolSpent: 0, earned: 0, leaked: 0, kills: 0 },
};
}
emit(e) {
@ -626,6 +720,7 @@
// ---- commands -------------------------------------------------------------------------
cmd(c) {
if (!c || typeof c !== 'object') return { ok: false, reason: 'bad_cmd' };
if (this.vs) return this.vsCmd(c);
switch (c.c) {
case 'place': return this.place(c.type, c.x, c.y, c.by | 0);
case 'sell': return this.sell(c.id);
@ -638,6 +733,189 @@
}
}
// ---- versus commands --------------------------------------------------------------------
// The command carries the issuer's `role` ('defender' | 'attacker'; the server fills it from the seat). Order of refusals, all of them
// BEFORE anything is charged or started: unknown command -> bad_cmd (waves are 'versus'), wrong or missing role -> 'role', round over
// -> 'over', then the command's own checks (bad_cmd / bad_kind / bad_target for malformed input, 'cap', 'max', 'cooldown', 'credits').
// A cooldown starts only when the command succeeded.
vsCmd(c) {
const need = hasOwn(DEFENDER_CMDS, c.c) ? 'defender' : hasOwn(ATTACKER_CMDS, c.c) ? 'attacker' : null;
if (!need) return { ok: false, reason: c.c === 'wave' || c.c === 'auto' || c.c === 'continue' ? 'versus' : 'bad_cmd' };
if (c.role !== need) return { ok: false, reason: 'role' };
if (this.state !== 'playing') return { ok: false, reason: 'over' };
let r;
switch (c.c) {
case 'place': r = this.place(c.type, c.x, c.y, c.by | 0); break;
case 'sell': r = this.sell(c.id); break;
case 'upgrade': r = this.upgrade(c.id, c.lv); break;
case 'target': r = this.setTargetMode(c.id, c.mode); break;
case 'tool': r = this.useTool(c); break;
case 'spawn': r = this.vsBuy(c, false); break;
case 'stage': r = this.vsBuy(c, true); break;
case 'launch': r = this.vsLaunch(c); break;
case 'tech': r = this.vsTech(c.id); break;
default: r = this.vsAbility(c);
}
if (r.ok && need === 'attacker') this.vsRelease(); // the first unit of a stream is on the map when the command returns
return r;
}
vsGate(g) {
if (g === undefined || g === null) return -1; // -1: round robin
return Number.isInteger(g) && g >= 0 && g < this.board.spawns.length ? g : -2;
}
vsAlive() { let n = 0; for (const m of this.monsters) if (!m.dead && !m.decoy) n++; return n + this.vs.rel.length; }
vsStaged() { let n = 0; for (const e of this.vs.staged) n += e[1]; return n; }
vsCount(c) { // units in a spawn / stage command: a positive whole number (default 1)
const n = c.n === undefined || c.n === null ? 1 : c.n;
return Number.isInteger(n) && n >= 1 && n <= VS.MAX_ALIVE ? n : 0;
}
// Queue `n` units of `kind` for release as a stream starting now (the stream's gaps: RELEASE_GAP, at most LAUNCH_SPAN s in all).
vsQueue(kind, n, gate, t0, gap) {
for (let i = 0; i < n; i++) {
const g = gate >= 0 ? gate : this.spawnRR++ % this.board.spawns.length;
this.vs.rel.push({ t: t0 + i * gap, kind, gate: g });
}
}
vsGap(n) { return n > 1 ? Math.min(VS.RELEASE_GAP, VS.LAUNCH_SPAN / n) : 0; }
// spawn (buy and release now) / stage (pay now, hold in the convoy)
vsBuy(c, stage) {
if (typeof c.kind !== 'string' || !hasOwn(ENEMIES, c.kind)) return { ok: false, reason: 'bad_kind' };
const n = this.vsCount(c);
if (!n) return { ok: false, reason: 'bad_cmd' };
const gate = this.vsGate(c.gate);
if (gate === -2) return { ok: false, reason: 'bad_target' };
const v = this.vs, cost = ENEMIES[c.kind].buyCost * n;
if (stage ? this.vsStaged() + n > VS.MAX_STAGED : this.vsAlive() + n > VS.MAX_ALIVE) return { ok: false, reason: 'cap' };
if (v.credits + EPS < cost) return { ok: false, reason: 'credits' };
v.credits -= cost; v.stats.unitsSpent += cost;
if (stage) {
const e = v.staged.find((q) => q[0] === c.kind);
if (e) e[1] += n; else v.staged.push([c.kind, n]);
return { ok: true, n, staged: this.vsStaged() };
}
this.vsQueue(c.kind, n, gate, this.time, this.vsGap(n));
return { ok: true, n };
}
// launch: let (as much as fits under the alive cap of) the convoy out as one stream
vsLaunch(c) {
const gate = this.vsGate(c.gate);
if (gate === -2) return { ok: false, reason: 'bad_target' };
const v = this.vs, total = this.vsStaged();
if (!total) return { ok: false, reason: 'empty' };
const room = VS.MAX_ALIVE - this.vsAlive();
if (room <= 0) return { ok: false, reason: 'cap' };
const k = Math.min(total, room), gap = this.vsGap(k);
let left = k, i = 0;
for (const e of v.staged) {
const take = Math.min(e[1], left);
this.vsQueue(e[0], take, gate, this.time + i * gap, gap);
e[1] -= take; left -= take; i += take;
if (!left) break;
}
v.staged = v.staged.filter((e) => e[1] > 0);
return { ok: true, n: k, staged: total - k };
}
// tech: the next level of one upgrade, TECH_COST * 2^(level now); applies to units that enter the map afterwards
vsTech(id) {
if (typeof id !== 'string' || !hasOwn(VS.TECH, id)) return { ok: false, reason: 'bad_target' };
const v = this.vs, lv = v.tech[id];
if (lv >= VS.TECH[id].max) return { ok: false, reason: 'max' };
const cost = VS.TECH_COST * Math.pow(2, lv);
if (v.credits + EPS < cost) return { ok: false, reason: 'credits' };
v.credits -= cost; v.stats.techSpent += cost;
v.tech[id] = lv + 1;
return { ok: true, level: lv + 1 };
}
techCost(id) { const lv = this.vs.tech[id]; return lv >= VS.TECH[id].max ? null : VS.TECH_COST * Math.pow(2, lv); }
// abilities: emp (tid) / decoy (gate? tid?) / surge / ddos
vsAbility(c) {
if (typeof c.id !== 'string' || !hasOwn(VS.ABILITIES, c.id)) return { ok: false, reason: 'bad_target' };
const v = this.vs, A = VS.ABILITIES[c.id];
let tower = null, gate = -1;
if (c.id === 'emp') {
tower = typeof c.tid === 'number' ? this.towerById(c.tid) : null;
if (!tower || TOWERS[tower.type].role === 'wall') return { ok: false, reason: 'bad_target' }; // a Firewall does nothing to disable
} else if (c.id === 'decoy') {
gate = this.vsGate(c.gate);
if (gate === -2) return { ok: false, reason: 'bad_target' };
if (c.tid !== undefined && c.tid !== null) { tower = typeof c.tid === 'number' ? this.towerById(c.tid) : null; if (!tower) return { ok: false, reason: 'bad_target' }; }
}
if (cooling(v.acd[c.id])) return { ok: false, reason: 'cooldown' };
if (v.credits + EPS < A.cost) return { ok: false, reason: 'credits' };
v.credits -= A.cost; v.stats.abilitySpent += A.cost; v.acd[c.id] = A.cd;
switch (c.id) {
case 'emp': tower.empT = A.dur; tower.tgt = 0; this.emit({ e: 'emp', id: tower.id, d: A.dur }); break;
case 'decoy': this.vsDecoy(gate, tower, A.dur); break;
case 'surge': v.surgeT = A.dur; this.emit({ e: 'surge', d: A.dur }); break;
default: v.ddosT = A.dur; this.emit({ e: 'ddos', d: A.dur });
}
return { ok: true };
}
// The decoy: an existing kind (a Ping) with the decoy flag, so no new wire kind. Invulnerable, harmless (leaks for nothing, pays nothing,
// earns nothing, outside the caps), gone after `dur` s. With `tower` it appears on the route cell closest to that tower, else at the gate.
vsDecoy(gate, tower, dur) {
const b = this.board, g = gate >= 0 ? gate : this.spawnRR++ % b.spawns.length;
let at = null;
if (tower) {
let bd = Infinity;
for (const cell of b.routes[g]) {
const d = (cell[0] - tower.x) * (cell[0] - tower.x) + (cell[1] - tower.y) * (cell[1] - tower.y);
if (d < bd) { bd = d; at = cell; }
}
}
const m = this.vsUnit('ping', g, at);
m.decoy = true; m.ttl = dur; m.leak = 0; m.reward = 0; m.buyCost = 0; m.stealthT = 0; m.regen = 0; m.shield = m.maxShield = 0;
this.monsters.push(m);
this.emit({ e: 'decoy', id: m.id, d: dur });
}
// defender tools: { c:'tool', id:'scan'|'patch'|'repair'|'quarantine', x?, y?, tid? }, paid with `gold`
useTool(c) {
if (typeof c.id !== 'string' || !hasOwn(VS.TOOLS, c.id)) return { ok: false, reason: 'bad_target' };
const v = this.vs, T = VS.TOOLS[c.id], b = this.board;
let tower = null;
if (c.id === 'scan') {
if (typeof c.x !== 'number' || typeof c.y !== 'number' || !isFinite(c.x) || !isFinite(c.y) || c.x < 0 || c.y < 0 || c.x > b.cols || c.y > b.rows) return { ok: false, reason: 'bad_target' };
} else if (c.id === 'patch') {
tower = typeof c.tid === 'number' ? this.towerById(c.tid) : null;
if (!tower || !(tower.empT > 0)) return { ok: false, reason: 'bad_target' }; // nothing to re-enable
} else if (c.id === 'repair') {
if (this.lives >= this.maxLives) return { ok: false, reason: 'max' };
}
if (cooling(v.dcd[c.id])) return { ok: false, reason: 'cooldown' };
if (this.gold < T.cost) return { ok: false, reason: 'credits' };
this.gold -= T.cost; v.stats.toolSpent += T.cost; v.dcd[c.id] = T.cd;
switch (c.id) {
case 'scan': {
const r2 = T.radius * T.radius;
for (const t of this.towers) {
const dx = t.x + 0.5 - c.x, dy = t.y + 0.5 - c.y;
if (t.empT > 0 && dx * dx + dy * dy <= r2) t.empT = 0;
}
v.scans.push({ x: c.x, y: c.y, t: T.reveal });
this.emit({ e: 'scan', x: round2(c.x), y: round2(c.y) });
break;
}
case 'patch': tower.empT = 0; break;
case 'repair': this.lives = Math.min(this.maxLives, this.lives + T.amount); this.emit({ e: 'repair' }); break;
default: v.freezeT = T.dur; this.emit({ e: 'quarantine', d: T.dur });
}
return { ok: true };
}
// A Scan zone reveals stealthed units (they can be targeted) for its `reveal` seconds.
vsRevealed(m) {
for (const z of this.vs.scans) { const dx = m.x - z.x, dy = m.y - z.y; if (dx * dx + dy * dy <= VS.TOOLS.scan.radius * VS.TOOLS.scan.radius) return true; }
return false;
}
// Cells monsters occupy or are about to enter; used to refuse placements that would trap or clip them.
monsterCells() {
const b = this.board, cols = b.cols;
@ -692,7 +970,7 @@
}
sell(id) {
if (this.state === 'lost') return { ok: false, reason: 'over' };
if (this.state === 'lost' || this.state === 'over') return { ok: false, reason: 'over' };
const t = this.towerById(id);
if (!t) return { ok: false, reason: 'no_tower' };
const def = TOWERS[t.type];
@ -736,12 +1014,14 @@
}
setAuto(v) {
if (this.vs) return { ok: false, reason: 'versus' };
this.autoWaves = v;
if (v && this.nextWaveIn < 0) this.nextWaveIn = WAVE_INTERVAL;
return { ok: true };
}
continueEndless() {
if (this.vs) return { ok: false, reason: 'versus' };
if (this.state !== 'won') return { ok: false, reason: 'not_won' };
this.state = 'playing';
this.winWave = Infinity;
@ -751,6 +1031,7 @@
// `expect` is the wave number the sender expects this command to start (the wave it saw + 1; absent: no check; the auto-wave timer
// never passes one). A second "Next wave" pressed at the same moment by the other player is refused as 'stale', not started twice.
startWave(expect) {
if (this.vs) return { ok: false, reason: 'versus' }; // versus has no waves: the attacker brings the units
if (this.state !== 'playing') return { ok: false, reason: 'over' };
if (expect !== undefined && expect !== null && expect !== this.wave + 1) return { ok: false, reason: 'stale' };
const n = ++this.wave;
@ -787,10 +1068,80 @@
this.monsters.push(m);
}
// ---- versus units ---------------------------------------------------------------------
// A unit at gate `gate` (or on the route cell `at` = [x, y]): the kind's BASE stats x the attacker's tech now. No hpScale, no difficulty.
vsUnit(kind, gate, at) {
const def = ENEMIES[kind], b = this.board, T = this.vs.tech, X = VS.TECH;
const s = at ? { x: at[0], y: at[1] } : b.spawns[gate];
const hp = Math.max(1, Math.round(def.hp * (1 + X.health.per * T.health)));
const shield = (def.shield || 0) + (T.shield ? X.shield.per * T.shield : 0);
const m = {
id: this.nid++, kind, air: !!def.air,
x: s.x + 0.5, y: s.y + 0.5, cx: s.x, cy: s.y, tx: -1, ty: -1,
hp, maxhp: hp, armor: def.armor + X.armor.per * T.armor, speed: def.speed * (1 + X.speed.per * T.speed),
reward: Math.max(1, Math.round(def.buyCost * VS.KILL_REWARD)),
leak: def.leak, slow: 0, slowT: 0, slowAmt: 0, stunT: 0,
shield, maxShield: shield, shieldT: 0,
rem: 0, dead: false, wave: 0,
buyCost: def.buyCost, earned: 0, // lifetime bonus paid so far
regen: X.regen.per * T.regen, // fraction of max hp per second
crypt: T.crypt ? X.crypt.res[T.crypt - 1] : 0, // slows work this much weaker
stealthT: T.stealth ? X.stealth.secs[T.stealth - 1] : 0, // towers cannot acquire it until this runs out (or a Scan reveals it)
};
m.rem = m.air ? Math.hypot(b.core.x - s.x, b.core.y - s.y) : b.field[s.y * b.cols + s.x];
return m;
}
// Units whose release time has come enter the map (a command calls this too, so the first unit of a stream is there at once).
vsRelease() {
const rel = this.vs.rel;
let w = 0;
for (let i = 0; i < rel.length; i++) {
const q = rel[i];
if (q.t <= this.time + 1e-9) { this.monsters.push(this.vsUnit(q.kind, q.gate)); this.vs.stats.spawned++; } else rel[w++] = q;
}
rel.length = w;
}
// Start of every versus tick: income, lifetime bonus, the defender's trickle, cooldowns and effect timers, unit timers, releases.
vsBegin(dt) {
const v = this.vs;
let inc = (VS.ATT_INCOME + VS.ATT_INCOME_GROWTH * (this.time - dt / 2)) * dt; // the rate in the middle of this tick: exact for a rate that rises linearly
for (const m of this.monsters) {
if (m.dead) continue;
if (m.decoy) { m.ttl -= dt; if (m.ttl <= 0) m.dead = true; continue; }
const cap = m.buyCost * VS.LIFE_CAP;
if (m.earned < cap) { const b = Math.min(m.buyCost * VS.LIFE_RATE * dt, cap - m.earned); m.earned += b; inc += b; }
if (m.stealthT > 0) m.stealthT -= dt;
if (m.regen > 0 && m.hp < m.maxhp) m.hp = Math.min(m.maxhp, m.hp + m.maxhp * m.regen * dt);
}
v.credits += inc; v.stats.earned += inc;
v.trickle += VS.DEF_TRICKLE * dt;
const whole = Math.floor(v.trickle);
if (whole > 0) { this.gold += whole; v.trickle -= whole; }
for (const k in v.acd) if (v.acd[k] > 0) v.acd[k] = Math.max(0, v.acd[k] - dt);
for (const k in v.dcd) if (v.dcd[k] > 0) v.dcd[k] = Math.max(0, v.dcd[k] - dt);
if (v.surgeT > 0) v.surgeT = Math.max(0, v.surgeT - dt);
if (v.ddosT > 0) v.ddosT = Math.max(0, v.ddosT - dt);
if (v.freezeT > 0) v.freezeT = Math.max(0, v.freezeT - dt);
if (v.scans.length) { for (const z of v.scans) z.t -= dt; v.scans = v.scans.filter((z) => z.t > 0); }
if (v.rel.length) this.vsRelease();
}
// The round is over: `winner` is 'attacker' (integrity gone) or 'defender' (time ran out).
vsEnd(winner) {
const v = this.vs;
if (this.lives < 0) this.lives = 0;
this.state = 'over';
v.result = { winner, t: round2(this.time), integrityLost: v.lost };
this.emit({ e: 'round', winner, t: v.result.t });
}
// ---- main step ------------------------------------------------------------------------
tick(dt) {
if (this.state !== 'playing') return;
this.time += dt;
if (this.vs) this.vsBegin(dt);
if (this.autoWaves) {
this.nextWaveIn -= dt;
if (this.nextWaveIn <= 0) this.startWave();
@ -816,6 +1167,11 @@
}
this.monsters.length = w;
if (this.vs) { // versus: integrity first (the attacker wins even on the last tick), then the clock
if (this.lives <= 0) this.vsEnd('attacker');
else if (this.time >= this.vs.limit) this.vsEnd('defender');
return;
}
if (this.lives <= 0) {
this.lives = 0;
this.state = 'lost';
@ -837,9 +1193,12 @@
// ---- monsters -------------------------------------------------------------------------
moveMonster(m, dt) {
if (m.stunT > 0) return; // stunned (Sandbox): frozen in place
const vs = this.vs;
if (vs && vs.freezeT > 0) return; // Quarantine: every unit is frozen
const b = this.board;
const slowMul = 1 - Math.min(0.6, m.slow);
let remaining = m.speed * slowMul * dt;
if (vs && vs.surgeT > 0) remaining *= 1 + VS.ABILITIES.surge.speed;
if (m.air) {
const gx = b.core.x + 0.5, gy = b.core.y + 0.5;
const dx = gx - m.x, dy = gy - m.y, d = Math.hypot(dx, dy);
@ -873,13 +1232,19 @@
leak(m) {
m.dead = true; m.leaked = true;
if (m.decoy) return; // a decoy that reaches the server is harmless and silent
const v = this.vs;
if (v) { // versus: the integrity taken off is counted, the attacker gets the unit's price back
v.lost += Math.min(m.leak, Math.max(0, this.lives));
v.credits += m.buyCost; v.stats.earned += m.buyCost; v.stats.leaked++;
}
this.lives -= m.leak;
this.leaks++;
this.emit({ e: 'leak', x: m.x, y: m.y, n: m.leak });
}
damage(m, raw, src, ignoreArmor) {
if (m.dead) return;
if (m.dead || m.decoy) return; // (a decoy cannot be hurt)
const d = ignoreArmor ? raw : Math.max(raw - m.armor, raw * 0.25); // armour applies once, to the damage dealt
let hit = d;
if (m.maxShield > 0) { // a shield soaks first, any damage restarts its regrow timer
@ -892,6 +1257,7 @@
m.dead = true;
this.gold += m.reward;
this.kills++;
if (this.vs) this.vs.stats.kills++;
if (src) src.kills++;
this.emit({ e: 'kill', x: m.x, y: m.y, k: m.kind, rw: m.reward });
}
@ -900,6 +1266,7 @@
// Shield: after shieldDelay s without damage it regrows shieldRegen of its maximum per second.
regenShield(m, dt) {
const def = ENEMIES[m.kind];
if (!def.shieldRegen) return; // a shield bought as tech on a kind that has none does not regrow
m.shieldT += dt;
const over = Math.min(dt, m.shieldT - def.shieldDelay);
if (over > 0 && m.shield < m.maxShield) m.shield = Math.min(m.maxShield, m.shield + m.maxShield * def.shieldRegen * over);
@ -930,7 +1297,7 @@
updateAuras() {
const ts = this.towers;
let sup = null;
for (const t of ts) { t.buff = 0; if (TOWERS[t.type].role === 'support') (sup || (sup = [])).push(t); }
for (const t of ts) { t.buff = 0; if (TOWERS[t.type].role === 'support' && !(t.empT > 0)) (sup || (sup = [])).push(t); } // (an EMPed balancer boosts nothing)
if (!sup) return;
for (const s of sup) {
const st = TOWERS[s.type].levels[s.level - 1], r2 = st.range * st.range;
@ -951,8 +1318,12 @@
if (m.air ? !def.air : !def.ground) continue;
const dx = m.x - tx, dy = m.y - ty, d2 = dx * dx + dy * dy;
if (d2 > r2) continue;
// versus: a stealthed unit cannot be ACQUIRED as a target (splash, beam and chain lightning still hit it once something else is
// shot) until its stealth runs out or a Scan reveals it; a decoy beats every other target, the nearest decoy first
if (m.stealthT > 0 && !this.vsRevealed(m)) continue;
let v;
switch (t.mode) {
if (m.decoy) v = 1e9 - d2;
else switch (t.mode) {
case 'last': v = m.rem; break;
case 'strong': v = m.hp + (m.shield || 0); break;
case 'close': v = -d2; break;
@ -964,23 +1335,25 @@
}
updateTower(t, dt) {
if (t.empT > 0) { t.empT -= dt; t.tgt = 0; return; } // versus: an EMPed tower does nothing (attack, slow, stun, boost) until it runs out
const def = TOWERS[t.type];
if (def.role === 'wall' || def.role === 'support') return;
const st = def.levels[t.level - 1];
const cx = t.x + 0.5, cy = t.y + 0.5;
if (def.role === 'control') { this.pulseStun(t, st, def, cx, cy, dt); return; }
const dd = this.vs && this.vs.ddosT > 0 ? 1 - VS.ABILITIES.ddos.slow : 1; // DDoS: cooldowns run slower
if (def.role === 'control') { this.pulseStun(t, st, def, cx, cy, dt * dd); return; }
if (def.role === 'aura') {
const r2 = st.range * st.range;
for (const m of this.monsters) {
if (m.dead) continue;
const dx = m.x - cx, dy = m.y - cy;
if (dx * dx + dy * dy > r2) continue;
const eff = st.slow * (1 - (ENEMIES[m.kind].slowRes || 0));
const eff = st.slow * (1 - (ENEMIES[m.kind].slowRes || 0)) * (1 - (m.crypt || 0));
if (eff > m.slow) m.slow = eff;
}
return;
}
t.cd -= dt * (1 + (t.buff || 0)); // a Load Balancer makes cooldowns elapse faster
t.cd -= dt * (1 + (t.buff || 0)) * dd; // a Load Balancer makes cooldowns elapse faster
const m = this.findTarget(t, st.range, def);
t.tgt = m ? m.id : 0;
if (!m) { if (t.cd < 0) t.cd = 0; return; }
@ -1051,7 +1424,7 @@
if (dx * dx + dy * dy <= r2) blast.push(o);
}
const slowFor = (o) => {
const eff = Math.min(0.6, st.slowOnHit * (1 - (ENEMIES[o.kind].slowRes || 0)));
const eff = Math.min(0.6, st.slowOnHit * (1 - (ENEMIES[o.kind].slowRes || 0)) * (1 - (o.crypt || 0)));
if (eff >= o.slowAmt || o.slowT <= 0) o.slowAmt = eff;
o.slowT = Math.max(o.slowT, st.slowFor);
};
@ -1120,12 +1493,35 @@
// Everything a client needs to (re)build the board from scratch.
fullState() {
return {
const f = {
map: this.mapId, rev: this.rev, towers: this.towerList(),
winWave: this.winWave === Infinity ? 0 : this.winWave,
maxLives: this.maxLives,
difficulty: this.difficulty,
};
if (this.vs) { f.mode = 'versus'; f.limit = this.vs.limit; } // only versus carries these: a co-op state is exactly what it was
return f;
}
// What ONE side may know that the other may not (the shared snapshot carries only snapshot().vs). The server sends it to the seat that
// holds the role; copies, so a caller cannot reach into the sim.
// attacker { credits, income (credits per second now), tech {id: level}, staged [[kind, n]], cd {ability: seconds left}, active {surge, ddos: seconds left} }
// defender { cd {tool: seconds left} } (its credits are `gold` in the shared snapshot)
privateState(role) {
const v = this.vs;
if (!v) return null;
const left = (o) => { const r = {}; for (const k in o) r[k] = up2(o[k]); return r; };
if (role === 'defender') return { cd: left(v.dcd) };
if (role !== 'attacker') return null;
let income = VS.ATT_INCOME + VS.ATT_INCOME_GROWTH * this.time;
for (const m of this.monsters) if (!m.dead && !m.decoy && m.earned < m.buyCost * VS.LIFE_CAP) income += m.buyCost * VS.LIFE_RATE;
return {
credits: down2(v.credits), income: round2(income),
tech: Object.assign({}, v.tech),
staged: v.staged.map((e) => [e[0], e[1]]),
cd: left(v.acd),
active: { surge: up2(v.surgeT), ddos: up2(v.ddosT) },
};
}
// Compact per-tick state for the wire. Arrays, not objects, to keep it small.
@ -1134,20 +1530,23 @@
const mo = this.monsters.map((m) => [m.id, ENEMY_ORDER.indexOf(m.kind), round2(m.x), round2(m.y), Math.ceil(m.hp + (m.shield || 0)), m.maxhp + (m.maxShield || 0), m.slow > 0 || m.stunT > 0 ? 1 : 0]);
const bu = this.bullets.map((b) => [b.id, b.k === 'mortar' ? 1 : 0, round2(b.x), round2(b.y)]);
const tt = [];
for (const t of this.towers) if (t.type !== 'wall') tt.push([t.id, t.tgt, t.kills]);
return {
const v = this.vs;
for (const t of this.towers) if (t.type !== 'wall') tt.push(v ? [t.id, t.tgt, t.kills, t.empT > 0 ? round2(t.empT) : 0] : [t.id, t.tgt, t.kills]); // versus: a 4th field, seconds left of an EMP
const snap = {
time: round2(this.time), g: this.gold, l: this.lives, w: this.wave, s: this.state,
au: this.autoWaves ? 1 : 0, nw: this.autoWaves ? round2(this.nextWaveIn) : -1,
k: this.kills, rev: this.rev, mo, bu, tt,
q: this.spawnQ.length,
};
if (v) snap.vs = { t: round2(this.time), lim: v.limit, st: this.vsStaged() }; // the SHARED part only: how big the convoy is, never what is in it
return snap;
}
}
function round2(v) { return Math.round(v * 100) / 100; }
return {
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE, HEAL_EVERY, HEAL_CAP,
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE, HEAL_EVERY, HEAL_CAP, VS,
DIFFICULTIES, DIFFICULTY_ORDER, DEFAULT_DIFFICULTY, isDifficulty, difficultyId,
MAPS, MAP_ORDER, TOWERS, TOWER_ORDER, TARGET_MODES, ENEMIES, ENEMY_ORDER,
priceFor, priceMult, upgradePrice, waveGroups, waveSummary, hpScale, rewardScale, clearBonus,

815
public/js/versus.js Normal file
View file

@ -0,0 +1,815 @@
/*
* NETWALL versus UI (docs/VERSUS.md, docs/PROTOCOL.md "Versus"). Everything that is specific to the attack-vs-defend mode lives here: the setup and
* room dialogs, the round / match result dialog, the role-aware HUD (attacker: unit shop, convoy + Launch, abilities, tech; defender: counter-tools),
* the countdown card and the sounds for the new actions. main.js owns the rest (board, input, co-op, solo) and calls into this module at a few
* guarded places; with no versus game running (V.active false) none of it does anything, so solo and co-op behave as they always did.
*
* The module talks to a controller (LocalController against the computer, or RemoteController in an online room) only through the documented
* surface: ctrl.vs (match message), ctrl.priv (role-private data), ctrl.role, ctrl.view, ctrl.send(cmd), ctrl.vsRole / vsReady / vsBot / vsStart /
* vsNext / vsRematch. The role of a command is never set here: the controller (or the server) knows the seat.
*/
(function (root) {
'use strict';
const NW = root.NW = root.NW || {};
const TD = root.TD;
const VS = TD.VS;
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const other = (r) => (r === 'attacker' ? 'defender' : 'attacker');
const roleCls = (r) => (r === 'attacker' ? 'attacker' : 'defender'); // (a role from the server goes into HTML only through this)
const cap1 = (s) => String(s).charAt(0).toUpperCase() + String(s).slice(1);
const mmss = (sec) => { sec = Math.max(0, Math.round(sec)); return Math.floor(sec / 60) + ':' + (sec % 60 < 10 ? '0' : '') + (sec % 60); };
const SVGNS = 'http://www.w3.org/2000/svg';
const icon = (id) => '<svg class="ic" aria-hidden="true"><use href="#' + id + '"/></svg>';
const SKILLS = [{ id: 'easy', name: 'Easy', v: 0.35 }, { id: 'normal', name: 'Normal', v: 0.7 }, { id: 'hard', name: 'Hard', v: 1 }];
const QTYS = [1, 5, 10];
const NAMES = {
armor: 'Armor', speed: 'Speed', health: 'Health', regen: 'Regen', shield: 'Shield', stealth: 'Stealth', crypt: 'Crypt',
emp: 'EMP', decoy: 'Decoy', surge: 'Surge', ddos: 'DDoS', scan: 'Scan', patch: 'Patch', repair: 'Repair', quarantine: 'Quarantine',
};
const nameOf = (id) => NAMES[id] || cap1(id);
const REASONS = {
role: "That is the other player's job", credits: 'Not enough credits', cooldown: 'Still cooling down', cap: 'Too many packets on the board', max: 'Nothing to do',
bad_target: 'Not a valid target', bad_kind: 'Unknown packet', empty: 'The convoy is empty', phase: 'The round has not started yet', frozen: 'Paused: waiting for the other player to come back',
versus: 'Not available in versus', not_host: 'Only the host can do that', no_opponent: 'Waiting for an opponent', offline: 'The opponent is offline',
not_ready: 'The opponent is not ready yet', full: 'Both seats are taken', over: 'The round is over',
};
// What a level of a tech upgrade does, worded from the table (a retune cannot leave this text wrong).
function techText(id, lv) {
const X = VS.TECH[id];
if (!X) return '';
switch (id) {
case 'armor': return '+' + +(X.per * lv).toFixed(2) + ' armour';
case 'speed': return '+' + Math.round(X.per * lv * 100) + '% speed';
case 'health': return '+' + Math.round(X.per * lv * 100) + '% hit points';
case 'regen': return Math.round(X.per * lv * 100) + '% of max hp back per second';
case 'shield': return '+' + Math.round(X.per * lv) + ' shield';
case 'stealth': return 'towers cannot target a packet for its first ' + X.secs[lv - 1] + ' s';
case 'crypt': return 'slows work ' + Math.round(X.res[lv - 1] * 100) + '% weaker';
default: return '';
}
}
function abilityText(id) {
const A = VS.ABILITIES[id];
if (!A) return '';
switch (id) {
case 'emp': return 'Disable one tower for ' + A.dur + ' s';
case 'decoy': return 'A harmless packet every tower shoots at for ' + A.dur + ' s';
case 'surge': return 'All packets ' + Math.round(A.speed * 100) + '% faster for ' + A.dur + ' s';
case 'ddos': return 'All towers fire ' + Math.round(A.slow * 100) + '% slower for ' + A.dur + ' s';
default: return '';
}
}
function toolText(id) {
const T = VS.TOOLS[id];
if (!T) return '';
switch (id) {
case 'scan': return 'Clear EMP and reveal stealth within ' + T.radius + ' cells for ' + T.reveal + ' s (tap the map)';
case 'patch': return 'Re-enable a disabled tower at once';
case 'repair': return 'Restore ' + T.amount + ' integrity';
case 'quarantine': return 'Freeze every packet for ' + T.dur + ' s';
default: return '';
}
}
// A segmented radiogroup (the same pattern as the difficulty picker): items [{ id, label, title? }]
function buildSeg(box, items, onPick) {
box.textContent = '';
for (const it of items) {
const b = document.createElement('button');
b.type = 'button'; b.dataset.v = it.id; b.setAttribute('role', 'radio'); b.setAttribute('aria-checked', 'false');
b.textContent = it.label; if (it.title) b.title = it.title;
b.addEventListener('click', () => onPick(it.id));
box.appendChild(b);
}
}
function segSet(box, id) { for (const b of box.children) b.setAttribute('aria-checked', b.dataset.v === String(id) ? 'true' : 'false'); }
function create(api) {
const { $, app, renderer, Audio, store, esc, toast, banner, showOverlay } = api;
const S = {
ctrl: null, active: false, role: null, vs: null, priv: null, privAt: 0, phase: '',
qty: 1, mode: 'now', gate: -1, shopOn: false, scanArm: false, empArm: false,
cd: {}, act: {}, fx: { surge: 0, ddos: 0, freeze: 0 }, confirm: { key: '', until: 0 },
endTimer: 0, sentNext: false, sentRematch: false, el: {}, last: {}, built: '', decoys: new Map(),
setup: { role: store.get('nw.vs.role', 'random'), limit: store.get('nw.vs.limit', VS.DEFAULT_LIMIT), skill: store.get('nw.vs.skill', 'normal') },
};
if (!['attacker', 'defender', 'random'].includes(S.setup.role)) S.setup.role = 'random';
if (!VS.LIMITS.includes(S.setup.limit)) S.setup.limit = VS.DEFAULT_LIMIT;
if (!SKILLS.some((k) => k.id === S.setup.skill)) S.setup.skill = 'normal';
const UIS = { role: null, tech: null, gate: -1, gates: 1, scanArm: false, empArm: false, decoys: S.decoys }; // what the renderer needs (reused every frame)
const now = () => performance.now();
// ------------------------------------------------------------------ small helpers
const ctrl = () => S.ctrl;
const mySlot = () => (S.ctrl && S.ctrl.you && Number.isInteger(S.ctrl.you.slot) ? S.ctrl.you.slot : 0);
const roleOf = () => (S.ctrl && S.vs ? S.vs.roles[mySlot()] || null : null);
const players = () => (S.ctrl && S.ctrl.players) || [];
const playerName = (slot) => {
if (slot === mySlot()) return 'You';
if (S.vs && S.vs.bot && S.vs.bot.slot === slot) return S.vs.bot.name || 'Computer';
const p = players().find((q) => q.slot === slot);
return p ? p.name : 'Opponent';
};
const phasePlaying = () => !!S.vs && S.vs.phase === 'playing' && !S.vs.frozen;
const gates = () => (S.ctrl && S.ctrl.board ? S.ctrl.board.spawns.length : 1);
const skillValue = () => (SKILLS.find((k) => k.id === S.setup.skill) || SKILLS[1]).v;
const credits = () => { // the attacker's purse, run forward from the last private message (4 Hz) so it moves smoothly
const p = S.priv; if (!p || p.role !== 'attacker') return 0;
return Math.max(0, Math.floor(p.credits + p.income * clamp((now() - S.privAt) / 1000, 0, 0.6)));
};
const stagedTotal = () => { let n = 0; if (S.priv && S.priv.staged) for (const e of S.priv.staged) n += e[1]; return n; };
const cdLeft = (id) => { const c = S.cd[id]; return c ? Math.max(0, c.left - (now() - c.at) / 1000) : 0; };
const actLeft = (id) => { const c = S.act[id]; return c ? Math.max(0, c.left - (now() - c.at) / 1000) : 0; };
const fxLeft = (id) => Math.max(0, (S.fx[id] - now()) / 1000);
function say(text, kind) { // the pill at the top of the stage (armed states)
const n = $('vsNote');
if (!text) { n.hidden = true; return; }
n.hidden = false; n.textContent = text; n.className = 'hint ' + (kind || 'info');
}
function disarm() {
if (!S.scanArm && !S.empArm) return;
S.scanArm = false; S.empArm = false; say(null);
}
function confirmTap(key, text) { // a costly action asks for a second tap within 2.5 s
const t = now();
if (S.confirm.key === key && t < S.confirm.until) { S.confirm.key = ''; return true; }
S.confirm.key = key; S.confirm.until = t + 2500;
toast(text || 'Tap again to confirm', 'good');
return false;
}
function send(cmd) {
const c = S.ctrl; if (!c) return { ok: false };
return c.send(cmd);
}
function gateArg(cmd) { if (S.gate >= 0 && S.gate < gates()) cmd.gate = S.gate; return cmd; }
// ------------------------------------------------------------------ attach / detach (called by main.useController)
function attach(c) {
const on = !!c && c.mode === 'versus';
if (!on) {
if (S.active) teardown();
S.ctrl = c;
return;
}
S.ctrl = c; S.active = true;
S.vs = c.vs || null; S.priv = c.priv || null; S.privAt = now(); S.phase = '';
S.role = null; S.gate = -1; S.scanArm = false; S.empArm = false; S.sentNext = false; S.sentRematch = false;
S.cd = {}; S.act = {}; S.fx = { surge: 0, ddos: 0, freeze: 0 }; S.decoys.clear(); S.last = {};
clearTimeout(S.endTimer);
$('app').dataset.mode = 'versus';
if (c.kind === 'remote') { c.sendCursor = () => {}; c.sendMark = () => {}; } // the server ignores them in versus (an opponent must not see where you aim)
c.on('vs', (m) => { if (S.ctrl === c) onVs(m); });
c.on('priv', (m) => { if (S.ctrl === c) onPriv(m); });
c.on('newgame', () => { if (S.ctrl === c) { disarm(); S.gate = -1; S.last = {}; S.cd = {}; S.act = {}; S.decoys.clear(); S.fx = { surge: 0, ddos: 0, freeze: 0 }; } });
if (c.priv) onPriv(c.priv);
if (c.vs) onVs(c.vs);
}
function teardown() {
S.active = false; S.role = null; S.vs = null; S.priv = null; S.phase = '';
clearTimeout(S.endTimer); say(null);
const a = $('app'); delete a.dataset.mode; delete a.dataset.role;
for (const id of ['vsbar', 'vstech', 'vsHud', 'vsCount']) $(id).hidden = true;
$('vsbar').textContent = ''; $('vstech').textContent = ''; $('vsFx').textContent = '';
S.built = ''; S.el = {};
if (S.shopOn) { S.shopOn = false; api.buildPalette(); }
app.last.gold = undefined;
for (const id of ['vsRoom', 'vsEnd']) if (!$(id).hidden) showOverlay(null);
api.resize();
}
// ------------------------------------------------------------------ messages
function onPriv(m) {
if (!m || m.role !== roleOf() && m.role !== (S.ctrl && S.ctrl.role)) return; // the first priv of a new round can race the vs message: a stale role is dropped
S.priv = m; S.privAt = now();
const t = now();
if (m.cd) for (const id in m.cd) S.cd[id] = { left: m.cd[id], at: t };
if (m.active) for (const id in m.active) S.act[id] = { left: m.active[id], at: t };
}
function onVs(m) {
if (!m) return;
const prev = S.phase;
S.vs = m; S.phase = m.phase;
syncRole();
if (m.phase !== prev) onPhase(prev, m.phase);
if (m.phase === 'lobby') renderRoom();
if (m.phase === 'roundover' || m.phase === 'matchover') { if (!$('vsEnd').hidden) renderEnd(); }
renderCount();
}
function onPhase(prev, ph) {
disarm(); S.confirm.key = '';
clearTimeout(S.endTimer);
if (ph === 'lobby') { showOverlay('vsRoom'); renderRoom(); }
else if (ph === 'countdown') {
S.sentNext = false; S.sentRematch = false;
hideMine(); S.gate = -1; S.last = {};
api.adoptBoard(); api.resetSelection(); // (a local match builds a new board for every round; the renderer must follow it)
Audio.music('battle');
} else if (ph === 'playing') {
hideMine();
if (prev === 'countdown') { banner(S.role === 'attacker' ? 'ATTACK!' : 'DEFEND!', S.role === 'attacker'); Audio.sfx('go'); }
} else if (ph === 'roundover' || ph === 'matchover') {
S.sentNext = false; S.sentRematch = false;
const won = ph === 'matchover' ? matchResult() === 'win' : roundWon();
Audio.music(null);
const show = () => { if (S.active && (S.phase === 'roundover' || S.phase === 'matchover')) { renderEnd(); showOverlay('vsEnd'); Audio.stinger(won ? 'win' : 'lose'); } };
if (prev === 'playing') S.endTimer = setTimeout(show, 1100); else show(); // a beat to watch the last second
}
}
function hideMine() { for (const id of ['vsRoom', 'vsEnd']) if (!$(id).hidden) { showOverlay(null); break; } }
function roundWon() { const r = S.vs && S.vs.result; return !!r && r.winner === roleOf(); }
function matchResult() { // 'win' | 'lose' | 'draw' for me, from the SERVER's verdict (never recomputed here)
const w = S.vs ? S.vs.winner : null;
if (w === null || w === undefined) return 'draw';
return w === mySlot() ? 'win' : 'lose';
}
// A role change (round 2, or the host moved the computer) rebuilds the dock: the palette becomes the unit shop for the attacker and the
// tower palette again for the defender.
function syncRole() {
const role = roleOf();
if (role === S.role) return;
S.role = role; S.priv = S.priv && S.priv.role === role ? S.priv : null;
disarm(); S.gate = -1; S.cd = {}; S.act = {};
$('app').dataset.role = role || '';
app.last.gold = undefined;
const att = role === 'attacker';
if (att) buildShop(); else if (S.shopOn) { S.shopOn = false; api.buildPalette(); }
buildDock();
app.selTower = 0; if (role) { api.selectType(null); }
api.renderInfo(true);
api.resize();
}
// ------------------------------------------------------------------ the dock: unit shop, convoy row, abilities / tools, tech
function drawUnitIcon(cv, kind) {
const def = TD.ENEMIES[kind]; if (!def || !NW.drawMonster) return;
const dpr = Math.min(2, root.devicePixelRatio || 1), size = cv.clientWidth || 34;
cv.width = cv.height = Math.round(size * dpr);
const ctx = cv.getContext('2d');
ctx.setTransform(dpr, 0, 0, dpr, 0, 0); ctx.clearRect(0, 0, size, size);
const k = size * 0.36 / Math.max(def.r * NW.CELL * 1.3, 8);
ctx.translate(size / 2, size / 2 + (kind === 'ghost' ? 4 : 0)); ctx.scale(k, k);
NW.drawMonster(ctx, { kind, x: 0, y: 0, hp: 1, maxhp: 1, id: 1, slow: 0 }, -0.6, 0.3, 0, 0, false);
}
function drawShopIcons() { for (const b of $('palette').children) if (b.dataset.kind) drawUnitIcon(b.querySelector('canvas'), b.dataset.kind); }
function unitTip(kind) {
const d = TD.ENEMIES[kind];
return d.name + ', ' + d.buyCost + ' credits: ' + d.hp + ' hp' + (d.armor ? ', armour ' + d.armor : '') + ', speed ' + d.speed + (d.air ? ', flies' : '') + (d.heal || d.healRange ? ', heals others' : '');
}
function buildShop() {
const pal = $('palette');
pal.textContent = '';
pal.classList.toggle('many', TD.ENEMY_ORDER.length > 6);
pal.classList.add('shop');
for (const kind of TD.ENEMY_ORDER) {
const d = TD.ENEMIES[kind];
const b = document.createElement('button');
b.className = 'tbtn ubtn'; b.dataset.kind = kind; b.type = 'button';
b.innerHTML = '<span class="key"></span><canvas></canvas><span class="nm"></span><span class="cost"></span>';
b.querySelector('.nm').textContent = d.name;
b.title = unitTip(kind);
b.addEventListener('click', () => { Audio.unlock(); buy(kind); b.classList.add('hit'); setTimeout(() => b.classList.remove('hit'), 160); });
pal.appendChild(b);
}
[...pal.children].forEach((b, i) => { b.querySelector('.key').textContent = i < 9 ? String(i + 1) : ''; });
S.shopOn = true; S.last.shop = '';
drawShopIcons();
api.updatePaletteHint();
}
function buildDock() {
const bar = $('vsbar'), tech = $('vstech');
bar.textContent = ''; tech.textContent = ''; S.el = {};
const att = S.role === 'attacker', def = S.role === 'defender';
bar.hidden = !(att || def); tech.hidden = !att;
$('vsHud').hidden = !S.role;
if (att) {
const abil = VS.ABILITY_ORDER.map((id) => dockBtn('ab', id, VS.ABILITIES[id].cost)).join('');
bar.innerHTML =
'<div class="vsrow vsctlrow"><button type="button" class="vsctl" id="vsQty"></button><button type="button" class="vsctl" id="vsMode"></button>' +
'<button type="button" class="vsctl" id="vsGateBtn" hidden></button>' +
'<button type="button" class="primary vslaunch" id="vsLaunch" disabled>' + icon('i-launch') + '<span class="lt"><b>LAUNCH</b><small></small></span></button></div>' +
'<div class="vsrow vsabil" id="vsAbil">' + abil + '</div>';
tech.innerHTML = '<div class="vshead"><span>Tech</span><small>permanent, for packets sent from now on</small></div><div class="vstiles" id="vsTiles"></div>';
const tiles = tech.querySelector('#vsTiles');
for (const id of VS.TECH_ORDER) {
const b = document.createElement('button');
b.type = 'button'; b.className = 'tbtn techbtn'; b.dataset.tech = id;
b.innerHTML = icon('i-te-' + id) + '<span class="nm"></span><span class="pips"></span><span class="cost"></span>';
b.querySelector('.nm').textContent = nameOf(id);
tiles.appendChild(b);
}
S.el = { qty: bar.querySelector('#vsQty'), mode: bar.querySelector('#vsMode'), gate: bar.querySelector('#vsGateBtn'), launch: bar.querySelector('#vsLaunch'), launchSub: bar.querySelector('#vsLaunch small'), tiles };
S.el.qty.addEventListener('click', () => { S.qty = QTYS[(QTYS.indexOf(S.qty) + 1) % QTYS.length]; Audio.sfx('click'); S.last.shop = ''; });
S.el.mode.addEventListener('click', () => { S.mode = S.mode === 'now' ? 'stage' : 'now'; Audio.sfx('click'); });
S.el.gate.addEventListener('click', () => { Audio.sfx('click'); setGate(S.gate + 1 >= gates() ? -1 : S.gate + 1); });
S.el.launch.addEventListener('click', launch);
bar.querySelector('#vsAbil').addEventListener('click', (e) => { const b = e.target.closest('button[data-ab]'); if (b) { Audio.unlock(); ability(b.dataset.ab); } });
tiles.addEventListener('click', (e) => { const b = e.target.closest('button[data-tech]'); if (b) { Audio.unlock(); buyTech(b.dataset.tech); } });
S.last.dock = ''; S.last.shop = '';
} else if (def) {
bar.innerHTML = '<div class="vsrow vsabil vstools" id="vsAbil">' + VS.TOOL_ORDER.map((id) => dockBtn('tl', id, VS.TOOLS[id].cost)).join('') + '</div>';
bar.querySelector('#vsAbil').addEventListener('click', (e) => { const b = e.target.closest('button[data-tl]'); if (b) { Audio.unlock(); useTool(b.dataset.tl); } });
S.last.dock = '';
}
if (att || def) {
for (const b of bar.querySelectorAll('.vsbtn')) { const id = b.dataset.ab || b.dataset.tl; S.el[id] = { b, cd: b.querySelector('.cd'), cost: b.querySelector('.cost'), ring: -1 }; }
}
}
function dockBtn(kind, id, cost) {
const tip = kind === 'ab' ? abilityText(id) : toolText(id);
return '<button type="button" class="vsbtn" data-' + kind + '="' + id + '" title="' + esc(nameOf(id) + ': ' + tip) + '" aria-label="' + esc(nameOf(id) + ', ' + cost + ' credits. ' + tip) + '">' +
icon(kind === 'ab' ? 'i-ab-' + id : 'i-tl-' + id) + '<span class="nm">' + esc(nameOf(id)) + '</span><span class="cost">' + cost + '</span><span class="cd"></span></button>';
}
// ------------------------------------------------------------------ actions: attacker
function buy(kind) {
if (!ready()) return;
const d = TD.ENEMIES[kind], have = credits();
let n = S.qty;
if (have < d.buyCost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
if (have < d.buyCost * n) { n = Math.floor(have / d.buyCost); toast('Only ' + n + ' affordable: buying ' + n); }
const res = send(gateArg({ c: S.mode === 'stage' ? 'stage' : 'spawn', kind, n }));
if (res && res.ok) {
Audio.sfx(S.mode === 'stage' ? 'stage' : 'buy');
if (S.ctrl.kind === 'remote' && S.priv) S.priv.credits = Math.max(0, S.priv.credits - d.buyCost * n);
}
}
function launch() {
if (!ready()) return;
if (!stagedTotal()) { toast(REASONS.empty, 'bad'); return; }
const res = send(gateArg({ c: 'launch' }));
if (res && res.ok) {
Audio.sfx('launch');
if (S.ctrl.kind === 'remote' && S.priv) S.priv.staged = [];
}
}
function buyTech(id) {
if (!ready()) return;
const lv = S.priv && S.priv.tech ? S.priv.tech[id] || 0 : 0, X = VS.TECH[id];
if (!X || lv >= X.max) { toast(REASONS.max === 'Nothing to do' ? nameOf(id) + ' is at its maximum' : REASONS.max); return; }
const cost = VS.TECH_COST * Math.pow(2, lv);
if (credits() < cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
const res = send({ c: 'tech', id });
if (res && res.ok) {
Audio.sfx('tech');
if (S.ctrl.kind === 'remote' && S.priv) { S.priv.credits = Math.max(0, S.priv.credits - cost); S.priv.tech = Object.assign({}, S.priv.tech, { [id]: lv + 1 }); }
}
}
function ability(id) {
if (!ready()) return;
const A = VS.ABILITIES[id]; if (!A) return;
if (id === 'emp') {
if (S.empArm) { disarm(); return; }
const t = app.selTower ? S.ctrl.view.towers.find((x) => x.id === app.selTower) : null;
if (t && t.type !== 'wall') { castEmp(t.id); return; }
disarm(); S.empArm = true; say('Tap a tower to EMP it (' + A.dur + ' s)'); Audio.sfx('click');
return;
}
if (cdLeft(id) > 0.05) { toast(nameOf(id) + ' is cooling down', 'bad'); return; }
if (credits() < A.cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
if (A.cost >= 150 && !confirmTap(id, 'Tap ' + nameOf(id) + ' again to fire it (' + A.cost + ')')) { flashConfirm(id); return; }
cast({ c: 'ability', id }, id, A.cost, A.cd, id === 'decoy');
}
function castEmp(tid) {
const A = VS.ABILITIES.emp;
disarm();
if (cdLeft('emp') > 0.05) { toast('EMP is cooling down', 'bad'); return; }
if (credits() < A.cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
cast({ c: 'ability', id: 'emp', tid }, 'emp', A.cost, A.cd, false);
app.selTower = 0; api.renderInfo(true);
}
function cast(cmd, id, cost, cd, useGate) {
const res = send(useGate ? gateArg(cmd) : cmd);
if (res && res.ok && S.ctrl.kind === 'remote' && S.priv) { S.priv.credits = Math.max(0, S.priv.credits - cost); S.cd[id] = { left: cd, at: now() }; }
}
function flashConfirm(id) {
const e = S.el[id]; if (!e) return;
e.b.classList.add('confirm'); setTimeout(() => e.b.classList.remove('confirm'), 2500);
}
function setGate(i) {
S.gate = i;
toast(i < 0 ? 'Gateways: automatic' : 'Gateway ' + (i + 1) + ' chosen', 'good');
}
// ------------------------------------------------------------------ actions: defender
function useTool(id) {
if (!ready()) return;
const T = VS.TOOLS[id]; if (!T) return;
const view = S.ctrl.view;
if (id === 'scan' && S.scanArm) { disarm(); return; }
if (cdLeft(id) > 0.05) { toast(nameOf(id) + ' is cooling down', 'bad'); return; }
if (view.gold < T.cost) { toast(REASONS.credits, 'bad'); Audio.sfx('error'); return; }
if (id === 'scan') { disarm(); api.selectType(null); S.scanArm = true; say('Tap the map to scan (radius ' + T.radius + ')'); Audio.sfx('click'); return; }
let cmd = { c: 'tool', id };
if (id === 'patch') {
const sel = app.selTower ? view.towers.find((t) => t.id === app.selTower && t.empT > 0) : null;
let t = sel;
if (!t) for (const x of view.towers) if (x.empT > 0 && (!t || x.empT > t.empT)) t = x;
if (!t) { toast('No tower is disabled', 'bad'); return; }
cmd.tid = t.id;
} else if (id === 'repair') {
if (view.lives >= view.maxLives) { toast('Integrity is already full', 'bad'); return; }
} else if (T.cost >= 150 && !confirmTap(id, 'Tap ' + nameOf(id) + ' again to use it (' + T.cost + ')')) { flashConfirm(id); return; }
const res = send(cmd);
if (res && res.ok) {
Audio.sfx(id === 'patch' ? 'patch' : 'click');
if (S.ctrl.kind === 'remote') S.cd[id] = { left: T.cd, at: now() };
}
}
function scanAt(cell) {
disarm();
const T = VS.TOOLS.scan;
if (cdLeft('scan') > 0.05) { toast('Scan is cooling down', 'bad'); return; }
if (S.ctrl.view.gold < T.cost) { toast(REASONS.credits, 'bad'); return; }
const res = send({ c: 'tool', id: 'scan', x: cell.x + 0.5, y: cell.y + 0.5 });
if (res && res.ok && S.ctrl.kind === 'remote') S.cd.scan = { left: T.cd, at: now() };
}
function ready() {
if (!S.active || !S.role) return false;
if (S.vs && S.vs.frozen) { toast(REASONS.frozen, 'bad'); return false; }
if (!phasePlaying()) { toast(REASONS.phase, 'bad'); return false; }
return true;
}
// ------------------------------------------------------------------ board taps and keys (called by main)
function tapCell(cell) {
if (!S.active || !S.role || !S.ctrl.board || !S.ctrl.board.inBounds(cell.x, cell.y)) return false;
const view = S.ctrl.view;
if (S.role === 'defender') {
if (S.scanArm && ready()) { scanAt(cell); return true; }
return false;
}
const tw = view.towers.find((x) => x.x === cell.x && x.y === cell.y);
if (S.empArm) {
if (tw && tw.type !== 'wall') { if (ready()) castEmp(tw.id); return true; }
if (tw) { toast("A Firewall can't be disabled", 'bad'); return true; }
disarm(); return true;
}
if (tw) return false; // an ordinary tap on a tower selects it (its panel offers EMP)
const sp = S.ctrl.board.spawns;
if (sp.length > 1) {
let best = -1, bd = 3;
for (let i = 0; i < sp.length; i++) { const d = Math.max(Math.abs(sp[i].x - cell.x), Math.abs(sp[i].y - cell.y)); if (d <= 1 && d < bd) { bd = d; best = i; } }
if (best >= 0) { Audio.sfx('click'); setGate(S.gate === best ? -1 : best); return true; }
}
return false;
}
// Keys: attacker digits buy units, Space launches; the wave / pause / speed keys do nothing in versus. Returns true when handled.
function key(k, e) {
if (!S.active) return false;
if (k === 'p' || k === 'f' || k === 'a') return true;
if (k === 'escape' || k === 'q') { disarm(); return false; }
if (S.role === 'attacker') {
if (k === ' ' || k === 'enter') { launch(); e.preventDefault(); return true; }
const i = k.length === 1 && k >= '1' && k <= '9' ? +k - 1 : k === '0' ? 9 : -1;
if (i >= 0 && TD.ENEMY_ORDER[i]) { buy(TD.ENEMY_ORDER[i]); e.preventDefault(); return true; }
return false;
}
if (k === ' ' || k === 'enter') return true;
return false;
}
const holdsOverlay = () => S.active && (S.phase === 'lobby' || S.phase === 'roundover' || S.phase === 'matchover');
function refreshOverlay() {
if (!S.active) return;
if (S.phase === 'lobby') { renderRoom(); showOverlay('vsRoom'); }
else if (S.phase === 'roundover' || S.phase === 'matchover') { renderEnd(); showOverlay('vsEnd'); }
}
// The stacked layout needs more room under the board in versus: the attacker's dock is shop + convoy + abilities + tech.
function minSide(H) {
if (!S.active || !S.role) return 0;
return S.role === 'attacker' ? clamp(Math.round(H * 0.4), 295, 340) : clamp(Math.round(H * 0.3), 190, 250);
}
function uiState() {
if (!S.active) return null;
UIS.role = S.role; UIS.tech = S.role === 'attacker' && S.priv ? S.priv.tech || null : null;
UIS.gate = S.gate; UIS.gates = gates(); UIS.scanArm = S.scanArm; UIS.empArm = S.empArm;
return UIS;
}
// ------------------------------------------------------------------ events (sounds and cues for the new actions)
function onEvent(e) {
if (!S.active) return;
const t = now();
switch (e.e) {
case 'emp': Audio.sfx('emp'); if (S.role === 'defender') toast('EMP: a tower went offline. Patch or Scan it', 'bad'); break;
case 'decoy': Audio.sfx('decoy'); if (e.id !== undefined) S.decoys.set(e.id, t + (e.d || 5) * 1000); break;
case 'surge': S.fx.surge = t + (e.d || 6) * 1000; Audio.sfx('surge'); banner('SURGE', true); break;
case 'ddos': S.fx.ddos = t + (e.d || 4) * 1000; Audio.sfx('ddos'); banner('DDoS', true); break;
case 'quarantine': S.fx.freeze = t + (e.d || 2) * 1000; Audio.sfx('quarantine'); banner('QUARANTINE'); break;
case 'scan': Audio.sfx('scan'); break;
case 'repair': Audio.sfx('repair'); break;
default: break;
}
}
const leakSfx = () => (S.active && S.role === 'attacker' ? 'breach' : 'leak');
const isDecoy = (m) => !!m.decoy || (S.decoys.size > 0 && S.decoys.has(m.id));
// ------------------------------------------------------------------ per frame: top bar, dock, cooldown rings
function setText(el, v) { if (el && el.textContent !== v) el.textContent = v; }
function setCls(el, c, on) { if (el && el.classList.contains(c) !== on) el.classList.toggle(c, on); }
function tick(t, view) {
if (!S.active) return;
const att = S.role === 'attacker', L = S.last, vsb = view.vs;
// clock
const left = vsb ? Math.max(0, vsb.lim - vsb.t) : S.vs ? S.vs.limit : 0;
const tt = mmss(left);
if (L.time !== tt) { L.time = tt; $('vTime').textContent = tt; }
const low = left <= 30 && phasePlaying();
if (L.low !== low) { L.low = low; $('statTime').classList.toggle('low', low); }
// the attacker's credits and income replace the defender's gold in the top bar
if (att) {
const c = credits(), inc = S.priv && S.priv.role === 'attacker' ? S.priv.income : 0;
if (L.cr !== c) { L.cr = c; $('vGold').textContent = String(c); }
const it = inc ? '+' + (Math.round(inc * 10) / 10) + '/s' : '';
if (L.inc !== it) { L.inc = it; $('vIncome').textContent = it; }
$('statGold').title = 'Your credits (income ' + it + ')';
} else if (L.inc !== '') { L.inc = ''; $('vIncome').textContent = ''; $('statGold').title = 'Credits'; }
// shop / tech / convoy
if (att) tickAttacker(view);
tickDock(view);
tickHud(view);
tickFx(t);
}
function tickAttacker(view) {
const L = S.last, c = credits(), E = S.el;
const shopKey = c + '|' + S.qty + '|' + S.mode;
if (E.qty && L.shop !== shopKey) {
L.shop = shopKey;
setText(E.qty, '×' + S.qty); E.qty.setAttribute('aria-label', 'Quantity ' + S.qty + ' per tap. Tap to change');
setText(E.mode, S.mode === 'stage' ? 'Stage' : 'Send');
E.mode.setAttribute('aria-label', S.mode === 'stage' ? 'Stage: pay now and hold the units in the convoy. Tap to switch to Send now' : 'Send now: units enter at once. Tap to switch to Stage');
E.mode.classList.toggle('on', S.mode === 'stage');
for (const b of $('palette').children) {
const d = TD.ENEMIES[b.dataset.kind]; if (!d) continue;
const price = d.buyCost * S.qty, poor = c < d.buyCost;
setText(b.querySelector('.cost'), String(price));
setCls(b, 'poor', poor);
b.setAttribute('aria-label', d.name + ', ' + price + ' credits' + (S.qty > 1 ? ' for ' + S.qty : '') + (poor ? ', not enough credits' : ''));
}
}
// convoy + Launch
const n = stagedTotal();
const comp = S.priv && S.priv.staged ? S.priv.staged.map((e) => e[1] + ' ' + (TD.ENEMIES[e[0]] ? TD.ENEMIES[e[0]].name : e[0])).join(', ') : '';
const lk = n + '|' + comp;
if (L.launch !== lk && E.launch) {
L.launch = lk;
E.launch.disabled = n === 0;
E.launch.querySelector('b').textContent = n ? 'LAUNCH ' + n : 'LAUNCH';
setText(E.launchSub, n ? comp : 'convoy empty');
E.launch.setAttribute('aria-label', n ? 'Launch the convoy: ' + comp : 'Launch (the convoy is empty: use Stage to hold units)');
}
const ng = gates();
if (E.gate) {
E.gate.hidden = ng < 2;
const gt = S.gate < 0 ? 'Gate: auto' : 'Gate ' + (S.gate + 1);
if (L.gate !== gt) { L.gate = gt; E.gate.textContent = S.gate < 0 ? 'Any gate' : 'Gate ' + (S.gate + 1); E.gate.setAttribute('aria-label', gt + '. Tap to change (or tap a gateway on the map)'); E.gate.classList.toggle('on', S.gate >= 0); }
}
// tech tiles
const tech = S.priv && S.priv.tech ? S.priv.tech : {};
for (const b of E.tiles ? E.tiles.children : []) {
const id = b.dataset.tech, X = VS.TECH[id], lv = tech[id] || 0, max = lv >= X.max;
const cost = max ? 0 : VS.TECH_COST * Math.pow(2, lv);
const key = lv + '|' + (max ? 'm' : c >= cost ? 'y' : 'n');
if (b.dataset.k === key) continue;
b.dataset.k = key;
b.querySelector('.pips').textContent = '●'.repeat(lv) + '○'.repeat(X.max - lv);
setText(b.querySelector('.cost'), max ? 'MAX' : String(cost));
setCls(b, 'poor', !max && c < cost); setCls(b, 'maxed', max);
const nxt = max ? 'maxed out' : 'next: ' + techText(id, lv + 1);
b.title = nameOf(id) + ' ' + lv + '/' + X.max + ', ' + nxt;
b.setAttribute('aria-label', nameOf(id) + ', level ' + lv + ' of ' + X.max + ', ' + nxt + (max ? '' : ', ' + cost + ' credits') + (!max && c < cost ? ', not enough credits' : ''));
}
}
function tickDock(view) {
const att = S.role === 'attacker', c = att ? credits() : view.gold, table = att ? VS.ABILITIES : VS.TOOLS;
for (const id in table) {
const e = S.el[id]; if (!e) continue;
const T = table[id], left = cdLeft(id), frac = T.cd ? clamp(left / T.cd, 0, 1) : 0;
const q = Math.round(frac * 50);
if (e.ring !== q) { e.ring = q; e.b.style.setProperty('--p', String(q / 50)); }
const act = att ? actLeft(id) : 0;
const txt = act > 0 ? Math.ceil(act) + 's' : left > 0.05 ? Math.ceil(left) + 's' : '';
setText(e.cd, txt);
setCls(e.b, 'cooling', left > 0.05);
setCls(e.b, 'poor', left <= 0.05 && c < T.cost);
setCls(e.b, 'live', act > 0);
setCls(e.b, 'armed', (id === 'emp' && S.empArm) || (id === 'scan' && S.scanArm));
if (id === 'patch') { let any = false; for (const t of view.towers) if (t.empT > 0) { any = true; break; } setCls(e.b, 'idle', !any); }
if (id === 'repair') setCls(e.b, 'idle', view.lives >= view.maxLives);
if (id === 'emp') { // a selected tower makes EMP a one-tap action
const sel = app.selTower ? view.towers.find((t) => t.id === app.selTower) : null;
setCls(e.b, 'ready', !!sel && sel.type !== 'wall');
}
}
// the EMP button in the selected tower's action bar (attacker)
const eb = $('info').querySelector('[data-act="emp"]');
if (eb) {
const left = cdLeft('emp'), A = VS.ABILITIES.emp;
setCls(eb, 'poor', c < A.cost || left > 0.05);
const cost = eb.querySelector('.cost'); setText(cost, left > 0.05 ? Math.ceil(left) + 's' : String(A.cost));
}
}
function tickHud(view) {
const L = S.last, hud = $('vsHud');
let txt;
const alive = view.monsters.length;
if (S.role === 'attacker') txt = (S.priv && S.priv.income ? '+' + (Math.round(S.priv.income * 10) / 10) + '/s · ' : '') + alive + ' alive · def ' + view.gold + 'cr';
else txt = alive + ' alive' + (view.vs && view.vs.st ? ' · ' + view.vs.st + ' staged' : '');
if (L.hud !== txt) { L.hud = txt; hud.textContent = txt; }
}
function tickFx(t) {
const box = $('vsFx'), L = S.last;
if (S.decoys.size > 12) for (const [id, until] of S.decoys) if (until < t) S.decoys.delete(id);
const parts = [];
for (const id of ['surge', 'ddos', 'freeze']) {
const left = fxLeft(id);
if (left > 0) parts.push([id, Math.ceil(left)]);
}
const key = parts.map((p) => p.join(':')).join(',');
if (L.fx === key) return;
L.fx = key;
const label = { surge: 'SURGE: packets faster', ddos: 'DDoS: towers slowed', freeze: 'QUARANTINE: packets frozen' };
box.innerHTML = parts.map((p) => '<span class="fxchip ' + p[0] + '">' + label[p[0]] + ' ' + p[1] + 's</span>').join('');
}
// ------------------------------------------------------------------ countdown / paused card on the stage
function renderCount() {
const box = $('vsCount'), m = S.vs;
if (!m || !S.role || m.phase === 'lobby' || m.phase === 'roundover' || m.phase === 'matchover' || (m.phase === 'playing' && !m.frozen)) { box.hidden = true; return; }
const att = S.role === 'attacker';
let html;
if (m.frozen) {
html = '<div class="vsc-big">PAUSED</div><div class="vsc-sub">The other player lost the connection. The round waits for them (up to a minute), then you win.</div>';
} else {
const n = m.countdown !== undefined ? m.countdown : 0;
html = '<div class="vsc-top">ROUND ' + m.round + ' OF ' + m.rounds + '</div>' +
'<div class="vsc-role ' + (att ? 'att' : 'def') + '">YOU ' + (att ? 'ATTACK' : 'DEFEND') + '</div>' +
'<div class="vsc-sub">' + (att ? 'Spend credits on packets and break the server before the clock runs out.' : 'Build walls and turrets, keep the server alive until the clock runs out.') + '</div>' +
'<div class="vsc-num" aria-hidden="true">' + n + '</div>';
if (S.last.cd !== n) { S.last.cd = n; if (n > 0) Audio.sfx('tick'); }
}
if (S.last.countHtml !== html) { S.last.countHtml = html; box.innerHTML = html; }
box.hidden = false;
}
// ------------------------------------------------------------------ dialogs: setup, room, result
function initDialogs() {
buildSeg($('vsRolePick'), [{ id: 'attacker', label: 'Attack' }, { id: 'defender', label: 'Defend' }, { id: 'random', label: 'Random' }], (v) => { Audio.sfx('click'); S.setup.role = v; store.set('nw.vs.role', v); segSet($('vsRolePick'), v); });
buildSeg($('vsLimitPick'), VS.LIMITS.map((s) => ({ id: s, label: Math.round(s / 60) + ' min' })), (v) => { Audio.sfx('click'); S.setup.limit = +v; store.set('nw.vs.limit', +v); segSet($('vsLimitPick'), v); });
buildSeg($('vsSkillPick'), SKILLS.map((k) => ({ id: k.id, label: k.name })), (v) => { Audio.sfx('click'); S.setup.skill = v; store.set('nw.vs.skill', v); segSet($('vsSkillPick'), v); });
segSet($('vsRolePick'), S.setup.role); segSet($('vsLimitPick'), S.setup.limit); segSet($('vsSkillPick'), S.setup.skill);
$('vsCode').addEventListener('input', (e) => { e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4); });
$('vsCode').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('btnVsJoin').click(); });
$('btnVsBack').addEventListener('click', () => { msg(''); api.cancelPending(); if (app.inGame) api.closeOverlayToGame(); else api.openMenu(); });
$('btnVsComputer').addEventListener('click', () => { Audio.unlock(); msg(''); api.startLocal({ role: S.setup.role, limit: S.setup.limit, skill: skillValue() }); });
$('btnVsCreate').addEventListener('click', () => { Audio.unlock(); api.connect({ room: null, map: app.mapId, mode: 'versus', limit: S.setup.limit, name: $('vsName').value, say: msg }); });
$('btnVsJoin').addEventListener('click', () => {
const code = $('vsCode').value.trim().toUpperCase();
if (!/^[A-Z0-9]{4}$/.test(code)) { msg('Enter the 4 character room code.', true); return; }
api.connect({ room: code, name: $('vsName').value, say: msg });
});
// room
buildSeg($('vsRoomRole'), [{ id: 'attacker', label: 'Attack' }, { id: 'defender', label: 'Defend' }, { id: 'random', label: 'Random' }], (v) => { Audio.sfx('click'); if (S.ctrl) S.ctrl.vsRole(v); });
buildSeg($('vsRoomOpp'), [{ id: 'friend', label: 'A friend' }, { id: 'computer', label: 'Computer' }], (v) => {
Audio.sfx('click');
if (!S.ctrl) return;
if (v === 'computer') { const mine = roleOf() || 'attacker'; S.ctrl.vsBot(other(mine), skillValue()); } else S.ctrl.vsBot(null);
});
$('btnVsReady').addEventListener('click', () => { Audio.sfx('click'); const me = mySlot(); S.ctrl.vsReady(!(S.vs && S.vs.ready && S.vs.ready[me])); });
$('btnVsStart').addEventListener('click', () => { Audio.sfx('click'); S.ctrl.vsStart(); });
$('btnVsInvite').addEventListener('click', () => api.invite());
$('btnVsLeave').addEventListener('click', () => api.exitToMenu());
// result
$('btnVsNext').addEventListener('click', () => { Audio.sfx('click'); S.sentNext = true; S.ctrl.vsNext(); renderEnd(); });
$('btnVsRematch').addEventListener('click', () => { Audio.sfx('click'); S.sentRematch = true; S.ctrl.vsRematch(); renderEnd(); });
$('btnVsEndMenu').addEventListener('click', () => api.exitToMenu());
}
function msg(text, bad) { const m = $('vsMsg'); m.textContent = text || ''; m.className = 'msg' + (bad ? ' bad' : ''); }
function openSetup(code) {
$('vsName').value = store.get('nw.name', '') || '';
$('vsMapName').textContent = 'Map: ' + TD.MAPS[app.mapId].name + ' (pick another in the menu)';
segSet($('vsRolePick'), S.setup.role); segSet($('vsLimitPick'), S.setup.limit); segSet($('vsSkillPick'), S.setup.skill);
msg(root.location.protocol === 'file:' ? 'Online play needs the Netwall server (npm start). Against the computer works from the file.' : '');
showOverlay('vsSetup'); api.setScreen(app.inGame ? 'playing' : 'menu');
if (code) { $('vsCode').value = code; $('btnVsJoin').focus({ preventScroll: true }); }
}
// ---- the online room (lobby phase)
function renderRoom() {
const c = S.ctrl, m = S.vs;
if (!c || !m || m.phase !== 'lobby') return;
const me = mySlot(), isHost = !!(c.you && c.you.host), opp = 1 - me;
const oppP = players().find((p) => p.slot === opp), botOpp = !!(m.bot && m.bot.slot === opp);
$('vsRoomCode').textContent = 'Room ' + (c.room || '');
$('vsRoomLimit').textContent = 'Round: ' + mmss(m.limit) + ' · 2 rounds, roles swap';
let seats = '';
for (const slot of [0, 1]) {
const p = players().find((q) => q.slot === slot), isBot = !!(m.bot && m.bot.slot === slot), role = roleCls(m.roles[slot]);
const nm = isBot ? (m.bot.name || 'Computer') : p ? p.name : null;
const rdy = isBot || (p && p.host) || (m.ready && m.ready[slot]);
seats += '<div class="vsseat' + (nm ? '' : ' empty') + '"><span class="dot" style="background:' + api.slotColor(slot) + '"></span>' +
'<span class="sn">' + (nm ? esc(nm) : 'Waiting for an opponent&hellip;') + '</span>' +
(p && c.you && p.pid === c.you.pid ? '<span class="you">(you)</span>' : '') + (p && p.host ? '<span class="you">host</span>' : '') + (p && !p.online ? '<span class="off">offline</span>' : '') +
(nm ? '<span class="rolebadge ' + role + '">' + (role === 'attacker' ? 'ATTACK' : 'DEFEND') + '</span><span class="rdy' + (rdy ? ' ok' : '') + '">' + (rdy ? '&#10003; ready' : 'not ready') + '</span>' : '') + '</div>';
}
$('vsSeats').innerHTML = seats;
segSet($('vsRoomRole'), m.random ? 'random' : roleOf());
$('vsOppField').hidden = !isHost;
segSet($('vsRoomOpp'), m.bot ? 'computer' : 'friend');
$('vsRoomNote').textContent = m.random ? 'Roles are drawn at random: you ' + (roleOf() === 'attacker' ? 'attack' : 'defend') + ' first, then it swaps.' : 'You ' + (roleOf() === 'attacker' ? 'attack' : 'defend') + ' first, then it swaps.';
let why = '';
if (!oppP && !botOpp) why = 'Waiting for an opponent to join. Share the invite, or play the computer.';
else if (oppP && !oppP.online) why = oppP.name + ' is offline.';
else if (oppP && !(m.ready && m.ready[opp])) why = 'Waiting for ' + oppP.name + ' to get ready.';
const imReady = !!(m.ready && m.ready[me]);
$('btnVsStart').hidden = !isHost;
$('btnVsStart').disabled = !!why;
$('btnVsReady').hidden = isHost;
$('btnVsReady').textContent = imReady ? 'Ready (tap to undo)' : "I'm ready";
$('btnVsReady').setAttribute('aria-pressed', imReady ? 'true' : 'false');
$('btnVsReady').classList.toggle('on', imReady);
const mm = $('vsRoomMsg');
mm.textContent = isHost ? why : imReady ? 'Waiting for the host to start.' : 'Press ready when you are.';
mm.className = 'msg';
}
// ---- round over / match over
function entryText(h) {
const r = h.result;
if (r.forfeit) return 'Forfeited';
return r.winner === 'attacker' ? 'Server fell at ' + mmss(r.t) : 'Server held for ' + mmss(r.t);
}
function renderEnd() {
const m = S.vs; if (!m || (m.phase !== 'roundover' && m.phase !== 'matchover')) return;
const me = mySlot(), over = m.phase === 'matchover', c = S.ctrl;
const hist = (m.history || []).slice();
if (m.result && !hist.some((h) => h.round === m.round)) hist.push({ round: m.round, roles: m.roles, result: m.result });
let title, text, color;
if (over) {
const res = matchResult();
title = res === 'win' ? 'You win the match!' : res === 'lose' ? 'You lose the match' : 'A draw';
color = res === 'win' ? 'var(--green)' : res === 'lose' ? 'var(--red)' : 'var(--amber)';
if (m.forfeit !== null && m.forfeit !== undefined) text = m.forfeit === me ? 'You left the match.' : playerName(m.forfeit) + ' left the match. You win by forfeit.';
else text = reasonText(m);
} else {
const won = roundWon(), r = m.result || {};
title = 'Round ' + m.round + ': ' + (won ? 'you won' : 'you lost');
color = won ? 'var(--green)' : 'var(--red)';
text = (r.winner === 'attacker' ? 'The server fell after ' + mmss(r.t) + '.' : 'The server held for the whole ' + mmss(r.t) + '.') + ' Integrity lost: ' + (r.integrityLost || 0) + '. ' +
'Next round you ' + (other(roleOf()) === 'attacker' ? 'attack' : 'defend') + '.';
}
$('vsEndTitle').textContent = title; $('vsEndTitle').style.color = color;
$('vsEndText').textContent = text;
// both rounds side by side
const cols = hist.map((h) => {
const mine = roleCls(h.roles[me]), won = h.result.winner === mine;
return '<div class="vsround"><h4>Round ' + h.round + '</h4>' +
'<div class="vsrow2"><span>You were</span><b class="rolebadge ' + mine + '">' + (mine === 'attacker' ? 'ATTACKER' : 'DEFENDER') + '</b></div>' +
'<div class="vsrow2"><span>Result</span><b>' + esc(entryText(h)) + '</b></div>' +
'<div class="vsrow2"><span>Integrity lost</span><b>' + esc(h.result.integrityLost || 0) + '</b></div>' +
'<div class="vsrow2"><span>Round won by</span><b class="' + (won ? 'good' : 'bad') + '">' + (won ? 'you' : esc(playerName(1 - me))) + '</b></div></div>';
});
if (!over) cols.push('<div class="vsround pending"><h4>Round ' + (m.round + 1) + '</h4><div class="vsrow2"><span>You will</span><b class="rolebadge ' + other(roleOf()) + '">' + (other(roleOf()) === 'attacker' ? 'ATTACK' : 'DEFEND') + '</b></div></div>');
let score = '';
if (over && m.scores && !(m.forfeit !== null && m.forfeit !== undefined)) {
score = '<div class="vsscore"><h4>Who attacked best</h4>' + m.scores.map((s) =>
'<div class="vsrow2"><span>' + esc(s.slot === me ? 'You' : playerName(s.slot)) + '</span><b>' + (s.fellAt !== null && s.fellAt !== undefined ? 'felled the server at ' + mmss(s.fellAt) : 'did not fell it, took off ' + (s.integrityLost || 0)) + '</b></div>').join('') + '</div>';
}
$('vsEndRounds').innerHTML = '<div class="vscols">' + cols.join('') + '</div>' + score;
// buttons and waiting text
const oppHere = c.kind === 'local' || !!(m.bot) || players().some((p) => p.slot !== me && p.online);
$('btnVsNext').hidden = over; $('btnVsRematch').hidden = !over;
$('btnVsNext').disabled = S.sentNext;
$('btnVsRematch').disabled = S.sentRematch || !oppHere;
$('btnVsRematch').textContent = 'Rematch (roles swap)';
const w = $('vsEndWait'); let wt = '';
if (!over && S.sentNext) wt = 'Waiting for the other player' + (m.nextIn ? ' (the next round starts anyway in ' + m.nextIn + ' s)' : '') + '…';
else if (!over && m.next && m.next[1 - me] && c.kind === 'remote' && !m.bot) wt = playerName(1 - me) + ' is ready for the next round.';
else if (over && S.sentRematch) wt = 'Waiting for the other player to accept the rematch…';
else if (over && m.rematch && m.rematch[1 - me] && !S.sentRematch && !m.bot) wt = playerName(1 - me) + ' wants a rematch.';
else if (over && !oppHere) wt = 'The other player has left.';
w.hidden = !wt; w.textContent = wt;
}
function reasonText(m) {
const sc = m.scores; if (!sc) return '';
const a = sc[0], b = sc[1], nm = (s) => (s.slot === mySlot() ? 'you' : playerName(s.slot));
if (a.fellAt !== null && b.fellAt !== null) return a.fellAt === b.fellAt ? 'Both servers fell at the same second.' : 'The faster fall wins: ' + nm(a) + ' ' + mmss(a.fellAt) + ', ' + nm(b) + ' ' + mmss(b.fellAt) + '.';
if (a.fellAt !== null || b.fellAt !== null) { const w = a.fellAt !== null ? a : b; return 'Only ' + nm(w) + ' felled the server (' + mmss(w.fellAt) + ').'; }
if (a.integrityLost === b.integrityLost) return 'Neither server fell, and the same integrity was taken off.';
return 'Neither server fell: the attacker who took off more integrity wins (' + nm(a) + ' ' + (a.integrityLost || 0) + ', ' + nm(b) + ' ' + (b.integrityLost || 0) + ').';
}
// the room code box of the setup dialog is filled by an invite link (?room=ABCD)
function onRoomWait(code) { openSetup(code); }
initDialogs();
return {
get active() { return S.active; }, get role() { return S.role; }, get shopOn() { return S.shopOn; }, get phase() { return S.phase; }, state: S,
attach, tick, tapCell, key, onEvent, leakSfx, isDecoy, minSide, uiState, holdsOverlay, refreshOverlay, openSetup, onRoomWait, renderRoom, renderEnd,
drawShopIcons, castEmp, disarm, msg, say, decoys: S.decoys, REASONS, matchResult,
};
}
NW.Versus = { create, techText, abilityText, toolText };
})(typeof self !== 'undefined' ? self : this);

View file

@ -1,6 +1,6 @@
/* Netwall service worker: network-first so updates always win, cache as an offline fallback (solo play offline). */
const CACHE = 'netwall-v1';
const CORE = ['./', 'index.html', 'css/style.css', 'js/sim.js', 'js/audio.js', 'js/controllers.js', 'js/render.js', 'js/main.js',
const CORE = ['./', 'index.html', 'css/style.css', 'js/sim.js', 'js/bot.js', 'js/audio.js', 'js/controllers.js', 'js/render.js', 'js/versus.js', 'js/main.js',
'manifest.webmanifest', 'icons/icon.svg', 'icons/icon-192.png', 'assets/music/tracks.json'];
self.addEventListener('install', (e) => {