aboutsummaryrefslogtreecommitdiff
path: root/planetwars-rules/src/rules.rs
blob: e339b4e6c7203a02129888f47304b8e8c75e6350 (plain)
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/// The planet wars game rules.
#[derive(Debug)]
pub struct PwState {
    pub players: Vec<Player>,
    pub planets: Vec<Planet>,
    pub expeditions: Vec<Expedition>,
    // How many expeditions were already dispatched.
    // This is needed for assigning expedition identifiers.
    pub expedition_num: u64,
    pub turn_num: u64,
    pub max_turns: u64,
}

#[derive(Debug)]
pub struct Player {
    pub id: usize,
    pub alive: bool,
}

#[derive(Debug)]
pub struct Fleet {
    pub owner: Option<usize>,
    pub ship_count: u64,
}

#[derive(Debug)]
pub struct Planet {
    pub id: usize,
    pub name: String,
    pub fleets: Vec<Fleet>,
    pub x: f64,
    pub y: f64,
}

#[derive(Debug)]
pub struct Expedition {
    pub id: u64,
    pub origin: usize,
    pub target: usize,
    pub fleet: Fleet,
    pub turns_remaining: u64,
}

#[derive(Debug)]
pub struct Dispatch {
    pub origin: usize,
    pub target: usize,
    pub ship_count: u64,
}

impl PwState {
    pub fn dispatch(&mut self, dispatch: &Dispatch) {
        let distance = self.planets[dispatch.origin].distance(&self.planets[dispatch.target]);

        let origin = &mut self.planets[dispatch.origin];
        origin.fleets[0].ship_count -= dispatch.ship_count;

        let expedition = Expedition {
            id: self.expedition_num,
            origin: dispatch.origin,
            target: dispatch.target,
            turns_remaining: distance,
            fleet: Fleet {
                owner: origin.owner(),
                ship_count: dispatch.ship_count,
            },
        };

        // increment counter
        self.expedition_num += 1;
        self.expeditions.push(expedition);
    }

    // Play one step of the game
    pub fn step(&mut self) {
        self.turn_num += 1;

        // Initially mark all players dead, re-marking them as alive once we
        // encounter a sign of life.
        for player in self.players.iter_mut() {
            player.alive = false;
        }

        self.step_expeditions();
        self.resolve_combat();
    }

    pub fn repopulate(&mut self) {
        for planet in self.planets.iter_mut() {
            if planet.owner().is_some() {
                planet.fleets[0].ship_count += 1;
            }
        }
    }

    fn step_expeditions(&mut self) {
        let mut i = 0;
        let exps = &mut self.expeditions;
        while i < exps.len() {
            // compare with 1 to avoid issues with planet distance 0
            if exps[i].turns_remaining <= 1 {
                // remove expedition from expeditions, and add to fleet
                let exp = exps.swap_remove(i);
                let planet = &mut self.planets[exp.target];
                planet.orbit(exp.fleet);
            } else {
                exps[i].turns_remaining -= 1;
                if let Some(owner_num) = exps[i].fleet.owner {
                    // owner has an expedition in progress; this is a sign of life.
                    self.players[owner_num].alive = true;
                }

                // proceed to next expedition
                i += 1;
            }
        }
    }

    fn resolve_combat(&mut self) {
        for planet in self.planets.iter_mut() {
            planet.resolve_combat();
            if let Some(owner_num) = planet.owner() {
                // owner owns a planet; this is a sign of life.
                self.players[owner_num].alive = true;
            }
        }
    }

    pub fn is_finished(&self) -> bool {
        let remaining = self.players.iter().filter(|p| p.alive).count();
        remaining < 2 || self.turn_num >= self.max_turns
    }

    pub fn living_players(&self) -> Vec<usize> {
        self.players
            .iter()
            .filter_map(|p| if p.alive { Some(p.id) } else { None })
            .collect()
    }
}

impl Planet {
    pub fn owner(&self) -> Option<usize> {
        self.fleets.first().and_then(|f| f.owner)
    }

    pub fn ship_count(&self) -> u64 {
        self.fleets.first().map_or(0, |f| f.ship_count)
    }

    /// Make a fleet orbit this planet.
    fn orbit(&mut self, fleet: Fleet) {
        // If owner already has a fleet present, merge
        for other in self.fleets.iter_mut() {
            if other.owner == fleet.owner {
                other.ship_count += fleet.ship_count;
                return;
            }
        }
        // else, add fleet to fleets list
        self.fleets.push(fleet);
    }

    fn resolve_combat(&mut self) {
        // The player owning the largest fleet present will win the combat.
        // Here, we resolve how many ships he will have left.
        // note: in the current implementation, we could resolve by doing
        // winner.ship_count -= second_largest.ship_count, but this does not
        // allow for simple customizations (such as changing combat balance).

        self.fleets
            .sort_by(|a, b| a.ship_count.cmp(&b.ship_count).reverse());
        while self.fleets.len() > 1 {
            let fleet = self.fleets.pop().unwrap();
            // destroy some ships
            for other in self.fleets.iter_mut() {
                other.ship_count -= fleet.ship_count;
            }

            // remove dead fleets
            while self.fleets.last().map(|f| f.ship_count) == Some(0) {
                self.fleets.pop();
            }
        }
    }

    fn distance(&self, other: &Planet) -> u64 {
        let dx = self.x - other.x;
        let dy = self.y - other.y;
        (dx.powi(2) + dy.powi(2)).sqrt().ceil() as u64
    }
}