From 8b0b992d88fd493168a71021b38e93f6a7dfba41 Mon Sep 17 00:00:00 2001 From: fwcd Date: Wed, 6 Sep 2023 01:32:29 +0200 Subject: [PATCH] Guess XML move mapping --- src/game/move.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 67 insertions(+), 5 deletions(-) diff --git a/src/game/move.rs b/src/game/move.rs index 4978ab5..7e9f097 100644 --- a/src/game/move.rs +++ b/src/game/move.rs @@ -2,30 +2,92 @@ use crate::util::{Error, Element, Result}; +use super::CubeDir; + /// A game move. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -pub struct Move; +pub enum Move { + /// Acceleration by the given amount. + Accelerate { + /// The amount to accelerate by. May be negative, but not zero. + acc: i32 + }, + /// Advancement in the direction of movement. + Advance { + /// The number of fields to move. + distance: usize, + }, + /// Nudging another ship. + Push { + /// The direction to nudge in. + direction: CubeDir, + }, + /// A turn of the ship. + Turn { + /// The direction to turn into. + direction: CubeDir, + }, +} impl TryFrom<&Element> for Move { type Error = Error; fn try_from(elem: &Element) -> Result { - todo!() + match elem.attribute("class")? { + "acceleration" => Ok(Self::Accelerate { acc: elem.attribute("acc")?.parse()? }), + "advance" => Ok(Self::Advance { distance: elem.attribute("distance")?.parse()? }), + "push" => Ok(Self::Push { direction: elem.attribute("direction")?.parse()? }), + "turn" => Ok(Self::Turn { direction: elem.attribute("direction")?.parse()? }), + class => Err(Error::UnknownVariant(format!("Unknown move class: {}", class))), + } } } impl From for Element { fn from(m: Move) -> Self { - todo!() + let base = Element::new("move"); + match m { + Move::Accelerate { acc } => base + .attribute("class", "acceleration") + .attribute("acc", acc) + .build(), + Move::Advance { distance } => base + .attribute("class", "advance") + .attribute("distance", distance) + .build(), + Move::Push { direction } => base + .attribute("class", "push") + .attribute("direction", direction) + .build(), + Move::Turn { direction } => base + .attribute("class", "turn") + .attribute("direction", direction) + .build(), + } } } #[cfg(test)] mod tests { - use crate::{util::assert_xml_format, game::Move}; + use crate::{util::assert_xml_format, game::{Move, CubeDir}}; + + // TODO: Add parse and/or roundtrip tests #[test] fn test_to_xml() { - assert_xml_format!(Move, ""); + assert_xml_format!( + Move::Accelerate { acc: -2 }, + r#""# + ); + + assert_xml_format!( + Move::Advance { distance: 10 }, + r#""# + ); + + assert_xml_format!( + Move::Push { direction: CubeDir::Left }, + r#""# + ); } }