Compare commits
2 Commits
90b0f830e0
...
4b30bf288a
Author | SHA1 | Date |
---|---|---|
Savanni D'Gerinel | 4b30bf288a | |
Savanni D'Gerinel | 96c6f2dfbf |
144
go-sgf/src/go.rs
144
go-sgf/src/go.rs
|
@ -1,3 +1,4 @@
|
||||||
|
// https://red-bean.com/sgf/
|
||||||
// https://red-bean.com/sgf/user_guide/index.html
|
// https://red-bean.com/sgf/user_guide/index.html
|
||||||
// https://red-bean.com/sgf/sgf4.html
|
// https://red-bean.com/sgf/sgf4.html
|
||||||
|
|
||||||
|
@ -94,23 +95,45 @@ impl<'a> From<ParseSizeError> for Error<'a> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub struct GameTree {
|
pub enum Rank {
|
||||||
pub file_format: i8,
|
Kyu(u8),
|
||||||
pub app: Option<String>,
|
Dan(u8),
|
||||||
pub game_type: GameType,
|
Pro(u8),
|
||||||
pub board_size: Size,
|
|
||||||
|
|
||||||
pub text: String,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl TryFrom<&str> for Rank {
|
||||||
|
type Error = String;
|
||||||
|
fn try_from(r: &str) -> Result<Rank, Self::Error> {
|
||||||
|
let parts = r.split(" ").map(|s| s.to_owned()).collect::<Vec<String>>();
|
||||||
|
let cnt = parts[0].parse::<u8>().map_err(|err| format!("{:?}", err))?;
|
||||||
|
match parts[1].to_ascii_lowercase().as_str() {
|
||||||
|
"kyu" => Ok(Rank::Kyu(cnt)),
|
||||||
|
"dan" => Ok(Rank::Dan(cnt)),
|
||||||
|
"pro" => Ok(Rank::Pro(cnt)),
|
||||||
|
_ => Err("unparsable".to_owned()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct GameTree {
|
||||||
|
pub file_format: i8,
|
||||||
|
pub app_name: Option<String>,
|
||||||
|
pub game_type: GameType,
|
||||||
|
pub board_size: Size,
|
||||||
|
pub info: GameInfo,
|
||||||
|
// pub text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
pub struct GameInfo {
|
pub struct GameInfo {
|
||||||
pub annotator: Option<String>,
|
pub annotator: Option<String>,
|
||||||
pub copyright: Option<String>,
|
pub copyright: Option<String>,
|
||||||
pub event: Option<String>,
|
pub event: Option<String>,
|
||||||
// Games can be played across multiple days, even multiple years. The format specifies
|
// Games can be played across multiple days, even multiple years. The format specifies
|
||||||
// shortcuts.
|
// shortcuts.
|
||||||
pub date_time: Vec<chrono::NaiveDate>,
|
pub date: Vec<chrono::NaiveDate>,
|
||||||
pub location: Option<String>,
|
pub location: Option<String>,
|
||||||
// special rules for the round-number and type
|
// special rules for the round-number and type
|
||||||
pub round: Option<String>,
|
pub round: Option<String>,
|
||||||
|
@ -118,16 +141,17 @@ pub struct GameInfo {
|
||||||
pub source: Option<String>,
|
pub source: Option<String>,
|
||||||
pub time_limits: Option<std::time::Duration>,
|
pub time_limits: Option<std::time::Duration>,
|
||||||
pub game_keeper: Option<String>,
|
pub game_keeper: Option<String>,
|
||||||
|
pub komi: Option<f32>,
|
||||||
|
|
||||||
pub game_name: Option<String>,
|
pub game_name: Option<String>,
|
||||||
pub game_comments: Option<String>,
|
pub game_comments: Option<String>,
|
||||||
|
|
||||||
pub black_player: Option<String>,
|
pub black_player: Option<String>,
|
||||||
pub black_rank: Option<String>,
|
pub black_rank: Option<Rank>,
|
||||||
pub black_team: Option<String>,
|
pub black_team: Option<String>,
|
||||||
|
|
||||||
pub white_player: Option<String>,
|
pub white_player: Option<String>,
|
||||||
pub white_rank: Option<String>,
|
pub white_rank: Option<Rank>,
|
||||||
pub white_team: Option<String>,
|
pub white_team: Option<String>,
|
||||||
|
|
||||||
pub opening: Option<String>,
|
pub opening: Option<String>,
|
||||||
|
@ -135,6 +159,7 @@ pub struct GameInfo {
|
||||||
pub result: Option<GameResult>,
|
pub result: Option<GameResult>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub enum GameResult {
|
pub enum GameResult {
|
||||||
Annulled,
|
Annulled,
|
||||||
Draw,
|
Draw,
|
||||||
|
@ -142,14 +167,43 @@ pub enum GameResult {
|
||||||
White(Win),
|
White(Win),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl TryFrom<&str> for GameResult {
|
||||||
|
type Error = String;
|
||||||
|
fn try_from(s: &str) -> Result<GameResult, Self::Error> {
|
||||||
|
println!("Result try_from: {:?}", s);
|
||||||
|
if s == "0" {
|
||||||
|
Ok(GameResult::Draw)
|
||||||
|
} else if s == "Void" {
|
||||||
|
Ok(GameResult::Annulled)
|
||||||
|
} else {
|
||||||
|
let parts = s.split("+").collect::<Vec<&str>>();
|
||||||
|
let res = match parts[0].to_ascii_lowercase().as_str() {
|
||||||
|
"b" => GameResult::Black,
|
||||||
|
"w" => GameResult::White,
|
||||||
|
_ => panic!("unknown result format"),
|
||||||
|
};
|
||||||
|
match parts[1].to_ascii_lowercase().as_str() {
|
||||||
|
"r" | "resign" => Ok(res(Win::Resignation)),
|
||||||
|
"t" | "time" => Ok(res(Win::Time)),
|
||||||
|
"f" | "forfeit" => Ok(res(Win::Forfeit)),
|
||||||
|
_ => {
|
||||||
|
let score = parts[1].parse::<f32>().unwrap();
|
||||||
|
Ok(res(Win::Score(score)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub enum Win {
|
pub enum Win {
|
||||||
Score(i32),
|
Score(f32),
|
||||||
Resignation,
|
Resignation,
|
||||||
Forfeit,
|
Forfeit,
|
||||||
Time,
|
Time,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub enum GameType {
|
pub enum GameType {
|
||||||
Go,
|
Go,
|
||||||
Unsupported,
|
Unsupported,
|
||||||
|
@ -185,7 +239,7 @@ pub fn parse_sgf<'a>(input: &'a str) -> Result<Vec<GameTree>, Error<'a>> {
|
||||||
Some(prop) => prop.values[0].parse::<i8>().unwrap(),
|
Some(prop) => prop.values[0].parse::<i8>().unwrap(),
|
||||||
None => 4,
|
None => 4,
|
||||||
};
|
};
|
||||||
let app = tree.sequence[0]
|
let app_name = tree.sequence[0]
|
||||||
.find_prop("AP")
|
.find_prop("AP")
|
||||||
.map(|prop| prop.values[0].clone());
|
.map(|prop| prop.values[0].clone());
|
||||||
let board_size = match tree.sequence[0].find_prop("SZ") {
|
let board_size = match tree.sequence[0].find_prop("SZ") {
|
||||||
|
@ -195,14 +249,38 @@ pub fn parse_sgf<'a>(input: &'a str) -> Result<Vec<GameTree>, Error<'a>> {
|
||||||
height: 19,
|
height: 19,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
let mut info = GameInfo::default();
|
||||||
|
info.black_player = tree.sequence[0]
|
||||||
|
.find_prop("PB")
|
||||||
|
.map(|prop| prop.values.join(", "));
|
||||||
|
|
||||||
|
info.black_rank = tree.sequence[0]
|
||||||
|
.find_prop("BR")
|
||||||
|
.and_then(|prop| Rank::try_from(prop.values[0].as_str()).ok());
|
||||||
|
|
||||||
|
info.white_player = tree.sequence[0]
|
||||||
|
.find_prop("PW")
|
||||||
|
.map(|prop| prop.values.join(", "));
|
||||||
|
|
||||||
|
info.white_rank = tree.sequence[0]
|
||||||
|
.find_prop("WR")
|
||||||
|
.and_then(|prop| Rank::try_from(prop.values[0].as_str()).ok());
|
||||||
|
|
||||||
|
info.result = tree.sequence[0]
|
||||||
|
.find_prop("RE")
|
||||||
|
.and_then(|prop| GameResult::try_from(prop.values[0].as_str()).ok());
|
||||||
|
|
||||||
|
info.time_limits = tree.sequence[0]
|
||||||
|
.find_prop("TM")
|
||||||
|
.and_then(|prop| prop.values[0].parse::<u64>().ok())
|
||||||
|
.and_then(|seconds| Some(std::time::Duration::from_secs(seconds)));
|
||||||
|
|
||||||
Ok(GameTree {
|
Ok(GameTree {
|
||||||
file_format,
|
file_format,
|
||||||
|
app_name,
|
||||||
app,
|
|
||||||
game_type: GameType::Go,
|
game_type: GameType::Go,
|
||||||
board_size,
|
board_size,
|
||||||
text: input.to_owned(),
|
info,
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.collect::<Result<Vec<GameTree>, Error>>()?;
|
.collect::<Result<Vec<GameTree>, Error>>()?;
|
||||||
|
@ -239,7 +317,7 @@ mod tests {
|
||||||
assert_eq!(trees.len(), 1);
|
assert_eq!(trees.len(), 1);
|
||||||
let tree = &trees[0];
|
let tree = &trees[0];
|
||||||
assert_eq!(tree.file_format, 4);
|
assert_eq!(tree.file_format, 4);
|
||||||
assert_eq!(tree.app, None);
|
assert_eq!(tree.app_name, None);
|
||||||
assert_eq!(tree.game_type, GameType::Go);
|
assert_eq!(tree.game_type, GameType::Go);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
tree.board_size,
|
tree.board_size,
|
||||||
|
@ -255,7 +333,7 @@ mod tests {
|
||||||
assert_eq!(trees.len(), 1);
|
assert_eq!(trees.len(), 1);
|
||||||
let tree = &trees[0];
|
let tree = &trees[0];
|
||||||
assert_eq!(tree.file_format, 4);
|
assert_eq!(tree.file_format, 4);
|
||||||
assert_eq!(tree.app, None);
|
assert_eq!(tree.app_name, None);
|
||||||
assert_eq!(tree.game_type, GameType::Go);
|
assert_eq!(tree.game_type, GameType::Go);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
tree.board_size,
|
tree.board_size,
|
||||||
|
@ -266,4 +344,32 @@ mod tests {
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_parses_game_info() {
|
||||||
|
with_file(std::path::Path::new("test_data/print1.sgf"), |trees| {
|
||||||
|
assert_eq!(trees.len(), 1);
|
||||||
|
let tree = &trees[0];
|
||||||
|
assert_eq!(tree.info.black_player, Some("Takemiya Masaki".to_owned()));
|
||||||
|
assert_eq!(tree.info.black_rank, Some(Rank::Dan(9)));
|
||||||
|
assert_eq!(tree.info.white_player, Some("Cho Chikun".to_owned()));
|
||||||
|
assert_eq!(tree.info.white_rank, Some(Rank::Dan(9)));
|
||||||
|
assert_eq!(tree.info.result, Some(GameResult::White(Win::Resignation)));
|
||||||
|
assert_eq!(
|
||||||
|
tree.info.time_limits,
|
||||||
|
Some(std::time::Duration::from_secs(28800))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
tree.info.date,
|
||||||
|
vec![
|
||||||
|
chrono::NaiveDate::from_ymd_opt(1996, 10, 18).unwrap(),
|
||||||
|
chrono::NaiveDate::from_ymd_opt(1996, 10, 19).unwrap(),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(tree.info.event, Some("21st Meijin".to_owned()));
|
||||||
|
assert_eq!(tree.info.event, Some("2 (final)".to_owned()));
|
||||||
|
assert_eq!(tree.info.source, Some("Go World #78".to_owned()));
|
||||||
|
assert_eq!(tree.info.game_keeper, Some("Arno Hollosi".to_owned()));
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,3 @@
|
||||||
use std::num::ParseIntError;
|
|
||||||
|
|
||||||
use nom::{
|
use nom::{
|
||||||
branch::alt,
|
branch::alt,
|
||||||
bytes::complete::{escaped_transform, tag},
|
bytes::complete::{escaped_transform, tag},
|
||||||
|
@ -9,6 +7,7 @@ use nom::{
|
||||||
sequence::delimited,
|
sequence::delimited,
|
||||||
IResult,
|
IResult,
|
||||||
};
|
};
|
||||||
|
use std::num::ParseIntError;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum ParseSizeError {
|
pub enum ParseSizeError {
|
||||||
|
@ -22,7 +21,7 @@ impl From<ParseIntError> for ParseSizeError {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub struct Size {
|
pub struct Size {
|
||||||
pub width: i32,
|
pub width: i32,
|
||||||
pub height: i32,
|
pub height: i32,
|
||||||
|
@ -120,7 +119,6 @@ pub fn parse_collection<'a, E: nom::error::ParseError<&'a str>>(
|
||||||
// note: must fix or preserve illegally formatted game-info properties
|
// note: must fix or preserve illegally formatted game-info properties
|
||||||
// note: must correct or delete illegally foramtted properties, but display a warning
|
// note: must correct or delete illegally foramtted properties, but display a warning
|
||||||
fn parse_tree<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Tree, E> {
|
fn parse_tree<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Tree, E> {
|
||||||
println!("::: parse_tree: {}", input);
|
|
||||||
let (input, _) = multispace0(input)?;
|
let (input, _) = multispace0(input)?;
|
||||||
delimited(tag("("), parse_sequence, tag(")"))(input)
|
delimited(tag("("), parse_sequence, tag(")"))(input)
|
||||||
}
|
}
|
||||||
|
@ -128,7 +126,6 @@ fn parse_tree<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult
|
||||||
fn parse_sequence<'a, E: nom::error::ParseError<&'a str>>(
|
fn parse_sequence<'a, E: nom::error::ParseError<&'a str>>(
|
||||||
input: &'a str,
|
input: &'a str,
|
||||||
) -> IResult<&'a str, Tree, E> {
|
) -> IResult<&'a str, Tree, E> {
|
||||||
println!("::: parse_sequence: {}", input);
|
|
||||||
let (input, _) = multispace0(input)?;
|
let (input, _) = multispace0(input)?;
|
||||||
let (input, nodes) = many1(parse_node)(input)?;
|
let (input, nodes) = many1(parse_node)(input)?;
|
||||||
let (input, _) = multispace0(input)?;
|
let (input, _) = multispace0(input)?;
|
||||||
|
@ -145,7 +142,6 @@ fn parse_sequence<'a, E: nom::error::ParseError<&'a str>>(
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_node<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Node, E> {
|
fn parse_node<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Node, E> {
|
||||||
println!("::: parse_node: {}", input);
|
|
||||||
let (input, _) = multispace0(input)?;
|
let (input, _) = multispace0(input)?;
|
||||||
let (input, _) = tag(";")(input)?;
|
let (input, _) = tag(";")(input)?;
|
||||||
let (input, properties) = many1(parse_property)(input)?;
|
let (input, properties) = many1(parse_property)(input)?;
|
||||||
|
@ -155,7 +151,6 @@ fn parse_node<'a, E: nom::error::ParseError<&'a str>>(input: &'a str) -> IResult
|
||||||
fn parse_property<'a, E: nom::error::ParseError<&'a str>>(
|
fn parse_property<'a, E: nom::error::ParseError<&'a str>>(
|
||||||
input: &'a str,
|
input: &'a str,
|
||||||
) -> IResult<&'a str, Property, E> {
|
) -> IResult<&'a str, Property, E> {
|
||||||
println!(":: parse_property: {}", input);
|
|
||||||
let (input, _) = multispace0(input)?;
|
let (input, _) = multispace0(input)?;
|
||||||
let (input, ident) = alpha1(input)?;
|
let (input, ident) = alpha1(input)?;
|
||||||
let (input, values) = many1(parse_propval)(input)?;
|
let (input, values) = many1(parse_propval)(input)?;
|
||||||
|
@ -178,14 +173,8 @@ fn parse_propval<'a, E: nom::error::ParseError<&'a str>>(
|
||||||
input: &'a str,
|
input: &'a str,
|
||||||
) -> IResult<&'a str, String, E> {
|
) -> IResult<&'a str, String, E> {
|
||||||
let (input, _) = multispace0(input)?;
|
let (input, _) = multispace0(input)?;
|
||||||
println!("- {}", input);
|
|
||||||
|
|
||||||
let (input, _) = tag("[")(input)?;
|
let (input, _) = tag("[")(input)?;
|
||||||
println!("-- {}", input);
|
|
||||||
|
|
||||||
let (input, value) = parse_propval_text(input)?;
|
let (input, value) = parse_propval_text(input)?;
|
||||||
println!("--- {}", input);
|
|
||||||
|
|
||||||
let (input, _) = tag("]")(input)?;
|
let (input, _) = tag("]")(input)?;
|
||||||
|
|
||||||
Ok((input, value.unwrap_or(String::new())))
|
Ok((input, value.unwrap_or(String::new())))
|
||||||
|
|
|
@ -60,6 +60,15 @@ dependencies = [
|
||||||
"unicode-width",
|
"unicode-width",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cool_asserts"
|
||||||
|
version = "2.0.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ee9f254e53f61e2688d3677fa2cbe4e9b950afd56f48819c98817417cf6b28ec"
|
||||||
|
dependencies = [
|
||||||
|
"indent_write",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "core-foundation-sys"
|
name = "core-foundation-sys"
|
||||||
version = "0.8.4"
|
version = "0.8.4"
|
||||||
|
@ -152,6 +161,12 @@ dependencies = [
|
||||||
"cxx-build",
|
"cxx-build",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "indent_write"
|
||||||
|
version = "2.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0cfe9645a18782869361d9c8732246be7b410ad4e919d3609ebabdac00ba12c3"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "itoa"
|
name = "itoa"
|
||||||
version = "1.0.6"
|
version = "1.0.6"
|
||||||
|
@ -171,6 +186,8 @@ dependencies = [
|
||||||
name = "kifu-core"
|
name = "kifu-core"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"chrono",
|
||||||
|
"cool_asserts",
|
||||||
"go-sgf",
|
"go-sgf",
|
||||||
"grid",
|
"grid",
|
||||||
"serde",
|
"serde",
|
||||||
|
|
|
@ -6,9 +6,13 @@ edition = "2021"
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
go-sgf = { path = "../../go-sgf" }
|
chrono = { version = "0.4" }
|
||||||
grid = { version = "0.9" }
|
go-sgf = { path = "../../go-sgf" }
|
||||||
serde_json = { version = "1" }
|
grid = { version = "0.9" }
|
||||||
serde = { version = "1", features = [ "derive" ] }
|
serde_json = { version = "1" }
|
||||||
thiserror = { version = "1" }
|
serde = { version = "1", features = [ "derive" ] }
|
||||||
typeshare = { version = "1" }
|
thiserror = { version = "1" }
|
||||||
|
typeshare = { version = "1" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
cool_asserts = { version = "2" }
|
||||||
|
|
|
@ -57,6 +57,7 @@ impl Database {
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use cool_asserts::assert_matches;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn it_reads_empty_database() {
|
fn it_reads_empty_database() {
|
||||||
|
@ -73,5 +74,14 @@ mod test {
|
||||||
for game in db.all_games() {
|
for game in db.all_games() {
|
||||||
assert_eq!(game.game_type, GameType::Go);
|
assert_eq!(game.game_type, GameType::Go);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
assert_matches!(db.all_games().find(|g| g.info.black_player == Some("Steve".to_owned())),
|
||||||
|
Some(game) => {
|
||||||
|
assert_eq!(game.info.black_player, Some("Steve".to_owned()));
|
||||||
|
assert_eq!(game.info.white_player, Some("Savanni".to_owned()));
|
||||||
|
assert_eq!(game.info.date, vec![chrono::NaiveDate::from_ymd_opt(2023, 4, 19).unwrap()]);
|
||||||
|
assert_eq!(game.info.komi, Some(6.5));
|
||||||
|
}
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue