Debian Codegraph @

src/game_area.rs

raw symbols SCIP
1 /*
2 * Copyright 2020-2024 Andrey Kutejko <[email protected]>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, see <http://www.gnu.org/licenses/>.
16 *
17 * For more details see the file COPYING.
18 */
19
20 use crate::{
21 animation::InfiniteAnimation,
22 arena::ObjectType,
23 assets::Assets,
24 game::{Game, GameEvent, MoveSafety, PlayerCommand, State},
25 game_config::{GameConfig, GameConfigs},
26 graphics::calculate_contrast_color,
27 properties::{CONTROL_KEYS, Properties},
28 scores::scores::{Category, add_score},
29 sound_player::{Sound, SoundPlayer},
30 theme::Theme,
31 themes,
32 utils::settings_aware_widget,
33 };
34 use gettextrs::gettext;
35 use gtk::{gdk, gio, glib, graphene, prelude::*, subclass::prelude::*};
36 use std::{cell::Ref, error::Error, f64::consts::PI, rc::Rc, time::Duration};
37
38 const MINIMUM_TILE_WIDTH: u32 = 8;
39 const MINIMUM_TILE_HEIGHT: u32 = 8;
40 const ANIMATION_DELAY_MILLIS: u64 = 100;
41 const ANIMATION_DELAY: Duration = Duration::from_millis(ANIMATION_DELAY_MILLIS);
42
43 mod imp {
44 use super::*;
45 use crate::arena::Position;
46 use crate::game::State;
47 use crate::slot::ListenerId;
48 use crate::theme::{
49 player_animation, player_dead_animation, robot1_animation, robot2_animation,
50 };
51 use std::cell::{Cell, OnceCell, RefCell};
52 use std::sync::OnceLock;
53 use std::time::{SystemTime, UNIX_EPOCH};
54
55 pub struct GameArea {
56 pub game: RefCell<Option<Game>>,
57 pub game_listener_id: Cell<Option<ListenerId>>,
58 pub game_configs: OnceCell<GameConfigs>,
59 pub assets: OnceCell<Rc<dyn Assets>>,
60 pub theme: RefCell<Option<Theme>>,
61 pub background_color: RefCell<gdk::RGBA>,
62 pub alternate_background_color: RefCell<gdk::RGBA>,
63 pub timer_id: Cell<Option<glib::SourceId>>,
64 pub player_animation: Box<dyn InfiniteAnimation>,
65 pub player_dead_animation: Box<dyn InfiniteAnimation>,
66 pub robot1_animation: Box<dyn InfiniteAnimation>,
67 pub robot2_animation: Box<dyn InfiniteAnimation>,
68 pub sound_player: SoundPlayer,
69 pub settings: OnceCell<gio::Settings>,
70 }
71
72 #[glib::object_subclass]
73 impl ObjectSubclass for GameArea {
74 const NAME: &'static str = "RobotsGameArea";
75 type Type = super::GameArea;
76 type ParentType = gtk::Widget;
77
78 fn new() -> Self {
79 Self {
80 game: Default::default(),
81 game_listener_id: Default::default(),
82 game_configs: Default::default(),
83 assets: Default::default(),
84 theme: Default::default(),
85 background_color: RefCell::new(gdk::RGBA::BLUE),
86 alternate_background_color: RefCell::new(gdk::RGBA::GREEN),
87 timer_id: Default::default(),
88
89 player_animation: Box::new(player_animation()),
90 player_dead_animation: Box::new(player_dead_animation()),
91 robot1_animation: Box::new(robot1_animation()),
92 robot2_animation: Box::new(robot2_animation()),
93
94 sound_player: SoundPlayer::new(),
95 settings: Default::default(),
96 }
97 }
98 }
99
100 impl ObjectImpl for GameArea {
101 fn constructed(&self) {
102 self.parent_constructed();
103
104 let obj = self.obj();
105 obj.set_layout_manager(Some(gtk::BinLayout::new()));
106
107 obj.set_focusable(true);
108 obj.set_focus_on_click(true);
109
110 let click_controller = gtk::GestureClick::new();
111 click_controller.connect_pressed(glib::clone!(
112 #[weak]
113 obj,
114 move |_, n_pressed, x, y| obj.mouse_cb(n_pressed, x, y)
115 ));
116 obj.add_controller(click_controller);
117
118 let motion_controller = gtk::EventControllerMotion::new();
119 motion_controller.connect_motion(glib::clone!(
120 #[weak]
121 obj,
122 move |_, x, y| obj.move_cb(x, y)
123 ));
124 obj.add_controller(motion_controller);
125
126 let key_controller = gtk::EventControllerKey::new();
127 key_controller.connect_key_pressed(glib::clone!(
128 #[weak]
129 obj,
130 #[upgrade_or]
131 glib::Propagation::Proceed,
132 move |_, keyval, _keycode, state| obj.keyboard_cb(keyval, state)
133 ));
134 obj.add_controller(key_controller);
135
136 self.timer_id.set(Some(glib::timeout_add_local(
137 ANIMATION_DELAY,
138 glib::clone!(
139 #[strong]
140 obj,
141 move || {
142 obj.timer_cb();
143 glib::ControlFlow::Continue
144 }
145 ),
146 )));
147 }
148
149 fn dispose(&self) {
150 if let Some(source_id) = self.timer_id.take() {
151 source_id.remove();
152 }
153
154 while let Some(child) = self.obj().first_child() {
155 child.unparent();
156 }
157 }
158
159 fn signals() -> &'static [glib::subclass::Signal] {
160 static SIGNALS: OnceLock<Vec<glib::subclass::Signal>> = OnceLock::new();
161 SIGNALS.get_or_init(|| {
162 vec![
163 glib::subclass::Signal::builder("updated")
164 .return_type::<()>()
165 .build(),
166 ]
167 })
168 }
169 }
170
171 impl WidgetImpl for GameArea {
172 fn snapshot(&self, snapshot: &gtk::Snapshot) {
173 let Some(renderer) = self
174 .obj()
175 .root()
176 .and_downcast::<gtk::Window>()
177 .and_then(|w| w.renderer())
178 else {
179 eprintln!("No renderer available");
180 return;
181 };
182
183 let game_ref = self.game.borrow();
184 let Some(game) = game_ref.as_ref() else {
185 return;
186 };
187
188 let time = SystemTime::now()
189 .duration_since(UNIX_EPOCH)
190 .map_or(0, |t| t.as_millis() / ANIMATION_DELAY_MILLIS as u128)
191 as usize;
192 let tile_width = (self.obj().width() as f64) / (game.width() as f64);
193 let tile_height = (self.obj().height() as f64) / (game.height() as f64);
194 let assets = self.assets.get().unwrap();
195
196 for y in 0..game.height() {
197 for x in 0..game.width() {
198 let position = Position { x, y };
199
200 let tile_rect = graphene::Rect::new(
201 ((x as f64) * tile_width) as f32,
202 ((y as f64) * tile_height) as f32,
203 (tile_width) as f32,
204 (tile_height) as f32,
205 );
206 let color = if (x + y) % 2 != 0 {
207 self.background_color.borrow()
208 } else {
209 self.alternate_background_color.borrow()
210 };
211 snapshot.append_color(&color, &tile_rect);
212
213 let object_type = game.get(position);
214 let frame = match object_type {
215 ObjectType::Player if game.state() == State::Dead => {
216 self.player_dead_animation.frame(time)
217 }
218 ObjectType::Player => self.player_animation.frame(time),
219 ObjectType::Robot1 => self.robot1_animation.frame(time),
220 ObjectType::Robot2 => self.robot2_animation.frame(time),
221 ObjectType::Heap => 0,
222 ObjectType::None => 0,
223 };
224 self.theme.borrow().as_ref().unwrap().draw_object(
225 object_type,
226 frame,
227 snapshot,
228 &tile_rect,
229 &renderer,
230 );
231 }
232 }
233
234 if let Some(splat) = game.splat() {
235 assets.splat_bubble().draw(
236 snapshot,
237 (splat.x as f64) * tile_width + 8.0,
238 (splat.y as f64) * tile_height + 8.0,
239 );
240 }
241
242 match game.state() {
243 State::Dead => {
244 let player = game.player();
245 assets.aieee_bubble().draw(
246 snapshot,
247 (player.x as f64) * tile_width + 8.0,
248 (player.y as f64) * tile_height + 4.0,
249 );
250 }
251 State::Complete => {
252 let player = game.player();
253 assets.yahoo_bubble().draw(
254 snapshot,
255 (player.x as f64) * tile_width + 8.0,
256 (player.y as f64) * tile_height + 4.0,
257 );
258 }
259 _ => {}
260 }
261 }
262 }
263 }
264
265 glib::wrapper! {
266 pub struct GameArea(ObjectSubclass<imp::GameArea>)
267 @extends gtk::Widget,
268 @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget;
269 }
270
271 impl GameArea {
272 pub fn new(
273 game_configs: GameConfigs,
274 assets: &Rc<dyn Assets>,
275 settings: &gio::Settings,
276 ) -> Result<Self, Box<dyn Error>> {
277 let this: Self = glib::Object::builder().build();
278
279 this.imp().game_configs.set(game_configs).ok().unwrap();
280 this.imp().assets.set(assets.clone()).ok().unwrap();
281 this.set_background_color(settings.bgcolour());
282 *this.imp().theme.borrow_mut() = Some(themes::find_best_match(
283 &assets.themes(),
284 &settings.theme(),
285 )?);
286 this.imp().settings.set(settings.clone()).ok().unwrap();
287
288 settings_aware_widget(&this, settings, None, |ga, s| ga.properties_changed_cb(s));
289
290 this.start_new_game();
291
292 Ok(this)
293 }
294
295 pub fn game(&self) -> Ref<'_, Option<Game>> {
296 self.imp().game.borrow()
297 }
298
299 pub fn set_game(&self, game: Game) {
300 let mut this_game = self.imp().game.borrow_mut();
301
302 if let Some(listener_id) = self.imp().game_listener_id.take()
303 && let Some(game) = this_game.as_ref()
304 {
305 game.on_game_event.disconnect(listener_id);
306 }
307
308 self.set_size_request(
309 (MINIMUM_TILE_WIDTH * game.width()) as i32,
310 (MINIMUM_TILE_HEIGHT * game.height()) as i32,
311 );
312
313 let game_listener_id = game.on_game_event.connect(glib::clone!(
314 #[weak(rename_to = this)]
315 self,
316 move |event| {
317 let event = *event;
318 glib::MainContext::default().spawn_local(async move {
319 this.on_game_event(event).await;
320 });
321 }
322 ));
323 *this_game = Some(game);
324 self.imp().game_listener_id.set(Some(game_listener_id));
325 }
326
327 pub fn set_background_color(&self, color: gdk::RGBA) {
328 *self.imp().background_color.borrow_mut() = color;
329 *self.imp().alternate_background_color.borrow_mut() = calculate_contrast_color(&color);
330 self.queue_draw();
331 }
332
333 fn timer_cb(&self) {
334 if let Some(game) = self.imp().game.borrow().as_ref() {
335 game.tick();
336 self.emit_by_name::<()>("updated", &[]);
337 }
338 self.queue_draw();
339 }
340
341 fn mouse_cb(&self, _n_press: i32, x: f64, y: f64) {
342 let game_ref = self.imp().game.borrow();
343 let Some(game) = game_ref.as_ref() else {
344 return;
345 };
346 if game.state() == State::Playing {
347 let (dx, dy) = self.get_dir(game, x, y);
348 let cmd = PlayerCommand::from_direction(dx, dy);
349 self.player_command(cmd);
350 }
351 }
352
353 fn move_cb(&self, x: f64, y: f64) {
354 let game_ref = self.imp().game.borrow();
355 let Some(game) = game_ref.as_ref() else {
356 return;
357 };
358 if game.state() == State::Playing {
359 let (dx, dy) = self.get_dir(game, x, y);
360 let cursor_index = 3 * (dy + 1) + (dx + 1);
361 let cursor = &self.imp().assets.get().unwrap().cursors()[cursor_index as usize];
362 self.set_cursor(Some(cursor));
363 } else {
364 self.set_cursor(None);
365 }
366 }
367
368 fn keyboard_cb(&self, key: gdk::Key, state: gdk::ModifierType) -> glib::Propagation {
369 const NO_MOD: gdk::ModifierType = gdk::ModifierType::NO_MODIFIER_MASK;
370 const CTRL: gdk::ModifierType = gdk::ModifierType::CONTROL_MASK;
371
372 let command = match (state, key) {
373 (NO_MOD, gdk::Key::KP_0 | gdk::Key::KP_Insert) => Some(PlayerCommand::RandomTeleport),
374 (CTRL, gdk::Key::KP_0 | gdk::Key::KP_Insert) => Some(PlayerCommand::SafeTeleport),
375 (NO_MOD, gdk::Key::KP_1 | gdk::Key::KP_End) => Some(PlayerCommand::SW),
376 (NO_MOD, gdk::Key::KP_2 | gdk::Key::KP_Down) => Some(PlayerCommand::S),
377 (NO_MOD, gdk::Key::KP_3 | gdk::Key::KP_Page_Down) => Some(PlayerCommand::SE),
378 (NO_MOD, gdk::Key::KP_4 | gdk::Key::KP_Left) => Some(PlayerCommand::W),
379 (NO_MOD, gdk::Key::KP_5 | gdk::Key::KP_Begin) => Some(PlayerCommand::Stay),
380 (CTRL, gdk::Key::KP_5 | gdk::Key::KP_Begin) => Some(PlayerCommand::Wait),
381 (NO_MOD, gdk::Key::KP_6 | gdk::Key::KP_Right) => Some(PlayerCommand::E),
382 (NO_MOD, gdk::Key::KP_7 | gdk::Key::KP_Home) => Some(PlayerCommand::NW),
383 (NO_MOD, gdk::Key::KP_8 | gdk::Key::KP_Up) => Some(PlayerCommand::N),
384 (NO_MOD, gdk::Key::KP_9 | gdk::Key::KP_Page_Up) => Some(PlayerCommand::NE),
385 (NO_MOD, key) => {
386 let settings = self.imp().settings.get().unwrap();
387 CONTROL_KEYS
388 .iter()
389 .find_map(|ck| (settings.get_control_key(ck) == key).then_some(ck.command))
390 }
391 _ => None,
392 };
393
394 if let Some(command) = command {
395 self.player_command(command);
396 glib::Propagation::Stop
397 } else {
398 glib::Propagation::Proceed
399 }
400 }
401
402 fn get_dir(&self, game: &Game, ix: f64, iy: f64) -> (i32, i32) {
403 let tile_width = (self.width() as f64) / (game.width() as f64);
404 let tile_height = (self.height() as f64) / (game.height() as f64);
405
406 let x = ((ix / tile_width) as u32).clamp(0, game.width());
407 let y = ((iy / tile_height) as u32).clamp(0, game.height());
408
409 let player = game.player();
410
411 // If we click on our man then we assume we hold.
412 if x == player.x && y == player.y {
413 return (0, 0);
414 }
415
416 // go in the general direction of the mouse click.
417 let dx = ix / tile_width - (player.x as f64 + 0.5);
418 let dy = iy / tile_height - (player.y as f64 + 0.5);
419
420 round_direction(dx, dy)
421 }
422
423 fn properties_changed_cb(&self, settings: &gio::Settings) {
424 if let Some(game) = self.imp().game.borrow().as_ref() {
425 let selected_config = settings.selected_config();
426 match self
427 .imp()
428 .game_configs
429 .get()
430 .unwrap()
431 .find_by_name(&selected_config)
432 {
433 Some(config) => {
434 game.set_config(config);
435 }
436 None => {
437 eprintln!("Cannot change config to {}", selected_config);
438 }
439 }
440 }
441
442 let selected_theme = settings.theme();
443 match themes::find_best_match(&self.imp().assets.get().unwrap().themes(), &selected_theme) {
444 Ok(theme) => {
445 *self.imp().theme.borrow_mut() = Some(theme);
446 }
447 Err(error) => {
448 eprintln!("Cannot change theme to {}: {}", selected_theme, error);
449 }
450 }
451
452 self.set_background_color(settings.bgcolour());
453
454 self.queue_draw();
455 }
456
457 pub fn start_new_game(&self) {
458 if let Some(game) = self.imp().game.borrow().as_ref() {
459 game.start_new_game();
460 self.queue_draw();
461 }
462 }
463
464 pub fn player_command(&self, cmd: PlayerCommand) {
465 let game_ref = self.imp().game.borrow();
466 let Some(game) = game_ref.as_ref() else {
467 return;
468 };
469 let safety = self.move_safety();
470 if game.player_command(cmd, safety) {
471 self.queue_draw();
472 } else {
473 self.play_sound(Sound::Bad);
474 }
475 }
476
477 async fn on_game_event(&self, event: GameEvent) {
478 match event {
479 GameEvent::Teleported => self.play_sound(Sound::Teleport),
480 GameEvent::Splat => self.play_sound(Sound::Splat),
481 GameEvent::LevelComplete => self.play_sound(Sound::Yahoo),
482 GameEvent::Death => self.play_sound(Sound::Die),
483 GameEvent::Scored(score) if score > 0 => self.log_score(score).await,
484 GameEvent::Victory => {
485 self.message_box(&gettext(
486 "Congratulations, You Have Defeated the Robots!! \nBut Can You do it Again?",
487 ));
488 self.play_sound(Sound::Victory);
489 }
490 GameEvent::NoTeleportLocations => {
491 self.message_box(&gettext("There are no teleport locations left!!"));
492 }
493 _ => {}
494 }
495 }
496
497 fn move_safety(&self) -> MoveSafety {
498 let properties = self.imp().settings.get().unwrap();
499 properties.move_safety()
500 }
501
502 fn game_config(&self) -> Option<Rc<GameConfig>> {
503 self.imp().game.borrow().as_ref().map(|g| g.config())
504 }
505
506 /// Enters a score in the high-score table
507 async fn log_score(&self, score: u32) {
508 let Some(game_config) = self.game_config() else {
509 return;
510 };
511 let Some(window) = self.root().and_downcast::<gtk::Window>() else {
512 return;
513 };
514
515 let category = Category {
516 key: game_config.name.to_string(),
517 safety: self.move_safety(),
518 };
519 add_score(&category, score as i64, &window).await;
520 }
521
522 fn play_sound(&self, sound: Sound) {
523 let properties = self.imp().settings.get().unwrap();
524 if properties.sound() {
525 self.imp().sound_player.play(sound);
526 }
527 }
528
529 /// Displays a modal dialog box with a given message
530 fn message_box(&self, msg: &str) {
531 if let Some(window) = self.root().and_downcast::<gtk::Window>() {
532 let dialog = gtk::AlertDialog::builder().message(msg).modal(true).build();
533 dialog.show(Some(&window));
534 } else {
535 eprintln!("There is no top level window.");
536 println!("{}", msg);
537 }
538 }
539
540 pub fn connect_updated<F>(&self, f: F) -> glib::signal::SignalHandlerId
541 where
542 F: Fn(&Self) + 'static,
543 {
544 self.connect_closure(
545 "updated",
546 false,
547 glib::closure_local!(move |this: &Self| (f)(this)),
548 )
549 }
550 }
551
552 fn round_direction(dx: f64, dy: f64) -> (i32, i32) {
553 if dx.abs() < 0.5 && dy.abs() < 0.5 {
554 return (0, 0);
555 }
556
557 const MOVE_TABLE: [(i32, i32); 8] = [
558 (-1, 0),
559 (-1, -1),
560 (0, -1),
561 (1, -1),
562 (1, 0),
563 (1, 1),
564 (0, 1),
565 (-1, 1),
566 ];
567
568 let angle = f64::atan2(dy, dx);
569
570 /* Note the adjustment we have to make (+9, not +8) because atan2's idea
571 * of octants and the ones we want are shifted by PI/8. */
572 let octant = (((8.0 * angle / PI).floor() as i32 + 9) / 2) % 8;
573
574 MOVE_TABLE[octant as usize]
575 }
576
577 #[cfg(test)]
578 mod test {
579 use super::*;
580
581 #[test]
582 fn test_round_direction() {
583 assert_eq!(round_direction(-2.0, -3.0), (-1, -1));
584 assert_eq!(round_direction(-3.0, -3.0), (-1, -1));
585 assert_eq!(round_direction(-3.0, -1.0), (-1, 0));
586 assert_eq!(round_direction(-3.0, 0.0), (-1, 0));
587 assert_eq!(round_direction(-3.0, 1.0), (-1, 0));
588 assert_eq!(round_direction(-3.0, 3.0), (-1, 1));
589
590 assert_eq!(round_direction(-1.0, -3.0), (0, -1));
591 assert_eq!(round_direction(-1.0, -1.0), (-1, -1));
592 assert_eq!(round_direction(-1.0, 0.0), (-1, 0));
593 assert_eq!(round_direction(-1.0, 1.0), (-1, 1));
594 assert_eq!(round_direction(-1.0, 3.0), (0, 1));
595
596 assert_eq!(round_direction(0.0, -2.0), (0, -1));
597 assert_eq!(round_direction(0.0, -1.0), (0, -1));
598 assert_eq!(round_direction(0.0, 0.0), (0, 0));
599 assert_eq!(round_direction(0.0, 1.0), (0, 1));
600 assert_eq!(round_direction(0.0, 2.0), (0, 1));
601
602 assert_eq!(round_direction(1.0, -2.0), (1, -1));
603 assert_eq!(round_direction(1.0, -1.0), (1, -1));
604 assert_eq!(round_direction(1.0, 0.0), (1, 0));
605 assert_eq!(round_direction(1.0, 1.0), (1, 1));
606 assert_eq!(round_direction(1.0, 2.0), (1, 1));
607 assert_eq!(round_direction(1.0, 3.0), (0, 1));
608
609 assert_eq!(round_direction(2.0, -2.0), (1, -1));
610 assert_eq!(round_direction(2.0, -1.0), (1, -1));
611 assert_eq!(round_direction(2.0, 0.0), (1, 0));
612 assert_eq!(round_direction(2.0, 1.0), (1, 1));
613 assert_eq!(round_direction(2.0, 2.0), (1, 1));
614 }
615 }