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
|
use std::fs::File;
use std::io;
use std::io::Read;
use serde_json;
use super::protocol as proto;
use super::rules::*;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
pub map_file: String,
pub max_turns: u64,
}
impl Config {
pub fn create_state(&self, num_players: usize) -> PwState {
let planets = self.load_map(num_players);
let players = (0..num_players)
.map(|player_num| Player {
id: player_num + 1,
alive: true,
})
.collect();
PwState {
players: players,
planets: planets,
expeditions: Vec::new(),
expedition_num: 0,
turn_num: 0,
max_turns: self.max_turns,
}
}
fn load_map(&self, num_players: usize) -> Vec<Planet> {
let map = self.read_map().expect("[PLANET_WARS] reading map failed");
return map
.planets
.into_iter()
.enumerate()
.map(|(num, planet)| {
let mut fleets = Vec::new();
let owner = planet.owner.and_then(|owner_num| {
// in the current map format, player numbers start at 1.
// TODO: we might want to change this.
// ignore players that are not in the game
if owner_num > 0 && owner_num <= num_players {
Some(owner_num - 1)
} else {
None
}
});
if planet.ship_count > 0 {
fleets.push(Fleet {
owner: owner,
ship_count: planet.ship_count,
});
}
return Planet {
id: num,
name: planet.name,
x: planet.x,
y: planet.y,
fleets: fleets,
};
})
.collect();
}
fn read_map(&self) -> io::Result<Map> {
let mut file = File::open(&self.map_file)?;
let mut buf = String::new();
file.read_to_string(&mut buf)?;
let map = serde_json::from_str(&buf)?;
return Ok(map);
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Map {
pub planets: Vec<proto::Planet>,
}
|