Skip to content
1        10        20        30        40        50        60        70        80        90        100       110       120       130       1401// The Phaser scene. It draws the flat from the server's map and renders2// whatever the latest snapshot says. It owns no game rules.3import Phaser from 'phaser';4import { bus } from './bus.js';5import { BASE, DEFAULT_BASE, OVERLAY, TILE, TILE_NAMES, buildTileCanvas } from './tiles.js';6import { buildCharacterCanvas, normalizeLook } from './character.js';7import { DISPENSER_LABELS, FOOD_NAMES } from './food.js';89const EXTERIOR_TILES = 20;10const EXTERIOR_COLOUR = '#3a2c4a';11const FRAME_W = 16;12const FRAME_H = 24;13const FEET_OFFSET = 9; // sprite centre sits this far above the server's feet point14const LABEL_STYLE = {15  fontFamily: 'monospace',16  fontSize: '5px',17  color: '#fff8e7',18  backgroundColor: 'rgba(20, 10, 25, 0.6)',19  padding: { x: 2, y: 1 },20};21const WANT_COLOUR = { pending: '#fff8e7', eating: '#ffd27a', done: '#9fd08a' };2223export class FlatScene extends Phaser.Scene {24  constructor() {25    super('Flat');26    this.people = new Map();27    this.guests = [];28    this.stationLabels = new Map();29    this.followed = null;30    this.latest = null;31  }3233  create() {34    this.map = this.registry.get('map');35    this.myId = this.registry.get('myId');3637    const tex = this.textures.addCanvas('tiles', buildTileCanvas());38    TILE_NAMES.forEach((name, i) => tex.add(name, 0, i * TILE, 0, TILE, TILE));39    this.drawMap();4041    // Outside the flat is a plain exterior colour, so any window size has something behind it.42    const pad = EXTERIOR_TILES * TILE;43    const worldW = this.map.width * TILE;44    const worldH = this.map.height * TILE;45    this.cameras.main.setBackgroundColor(EXTERIOR_COLOUR);46    this.cameras.main.setBounds(-pad, -pad, worldW + 2 * pad, worldH + 2 * pad);47    this.applyZoom();48    this.scale.on('resize', () => this.applyZoom());4950    this.onState = (e) => { this.latest = e.detail; };51    bus.addEventListener('state', this.onState);52    this.events.once('shutdown', () => bus.removeEventListener('state', this.onState));53  }5455  // Narrow screens (phones) get a smaller zoom so more of the flat fits.56  applyZoom() {57    this.cameras.main.setZoom(this.scale.width < 700 ? 2 : 3);58  }5960  drawMap() {61    this.map.rows.forEach((row, ty) => {62      [...row].forEach((ch, tx) => {63        const cx = tx * TILE + TILE / 2;64        const cy = ty * TILE + TILE / 2;65        this.add.image(cx, cy, 'tiles', BASE[ch] ?? DEFAULT_BASE).setDepth(0);66        if (OVERLAY[ch]) this.add.image(cx, cy, 'tiles', OVERLAY[ch]).setDepth(1);67        if (DISPENSER_LABELS[ch]) this.label(cx, cy - 10, DISPENSER_LABELS[ch], 5);68      });69    });70  }7172  label(x, y, text, depth = 20) {73    return this.add.text(x, y, text, LABEL_STYLE)74      .setOrigin(0.5, 1)75      .setResolution(3)76      .setDepth(depth);77  }7879  // One texture per distinct look, shared by everyone who has it.80  charKey(lookIndexes) {81    const look = normalizeLook(lookIndexes);82    const key = `char-${Object.values(look).join('-')}`;83    if (!this.textures.exists(key)) {84      const tex = this.textures.addCanvas(key, buildCharacterCanvas(look));85      for (let i = 0; i < 12; i++) tex.add(String(i), 0, i * FRAME_W, 0, FRAME_W, FRAME_H);86      for (let dir = 0; dir < 4; dir++) {87        this.anims.create({88          key: `${key}-walk-${dir}`,89          frames: [1, 0, 2, 0].map((s) => ({ key, frame: String(dir * 3 + s) })),90          frameRate: 8,91          repeat: -1,92        });93      }94    }95    return key;96  }9798  update() {99    if (!this.latest) return;100    this.syncPeople(this.latest);101    this.syncGuests(this.latest);102    this.syncStations(this.latest);103    this.followMe();104    for (const e of this.people.values()) this.animate(e);105  }106107  syncPeople(s) {108    const seen = new Set();109    for (const p of s.players) {110      seen.add(p.id);111      let e = this.people.get(p.id);112      if (!e) {113        const key = this.charKey(p.look);114        const sprite = this.add.sprite(p.x, p.y - FEET_OFFSET, key, '0');115        e = {116          key,117          sprite,118          name: this.label(0, 0, p.name, 30),119          hand: this.label(0, 0, '', 30),120        };121        this.people.set(p.id, e);122      }123      e.target = { x: p.x, y: p.y - FEET_OFFSET };124      e.dir = p.dir;125      e.moving = p.moving;126      const handText = p.hand ? `(${FOOD_NAMES[p.hand]})` : '';127      if (e.hand.text !== handText) e.hand.setText(handText);128      const colour = p.id === this.myId ? '#ffd27a' : '#fff8e7';129      if (e.name.style.color !== colour) e.name.setColor(colour);130    }131    for (const [id, e] of this.people) {132      if (seen.has(id)) continue;133      e.sprite.destroy();134      e.name.destroy();135      e.hand.destroy();136      this.people.delete(id);137    }138  }139140  animate(e) {141    if (!e.target) return;142    const s = e.sprite;143    s.x += (e.target.x - s.x) * 0.45;144    s.y += (e.target.y - s.y) * 0.45;145    s.setDepth(s.y);146    if (e.moving) {147      s.anims.play(`${e.key}-walk-${e.dir}`, true);148    } else {149      s.anims.stop();150      s.setFrame(String(e.dir * 3));151    }152    e.name.setPosition(s.x, s.y - 12);153    e.hand.setPosition(s.x, s.y - 20);154    e.name.setDepth(s.y + 1);155    e.hand.setDepth(s.y + 1);156  }157158  syncGuests(s) {159    if (this.guests.length) return;160    this.guests = s.guests.map((g) => {161      const x = g.x * TILE + TILE / 2;162      const y = g.y * TILE + TILE;163      const sprite = this.add.sprite(x, y, this.charKey(g.look), '0').setOrigin(0.5, 1).setDepth(y);164      const text = this.label(x, y - 26, '', 30);165      return { sprite, text, name: g.name };166    });167  }168169  followMe() {170    const me = this.people.get(this.myId);171    if (me && this.followed !== me.sprite) {172      this.followed = me.sprite;173      this.cameras.main.startFollow(me.sprite, true, 0.15, 0.15);174    }175  }176177  syncStations(s) {178    this.syncGuestBubbles(s);179180    for (const st of s.stations) {181      const key = `${st.x},${st.y}`;182      const text = stationText(st);183      let label = this.stationLabels.get(key);184      if (!text) {185        if (label) label.setText('');186        continue;187      }188      if (!label) {189        label = this.label(st.x * TILE + TILE / 2, st.y * TILE - 2, '', 30);190        this.stationLabels.set(key, label);191      }192      if (label.text !== text) label.setText(text);193    }194  }195196  // Each guest's name and what they still want.197  syncGuestBubbles(s) {198    s.guests.forEach((g, i) => {199      const gv = this.guests[i];200      if (!gv) return;201      const lines = [g.name, ...g.wants.map((w) => `${FOOD_NAMES[w.food]}${w.state === 'done' ? ' ✓' : w.state === 'eating' ? ' …' : ''}`)];202      const text = lines.join('\n');203      if (gv.text.text !== text) {204        gv.text.setText(text);205        gv.text.setColor(WANT_COLOUR[g.wants.some((w) => w.state === 'pending') ? 'pending' : 'done']);206      }207    });208  }209}210211212function stationText(st) {213  const left = Math.ceil(st.left);214  const food = (f) => FOOD_NAMES[f] ?? f;215  switch (st.kind) {216    case 'board':217      if (st.phase === 'busy') return `chopping ${left}s`;218      if (st.phase === 'ready') return `${food(st.items[0])} ready`;219      return '';220    case 'pot':221    case 'oven':222      if (st.phase === 'busy') return `${st.kind === 'pot' ? 'simmering' : 'roasting'} ${left}s`;223      if (st.phase === 'ready') return `${st.kind === 'pot' ? 'soup' : 'roast'} ready`;224      return st.items.length ? `${st.items.length}/3 in` : '';225    case 'bowl':226      if (st.phase === 'ready') return 'salad ready';227      return st.items.length ? `${st.items.length}/2 in` : '';228    default:229      return '';230  }231}