From: Ian Jackson Date: Sun, 30 Aug 2020 10:28:32 +0000 (+0100) Subject: clamp onto table X-Git-Tag: otter-0.2.0~1039 X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~ianmdlvl/git?a=commitdiff_plain;h=5ab705b92ebfb5058ad1d608414f45bfcca924af;p=otter.git clamp onto table --- diff --git a/src/api.rs b/src/api.rs index 50ef5f7a..a3224a9c 100644 --- a/src/api.rs +++ b/src/api.rs @@ -212,7 +212,9 @@ impl ApiPieceOp for ApiPieceMove { _lens: &dyn Lens) -> (PieceUpdateOp<()>, Vec) { let pc = gs.pieces.byid_mut(piece).unwrap(); - + if let (_,true) = self.0.clamped(gs.table_size) { + throw!(GameError::PosOffTable); + } pc.pos = self.0; let update = PieceUpdateOp::Move(self.0); (update, vec![]) diff --git a/src/error.rs b/src/error.rs index f7d562c5..8aa36586 100644 --- a/src/error.rs +++ b/src/error.rs @@ -8,6 +8,7 @@ pub enum GameError { PieceGone, PieceHeld, FaceNotFound, + PosOffTable, InternalErrorSVG(#[from] SVGProcessingError), } diff --git a/src/gamestate.rs b/src/gamestate.rs index a9ca08aa..f860430a 100644 --- a/src/gamestate.rs +++ b/src/gamestate.rs @@ -144,6 +144,31 @@ impl Display for ZCoord { } } +pub trait ClampTable : Sized { + fn clamped(self, range: Self) -> (Self, bool); +} + +impl ClampTable for Coord { + fn clamped(self, range: Coord) -> (Coord, bool) { + if self < 0 { return (0, true) } + if self > range { return (range, true) } + return (self, false) + } +} + +impl ClampTable for Pos { + fn clamped(self, range: Pos) -> (Pos, bool) { + let mut output = ArrayVec::new(); + let mut did = false; + for (npos, tdid) in self.iter().zip(range.iter()) + .map(|(&pos, &rng)| pos.clamped(rng)) { + output.push(npos); + did |= tdid; + } + (output.into_inner().unwrap(), did) + } +} + // ---------- game state - rendering etc. ---------- impl PieceState {