refactor to modules; update player based on new prototype
This commit is contained in:
@@ -1,302 +1,301 @@
|
||||
use ggez;
|
||||
#[windows_subsystem = "windows"]
|
||||
|
||||
// Next we need to actually `use` the pieces of ggez that we are going
|
||||
// to need frequently.
|
||||
use ggez::event::{KeyCode, KeyMods, EventsLoop};
|
||||
use ggez::{event, graphics, Context, GameResult};
|
||||
use log::error;
|
||||
use pixels::{Error, SurfaceTexture, PixelsBuilder};
|
||||
use pixels::wgpu::BackendBit;
|
||||
use winit::dpi::{LogicalPosition, LogicalSize, PhysicalSize};
|
||||
use winit::event::{Event, VirtualKeyCode};
|
||||
use winit::event_loop::{ControlFlow, EventLoop};
|
||||
use winit_input_helper::WinitInputHelper;
|
||||
use std::collections::HashMap;
|
||||
|
||||
// We'll bring in some things from `std` to help us in the future.
|
||||
use std::time::{Duration, Instant};
|
||||
#[derive(Clone, Debug)]
|
||||
struct Image {
|
||||
pixels: [u8; 64]
|
||||
}
|
||||
|
||||
use ggez::graphics::{Rect};
|
||||
use ggez::conf::FullscreenType;
|
||||
struct Game {
|
||||
width: usize,
|
||||
height: usize,
|
||||
player_position: (u8, u8),
|
||||
player_avatar: Image,
|
||||
palette: [[u8; 4]; 4],
|
||||
current_music: Option<String>,
|
||||
music: HashMap<String, rodio::Sink>,
|
||||
}
|
||||
|
||||
// The first thing we want to do is set up some constants that will help us out later.
|
||||
|
||||
// Here we define the size of our game board in terms of how many grid
|
||||
// cells it will take up. We choose to make a 30 x 20 game board.
|
||||
const GRID_SIZE: (u8, u8) = (16, 9);
|
||||
// dimension, i.e. 8×8 (square)
|
||||
const GRID_CELL_SIZE: u8 = 8;
|
||||
|
||||
const UPDATES_PER_SECOND: f32 = 0.4;
|
||||
// And we get the milliseconds of delay that this update rate corresponds to.
|
||||
const MILLIS_PER_UPDATE: u64 = (1.0 / UPDATES_PER_SECOND * 1000.0) as u64;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
struct GridPosition { x: u8, y: u8 }
|
||||
|
||||
impl GridPosition {
|
||||
/// We make a standard helper function so that we can create a new `GridPosition`
|
||||
/// more easily.
|
||||
pub fn new(x: u8, y: u8) -> Self {
|
||||
GridPosition { x, y }
|
||||
}
|
||||
|
||||
/// We'll make another helper function that takes one grid position and returns a new one after
|
||||
/// making one move in the direction of `dir`. We use our `SignedModulo` trait
|
||||
/// above, which is now implemented on `i16` because it satisfies the trait bounds,
|
||||
/// to automatically wrap around within our grid size if the move would have otherwise
|
||||
/// moved us off the board to the top, bottom, left, or right.
|
||||
pub fn new_from_move(pos: GridPosition, dir: Direction) -> Self {
|
||||
match dir {
|
||||
Direction::Up => GridPosition::new(pos.x, pos.y - 1),
|
||||
Direction::Down => GridPosition::new(pos.x, pos.y + 1),
|
||||
Direction::Left => GridPosition::new(pos.x - 1, pos.y),
|
||||
Direction::Right => GridPosition::new(pos.x + 1, pos.y),
|
||||
impl Game {
|
||||
fn draw(&self, screen: &mut [u8]) {
|
||||
// clear screen
|
||||
for pixel in screen.chunks_exact_mut(4) {
|
||||
pixel.copy_from_slice(&self.palette[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// We implement the `From` trait, which in this case allows us to convert easily between
|
||||
/// a GridPosition and a ggez `graphics::Rect` which fills that grid cell.
|
||||
/// Now we can just call `.into()` on a `GridPosition` where we want a
|
||||
/// `Rect` that represents that grid cell.
|
||||
impl From<GridPosition> for graphics::Rect {
|
||||
fn from(pos: GridPosition) -> Self {
|
||||
graphics::Rect::new_i32(
|
||||
pos.x as i32 * GRID_CELL_SIZE as i32,
|
||||
pos.y as i32 * GRID_CELL_SIZE as i32,
|
||||
GRID_CELL_SIZE as i32,
|
||||
GRID_CELL_SIZE as i32,
|
||||
)
|
||||
}
|
||||
}
|
||||
let (player_x, player_y) = self.player_position;
|
||||
|
||||
impl From<(u8, u8)> for GridPosition {
|
||||
fn from(pos: (u8, u8)) -> Self {
|
||||
GridPosition { x: pos.0, y: pos.1 }
|
||||
}
|
||||
}
|
||||
// each row of player avatar
|
||||
for (tile_y, row) in self.player_avatar.pixels.chunks(8).enumerate() {
|
||||
for (tile_x, pixel) in row.iter().enumerate() {
|
||||
let colour = self.palette[*pixel as usize];
|
||||
|
||||
/// Next we create an enum that will represent all the possible
|
||||
/// directions that our snake could move.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Direction {
|
||||
Up,
|
||||
Down,
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
/// We also create a helper function that will let us convert between a
|
||||
/// `ggez` `Keycode` and the `Direction` that it represents. Of course,
|
||||
/// not every keycode represents a direction, so we return `None` if this
|
||||
/// is the case.
|
||||
pub fn from_keycode(key: KeyCode) -> Option<Direction> {
|
||||
match key {
|
||||
KeyCode::Up => Some(Direction::Up),
|
||||
KeyCode::Down => Some(Direction::Down),
|
||||
KeyCode::Left => Some(Direction::Left),
|
||||
KeyCode::Right => Some(Direction::Right),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Avatar {
|
||||
pos: GridPosition,
|
||||
}
|
||||
|
||||
impl Avatar {
|
||||
pub fn new(pos: GridPosition) -> Self {
|
||||
Avatar {
|
||||
pos
|
||||
}
|
||||
}
|
||||
|
||||
/// The main update function for our snake which gets called every time
|
||||
/// we want to update the game state.
|
||||
fn update(&mut self) {
|
||||
|
||||
}
|
||||
|
||||
/// Again, note that this approach to drawing is fine for the limited scope of this
|
||||
/// example, but larger scale games will likely need a more optimized render path
|
||||
/// using SpriteBatch or something similar that batches draw calls.
|
||||
fn draw(&self, ctx: &mut Context, multiplier: &u8) -> GameResult<()> {
|
||||
let dimension = (GRID_CELL_SIZE * multiplier) as f32;
|
||||
|
||||
// And then we do the same for the head, instead making it fully red to distinguish it.
|
||||
let rectangle = graphics::Mesh::new_rectangle(
|
||||
ctx,
|
||||
graphics::DrawMode::fill(),
|
||||
ggez::graphics::Rect {
|
||||
x: (self.pos.x as u16 * GRID_CELL_SIZE as u16 * *multiplier as u16) as f32,
|
||||
y: (self.pos.y as u16 * GRID_CELL_SIZE as u16 * *multiplier as u16) as f32,
|
||||
w: dimension,
|
||||
h: dimension,
|
||||
},
|
||||
[1.0, 0.5, 0.0, 1.0].into(),
|
||||
)?;
|
||||
|
||||
graphics::draw(ctx, &rectangle, (ggez::mint::Point2 { x: 0.0, y: 0.0 },))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Now we have the heart of our game, the GameState. This struct
|
||||
/// will implement ggez's `EventHandler` trait and will therefore drive
|
||||
/// everything else that happens in our game.
|
||||
struct GameState {
|
||||
avatar: Avatar,
|
||||
/// And we track the last time we updated so that we can limit
|
||||
/// our update rate.
|
||||
last_update: Instant,
|
||||
/// integer multiples for scaling the display
|
||||
size_multiplier: u8,
|
||||
fullscreen: bool,
|
||||
scene_width: u8,
|
||||
scene_height: u8,
|
||||
}
|
||||
|
||||
impl GameState {
|
||||
pub fn new() -> Self {
|
||||
let avatar = Avatar {
|
||||
pos: (GRID_SIZE.0 / 4, GRID_SIZE.1 / 2).into(),
|
||||
};
|
||||
|
||||
GameState {
|
||||
avatar,
|
||||
last_update: Instant::now(),
|
||||
size_multiplier: 4,
|
||||
fullscreen: false,
|
||||
scene_width: 16,
|
||||
scene_height: 9
|
||||
}
|
||||
}
|
||||
|
||||
fn toggle_fullscreen(&mut self) {
|
||||
self.fullscreen = !self.fullscreen;
|
||||
}
|
||||
}
|
||||
|
||||
/// Now we implement EventHandler for GameState. This provides an interface
|
||||
/// that ggez will call automatically when different events happen.
|
||||
impl event::EventHandler for GameState {
|
||||
/// Update will happen on every frame before it is drawn. This is where we update
|
||||
/// our game state to react to whatever is happening in the game world.
|
||||
fn update(&mut self, _ctx: &mut Context) -> GameResult {
|
||||
// First we check to see if enough time has elapsed since our last update based on
|
||||
// the update rate we defined at the top.
|
||||
if Instant::now() - self.last_update >= Duration::from_millis(MILLIS_PER_UPDATE) {
|
||||
self.avatar.update();
|
||||
|
||||
// If we updated, we set our last_update to be now
|
||||
self.last_update = Instant::now();
|
||||
}
|
||||
// Finally we return `Ok` to indicate we didn't run into any errors
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// draw is where we should actually render the game's current state.
|
||||
fn draw(&mut self, ctx: &mut Context) -> GameResult {
|
||||
graphics::clear(ctx, [0.1, 0.1, 0.1, 1.0].into());
|
||||
|
||||
// todo draw the whole game, not just the avatar
|
||||
self.avatar.draw(ctx, &self.size_multiplier)?;
|
||||
|
||||
// Finally we call graphics::present to cycle the GPU's framebuffer and display
|
||||
// the new frame we just drew.
|
||||
graphics::present(ctx)?;
|
||||
|
||||
// We yield the current thread until the next update
|
||||
ggez::timer::yield_now();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// key_down_event gets fired when a key gets pressed.
|
||||
fn key_down_event(
|
||||
&mut self,
|
||||
ctx: &mut Context,
|
||||
keycode: KeyCode,
|
||||
modifier: KeyMods,
|
||||
_repeat: bool,
|
||||
) {
|
||||
if let Some(dir) = Direction::from_keycode(keycode) {
|
||||
match dir {
|
||||
Direction::Up => {
|
||||
if self.avatar.pos.y > 0 {
|
||||
self.avatar.pos.y -= 1
|
||||
}
|
||||
}
|
||||
Direction::Right => {
|
||||
if self.avatar.pos.x < GRID_SIZE.0 - 1 {
|
||||
self.avatar.pos.x += 1
|
||||
}
|
||||
}
|
||||
Direction::Down => {
|
||||
// if y is less than 8 it's ok to increment it
|
||||
if self.avatar.pos.y < GRID_SIZE.1 - 1 {
|
||||
self.avatar.pos.y += 1
|
||||
}
|
||||
}
|
||||
Direction::Left => {
|
||||
if self.avatar.pos.x > 0 {
|
||||
self.avatar.pos.x -= 1
|
||||
}
|
||||
for (v, value) in colour.iter().enumerate() {
|
||||
screen[
|
||||
(
|
||||
// player vertical offset (number of lines above)
|
||||
(player_y as usize * 8 * (8 * self.width as usize))
|
||||
+
|
||||
// player horizontal offset; number of pixels to the left
|
||||
(player_x as usize * 8)
|
||||
+
|
||||
// tile vertical offset; number of lines within tile
|
||||
(tile_y as usize * (8 * self.width as usize))
|
||||
+
|
||||
(tile_x as usize) // tile horizontal offset
|
||||
)
|
||||
* 4 // we're dealing with rgba values so multiply everything by 4
|
||||
+ v // value offset: which of the rgba values?
|
||||
] = value.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// todo handle plus/minus keys
|
||||
if keycode == KeyCode::Add {
|
||||
self.size_multiplier += 1;
|
||||
} else if keycode == KeyCode::Subtract && self.size_multiplier > 1 {
|
||||
self.size_multiplier -= 1;
|
||||
}
|
||||
|
||||
if keycode == KeyCode::F11 || (modifier == KeyMods::ALT && keycode == KeyCode::Return) {
|
||||
self.toggle_fullscreen();
|
||||
|
||||
if self.fullscreen {
|
||||
graphics::set_fullscreen(ctx, FullscreenType::True).unwrap();
|
||||
} else {
|
||||
graphics::set_fullscreen(ctx, FullscreenType::Windowed).unwrap();
|
||||
graphics::set_drawable_size(
|
||||
ctx,
|
||||
(self.scene_width * self.size_multiplier) as f32,
|
||||
(self.scene_height * self.size_multiplier) as f32
|
||||
).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
// todo change window size
|
||||
}
|
||||
|
||||
// fn update(&self) {
|
||||
//
|
||||
// }
|
||||
}
|
||||
|
||||
fn window_setup(x: u8, y: u8, multiplier: u8) -> (Context, EventsLoop) {
|
||||
let x = (x as u16 * GRID_CELL_SIZE as u16 * multiplier as u16) as f32;
|
||||
let y = (y as u16 * GRID_CELL_SIZE as u16 * multiplier as u16) as f32;
|
||||
fn main() -> Result<(), Error> {
|
||||
env_logger::init();
|
||||
|
||||
// Here we use a ContextBuilder to setup metadata about our game. First the title and author
|
||||
let (ctx, events_loop) = ggez::ContextBuilder::new("snake", "Gray Olson")
|
||||
// Next we set up the window. This title will be displayed in the title bar of the window.
|
||||
.window_setup(
|
||||
ggez::conf::WindowSetup::default().title("Write your game's title here")
|
||||
)
|
||||
// Now we get to set the size of the window, which we use our SCREEN_SIZE constant from earlier to help with
|
||||
.window_mode(ggez::conf::WindowMode::default().dimensions(x, y))
|
||||
// And finally we attempt to build the context and create the window. If it fails, we panic with the message
|
||||
// "Failed to build ggez context"
|
||||
.build()
|
||||
.unwrap();
|
||||
let mut game = Game {
|
||||
width: 16,
|
||||
height: 9,
|
||||
player_position: (8, 4),
|
||||
player_avatar: Image { pixels: [
|
||||
0,0,0,2,2,0,0,0,
|
||||
0,0,0,2,2,0,0,0,
|
||||
0,0,1,1,1,0,2,0,
|
||||
0,1,1,1,1,1,0,0,
|
||||
2,0,1,1,1,0,0,0,
|
||||
0,0,3,3,3,0,0,0,
|
||||
0,0,3,0,3,0,0,0,
|
||||
0,0,3,0,3,0,0,0,
|
||||
]},
|
||||
palette: [
|
||||
[0xff, 0x7f, 0x7f, 0xff],
|
||||
[0xff, 0xb2, 0x7f, 0xff],
|
||||
[0xff, 0xe9, 0x7f, 0xff],
|
||||
[0x00, 0x7f, 0x7f, 0x46],
|
||||
],
|
||||
current_music: None,
|
||||
music: HashMap::new(),
|
||||
};
|
||||
|
||||
(ctx, events_loop)
|
||||
}
|
||||
let event_loop = EventLoop::new();
|
||||
let mut input = WinitInputHelper::new();
|
||||
|
||||
fn main() -> GameResult {
|
||||
// Next we create a new instance of our GameState struct, which implements EventHandler
|
||||
let state = &mut GameState::new();
|
||||
|
||||
let (mut ctx, mut events_loop) = window_setup(
|
||||
GRID_SIZE.0,
|
||||
GRID_SIZE.1,
|
||||
state.size_multiplier
|
||||
let (window, p_width, p_height, mut _hidpi_factor) = create_window(
|
||||
"pixels test",
|
||||
(game.width * 8) as f64,
|
||||
(game.height * 8) as f64,
|
||||
&event_loop
|
||||
);
|
||||
|
||||
// And finally we actually run our game, passing in our context and state.
|
||||
event::run(&mut ctx, &mut events_loop, state)
|
||||
let surface_texture = SurfaceTexture::new(p_width, p_height, &window);
|
||||
|
||||
let mut pixels = PixelsBuilder::new(
|
||||
(game.width * 8) as u32, (game.height * 8) as u32, surface_texture
|
||||
)
|
||||
.wgpu_backend(BackendBit::GL | BackendBit::PRIMARY)
|
||||
.enable_vsync(false)
|
||||
.build()?;
|
||||
|
||||
let device = rodio::default_output_device().unwrap();
|
||||
|
||||
let source = rodio_xm::XMSource::from_bytes(
|
||||
include_bytes!("../ninety degrees.xm")
|
||||
);
|
||||
|
||||
let sink = rodio::Sink::new(&device);
|
||||
sink.append(source);
|
||||
sink.pause();
|
||||
|
||||
game.music.insert(":ninety degrees".into(), sink);
|
||||
|
||||
let source = rodio_xm::XMSource::from_bytes(
|
||||
include_bytes!("../orn_keygentheme2001.xm")
|
||||
);
|
||||
|
||||
let sink = rodio::Sink::new(&device);
|
||||
sink.append(source);
|
||||
sink.pause();
|
||||
|
||||
game.music.insert("orn_keygentheme2001".into(), sink);
|
||||
|
||||
game.current_music = None;
|
||||
|
||||
event_loop.run(move |event, _, control_flow| {
|
||||
// The one and only event that winit_input_helper doesn't have for us...
|
||||
if let Event::RedrawRequested(_) = event {
|
||||
game.draw(pixels.get_frame());
|
||||
|
||||
if pixels
|
||||
.render()
|
||||
.map_err(|e| error!("pixels.render() failed: {:?}", e))
|
||||
.is_err()
|
||||
{
|
||||
*control_flow = ControlFlow::Exit;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// For everything else, for let winit_input_helper collect events to build its state.
|
||||
// It returns `true` when it is time to update our game state and request a redraw.
|
||||
if input.update(&event) {
|
||||
// Close events
|
||||
if input.key_pressed(VirtualKeyCode::Escape) || input.quit() {
|
||||
*control_flow = ControlFlow::Exit;
|
||||
return;
|
||||
}
|
||||
|
||||
if input.key_pressed(VirtualKeyCode::M) {
|
||||
// pause the current tune
|
||||
if game.current_music.is_some() {
|
||||
game.music.get(game.current_music.as_ref().unwrap()).unwrap().pause();
|
||||
}
|
||||
|
||||
if game.current_music.is_none() || game.current_music.as_ref().unwrap() == "orn_keygentheme2001" {
|
||||
// play the first tune
|
||||
game.current_music = Some(":ninety degrees".into());
|
||||
game.music.get(game.current_music.as_ref().unwrap()).unwrap().play();
|
||||
} else {
|
||||
// play the second tune
|
||||
game.current_music = Some("orn_keygentheme2001".into());
|
||||
game.music.get(game.current_music.as_ref().unwrap()).unwrap().play();
|
||||
}
|
||||
}
|
||||
|
||||
if input.key_pressed(VirtualKeyCode::Left) {
|
||||
let (x, y) = game.player_position;
|
||||
if x > 0 {
|
||||
game.player_position = (x - 1, y);
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
if input.key_pressed(VirtualKeyCode::Right) {
|
||||
let (x, y) = game.player_position;
|
||||
if x < game.width as u8 - 1 {
|
||||
game.player_position = (x + 1, y);
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
if input.key_pressed(VirtualKeyCode::Up) {
|
||||
let (x, y) = game.player_position;
|
||||
if y > 0 {
|
||||
game.player_position = (x, y - 1);
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
if input.key_pressed(VirtualKeyCode::Down) {
|
||||
let (x, y) = game.player_position;
|
||||
if y < game.height as u8 - 1 {
|
||||
game.player_position = (x, y + 1);
|
||||
window.request_redraw();
|
||||
}
|
||||
}
|
||||
|
||||
// Adjust high DPI factor
|
||||
if let Some(factor) = input.scale_factor_changed() {
|
||||
_hidpi_factor = factor;
|
||||
window.request_redraw();
|
||||
}
|
||||
|
||||
// Resize the window
|
||||
if let Some(size) = input.window_resized() {
|
||||
pixels.resize_surface(size.width, size.height);
|
||||
window.request_redraw();
|
||||
}
|
||||
|
||||
*control_flow = ControlFlow::Wait;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn window_builder(title: &str, event_loop: &EventLoop<()>) -> winit::window::Window {
|
||||
winit::window::WindowBuilder::new()
|
||||
.with_visible(false)
|
||||
.with_title(title).build(&event_loop).unwrap()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn window_builder(title: &str, event_loop: &EventLoop<()>) -> winit::window::Window {
|
||||
use winit::platform::windows::WindowBuilderExtWindows;
|
||||
|
||||
winit::window::WindowBuilder::new()
|
||||
.with_drag_and_drop(false)
|
||||
.with_visible(false)
|
||||
.with_title(title).build(&event_loop).unwrap()
|
||||
}
|
||||
|
||||
/// Create a window for the game.
|
||||
///
|
||||
/// Automatically scales the window to cover about 2/3 of the monitor height.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Tuple of `(window, surface, width, height, hidpi_factor)`
|
||||
/// `width` and `height` are in `PhysicalSize` units.
|
||||
fn create_window(
|
||||
title: &str,
|
||||
width: f64,
|
||||
height: f64,
|
||||
event_loop: &EventLoop<()>,
|
||||
) -> (winit::window::Window, u32, u32, f64) {
|
||||
let window = window_builder(title, event_loop);
|
||||
|
||||
let hidpi_factor = window.scale_factor();
|
||||
|
||||
// Get dimensions
|
||||
|
||||
let (monitor_width, monitor_height) = {
|
||||
if let Some(monitor) = window.current_monitor() {
|
||||
let size = monitor.size().to_logical(hidpi_factor);
|
||||
(size.width, size.height)
|
||||
} else {
|
||||
(width, height)
|
||||
}
|
||||
};
|
||||
|
||||
let scale = (monitor_height / height * 2.0 / 3.0).round().max(1.0);
|
||||
|
||||
// Resize, center, and display the window
|
||||
let min_size: winit::dpi::LogicalSize<f64> =
|
||||
PhysicalSize::new(width, height).to_logical(hidpi_factor);
|
||||
|
||||
let default_size =
|
||||
LogicalSize::new(width * scale, height * scale);
|
||||
|
||||
let center = LogicalPosition::new(
|
||||
(monitor_width - width * scale) / 2.0,
|
||||
(monitor_height - height * scale) / 2.0,
|
||||
);
|
||||
|
||||
window.set_inner_size(default_size);
|
||||
window.set_min_inner_size(Some(min_size));
|
||||
window.set_outer_position(center);
|
||||
window.set_visible(true);
|
||||
|
||||
let size = default_size.to_physical::<f64>(hidpi_factor);
|
||||
|
||||
(
|
||||
window,
|
||||
size.width.round() as u32,
|
||||
size.height.round() as u32,
|
||||
hidpi_factor,
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user