| 1 |
use sdl2::{pixels::Color, rect::Rect}; |
| 2 |
|
| 3 |
use crate::{ |
| 4 |
app::App, |
| 5 |
game_context::{GameContext, GameState, Point}, |
| 6 |
}; |
| 7 |
|
| 8 |
|
| 9 |
pub struct Renderer { |
| 10 |
pub canvas: sdl2::render::Canvas<sdl2::video::Window>, |
| 11 |
} |
| 12 |
|
| 13 |
impl Renderer { |
| 14 |
pub const GRID_X_SIZE: u32 = 40; |
| 15 |
pub const GRID_Y_SIZE: u32 = 30; |
| 16 |
pub const DOT_SIZE_IN_PXS: u32 = 20; |
| 17 |
|
| 18 |
pub fn new(app: &mut App) -> Result<Self, String> { |
| 19 |
let video_subsystem: sdl2::VideoSubsystem = app.sdl.video()?; |
| 20 |
let window: sdl2::video::Window = video_subsystem |
| 21 |
.window( |
| 22 |
"rust-sdl2 demo", |
| 23 |
Self::GRID_X_SIZE * Self::DOT_SIZE_IN_PXS, |
| 24 |
Self::GRID_Y_SIZE * Self::DOT_SIZE_IN_PXS, |
| 25 |
) |
| 26 |
.position_centered() |
| 27 |
.opengl() |
| 28 |
.build() |
| 29 |
.unwrap(); |
| 30 |
|
| 31 |
let canvas: sdl2::render::Canvas<sdl2::video::Window> = |
| 32 |
window.clone().into_canvas().build().unwrap(); |
| 33 |
|
| 34 |
Ok(Self { |
| 35 |
canvas, |
| 36 |
}) |
| 37 |
} |
| 38 |
|
| 39 |
pub fn draw(&mut self, app: &mut App) -> Result<(), String> { |
| 40 |
self.draw_background(&app.game_context); |
| 41 |
let _ = self.draw_player(&app.game_context); |
| 42 |
let _ = self.draw_food(&app.game_context); |
| 43 |
self.canvas.present(); |
| 44 |
Ok(()) |
| 45 |
} |
| 46 |
|
| 47 |
pub fn draw_dot(&mut self, point: &Point) -> Result<(), String> { |
| 48 |
let Point(x, y) = point; |
| 49 |
self.canvas.fill_rect(Rect::new( |
| 50 |
x * Self::DOT_SIZE_IN_PXS as i32, |
| 51 |
y * Self::DOT_SIZE_IN_PXS as i32, |
| 52 |
Self::DOT_SIZE_IN_PXS, |
| 53 |
Self::DOT_SIZE_IN_PXS, |
| 54 |
)) |
| 55 |
} |
| 56 |
|
| 57 |
pub fn draw_background(&mut self, game_context: &GameContext) { |
| 58 |
let bg_color = match game_context.state { |
| 59 |
GameState::Playing => Color::RGB(0, 0, 0), |
| 60 |
GameState::Paused => Color::RGB(30, 30, 30), |
| 61 |
}; |
| 62 |
|
| 63 |
self.canvas.set_draw_color(bg_color); |
| 64 |
self.canvas.clear(); |
| 65 |
} |
| 66 |
|
| 67 |
pub fn draw_player(&mut self, game_context: &GameContext) -> Result<(), String> { |
| 68 |
self.canvas.set_draw_color(Color::GREEN); |
| 69 |
for point in &game_context.player_position { |
| 70 |
self.draw_dot(point)?; |
| 71 |
} |
| 72 |
Ok(()) |
| 73 |
} |
| 74 |
|
| 75 |
pub fn draw_food(&mut self, game_context: &GameContext) -> Result<(), String> { |
| 76 |
self.canvas.set_draw_color(Color::RED); |
| 77 |
for point in &game_context.food { |
| 78 |
self.draw_dot(point)?; |
| 79 |
} |
| 80 |
Ok(()) |
| 81 |
} |
| 82 |
} |