xonecas.ioDon't click! Sean Caetano Martin Sign in

space-browser / commits / da2d52d

feat: pvp

xonecas5 weeks agoda2d52d37220297ff86bd57eca891ad097238691parent 067ab575 files changed

client/src/main.ts+20-2
@@ -1,5 +1,5 @@
11 import { connect, type State } from './net';
2-import type { Loose, Ore, Ship } from './sim';
2+import type { Loose, Ore, Ship, Shot } from './sim';
33 import { View, CELL, CELL_WORLD, ZOOM_MIN, ZOOM_MAX, type Camera } from './view';
44
55 const canvas = document.getElementById('view') as HTMLCanvasElement;
@@ -26,6 +26,7 @@ const net = connect((s) => {
2626 const ships = new Map<number, Ship>();
2727 const loose = new Map<number, Loose>();
2828 const ore = new Map<number, Ore>();
29+const shots = new Map<number, Shot>();
2930
3031 const cam: Camera & { follow: boolean } = { x: 0, y: 0, zoom: 0.5, follow: true };
3132 const keys = new Set<string>();
@@ -138,6 +139,7 @@ function frame(): void {
138139 s.ty = p.ty;
139140 s.fuel = p.fuel; // a gauge has to jump, not ease, or it lies about the tank
140141 s.fuelmax = p.fuelmax;
142+ s.foe = p.foe;
141143 s.pieces = p.pieces; // a hull is never eased: a piece is where the server says
142144 }
143145 }
@@ -169,6 +171,13 @@ function frame(): void {
169171 }
170172 }
171173 for (const id of ore.keys()) if (!oreLive.has(id)) ore.delete(id);
174+
175+ const shotLive = new Set<number>();
176+ for (const s of state.shots ?? []) {
177+ shotLive.add(s.id);
178+ shots.set(s.id, s); // a round is never eased, it is where the server put it
179+ }
180+ for (const id of shots.keys()) if (!shotLive.has(id)) shots.delete(id);
172181 }
173182
174183 const me = state ? ships.get(state.you) : undefined;
@@ -180,7 +189,16 @@ function frame(): void {
180189
181190 // The marker is the order the server is flying: never a click of our own.
182191 const marker = me && !state?.held ? { x: me.tx, y: me.ty } : null;
183- view.draw(cam, state?.bodies ?? [], [...ships.values()], state?.you ?? 0, [...loose.values()], [...ore.values()], marker);
192+ view.draw(
193+ cam,
194+ state?.bodies ?? [],
195+ [...ships.values()],
196+ state?.you ?? 0,
197+ [...shots.values()],
198+ [...loose.values()],
199+ [...ore.values()],
200+ marker,
201+ );
184202 requestAnimationFrame(frame);
185203 }
186204 requestAnimationFrame(frame);
client/src/net.ts+10-2
@@ -1,8 +1,16 @@
11 // One socket is one player. The server owns the world; we send intents and are
22 // handed back the state to draw.
3-import type { Body, Loose, Ore, Ship } from './sim';
3+import type { Body, Loose, Ore, Ship, Shot } from './sim';
44
5-export type State = { you: number; held: number; bodies: Body[]; loose: Loose[]; ore: Ore[]; players: Ship[] };
5+export type State = {
6+ you: number;
7+ held: number;
8+ bodies: Body[];
9+ loose: Loose[];
10+ ore: Ore[];
11+ shots: Shot[];
12+ players: Ship[];
13+};
614
715 export function connect(onState: (s: State) => void): { send: (msg: unknown) => void } {
816 let ws: WebSocket | null = null;
client/src/sim.ts+2-0
@@ -24,6 +24,7 @@ export type Loose = {
2424 tier: number;
2525 };
2626 export type Ore = { id: number; x: number; y: number; h: number; towed: number };
27+export type Shot = { id: number; x: number; y: number; h: number };
2728 export type Body = { id: number; kind: 'star' | 'shipyard' | 'barren'; r: number; x: number; y: number };
2829
2930 export type Ship = {
@@ -36,6 +37,7 @@ export type Ship = {
3637 ty: number;
3738 fuel: number; // what is in the tank
3839 fuelmax: number; // capacity, summed from the hull
40+ foe: number; // the ship this one is hostile with, 0 = neutral
3941 pieces: Piece[];
4042 };
4143
client/src/view.ts+47-11
@@ -2,7 +2,7 @@
22 // then a single fullscreen pass quantizes it into glyphs of the amber ramp.
33 // Two channels carry the shading: R = luminance (which glyph), G = palette index.
44 import * as THREE from 'three';
5-import { toWorld, type Body, type Kind, type Loose, type Ore, type Ship } from './sim';
5+import { toWorld, type Body, type Kind, type Loose, type Ore, type Ship, type Shot } from './sim';
66
77 export const CELL = 12; // css px per character cell
88 export const CELL_WORLD = 2; // world units per character cell at zoom 1
@@ -10,6 +10,8 @@ export const ZOOM_MIN = 0.6; // furthest out: far enough to frame a whole system
1010 export const ZOOM_MAX = 1.8; // closest in
1111 const SHIP_R = 11; // world radius of a hull
1212 const ORE_R = 6.5; // world radius of an ore piece
13+const SHOT_LEN = 13; // world units of laser line behind a round
14+const SHOT_W = 1.6; // world units thick: one bright cell wide
1315 const FUEL_CELLS = 12; // the fuel gauge is this many cells wide at any zoom
1416 const FUEL_WORD = 'FUEL'; // a word, not glyphs: letters are spelled out per cell
1517
@@ -146,23 +148,29 @@ const shade = (g: THREE.Group, role: Role) => {
146148 g.children.forEach((m, i) => (m as Part).material.color.copy(c[i]));
147149 };
148150
149-// What a piece looks like is entirely its health and its tier.
151+// What a piece looks like is entirely its health, its tier and whether the ship it
152+// belongs to is hostile to us. A hostile hull wears a strong red rim, which is a
153+// statement about the ship, not damage to it.
150154 type Wear = { hp: number; maxhp: number; tier: number };
151-function paint(g: THREE.Group, role: Role, w: Wear): void {
155+function paint(g: THREE.Group, role: Role, w: Wear, hostile: boolean): void {
152156 const ratio = w.maxhp > 0 ? w.hp / w.maxhp : 1;
153157 const [hi, lo] = ratio > 0.66 ? SHADE[role] : ratio > 0.33 ? HURT[0] : HURT[1];
154- const [edge, a, b] = g.children as Part[]; // built in this order
158+ const [rim, edge, a, b] = g.children as Part[]; // built in this order
159+ rim.visible = hostile;
160+ if (hostile) rim.material.color.copy(HURT[1][0]); // the rim of an enemy
155161 a.material.color.copy(hi);
156162 b.material.color.copy(lo);
157- edge.visible = w.tier > 0;
158- if (w.tier > 0) edge.material.color.copy(TIER[w.tier]);
163+ edge.visible = w.tier > 0 && !hostile; // the rim already says more than a tier
164+ if (edge.visible) edge.material.color.copy(TIER[w.tier]);
159165 }
160166
161167 // The tier border is a larger copy of the same shape drawn first, so the
162-// silhouette covers its middle and only a rim of it shows.
168+// silhouette covers its middle and only a rim of it shows. A hostile hull gets a
169+// second, fatter copy outside that, so an enemy reads as a strong red border even
170+// when a cell is several world units wide.
163171 function piece(kind: Kind): THREE.Group {
164172 const g = new THREE.Group();
165- for (const [scale, v] of [[1.3, 0], [1, 1], [0.7, 0.5]]) {
173+ for (const [scale, v] of [[1.9, 0], [1.3, 0], [1, 1], [0.7, 0.5]]) {
166174 g.add(new THREE.Mesh(pieceGeometry(kind, scale), new THREE.MeshBasicMaterial({ color: lum(v) })));
167175 }
168176 return g;
@@ -271,6 +279,7 @@ export class View {
271279 private quad = new THREE.Scene();
272280 private pieceMeshes = new Map<number, THREE.Group>();
273281 private oreMeshes = new Map<number, THREE.Group>();
282+ private shotMeshes = new Map<number, Part>();
274283 private bodyMeshes = new Map<number, THREE.Group>();
275284 private marker = crosshair();
276285 private hud = new THREE.Scene();
@@ -380,6 +389,7 @@ export class View {
380389 y: number,
381390 h: number,
382391 w: Wear,
392+ hostile: boolean,
383393 seen: Set<number>,
384394 ): void {
385395 seen.add(id);
@@ -389,7 +399,7 @@ export class View {
389399 this.pieceMeshes.set(id, g);
390400 this.scene.add(g);
391401 }
392- paint(g, role, w);
402+ paint(g, role, w, hostile);
393403 g.position.set(x, y, 0);
394404 g.rotation.z = h;
395405 }
@@ -427,6 +437,7 @@ export class View {
427437 bodies: Body[],
428438 ships: Ship[],
429439 ownId: number,
440+ shots: Shot[],
430441 loose: Loose[],
431442 ore: Ore[],
432443 marker: { x: number; y: number } | null,
@@ -445,14 +456,18 @@ export class View {
445456 this.bodies(bodies, performance.now() / 1000);
446457
447458 const seen = new Set<number>();
459+ const foe = ships.find((s) => s.id === ownId)?.foe ?? 0;
448460 for (const s of ships) {
449461 const role: Role = s.id === ownId ? 'own' : 'other';
462+ // A ship is an enemy the moment either side has declared it, so the rim can
463+ // never say hostile while the guns say neutral.
464+ const hostile = s.id !== ownId && (s.id === foe || s.foe === ownId);
450465 for (const p of s.pieces) {
451466 const w = toWorld(s, p);
452- this.place(p.id, p.kind, role, w.x, w.y, s.h, p, seen);
467+ this.place(p.id, p.kind, role, w.x, w.y, s.h, p, hostile, seen);
453468 }
454469 }
455- for (const l of loose) this.place(l.id, l.kind, 'loose', l.x, l.y, l.h, l, seen);
470+ for (const l of loose) this.place(l.id, l.kind, 'loose', l.x, l.y, l.h, l, false, seen);
456471 for (const [id, g] of this.pieceMeshes) {
457472 if (seen.has(id)) continue;
458473 this.scene.remove(g);
@@ -478,6 +493,27 @@ export class View {
478493 this.scene.remove(g);
479494 this.oreMeshes.delete(id);
480495 }
496+ // A round is a laser line lying along its heading, so a dodged shot is read as
497+ // a line passing by the hull rather than a dot that vanished. It is never eased:
498+ // a round has to be where the server says or it cannot be trusted to dodge.
499+ const shotSeen = new Set<number>();
500+ for (const s of shots) {
501+ shotSeen.add(s.id);
502+ let m = this.shotMeshes.get(s.id);
503+ if (!m) {
504+ m = plate(SHOT_LEN, SHOT_W, 1);
505+ m.material.color.copy(lum(1, 7));
506+ this.shotMeshes.set(s.id, m);
507+ this.scene.add(m);
508+ }
509+ m.position.set(s.x - Math.cos(s.h) * SHOT_LEN * 0.5, s.y - Math.sin(s.h) * SHOT_LEN * 0.5, 0);
510+ m.rotation.z = s.h;
511+ }
512+ for (const [id, m] of this.shotMeshes) {
513+ if (shotSeen.has(id)) continue;
514+ this.scene.remove(m);
515+ this.shotMeshes.delete(id);
516+ }
481517 this.marker.visible = marker !== null;
482518 if (marker) {
483519 this.marker.position.set(snapCell(marker.x, cam.x, wpc), snapCell(marker.y, cam.y, wpc), 0.5);
server/main.go+191-3
@@ -59,6 +59,12 @@ const (
5959
6060 fuelPer = 900.0 // world units of travel one unit of fuel buys
6161 refuel = 1.0 // fuel a second a docked shipyard puts back in the tank
62+
63+ gunRange = 140.0 // world distance a triangle will shoot at
64+ gunCool = 1.6 // seconds between salvos from one hull
65+ shotSpeed = 150.0 // a round is faster than a ship, so range alone is not safety
66+ shotDmg = 3.0 // hit points one round takes off a piece
67+ approach = 0.8 // of gun range: an approach order closes to here, no further
6268 )
6369
6470 // A hull is a graph of pieces placed relative to the ship. Piece ids are unique
@@ -87,6 +93,18 @@ type loose struct {
8793 held int // player dragging it, 0 = free
8894 }
8995
96+// A shot is a real object in the world: it travels, it can be outrun sideways,
97+// and it only hurts the piece it actually crosses.
98+type shot struct {
99+ ID int `json:"id"`
100+ X float64 `json:"x"`
101+ Y float64 `json:"y"`
102+ H float64 `json:"h"`
103+
104+ owner int // player who fired it, immune to its own round
105+ left float64 // world distance it can still travel
106+}
107+
90108 // An ore piece is thrown out of a barren planet and parks in one of its rings.
91109 // It lives in the planet's rotating frame (an angle and a radius), so it travels
92110 // with the planet around the star, and it is only a world point once placed.
@@ -130,7 +148,10 @@ type player struct {
130148 Pieces []piece `json:"pieces"`
131149 Fuel float64 `json:"fuel"` // what is in the tank, spent by flying
132150 FuelMax float64 `json:"fuelmax"` // capacity, summed from the hull every tick
151+ Foe int `json:"foe"` // player this ship is hostile with, 0 = neutral
133152
153+ chase int // player this ship was ordered to close on, 0 = no order
154+ cool float64 // seconds until the guns can fire again
134155 vx, vy float64
135156 orbit int // body the ship is anchored to, 0 = none
136157 ox, oy float64 // ring point, in world space, at the moment of anchoring
@@ -152,6 +173,7 @@ type hub struct {
152173 bodies []*body
153174 loose []*loose
154175 ore []*ore
176+ shots []*shot
155177 nextPiece int
156178 time float64
157179 }
@@ -163,6 +185,7 @@ type state struct {
163185 Bodies []*body `json:"bodies"`
164186 Loose []*loose `json:"loose"`
165187 Ore []*ore `json:"ore"`
188+ Shots []*shot `json:"shots"`
166189 Players []*player `json:"players"`
167190 }
168191
@@ -276,6 +299,7 @@ func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
276299
277300 h.mu.Lock()
278301 delete(h.clients, c)
302+ h.forgive(c.p.ID)
279303 if l := h.looseByID(c.p.held); l != nil {
280304 l.held = 0
281305 }
@@ -290,8 +314,8 @@ func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
290314
291315 // ---- intents ----
292316
293-// A click is resolved by the server: grab a piece, tear one off, park on a body,
294-// or fly to a point. The client never decides which happened.
317+// A click is resolved by the server: grab a piece, tear one off, engage a ship,
318+// park on a body, or fly to a point. The client never decides which happened.
295319 func (h *hub) pick(p *player, x, y float64) {
296320 if l := h.freeLooseAt(x, y); l != nil {
297321 p.held, l.held = l.ID, p.ID
@@ -306,14 +330,32 @@ func (h *hub) pick(p *player, x, y float64) {
306330 return
307331 }
308332 }
333+ for c := range h.clients {
334+ if c.p != p && hullPieceAt(c.p, x, y) != 0 {
335+ h.engage(p, c.p)
336+ return
337+ }
338+ }
309339 if b := h.bodyAt(x, y); b != nil {
310340 h.anchor(p, b)
311341 return
312342 }
343+ p.chase = 0 // any other order takes the ship off its approach
313344 p.orbit = 0
314345 p.TX, p.TY = x, y
315346 }
316347
348+// Clicking a ship is a declaration, not a shot: both hulls become hostile and the
349+// attacker closes to gun range. Nobody is hostile until someone says so.
350+func (h *hub) engage(p, o *player) {
351+ for c := range h.clients {
352+ if c.p.Foe == p.ID || c.p.Foe == o.ID {
353+ c.p.Foe = 0 // an old pairing ends when a new one starts
354+ }
355+ }
356+ p.Foe, o.Foe, p.chase, p.orbit = o.ID, p.ID, o.ID, 0
357+}
358+
317359 func (h *hub) drag(p *player, x, y float64) {
318360 l := h.looseByID(p.held)
319361 if l == nil || l.held != p.ID {
@@ -461,6 +503,7 @@ func (h *hub) anchor(p *player, b *body) {
461503 a := math.Atan2(p.Y-b.Y, p.X-b.X) // enter the ring on the side we already are on
462504 r := b.R + gap
463505 p.orbit, p.anchored = b.ID, h.time
506+ p.chase = 0 // settling into orbit breaks off any approach order
464507 p.ox, p.oy = b.X+math.Cos(a)*r, b.Y+math.Sin(a)*r
465508 }
466509
@@ -549,6 +592,7 @@ func (h *hub) destroy(p *player, id int) {
549592 // comes back at the spawn in a brand new ship under a new player id, so the client
550593 // snaps there instead of sliding out of its own corpse.
551594 func (h *hub) respawn(p *player) *player {
595+ h.forgive(p.ID) // the run that just ended is nobody's enemy any more
552596 for _, q := range p.Pieces[1:] { // the dead root piece is gone, not salvage
553597 x, y := hullToWorld(p, q.LX, q.LY)
554598 h.loose = append(h.loose, &loose{ID: q.ID, Kind: q.Kind, X: x, Y: y, H: p.H,
@@ -638,6 +682,105 @@ func (p *player) steer(dt float64) {
638682 }
639683 }
640684
685+// A neutral ship never opens fire. Once two hulls are hostile, every triangle that
686+// has the enemy in range fires one round a salvo, and the round has to be flown
687+// into: leaving range or dodging sideways is the whole defence.
688+func (h *hub) guns(p *player, dt float64) {
689+ p.cool = math.Max(0, p.cool-dt)
690+ if p.cool > 0 {
691+ return
692+ }
693+ t := h.foeNear(p)
694+ if t == nil {
695+ return
696+ }
697+ fired := false
698+ for _, q := range p.Pieces {
699+ if q.Kind != "triangle" {
700+ continue // only a gun shoots
701+ }
702+ x, y := hullToWorld(p, q.LX, q.LY)
703+ if math.Hypot(t.X-x, t.Y-y) > gunRange {
704+ continue
705+ }
706+ h.shots = append(h.shots, &shot{ID: h.pieceID(), X: x, Y: y,
707+ H: math.Atan2(t.Y-y, t.X-x), owner: p.ID, left: gunRange})
708+ fired = true
709+ }
710+ if fired {
711+ p.cool = gunCool
712+ }
713+}
714+
715+// The closest ship this hull is hostile with. Rounds hit whatever they touch, so
716+// this only decides who the guns are pointed at.
717+func (h *hub) foeNear(p *player) *player {
718+ var got *player
719+ best := math.MaxFloat64
720+ for c := range h.clients {
721+ o := c.p
722+ if o == p || (p.Foe != o.ID && o.Foe != p.ID) {
723+ continue
724+ }
725+ if d := math.Hypot(o.X-p.X, o.Y-p.Y); d < best {
726+ best, got = d, o
727+ }
728+ }
729+ return got
730+}
731+
732+// A round flies in a straight line and lives for one gun range. A shot that has
733+// gone that far missed, so it leaves the world instead of crossing the system.
734+func (h *hub) stepShots(dt float64) {
735+ live := h.shots[:0]
736+ for _, s := range h.shots {
737+ d := shotSpeed * dt
738+ nx, ny := s.X+math.Cos(s.H)*d, s.Y+math.Sin(s.H)*d
739+ if p, id := h.shotHit(s, nx, ny); p != nil {
740+ h.hurt(p, id)
741+ continue
742+ }
743+ s.X, s.Y, s.left = nx, ny, s.left-d
744+ if s.left > 0 {
745+ live = append(live, s)
746+ }
747+ }
748+ h.shots = live
749+}
750+
751+// A round is checked as the segment it swept this tick, so a fast one can never
752+// tunnel through a piece between two ticks. The first piece on the path takes it.
753+func (h *hub) shotHit(s *shot, nx, ny float64) (*player, int) {
754+ var got *player
755+ id, best := 0, math.MaxFloat64
756+ for c := range h.clients {
757+ p := c.p
758+ if p.ID == s.owner {
759+ continue
760+ }
761+ for _, q := range p.Pieces {
762+ x, y := hullToWorld(p, q.LX, q.LY)
763+ if d, t := segDist(s.X, s.Y, nx, ny, x, y); d < pieceR && t < best {
764+ best, got, id = t, p, q.ID
765+ }
766+ }
767+ }
768+ return got, id
769+}
770+
771+func (h *hub) hurt(p *player, id int) {
772+ for i := range p.Pieces {
773+ if p.Pieces[i].ID != id {
774+ continue
775+ }
776+ p.Pieces[i].HP = math.Max(0, p.Pieces[i].HP-shotDmg)
777+ if p.Pieces[i].HP == 0 {
778+ h.destroy(p, id) // a piece at zero is gone, and takes what hung off it
779+ }
780+ return
781+ }
782+}
783+
641784 func (h *hub) step(dt float64) {
642785 h.time += dt
643786 for _, b := range h.bodies {
@@ -662,9 +805,17 @@ func (h *hub) step(dt float64) {
662805 p.TX = p.ox*cs - p.oy*sn
663806 p.TY = p.ox*sn + p.oy*cs
664807 }
808+ if o := h.player(p.chase); o != nil {
809+ if math.Hypot(o.X-p.X, o.Y-p.Y) > gunRange*approach {
810+ p.TX, p.TY = o.X, o.Y // close in until the guns can reach
811+ } else {
812+ p.TX, p.TY = p.X, p.Y // in range: settle and keep shooting
813+ }
814+ }
665815 p.steer(dt)
666816 h.burn(p, dt)
667817 h.haul(p)
818+ h.guns(p, dt)
668819 p.FuelMax = p.capacity()
669820 h.drive(p, dt)
670821 if b := h.body(p.orbit); b != nil && b.Kind == "shipyard" && p.docked() {
@@ -679,6 +830,7 @@ func (h *hub) step(dt float64) {
679830 c.p = h.respawn(p) // the root piece is the run itself, and so is the tank
680831 }
681832 }
833+ h.stepShots(dt)
682834 }
683835
684836 func oreWait() float64 { return oreWaitMin + rand.Float64()*(oreWaitMax-oreWaitMin) }
@@ -784,7 +936,7 @@ func (h *hub) tick() {
784936 for c := range h.clients {
785937 b, err := json.Marshal(state{
786938 T: "state", You: c.p.ID, Held: c.p.held,
787- Bodies: h.bodies, Loose: h.loose, Ore: h.ore, Players: players,
939+ Bodies: h.bodies, Loose: h.loose, Ore: h.ore, Shots: h.shots, Players: players,
788940 })
789941 if err == nil {
790942 out[c] = b
@@ -810,6 +962,31 @@ func (h *hub) body(id int) *body {
810962 return nil
811963 }
812964
965+func (h *hub) player(id int) *player {
966+ if id == 0 {
967+ return nil
968+ }
969+ for c := range h.clients {
970+ if c.p.ID == id {
971+ return c.p
972+ }
973+ }
974+ return nil
975+}
976+
977+// A dead or departed ship takes its grudges with it: nobody stays hostile with a
978+// ship that is no longer there.
979+func (h *hub) forgive(id int) {
980+ for c := range h.clients {
981+ if c.p.Foe == id {
982+ c.p.Foe = 0
983+ }
984+ if c.p.chase == id {
985+ c.p.chase = 0
986+ }
987+ }
988+}
989+
813990 func (h *hub) bodyAt(x, y float64) *body {
814991 for _, b := range h.bodies {
815992 if math.Hypot(b.X-x, b.Y-y) < b.R*hitR {
@@ -893,4 +1070,15 @@ func hullToLocal(p *player, x, y float64) (float64, float64) {
8931070
8941071 func wrap(a float64) float64 { return math.Atan2(math.Sin(a), math.Cos(a)) }
8951072
1073+// How far a point lies from a segment, and how far along that segment the closest
1074+// approach is, so the earliest piece on a round's path can be picked.
1075+func segDist(x0, y0, x1, y1, px, py float64) (float64, float64) {
1076+ dx, dy := x1-x0, y1-y0
1077+ t := 0.0
1078+ if l := dx*dx + dy*dy; l > 0 {
1079+ t = math.Max(0, math.Min(1, ((px-x0)*dx+(py-y0)*dy)/l))
1080+ }
1081+ return math.Hypot(x0+t*dx-px, y0+t*dy-py), t
1082+}
1083+
8961084 func finite(f float64) bool { return !math.IsNaN(f) && !math.IsInf(f, 0) }