summaryrefslogtreecommitdiff
path: root/src/game.rs
blob: 51cc5db4194741eb496fe09087f5b7b9a5d5f73b (plain)
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
use ggez::event::{EventHandler, KeyCode, KeyMods};
use ggez::graphics::{self, spritebatch::SpriteBatch, DrawParam, FilterMode, Image, WrapMode};
use ggez::{Context, GameResult};

use crate::camera::Camera;
use crate::dialogbox::DialogBox;
use crate::entity::Operable;
use crate::world::World;

pub struct Game {
    world: World,
    spritebatch: SpriteBatch,
    dialogbox: DialogBox,
    camera: Camera,
}

impl Game {
    pub fn new(context: &mut Context) -> GameResult<Game> {
        let mut image = Image::new(context, "/tileset.png")?;
        image.set_filter(FilterMode::Nearest);
        image.set_wrap(WrapMode::Mirror, WrapMode::Mirror);
        let world = World::new(context);
        let dimensions = world.get_dimensions();

        Ok(Game {
            world,
            spritebatch: SpriteBatch::new(image),
            dialogbox: DialogBox::new(context),
            camera: Camera::new(dimensions),
        })
    }
}

impl EventHandler for Game {
    fn update(&mut self, _context: &mut Context) -> GameResult {
        self.world.update();
        self.camera.give_center(self.world.player.get_position());

        if !self.world.player_in_talking_range() {
            self.dialogbox.populate_display(None);
        }

        self.dialogbox.update();
        Ok(())
    }

    fn draw(&mut self, context: &mut Context) -> GameResult {
        graphics::clear(context, graphics::Color::BLACK);

        self.world.draw(&mut self.spritebatch);

        graphics::draw(
            context,
            &self.spritebatch,
            DrawParam::default().dest(self.camera.draw),
        )?;

        self.dialogbox.draw(context)?;

        self.spritebatch.clear();

        graphics::present(context)?;

        Ok(())
    }

    fn key_up_event(&mut self, _: &mut Context, keycode: KeyCode, _: KeyMods) {
        self.world.give_key_up(keycode);
    }

    fn key_down_event(
        &mut self,
        context: &mut Context,
        keycode: KeyCode,
        _: KeyMods,
        repeat: bool,
    ) {
        if !repeat {
            match keycode {
                KeyCode::Q => context.continuing = false,
                KeyCode::E => self.dialogbox.populate_display(self.world.get_dialogtree()),
                KeyCode::J => self.dialogbox.next_response(),
                KeyCode::K => self.dialogbox.prev_response(),
                KeyCode::Return => self.dialogbox.choose_reponse(),
                _ => self.world.give_key_down(keycode),
            }
        }
    }
}