space-browser / commits / 6090b9f
chore: refactor main.go into multiple files with separate concerns
This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.
@@ -0,0 +1,40 @@
1+package main
2+
3+import "math"
4+
5+func hullPieceAt(p *player, x, y float64) int {
6+ id, best := 0, grabR
7+ for _, q := range p.Pieces {
8+ wx, wy := hullToWorld(p, q.LX, q.LY)
9+ if d := math.Hypot(wx-x, wy-y); d < best {
10+ best, id = d, q.ID
11+ }
12+ }
13+ return id
14+}
15+
16+func hullToWorld(p *player, lx, ly float64) (float64, float64) {
17+ c, s := math.Cos(p.H), math.Sin(p.H)
18+ return p.X + lx*c - ly*s, p.Y + lx*s + ly*c
19+}
20+
21+func hullToLocal(p *player, x, y float64) (float64, float64) {
22+ c, s := math.Cos(p.H), math.Sin(p.H)
23+ dx, dy := x-p.X, y-p.Y
24+ return dx*c + dy*s, -dx*s + dy*c
25+}
26+
27+func wrap(a float64) float64 { return math.Atan2(math.Sin(a), math.Cos(a)) }
28+
29+// How far a point lies from a segment, and how far along that segment the closest
30+// approach is, so the earliest piece on a round's path can be picked.
31+func segDist(x0, y0, x1, y1, px, py float64) (float64, float64) {
32+ dx, dy := x1-x0, y1-y0
33+ t := 0.0
34+ if l := dx*dx + dy*dy; l > 0 {
35+ t = math.Max(0, math.Min(1, ((px-x0)*dx+(py-y0)*dy)/l))
36+ }
37+ return math.Hypot(x0+t*dx-px, y0+t*dy-py), t
38+}
39+
40+func finite(f float64) bool { return !math.IsNaN(f) && !math.IsInf(f, 0) }
@@ -0,0 +1,102 @@
1+package main
2+
3+import "math"
4+
5+// A neutral ship never opens fire. Once two hulls are hostile, every triangle that
6+// has the enemy in range fires one round a salvo, and the round has to be flown
7+// into: leaving range or dodging sideways is the whole defence.
8+func (h *hub) guns(p *player, dt float64) {
9+ p.cool = math.Max(0, p.cool-dt)
10+ if p.cool > 0 {
11+ return
12+ }
13+ t := h.foeNear(p)
14+ if t == nil {
15+ return
16+ }
17+ fired := false
18+ for _, q := range p.Pieces {
19+ if q.Kind != "triangle" {
20+ continue // only a gun shoots
21+ }
22+ x, y := hullToWorld(p, q.LX, q.LY)
23+ if math.Hypot(t.X-x, t.Y-y) > gunRange {
24+ continue
25+ }
26+ h.shots = append(h.shots, &shot{ID: h.pieceID(), X: x, Y: y,
27+ H: math.Atan2(t.Y-y, t.X-x), owner: p.ID, left: gunRange})
28+ fired = true
29+ }
30+ if fired {
31+ p.cool = gunCool
32+ }
33+}
34+
35+// The closest ship this hull is hostile with. Rounds hit whatever they touch, so
36+// this only decides who the guns are pointed at.
37+func (h *hub) foeNear(p *player) *player {
38+ var got *player
39+ best := math.MaxFloat64
40+ for c := range h.clients {
41+ o := c.p
42+ if o == p || (p.Foe != o.ID && o.Foe != p.ID) {
43+ continue
44+ }
45+ if d := math.Hypot(o.X-p.X, o.Y-p.Y); d < best {
46+ best, got = d, o
47+ }
48+ }
49+ return got
50+}
51+
52+// A round flies in a straight line and lives for one gun range. A shot that has
53+// gone that far missed, so it leaves the world instead of crossing the system.
54+func (h *hub) stepShots(dt float64) {
55+ live := h.shots[:0]
56+ for _, s := range h.shots {
57+ d := shotSpeed * dt
58+ nx, ny := s.X+math.Cos(s.H)*d, s.Y+math.Sin(s.H)*d
59+ if p, id := h.shotHit(s, nx, ny); p != nil {
60+ h.hurt(p, id)
61+ continue
62+ }
63+ s.X, s.Y, s.left = nx, ny, s.left-d
64+ if s.left > 0 {
65+ live = append(live, s)
66+ }
67+ }
68+ h.shots = live
69+}
70+
71+// A round is checked as the segment it swept this tick, so a fast one can never
72+// tunnel through a piece between two ticks. The first piece on the path takes it.
73+func (h *hub) shotHit(s *shot, nx, ny float64) (*player, int) {
74+ var got *player
75+ id, best := 0, math.MaxFloat64
76+ for c := range h.clients {
77+ p := c.p
78+ if p.ID == s.owner {
79+ continue
80+ }
81+ for _, q := range p.Pieces {
82+ x, y := hullToWorld(p, q.LX, q.LY)
83+ if d, t := segDist(s.X, s.Y, nx, ny, x, y); d < pieceR && t < best {
84+ best, got, id = t, p, q.ID
85+ }
86+ }
87+ }
88+ return got, id
89+}
90+
91+func (h *hub) hurt(p *player, id int) {
92+ for i := range p.Pieces {
93+ if p.Pieces[i].ID != id {
94+ continue
95+ }
96+ p.Pieces[i].HP = math.Max(0, p.Pieces[i].HP-shotDmg)
97+ if p.Pieces[i].HP == 0 {
98+ h.destroy(p, id) // a piece at zero is gone, and takes what hung off it
99+ }
100+ return
101+ }
102+}
@@ -0,0 +1,169 @@
1+package main
2+
3+import (
4+ "math"
5+ "sort"
6+)
7+
8+// Parking on a body bolts the target to that body's frame: the ring point turns
9+// with the planet around its star, so the ship is carried along.
10+func (h *hub) anchor(p *player, b *body) {
11+ gap := standoff
12+ if b.Kind == "star" {
13+ gap = starGap
14+ }
15+ a := math.Atan2(p.Y-b.Y, p.X-b.X) // enter the ring on the side we already are on
16+ r := b.R + gap
17+ p.orbit, p.anchored = b.ID, h.time
18+ p.chase = 0 // settling into orbit breaks off any approach order
19+ p.ox, p.oy = b.X+math.Cos(a)*r, b.Y+math.Sin(a)*r
20+}
21+
22+// Torn-off pieces keep the ids they had, so a piece never becomes a new thing by
23+// being ripped off a hull.
24+func (h *hub) detach(p *player, id int) []*loose {
25+ if len(p.Pieces) < 2 || p.Pieces[0].ID == id {
26+ return nil
27+ }
28+ return h.sever(p, map[int]bool{id: true})
29+}
30+
31+// Anything no longer connected to the root piece drifts off, carrying the damage
32+// it had taken with it.
33+func (h *hub) sever(p *player, gone map[int]bool) []*loose {
34+ for grew := true; grew; {
35+ grew = false
36+ for _, q := range p.Pieces {
37+ if !gone[q.ID] && gone[q.Parent] {
38+ gone[q.ID], grew = true, true
39+ }
40+ }
41+ }
42+ var off []*loose
43+ keep := p.Pieces[:0]
44+ for _, q := range p.Pieces {
45+ if !gone[q.ID] {
46+ keep = append(keep, q)
47+ continue
48+ }
49+ off = append(off, h.wreck(p, q))
50+ }
51+ p.Pieces = keep
52+ return off
53+}
54+
55+// A piece torn off a hull keeps its identity, its damage and its tier, and lands in
56+// space where the hull was holding it.
57+func (h *hub) wreck(p *player, q piece) *loose {
58+ x, y := hullToWorld(p, q.LX, q.LY)
59+ return &loose{ID: q.ID, Kind: q.Kind, X: x, Y: y, H: p.H, HP: q.HP, MaxHP: q.MaxHP, Tier: q.Tier}
60+}
61+
62+// A star is not instant death: its heat eats whatever of the hull actually enters
63+// it, so brushing the limb costs armour and lingering costs the run. A piece is hit
64+// by its own outline, not the ship's centre, so a big rig can lose an outer piece
65+// while the root stays clear.
66+func (h *hub) burn(p *player, dt float64) {
67+ var dead []int
68+ for i := range p.Pieces {
69+ q := &p.Pieces[i]
70+ x, y := hullToWorld(p, q.LX, q.LY)
71+ if !h.hot(x, y) {
72+ continue
73+ }
74+ q.HP = math.Max(0, q.HP-burn*dt)
75+ if q.HP == 0 {
76+ dead = append(dead, q.ID)
77+ }
78+ }
79+ for _, id := range dead {
80+ h.destroy(p, id) // the dead piece and whatever only it held on
81+ }
82+}
83+
84+// A point is hot once it sits past a star's surface, with a piece's own girth
85+// taken into account, so only real overlap burns.
86+func (h *hub) hot(x, y float64) bool {
87+ for _, b := range h.bodies {
88+ if b.Kind == "star" && math.Hypot(b.X-x, b.Y-y) < b.R+pieceR {
89+ return true
90+ }
91+ }
92+ return false
93+}
94+
95+// A piece at zero hit points is destroyed for good: the hull loses it, and
96+// whatever it was the only link to breaks off as wreckage.
97+func (h *hub) destroy(p *player, id int) {
98+ if len(p.Pieces) < 2 || p.Pieces[0].ID == id {
99+ return // the root piece is the run itself
100+ }
101+ for _, l := range h.sever(p, map[int]bool{id: true}) {
102+ if l.ID != id {
103+ h.loose = append(h.loose, l) // the dead piece is gone, not salvage
104+ }
105+ }
106+}
107+
108+// Losing the root piece ends that life. Everything still bolted to the hull is left
109+// where the ship died as loose wreckage, the tow line goes slack, and the callsign
110+// comes back at the spawn in a brand new ship under a new player id, so the client
111+// snaps there instead of sliding out of its own corpse.
112+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)
118+ h.nextID++
119+ q := &player{ID: h.nextID, Name: p.Name, // the callsign outlives the ship
120+ X: spawnX, Y: spawnY, TX: spawnX, TY: spawnY}
121+ q.Pieces = []piece{h.fitted("triangle", 0)} // every life starts from one triangle
122+ q.FuelMax = q.capacity()
123+ q.Fuel = q.FuelMax
124+ return q
125+}
126+
127+// Snap a dropped piece onto the free slot closest to where it was let go.
128+func (h *hub) attach(p *player, l *loose) bool {
129+ lx, ly := hullToLocal(p, l.X, l.Y)
130+ dist := func(q piece) float64 { return math.Hypot(q.LX-lx, q.LY-ly) }
131+ near := append([]piece(nil), p.Pieces...)
132+ sort.Slice(near, func(i, j int) bool { return dist(near[i]) < dist(near[j]) })
133+ if dist(near[0]) > spacing*1.5 {
134+ return false // not dropped on the hull
135+ }
136+ for _, q := range near {
137+ slot, best := -1, math.MaxFloat64
138+ for i := 0; i < slots; i++ {
139+ a := float64(i) / slots * 2 * math.Pi
140+ x, y := q.LX+math.Cos(a)*spacing, q.LY+math.Sin(a)*spacing
141+ taken := false
142+ for _, r := range p.Pieces {
143+ if math.Hypot(r.LX-x, r.LY-y) < spacing*0.5 {
144+ taken = true
145+ break
146+ }
147+ }
148+ if taken {
149+ continue // slot is occupied
150+ }
151+ if d := math.Abs(wrap(a - math.Atan2(ly-q.LY, lx-q.LX))); d < best {
152+ slot, best = i, d
153+ }
154+ }
155+ if slot < 0 {
156+ continue // piece is surrounded, try the next one out
157+ }
158+ a := float64(slot) / slots * 2 * math.Pi
159+ p.Pieces = append(p.Pieces, piece{
160+ ID: l.ID, Kind: l.Kind, Parent: q.ID,
161+ LX: q.LX + math.Cos(a)*spacing,
162+ LY: q.LY + math.Sin(a)*spacing,
163+ HP: l.HP, MaxHP: l.MaxHP, Tier: l.Tier,
164+ })
165+ h.removeLoose(l.ID)
166+ return true
167+ }
168+ return false
169+}
@@ -0,0 +1,199 @@
1+package main
2+
3+import (
4+ "math"
5+ "math/rand"
6+)
7+
8+// A click is resolved by the server: grab a piece, tear one off, engage a ship,
9+// park on a body, or fly to a point. The client never decides which happened.
10+func (h *hub) pick(p *player, x, y float64) {
11+ if l := h.freeLooseAt(x, y); l != nil {
12+ p.held, l.held = l.ID, p.ID
13+ return
14+ }
15+ if id := hullPieceAt(p, x, y); id != 0 {
16+ if off := h.detach(p, id); len(off) > 0 {
17+ h.loose = append(h.loose, off...)
18+ if l := h.looseByID(id); l != nil {
19+ p.held, l.held = id, p.ID
20+ }
21+ return
22+ }
23+ }
24+ for c := range h.clients {
25+ if c.p != p && hullPieceAt(c.p, x, y) != 0 {
26+ h.engage(p, c.p)
27+ return
28+ }
29+ }
30+ if b := h.bodyAt(x, y); b != nil {
31+ h.anchor(p, b)
32+ return
33+ }
34+ p.chase = 0 // any other order takes the ship off its approach
35+ p.orbit = 0
36+ p.TX, p.TY = x, y
37+}
38+
39+// Clicking a ship is a declaration, not a shot: both hulls become hostile and the
40+// attacker closes to gun range. Nobody is hostile until someone says so.
41+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
45+ }
46+ }
47+ p.Foe, o.Foe, p.chase, p.orbit = o.ID, p.ID, o.ID, 0
48+}
49+
50+func (h *hub) drag(p *player, x, y float64) {
51+ l := h.looseByID(p.held)
52+ if l == nil || l.held != p.ID {
53+ return
54+ }
55+ l.X, l.Y = x, y
56+}
57+
58+func (h *hub) drop(p *player, x, y float64) {
59+ l := h.looseByID(p.held)
60+ if l == nil {
61+ return
62+ }
63+ p.held, l.held = 0, 0
64+ l.X, l.Y = x, y
65+ h.attach(p, l)
66+}
67+
68+// Flying over ore hooks it onto the line: no clicks and nothing to decide. The
69+// line only takes what the hull can haul, so a full ship flies past the rest.
70+func (h *hub) haul(p *player) {
71+ for _, o := range h.ore {
72+ if len(p.tow) >= p.towLimit() {
73+ return
74+ }
75+ if o.Towed != 0 || math.Hypot(p.X-o.X, p.Y-o.Y) > oreTouch {
76+ continue
77+ }
78+ o.Towed, o.planet = p.ID, 0 // off the ring and onto the line
79+ p.tow = append(p.tow, o.ID)
80+ }
81+}
82+
83+func (p *player) release(o *ore) {
84+ o.Towed = 0
85+ for i, id := range p.tow {
86+ if id == o.ID {
87+ p.tow = append(p.tow[:i], p.tow[i+1:]...)
88+ return
89+ }
90+ }
91+}
92+
93+func (p *player) towLimit() int {
94+ n := towBase
95+ for _, q := range p.Pieces {
96+ if q.Kind == "circle" {
97+ n += towPer
98+ }
99+ }
100+ return n
101+}
102+
103+// Docked means the ship has actually settled on its ring point, not that it is
104+// still crossing the system toward it: a yard only serves a ship that stopped.
105+func (p *player) docked() bool {
106+ return math.Hypot(p.X-p.TX, p.Y-p.TY) < dockR
107+}
108+
109+// Fuel capacity is summed from the hull: every piece carries a little and the
110+// star carries most of it, so range is a decision about what you bolt on.
111+func (p *player) capacity() float64 {
112+ f := 0.0
113+ for _, q := range p.Pieces {
114+ _, u := stats(q.Kind, q.Tier)
115+ f += u
116+ }
117+ return f
118+}
119+
120+// Fuel is spent by the distance flown, so a stopped ship spends nothing, and a
121+// ship settled in orbit is carried by the body for free. A docked shipyard fills
122+// the tank back up for free.
123+func (h *hub) drive(p *player, dt float64) {
124+ if p.orbit != 0 && p.docked() {
125+ if b := h.body(p.orbit); b != nil && b.Kind == "shipyard" {
126+ p.Fuel = math.Min(p.FuelMax, p.Fuel+refuel*dt)
127+ }
128+ return
129+ }
130+ p.Fuel = math.Max(0, p.Fuel-math.Hypot(p.vx, p.vy)*dt/fuelPer)
131+}
132+
133+// A shipyard services one load of ore at a time: three ore patch the whole hull
134+// up, and once nothing is damaged the load buys a tier on a random piece that can
135+// still take one. A whole, fully upgraded ship has nothing to buy, so it keeps
136+// its ore and the yard does not fire.
137+func (h *hub) service(p *player) bool {
138+ hurt := false
139+ for i, q := range p.Pieces {
140+ if q.HP < q.MaxHP {
141+ hurt = true
142+ p.Pieces[i].HP = q.MaxHP
143+ }
144+ }
145+ if hurt {
146+ return true // repair first: a wreck is worth nothing upgraded
147+ }
148+ var open []int
149+ for i, q := range p.Pieces {
150+ if q.Tier < maxTier {
151+ open = append(open, i)
152+ }
153+ }
154+ if len(open) == 0 {
155+ return false
156+ }
157+ q := &p.Pieces[open[rand.Intn(len(open))]]
158+ q.Tier++
159+ q.MaxHP, _ = stats(q.Kind, q.Tier)
160+ q.HP = q.MaxHP // a yard upgrade comes out whole
161+ return true
162+}
163+
164+// Ore handed over leaves the world with the line: the yard keeps it.
165+func (h *hub) spend(p *player) {
166+ for i := 0; i < yardOre && len(p.tow) > 0; i++ {
167+ o := h.oreByID(p.tow[0])
168+ if o == nil {
169+ p.tow = p.tow[1:] // an ore that is already gone can never stall the yard
170+ continue
171+ }
172+ p.release(o)
173+ h.removeOre(o.ID)
174+ }
175+}
176+
177+// Whatever the ship was dragging stays where it was: a dead or departed hull takes
178+// nothing with it.
179+func (h *hub) abandon(p *player) {
180+ for _, id := range p.tow {
181+ if o := h.oreByID(id); o != nil {
182+ o.Towed = 0 // the line goes slack where the ship stopped
183+ }
184+ }
185+ if l := h.looseByID(p.held); l != nil {
186+ l.held = 0
187+ }
188+}
189+
190+// A ship in orbit of a shipyard keeps handing over loads as long as it has
191+// enough ore on the line, one load a second so the yard can be watched working.
192+func (h *hub) yard(p *player, dt float64) {
193+ p.yard = math.Max(0, p.yard-dt)
194+ if p.yard > 0 || len(p.tow) < yardOre || !h.service(p) {
195+ return
196+ }
197+ h.spend(p)
198+ p.yard = yardGap
199+}
@@ -0,0 +1,105 @@
1+package main
2+
3+import "math"
4+
5+// Every ship in the world. The caller holds the lock.
6+func (h *hub) players() []*player {
7+ players := make([]*player, 0, len(h.clients))
8+ for c := range h.clients {
9+ players = append(players, c.p)
10+ }
11+ return players
12+}
13+
14+func (h *hub) body(id int) *body {
15+ for _, b := range h.bodies {
16+ if b.ID == id {
17+ return b
18+ }
19+ }
20+ return nil
21+}
22+
23+func (h *hub) player(id int) *player {
24+ if id == 0 {
25+ return nil
26+ }
27+ for c := range h.clients {
28+ if c.p.ID == id {
29+ return c.p
30+ }
31+ }
32+ return nil
33+}
34+
35+// A dead or departed ship takes its grudges with it: nobody stays hostile with a
36+// ship that is no longer there.
37+func (h *hub) forgive(id int) {
38+ for c := range h.clients {
39+ if c.p.Foe == id {
40+ c.p.Foe = 0
41+ }
42+ if c.p.chase == id {
43+ c.p.chase = 0
44+ }
45+ }
46+}
47+
48+func (h *hub) bodyAt(x, y float64) *body {
49+ for _, b := range h.bodies {
50+ if math.Hypot(b.X-x, b.Y-y) < b.R*hitR {
51+ return b
52+ }
53+ }
54+ return nil
55+}
56+
57+func (h *hub) looseByID(id int) *loose {
58+ for _, l := range h.loose {
59+ if l.ID == id {
60+ return l
61+ }
62+ }
63+ return nil
64+}
65+
66+func (h *hub) freeLooseAt(x, y float64) *loose {
67+ var got *loose
68+ best := grabR
69+ for _, l := range h.loose {
70+ if l.held != 0 {
71+ continue
72+ }
73+ if d := math.Hypot(l.X-x, l.Y-y); d < best {
74+ best, got = d, l
75+ }
76+ }
77+ return got
78+}
79+
80+func (h *hub) oreByID(id int) *ore {
81+ for _, o := range h.ore {
82+ if o.ID == id {
83+ return o
84+ }
85+ }
86+ return nil
87+}
88+
89+func (h *hub) removeLoose(id int) {
90+ for i, l := range h.loose {
91+ if l.ID == id {
92+ h.loose = append(h.loose[:i], h.loose[i+1:]...)
93+ return
94+ }
95+ }
96+}
97+
98+func (h *hub) removeOre(id int) {
99+ for i, o := range h.ore {
100+ if o.ID == id {
101+ h.ore = append(h.ore[:i], h.ore[i+1:]...)
102+ return
103+ }
104+ }
105+}
@@ -1,3 +1,7 @@
1+// The server owns everything a client draws: celestial bodies, ships, hulls and
2+// loose pieces. Clients send intents (pick, drag, drop) and render the state
3+// they are handed.
4+
15 package main
26
37 import (
@@ -7,188 +11,11 @@ import (
711 "math"
812 "math/rand"
913 "net/http"
10- "sort"
1114 "strconv"
12- "sync"
13- "time"
1415
1516 "github.com/gorilla/websocket"
1617 )
1718
18-// The server owns everything a client draws: celestial bodies, ships, hulls and
19-// loose pieces. Clients send intents (pick, drag, drop) and render the state
20-// they are handed.
21-
22-const (
23- tickRate = 20
24- tickDt = 1.0 / tickRate
25-
26- starR = 30.0
27- standoff = 26.0 // ring radius beyond a planet's surface
28- starGap = 34.0 // a star kills on contact, so its ring sits further out
29- hitR = 1.5 // click radius of a body, as a multiple of its radius
30- grabR = 13.0 // world radius to pick a piece up
31- spacing = 17.0 // world distance between attached piece centers
32- slots = 6 // attachment directions around a hull piece
33- maxSpeed = 90.0
34- accel = 260.0
35- arrive = 2.2 // slowdown radius factor
36- spawnX = 0.0
37- spawnY = -70.0
38- reach = 4000.0 // an order further out than this is ignored
39-
40- oreGap = 15.0 // closest two ore may sit: also the spacing of the rings
41- oreRings = 4 // rings a barren planet can park ore on
42- oreRingMin = 12.0 // first ring's distance beyond the surface
43- oreBrake = 10.0 // outward deceleration, so a launch coasts out then parks
44- oreOrbitV = 12.0 // world units per second travelled along a ring
45- oreTouch = 14.0 // flying this close to ore hooks it onto the line
46- towGap = 12.0 // distance between ore on a tow line
47- oreWaitMin = 30.0 // a barren planet throws an ore every 30-60s
48- oreWaitMax = 60.0
49- oreHolds = 3 // a barren planet holds 3-6 ore, a fixed count per planet
50-
51- pieceR = 11.0 // world radius of a piece, for star heat overlap
52- burn = 5.0 // hit points a second a piece loses inside a star
53- dockR = 8.0 // the ship counts as docked inside this of its ring point
54- towBase = 3 // ore a hull can haul with no circle at all
55- towPer = 3 // extra ore each circle adds to the line
56- maxTier = 2 // a piece can be upgraded twice
57- yardOre = 3 // ore a shipyard takes for one service
58- yardGap = 1.0 // seconds between services, so a full line drains visibly
59-
60- fuelPer = 900.0 // world units of travel one unit of fuel buys
61- 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
68-)
69-
70-// A hull is a graph of pieces placed relative to the ship. Piece ids are unique
71-// across the whole world, so a piece can be torn off one hull and bolted to
72-// another without ever changing identity.
73-type piece struct {
74- ID int `json:"id"`
75- Kind string `json:"kind"`
76- LX float64 `json:"lx"`
77- LY float64 `json:"ly"`
78- Parent int `json:"parent"`
79- HP float64 `json:"hp"`
80- MaxHP float64 `json:"maxhp"`
81- Tier int `json:"tier"`
82-}
83-
84-type loose struct {
85- ID int `json:"id"`
86- Kind string `json:"kind"`
87- X float64 `json:"x"`
88- Y float64 `json:"y"`
89- H float64 `json:"h"`
90- HP float64 `json:"hp"`
91- MaxHP float64 `json:"maxhp"`
92- Tier int `json:"tier"`
93- held int // player dragging it, 0 = free
94-}
95-
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-
108-// An ore piece is thrown out of a barren planet and parks in one of its rings.
109-// It lives in the planet's rotating frame (an angle and a radius), so it travels
110-// with the planet around the star, and it is only a world point once placed.
111-type ore struct {
112- ID int `json:"id"`
113- X float64 `json:"x"`
114- Y float64 `json:"y"`
115- H float64 `json:"h"`
116- Towed int `json:"towed"` // player hauling it, 0 = loose
117-
118- planet int // body it orbits, 0 = drifting where it was let go
119- a float64 // slot angle on its ring, in the planet's frame
120- r float64 // current distance from the planet centre
121- vr float64 // outward speed, 0 once it is parked in its ring
122- ring float64 // radius it settles into
123-}
124-
125-// A body is a star or a planet. Orbit 0 and speed 0 is the star, which never
126-// moves; planets revolve and their current place is recomputed every tick.
127-type body struct {
128- ID int `json:"id"`
129- Kind string `json:"kind"`
130- R float64 `json:"r"`
131- X float64 `json:"x"`
132- Y float64 `json:"y"`
133- orbit float64
134- a0 float64
135- speed float64
136- wait float64 // seconds until a barren planet throws its next ore
137- cap int // how many ore this barren planet keeps in orbit
138-}
139-
140-type player struct {
141- ID int `json:"id"`
142- Name string `json:"name"`
143- X float64 `json:"x"`
144- Y float64 `json:"y"`
145- H float64 `json:"h"`
146- TX float64 `json:"tx"`
147- TY float64 `json:"ty"`
148- Pieces []piece `json:"pieces"`
149- Fuel float64 `json:"fuel"` // what is in the tank, spent by flying
150- FuelMax float64 `json:"fuelmax"` // capacity, summed from the hull every tick
151- Foe int `json:"foe"` // player this ship is hostile with, 0 = neutral
152-
153- chase int // player this ship was ordered to close on, 0 = no order
154- cool float64 // seconds until the guns can fire again
155- vx, vy float64
156- orbit int // body the ship is anchored to, 0 = none
157- ox, oy float64 // ring point, in world space, at the moment of anchoring
158- anchored float64 // world time of anchoring
159- held int // loose piece being dragged, 0 = none
160- tow []int // ore on the tow line, in order behind the ship
161- yard float64 // seconds until a shipyard will take another load
162-}
163-
164-type client struct {
165- ws *websocket.Conn
166- p *player
167-}
168-
169-type hub struct {
170- mu sync.Mutex
171- clients map[*client]bool
172- nextID int
173- bodies []*body
174- loose []*loose
175- ore []*ore
176- shots []*shot
177- nextPiece int
178- time float64
179-}
180-
181-type state struct {
182- T string `json:"t"`
183- You int `json:"you"`
184- Held int `json:"held"`
185- Bodies []*body `json:"bodies"`
186- Loose []*loose `json:"loose"`
187- Ore []*ore `json:"ore"`
188- Shots []*shot `json:"shots"`
189- Players []*player `json:"players"`
190-}
191-
19219 var upgrader = websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
19320
19421 var addr = flag.String("addr", ":8090", "listen address")
@@ -219,39 +46,6 @@ func newHub() *hub {
21946 return h
22047 }
22148
222-func (h *hub) pieceID() int {
223- h.nextPiece++
224- return h.nextPiece
225-}
226-
227-// ---- stats ----
228-
229-// Every piece carries two numbers: hit points and fuel. A square is twice as
230-// tough as anything else and a star carries five times the fuel; each tier adds
231-// half again on top, so a fully upgraded piece is worth two base pieces of it.
232-func stats(kind string, tier int) (hp, fuel float64) {
233- hp, fuel = 10, 1
234- switch kind {
235- case "square":
236- hp = 20
237- case "star":
238- fuel = 5
239- }
240- m := 1 + 0.5*float64(tier)
241- return hp * m, fuel * m
242-}
243-
244-// A new piece arrives intact: full hit points for its kind and tier.
245-func (h *hub) fitted(kind string, tier int) piece {
246- hp, _ := stats(kind, tier)
247- return piece{ID: h.pieceID(), Kind: kind, HP: hp, MaxHP: hp, Tier: tier}
248-}
249-
250-func (h *hub) debris(kind string, tier int, x, y float64) *loose {
251- hp, _ := stats(kind, tier)
252- return &loose{ID: h.pieceID(), Kind: kind, X: x, Y: y, HP: hp, MaxHP: hp, Tier: tier}
253-}
254-
25549 func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
25650 ws, err := upgrader.Upgrade(w, r, nil)
25751 if err != nil {
@@ -306,655 +100,6 @@ func (h *hub) handle(w http.ResponseWriter, r *http.Request) {
306100 ws.Close()
307101 }
308102
309-// ---- intents ----
310-
311-// A click is resolved by the server: grab a piece, tear one off, engage a ship,
312-// park on a body, or fly to a point. The client never decides which happened.
313-func (h *hub) pick(p *player, x, y float64) {
314- if l := h.freeLooseAt(x, y); l != nil {
315- p.held, l.held = l.ID, p.ID
316- return
317- }
318- if id := hullPieceAt(p, x, y); id != 0 {
319- if off := h.detach(p, id); len(off) > 0 {
320- h.loose = append(h.loose, off...)
321- if l := h.looseByID(id); l != nil {
322- p.held, l.held = id, p.ID
323- }
324- return
325- }
326- }
327- for c := range h.clients {
328- if c.p != p && hullPieceAt(c.p, x, y) != 0 {
329- h.engage(p, c.p)
330- return
331- }
332- }
333- if b := h.bodyAt(x, y); b != nil {
334- h.anchor(p, b)
335- return
336- }
337- p.chase = 0 // any other order takes the ship off its approach
338- p.orbit = 0
339- p.TX, p.TY = x, y
340-}
341-
342-// Clicking a ship is a declaration, not a shot: both hulls become hostile and the
343-// attacker closes to gun range. Nobody is hostile until someone says so.
344-func (h *hub) engage(p, o *player) {
345- for c := range h.clients {
346- if c.p.Foe == p.ID || c.p.Foe == o.ID {
347- c.p.Foe = 0 // an old pairing ends when a new one starts
348- }
349- }
350- p.Foe, o.Foe, p.chase, p.orbit = o.ID, p.ID, o.ID, 0
351-}
352-
353-func (h *hub) drag(p *player, x, y float64) {
354- l := h.looseByID(p.held)
355- if l == nil || l.held != p.ID {
356- return
357- }
358- l.X, l.Y = x, y
359-}
360-
361-func (h *hub) drop(p *player, x, y float64) {
362- l := h.looseByID(p.held)
363- if l == nil {
364- return
365- }
366- p.held, l.held = 0, 0
367- l.X, l.Y = x, y
368- h.attach(p, l)
369-}
370-
371-// Flying over ore hooks it onto the line: no clicks and nothing to decide. The
372-// line only takes what the hull can haul, so a full ship flies past the rest.
373-func (h *hub) haul(p *player) {
374- for _, o := range h.ore {
375- if len(p.tow) >= p.towLimit() {
376- return
377- }
378- if o.Towed != 0 || math.Hypot(p.X-o.X, p.Y-o.Y) > oreTouch {
379- continue
380- }
381- o.Towed, o.planet = p.ID, 0 // off the ring and onto the line
382- p.tow = append(p.tow, o.ID)
383- }
384-}
385-
386-func (p *player) release(o *ore) {
387- o.Towed = 0
388- for i, id := range p.tow {
389- if id == o.ID {
390- p.tow = append(p.tow[:i], p.tow[i+1:]...)
391- return
392- }
393- }
394-}
395-
396-func (p *player) towLimit() int {
397- n := towBase
398- for _, q := range p.Pieces {
399- if q.Kind == "circle" {
400- n += towPer
401- }
402- }
403- return n
404-}
405-
406-// Docked means the ship has actually settled on its ring point, not that it is
407-// still crossing the system toward it: a yard only serves a ship that stopped.
408-func (p *player) docked() bool {
409- return math.Hypot(p.X-p.TX, p.Y-p.TY) < dockR
410-}
411-
412-// Fuel capacity is summed from the hull: every piece carries a little and the
413-// star carries most of it, so range is a decision about what you bolt on.
414-func (p *player) capacity() float64 {
415- f := 0.0
416- for _, q := range p.Pieces {
417- _, u := stats(q.Kind, q.Tier)
418- f += u
419- }
420- return f
421-}
422-
423-// Fuel is spent by the distance flown, so a stopped ship spends nothing, and a
424-// ship settled in orbit is carried by the body for free. A docked shipyard fills
425-// the tank back up for free.
426-func (h *hub) drive(p *player, dt float64) {
427- if p.orbit != 0 && p.docked() {
428- if b := h.body(p.orbit); b != nil && b.Kind == "shipyard" {
429- p.Fuel = math.Min(p.FuelMax, p.Fuel+refuel*dt)
430- }
431- return
432- }
433- p.Fuel = math.Max(0, p.Fuel-math.Hypot(p.vx, p.vy)*dt/fuelPer)
434-}
435-
436-// A shipyard services one load of ore at a time: three ore patch the whole hull
437-// up, and once nothing is damaged the load buys a tier on a random piece that can
438-// still take one. A whole, fully upgraded ship has nothing to buy, so it keeps
439-// its ore and the yard does not fire.
440-func (h *hub) service(p *player) bool {
441- hurt := false
442- for i, q := range p.Pieces {
443- if q.HP < q.MaxHP {
444- hurt = true
445- p.Pieces[i].HP = q.MaxHP
446- }
447- }
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.
Cut short: this commit's diff is over 1000 lines.