space-browser / commits / 9d4c3b8
feat: basic AI neural ships
@@ -59,7 +59,7 @@ const targets = (): Target[] => {
5959 });
6060 };
6161 for (const s of ships.values()) {
62- add(s.id, s.id === state?.you ? 'me' : 'ship', 0, s.x, s.y);
62+ add(s.id, s.id === state?.you ? 'me' : s.ai ? 'ai' : 'ship', 0, s.x, s.y);
6363 for (const p of s.pieces) {
6464 const w = toWorld(s, p);
6565 add(p.id, 'piece', s.id, w.x, w.y);
@@ -38,6 +38,7 @@ export type Ship = {
3838 fuel: number; // what is in the tank
3939 fuelmax: number; // capacity, summed from the hull
4040 foe: number; // the ship this one is hostile with, 0 = neutral
41+ ai: boolean; // a server-run hull, so it draws in its own colour
4142 pieces: Piece[];
4243 };
4344
@@ -218,7 +218,7 @@ export class View {
218218 const seen = new Set<number>();
219219 const foe = ships.find((s) => s.id === ownId)?.foe ?? 0;
220220 for (const s of ships) {
221- const role: Role = s.id === ownId ? 'own' : 'other';
221+ const role: Role = s.id === ownId ? 'own' : s.ai ? 'ai' : 'other';
222222 // A ship is an enemy the moment either side has declared it, so the rim can
223223 // never say hostile while the guns say neutral.
224224 const hostile = s.id !== ownId && (s.id === foe || s.foe === ownId);
@@ -6,10 +6,11 @@ import * as THREE from 'three';
66 export const GLYPHS = ' .:-=+*#%@';
77 // 0-7 is the amber ramp used for everything that flies. 8-12 are reserved for
88 // celestial bodies, so a rust planet and a steel planet never read as each other.
9-// 13-14 are damage: a hurt piece can never be mistaken for a healthy one.
9+// 13-14 are damage: a hurt piece can never be mistaken for a healthy one. 15 is
10+// the AI hull: neither the gold of another player nor the red of an enemy.
1011 export const PALETTE = [
1112 0x0c0803, 0x241806, 0x3d2709, 0x57370c, 0x754c11, 0x98631a, 0xc78a20, 0xffe9a8,
12- 0x4a1d0f, 0x9c4f28, 0x1f4453, 0x7fc0d4, 0xfff6dd, 0x7a1512, 0xff4a3d,
13+ 0x4a1d0f, 0x9c4f28, 0x1f4453, 0x7fc0d4, 0xfff6dd, 0x7a1512, 0xff4a3d, 0x5fbf8a,
1314 ];
1415 const ATLAS_CELL = 32;
1516
@@ -8,13 +8,15 @@ import { pieceGeometry, poly } from './shapes';
88 const ORE_R = 6.5; // world radius of an ore piece
99
1010 // A piece is a bright silhouette with a dimmer inset plate, so the cel shading
11-// survives the downsample to cell resolution. Three roles must never read as
12-// each other: your hull is the brightest cream, another player's hull is gold,
13-// and loose wreckage is dim sepia. A piece flips shade the moment it is bolted
14-// on or torn off, and turns red for everyone once it starts taking hits.
11+// survives the downsample to cell resolution. The roles must never read as each
12+// other: your hull is the brightest cream, another player's hull is gold, a
13+// server-run AI hull is green, and loose wreckage is dim sepia. A piece flips
14+// shade the moment it is bolted on or torn off, and turns red for everyone once
15+// it starts taking hits.
1516 const SHADE = {
1617 own: [lum(1, 7), lum(0.5, 7)],
1718 other: [lum(0.8, 6), lum(0.4, 6)],
19+ ai: [lum(0.75, 15), lum(0.35, 15)],
1820 loose: [lum(0.55, 5), lum(0.28, 5)],
1921 ore: [lum(0.95, 6), lum(0.5, 4)], // ore in a planet's ring
2022 towed: [lum(1, 7), lum(0.55, 6)], // ore on someone's line, bright as a hull
@@ -0,0 +1,73 @@
1+package main
2+
3+import (
4+ "math"
5+ "math/rand"
6+ "strconv"
7+)
8+
9+// A passive AI hull: born on a shipyard's ring, it picks an orbit line of its own
10+// and circles the yard. It is nobody's enemy until someone picks a fight with it.
11+func (h *hub) spawnAI(b *body) *player {
12+ a := rand.Float64() * 2 * math.Pi
13+ r := b.R + standoff
14+ h.nextID++
15+ p := &player{ID: h.nextID, Name: "AI" + strconv.Itoa(h.nextID), AI: true, home: b.ID,
16+ X: b.X + math.Cos(a)*r, Y: b.Y + math.Sin(a)*r,
17+ angle: a, ring: r + patrolLow + rand.Float64()*patrolHigh,
18+ spin: patrolSpin * (0.8 + 0.5*rand.Float64())}
19+ if rand.Intn(2) == 0 {
20+ p.spin = -p.spin
21+ }
22+ gun := h.fitted("triangle", 0)
23+ plate := h.fitted("square", 0)
24+ plate.Parent, plate.LX = gun.ID, spacing
25+ other := h.fitted("triangle", 0)
26+ other.Parent, other.LY = gun.ID, spacing
27+ p.Pieces = []piece{gun, plate, other}
28+ p.FuelMax = p.capacity()
29+ p.Fuel = p.FuelMax
30+ return p
31+}
32+
33+// An AI flies its own orbit line around the yard it was born at. The moment it is
34+// hostile with anything it drops the patrol and runs that ship down, and it keeps
35+// running it down until one of the two is dead.
36+func (h *hub) think(p *player, dt float64) {
37+ p.angle += p.spin * dt
38+ if p.Foe != 0 {
39+ p.orbit, p.chase = 0, p.Foe
40+ return // the chase order below flies it into gun range
41+ }
42+ if b := h.body(p.home); b != nil {
43+ p.TX, p.TY = b.X+math.Cos(p.angle)*p.ring, b.Y+math.Sin(p.angle)*p.ring
44+ }
45+}
46+
47+// A wrecked AI leaves its hull in space like anyone else, and its yard births a
48+// replacement after a delay, so a system never runs out of traffic.
49+func (h *hub) bury(p *player) {
50+ h.corpse(p)
51+ for i, q := range h.ai {
52+ if q == p {
53+ h.ai = append(h.ai[:i], h.ai[i+1:]...)
54+ break
55+ }
56+ }
57+ h.grave = append(h.grave, &grave{home: p.home, wait: aiDelay})
58+}
59+
60+// Graves count down, then birth a new hull in the same shipyard's orbit.
61+func (h *hub) stepAI(dt float64) {
62+ live := h.grave[:0]
63+ for _, g := range h.grave {
64+ if g.wait -= dt; g.wait > 0 {
65+ live = append(live, g)
66+ continue
67+ }
68+ if b := h.body(g.home); b != nil {
69+ h.ai = append(h.ai, h.spawnAI(b))
70+ }
71+ }
72+ h.grave = live
73+}
@@ -37,8 +37,7 @@ func (h *hub) guns(p *player, dt float64) {
3737 func (h *hub) foeNear(p *player) *player {
3838 var got *player
3939 best := math.MaxFloat64
40- for c := range h.clients {
41- o := c.p
40+ for _, o := range h.players() {
4241 if o == p || (p.Foe != o.ID && o.Foe != p.ID) {
4342 continue
4443 }
@@ -73,8 +72,7 @@ func (h *hub) stepShots(dt float64) {
7372 func (h *hub) shotHit(s *shot, nx, ny float64) (*player, int) {
7473 var got *player
7574 id, best := 0, math.MaxFloat64
76- for c := range h.clients {
77- p := c.p
75+ for _, p := range h.players() {
7876 if p.ID == s.owner {
7977 continue
8078 }
@@ -110,11 +110,7 @@ func (h *hub) destroy(p *player, id int) {
110110 // comes back at the spawn in a brand new ship under a new player id, so the client
111111 // snaps there instead of sliding out of its own corpse.
112112 func (h *hub) respawn(p *player) *player {
113- h.forgive(p.ID) // the run that just ended is nobody's enemy any more
114- for _, q := range p.Pieces[1:] { // the dead root piece is gone, not salvage
115- h.loose = append(h.loose, h.wreck(p, q))
116- }
117- h.abandon(p)
113+ h.corpse(p)
118114 h.nextID++
119115 q := &player{ID: h.nextID, Name: p.Name, // the callsign outlives the ship
120116 X: spawnX, Y: spawnY, TX: spawnX, TY: spawnY}
@@ -124,6 +120,16 @@ func (h *hub) respawn(p *player) *player {
124120 return q
125121 }
126122
123+// A dead hull leaves everything but its root piece where it died, its tow line
124+// goes slack, and the run that just ended is nobody's enemy any more.
125+func (h *hub) corpse(p *player) {
126+ h.forgive(p.ID)
127+ for _, q := range p.Pieces[1:] { // the dead root piece is gone, not salvage
128+ h.loose = append(h.loose, h.wreck(p, q))
129+ }
130+ h.abandon(p)
131+}
132+
127133 // Snap a dropped piece onto the free slot closest to where it was let go.
128134 func (h *hub) attach(p *player, l *loose) bool {
129135 lx, ly := hullToLocal(p, l.X, l.Y)
@@ -21,9 +21,9 @@ func (h *hub) pick(p *player, x, y float64) {
2121 return
2222 }
2323 }
24- for c := range h.clients {
25- if c.p != p && hullPieceAt(c.p, x, y) != 0 {
26- h.engage(p, c.p)
24+ for _, o := range h.players() {
25+ if o != p && hullPieceAt(o, x, y) != 0 {
26+ h.engage(p, o)
2727 return
2828 }
2929 }
@@ -39,9 +39,9 @@ func (h *hub) pick(p *player, x, y float64) {
3939 // Clicking a ship is a declaration, not a shot: both hulls become hostile and the
4040 // attacker closes to gun range. Nobody is hostile until someone says so.
4141 func (h *hub) engage(p, o *player) {
42- for c := range h.clients {
43- if c.p.Foe == p.ID || c.p.Foe == o.ID {
44- c.p.Foe = 0 // an old pairing ends when a new one starts
42+ for _, q := range h.players() {
43+ if q.Foe == p.ID || q.Foe == o.ID {
44+ q.Foe = 0 // an old pairing ends when a new one starts
4545 }
4646 }
4747 p.Foe, o.Foe, p.chase, p.orbit = o.ID, p.ID, o.ID, 0
@@ -68,6 +68,9 @@ func (h *hub) drop(p *player, x, y float64) {
6868 // Flying over ore hooks it onto the line: no clicks and nothing to decide. The
6969 // line only takes what the hull can haul, so a full ship flies past the rest.
7070 func (h *hub) haul(p *player) {
71+ if p.AI {
72+ return // an AI carries nothing: ore only ever moves between players
73+ }
7174 for _, o := range h.ore {
7275 if len(p.tow) >= p.towLimit() {
7376 return
@@ -121,6 +124,9 @@ func (p *player) capacity() float64 {
121124 // ship settled in orbit is carried by the body for free. A docked shipyard fills
122125 // the tank back up for free.
123126 func (h *hub) drive(p *player, dt float64) {
127+ if p.AI {
128+ return // an AI never leaves its system, so range is not a thing it plays
129+ }
124130 if p.orbit != 0 && p.docked() {
125131 if b := h.body(p.orbit); b != nil && b.Kind == "shipyard" {
126132 p.Fuel = math.Min(p.FuelMax, p.Fuel+refuel*dt)
@@ -2,13 +2,14 @@ package main
22
33 import "math"
44
5-// Every ship in the world. The caller holds the lock.
5+// Every ship in the world, connected players and server-run AI alike. The caller
6+// holds the lock.
67 func (h *hub) players() []*player {
7- players := make([]*player, 0, len(h.clients))
8+ players := make([]*player, 0, len(h.clients)+len(h.ai))
89 for c := range h.clients {
910 players = append(players, c.p)
1011 }
11- return players
12+ return append(players, h.ai...)
1213 }
1314
1415 func (h *hub) body(id int) *body {
@@ -29,18 +30,23 @@ func (h *hub) player(id int) *player {
2930 return c.p
3031 }
3132 }
33+ for _, p := range h.ai {
34+ if p.ID == id {
35+ return p
36+ }
37+ }
3238 return nil
3339 }
3440
3541 // A dead or departed ship takes its grudges with it: nobody stays hostile with a
3642 // ship that is no longer there.
3743 func (h *hub) forgive(id int) {
38- for c := range h.clients {
39- if c.p.Foe == id {
40- c.p.Foe = 0
44+ for _, p := range h.players() {
45+ if p.Foe == id {
46+ p.Foe = 0
4147 }
42- if c.p.chase == id {
43- c.p.chase = 0
48+ if p.chase == id {
49+ p.chase = 0
4450 }
4551 }
4652 }
@@ -38,6 +38,17 @@ func newHub() *hub {
3838 {ID: 2, Kind: "shipyard", R: 20, orbit: 120, a0: -1.57, speed: 0.06},
3939 {ID: 3, Kind: "barren", R: 28, orbit: 215, a0: 0.6, speed: 0.035, wait: oreWait(), cap: oreHolds + rand.Intn(4)},
4040 }
41+ // Place the bodies before anything is born around them, then fill every yard
42+ // with its passive AI traffic.
43+ for _, b := range h.bodies {
44+ b.place(0)
45+ if b.Kind != "shipyard" {
46+ continue
47+ }
48+ for i := 0; i < aiPerYard; i++ {
49+ h.ai = append(h.ai, h.spawnAI(b))
50+ }
51+ }
4152 // Wreckage around the spawn, to build a first hull out of.
4253 for i, k := range []string{"square", "circle", "star", "triangle"} {
4354 h.loose = append(h.loose, h.debris(k, 0,
@@ -34,8 +34,7 @@ func (p *player) steer(dt float64) {
3434 func (h *hub) step(dt float64) {
3535 h.time += dt
3636 for _, b := range h.bodies {
37- a := b.a0 + b.speed*h.time
38- b.X, b.Y = math.Cos(a)*b.orbit, math.Sin(a)*b.orbit
37+ b.place(h.time)
3938 if b.Kind != "barren" {
4039 continue
4140 }
@@ -47,8 +46,10 @@ func (h *hub) step(dt float64) {
4746 for _, o := range h.ore {
4847 h.stepOre(o, dt)
4948 }
50- for c := range h.clients {
51- p := c.p
49+ for _, p := range h.players() { // every hull, connected or not
50+ if p.AI {
51+ h.think(p, dt) // patrol a yard, or run down whoever it is fighting
52+ }
5253 if b := h.body(p.orbit); b != nil {
5354 d := b.speed * (h.time - p.anchored)
5455 cs, sn := math.Cos(d), math.Sin(d)
@@ -77,10 +78,27 @@ func (h *hub) step(dt float64) {
7778 }
7879 }
7980 if p.Pieces[0].HP == 0 || p.Fuel == 0 {
80- c.p = h.respawn(p) // the root piece is the run itself, and so is the tank
81+ h.die(p) // the root piece is the run itself, and so is the tank
8182 }
8283 }
8384 h.stepShots(dt)
85+ h.stepAI(dt)
86+}
87+
88+// A root piece at zero, or a dry tank, ends that hull. A player is replaced at
89+// once under a new id, so the client snaps there; an AI leaves a wreck and comes
90+// back to its own shipyard after a delay.
91+func (h *hub) die(p *player) {
92+ if p.AI {
93+ h.bury(p)
94+ return
95+ }
96+ for c := range h.clients {
97+ if c.p == p {
98+ c.p = h.respawn(p)
99+ return
100+ }
101+ }
84102 }
85103
86104 func (h *hub) tick() {
@@ -1,6 +1,7 @@
11 package main
22
33 import (
4+ "math"
45 "sync"
56
67 "github.com/gorilla/websocket"
@@ -47,6 +48,12 @@ const (
4748 fuelPer = 900.0 // world units of travel one unit of fuel buys
4849 refuel = 1.0 // fuel a second a docked shipyard puts back in the tank
4950
51+ aiPerYard = 2 // passive AI ships a shipyard keeps in orbit
52+ aiDelay = 25.0 // seconds after an AI death before that yard births another
53+ patrolSpin = 0.18 // radians a second an AI circles its yard on patrol
54+ patrolLow = 6.0 // the tightest patrol line sits this far beyond the standoff
55+ patrolHigh = 30.0 // and the widest this much further out again
56+
5057 gunRange = 140.0 // world distance a triangle will shoot at
5158 gunCool = 1.6 // seconds between salvos from one hull
5259 shotSpeed = 150.0 // a round is faster than a ship, so range alone is not safety
@@ -124,6 +131,13 @@ type body struct {
124131 cap int // how many ore this barren planet keeps in orbit
125132 }
126133
134+// A body's place is a pure function of world time: planets revolve, and the star
135+// (orbit 0) never moves.
136+func (b *body) place(t float64) {
137+ a := b.a0 + b.speed*t
138+ b.X, b.Y = math.Cos(a)*b.orbit, math.Sin(a)*b.orbit
139+}
140+
127141 type player struct {
128142 ID int `json:"id"`
129143 Name string `json:"name"`
@@ -135,9 +149,14 @@ type player struct {
135149 Pieces []piece `json:"pieces"`
136150 Fuel float64 `json:"fuel"` // what is in the tank, spent by flying
137151 FuelMax float64 `json:"fuelmax"` // capacity, summed from the hull every tick
138- Foe int `json:"foe"` // player this ship is hostile with, 0 = neutral
139-
140- chase int // player this ship was ordered to close on, 0 = no order
152+ Foe int `json:"foe"` // ship this one is hostile with, 0 = neutral
153+ AI bool `json:"ai"` // a server-run hull, not a connection
154+
155+ home int // shipyard body an AI was born at, and comes back to
156+ angle float64 // AI patrol angle around that yard
157+ ring float64 // AI patrol radius around it
158+ spin float64 // AI patrol angular speed, negative for the other way round
159+ chase int // ship this one was ordered to close on, 0 = no order
141160 cool float64 // seconds until the guns can fire again
142161 vx, vy float64
143162 orbit int // body the ship is anchored to, 0 = none
@@ -153,6 +172,12 @@ type client struct {
153172 p *player
154173 }
155174
175+// A wrecked AI is gone for a while, then its shipyard births a replacement.
176+type grave struct {
177+ home int
178+ wait float64
179+}
180+
156181 type hub struct {
157182 mu sync.Mutex
158183 clients map[*client]bool
@@ -161,6 +186,8 @@ type hub struct {
161186 loose []*loose
162187 ore []*ore
163188 shots []*shot
189+ ai []*player // server-run hulls, tracked whether or not anyone is connected
190+ grave []*grave
164191 nextPiece int
165192 time float64
166193 }