bracket_terminal::add_wasm_support!();
use bracket_terminal::prelude::*;
use bracket_random::prelude::*;
#[derive(PartialEq, Copy, Clone)]
enum TileType {
Wall,
Floor,
}
struct State {
map: Vec<TileType>,
player_position: usize,
}
pub fn xy_idx(x: i32, y: i32) -> usize {
(y as usize * 80) + x as usize
}
pub fn idx_xy(idx: usize) -> (i32, i32) {
(idx as i32 % 80, idx as i32 / 80)
}
impl State {
pub fn new() -> State {
let mut state = State {
map: vec![TileType::Floor; 80 * 50],
player_position: xy_idx(40, 25),
};
for x in 0..80 {
state.map[xy_idx(x, 0)] = TileType::Wall;
state.map[xy_idx(x, 49)] = TileType::Wall;
}
for y in 0..50 {
state.map[xy_idx(0, y)] = TileType::Wall;
state.map[xy_idx(79, y)] = TileType::Wall;
}
let mut rng = RandomNumberGenerator::new();
for _ in 0..400 {
let x = rng.roll_dice(1, 80) - 1;
let y = rng.roll_dice(1, 50) - 1;
let idx = xy_idx(x, y);
if state.player_position != idx {
state.map[idx] = TileType::Wall;
}
}
state
}
pub fn move_player(&mut self, delta_x: i32, delta_y: i32) {
let current_position = idx_xy(self.player_position);
let new_position = (current_position.0 + delta_x, current_position.1 + delta_y);
let new_idx = xy_idx(new_position.0, new_position.1);
if self.map[new_idx] == TileType::Floor {
self.player_position = new_idx;
}
}
}
impl GameState for State {
fn tick(&mut self, ctx: &mut BTerm) {
match ctx.key {
None => {} Some(key) => {
match key {
VirtualKeyCode::Numpad8 => self.move_player(0, -1),
VirtualKeyCode::Numpad4 => self.move_player(-1, 0),
VirtualKeyCode::Numpad6 => self.move_player(1, 0),
VirtualKeyCode::Numpad2 => self.move_player(0, 1),
VirtualKeyCode::Numpad7 => self.move_player(-1, -1),
VirtualKeyCode::Numpad9 => self.move_player(1, -1),
VirtualKeyCode::Numpad1 => self.move_player(-1, 1),
VirtualKeyCode::Numpad3 => self.move_player(1, 1),
VirtualKeyCode::Up => self.move_player(0, -1),
VirtualKeyCode::Down => self.move_player(0, 1),
VirtualKeyCode::Left => self.move_player(-1, 0),
VirtualKeyCode::Right => self.move_player(1, 0),
_ => {} }
}
}
ctx.cls();
let mut y = 0;
let mut x = 0;
for tile in &self.map {
match tile {
TileType::Floor => {
ctx.print_color(
x,
y,
RGB::from_f32(0.5, 0.5, 0.5),
RGB::from_f32(0., 0., 0.),
".",
);
}
TileType::Wall => {
ctx.print_color(
x,
y,
RGB::from_f32(0.0, 1.0, 0.0),
RGB::from_f32(0., 0., 0.),
"#",
);
}
}
x += 1;
if x > 79 {
x = 0;
y += 1;
}
}
let ppos = idx_xy(self.player_position);
ctx.print_color(
ppos.0,
ppos.1,
RGB::from_f32(1.0, 1.0, 0.0),
RGB::from_f32(0., 0., 0.),
"@",
);
}
}
fn main() {
let context = BTermBuilder::simple80x50()
.with_title("Bracket Terminal Example - Walking")
.build();
let gs = State::new();
main_loop(context, gs);
}