Add click-to-move controls, readable journal and chat, and action sounds

This commit is contained in:
coyotte508 2026-09-10 22:13:47 +02:00
commit 09081dec4a
20 changed files with 1181 additions and 533 deletions

View file

@ -1,6 +1,6 @@
{
"name": "container-engine",
"version": "2.0.0",
"version": "2.0.1",
"description": "An engine for Container",
"main": "dist/index.js",
"types": "index.ts",

View file

@ -1056,8 +1056,10 @@ function containerColorHTML(containerColor: ContainerColor) {
case ContainerColor.Orange:
case ContainerColor.Tan:
case ContainerColor.White:
return `<span style="background-color: ${containerColor}; font-weight: bold; border: 1px solid black; padding: 0 3px;">${containerColor}</span>`;
return `<span style="background-color: ${containerColor}; color: ${
containerColor === ContainerColor.Brown ? '#fff' : '#111'
}; font-weight: bold; border: 1px solid black; padding: 0 3px;">${containerColor}</span>`;
case ContainerColor.Black:
return '<span style="background-color: #2F4F4F; font-weight: bold; border: 1px solid black; padding: 0 3px;">darkslategray</span>';
return '<span style="background-color: #2F4F4F; color: #fff; font-weight: bold; border: 1px solid black; padding: 0 3px;">darkslategray</span>';
}
}

5
scripts/LOCAL-REVIEW.md Normal file
View file

@ -0,0 +1,5 @@
Local review controls and BGS release metadata.
`viewer-preferences.json` is a merge patch for BGS releases: enable the embedded chat and add/update the sound preference while preserving all other preferences and viewer fields. Do not PUT this partial file as a full game-info document.
The local viewer has a Playtest tools panel with individual sound buttons and a mute toggle. Chat messages entered in the local preview stay local.

View file

@ -0,0 +1,4 @@
{
"viewer": { "chat": true },
"preferences": [{ "name": "sound", "label": "Game action sounds", "type": "checkbox", "default": true }]
}

View file

