1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
use std::fmt;
use ggez::{graphics, Context, GameResult};
use crate::ChessGui;
#[derive(Copy, Clone, Eq, PartialEq, Default, Debug)]
pub enum Align {
Left,
Right,
#[default]
Center,
}
#[derive(Copy, Clone)]
pub struct Button {
pub id: &'static str,
rect: graphics::Rect,
color: graphics::Color,
text: &'static str,
align: Align,
func: Option<fn(&mut ChessGui)>,
}
impl Button {
pub fn new(
id: &'static str,
rect: graphics::Rect,
color: graphics::Color,
text: &'static str,
align: Align,
func: Option<fn(&mut ChessGui)>,
) -> Self {
Button {
id,
rect,
color,
text,
align,
func,
}
}
pub fn contains(&self, x: f32, y: f32) -> bool {
self.rect.contains([x, y])
}
pub fn draw(&self, ctx: &mut Context, font_path: &str, font_scale: f32) -> GameResult {
self.draw_rect(ctx)?;
self.draw_text(ctx, font_path, font_scale)?;
Ok(())
}
fn draw_rect(&self, ctx: &mut Context) -> GameResult {
let mesh = graphics::MeshBuilder::new()
.rectangle(graphics::DrawMode::fill(), self.rect, self.color)?
.build(ctx)?;
graphics::draw(ctx, &mesh, graphics::DrawParam::default())?;
Ok(())
}
fn draw_text(&self, ctx: &mut Context, font_path: &str, font_scale: f32) -> GameResult {
let font = graphics::Font::new(ctx, font_path)?;
let text = graphics::Text::new((self.text, font, font_scale));
let dest_point = match self.align {
Align::Left => [self.rect.x, self.rect.y],
Align::Right => [
self.rect.x + self.rect.w - text.width(ctx),
self.rect.y + self.rect.h - text.height(ctx),
],
Align::Center => [
self.rect.x + (self.rect.w - text.width(ctx)) / 2.0,
self.rect.y + (self.rect.h - text.height(ctx)) / 2.0,
],
};
graphics::draw(ctx, &text, (dest_point,))?;
Ok(())
}
pub fn clicked(&self, chess_gui: &mut ChessGui) {
if let Some(func) = self.func {
func(chess_gui);
}
}
}
impl fmt::Display for Button {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.id)
}
}
impl fmt::Debug for Button {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.id)
}
}