From d82ccf00dc076d3cbc3f09136094f3b57e4a87d3 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Thu, 11 Nov 2021 17:18:19 -0600 Subject: [PATCH] Work on obstacles spawning --- src/main.rs | 110 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 106 insertions(+), 4 deletions(-) diff --git a/src/main.rs b/src/main.rs index a642b87..7f97056 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,75 @@ #![warn(clippy::all, clippy::pedantic)] +#![feature(stmt_expr_attributes)] use bracket_lib::prelude::*; +struct Obstacle { + x: i32, + gap_y: u16, + gap_height: u16, +} + +impl Obstacle { + fn new(x: i32, score: u32) -> Self { + let mut random = RandomNumberGenerator::new(); + Obstacle { + x, + gap_y: random.range(10, 40), + // TODO: increase difficulty + gap_height: u16::max(2, 15), + } + } +} + +struct Player { + x: i32, + y: i32, + velocity: f32, +} + +// const SCREEN_WIDTH: u16 = 80; +const SCREEN_HEIGHT: u16 = 50; +const FRAME_DURATION: f32 = 20.0; + +const X_OFFSET: i32 = 10; +const Y_START: i32 = 25; + +impl Player { + fn new(y: i32) -> Self { + Player { + x: 0, + y, + velocity: -2.0, + } + } + + fn render(&mut self, ctx: &mut BTerm) { + ctx.set(X_OFFSET, self.y, YELLOW, BLACK, to_cp437('@')); + } + + fn update(&mut self) { + if self.velocity < 2.0 { + self.velocity += 0.2; + // self.velocity = self.velocity.clamp(-2.0 + } + #[allow(clippy::cast_possible_truncation)] + self.y += self.velocity.round() as i32; + self.x += 1; + if self.y < 0 { + self.y = 0; + } + } + + fn flap(&mut self) { + self.velocity = -2.0; + } +} + struct State { - mode: GameMode + player: Player, + time: f32, + mode: GameMode, + score: u32, } enum GameMode { @@ -15,7 +81,10 @@ enum GameMode { impl State { fn new() -> Self { State { + player: Player::new(Y_START), + time: 0.0, mode: GameMode::Menu, + score: 0u32, } } @@ -35,19 +104,52 @@ impl State { } fn restart(&mut self) { + self.player = Player::new(25); + self.time = 0.0; self.mode = GameMode::Playing; } fn play(&mut self, ctx: &mut BTerm) { - ctx.cls(); + ctx.cls_bg(BLACK); + self.time += ctx.frame_time_ms; + ctx.print(1, 1, "Playing..."); + + // update + if self.time > FRAME_DURATION { + self.player.update(); + self.time %= FRAME_DURATION; + } + + if let Some(VirtualKeyCode::Space) = ctx.key { + self.player.flap(); + } + + self.player.render(ctx); + + if self.player.y > SCREEN_HEIGHT as i32 { + self.die(); + } + // self.mode = GameMode::Dead; + } + + fn die(&mut self) { self.mode = GameMode::Dead; } fn dead(&mut self, ctx: &mut BTerm) { ctx.cls(); - ctx.print(1, 1, "You died!"); - self.mode = GameMode::Menu; + ctx.print_centered(5, "You are dead. =("); + ctx.print_centered(8, "(P) Play Again"); + ctx.print_centered(9, "(Q) Quit"); + + if let Some(key) = ctx.key { + match key { + VirtualKeyCode::P => self.restart(), + VirtualKeyCode::Q => ctx.quitting = true, + _ => {}, + } + } } }