~bigbes/game-prototype-ftl

ref: 3144cda7fcb30beaa78e85783d0af8994484edfe game-prototype-ftl/systems.go -rw-r--r-- 2.2 KiB
3144cda7 — Eugene Blikh systems-power: hoist HUD cellBottom out of inner loop 30 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main

// ReactorCap is the maximum total power that can be distributed across all
// ship systems at any time.
const ReactorCap = 8

// System holds the power state of a single ship system.
// Instances are indexed in a slice by int(RoomRole) so that callers can do
// a direct O(1) lookup when the role is known; addPower / removePower still
// do a linear scan by Role field for safety.
type System struct {
	Role       RoomRole
	PowerLevel int
	MaxLevel   int
}

// NewStartingSystems returns a 5-element slice indexed by int(RoomRole).
// All systems start at PowerLevel 0.
func NewStartingSystems() []System {
	return []System{
		int(RolePilot):   {Role: RolePilot, PowerLevel: 0, MaxLevel: 1},
		int(RoleWeapons): {Role: RoleWeapons, PowerLevel: 0, MaxLevel: 4},
		int(RoleShields): {Role: RoleShields, PowerLevel: 0, MaxLevel: 4},
		int(RoleMedBay):  {Role: RoleMedBay, PowerLevel: 0, MaxLevel: 2},
		int(RoleEngines): {Role: RoleEngines, PowerLevel: 0, MaxLevel: 4},
	}
}

// reactorUsed returns the sum of PowerLevel across all systems.
func reactorUsed(sys []System) int {
	total := 0
	for _, s := range sys {
		total += s.PowerLevel
	}
	return total
}

// addPower attempts to raise the PowerLevel of the system with the given role
// by 1. It returns false (no-op) if:
//   - the system is already at its MaxLevel (IV4), or
//   - the reactor would exceed reactorCap (IV3).
//
// Respects IV2: this is the sole mutator of System.PowerLevel for increments.
func addPower(sys []System, role RoomRole, reactorCap int) bool {
	for i := range sys {
		if sys[i].Role != role {
			continue
		}
		if sys[i].PowerLevel >= sys[i].MaxLevel {
			return false
		}
		if reactorUsed(sys) >= reactorCap {
			return false
		}
		sys[i].PowerLevel++
		return true
	}
	return false
}

// removePower attempts to lower the PowerLevel of the system with the given
// role by 1. It returns false (no-op) if the system is already at 0 (IV4).
//
// Respects IV2: this is the sole mutator of System.PowerLevel for decrements.
func removePower(sys []System, role RoomRole) bool {
	for i := range sys {
		if sys[i].Role != role {
			continue
		}
		if sys[i].PowerLevel <= 0 {
			return false
		}
		sys[i].PowerLevel--
		return true
	}
	return false
}