use ggez::{Context, GameResult};
use ggez::graphics::{self, DrawParam, Rect};
use crate::core::resources::Resources;
use crate::ui::grid::Grid;
use crate::plants::Plant;
pub const SHOVEL_DEFAULT_X: f32 = 700.0;
pub const SHOVEL_DEFAULT_Y: f32 = 8.0;
pub const SHOVEL_WIDTH: f32 = 70.0;
pub const SHOVEL_HEIGHT: f32 = 70.0;
pub const SHOVEL_BANK_WIDTH: f32 = 80.0;
pub const SHOVEL_BANK_HEIGHT: f32 = 80.0;
pub struct Shovel {
pub position: (f32, f32),
pub is_dragging: bool,
pub rect: Rect,
pub bank_rect: Rect,
}
impl Shovel {
pub fn new() -> Self {
Shovel {
position: (SHOVEL_DEFAULT_X, SHOVEL_DEFAULT_Y),
is_dragging: false,
rect: Rect::new(SHOVEL_DEFAULT_X, SHOVEL_DEFAULT_Y, SHOVEL_WIDTH, SHOVEL_HEIGHT),
bank_rect: Rect::new(SHOVEL_DEFAULT_X - 5.0, SHOVEL_DEFAULT_Y - 5.0, SHOVEL_BANK_WIDTH, SHOVEL_BANK_HEIGHT),
}
}
pub fn update_position(&mut self, x: f32, y: f32) {
if self.is_dragging {
self.position = (x - SHOVEL_WIDTH / 2.0, y - SHOVEL_HEIGHT / 2.0);
self.rect.x = self.position.0;
self.rect.y = self.position.1;
}
}
pub fn is_clicked(&self, x: f32, y: f32) -> bool {
self.rect.contains([x, y])
}
pub fn dig(&self, x: f32, y: f32, grid: &mut Grid, plants: &mut Vec<Plant>) -> bool {
if let Some((grid_x, grid_y)) = grid.get_grid_position(x, y) {
if grid.is_occupied(grid_x, grid_y) {
let plant_index = plants.iter().position(|plant|
plant.grid_x == grid_x && plant.grid_y == grid_y
);
if let Some(index) = plant_index {
plants.remove(index);
grid.unoccupy(grid_x, grid_y);
return true;
}
}
}
false
}
pub fn draw(&self, ctx: &mut Context, resources: &Resources) -> GameResult {
let bank_param = DrawParam::default()
.dest([self.bank_rect.x, self.bank_rect.y])
.scale([self.bank_rect.w / resources.shovel_bank_image.width() as f32,
self.bank_rect.h / resources.shovel_bank_image.height() as f32]);
graphics::draw(ctx, &resources.shovel_bank_image, bank_param)?;
let shovel_param = DrawParam::default()
.dest([self.rect.x, self.rect.y])
.scale([self.rect.w / resources.shovel_image.width() as f32,
self.rect.h / resources.shovel_image.height() as f32]);
graphics::draw(ctx, &resources.shovel_image, shovel_param)?;
Ok(())
}
pub fn reset(&mut self) {
self.position = (SHOVEL_DEFAULT_X, SHOVEL_DEFAULT_Y);
self.rect.x = self.position.0;
self.rect.y = self.position.1;
self.is_dragging = false;
}
}