summaryrefslogtreecommitdiff
path: root/src/main.rs
diff options
context:
space:
mode:
authorDominik Kaiser2026-05-28 09:48:49 +0200
committerDominik Kaiser2026-05-28 09:48:49 +0200
commit827d5ad9c412791dbbb367bb09316e7ce29351e3 (patch)
treef3663e6f8b55bf7576fb4433fed9441c29be954f /src/main.rs
downloadflappy-bird-827d5ad9c412791dbbb367bb09316e7ce29351e3.tar.gz
flappy-bird-827d5ad9c412791dbbb367bb09316e7ce29351e3.zip
Rust implementation
Diffstat (limited to 'src/main.rs')
-rw-r--r--src/main.rs109
1 files changed, 109 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs
new file mode 100644
index 0000000..513a830
--- /dev/null
+++ b/src/main.rs
@@ -0,0 +1,109 @@
+use macroquad::prelude::*;
+
+const SCREEN_WIDTH: f32 = 500.0;
+const SCREEN_HEIGHT: f32 = 800.0;
+const PLAYER_SIZE: f32 = 50.0;
+const GRAVITY: f32 = 1.2;
+const JUMP_HEIGHT: f32 = 20.0;
+const BAR_GAP: f32 = 150.0;
+const BAR_SPEED: f32 = 2.0;
+const BAR_WIDTH: f32 = 50.0;
+
+struct Player {
+ x: f32,
+ y: f32,
+ velocity_y: f32,
+}
+
+impl Player {
+ fn draw(&self) {
+ draw_rectangle(self.x, self.y, PLAYER_SIZE, PLAYER_SIZE, GOLD);
+ }
+
+ fn is_colliding_with_bar(&self, bar: &Bar) -> bool {
+ if self.x + PLAYER_SIZE < bar.x
+ || self.x > bar.x + BAR_WIDTH {
+ return false;
+ }
+ if self.y + PLAYER_SIZE < bar.y + BAR_GAP && self.y > bar.y - BAR_GAP {
+ return false;
+ }
+ true
+ }
+}
+
+struct Bar {
+ x: f32,
+ y: f32,
+ velocity_x: f32,
+}
+
+impl Bar {
+ fn draw(&self) {
+ draw_rectangle(self.x, 0.0, BAR_WIDTH, self.y - BAR_GAP, BLACK);
+ draw_rectangle(self.x, self.y + BAR_GAP, BAR_WIDTH, SCREEN_HEIGHT, BLACK);
+ }
+}
+
+#[macroquad::main("FlappyBird")]
+async fn main() {
+ loop {
+ loop {
+ request_new_screen_size(SCREEN_WIDTH, SCREEN_HEIGHT);
+ clear_background(BLUE);
+ if is_key_pressed(KeyCode::Enter) {
+ break;
+ }
+ next_frame().await
+ }
+
+ let score = play().await;
+ println!("{}", score);
+ }
+}
+
+async fn play() -> i32 {
+ let x = 100.0;
+ let y = (SCREEN_HEIGHT - PLAYER_SIZE) / 2.0;
+ let mut player = Player {x, y, velocity_y: 0.0};
+
+ let bar_y = macroquad::rand::gen_range(2.0 * BAR_GAP, SCREEN_HEIGHT - (2.0 * BAR_GAP));
+ let mut bar = Bar {x: SCREEN_WIDTH, y: bar_y, velocity_x: BAR_SPEED};
+
+ let mut score = 0;
+
+ loop {
+ clear_background(BLUE);
+
+ player.velocity_y += GRAVITY;
+
+ if is_key_pressed(KeyCode::Space) {
+ player.velocity_y = -JUMP_HEIGHT;
+ }
+
+ if player.y < 0.0 || player.y > SCREEN_HEIGHT - PLAYER_SIZE {
+ break;
+ }
+ player.y += player.velocity_y;
+
+ bar.x -= bar.velocity_x;
+
+ if bar.x < -BAR_WIDTH {
+ bar.x = SCREEN_WIDTH;
+ bar.y = (2.0 * BAR_GAP) +
+ (macroquad::rand::rand() as f32 % (SCREEN_HEIGHT - (4.0 * BAR_GAP)));
+ score += 1;
+ }
+
+ if player.is_colliding_with_bar(&bar) {
+ break;
+ }
+
+ player.draw();
+ bar.draw();
+ draw_text(&score.to_string(), SCREEN_WIDTH / 2.0 - 25.0, 50.0, 60.0, WHITE);
+
+ next_frame().await
+ }
+ score
+} \ No newline at end of file