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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
use std::fmt;
use std::time::Duration;
use chrono::{NaiveDate, NaiveTime};

#[derive(Default, Debug, PartialEq, Eq)]
pub struct GameRecord {
    pub black_player: Option<String>,
    pub white_player: Option<String>,
    pub event: Option<String>,
    pub site: Option<String>,
    pub start_time: Option<Time>,
    pub end_time: Option<Time>,
    pub time_limit: Option<TimeLimit>,
    pub opening: Option<String>,
    pub start_pos: Position,
    pub moves: Vec<MoveRecord>,
}

impl fmt::Display for GameRecord {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "V2.2")?;

        // Metadata
        let metadata = [
            ("N+", self.black_player.as_ref().map(|x| x.to_string())),
            ("N-", self.white_player.as_ref().map(|x| x.to_string())),
            ("$EVENT:", self.event.as_ref().map(|x| x.to_string())),
            ("$SITE:", self.site.as_ref().map(|x| x.to_string())),
            (
                "$START_TIME:",
                self.start_time.as_ref().map(|x| x.to_string()),
            ),
            ("$END_TIME:", self.end_time.as_ref().map(|x| x.to_string())),
            (
                "$TIME_LIMIT:",
                self.time_limit.as_ref().map(|x| x.to_string()),
            ),
            ("$OPENING:", self.opening.as_ref().map(|x| x.to_string())),
        ];
        for &(ref key, ref value) in &metadata {
            if let Some(ref value) = *value {
                writeln!(f, "{}{}", key, value)?;
            }
        }

        // Position
        write!(f, "{}", self.start_pos)?;

        // Move records
        for record in &self.moves {
            write!(f, "{}", record)?;
        }

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Time {
    pub date: NaiveDate,
    pub time: Option<NaiveTime>,
}

impl fmt::Display for Time {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.date.format("%Y/%m/%d"))?;
        if let Some(time) = self.time {
            write!(f, " {}", time.format("%H:%M:%S"))?;
        }

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct TimeLimit {
    pub main_time: Duration,
    pub byoyomi: Duration,
}

impl fmt::Display for TimeLimit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let secs = self.main_time.as_secs();
        let hours = secs / 3600;
        let minutes = (secs % 3600) / 60;

        write!(
            f,
            "{:02}:{:02}+{:02}",
            hours,
            minutes,
            self.byoyomi.as_secs()
        )
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq)]
pub enum GameAttribute {
    Time(Time),
    TimeLimit(TimeLimit),
    Str(String),
}

impl fmt::Display for GameAttribute {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            GameAttribute::Time(ref time) => write!(f, "{}", time),
            GameAttribute::TimeLimit(ref time_limit) => write!(f, "{}", time_limit),
            GameAttribute::Str(ref s) => write!(f, "{}", s),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Color {
    Black,
    White,
}

impl Default for Color {
    fn default() -> Self {
        Color::Black
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Color::Black => write!(f, "+"),
            Color::White => write!(f, "-"),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Square {
    pub file: u8,
    pub rank: u8,
}

impl Square {
    pub fn new(file: u8, rank: u8) -> Square {
        Square { file, rank }
    }
}

impl fmt::Display for Square {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}{}", self.file, self.rank)
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum PieceType {
    Pawn,
    Lance,
    Knight,
    Silver,
    Gold,
    Bishop,
    Rook,
    King,
    ProPawn,
    ProLance,
    ProKnight,
    ProSilver,
    Horse,
    Dragon,
    All,
}

impl fmt::Display for PieceType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let pt = match *self {
            PieceType::Pawn => "FU",
            PieceType::Lance => "KY",
            PieceType::Knight => "KE",
            PieceType::Silver => "GI",
            PieceType::Gold => "KI",
            PieceType::Bishop => "KA",
            PieceType::Rook => "HI",
            PieceType::King => "OU",
            PieceType::ProPawn => "TO",
            PieceType::ProLance => "NY",
            PieceType::ProKnight => "NK",
            PieceType::ProSilver => "NG",
            PieceType::Horse => "UM",
            PieceType::Dragon => "RY",
            PieceType::All => "AL",
        };
        write!(f, "{}", pt)
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, Default, PartialEq, Eq)]
pub struct Position {
    pub drop_pieces: Vec<(Square, PieceType)>,
    pub bulk: Option<[[Option<(Color, PieceType)>; 9]; 9]>,
    pub add_pieces: Vec<(Color, Square, PieceType)>,
    pub side_to_move: Color,
}

impl fmt::Display for Position {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(ref bulk) = self.bulk {
            for (i, ref row) in bulk.iter().enumerate() {
                write!(f, "P{}", i + 1)?;

                for pc in row.iter() {
                    match *pc {
                        Some((ref color, ref pt)) => write!(f, "{}{}", color, pt)?,
                        None => write!(f, " * ")?,
                    }
                }

                writeln!(f, "")?;
            }
        } else {
            write!(f, "PI")?;
            for &(ref sq, ref pt) in &self.drop_pieces {
                write!(f, "{}{}", sq, pt)?;
            }
            writeln!(f, "")?;
        }

