I'm currently teaching myself Rust with a roguelike tutorial, and I'm attempting to get a key press to move a character diagonally which would mean player_x -=1
, player_y -= 1
for up left.
No matter which way I try to arrange the code, I keep getting error messages from the compiler. I couldn't find any example of this anywhere in the documentation or on GitHub.
Key { code: Escape, .. } => return true, // exit game
// movement keys
Key { code: Up, .. } => *player_y -= 1,
Key { code: Down, .. } => *player_y += 1,
Key { code: Left, .. } => *player_x -= 1,
Key { code: Right, .. } => *player_x += 1,
Key { printable: 'k', .. } => *player_y -= 1,
Key { printable: 'k', .. } => *player_x -= 1,
_ => {}
You can kind of see what I'm trying to do here, but this throws an error message saying the pattern is unreachable, how would I fix this code?
Here's the full code, it's fairly small, not sure what would be alone necessary to compile:
extern crate tcod;
extern crate input;
use tcod::console::*;
use tcod::colors;
// actual size of the window
const SCREEN_WIDTH: i32 = 80;
const SCREEN_HEIGHT: i32 = 50;
const LIMIT_FPS: i32 = 20; // 20 frames-per-second maximum
fn handle_keys(root: &mut Root, player_x: &mut i32, player_y: &mut i32) -> bool {
use tcod::input::Key;
use tcod::input::KeyCode::*;
let key = root.wait_for_keypress(true);
match key {
Key { code: Enter, alt: true, .. } => {
// Alt+Enter: toggle fullscreen
let fullscreen = root.is_fullscreen();
root.set_fullscreen(!fullscreen);
}
Key { code: Escape, .. } => return true, // exit game
// movement keys
Key { code: Up, .. } => *player_y -= 1,
Key { code: Down, .. } => *player_y += 1,
Key { code: Left, .. } => *player_x -= 1,
Key { code: Right, .. } => *player_x += 1,
Key { printable: 'k', ..} => *player_y -= 1,
Key { printable: 'k', ..} => *player_x -= 1,
_ => {},
}
false
}
fn main() {
let mut root = Root::initializer()
.font("terminal8x8_gs_tc.png", FontLayout::Tcod)
.font_type(FontType::Greyscale)
.size(SCREEN_WIDTH, SCREEN_HEIGHT)
.title("Rust/libtcod tutorial")
.init();
tcod::system::set_fps(LIMIT_FPS);
let mut player_x = SCREEN_WIDTH / 2;
let mut player_y = SCREEN_HEIGHT / 2;
while !root.window_closed() {
root.set_default_foreground(colors::WHITE);
root.put_char(player_x, player_y, '@', BackgroundFlag::None);
root.flush();
root.put_char(player_x, player_y, ' ', BackgroundFlag::None);
// handle keys and exit game if needed
let exit = handle_keys(&mut root, &mut player_x, &mut player_y);
if exit {
break
}
}
}