// https://red-bean.com/sgf/user_guide/index.html
// https://red-bean.com/sgf/sgf4.html
// todo: support collections in a file
// Properties to support. Remove each one as it gets support.
// B
// KO
// MN
// W
// AB
// AE
// AW
// PL
// C
// DM
// GB
// GW
// HO
// N
// UC
// V
// BM
// DO
// IT
// TE
// AR
// CR
// DD
// LB
// LN
// MA
// SL
// SQ
// TR
// AP
// CA
// FF
// GM
// ST
// SZ
// AN
// BR
// BT
// CP
// DT
// EV
// GN
// GC
// ON
// OT
// PB
// PC
// PW
// RE
// RO
// RU
// SO
// TM
// US
// WR
// WT
// BL
// OB
// OW
// WL
// FG
// PM
// VW
use crate::tree::{parse_collection, parse_size, ParseSizeError, Size};
use nom::IResult;
#[derive(Debug)]
pub enum Error<'a> {
InvalidField,
InvalidBoardSize,
Incomplete,
InvalidSgf(nom::error::VerboseError<&'a str>),
}
impl<'a> From>> for Error<'a> {
fn from(err: nom::Err>) -> Self {
match err {
nom::Err::Incomplete(_) => Error::Incomplete,
nom::Err::Error(e) => Error::InvalidSgf(e.clone()),
nom::Err::Failure(e) => Error::InvalidSgf(e.clone()),
}
}
}
impl<'a> From for Error<'a> {
fn from(_: ParseSizeError) -> Self {
Self::InvalidBoardSize
}
}
#[derive(Debug)]
pub struct GameTree {
pub file_format: i8,
pub app: Option,
pub game_type: GameType,
pub board_size: Size,
pub text: String,
}
pub struct GameInfo {
pub annotator: Option,
pub copyright: Option,
pub event: Option,
// Games can be played across multiple days, even multiple years. The format specifies
// shortcuts.
pub date_time: Vec,
pub location: Option,
// special rules for the round-number and type
pub round: Option,
pub ruleset: Option,
pub source: Option,
pub time_limits: Option,
pub game_keeper: Option,
pub game_name: Option,
pub game_comments: Option,
pub black_player: Option,
pub black_rank: Option,
pub black_team: Option,
pub white_player: Option,
pub white_rank: Option,
pub white_team: Option,
pub opening: Option,
pub overtime: Option,
pub result: Option,
}
pub enum GameResult {
Annulled,
Draw,
Black(Win),
White(Win),
}
pub enum Win {
Score(i32),
Resignation,
Forfeit,
Time,
}
#[derive(Debug, PartialEq)]
pub enum GameType {
Go,
Unsupported,
}
enum PropType {
Move,
Setup,
Root,
GameInfo,
}
enum PropValue {
Empty,
Number,
Real,
Double,
Color,
SimpleText,
Text,
Point,
Move,
Stone,
}
pub fn parse_sgf<'a>(input: &'a str) -> Result, Error<'a>> {
let (input, trees) = parse_collection::>(input)?;
let games = trees
.into_iter()
.map(|tree| {
let file_format = match tree.sequence[0].find_prop("FF") {
Some(prop) => prop.values[0].parse::().unwrap(),
None => 4,
};
let app = tree.sequence[0]
.find_prop("AP")
.map(|prop| prop.values[0].clone());
let board_size = match tree.sequence[0].find_prop("SZ") {
Some(prop) => Size::try_from(prop.values[0].as_str())?,
None => Size {
width: 19,
height: 19,
},
};
Ok(GameTree {
file_format,
app,
game_type: GameType::Go,
board_size,
text: input.to_owned(),
})
})
.collect::, Error>>()?;
Ok(games)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tree::Size;
use std::fs::File;
use std::io::Read;
const EXAMPLE: &'static str = "(;FF[4]C[root](;C[a];C[b](;C[c])
(;C[d];C[e]))
(;C[f](;C[g];C[h];C[i])
(;C[j])))";
fn with_text(text: &str, f: impl FnOnce(Vec)) {
let games = parse_sgf(text).unwrap();
f(games);
}
fn with_file(path: &std::path::Path, f: impl FnOnce(Vec)) {
let mut file = File::open(path).unwrap();
let mut text = String::new();
let _ = file.read_to_string(&mut text);
with_text(&text, f);
}
#[test]
fn it_parses_game_root() {
with_text(EXAMPLE, |trees| {
assert_eq!(trees.len(), 1);
let tree = &trees[0];
assert_eq!(tree.file_format, 4);
assert_eq!(tree.app, None);
assert_eq!(tree.game_type, GameType::Go);
assert_eq!(
tree.board_size,
Size {
width: 19,
height: 19
}
);
// assert_eq!(tree.text, EXAMPLE.to_owned());
});
with_file(std::path::Path::new("test_data/print1.sgf"), |trees| {
assert_eq!(trees.len(), 1);
let tree = &trees[0];
assert_eq!(tree.file_format, 4);
assert_eq!(tree.app, None);
assert_eq!(tree.game_type, GameType::Go);
assert_eq!(
tree.board_size,
Size {
width: 19,
height: 19
}
);
});
}
}