        for &(ref color, ref sq, ref pt) in &self.add_pieces {
            writeln!(f, "P{}{}{}", color, sq, pt)?;
        }

        writeln!(f, "{}", self.side_to_move)?;

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Action {
    Move(Color, Square, Square, PieceType),
    Toryo,
    Chudan,
    Sennichite,
    TimeUp,
    IllegalMove,
    IllegalAction(Color),
    Jishogi,
    Kachi,
    Hikiwake,
    Matta,
    Tsumi,
    Fuzumi,
    Error,
}

impl fmt::Display for Action {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Action::Move(ref color, ref from, ref to, ref pt) => {
                write!(f, "{}{}{}{}", color, from, to, pt)
            }
            Action::Toryo => write!(f, "%TORYO"),
            Action::Chudan => write!(f, "%CHUDAN"),
            Action::Sennichite => write!(f, "SENNICHITE"),
            Action::TimeUp => write!(f, "%TIME_UP"),
            Action::IllegalMove => write!(f, "%ILLEGAL_MOVE"),
            Action::IllegalAction(ref color) => write!(f, "%{}ILLEGAL_ACTION", color),
            Action::Jishogi => write!(f, "%JISHOGI"),
            Action::Kachi => write!(f, "%KACHI"),
            Action::Hikiwake => write!(f, "%HIKIWAKE"),
            Action::Matta => write!(f, "%MATTA"),
            Action::Tsumi => write!(f, "%TSUMI"),
            Action::Fuzumi => write!(f, "%FUZUMI"),
            Action::Error => write!(f, "%ERROR"),
        }
    }
}

////////////////////////////////////////////////////////////////////////////////

#[derive(Debug, PartialEq, Eq)]
pub struct MoveRecord {
    pub action: Action,
    pub time: Option<Duration>,
}

impl fmt::Display for MoveRecord {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "{}", self.action)?;

        if let Some(ref time) = self.time {
            writeln!(f, "T{}", time.as_secs())?;
        }

        Ok(())
    }
}

////////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let mut g = GameRecord::default();
        g.black_player = Some("NAKAHARA".to_string());
        g.white_player = Some("YONENAGA".to_string());
        g.event = Some("13th World Computer Shogi Championship".to_string());
        g.site = Some("KAZUSA ARC".to_string());
        g.start_time = Some(Time {
            date: NaiveDate::from_ymd(2003, 5, 3),
            time: Some(NaiveTime::from_hms(10, 30, 0)),
        });
        g.end_time = Some(Time {
            date: NaiveDate::from_ymd(2003, 5, 3),
            time: Some(NaiveTime::from_hms(11, 11, 5)),
        });
        g.time_limit = Some(TimeLimit {
            main_time: Duration::from_secs(1500),
            byoyomi: Duration::from_secs(0),
        });
        g.opening = Some("YAGURA".to_string());
        g.moves.push(MoveRecord {
            action: Action::Move(
                Color::Black,
                Square::new(8, 7),
                Square::new(8, 6),
                PieceType::Pawn,
            ),
            time: Some(Duration::from_secs(5)),
        });
        g.moves.push(MoveRecord {
            action: Action::Toryo,
            time: None,
        });

        let csa = "\
V2.2
N+NAKAHARA
N-YONENAGA
$EVENT:13th World Computer Shogi Championship
$SITE:KAZUSA ARC
$START_TIME:2003/05/03 10:30:00
$END_TIME:2003/05/03 11:11:05
$TIME_LIMIT:00:25+00
$OPENING:YAGURA
PI
+
+8786FU
T5
%TORYO
";

        assert_eq!(csa, g.to_string());
    }
}