commit 90105f8b357c7393fc7e80be1819712f327006ec Author: Sridhar Ratnakumar Date: Tue Apr 6 13:16:53 2021 -0400 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..4c45dcc --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,5 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "bouncy" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..96e8883 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "bouncy" +version = "0.1.0" +authors = ["Sridhar Ratnakumar "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..965f785 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,117 @@ +use std::fmt::{Display, Formatter}; + +enum VertDir { + Up, + Down, +} + +enum HorizDir { + Left, + Right, +} + +struct Ball { + x: u32, + y: u32, + vert_dir: VertDir, + horiz_dir: HorizDir, +} + +struct Frame { + width: u32, + height: u32, +} + +struct Game { + frame: Frame, + ball: Ball, +} + +impl Game { + fn new() -> Game { + let frame = Frame { + width: 60, + height: 30, + }; + let ball = Ball { + x: 2, + y: 4, + vert_dir: VertDir::Up, + horiz_dir: HorizDir::Left, + }; + Game {frame, ball} + } + + fn step(&mut self) { + self.ball.bounce(&self.frame); + self.ball.mv(); + } +} + +impl Ball { + fn bounce(&mut self, frame: &Frame) { + if self.x == 0 { + self.horiz_dir = HorizDir::Right; + } else if self.x == frame.width - 1 { + self.horiz_dir = HorizDir::Left; + } + + if self.y == 0 { + self.vert_dir = VertDir::Down; + } else if self.y == frame.height - 1 { + self.vert_dir = VertDir::Up; + } + } + + fn mv(&mut self) { + match self.horiz_dir { + HorizDir::Left => self.x -= 1, + HorizDir::Right => self.x += 1, + } + match self.vert_dir { + VertDir::Up => self.y -= 1, + VertDir::Down => self.y += 1, + } + } +} + +impl Display for Game { + fn fmt(&self, fmt: &mut Formatter) -> std::fmt::Result { + let top_bottom = |fmt: &mut Formatter| { + write!(fmt, "+"); + for _ in 0..self.frame.width { + write!(fmt, "-"); + } + write!(fmt, "+\n") + }; + + top_bottom(fmt)?; + + for row in 0..self.frame.height { + write!(fmt, "|"); + + for column in 0..self.frame.width { + let c = if row == self.ball.y && column == self.ball.x { + 'o' + } else { + ' ' + }; + write!(fmt, "{}", c); + } + + write!(fmt, "|\n"); + } + + top_bottom(fmt) + } +} + +fn main () { + let mut game = Game::new(); + let sleep_duration = std::time::Duration::from_millis(33); + loop { + println!("{}", game); + game.step(); + std::thread::sleep(sleep_duration); + } +}