| 1 | use sdl2::pixels::Color; |
| 2 | use sdl2::rect::Point; |
| 3 | use sdl2::rect::Rect; |
| 4 | use sdl2::render::Canvas; |
| 5 | use sdl2::video::Window; |
| 6 | |
| 7 | use common::Point2D; |
| 8 | use sdl2::gfx::primitives::DrawRenderer; |
| 9 | use {SCREEN_HEIGHT, SCREEN_WIDTH}; |
| 10 | |
| 11 | pub trait Boll { |
| 12 | fn update(&mut self); |
| 13 | fn draw(&self, canvas: &mut Canvas<Window>, size: u32); |
| 14 | } |
| 15 | |
| 16 | pub struct SquareBoll { |
| 17 | pub pos: Point2D<f64>, |
| 18 | pub vel: Point2D<f64>, |
| 19 | } |
| 20 | |
| 21 | impl Boll for SquareBoll { |
| 22 | fn update(&mut self) { |
| 23 | self.vel.y += 0.1; |
| 24 | self.pos += self.vel; |
| 25 | |
| 26 | if self.pos.x < 0.0 { |
| 27 | self.pos.x = -self.pos.x; |
| 28 | self.vel.x = -self.vel.x; |
| 29 | } |
| 30 | if self.pos.x > SCREEN_WIDTH as f64 { |
| 31 | self.pos.x = SCREEN_WIDTH as f64 - (self.pos.x - SCREEN_WIDTH as f64); |
| 32 | self.vel.x = -self.vel.x; |
| 33 | } |
| 34 | if self.pos.y < 0.0 { |
| 35 | self.pos.y = -self.pos.y; |
| 36 | self.vel.y = -self.vel.y; |
| 37 | } |
| 38 | if self.pos.y > SCREEN_HEIGHT as f64 { |
| 39 | self.pos.y = SCREEN_HEIGHT as f64 - (self.pos.y - SCREEN_HEIGHT as f64); |
| 40 | self.vel.y = -self.vel.y; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | fn draw(&self, canvas: &mut Canvas<Window>, size: u32) { |
| 45 | canvas.set_draw_color(Color::RGBA( |
| 46 | 255 - std::cmp::min(255, (self.vel.length() * 25.0) as u8), |
| 47 | (255.0 * (self.pos.x / SCREEN_WIDTH as f64)) as u8, |
| 48 | (255.0 * (self.pos.y / SCREEN_HEIGHT as f64)) as u8, |
| 49 | 128, |
| 50 | )); |
| 51 | let mut r = Rect::new(0, 0, size, size); |
| 52 | r.center_on(Point::new(self.pos.x as i32, self.pos.y as i32)); |
| 53 | canvas.fill_rect(r).unwrap(); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | pub struct CircleBoll { |
| 58 | pub boll: SquareBoll, |
| 59 | } |
| 60 | |
| 61 | impl CircleBoll { |
| 62 | pub fn new(pos: Point2D<f64>, vel: Point2D<f64>) -> CircleBoll { |
| 63 | CircleBoll { |
| 64 | boll: SquareBoll { pos, vel }, |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | impl Boll for CircleBoll { |
| 70 | fn update(&mut self) { |
| 71 | self.boll.update(); |
| 72 | } |
| 73 | |
| 74 | fn draw(&self, canvas: &mut Canvas<Window>, size: u32) { |
| 75 | let val = 255 - std::cmp::min(255, (self.boll.vel.length() * 20.0) as u8); |
| 76 | canvas |
| 77 | .filled_circle( |
| 78 | self.boll.pos.x as i16, |
| 79 | self.boll.pos.y as i16, |
| 80 | size as i16, |
| 81 | Color::RGBA(val, val, val, 128), |
| 82 | ) |
| 83 | .unwrap(); |
| 84 | } |
| 85 | } |