dungeoncrawler

This commit is contained in:
unintendedfraud
2023-10-07 12:53:21 +02:00
parent 7649edf439
commit 227c0021fe
4 changed files with 145 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "dungeoncrawler"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bracket-lib = "~0.8.1"
+44
View File
@@ -0,0 +1,44 @@
mod map;
mod player;
mod prelude {
pub use bracket_lib::prelude::*;
pub const SCREEN_WIDTH: i32 = 80;
pub const SCREEN_HEIGHT: i32 = 50;
pub use crate::map::*;
pub use crate::player::*;
}
use prelude::*;
struct State {
map: Map,
player: Player,
}
impl State {
fn new() -> Self {
Self {
map: Map::new(),
player: Player::new(Point { x: 0, y: 0 }),
}
}
}
impl GameState for State {
fn tick(&mut self, ctx: &mut BTerm) {
ctx.cls();
self.player.update(ctx, &self.map);
self.map.render(ctx);
self.player.render(ctx);
}
}
fn main() -> BError {
let ctx = BTermBuilder::simple80x50()
.with_title("Dungeon Crawler")
.with_fps_cap(30.0)
.build()?;
main_loop(ctx, State::new())
}
+53
View File
@@ -0,0 +1,53 @@
use crate::prelude::*;
const NUM_TILES: usize = (SCREEN_WIDTH * SCREEN_HEIGHT) as usize;
#[derive(Copy, Clone, PartialEq)]
pub enum TileType {
Wall,
Floor,
}
pub struct Map {
pub tiles: Vec<TileType>,
}
impl Map {
pub fn new() -> Self {
Self {
tiles: vec![TileType::Floor; NUM_TILES],
}
}
pub fn render(&self, ctx: &mut BTerm) {
for y in 0..SCREEN_HEIGHT {
for x in 0..SCREEN_WIDTH {
let idx = map_idx(x, y);
match self.tiles[idx] {
TileType::Floor => ctx.set(x, y, YELLOW, BLACK, to_cp437('.')),
TileType::Wall => ctx.set(x, y, GREEN, BLACK, to_cp437('#')),
}
}
}
}
pub fn in_bounds(&self, point: Point) -> bool {
point.x >= 0 && point.x < SCREEN_WIDTH && point.y >= 0 && point.y < SCREEN_HEIGHT
}
pub fn can_enter_tile(&self, point: Point) -> bool {
self.in_bounds(point) && self.tiles[map_idx(point.x, point.y)] == TileType::Floor
}
pub fn try_idx(&self, point: Point) -> Option<usize> {
if !self.in_bounds(point) {
None
} else {
Some(map_idx(point.x, point.y))
}
}
}
pub fn map_idx(x: i32, y: i32) -> usize {
((y * SCREEN_WIDTH) + x) as usize
}
+39
View File
@@ -0,0 +1,39 @@
use crate::prelude::*;
pub struct Player {
position: Point,
}
impl Player {
pub fn new(position: Point) -> Self {
Player { position }
}
pub fn render(&self, ctx: &mut BTerm) {
ctx.set(
self.position.x,
self.position.y,
WHITE,
BLACK,
to_cp437('@'),
)
}
pub fn update(&mut self, ctx: &mut BTerm, map: &Map) {
if let Some(key) = ctx.key {
let delta = match key {
VirtualKeyCode::Up => Point::new(0, -1),
VirtualKeyCode::Down => Point::new(0, 1),
VirtualKeyCode::Left => Point::new(-1, 0),
VirtualKeyCode::Right => Point::new(1, 0),
_ => Point::zero(),
};
let new_position = self.position + delta;
if map.can_enter_tile(new_position) {
self.position = new_position;
}
}
}
}