Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

### Added

- Bots with character (#64): every bot is a named rider of a made-up cast ("Gus Tailwind", "Penny Farthing") (and, rarely, Goldie Lemon in lemon yellow) with a riding type (rouleur, climber, sprinter, attacker, tourer) and a team kit, the same everywhere. Bots now race you: they take turns on the front of a group and swing off, attack near the top of a climb, take up the chase when you come past and sprint for the line, as long as their energy (W′) lasts. They ride in groups that spawn out of sight around every rider (mostly a group ahead to chase, sometimes one coming up from behind),; the number of riders per route is still `OPENRADLR_TARGET_RIDERS`. The 3D view shows bots in their team's kit, the rider list names their type, and the ticker calls out moves near you.
- Golden lemons: a few lemons float over the road, each in one lane, and move to new places every day (the same for every rider). Ride through one in its lane to collect it; they grow back every lap. A pickup shows in the ticker with your all-time count, and the finish screen lists the ride's lemons. No counter on the HUD: it's an easter egg.
- Ghost lap: your best lap on a loop route is kept in the browser, and a see-through rider labelled "Best lap" rides it again from the line, lane changes and all. The HUD shows the live gap ("Best lap +4.2 s", red behind, green ahead), and a faster lap becomes the new ghost at once. Hidden in races and events.
- Crowds along the route: spectators line the last 600 m of every climb in loose groups, thicker towards the top, and every sprint line gets a crowd behind barriers. They turn towards a rider coming by and cheer harder (penguins clap faster), and some wave flags. The more riders are online, the more of them come out; bots don't count.
Expand Down
9 changes: 9 additions & 0 deletions client/public/js/i18n/de.js
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,15 @@ export default {
"panels.remote.other": "{n} aus anderen Apps",
"panels.botSuffix": "(Bot)",
"panels.bot": "Bot",
"panels.botStyle.rouleur": "Rouleur-Bot",
"panels.botStyle.climber": "Kletterer-Bot",
"panels.botStyle.sprinter": "Sprinter-Bot",
"panels.botStyle.attacker": "Angreifer-Bot",
"panels.botStyle.tourer": "Tourenfahrer-Bot",
"bots.attack": "{name} greift an!",
"bots.sprint": "{name} geht in den Sprint!",
"bots.answer": "{name} nimmt die Verfolgung auf!",
"bots.pull": "{name} geht nach vorn und übernimmt die Führung.",
"panels.joined": "{who} ist beigetreten",
"panels.race.countdown": "Rennen über {laps} startet in {s} s",
"panels.race.started": "Rennen gestartet — los!",
Expand Down
9 changes: 9 additions & 0 deletions client/public/js/i18n/en.js
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,15 @@ export default {
"panels.remote.other": "{n} from other apps",
"panels.botSuffix": "(bot)",
"panels.bot": "bot",
"panels.botStyle.rouleur": "rouleur bot",
"panels.botStyle.climber": "climber bot",
"panels.botStyle.sprinter": "sprinter bot",
"panels.botStyle.attacker": "attacker bot",
"panels.botStyle.tourer": "tourer bot",
"bots.attack": "{name} attacks!",
"bots.sprint": "{name} goes for the sprint!",
"bots.answer": "{name} takes up the chase!",
"bots.pull": "{name} comes through for a turn on the front.",
"panels.joined": "{who} joined",
"panels.race.countdown": "Race over {laps} starts in {s} s",
"panels.race.started": "Race started — go!",
Expand Down
12 changes: 12 additions & 0 deletions client/public/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { JUNCTION_WINDOW_M, OFF_ROUTE_ID, junctionAhead, offRouteRoad, stepOptio
import { RideAutosave, continueAllowed, indexedDbStore, unfinishedLabel } from "./ride/rideAutosave.js";
import { backToMenuWarning, createFinishController } from "./ride/finishController.js";
import { LemonHunt, lemonDay, lemonsFor } from "./ride/lemons.js";
import { BotCalls } from "./ride/botCalls.js";
import { GhostStore, LapRun, formatLapGap, ghostAt, timeAt } from "./ride/ghostLap.js";
import { MilestoneWatch, lifetimeTotals } from "./ride/milestones.js";
import { RideHistory, rideRecord } from "./ride/rideHistory.js";
Expand Down Expand Up @@ -331,6 +332,8 @@ const app = {
splits: [],
shownSplits: 0,
splitToastTimer: null,
/** Bots' moves near me, called out in the ticker (#64). */
botCalls: new BotCalls(),
/** Golden lemons on my route (null off the routes, in the studio and workouts), and how many this ride collected. */
lemonHunt: null,
lemonsThisRide: 0,
Expand Down Expand Up @@ -1440,6 +1443,13 @@ function runAction(action) {
}

/** A message for the rider: kept in the feed drawer and shown briefly on the HUD. */
const BOT_CALL_TEXT = Object.freeze({ attack: "bots.attack", sprint: "bots.sprint", answer: "bots.answer", pull: "bots.pull" });

/** A line in the ticker when a bot near me starts a move (#64). */
function callBotMoves(riders, me) {
for (const call of app.botCalls.update({ riders, me, route: app.route, nowS: now() })) notify(t(BOT_CALL_TEXT[call.move], { name: call.name }));
}

function notify(text, kind = "event") {
appendFeed($("feed"), text, kind);
if (!$("hud-ticker")) return;
Expand Down Expand Up @@ -1787,6 +1797,7 @@ function endRide() {
splits: [],
shownSplits: 0,
splitToastTimer: (clearTimeout(app.splitToastTimer), ($("split-toast").hidden = true), null),
botCalls: new BotCalls(),
lemonHunt: null,
lemonsThisRide: 0,
lemonTotal: 0,
Expand Down Expand Up @@ -1873,6 +1884,7 @@ function wireConnection(connection) {
app.state = { ...message, riders: riders.filter(onMyRoute), elsewhere };
// The workout screen has none of the ride panels.
if (!app.workout) updatePanels();
if (!app.workout && app.route) callBotMoves(riders, me);
});
on("studio_state", (message) => {
app.state = message;
Expand Down
49 changes: 49 additions & 0 deletions client/public/js/ride/botCalls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* Calls out bots' moves near me in the ticker (#64): an attack, a sprint, a
* chase after me, a turn on the front. Only the start of a move counts, by a
* bot on my route within `BOT_CALLS.reachM`; a chase only when the bot is
* behind me. At most one line every `everyS`, and the same bot and move at
* most once every `repeatS`. Pure: the caller posts the lines.
*/
export const BOT_CALLS = Object.freeze({ reachM: 120, everyS: 15, repeatS: 90 });

const CALLED = new Set(["attack", "sprint", "answer", "pull"]);

export class BotCalls {
/** Each bot's move when last seen (null while it just rides). */
#moves = new Map();
/** When each "bot:move" was last called out. */
#said = new Map();
#lastS = -Infinity;

/**
* @param {{riders: object[], me: ?{route: ?string, distance: number}, route: {signedGap(a: number, b: number): number}, nowS: number}} frame
* @returns {{id: number, name: string, move: string}[]} the line to post, if any
*/
update({ riders, me, route, nowS }) {
const started = [];
const seen = new Set();
for (const rider of riders) {
if (!rider.is_bot) continue;
seen.add(rider.id);
const known = this.#moves.has(rider.id);
const before = this.#moves.get(rider.id);
const move = rider.move ?? null;
this.#moves.set(rider.id, move);
// A bot first seen mid-move didn't start it in front of me.
if (!known || !move || move === before || !CALLED.has(move)) continue;
if (!me?.route || rider.route !== me.route) continue;
const gap = route.signedGap(me.distance, rider.distance);
if (Math.abs(gap) > BOT_CALLS.reachM) continue;
if (move === "answer" && gap >= 0) continue;
started.push({ id: rider.id, name: rider.name, move });
}
for (const id of this.#moves.keys()) if (!seen.has(id)) this.#moves.delete(id);
if (nowS - this.#lastS < BOT_CALLS.everyS) return [];
const call = started.find((c) => nowS - (this.#said.get(`${c.id}:${c.move}`) ?? -Infinity) >= BOT_CALLS.repeatS);
if (!call) return [];
this.#lastS = nowS;
this.#said.set(`${call.id}:${call.move}`, nowS);
return [call];
}
}
20 changes: 20 additions & 0 deletions client/public/js/view/botKits.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Bot teams' kit colours (#64). The server sends each bot's `team`; its jersey
* takes the team's colour in the 3D view. None is orange (me) or sky blue
* (humans), so bots still read as bots. Unknown teams keep the bot grey.
*/
export const TEAM_KITS = Object.freeze({
zitrone: "#f2cf2a",
moos: "#4f8f3a",
kirsche: "#b3263a",
lavendel: "#8c6bc8",
kreide: "#ecebe4",
schiefer: "#2f3339",
petrol: "#1f7f7a",
rose: "#e58fb2",
});

/** A bot's kit colour (`#rrggbb`), or null for humans and unknown teams. */
export function botKit(rider) {
return (rider?.is_bot && Object.hasOwn(TEAM_KITS, rider.team) && TEAM_KITS[rider.team]) || null;
}
19 changes: 17 additions & 2 deletions client/public/js/view/panels.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,27 @@ export function riderName(rider) {
return isPaddler(rider) ? `${rider.name} ${PADDLE_BADGE}` : rider.name;
}

const BOT_STYLES = Object.freeze({
rouleur: "panels.botStyle.rouleur",
climber: "panels.botStyle.climber",
sprinter: "panels.botStyle.sprinter",
attacker: "panels.botStyle.attacker",
tourer: "panels.botStyle.tourer",
});

/** A bot's badge: its riding type ("climber bot"), or plain "bot" (#64). */
export function botBadgeText(rider) {
return Object.hasOwn(BOT_STYLES, rider.style) ? t(BOT_STYLES[rider.style]) : t("panels.bot");
}

export function renderRiderList(list, entries, myId) {
list.replaceChildren(
...entries.map(({ rider, gap, routeName }) => {
const item = element("li", rider.id === myId ? "rider me" : "rider");
const name = element("span", "rider-name", rider.name);
if (rider.is_bot) name.append(element("span", "badge", t("panels.bot")));
// The name gives way to the badges: a bot is always marked, however long its name.
const name = element("span", "rider-name split");
name.append(element("span", "rider-name-text", rider.name));
if (rider.is_bot) name.append(element("span", "badge", botBadgeText(rider)));
if (isRemote(rider)) name.append(element("span", "badge badge-remote", rider.app));
if (isPaddler(rider)) name.append(paddleBadge());
item.append(name, element("span", "rider-power", `${Math.round(rider.power)} W`), element("span", "rider-gap", rider.id === myId ? "" : gap === null ? routeName : formatGap(gap)));
Expand Down
13 changes: 11 additions & 2 deletions client/public/js/view3d/view3d.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* floating name labels. Same inputs as the 2D views (smoothed riders), so it
* needs no protocol changes.
*/
import { TEAM_KITS, botKit } from "../view/botKits.js";
import { CAMERA_MODES, ChaseCamera } from "./chaseCamera.js";
import { clipFor, mirrorPlant, mirrorPose, settle } from "./clips.js";
import { chunkNear, chunkVisible } from "./chunks.js";
Expand Down Expand Up @@ -69,6 +70,14 @@ export function hexToRgb(hex) {
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}

/** Bot teams' kit colours as tints (#64). */
const KIT_TINTS = new Map(Object.entries(TEAM_KITS).map(([team, hex]) => [team, hexToRgb(hex)]));

/** A bot's jersey: its team's kit, else the bot grey. */
function botTint(rider, tints) {
return (botKit(rider) && KIT_TINTS.get(rider.team)) || tints.bot;
}

/**
* Projects a world point to CSS pixels. Returns null when it is behind the camera.
* @returns {{x: number, y: number, depth: number} | null}
Expand Down Expand Up @@ -656,7 +665,7 @@ export class View3D {
const seatModel = multiply(base, placement(seat.hip, seat.yaw));
// The hip stays put when the rider is scaled: scale about it, then bring the solo hip to the origin.
const legsModel = multiply(seatModel, multiply(scaling(look.scale), placement([0, -hy, -hz])));
const tint = rider.id === myId ? tints.me : isRemote(rider) ? tints.remote : rider.is_bot ? tints.bot : tints.human;
const tint = rider.id === myId ? tints.me : isRemote(rider) ? tints.remote : rider.is_bot ? botTint(rider, tints) : tints.human;
bodies.push({ variant: look.variant, model: multiply(seatModel, scaling(look.scale)), tint });
limbs.push(...this.#legs(legsModel, look, this.#pedal(rider.id, seatCadence(rider), dt)));
heads.set(rider.id, transformPoint(seatModel, [0, 0.62 * look.scale + 0.55, 0]).slice(0, 3));
Expand Down Expand Up @@ -718,7 +727,7 @@ export class View3D {
// Far riders are invisible anyway; riders right at the camera would block the view.
if (fromCamera > 600 || (fromCamera < SCENE.nearCameraHide && rider.id !== myId)) continue;
const cadence = rider.id === myId ? (myCadence ?? 0) : rider.power > 0 ? 85 : 0;
const tint = rider.ghost ? SCENE.ghost.tint : rider.id === myId ? tints.me : isRemote(rider) ? tints.remote : rider.is_bot ? tints.bot : tints.human;
const tint = rider.ghost ? SCENE.ghost.tint : rider.id === myId ? tints.me : isRemote(rider) ? tints.remote : rider.is_bot ? botTint(rider, tints) : tints.human;
const parts = gym ? this.#workoutParts(rider, gym, timeS) : this.#riderParts(rider, position, forward, cadence, dt);
visible.push({ rider, position, forward, fromCamera, tint, ghost: Boolean(rider.ghost), ...parts });
}
Expand Down
17 changes: 17 additions & 0 deletions client/public/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -2990,6 +2990,23 @@ body.riding {
white-space: nowrap;
}

.rider-name.split {
display: flex;
align-items: baseline;
min-width: 0;
}

.rider-name-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-width: 0;
}

.rider-name.split .badge {
flex: none;
}

.rider-gap,
.rider-power {
text-align: right;
Expand Down
113 changes: 113 additions & 0 deletions client/test/bots.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { test, afterEach } from "node:test";
import assert from "node:assert/strict";
import { BOT_CALLS, BotCalls } from "../public/js/ride/botCalls.js";
import { TEAM_KITS, botKit } from "../public/js/view/botKits.js";
import { botBadgeText } from "../public/js/view/panels.js";
import { setLocale } from "../public/js/i18n/i18n.js";

afterEach(() => setLocale("en"));

// --- kits --------------------------------------------------------------------------

const rgb = (hex) => [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16));
const hue = ([r, g, b]) => {
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
if (max === min) return null;
const d = max - min;
const h = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
return (h * 60 + 360) % 360;
};

test("no team rides in my orange or the humans' sky blue", () => {
const me = hue(rgb("#ff7a1a"));
const human = hue(rgb("#4cc3ff"));
for (const [team, hex] of Object.entries(TEAM_KITS)) {
const h = hue(rgb(hex));
if (h === null) continue;
const apart = (a, b) => Math.min(Math.abs(a - b), 360 - Math.abs(a - b));
assert.ok(apart(h, me) > 15, `${team} is too close to orange`);
assert.ok(apart(h, human) > 15, `${team} is too close to sky blue`);
}
});

test("a bot wears its team's kit; humans and unknown teams none", () => {
assert.equal(botKit({ is_bot: true, team: "moos" }), TEAM_KITS.moos);
assert.equal(botKit({ is_bot: true, team: "nowhere" }), null);
assert.equal(botKit({ is_bot: true, team: "toString" }), null);
assert.equal(botKit({ is_bot: true }), null);
assert.equal(botKit({ is_bot: false, team: "moos" }), null);
});

// --- the badge --------------------------------------------------------------------

test("the bot badge names the riding type, in the rider's language", () => {
assert.equal(botBadgeText({ is_bot: true, style: "climber" }), "climber bot");
assert.equal(botBadgeText({ is_bot: true }), "bot");
assert.equal(botBadgeText({ is_bot: true, style: "unicyclist" }), "bot");
setLocale("de");
assert.equal(botBadgeText({ is_bot: true, style: "climber" }), "Kletterer-Bot");
});

// --- ticker calls -----------------------------------------------------------------

const route = { signedGap: (from, to) => to - from };
const me = { id: 1, route: "r", distance: 1000 };
const bot = (move, distance = 1050, extra = {}) => ({ id: 7, name: "Gus Tailwind", is_bot: true, route: "r", distance, move, ...extra });

function calls(frames) {
const watch = new BotCalls();
return frames.map(({ riders, nowS }) => watch.update({ riders, me, route, nowS }));
}

test("a bot near me starting an attack is called out once", () => {
const out = calls([
{ riders: [bot(undefined)], nowS: 0 },
{ riders: [bot("attack")], nowS: 1 },
{ riders: [bot("attack")], nowS: 2 },
]);
assert.deepEqual(out, [[], [{ id: 7, name: "Gus Tailwind", move: "attack" }], []]);
});

test("a bot first seen mid-move, far away, on another route or a human is not called out", () => {
for (const [first, second] of [
[null, bot("attack")],
[bot(undefined, 1000 + BOT_CALLS.reachM + 50), bot("attack", 1000 + BOT_CALLS.reachM + 50)],
[bot(undefined, 1050, { route: "other" }), bot("attack", 1050, { route: "other" })],
[bot(undefined, 1050, { is_bot: false }), bot("attack", 1050, { is_bot: false })],
]) {
const out = calls([
{ riders: first ? [first] : [], nowS: 0 },
{ riders: [second], nowS: 1 },
]);
assert.deepEqual(out[1], [], JSON.stringify(second));
}
});

test("a chase is only called out when the bot comes after me", () => {
const ahead = calls([
{ riders: [bot(undefined, 1030)], nowS: 0 },
{ riders: [bot("answer", 1030)], nowS: 1 },
]);
assert.deepEqual(ahead[1], []);
const behind = calls([
{ riders: [bot(undefined, 970)], nowS: 0 },
{ riders: [bot("answer", 970)], nowS: 1 },
]);
assert.equal(behind[1][0].move, "answer");
});

test("calls are spaced out and the same bot's move isn't repeated soon", () => {
const other = (move) => ({ ...bot(move), id: 8, name: "Sally Sprocket" });
const out = calls([
{ riders: [bot(undefined), other(undefined)], nowS: 0 },
{ riders: [bot("attack"), other("pull")], nowS: 1 },
{ riders: [bot(undefined), other(undefined)], nowS: 5 },
{ riders: [bot("attack"), other("pull")], nowS: 10 },
{ riders: [bot(undefined), other(undefined)], nowS: 30 },
{ riders: [bot("attack"), other("pull")], nowS: 40 },
]);
assert.equal(out[1].length, 1, "one line at a time");
assert.deepEqual(out[3], [], `within ${BOT_CALLS.everyS} s of the last line`);
assert.deepEqual(out[5], [{ id: 8, name: "Sally Sprocket", move: "pull" }], "Gus's attack was called less than 90 s ago");
});
10 changes: 10 additions & 0 deletions client/test/remoteRiders.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,13 @@ test("a remote name with markup stays text in the 3D label", () =>
assert.ok(nodes.some((node) => node.textContent === "<img src=x onerror=alert(1)>"));
assert.ok(nodes.some((node) => node.className.includes("badge") && node.textContent === "incyclist"));
}));

test("a bot's name and its type badge are apart in the row, so only the name is cut short (#64)", () =>
withFakeDocument(() => {
const list = new FakeElement("ul");
const bot = { id: 9, name: "Valentina Draftsworth", is_bot: true, style: "attacker", power: 150 };
renderRiderList(list, [{ rider: bot, gap: 5, routeName: "" }], 1);
const nodes = list.all();
assert.ok(nodes.some((node) => node.className === "rider-name-text" && node.textContent === "Valentina Draftsworth"));
assert.ok(nodes.some((node) => node.className === "badge" && node.textContent === "attacker bot"));
}));
Loading
Loading