Compare commits
13 Commits
main
...
add_level_
Author | SHA1 | Date |
---|---|---|
Joachim Lusiardi | 9971d9dee5 | |
Joachim Lusiardi | 91160edb3f | |
Joachim Lusiardi | b4122d321b | |
Joachim Lusiardi | a9c22f0944 | |
Joachim Lusiardi | 95f5fd4944 | |
Joachim Lusiardi | 3df042b0d8 | |
Joachim Lusiardi | 186e9136c7 | |
Joachim Lusiardi | ddf206343c | |
Joachim Lusiardi | 3830f26e92 | |
Joachim Lusiardi | 62040642eb | |
Joachim Lusiardi | 9101e0ae6d | |
Joachim Lusiardi | 732c68448f | |
Joachim Lusiardi | 51419ff0b8 |
|
@ -0,0 +1,11 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="EMPTY_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
|
@ -86,9 +86,34 @@ name = "el_diabolo"
|
|||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"crossterm",
|
||||
"petgraph",
|
||||
"rand",
|
||||
"ratatui",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
|
||||
|
||||
[[package]]
|
||||
name = "fixedbitset"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe9006bed769170c11f845cf00c7c1e9092aeb3f268e007c3e760ac68008070f"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.14.2"
|
||||
|
@ -105,6 +130,16 @@ version = "0.4.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "2.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indoc"
|
||||
version = "2.0.4"
|
||||
|
@ -198,6 +233,22 @@ version = "1.0.14"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c"
|
||||
|
||||
[[package]]
|
||||
name = "petgraph"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1d3afd2628e69da2be385eb6f2fd57c8ac7977ceeff6dc166ff1657b0e386a9"
|
||||
dependencies = [
|
||||
"fixedbitset",
|
||||
"indexmap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.69"
|
||||
|
@ -216,6 +267,36 @@ dependencies = [
|
|||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.8.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ratatui"
|
||||
version = "0.24.0"
|
||||
|
|
|
@ -8,3 +8,5 @@ edition = "2021"
|
|||
[dependencies]
|
||||
ratatui = "0.24.0"
|
||||
crossterm = "0.27.0"
|
||||
rand = "0.8.5"
|
||||
petgraph = "0.6.4"
|
||||
|
|
27
src/game.rs
27
src/game.rs
|
@ -1,7 +1,30 @@
|
|||
use crate::level::Level;
|
||||
use crate::level::{Level, LevelElement};
|
||||
use crate::player::Player;
|
||||
|
||||
pub struct Game {
|
||||
pub player: Player,
|
||||
pub levels: [Level; 25]
|
||||
pub levels: [Level; 25],
|
||||
}
|
||||
|
||||
impl Game {
|
||||
pub fn move_player(&mut self, dx: i8, dy: i8) {
|
||||
// check if move is allowed first
|
||||
let player = &self.player;
|
||||
let player_pos = player.get_position();
|
||||
let level = &self.levels[player_pos.get_level() as usize];
|
||||
let new_x = ((player_pos.get_x() as i16) + dx as i16) as u16;
|
||||
let new_y = ((player_pos.get_y() as i16) + dy as i16) as u16;
|
||||
let can_go: bool = match level.get_element(new_x as i16, new_y as i16) {
|
||||
None => { false }
|
||||
Some(t) => {
|
||||
match t {
|
||||
LevelElement::Wall => { false }
|
||||
_ => { true }
|
||||
}
|
||||
}
|
||||
};
|
||||
if can_go {
|
||||
self.player.change_position(dx, dy);
|
||||
}
|
||||
}
|
||||
}
|
40
src/level.rs
40
src/level.rs
|
@ -1,30 +1,48 @@
|
|||
pub const LEVEL_WIDTH: usize = 50;
|
||||
pub const LEVEL_HEIGHT: usize = 25;
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
enum LevelElement {
|
||||
pub enum LevelElement {
|
||||
Wall,
|
||||
Floor,
|
||||
StairDown,
|
||||
StairUp,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub enum RoomType {
|
||||
Start,
|
||||
End,
|
||||
StairUp,
|
||||
StairDown,
|
||||
BasicRoom,
|
||||
EmptyRoom,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub struct Level {
|
||||
structure: [[LevelElement; 25]; 80],
|
||||
pub(crate) structure: [[LevelElement; LEVEL_HEIGHT]; LEVEL_WIDTH],
|
||||
pub(crate) start_x: usize,
|
||||
pub(crate) start_y: usize,
|
||||
}
|
||||
|
||||
impl Level {
|
||||
pub fn new() -> Level {
|
||||
let mut s = [[LevelElement::Wall; 25]; 80];
|
||||
s[4][4] = LevelElement::StairDown;
|
||||
s[75][20] = LevelElement::StairUp;
|
||||
let s = [[LevelElement::Wall; LEVEL_HEIGHT]; LEVEL_WIDTH];
|
||||
Level {
|
||||
structure: s
|
||||
structure: s,
|
||||
start_x: 1,
|
||||
start_y: 1,
|
||||
}
|
||||
}
|
||||
pub fn get_element(&self, x: usize, y: usize) -> Option<LevelElement> {
|
||||
if x >= 80 || y >= 25 {
|
||||
pub fn get_element(&self, x: i16, y: i16) -> Option<LevelElement> {
|
||||
if x < 0 || y < 0 {
|
||||
return None;
|
||||
}
|
||||
Some(self.structure[x][y])
|
||||
if x >= LEVEL_WIDTH as i16 || y >= LEVEL_HEIGHT as i16 {
|
||||
return None;
|
||||
}
|
||||
Some(self.structure[x as usize][y as usize])
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -33,6 +51,6 @@ fn test_get_element() {
|
|||
let l = Level::new();
|
||||
assert_eq!(l.get_element(0, 0).unwrap(), LevelElement::Wall);
|
||||
assert_eq!(l.get_element(4, 4).unwrap(), LevelElement::StairDown);
|
||||
assert_eq!(l.get_element(79, 24).unwrap(), LevelElement::Wall);
|
||||
assert_eq!(l.get_element(80, 25), None);
|
||||
assert_eq!(l.get_element(49, 24).unwrap(), LevelElement::Wall);
|
||||
assert_eq!(l.get_element(50, 25), None);
|
||||
}
|
||||
|
|
|
@ -0,0 +1,294 @@
|
|||
use std::cmp::{max, min};
|
||||
use std::ops::Range;
|
||||
use rand::prelude::SliceRandom;
|
||||
use rand::Rng;
|
||||
use petgraph::graph::UnGraph;
|
||||
use petgraph::graph::Graph;
|
||||
use petgraph::data::*;
|
||||
use petgraph::algo::min_spanning_tree;
|
||||
use rand::rngs::ThreadRng;
|
||||
|
||||
use crate::level::{Level, LevelElement, RoomType};
|
||||
|
||||
const ROOMS_VERTICAL: usize = 7;
|
||||
const ROOMS_HORIZONTAL: usize = 4;
|
||||
const ROOM_WIDTH: usize = 7;
|
||||
const ROOM_HEIGHT: usize = 6;
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
struct ConnectionInfo {
|
||||
offset: usize,
|
||||
distance: usize,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
struct Room {
|
||||
pub kind: RoomType,
|
||||
pub offset_x: usize,
|
||||
pub offset_y: usize,
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub connection_down: Option<ConnectionInfo>,
|
||||
pub connection_right: Option<ConnectionInfo>,
|
||||
// pub connected: bool,
|
||||
}
|
||||
|
||||
impl Room {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
kind: RoomType::EmptyRoom,
|
||||
offset_x: 0,
|
||||
offset_y: 0,
|
||||
width: 0,
|
||||
height: 0,
|
||||
connection_down: None,
|
||||
connection_right: None,
|
||||
// connected: false,
|
||||
}
|
||||
}
|
||||
/// change the size and position of a room randomly within its bounds
|
||||
fn random(&mut self, rng: &mut ThreadRng) {
|
||||
let width = rng.gen_range(3..6);
|
||||
let height = rng.gen_range(3..5);
|
||||
self.width = width;
|
||||
self.height = height;
|
||||
self.offset_x = rng.gen_range(0..(ROOM_WIDTH - width));
|
||||
self.offset_y = rng.gen_range(0..(ROOM_HEIGHT - height));
|
||||
}
|
||||
fn get_x_range(&self) -> Range<usize> {
|
||||
self.offset_x..self.offset_x + self.width
|
||||
}
|
||||
fn get_y_range(&self) -> Range<usize> {
|
||||
self.offset_y..self.offset_y + self.height
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LevelGenerator {
|
||||
rooms: [[Room; ROOMS_HORIZONTAL]; ROOMS_VERTICAL],
|
||||
}
|
||||
|
||||
impl LevelGenerator {
|
||||
pub fn generate(level: usize) -> Self {
|
||||
let mut rng = rand::thread_rng();
|
||||
let mut rooms = [[Room::new(); ROOMS_HORIZONTAL]; ROOMS_VERTICAL];
|
||||
let mut graph = UnGraph::<(usize, usize), u16>::default();
|
||||
|
||||
// trick the room_connectable function into failing on the first iteration
|
||||
rooms[0][0].kind = RoomType::BasicRoom;
|
||||
|
||||
while !LevelGenerator::rooms_connectable(&rooms) {
|
||||
let mut room_types: Vec<RoomType> = Vec::with_capacity(ROOMS_HORIZONTAL * ROOMS_VERTICAL);
|
||||
// level 0 contains a start room, all others contain a stair up
|
||||
if level == 0 {
|
||||
room_types.push(RoomType::Start);
|
||||
} else {
|
||||
room_types.push(RoomType::StairUp);
|
||||
}
|
||||
// level 24 (the last) contains an end room, all others a stair down
|
||||
if level == 24 {
|
||||
room_types.push(RoomType::End);
|
||||
} else {
|
||||
room_types.push(RoomType::StairDown);
|
||||
}
|
||||
// generate a random set of rooms and shuffle them
|
||||
for _ in room_types.len()..ROOMS_HORIZONTAL * ROOMS_VERTICAL {
|
||||
match rng.gen_range(1..=6) {
|
||||
// TODO tune room type distribution
|
||||
1..=3 => { room_types.push(RoomType::EmptyRoom) }
|
||||
_ => { room_types.push(RoomType::BasicRoom) }
|
||||
}
|
||||
}
|
||||
room_types.shuffle(&mut rng);
|
||||
|
||||
graph.clear();
|
||||
// place the rooms in the array an add nodes to the graph for every non empty room
|
||||
for c in 0..ROOMS_VERTICAL {
|
||||
for r in 0..ROOMS_HORIZONTAL {
|
||||
rooms[c][r].kind = room_types.pop().unwrap();
|
||||
if rooms[c][r].kind != RoomType::EmptyRoom {
|
||||
rooms[c][r].random(&mut rng);
|
||||
graph.add_node((c, r));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// add edges to the graph connecting each room to all of its neighbours (max 4 of them)
|
||||
for c in 0..ROOMS_VERTICAL {
|
||||
for r in 0..ROOMS_HORIZONTAL {
|
||||
if rooms[c][r].kind == RoomType::EmptyRoom {
|
||||
continue;
|
||||
}
|
||||
let src_index = graph.node_indices().find(|i| graph[*i] == (c, r)).unwrap();
|
||||
for r_1 in r + 1..ROOMS_HORIZONTAL {
|
||||
if rooms[c][r_1].kind != RoomType::EmptyRoom {
|
||||
let tgt_index = graph.node_indices().find(|i| graph[*i] == (c, r_1)).unwrap();
|
||||
// todo use random weight for edge
|
||||
graph.add_edge(src_index, tgt_index, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
for c_1 in c + 1..ROOMS_VERTICAL {
|
||||
if rooms[c_1][r].kind != RoomType::EmptyRoom {
|
||||
let tgt_index = graph.node_indices().find(|i| graph[*i] == (c_1, r)).unwrap();
|
||||
// todo use random weight for edge
|
||||
graph.add_edge(src_index, tgt_index, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// calculate a minimum spanning tree
|
||||
let mst: Graph<(usize, usize), u16, petgraph::Undirected> = Graph::from_elements(min_spanning_tree(&graph));
|
||||
for edge in mst.raw_edges() {
|
||||
let src = mst[edge.source()];
|
||||
let tgt = mst[edge.target()];
|
||||
|
||||
let src_room = rooms[src.0][src.1];
|
||||
let mut tgt_room = rooms[tgt.0][tgt.1];
|
||||
|
||||
// cols are the same, either up or down
|
||||
if src.0 == tgt.0 {
|
||||
let range = LevelGenerator::range_overlap(src_room.get_x_range(), tgt_room.get_x_range());
|
||||
let position: usize;
|
||||
if range.is_empty() {
|
||||
position = range.start;
|
||||
} else {
|
||||
position = rng.gen_range(range);
|
||||
}
|
||||
if src.1 < tgt.1 {
|
||||
// src to tgt
|
||||
rooms[src.0][src.1].connection_down = Some(ConnectionInfo { offset: position, distance: tgt.1 - src.1 });
|
||||
} else {
|
||||
// tgt to src
|
||||
tgt_room.connection_down = Some(ConnectionInfo { offset: position, distance: src.1 - tgt.1 });
|
||||
}
|
||||
}
|
||||
// rows are the same, either left or right
|
||||
if src.1 == tgt.1 {
|
||||
let range = LevelGenerator::range_overlap(src_room.get_y_range(), tgt_room.get_y_range());
|
||||
let mut position: usize;
|
||||
if range.is_empty() {
|
||||
position = range.start;
|
||||
} else {
|
||||
position = rng.gen_range(range);
|
||||
}
|
||||
if src.1 == 0 && position == 0 {
|
||||
position = 1;
|
||||
}
|
||||
if src.0 < tgt.0 {
|
||||
// src to tgt
|
||||
rooms[src.0][src.1].connection_right = Some(ConnectionInfo { offset: position, distance: tgt.0 - src.0 });
|
||||
} else {
|
||||
// tgt to src
|
||||
tgt_room.connection_right = Some(ConnectionInfo { offset: position, distance: src.1 - tgt.1 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LevelGenerator {
|
||||
rooms
|
||||
}
|
||||
}
|
||||
|
||||
fn range_overlap(r1: Range<usize>, r2: Range<usize>) -> Range<usize> {
|
||||
max(r1.start, r2.start)..min(r1.end, r2.end)
|
||||
}
|
||||
|
||||
/// Verifies that for a given matrix of rooms each room has at least one other room in the
|
||||
/// same row or column.
|
||||
fn rooms_connectable(rooms: &[[Room; ROOMS_HORIZONTAL]; ROOMS_VERTICAL]) -> bool {
|
||||
for c in 0..ROOMS_VERTICAL {
|
||||
for r in 0..ROOMS_HORIZONTAL {
|
||||
if rooms[c][r].kind != RoomType::EmptyRoom {
|
||||
let mut connected = 0;
|
||||
for c1 in 0..ROOMS_VERTICAL {
|
||||
if rooms[c1][r].kind != RoomType::EmptyRoom {
|
||||
connected += 1;
|
||||
}
|
||||
}
|
||||
for r1 in 0..ROOMS_HORIZONTAL {
|
||||
if rooms[c][r1].kind != RoomType::EmptyRoom {
|
||||
connected += 1;
|
||||
}
|
||||
}
|
||||
if connected <= 2 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
pub fn render(&self) -> Level {
|
||||
let mut rng = rand::thread_rng();
|
||||
let mut s = [[LevelElement::Wall; 1 + ROOMS_HORIZONTAL * ROOM_HEIGHT]; 1 + ROOMS_VERTICAL * ROOM_WIDTH];
|
||||
let mut start_x: usize = 0;
|
||||
let mut start_y: usize = 0;
|
||||
for c in 0..ROOMS_VERTICAL {
|
||||
for r in 0..ROOMS_HORIZONTAL {
|
||||
let top = 1 + r * ROOM_HEIGHT;
|
||||
let left = 1 + c * ROOM_WIDTH;
|
||||
let room = self.rooms[c][r];
|
||||
for x in 0..room.width {
|
||||
for y in 0..room.height {
|
||||
s[left + room.offset_x + x][top + room.offset_y + y] = LevelElement::Floor;
|
||||
}
|
||||
}
|
||||
if room.kind == RoomType::StairDown {
|
||||
s[left + room.offset_x + rng.gen_range(0..room.width)][top + room.offset_y + rng.gen_range(0..room.height)] = LevelElement::StairDown;
|
||||
}
|
||||
if room.kind == RoomType::Start || room.kind == RoomType::StairUp {
|
||||
start_x = left + room.offset_x + rng.gen_range(0..room.width);
|
||||
start_y = top + room.offset_y + rng.gen_range(0..room.height);
|
||||
}
|
||||
if room.kind == RoomType::StairUp {
|
||||
s[start_x][start_y] = LevelElement::StairUp;
|
||||
}
|
||||
}
|
||||
}
|
||||
//
|
||||
for c in 0..ROOMS_VERTICAL {
|
||||
for r in 0..ROOMS_HORIZONTAL {
|
||||
let src_room = self.rooms[c][r];
|
||||
if let Some(x_conn) = src_room.connection_down {
|
||||
let tgt_room = self.rooms[c][r + x_conn.distance];
|
||||
let top = 1 + r * ROOM_HEIGHT + src_room.offset_y;
|
||||
let left = 1 + c * ROOM_WIDTH + x_conn.offset;
|
||||
let bottom = 1 + (r + x_conn.distance) * ROOM_HEIGHT + tgt_room.offset_y + tgt_room.height;
|
||||
for i in top..bottom {
|
||||
if s[left][i] == LevelElement::Wall {
|
||||
s[left][i] = LevelElement::Floor;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(y_conn) = src_room.connection_right {
|
||||
let tgt_room = self.rooms[c + y_conn.distance][r];
|
||||
|
||||
let top = 1 + r * ROOM_HEIGHT + src_room.offset_y + y_conn.offset - 1;
|
||||
let left = 1 + c * ROOM_WIDTH + src_room.offset_x;
|
||||
let right = 1 + (c + y_conn.distance) * ROOM_WIDTH + tgt_room.offset_x + tgt_room.width;
|
||||
for i in left..right {
|
||||
if s[i][top] == LevelElement::Wall {
|
||||
s[i][top] = LevelElement::Floor;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Level {
|
||||
structure: s,
|
||||
start_x,
|
||||
start_y,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_level_gen() {
|
||||
let level = LevelGenerator::generate(0);
|
||||
println!("{:?}", level);
|
||||
assert_eq!(1, 2);
|
||||
}
|
|
@ -0,0 +1,155 @@
|
|||
use ratatui::prelude::*;
|
||||
use ratatui::widgets::Widget;
|
||||
|
||||
use crate::game::Game;
|
||||
use crate::level::LevelElement;
|
||||
|
||||
const FG_BROWN: Color = Color::Rgb(186, 74, 0);
|
||||
|
||||
pub struct LevelWidget<'a> {
|
||||
pub game: &'a Game,
|
||||
}
|
||||
|
||||
impl<'a> LevelWidget<'a> {
|
||||
fn set_cell(&self, buf: &mut Buffer, x: u16, y: u16, symbol: &str, fg: Color, bg: Color) {
|
||||
buf.
|
||||
get_mut(x, y).
|
||||
set_symbol(symbol).
|
||||
set_bg(bg).
|
||||
set_fg(fg);
|
||||
}
|
||||
|
||||
fn calculate_wall(top: Option<LevelElement>, right: Option<LevelElement>, bottom: Option<LevelElement>, left: Option<LevelElement>) -> String {
|
||||
let mut val = 0;
|
||||
val += match top {
|
||||
Some(n) => {
|
||||
match n {
|
||||
LevelElement::Wall => 1,
|
||||
_ => 0
|
||||
}
|
||||
}
|
||||
None => 0
|
||||
};
|
||||
val += match right {
|
||||
Some(n) => {
|
||||
match n {
|
||||
LevelElement::Wall => 2,
|
||||
_ => 0
|
||||
}
|
||||
}
|
||||
None => 0
|
||||
};
|
||||
val += match bottom {
|
||||
Some(n) => {
|
||||
match n {
|
||||
LevelElement::Wall => 4,
|
||||
_ => 0
|
||||
}
|
||||
}
|
||||
None => 0
|
||||
};
|
||||
val += match left {
|
||||
Some(n) => {
|
||||
match n {
|
||||
LevelElement::Wall => 8,
|
||||
_ => 0
|
||||
}
|
||||
}
|
||||
None => 0
|
||||
};
|
||||
[
|
||||
"╋", "┃", "━", "┗",
|
||||
"┃", "┃", "┏", "┣",
|
||||
"━", "┛", "━", "┻",
|
||||
"┓", "┫", "┳", "╋",
|
||||
][val].to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Widget for LevelWidget<'a> {
|
||||
fn render(self, area: Rect, buf: &mut Buffer) {
|
||||
let player = &self.game.player;
|
||||
let player_pos = player.get_position();
|
||||
let level = &self.game.levels[player_pos.get_level() as usize];
|
||||
|
||||
let al = area.left();
|
||||
let at = area.top();
|
||||
|
||||
// draw the level elements
|
||||
for x in al..area.right() {
|
||||
for y in at..area.bottom() {
|
||||
let level_x = (x - al) as i16;
|
||||
let level_y = (y - at) as i16;
|
||||
match level.get_element(level_x, level_y) {
|
||||
None => {}
|
||||
Some(e) => {
|
||||
match e {
|
||||
LevelElement::Wall => {
|
||||
let top = level.get_element(level_x, level_y - 1);
|
||||
let right = level.get_element(level_x + 1, level_y);
|
||||
let bottom = level.get_element(level_x, level_y + 1);
|
||||
let left = level.get_element(level_x - 1, level_y);
|
||||
let symbol = LevelWidget::calculate_wall(top, right, bottom, left);
|
||||
self.set_cell(buf, x, y, symbol.as_str(), FG_BROWN, Color::Gray);
|
||||
}
|
||||
LevelElement::Floor => {
|
||||
self.set_cell(buf, x, y, " ", FG_BROWN, Color::Gray);
|
||||
}
|
||||
LevelElement::StairDown => {
|
||||
self.set_cell(buf, x, y, ">", Color::Yellow, Color::Gray);
|
||||
}
|
||||
LevelElement::StairUp => {
|
||||
self.set_cell(buf, x, y, "<", Color::Yellow, Color::Gray);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// draw player
|
||||
self.set_cell(buf, al + player_pos.get_x(), at + player_pos.get_y(), "8", Color::Red, Color::Gray);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_wall_symbol() {
|
||||
let wall = Some(LevelElement::Wall);
|
||||
// 0
|
||||
let s = LevelWidget::calculate_wall(None, None, None, None);
|
||||
assert_eq!(s, "╋");
|
||||
// 15
|
||||
let s = LevelWidget::calculate_wall(wall, wall, wall, wall);
|
||||
assert_eq!(s, "╋");
|
||||
|
||||
// 1
|
||||
let s = LevelWidget::calculate_wall(wall, None, None, None);
|
||||
assert_eq!(s, "┃");
|
||||
// 5
|
||||
let s = LevelWidget::calculate_wall(wall, None, wall, None);
|
||||
assert_eq!(s, "┃");
|
||||
// 4
|
||||
let s = LevelWidget::calculate_wall(None, None, wall, None);
|
||||
assert_eq!(s, "┃");
|
||||
|
||||
// 2
|
||||
let s = LevelWidget::calculate_wall(None, wall, None, None);
|
||||
assert_eq!(s, "━");
|
||||
// 10
|
||||
let s = LevelWidget::calculate_wall(None, wall, None, wall);
|
||||
assert_eq!(s, "━");
|
||||
|
||||
// 9
|
||||
let s = LevelWidget::calculate_wall(wall, None, None, wall);
|
||||
assert_eq!(s, "┛");
|
||||
// 3
|
||||
let s = LevelWidget::calculate_wall(wall, wall, None, None);
|
||||
assert_eq!(s, "┗");
|
||||
// 6
|
||||
let s = LevelWidget::calculate_wall(None, wall, wall, None);
|
||||
assert_eq!(s, "┏");
|
||||
// 12
|
||||
let s = LevelWidget::calculate_wall(None, None, wall, wall);
|
||||
assert_eq!(s, "┓");
|
||||
}
|
||||
|
101
src/main.rs
101
src/main.rs
|
@ -1,16 +1,109 @@
|
|||
use crossterm::{
|
||||
event::{self, KeyCode, KeyEventKind},
|
||||
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
|
||||
ExecutableCommand,
|
||||
};
|
||||
use ratatui::{
|
||||
prelude::{CrosstermBackend, Stylize, Terminal},
|
||||
widgets::Paragraph,
|
||||
};
|
||||
use std::io::{stdout, Result};
|
||||
use ratatui::prelude::*;
|
||||
use ratatui::widgets::Block;
|
||||
|
||||
use crate::game::Game;
|
||||
use crate::level::Level;
|
||||
use crate::level_widget::LevelWidget;
|
||||
use crate::player::Player;
|
||||
use crate::level_generator::LevelGenerator;
|
||||
|
||||
mod game;
|
||||
mod player;
|
||||
mod level;
|
||||
mod position;
|
||||
mod level_widget;
|
||||
mod level_generator;
|
||||
|
||||
fn main() {
|
||||
let g = Game {
|
||||
fn main() -> Result<()> {
|
||||
let mut levels: [Level; 25] = [Level::new(); 25];
|
||||
for l in 0..25 {
|
||||
levels[l] = LevelGenerator::generate(l).render();
|
||||
}
|
||||
let mut g = Game {
|
||||
player: Player::new("Teddy Tester", 10),
|
||||
levels: [Level::new();25]
|
||||
levels,
|
||||
};
|
||||
println!("{}",g.player.get_name());
|
||||
|
||||
g.player.change_position((levels[0].start_x) as i8, (levels[0].start_y) as i8);
|
||||
|
||||
stdout().execute(EnterAlternateScreen)?;
|
||||
enable_raw_mode()?;
|
||||
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
|
||||
terminal.clear()?;
|
||||
|
||||
loop {
|
||||
terminal.draw(|frame| {
|
||||
let mut area = frame.size();
|
||||
frame.render_widget(Block::default().style(Style::default().bg(Color::Green)), area);
|
||||
|
||||
if area.width > 80 {
|
||||
area.x = (area.width - 80) / 2;
|
||||
area.width = 80;
|
||||
}
|
||||
if area.height > 25 {
|
||||
area.y = (area.height - 25) / 2;
|
||||
area.height = 25;
|
||||
}
|
||||
|
||||
let map_area = Rect {
|
||||
x: area.x,
|
||||
y: area.y,
|
||||
width: level::LEVEL_WIDTH as u16,
|
||||
height: level::LEVEL_HEIGHT as u16,
|
||||
};
|
||||
frame.render_widget(LevelWidget { game: &g }, map_area);
|
||||
|
||||
let stats_area = Rect {
|
||||
x: area.x + 50,
|
||||
y: area.y,
|
||||
width: 30,
|
||||
height: 25,
|
||||
};
|
||||
frame.render_widget(
|
||||
Paragraph::new(format!("{}\nHealth: {}/{}\n{}/{}/{}",
|
||||
g.player.get_name(),
|
||||
g.player.get_life(),
|
||||
g.player.get_max_life(),
|
||||
g.player.get_position().get_level(),
|
||||
g.player.get_position().get_x(),
|
||||
g.player.get_position().get_y()))
|
||||
.white()
|
||||
.on_blue(),
|
||||
stats_area,
|
||||
);
|
||||
})?;
|
||||
if event::poll(std::time::Duration::from_millis(16))? {
|
||||
if let event::Event::Key(key) = event::read()? {
|
||||
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') {
|
||||
break;
|
||||
}
|
||||
if key.kind == KeyEventKind::Press && key.code == KeyCode::Left {
|
||||
g.move_player(-1, 0);
|
||||
}
|
||||
if key.kind == KeyEventKind::Press && key.code == KeyCode::Right {
|
||||
g.move_player(1, 0);
|
||||
}
|
||||
if key.kind == KeyEventKind::Press && key.code == KeyCode::Up {
|
||||
g.move_player(0, -1);
|
||||
}
|
||||
if key.kind == KeyEventKind::Press && key.code == KeyCode::Down {
|
||||
g.move_player(0, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stdout().execute(LeaveAlternateScreen)?;
|
||||
disable_raw_mode()?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -12,7 +12,7 @@ impl Player {
|
|||
pub fn new(name: &str, max_life: i16) -> Player {
|
||||
Player {
|
||||
name: name.to_string(),
|
||||
position: Position::new(0, 1, 1),
|
||||
position: Position::new(0, 0, 0),
|
||||
life: max_life,
|
||||
max_life,
|
||||
}
|
||||
|
@ -20,9 +20,17 @@ impl Player {
|
|||
pub fn get_name(&self) -> String {
|
||||
return self.name.clone();
|
||||
}
|
||||
pub fn get_life(&self) -> i16 { self.life }
|
||||
pub fn get_max_life(&self) -> i16 { self.max_life }
|
||||
pub fn change_life(&mut self, by: i16) {
|
||||
self.life = max(0, min(self.max_life, self.life + by));
|
||||
}
|
||||
pub fn get_position(&self) -> Position {
|
||||
self.position
|
||||
}
|
||||
pub fn change_position(&mut self, dx: i8, dy: i8) {
|
||||
self.position.change(dx, dy);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
@ -1,15 +1,32 @@
|
|||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub struct Position {
|
||||
level: u8,
|
||||
x: u8,
|
||||
y: u8,
|
||||
x: u16,
|
||||
y: u16,
|
||||
}
|
||||
|
||||
impl Position {
|
||||
pub fn new(level: u8, x: u8, y: u8) -> Self {
|
||||
pub fn new(level: u8, x: u16, y: u16) -> Self {
|
||||
Self {
|
||||
level,
|
||||
x,
|
||||
y,
|
||||
}
|
||||
}
|
||||
pub fn get_level(&self) -> u8 {
|
||||
self.level
|
||||
}
|
||||
|
||||
pub fn get_x(&self) -> u16 {
|
||||
self.x
|
||||
}
|
||||
|
||||
pub fn get_y(&self) -> u16 {
|
||||
self.y
|
||||
}
|
||||
|
||||
pub fn change(&mut self, dx: i8, dy: i8) {
|
||||
self.x = ((self.x as i16) + dx as i16) as u16;
|
||||
self.y = ((self.y as i16) + dy as i16) as u16;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue