xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / internal / server / move.go 92 lines2.0 kB Raw
1package server
2
3import (
4	"errors"
5	"slices"
6
7	"tinyadventure/internal/model"
8	"tinyadventure/internal/world"
9)
10
11func (g *game) path(tx, ty int) ([][2]int, error) {
12	m := &g.state.Map
13	if !m.Walkable(tx, ty) {
14		return nil, errors.New("tile is not walkable")
15	}
16	from, to := [2]int{g.state.Party.X, g.state.Party.Y}, [2]int{tx, ty}
17	if from == to {
18		return nil, nil
19	}
20	if out := world.Path(m, from, to, g.guarded); out != nil {
21		return out, nil
22	}
23	if out := world.Path(m, from, to, nil); out != nil {
24		return out, nil
25	}
26	return nil, errors.New("tile is unreachable")
27}
28
29func (g *game) guarded(x, y int) bool { return g.blocker(x, y) != "" }
30
31func (g *game) blocker(x, y int) string {
32	if p := g.poiAt(x, y); p != nil && !p.Cleared {
33		return p.ID
34	}
35	if b := g.bandAt(x, y); b != nil {
36		return b.ID
37	}
38	return ""
39}
40
41func (g *game) move(tx, ty, limit int) error {
42	g.shake()
43	g.begin()
44	steps, err := g.path(tx, ty)
45	if err != nil {
46		return err
47	}
48	if limit > 0 && len(steps) > limit {
49		steps = steps[:limit]
50	}
51	lost := map[string]int{}
52	for _, s := range steps {
53		if id := g.blocker(s[0], s[1]); id != "" {
54			g.threat = id
55			break
56		}
57		g.state.Party.X, g.state.Party.Y = s[0], s[1]
58		g.state.Trail = append(g.state.Trail, s)
59		g.state.Summary.Hexes++
60		g.pass(g.state.Map.Cost(s[0], s[1]))
61		g.pickup(s[0], s[1])
62		g.visit(s[0], s[1])
63		endure(&g.state.Map, g.state.Party.Units, s[0], s[1], lost)
64		g.settle()
65		if id := g.tickBands(); id != "" {
66			g.threat = id
67			break
68		}
69	}
70	g.noteHazards(lost)
71	return nil
72}
73
74func (g *game) route(tx, ty int) (model.Route, error) {
75	steps, err := g.path(tx, ty)
76	out := model.Route{Path: [][2]int{}}
77	units, lost := slices.Clone(g.state.Party.Units), map[string]int{}
78	for _, s := range steps {
79		if out.Blocked = g.blocker(s[0], s[1]); out.Blocked != "" {
80			break
81		}
82		out.Path = append(out.Path, s)
83		out.Time += g.state.Map.Cost(s[0], s[1])
84		endure(&g.state.Map, units, s[0], s[1], lost)
85	}
86	for _, n := range lost {
87		out.Hazard += n
88	}
89	c := g.state.Clock
90	out.Dusk = !c.Night() && c.Time+out.Time >= c.DayLength
91	return out, err
92}