use ggez::{Context, GameResult};
use ggez::graphics::{self, Mesh, Color, DrawParam};
pub const GRID_START_X: f32 = 254.0; pub const GRID_START_Y: f32 = 75.0; pub const GRID_CELL_HEIGHT: f32 = 100.0; pub const GRID_CELL_WIDTH: f32 = 80.0; pub const GRID_WIDTH: usize = 9; pub const GRID_HEIGHT: usize = 5;
pub struct Grid {
occupied: [[bool; GRID_WIDTH]; GRID_HEIGHT], }
impl Grid {
pub fn new() -> Self {
Grid {
occupied: [[false; GRID_WIDTH]; GRID_HEIGHT], }
}
pub fn get_grid_position(&self, x: f32, y: f32) -> Option<(usize, usize)> {
if x < GRID_START_X || x > GRID_START_X + GRID_CELL_WIDTH * GRID_WIDTH as f32 ||
y < GRID_START_Y || y > GRID_START_Y + GRID_CELL_HEIGHT * GRID_HEIGHT as f32 {
return None;
}
let grid_x = ((x - GRID_START_X) / GRID_CELL_WIDTH) as usize;
let grid_y = ((y - GRID_START_Y) / GRID_CELL_HEIGHT) as usize;
if grid_x < GRID_WIDTH && grid_y < GRID_HEIGHT {
Some((grid_x, grid_y))
} else {
None
}
}
pub fn is_occupied(&self, x: usize, y: usize) -> bool {
self.occupied[y][x]
}
pub fn occupy(&mut self, x: usize, y: usize) {
self.occupied[y][x] = true;
}
pub fn draw(&self, ctx: &mut Context) -> GameResult {
for i in 0..=GRID_WIDTH {
let x = GRID_START_X + i as f32 * GRID_CELL_WIDTH;
let line = Mesh::new_line(
ctx,
&[[x, GRID_START_Y], [x, GRID_START_Y + GRID_CELL_HEIGHT * GRID_HEIGHT as f32]],
1.0,
Color::new(0.0, 0.0, 0.0, 0.2),
)?;
graphics::draw(ctx, &line, DrawParam::default())?;
}
for i in 0..=GRID_HEIGHT {
let y = GRID_START_Y + i as f32 * GRID_CELL_HEIGHT;
let line = Mesh::new_line(
ctx,
&[[GRID_START_X, y], [GRID_START_X + GRID_CELL_WIDTH * GRID_WIDTH as f32, y]],
1.0,
Color::new(0.0, 0.0, 0.0, 0.2),
)?;
graphics::draw(ctx, &line, DrawParam::default())?;
}
Ok(())
}
}