forked from ggez/ggez
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02_hello_world.rs
86 lines (72 loc) · 2.66 KB
/
02_hello_world.rs
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
//! Basic hello world example.
use cgmath;
use ggez;
use ggez::event;
use ggez::graphics;
use ggez::{Context, GameResult};
use std::env;
use std::path;
// First we make a structure to contain the game's state
struct MainState {
frames: usize,
text: graphics::Text,
}
impl MainState {
fn new(ctx: &mut Context) -> GameResult<MainState> {
// The ttf file will be in your resources directory. Later, we
// will mount that directory so we can omit it in the path here.
let font = graphics::Font::new(ctx, "/DejaVuSerif.ttf")?;
let text = graphics::Text::new(("Hello world!", font, 48.0));
let s = MainState { frames: 0, text };
Ok(s)
}
}
// Then we implement the `ggez:event::EventHandler` trait on it, which
// requires callbacks for updating and drawing the game state each frame.
//
// The `EventHandler` trait also contains callbacks for event handling
// that you can override if you wish, but the defaults are fine.
impl event::EventHandler for MainState {
fn update(&mut self, _ctx: &mut Context) -> GameResult {
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult {
graphics::clear(ctx, [0.1, 0.2, 0.3, 1.0].into());
// Drawables are drawn from their top-left corner.
let offset = self.frames as f32 / 10.0;
let dest_point = mint::Point2 {
x: (offset),
y: (offset),
};
graphics::draw(ctx, &self.text, (dest_point,))?;
graphics::present(ctx)?;
self.frames += 1;
if (self.frames % 100) == 0 {
println!("FPS: {}", ggez::timer::fps(ctx));
}
Ok(())
}
}
// Now our main function, which does three things:
//
// * First, create a new `ggez::ContextBuilder`
// object which contains configuration info on things such
// as screen resolution and window title.
// * Second, create a `ggez::game::Game` object which will
// do the work of creating our MainState and running our game.
// * Then, just call `game.run()` which runs the `Game` mainloop.
pub fn main() -> GameResult {
// We add the CARGO_MANIFEST_DIR/resources to the resource paths
// so that ggez will look in our cargo project directory for files.
let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
let mut path = path::PathBuf::from(manifest_dir);
path.push("resources");
path
} else {
path::PathBuf::from("./resources")
};
let cb = ggez::ContextBuilder::new("helloworld", "ggez").add_resource_path(resource_dir);
let (ctx, event_loop) = &mut cb.build()?;
let state = &mut MainState::new(ctx)?;
event::run(ctx, event_loop, state)
}