@ -1,5 +1,10 @@
<template>
<g :class="['placeholder', { showDrop }]">
<g
:class="['placeholder', { showDrop, canClick: ui.selected && canDrop }]"
@click.stop="clickDestination"
@mousedown="prepareClick"
@touchstart="prepareClick"
>
<rect :width="width" :height="height" fill="black" />
<title v-if="data && data.type == 'playerHarbor'">Harbor</title>
<title v-else-if="data && data.type == 'factoryStore'">Factory Store</title>
@ -105,18 +110,33 @@ export default class DropZone extends Vue {
}
}
get canDrop() {
if (!this.enabled || !this.ui.dragged || this.accepts?.indexOf(this.ui.dragged.pieceType) == -1) return false;
get activePiece() {
return this.ui.dragged || (this.ui.selected?.canDrag ? this.ui.selected : null);
}
if (this.ui.dragged.pieceType == PieceType.Loan) {
const loan = this.ui.dragged as LoanCard;
prepareClick(event: Event) {
if (this.ui.selected && this.canDrop) event.stopPropagation();
}
clickDestination() {
if (this.ui.selected && this.canDrop) {
this.communicator.emit('pieceDrop', this.ui.selected, this.data);
this.ui.selected = null;
}
}
get canDrop() {
if (!this.enabled || !this.activePiece || this.accepts?.indexOf(this.activePiece.pieceType) == -1) return false;
if (this.activePiece.pieceType == PieceType.Loan) {
const loan = this.activePiece as LoanCard;
if (loan.owner == this.player) {
if (this.data.type == DropZoneType.GetLoan) return false;
} else {
if (this.data.type == DropZoneType.PayLoan) return false;
}
} else if (this.ui.dragged.pieceType == PieceType.Ship) {
const ship = this.ui.dragged as Ship;
} else if (this.activePiece.pieceType == PieceType.Ship) {
const ship = this.activePiece as Ship;
if (ship.position == ShipPosition.OpenSea) {
if (this.data.type == DropZoneType.OpenSea) return false;
@ -126,8 +146,8 @@ export default class DropZone extends Vue {
} else {
if (this.data.type != DropZoneType.OpenSea) return false;
}
} else if (this.ui.dragged.pieceType == PieceType.Container) {
const container = this.ui.dragged as Container;
} else if (this.activePiece.pieceType == PieceType.Container) {
const container = this.activePiece as Container;
if (container.state == ContainerState.OnBoard) {
if (this.data.type != DropZoneType.FactoryStore) return false;
} else if (container.state == ContainerState.OnFactoryStore) {
@ -161,7 +181,7 @@ export default class DropZone extends Vue {
}
get showDrop() {
return !this.preferences.disableHelp && this.canDrop;
return (!!this.ui.selected || !this.preferences.disableHelp) && this.canDrop;
}
}
</script>
@ -174,8 +194,9 @@ g.placeholder {
&.showDrop {
rect {
stroke: blue;
stroke-width: 2px;
stroke: #1b6c87;
stroke-width: 1.3px;
rx: 3px;
}
}
@ -184,3 +205,13 @@ g.placeholder {
}
}
</style>
<style>
.piece.click-selected {
filter: drop-shadow(0 0 3px #fff) drop-shadow(0 0 2px #203a45);
}
g.placeholder.canClick rect {
fill: #1b6c8722;
stroke-dasharray: 4 3;
}
</style>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,61 @@
<template>
<details class="inline-game-log" open>
<summary>Journal</summary>
<div ref="feed" class="journal-feed" @scroll="onScroll">
<div v-for="(entry, index) in entries" :key="index" class="journal-entry" v-html="entry" />
<div v-if="!entries.length">No actions yet.</div>
</div>
</details>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
@Component
export default class InlineLog extends Vue {
@Prop({ default: () => [] }) entries!: string[];
follow = true;
mounted() {
this.scrollToLatest();
}
@Watch('entries') changed() {
if (this.follow) {
this.$nextTick(this.scrollToLatest);
}
}
scrollToLatest() {
const feed = this.$refs.feed as HTMLElement;
if (feed) {
feed.scrollTop = feed.scrollHeight;
}
}
onScroll() {
const feed = this.$refs.feed as HTMLElement;
this.follow = feed.scrollHeight - feed.scrollTop - feed.clientHeight < 32;
}
}
</script>
<style scoped>
.inline-game-log {
box-sizing: border-box;
width: 100%;
padding: 10px 14px;
border: 1px solid #75818d66;
border-radius: 6px;
background: #e5eeea;
color: #203a45;
font: 14px system-ui;
}
summary {
cursor: pointer;
font-weight: 600;
}
.journal-feed {
max-height: 220px;
overflow: auto;
overscroll-behavior: contain;
margin-top: 8px;
}
.journal-entry {
padding: 5px 0;
border-bottom: 1px solid #75818d33;
}
</style>

View file

@ -5,12 +5,15 @@
getPlayerName()
}}</text>
<rect width="250" height="180" x="0" y="20" fill="gray" />
<rect width="250" height="180" x="0" y="20" fill="#e2e0d3" stroke="#899997" />
<rect width="246" height="2" x="2" y="21" :fill="color" />
<text x="248" y="104" text-anchor="end" font-size="8" fill="#45585b">FACTORY SALES</text>
<text x="248" y="194" text-anchor="end" font-size="8" fill="#45585b">WAREHOUSE SALES</text>
<rect width="20" height="80" x="0" y="200" fill="gray" />
<rect width="20" height="80" x="62" y="200" fill="gray" />
<rect width="20" height="80" x="124" y="200" fill="gray" />
<rect width="20" height="80" x="186" y="200" fill="gray" />
<rect width="20" height="80" x="0" y="200" fill="#c6c6b8" />
<rect width="20" height="80" x="62" y="200" fill="#c6c6b8" />
<rect width="20" height="80" x="124" y="200" fill="#c6c6b8" />
<rect width="20" height="80" x="186" y="200" fill="#c6c6b8" />
<DropZone
:transform="`translate(20, 200)`"
:width="42"
@ -49,14 +52,14 @@
:data="{ type: 'getLoan' }"
/>
<circle r="14" cx="28" cy="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="28" y="40" fill="lightgray">-</text>
<circle r="14" cx="76" cy="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="76" y="40" fill="lightgray">6</text>
<circle r="14" cx="124" cy="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="124" y="40" fill="lightgray">9</text>
<circle r="14" cx="172" cy="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="171" y="40" fill="lightgray">12</text>
<circle r="14" cx="28" cy="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="28" y="40" fill="#394b4d">-</text>
<circle r="14" cx="76" cy="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="76" y="40" fill="#394b4d">6</text>
<circle r="14" cx="124" cy="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="124" y="40" fill="#394b4d">9</text>
<circle r="14" cx="172" cy="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="171" y="40" fill="#394b4d">12</text>
<DropZone
:transform="`translate(13, 25)`"
:width="174"
@ -66,8 +69,8 @@
:data="{ type: 'factory' }"
/>
<rect x="8" y="60" width="40" height="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="28" y="90" fill="lightgray">1</text>
<rect x="8" y="60" width="40" height="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="28" y="90" fill="#394b4d">1</text>
<DropZone
:transform="`translate(8, 60)`"
:width="40"
@ -76,8 +79,8 @@
:accepts="'container'"
:data="{ type: 'factoryStore', price: 1 }"
/>
<rect x="56" y="60" width="40" height="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="76" y="90" fill="lightgray">2</text>
<rect x="56" y="60" width="40" height="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="76" y="90" fill="#394b4d">2</text>
<DropZone
:transform="`translate(56, 60)`"
:width="40"
@ -86,8 +89,8 @@
:accepts="'container'"
:data="{ type: 'factoryStore', price: 2 }"
/>
<rect x="104" y="60" width="40" height="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="124" y="90" fill="lightgray">3</text>
<rect x="104" y="60" width="40" height="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="124" y="90" fill="#394b4d">3</text>
<DropZone
:transform="`translate(104, 60)`"
:width="40"
@ -96,8 +99,8 @@
:accepts="'container'"
:data="{ type: 'factoryStore', price: 3 }"
/>
<rect x="152" y="60" width="40" height="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="172" y="90" fill="lightgray">4</text>
<rect x="152" y="60" width="40" height="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="172" y="90" fill="#394b4d">4</text>
<DropZone
:transform="`translate(152, 60)`"
:width="40"
@ -107,26 +110,22 @@
:data="{ type: 'factoryStore', price: 4 }"
/>
<g transform="translate(8, 105)"
><path d="M20 0 L40 13 L40 40 L0 40 L0 13Z" fill="none" stroke="lightgray"
/></g>
<text text-anchor="middle" x="28" y="128" fill="lightgray">-</text>
<g transform="translate(56, 105)"
><path d="M20 0 L40 13 L40 40 L0 40 L0 13Z" fill="none" stroke="lightgray"
/></g>
<text text-anchor="middle" x="76" y="128" fill="lightgray">4</text>
<g transform="translate(8, 105)"><path d="M20 0 L40 13 L40 40 L0 40 L0 13Z" fill="none" stroke="#6f7976" /></g>
<text text-anchor="middle" x="28" y="128" fill="#394b4d">-</text>
<g transform="translate(56, 105)"><path d="M20 0 L40 13 L40 40 L0 40 L0 13Z" fill="none" stroke="#6f7976" /></g>
<text text-anchor="middle" x="76" y="128" fill="#394b4d">4</text>
<g transform="translate(104, 105)"
><path d="M20 0 L40 13 L40 40 L0 40 L0 13Z" fill="none" stroke="lightgray"
><path d="M20 0 L40 13 L40 40 L0 40 L0 13Z" fill="none" stroke="#6f7976"
/></g>
<text text-anchor="middle" x="124" y="128" fill="lightgray">5</text>
<text text-anchor="middle" x="124" y="128" fill="#394b4d">5</text>
<g transform="translate(152, 105)"
><path d="M20 0 L40 13 L40 40 L0 40 L0 13Z" fill="none" stroke="lightgray"
><path d="M20 0 L40 13 L40 40 L0 40 L0 13Z" fill="none" stroke="#6f7976"
/></g>
<text text-anchor="middle" x="172" y="128" fill="lightgray">6</text>
<text text-anchor="middle" x="172" y="128" fill="#394b4d">6</text>
<g transform="translate(200, 105)"
><path d="M20 0 L40 13 L40 40 L0 40 L0 13Z" fill="none" stroke="lightgray"
><path d="M20 0 L40 13 L40 40 L0 40 L0 13Z" fill="none" stroke="#6f7976"
/></g>
<text text-anchor="middle" x="220" y="128" fill="lightgray">7</text>
<text text-anchor="middle" x="220" y="128" fill="#394b4d">7</text>
<DropZone
:transform="`translate(7, 104)`"
:width="234"
@ -136,8 +135,8 @@
:data="{ type: 'warehouse' }"
/>
<rect x="8" y="150" width="40" height="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="28" y="180" fill="lightgray">2</text>
<rect x="8" y="150" width="40" height="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="28" y="180" fill="#394b4d">2</text>
<DropZone
:transform="`translate(8, 150)`"
:width="40"
@ -146,8 +145,8 @@
:accepts="'container'"
:data="{ type: 'warehouseStore', price: 2 }"
/>
<rect x="56" y="150" width="40" height="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="76" y="180" fill="lightgray">3</text>
<rect x="56" y="150" width="40" height="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="76" y="180" fill="#394b4d">3</text>
<DropZone
:transform="`translate(56, 150)`"
:width="40"
@ -156,8 +155,8 @@
:accepts="'container'"
:data="{ type: 'warehouseStore', price: 3 }"
/>
<rect x="104" y="150" width="40" height="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="124" y="180" fill="lightgray">4</text>
<rect x="104" y="150" width="40" height="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="124" y="180" fill="#394b4d">4</text>
<DropZone
:transform="`translate(104, 150)`"
:width="40"
@ -166,8 +165,8 @@
:accepts="'container'"
:data="{ type: 'warehouseStore', price: 4 }"
/>
<rect x="152" y="150" width="40" height="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="172" y="180" fill="lightgray">5</text>
<rect x="152" y="150" width="40" height="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="172" y="180" fill="#394b4d">5</text>
<DropZone
:transform="`translate(152, 150)`"
:width="40"
@ -176,8 +175,8 @@
:accepts="'container'"
:data="{ type: 'warehouseStore', price: 5 }"
/>
<rect x="200" y="150" width="40" height="40" fill="none" stroke="lightgray" />
<text text-anchor="middle" x="220" y="180" fill="lightgray">6</text>
<rect x="200" y="150" width="40" height="40" fill="none" stroke="#6f7976" />
<text text-anchor="middle" x="220" y="180" fill="#394b4d">6</text>
<DropZone
:transform="`translate(200, 150)`"
:width="40"

View file

@ -4,7 +4,9 @@
:class="['piece', { dragging, canDrag }]"
:transform="`translate(${currentX}, ${currentY}) rotate(${rotate}, 10, 5)`"
>
<rect width="20" height="10" :fill="color" stroke="black" />
<rect width="20" height="10" rx=".8" :fill="color" stroke="#21343b" />
<path d="M4 2V8 M8 2V8 M12 2V8 M16 2V8" stroke="#10252b" stroke-opacity=".3" stroke-width=".7" />
<path d="M1 1H19" stroke="white" stroke-opacity=".5" />
<title>Container</title>
</g>

View file

@ -38,6 +38,7 @@ export default class Draggable extends Vue {
_offset = { x: 0, y: 0 };
_transform?: SVGTransform;
_dragStart?: number;
_press?: { x: number; y: number };
get svgElement() {
return document.querySelector('#scene') as SVGSVGElement;
@ -50,7 +51,8 @@ export default class Draggable extends Vue {
startDrag(evt: MouseEvent | TouchEvent) {
if (!this.canDrag) return;
this.dragging = true;
if (evt instanceof MouseEvent && evt.button !== 0) return;
this._press = this.getMousePosition(evt);
this._offset = this.getMousePosition(evt);
// Get all the transforms currently on this element
@ -72,24 +74,25 @@ export default class Draggable extends Vue {
}
drag(evt: MouseEvent | TouchEvent) {
if (!this.dragging) {
if (!this._press) {
return;
}
evt.preventDefault();
const coord = this.getMousePosition(evt);
if (!this.dragging && Math.hypot(coord.x - this._press.x, coord.y - this._press.y) < 5) return;
this.dragging = true;
evt.preventDefault();
this._transform!.setTranslate(coord.x - this._offset.x, coord.y - this._offset.y);
this.$emit('draggedTo', { x: coord.x - this._offset.x, y: coord.y - this._offset.y });
}
endDrag() {
if (!this._press) return;
const clicked = !this.dragging;
this._press = undefined;
this.dragging = false;
if (Date.now() - this._dragStart! < 100) {
this.$nextTick(() => {
this.$emit('fastClick', this);
});
}
if (clicked) this.$nextTick(() => this.$emit('fastClick', this));
}
getMousePosition(evt: MouseEvent | TouchEvent) {

View file

@ -1,6 +1,8 @@
<template>
<g :id="elId" :class="['piece', { dragging, canDrag }]" :transform="`translate(${currentX}, ${currentY})`">
<circle r="10" :fill="color" stroke="black" />
<circle r="10" :fill="color" stroke="#233b43" />
<path d="M-6 6 V-2 L-1 0 V-4 L4 -1 V-7 H7 V6Z" fill="#172d34" fill-opacity=".85" />
<path d="M-4 2 V4 M0 2 V4 M4 2 V4" stroke="#f4eed6" stroke-width="1.3" />
<title>Factory</title>
</g>

View file

@ -6,6 +6,11 @@ import { PieceType, UIData } from '@/types/ui-data';
@Component({
created(this: Piece) {
this.$on('fastClick', () => {
if (this.canDrag && this.pieceType !== PieceType.Loan) {
this.ui.selected = this.ui.selected === this ? null : this;
}
});
this.$on('draggedTo', (coords: { x: number; y: number }) => {
[this.currentX, this.currentY] = [coords.x, coords.y];
@ -16,6 +21,7 @@ import { PieceType, UIData } from '@/types/ui-data';
},
mounted(this: Piece) {
this.mounted = true;
this.$el.addEventListener('click', (event) => event.stopPropagation());
},
beforeDestroy(this: Piece) {
this.onTransitionEnd();
@ -105,6 +111,7 @@ export default class Piece extends Draggable {
@Watch('dragging')
onDraggingChanged() {
if (this.dragging) {
this.ui.selected = null;
this.ui.dragged = this;
} else {
this.ui.dragged = null;
@ -112,6 +119,16 @@ export default class Piece extends Draggable {
}
}
@Watch('canDrag')
onAvailabilityChanged() {
if (!this.canDrag && this.ui.selected === this) this.ui.selected = null;
}
@Watch('ui.selected')
onSelectionChanged() {
this.$el.classList.toggle('click-selected', this.ui.selected === this);
}
onTransitionEnd() {
// console.log("on transition end", this.transitioning);
if (this.transitioning) {

View file

@ -4,7 +4,15 @@
:class="['piece', { dragging, canDrag }]"
:transform="`translate(${currentX}, ${currentY}) rotate(${rotate}, 15, 40)`"
>
<path d="M15 0 L30 10 L30 80 L0 80 L0 10Z" :fill="color" stroke="black" />
<path
d="M15 0 Q29 7 30 17 L30 72 Q30 80 23 80 H7 Q0 80 0 72 V17 Q1 7 15 0Z"
:fill="color"
stroke="#203a45"
stroke-width="1.5"
/>
<path d="M15 6 L25 16 V71 H5 V16Z" fill="#eef1e6" fill-opacity=".8" />
<path d="M5 68 H25 V76 H5Z" fill="#344954" />
<path d="M8 70 H12 M17 70 H21" stroke="#c4e4e8" stroke-width="2" />
<Container
v-for="(container, i) in containers"
:key="container.id"

View file

@ -1,6 +1,9 @@
<template>
<g :id="elId" :class="['piece', { dragging, canDrag }]" :transform="`translate(${currentX}, ${currentY})`">
<path d="M15 0 L30 10 L30 30 L0 30 L0 10Z" fill="dimgray" stroke="black" />
<path d="M15 0 L30 10 L30 30 L0 30 L0 10Z" fill="#789298" stroke="#233b43" />
<path d="M0 10 L15 0 L30 10" fill="none" stroke="#344a51" stroke-width="2" />
<path d="M7 30V14 H23V30" fill="#dae2da" stroke="#425c65" />
<path d="M8 18H22 M8 22H22 M8 26H22" stroke="#6c8285" />
<title>Warehouse</title>
</g>
</template>

239
viewer/src/game-chat.ts Normal file
View file

@ -0,0 +1,239 @@
import { playerColors } from 'container-engine/src/engine';
type ChatMessage = { _id?: string; author?: string; text: string; createdAt?: string; playerIndex?: number };
type ChatEmitter = {
on: (event: string, fn: (data: any) => void) => unknown;
emit: (event: string, data: any) => unknown;
};
export function mountGameChat(emitter: ChatEmitter, host: Element): void {
const panel = document.createElement('details');
panel.className = 'bgs-game-chat';
panel.open = true;
panel.innerHTML =
'<summary>Chat</summary><div class="chat-messages" role="log" aria-label="Game chat"></div><form><input type="text" aria-label="Chat message" placeholder="Message…" autocomplete="off"><button type="submit">Send</button></form><div class="chat-status" role="status"></div>';
const style = document.createElement('style');
style.textContent = `
.bgs-game-chat{box-sizing:border-box;font:14px/1.4 Arial,sans-serif;border:1px solid #9eb4b5;border-radius:3px;margin:8px 0;padding:8px 12px;background:var(--bg-panel,#e5eeea);color:var(--text,#203a45)}
.bgs-game-chat summary{cursor:pointer;font-weight:650;border-radius:3px;width:fit-content;padding:2px 4px;margin:-2px -4px}
.bgs-game-chat summary:hover{color:#126778}
.bgs-game-chat summary:focus-visible,.bgs-game-chat button:focus-visible{outline:2px solid #247d8c;outline-offset:3px}
.bgs-game-chat .chat-messages{max-height:250px;overflow:auto;overscroll-behavior:contain;margin:6px 0 8px}
.bgs-game-chat article{padding:5px 0;border-bottom:1px solid #75818d26;white-space:pre-wrap;overflow-wrap:anywhere}
.bgs-game-chat article strong{padding:0 3px;font-weight:bold}
.bgs-game-chat article:last-child{border-bottom:0}
.bgs-game-chat time{font-size:12px;color:#536e77;margin-left:8px;white-space:nowrap}
.bgs-game-chat form{display:flex;gap:6px;align-items:center;margin:0}
.bgs-game-chat input{flex:1;min-width:0;box-sizing:border-box;height:30px;background:#f2f4ee;color:#203a45;border:1px solid #899997;border-radius:2px;padding:4px 7px;font:14px Arial,sans-serif}
.bgs-game-chat input::placeholder{color:#637477}
.bgs-game-chat input:focus{outline:2px solid #527f89;outline-offset:1px}
.bgs-game-chat button{box-sizing:border-box;height:30px;cursor:pointer;border:1px solid #7f8c8d;border-radius:3px;background:#dddeda;color:#172d34;padding:3px 12px;font:14px Arial,sans-serif}
.bgs-game-chat button:hover:not(:disabled){background:#c8d3d0}
.bgs-game-chat button:disabled{color:#788786;border-color:#b0bcb8;background:#dce3df;cursor:default}
.bgs-game-chat .chat-status{font-size:12px;margin-top:6px}
.bgs-game-chat .chat-status:empty{display:none}
`;
panel.append(style);
host.insertAdjacentElement('afterend', panel);
const list = panel.querySelector('.chat-messages') as HTMLDivElement;
const input = panel.querySelector('input') as HTMLInputElement;
const button = panel.querySelector('button') as HTMLButtonElement;
const status = panel.querySelector('.chat-status') as HTMLDivElement;
let messages: ChatMessage[] = [];
let players: { id: number; name: string }[] = [];
let localPlayer: number | undefined;
emitter.on('state', (state) => {
players = state?.players || [];
render();
});
emitter.on('player', (player) => {
localPlayer = player?.index;
render();
});
let canSend = false;
let disabled = false;
let reason = 'Chat is connecting…';
let pending: { id: string; text: string } | undefined;
let timeout: ReturnType<typeof setTimeout> | undefined;
let readTimer: ReturnType<typeof setTimeout> | undefined;
let watermark = '';
let candidate = '';
let following = true;
function controls(): void {
button.disabled = !canSend || disabled || !!pending || !input.value.trim();
input.disabled = !canSend || disabled;
}
function read(): void {
if (!panel.open || document.visibilityState !== 'visible' || !document.hasFocus()) {
return;
}
const bounds = list.getBoundingClientRect();
const visible = Array.from(list.children).filter((el) => {
const r = el.getBoundingClientRect();
return r.bottom <= Math.min(bounds.bottom, window.innerHeight) + 1 && r.top >= Math.max(bounds.top, 0);
});
const id = (visible[visible.length - 1] as HTMLElement)?.dataset.id || '';
if (!/^[a-f0-9]{24}$/i.test(id) || id.toLowerCase() <= watermark) {
return;
}
candidate = candidate > id.toLowerCase() ? candidate : id.toLowerCase();
if (!readTimer) {
readTimer = setTimeout(() => {
readTimer = undefined;
if (candidate > watermark) {
watermark = candidate;
emitter.emit('chat:read', { messageId: watermark });
}
}, 500);
}
}
function render(): void {
list.textContent = '';
for (const message of messages) {
const row = document.createElement('article');
row.dataset.id = message._id || '';
const author = document.createElement('strong');
author.textContent = message.author || 'Game';
const index =
message.playerIndex ??
(message.author === 'You' ? localPlayer : players.find((p) => p.name === message.author)?.id);
if (index !== undefined && playerColors[index]) {
author.style.backgroundColor = playerColors[index];
author.style.color = '#111';
}
row.append(author, document.createTextNode(' '), document.createTextNode(message.text));
if (message.createdAt) {
const time = document.createElement('time');
const date = new Date(message.createdAt);
if (!isNaN(date.getTime())) {
time.textContent = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
time.title = date.toLocaleString();
row.append(time);
}
}
list.append(row);
}
if (following) {
list.scrollTop = list.scrollHeight;
}
read();
}
emitter.on('chat:messages', (data: ChatMessage[]) => {
messages = data || [];
render();
});
emitter.on('chat:appended', (data: ChatMessage[]) => {
for (const message of data || []) {
if (!message._id || !messages.some((m) => m._id === message._id)) {
messages.push(message);
}
}
render();
});
emitter.on('chat:updated', (data: ChatMessage[]) => {
for (const message of data || []) {
const index = messages.findIndex((m) => m._id === message._id);
if (index >= 0) {
messages[index] = message;
}
}
render();
});
emitter.on('chat:deleted', (ids: string[]) => {
messages = messages.filter((m) => !ids.includes(m._id || ''));
render();
});
emitter.on('chat:disabled', (value: boolean) => {
disabled = value;
status.textContent = value ? 'Chat disabled' : reason;
controls();
});
emitter.on('chat:state', (value: { canSend: boolean; reason?: string }) => {
canSend = value.canSend;
reason = canSend
? ''
: (
{
'not-logged-in': 'Sign in to chat',
'not-confirmed': 'Confirm your account to chat',
'not-a-player': 'Only players can send messages',
'chat-disabled': 'Chat disabled',
'no-game': 'Chat will be available when the game starts',
} as Record<string, string>
)[value.reason || ''] || 'Chat is read-only';
status.textContent = reason;
controls();
});
emitter.on('chat:result', (result: { requestId: string; ok: boolean; error?: string }) => {
if (pending?.id !== result.requestId) {
return;
}
if (timeout) {
clearTimeout(timeout);
}
if (result.ok && input.value === pending.text) {
input.value = '';
}
status.textContent = result.ok ? '' : result.error || 'Message could not be sent. Your draft is kept.';
pending = undefined;
controls();
});
panel.querySelector('form')!.onsubmit = (event) => {
event.preventDefault();
if (button.disabled) {
return;
}
pending = { id: `${Date.now()}-${Math.random().toString(36).slice(2)}`, text: input.value };
controls();
status.textContent = 'Sending…';
emitter.emit('chat:send', { text: pending.text.trim(), requestId: pending.id });
timeout = setTimeout(() => {
if (pending) {
pending = undefined;
status.textContent = 'No confirmation received. Check the conversation before sending again.';
controls();
}
}, 20000);
};
input.oninput = controls;
input.onkeydown = (event) => {
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
event.preventDefault();
panel.querySelector('form')!.requestSubmit();
}
};
list.onscroll = () => {
following = list.scrollHeight - list.scrollTop - list.clientHeight < 32;
read();
};
panel.ontoggle = () => {
if (panel.open && following) {
list.scrollTop = list.scrollHeight;
}
read();
};
window.addEventListener('scroll', read, { passive: true });
window.addEventListener('focus', read);
document.addEventListener('visibilitychange', read);
status.textContent = reason;
controls();
}
export function installLocalChat(emitter: ChatEmitter): void {
emitter.emit('chat:state', { canSend: true });
emitter.emit('chat:messages', [
{
_id: '000000000000000000000001',
author: 'Playtest',
text: 'Local chat preview. Messages stay in this browser.',
createdAt: new Date().toISOString(),
},
]);
let next = 2;
emitter.on('chat:send', ({ text, requestId }) => {
emitter.emit('chat:appended', [
{ _id: (next++).toString(16).padStart(24, '0'), author: 'You', text, createdAt: new Date().toISOString() },
]);
emitter.emit('chat:result', { requestId, ok: true });
});
}

View file

@ -0,0 +1,52 @@
function pieceIcon(kind: string, color = ''): string {
const label = `${color === 'darkslategray' ? 'dark green' : color} ${kind}`.trim();
const shape =
kind === 'factory'
? `<g transform="translate(11 11)"><circle r="10" fill="${color}" stroke="#233b43"/><path d="M-6 6 V-2 L-1 0 V-4 L4 -1 V-7 H7 V6Z" fill="#172d34" fill-opacity=".85"/><path d="M-4 2 V4 M0 2 V4 M4 2 V4" stroke="#f4eed6" stroke-width="1.3"/></g>`
: kind === 'container'
? `<g transform="translate(1 6)"><rect width="20" height="10" rx=".8" fill="${color}" stroke="#21343b"/><path d="M4 2V8 M8 2V8 M12 2V8 M16 2V8" stroke="#10252b" stroke-opacity=".3" stroke-width=".7"/><path d="M1 1H19" stroke="white" stroke-opacity=".5"/></g>`
: '<g transform="translate(1 1) scale(.66)"><path d="M15 0 L30 10 L30 30 L0 30 L0 10Z" fill="#789298" stroke="#233b43"/><path d="M0 10 L15 0 L30 10" fill="none" stroke="#344a51" stroke-width="2"/><path d="M7 30V14 H23V30" fill="#dae2da" stroke="#425c65"/><path d="M8 18H22 M8 22H22 M8 26H22" stroke="#6c8285"/></g>';
return `<span title="${label}" style="display:inline-block;vertical-align:middle;line-height:0"><svg role="img" aria-label="${label}" width="26" height="26" viewBox="0 0 22 22"><title>${label}</title>${shape}</svg></span>`;
}
export function journalPieces(html: string): string {
const root = document.createElement('div');
root.innerHTML = html;
for (const badge of Array.from(root.querySelectorAll('span'))) {
const color = badge.textContent || '';
const tail = badge.nextSibling;
if (
!badge.style.border ||
!/^(brown|orange|tan|white|darkslategray)$/.test(color) ||
tail?.nodeType !== Node.TEXT_NODE
)
continue;
const match = tail.textContent?.match(/^ (factory container|warehouse container|factory|container)\b/);
if (!match) continue;
const kind = match[1].endsWith('container') ? 'container' : 'factory';
const source =
match[1] === 'factory container'
? ' at the factory'
: match[1] === 'warehouse container'
? ' at the warehouse'
: '';
tail.textContent = source + tail.textContent!.slice(match[0].length);
const before = badge.previousSibling;
if (before?.nodeType === Node.TEXT_NODE) {
before.textContent = before.textContent!.replace(/\ba $/, '');
}
badge.outerHTML = pieceIcon(kind, color);
}
for (const node of Array.from(root.childNodes)) {
if (node.nodeType !== Node.TEXT_NODE || !node.textContent?.includes('a warehouse')) continue;
const fragment = document.createElement('span');
// Only replace text nodes: player names and existing markup stay intact.
const parts = node.textContent.split(/\ba warehouse\b/);
parts.forEach((part, i) => {
if (i) fragment.insertAdjacentHTML('beforeend', pieceIcon('warehouse'));
fragment.append(document.createTextNode(part));
});
node.replaceWith(fragment);
}
return root.innerHTML;
}

View file

@ -2,6 +2,8 @@ import type { GameState, Move } from 'container-engine';
import { EventEmitter } from 'events';
import Vue from 'vue';
import Game from './components/Game.vue';
import { mountGameChat } from './game-chat';
import { installActionSounds } from './sounds';
import type { Preferences } from './types/ui-data';
function launch(selector: string) {
@ -65,6 +67,8 @@ function launch(selector: string) {
}
});
installActionSounds(item);
mountGameChat(item, app.$el);
return item;
}

View file

@ -2,12 +2,16 @@ import { GameState, move as execMove, Move, setup, stripSecret } from 'container
import { moveAI } from 'container-engine/src/engine';
import { cloneDeep } from 'lodash';
import AbstractJudge from '../../engine/src/fixtures/Abstract-judge-7215.json';
import { installLocalChat } from './game-chat';
import launch from './launch';
import { mountSoundTests } from './sounds';
function launchSelfContained(selector = '#app') {
const strip = false;
const emitter = launch(selector);
mountSoundTests(emitter);
installLocalChat(emitter);
let gameState = setup(5, {});

207
viewer/src/sounds.ts Normal file
View file

@ -0,0 +1,207 @@
type Note = [number, number, number, number, number?, number?];
type Cue = { label: string; notes: Note[] };
export const soundCues: Record<string, Cue> = {
sail: {
label: 'Ship sailing',
notes: [
[0, 1.4, 0, 0.13, 650, 0.32],
[0.5, 1.4, 0, 0.09, 800, 0.38],
[0.08, 1.55, 105, 0.035, 82, 0.3],
],
},
produce: {
label: 'Container production',
notes: [
[0, 0.12, 0, 0.13, 1400],
[0.13, 0.12, 0, 0.1, 1200],
[0.25, 0.16, 140, 0.09, 75],
],
},
build: {
label: 'Factory / warehouse',
notes: [
[0, 0.1, 0, 0.16, 1100],
[0.1, 0.22, 105, 0.11, 50],
],
},
trade: {
label: 'Cargo sale / purchase',
notes: [
[0, 0.12, 700, 0.07],
[0.1, 0.16, 1050, 0.06],
],
},
bid: { label: 'Auction bid', notes: [[0, 0.12, 350, 0.08, 500]] },
loan: {
label: 'Loan / repayment',
notes: [
[0, 0.14, 700, 0.06, 400],
[0.13, 0.15, 400, 0.05],
],
},
};
let context: AudioContext | undefined;
let enabled = true;
export function setSoundEnabled(value: boolean): void {
enabled = value;
}
export function playSound(name: string): void {
if (!enabled || !soundCues[name] || typeof window === 'undefined') {
return;
}
if (typeof navigator !== 'undefined') {
const activation = (navigator as Navigator & { userActivation?: { hasBeenActive: boolean } }).userActivation;
if (activation && !activation.hasBeenActive) {
return;
}
}
const Audio = window.AudioContext;
if (!Audio) {
return;
}
context = context || new Audio();
const ctx = context;
void ctx
.resume()
.then(() => {
if (!enabled || ctx.state !== 'running') {
return;
}
for (const [offset, duration, frequency, volume, endFrequency, attack] of soundCues[name].notes) {
const start = ctx.currentTime + offset;
const gain = ctx.createGain();
gain.gain.setValueAtTime(0.0001, start);
gain.gain.exponentialRampToValueAtTime(volume, start + (attack || 0.008));
gain.gain.exponentialRampToValueAtTime(0.0001, start + duration);
gain.connect(ctx.destination);
if (frequency === 0) {
const buffer = ctx.createBuffer(1, Math.ceil(ctx.sampleRate * duration), ctx.sampleRate);
const samples = buffer.getChannelData(0);
let wash = 0;
for (let i = 0; i < samples.length; i++) {
const noise = Math.random() * 2 - 1;
wash = wash * 0.97 + noise * 0.03;
samples[i] = attack ? wash * 3 * (0.75 + 0.25 * Math.sin((i / ctx.sampleRate) * 13)) : noise;
}
const source = ctx.createBufferSource();
source.buffer = buffer;
const filter = ctx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.value = endFrequency || 900;
if (attack) {
filter.frequency.setValueAtTime(350, start);
filter.frequency.exponentialRampToValueAtTime(endFrequency || 900, start + attack);
filter.frequency.exponentialRampToValueAtTime(280, start + duration);
}
source.connect(filter);
filter.connect(gain);
source.start(start);
source.stop(start + duration);
} else {
const oscillator = ctx.createOscillator();
oscillator.type = 'sine';
oscillator.frequency.setValueAtTime(frequency, start);
oscillator.frequency.exponentialRampToValueAtTime(endFrequency || frequency, start + duration);
oscillator.connect(gain);
oscillator.start(start);
oscillator.stop(start + duration);
}
}
})
.catch(() => undefined);
}
export function installActionSounds(emitter: { on: (event: string, fn: (value: any) => void) => unknown }): void {
let previous: string[] | undefined;
let replaying = false;
emitter.on('update:preference', (pref) => {
if (pref?.name === 'sound') {
setSoundEnabled(pref.value);
}
});
emitter.on('preferences', (prefs) => {
if (typeof prefs?.sound === 'boolean') {
setSoundEnabled(prefs.sound);
}
});
emitter.on('replay:start', () => {
replaying = true;
});
emitter.on('replay:end', () => {
replaying = false;
previous = undefined;
});
const receiveState = (state: any) => {
const entries = state?.log || [];
const next = entries.map((entry: any) => JSON.stringify(entry));
const extendsHistory =
previous && previous.length < next.length && previous.every((entry, i) => entry === next[i]);
const from = previous?.length || 0;
previous = next;
if (!extendsHistory || replaying) {
return;
}
const cues = entries
.slice(from)
.map((entry: any) => cueForEntry(entry))
.filter(Boolean);
// Reconnection can deliver a whole round: play only the most recent event.
const cue = cues[cues.length - 1];
if (cue) {
playSound(cue);
}
};
emitter.on('state', receiveState);
emitter.on('gamelog', (event) => {
if (event?.data?.state) {
receiveState(event.data.state);
}
});
}
export function mountSoundTests(emitter: { emit: (event: string, value: any) => unknown }): void {
const panel = document.createElement('details');
panel.style.cssText =
'position:relative;z-index:5;padding:10px 16px;margin:8px;background:#172638;color:#f0f4f8;border:1px solid #56718a;border-radius:8px;font:14px system-ui';
const summary = document.createElement('summary');
summary.textContent = 'Playtest tools · sounds';
panel.append(summary);
const label = document.createElement('label');
label.style.margin = '10px';
const toggle = document.createElement('input');
toggle.type = 'checkbox';
toggle.checked = true;
toggle.onchange = () => {
setSoundEnabled(toggle.checked);
emitter.emit('preferences', { sound: toggle.checked });
};
label.append(toggle, ' Game sounds');
panel.append(label);
for (const [name, cue] of Object.entries(soundCues)) {
const button = document.createElement('button');
button.type = 'button';
button.textContent = cue.label;
button.style.cssText =
'margin:8px 4px;padding:7px 12px;color:#f0f4f8;background:#294663;border:1px solid #7391ad;border-radius:5px;cursor:pointer';
button.onclick = () => playSound(name);
panel.append(button);
}
document.body.prepend(panel);
}
function cueForEntry(entry: any): string | undefined {
return (
{
sail: 'sail',
produce: 'produce',
buyFactory: 'build',
buyWarehouse: 'build',
domesticSale: 'trade',
buyFromFactory: 'trade',
buyFromWarehouse: 'trade',
accept: 'trade',
bid: 'bid',
getLoan: 'loan',
payLoan: 'loan',
} as Record<string, string>
)[entry.move?.name];
}

View file

@ -4,6 +4,7 @@ import Vue from 'vue';
export interface UIData {
/** The Piece component instance (Piece.vue) currently being dragged, if any */
dragged?: (Vue & { pieceType: PieceType; pieceId: string }) | null;
selected?: (Vue & { pieceType: PieceType; pieceId: string; canDrag: boolean }) | null;
waitingAnimations: number;
}