extern crate rand;
use rand::random;
extern crate simple;
use simple::{Event, Rect, Window};
static SCREEN_WIDTH: u16 = 1280;
static SCREEN_HEIGHT: u16 = 720;
fn rand_up_to(upper_bound: f32) -> f32 {
random::<f32>().abs() * upper_bound
}
#[derive(Debug, Copy, Clone)]
struct Square {
x: f32,
y: f32,
speed_x: f32,
speed_y: f32,
color: (u8, u8, u8, u8),
}
impl Square {
fn new_at_position(x: f32, y: f32) -> Self {
let angle: f32 = rand_up_to(3.141592 * 2.0);
Square {
x: x,
y: y,
speed_x: angle.sin() * 8.0,
speed_y: angle.cos() * 8.0,
color: (random(), random(), random(), 255), }
}
fn new() -> Self {
Square::new_at_position(
rand_up_to(SCREEN_WIDTH as f32),
rand_up_to(SCREEN_HEIGHT as f32),
)
}
fn update(&mut self) {
self.x += self.speed_x;
self.y += self.speed_y;
if self.x < 0.0 || self.x > SCREEN_WIDTH as f32 {
self.speed_x *= -1f32;
}
if self.y < 0.0 || self.y > SCREEN_HEIGHT as f32 {
self.speed_y *= -1f32;
}
}
fn draw(&self, app: &mut Window) {
app.set_color(self.color.0, self.color.1, self.color.2, self.color.3);
app.fill_rect(Rect::new(self.x as i32 - 32, self.y as i32 - 32, 64, 64));
}
}
fn main() {
let mut app = Window::new("Squares", SCREEN_WIDTH, SCREEN_HEIGHT);
let mut squares = vec![Square::new(), Square::new(), Square::new()];
while app.next_frame() {
while app.has_event() {
match app.next_event() {
Event::Mouse {
is_down: true,
mouse_x,
mouse_y,
..
} => squares.push(Square::new_at_position(mouse_x as f32, mouse_y as f32)),
_ => (),
}
}
app.clear();
for square in squares.iter_mut() {
square.update();
square.draw(&mut app);
}
}
}