xonecas.ioDon't click! Sean Caetano Martin Sign in
tiny-adventure / internal / sim / combat.go 205 lines4.7 kB Raw
1package sim
2
3import (
4	"math/rand/v2"
5	"slices"
6	"sort"
7
8	"tinyadventure/internal/model"
9)
10
11const MaxRounds = 40
12
13const (
14	OutcomeVictory = "victory"
15	OutcomeDefeat  = "defeat"
16)
17
18type Result struct {
19	Outcome string
20	Rounds  int
21	Log     []model.CombatEvent
22	Rewards model.Rewards
23}
24
25type combatant struct {
26	unit    model.Unit
27	side    int
28	role    string
29	hp      int
30	stats   model.Stats
31	abils   []model.Ability
32	cd      map[string]int
33	struck  bool
34	ambush  bool
35	traits  []string
36	edge    string
37	guards  []string
38	effects []effect
39	hurtBy  *combatant
40}
41
42func newCombatant(u model.Unit, side int) *combatant {
43	s := Effective(u)
44	t := TraitsOf(u)
45	return &combatant{
46		unit: u, side: side, role: RoleOf(u.Class), hp: s.HP, stats: s, abils: AllAbilities(u), cd: map[string]int{},
47		traits: t, edge: edgeOf(t), guards: guardsOf(t, u.Resist),
48	}
49}
50
51func (c *combatant) has(t string) bool { return slices.Contains(c.traits, t) }
52
53func (c *combatant) alive() bool { return c.hp > 0 }
54
55func (c *combatant) hurt() bool { return c.hp*2 < c.stats.MaxHP }
56
57type battle struct {
58	r    *rand.Rand
59	all  []*combatant
60	log  []model.CombatEvent
61	tick int
62}
63
64func (b *battle) side(s int) []*combatant {
65	var out []*combatant
66	for _, c := range b.all {
67		if c.side == s && c.alive() {
68			out = append(out, c)
69		}
70	}
71	return out
72}
73
74func (b *battle) act(actor *combatant, extra bool) {
75	if !extra {
76		for id, v := range actor.cd {
77			if v > 0 {
78				actor.cd[id] = v - 1
79			}
80		}
81	}
82	actor.startTurn()
83	defer actor.endTurn()
84	a := b.choose(actor, extra)
85	foes := b.side(1 - actor.side)
86	switch a.Kind {
87	case KindHeal:
88		b.heal(actor, a)
89	case KindBuff, KindDebuff:
90		b.cast(actor, a)
91	case KindAoE:
92		for _, f := range foes {
93			if f.alive() {
94				b.hit(actor, f, a, 1)
95			}
96		}
97	default:
98		b.hit(actor, b.pickTarget(actor, foes), a, 1)
99	}
100	if a.ID != StrikeID {
101		actor.cd[a.ID] = a.Cooldown + 1
102	}
103}
104
105func Simulate(r *rand.Rand, party []model.Unit, enemies []model.Unit) (string, int, []model.CombatEvent, []int) {
106	b := &battle{r: r}
107	for _, u := range party {
108		b.all = append(b.all, newCombatant(u, 0))
109	}
110	for _, u := range enemies {
111		b.all = append(b.all, newCombatant(u, 1))
112	}
113	rounds := 0
114	for rounds < MaxRounds && len(b.side(0)) > 0 && len(b.side(1)) > 0 {
115		rounds++
116		b.tick = rounds
117		order := make([]*combatant, 0, len(b.all))
118		for _, c := range b.all {
119			if c.alive() {
120				order = append(order, c)
121			}
122		}
123		first := func(c *combatant) bool { return rounds == 1 && c.has("first") }
124		sort.SliceStable(order, func(i, j int) bool {
125			if first(order[i]) != first(order[j]) {
126				return first(order[i])
127			}
128			return order[i].stats.Speed > order[j].stats.Speed
129		})
130		for _, c := range order {
131			if !c.alive() || len(b.side(0)) == 0 || len(b.side(1)) == 0 {
132				continue
133			}
134			b.act(c, false)
135		}
136	}
137	outcome := OutcomeDefeat
138	if len(b.side(1)) == 0 && len(b.side(0)) > 0 {
139		outcome = OutcomeVictory
140	}
141	hp := make([]int, len(party))
142	for i := range party {
143		hp[i] = b.all[i].hp
144	}
145	return outcome, rounds, b.log, hp
146}
147
148func Forecast(r *rand.Rand, party []model.Unit, enemies []model.Unit, runs int) (odds, wounds int) {
149	wins, start, left := 0, 0, 0
150	for _, u := range party {
151		start += Effective(u).HP
152	}
153	for range runs {
154		outcome, _, _, hp := Simulate(r, party, enemies)
155		if outcome == OutcomeVictory {
156			wins++
157		}
158		for _, v := range hp {
159			left += v
160		}
161	}
162	return wins * 100 / runs, max(0, 100-left*100/max(1, start*runs))
163}
164
165func Fight(r *rand.Rand, p *model.Party, enc model.Encounter, nodeTier int) Result {
166	outcome, rounds, log, hp := Simulate(r, p.Units, enc.Enemies)
167	res := Result{Outcome: outcome, Rounds: rounds, Log: log, Rewards: model.Rewards{Items: []model.Item{}}}
168	if outcome != OutcomeVictory {
169		return res
170	}
171	for i := range p.Units {
172		p.Units[i].Stats.HP = max(0, hp[i])
173	}
174	res.Rewards = Rewards(r, enc, nodeTier)
175	share := max(1, res.Rewards.XP/max(len(p.Units), 1))
176	for i := range p.Units {
177		if !p.Units[i].Fallen() {
178			Grant(&p.Units[i], CatchUp(share, nodeTier, p.Units[i].Level))
179		}
180	}
181	p.Gold += res.Rewards.Gold
182	p.Inventory = append(p.Inventory, res.Rewards.Items...)
183	return res
184}
185
186func Rewards(r *rand.Rand, enc model.Encounter, nodeTier int) model.Rewards {
187	rw := model.Rewards{Items: []model.Item{}}
188	tier := 1
189	for _, e := range enc.Enemies {
190		rw.XP += enemyXP(e, enc.Boss && e.Class == "boss")
191		rw.Gold += 3*e.Level + r.IntN(4)
192		tier = max(tier, e.Level)
193		if r.IntN(100) < 20 {
194			rw.Items = append(rw.Items, RollItem(r, max(e.Level, nodeTier)))
195		}
196	}
197	if enc.Boss {
198		rw.Items = append(rw.Items, RollItem(r, max(tier+1, nodeTier)), RollItem(r, max(tier+1, nodeTier)))
199	}
200	return rw
201}
202
203func CatchUp(xp, enemyLevel, heroLevel int) int {
204	return xp * (2 + max(0, enemyLevel-heroLevel)) / 2
205}