-
-
Notifications
You must be signed in to change notification settings - Fork 117
/
main.rs
199 lines (173 loc) · 6.07 KB
/
main.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#![deny(clippy::all)]
#![forbid(unsafe_code)]
use game_loop::{game_loop, Time, TimeTrait as _};
use gilrs::{Button, GamepadId, Gilrs};
use log::{debug, error};
use pixels::{Error, Pixels, SurfaceTexture};
use simple_invaders::{Controls, Direction, World, FPS, HEIGHT, TIME_STEP, WIDTH};
use std::{env, time::Duration};
use winit::{
dpi::LogicalSize,
event::{Event, VirtualKeyCode},
event_loop::EventLoop,
window::WindowBuilder,
};
use winit_input_helper::WinitInputHelper;
/// Uber-struct representing the entire game.
struct Game {
/// Software renderer.
pixels: Pixels,
/// Invaders world.
world: World,
/// Player controls for world updates.
controls: Controls,
/// Event manager.
input: WinitInputHelper,
/// GamePad manager.
gilrs: Gilrs,
/// GamePad ID for the player.
gamepad: Option<GamepadId>,
/// Game pause state.
paused: bool,
/// State for key edge detection.
held: [bool; 2],
}
impl Game {
fn new(pixels: Pixels, debug: bool) -> Self {
Self {
pixels,
world: World::new(generate_seed(), debug),
controls: Controls::default(),
input: WinitInputHelper::new(),
gilrs: Gilrs::new().unwrap(), // XXX: Don't unwrap.
gamepad: None,
paused: false,
held: [false; 2],
}
}
fn update_controls(&mut self, event: &Event<()>) {
// Let winit_input_helper collect events to build its state.
self.input.update(event);
// Pump the gilrs event loop and find an active gamepad
while let Some(gilrs::Event { id, event, .. }) = self.gilrs.next_event() {
let pad = self.gilrs.gamepad(id);
if self.gamepad.is_none() {
debug!("Gamepad with id {} is connected: {}", id, pad.name());
self.gamepad = Some(id);
} else if event == gilrs::ev::EventType::Disconnected {
debug!("Gamepad with id {} is disconnected: {}", id, pad.name());
self.gamepad = None;
}
}
self.controls = {
// Keyboard controls
let held = [
self.input.key_held(VirtualKeyCode::Pause),
self.input.key_held(VirtualKeyCode::P),
];
let mut left = self.input.key_held(VirtualKeyCode::Left);
let mut right = self.input.key_held(VirtualKeyCode::Right);
let mut fire = self.input.key_held(VirtualKeyCode::Space);
let mut pause = (held[0] ^ self.held[0] & held[0]) | (held[1] ^ self.held[1] & held[1]);
self.held = held;
// GamePad controls
if let Some(id) = self.gamepad {
let gamepad = self.gilrs.gamepad(id);
left |= gamepad.is_pressed(Button::DPadLeft);
right |= gamepad.is_pressed(Button::DPadRight);
fire |= gamepad.is_pressed(Button::South);
pause |= gamepad.button_data(Button::Start).map_or(false, |button| {
button.is_pressed() && button.counter() == self.gilrs.counter()
});
}
self.gilrs.inc();
if pause {
self.paused = !self.paused;
}
let direction = if left {
Direction::Left
} else if right {
Direction::Right
} else {
Direction::Still
};
Controls { direction, fire }
};
}
}
fn main() -> Result<(), Error> {
env_logger::init();
let event_loop = EventLoop::new();
// Enable debug mode with `DEBUG=true` environment variable
let debug = env::var("DEBUG")
.unwrap_or_else(|_| "false".to_string())
.parse()
.unwrap_or(false);
let window = {
let size = LogicalSize::new(WIDTH as f64, HEIGHT as f64);
let scaled_size = LogicalSize::new(WIDTH as f64 * 3.0, HEIGHT as f64 * 3.0);
WindowBuilder::new()
.with_title("pixel invaders")
.with_inner_size(scaled_size)
.with_min_inner_size(size)
.build(&event_loop)
.unwrap()
};
let pixels = {
let window_size = window.inner_size();
let surface_texture = SurfaceTexture::new(window_size.width, window_size.height, &window);
Pixels::new(WIDTH as u32, HEIGHT as u32, surface_texture)?
};
let game = Game::new(pixels, debug);
game_loop(
event_loop,
window,
game,
FPS as u32,
0.1,
move |g| {
// Update the world
if !g.game.paused {
g.game.world.update(&g.game.controls);
}
},
move |g| {
// Drawing
g.game.world.draw(g.game.pixels.get_frame());
if let Err(e) = g.game.pixels.render() {
error!("pixels.render() failed: {}", e);
g.exit();
}
// Sleep the main thread to limit drawing to the fixed time step.
// See: https://github.com/parasyte/pixels/issues/174
let dt = TIME_STEP.as_secs_f64() - Time::now().sub(&g.current_instant());
if dt > 0.0 {
std::thread::sleep(Duration::from_secs_f64(dt));
}
},
|g, event| {
// Update controls
g.game.update_controls(&event);
// Close events
if g.game.input.key_pressed(VirtualKeyCode::Escape) || g.game.input.quit() {
g.exit();
return;
}
// Resize the window
if let Some(size) = g.game.input.window_resized() {
g.game.pixels.resize_surface(size.width, size.height);
}
},
);
}
/// Generate a pseudorandom seed for the game's PRNG.
fn generate_seed() -> (u64, u64) {
use byteorder::{ByteOrder, NativeEndian};
use getrandom::getrandom;
let mut seed = [0_u8; 16];
getrandom(&mut seed).expect("failed to getrandom");
(
NativeEndian::read_u64(&seed[0..8]),
NativeEndian::read_u64(&seed[8..16]),
)
}