Untitled
plain_text
a month ago
3.4 kB
3
Indexable
Never
use sfml::graphics::CircleShape; use sfml::graphics::Color; use sfml::graphics::RenderTarget; use sfml::graphics::RenderWindow; use sfml::graphics::Shape; use sfml::graphics::Transformable; use sfml::system::Vector2f; use sfml::window::mouse::Button; use sfml::window::Event; use sfml::window::Key; use sfml::window::Style; const FRAME_LIMIT: u32 = 30; const SPEED_LIMIT: usize = 40; pub struct Game<'a> { window: RenderWindow, circle: CircleShape<'a>, } impl<'a> Default for Game<'a> { fn default() -> Self { Self::new() } } fn vector_length(vector: Vector2f) -> f32 { (vector.x * vector.x + vector.y * vector.y).sqrt() } impl<'a> Game<'a> { pub fn new() -> Self { let mut window = RenderWindow::new( (800, 600), "grim_game", Style::default(), &Default::default(), ); window.set_framerate_limit(FRAME_LIMIT); window.set_vertical_sync_enabled(true); let mut circle = CircleShape::new(20.0, 30); circle.set_fill_color(Color::GREEN); Self { window, circle } } pub fn run(&mut self) { let mut is_a_pressed = false; let mut is_s_pressed = false; let mut is_d_pressed = false; let mut is_f_pressed = false; while self.window.is_open() { while let Some(event) = self.window.poll_event() { match event { Event::Closed => self.window.close(), Event::KeyPressed { code, .. } => match code { Key::A => is_a_pressed = true, Key::S => is_s_pressed = true, Key::D => is_d_pressed = true, Key::F => is_f_pressed = true, _ => (), }, Event::KeyReleased { code, .. } => match code { Key::A => is_a_pressed = false, Key::S => is_s_pressed = false, Key::D => is_d_pressed = false, Key::F => is_f_pressed = false, _ => (), }, Event::MouseButtonPressed { code, .. } => match code { Button::Right => self.window.close(), _ => (), }, _ => (), } let mut move_direction = Vector2f::default(); if is_a_pressed { move_direction.x += 1.0; } if is_s_pressed { move_direction.x -= 1.0; } if is_d_pressed { move_direction.y += 1.0; } if is_f_pressed { move_direction.y -= 1.0; } let length = vector_length(move_direction); if length > 0.0 { println!("{}", length); move_direction /= length; } move_direction *= SPEED_LIMIT as f32 / FRAME_LIMIT as f32; self.circle.move_(move_direction); self.window.clear(Color::BLACK); self.window.draw(&self.circle); self.window.display(); } } } }