Compare commits

...

20 Commits

Author SHA1 Message Date
Joachim Lusiardi 7a8fa84942 Implement chest experiment one 2023-11-22 21:09:08 +01:00
Joachim Lusiardi 849749b6bb fix bug 2023-11-22 06:59:05 +01:00
Joachim Lusiardi 470d00bbe1 git fix underflow bug 2023-11-21 21:27:26 +01:00
Joachim Lusiardi f9deea4bde remove casts 2023-11-21 20:38:27 +01:00
Joachim Lusiardi 1cfe16c4ef Implement fog of dungeon 2023-11-20 22:59:19 +01:00
Joachim Lusiardi d44c0fd53e Implement level change 2023-11-19 18:50:55 +01:00
Joachim Lusiardi 7e6b2b287b use user's name as character name 2023-11-19 16:43:45 +01:00
Joachim Lusiardi 9971d9dee5 level generator works
fixing imports and stuff
2023-11-19 16:22:16 +01:00
Joachim Lusiardi 91160edb3f minimal spanning tree implemented
no disconnected rooms
2023-11-19 09:59:19 +01:00
Joachim Lusiardi b4122d321b clean up 2023-11-15 21:57:51 +01:00
Joachim Lusiardi a9c22f0944 generator except paths 2023-11-15 21:42:20 +01:00
Joachim Lusiardi 95f5fd4944 working on level generator
rooms work, connections are missing
2023-11-14 10:01:53 +01:00
Joachim Lusiardi 3df042b0d8 start generating rooms 2023-11-12 18:58:02 +01:00
Joachim Lusiardi 186e9136c7 use rand crate 2023-11-12 17:19:55 +01:00
Joachim Lusiardi ddf206343c start generating 2023-11-12 15:48:03 +01:00
Joachim Lusiardi 3830f26e92 Check if move would end in a wall first 2023-11-12 09:20:03 +01:00
Joachim Lusiardi 62040642eb move player 2023-11-11 18:55:31 +01:00
Joachim Lusiardi 9101e0ae6d Player is drawn 2023-11-11 18:09:12 +01:00
Joachim Lusiardi 732c68448f forgotten file 2023-11-11 16:01:44 +01:00
Joachim Lusiardi 51419ff0b8 Wall drawing works 2023-11-11 07:00:29 +01:00
10 changed files with 956 additions and 27 deletions

11
.idea/el_diabolo.iml Normal file
View File

@ -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>

171
Cargo.lock generated
View File

@ -38,6 +38,12 @@ version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07"
[[package]]
name = "bumpalo"
version = "3.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec"
[[package]]
name = "cassowary"
version = "0.3.0"
@ -86,7 +92,33 @@ name = "el_diabolo"
version = "0.1.0"
dependencies = [
"crossterm",
"petgraph",
"rand",
"ratatui",
"whoami",
]
[[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]]
@ -105,6 +137,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"
@ -120,6 +162,15 @@ dependencies = [
"either",
]
[[package]]
name = "js-sys"
version = "0.3.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54c0c35952f67de54bb584e9fd912b3023117cbafc0a77d8f3dee1fb5f572fe8"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "libc"
version = "0.2.149"
@ -198,6 +249,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 +283,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"
@ -354,6 +451,80 @@ version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
version = "0.2.88"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7daec296f25a1bae309c0cd5c29c4b260e510e6d813c286b19eaadf409d40fce"
dependencies = [
"cfg-if",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.88"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e397f4664c0e4e428e8313a469aaa58310d302159845980fd23b0f22a847f217"
dependencies = [
"bumpalo",
"log",
"once_cell",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.88"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5961017b3b08ad5f3fe39f1e79877f8ee7c23c5e5fd5eb80de95abc41f1f16b2"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.88"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5353b8dab669f5e10f5bd76df26a9360c748f054f862ff5f3f8aae0c7fb3907"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.88"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d046c5d029ba91a1ed14da14dca44b68bf2f124cfbaf741c54151fdb3e0750b"
[[package]]
name = "web-sys"
version = "0.3.65"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5db499c5f66323272151db0e666cd34f78617522fb0c1604d31a27c50c206a85"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "whoami"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22fc3756b8a9133049b26c7f61ab35416c130e8c09b660f5b3958b446f52cc50"
dependencies = [
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "winapi"
version = "0.3.9"

View File

@ -8,3 +8,6 @@ edition = "2021"
[dependencies]
ratatui = "0.24.0"
crossterm = "0.27.0"
rand = "0.8.5"
petgraph = "0.6.4"
whoami = "1.4.1"

View File

@ -1,7 +1,54 @@
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: i16, dy: i16) {
// check if move is allowed first
let player = &self.player;
let player_pos = player.get_position();
let level = &self.levels[player_pos.get_level()];
let new_x: i16 = player_pos.get_x() as i16 + dx;
let new_y: i16 = player_pos.get_y() as i16 + dy;
let can_go: bool = match level.get_element(new_x, new_y) {
None => { false }
Some(t) => {
match t {
LevelElement::Wall => { false }
_ => { true }
}
}
};
if can_go {
match level.get_element(new_x, new_y).unwrap() {
LevelElement::StairDown => {
let next_level = player_pos.get_level() + 1;
let start_x: usize = self.levels[next_level].start_x;
let start_y: usize = self.levels[next_level].start_y;
self.player.set_position(next_level, start_x, start_y);
self.levels[next_level].discover(self.player.get_position());
}
LevelElement::StairUp => {
self.player.set_position(
player_pos.get_level() - 1,
self.levels[player_pos.get_level() - 1].end_x,
self.levels[player_pos.get_level() - 1].end_y,
);
}
LevelElement::Chest {gold} => {
self.player.add_gold(gold);
self.player.change_position(dx, dy);
self.levels[player_pos.get_level()].discover(self.player.get_position());
}
_ => {
self.player.change_position(dx, dy);
self.levels[player_pos.get_level()].discover(self.player.get_position());
}
};
}
}
}

View File

@ -1,30 +1,101 @@
use std::cmp::{max, min};
use crate::position::Position;
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,
Start,
End,
Chest { gold: usize },
Unknown,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum RoomType {
Start,
End,
StairUp,
StairDown,
BasicRoom,
TreasureRoom,
EmptyRoom,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Level {
structure: [[LevelElement; 25]; 80],
pub(crate) structure: [[LevelElement; LEVEL_HEIGHT]; LEVEL_WIDTH],
pub(crate) discovered: [[bool; LEVEL_HEIGHT]; LEVEL_WIDTH],
pub(crate) start_x: usize,
pub(crate) start_y: usize,
pub(crate) end_x: usize,
pub(crate) end_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,
discovered: [[false; LEVEL_HEIGHT]; LEVEL_WIDTH],
start_x: 1,
start_y: 1,
end_x: 1,
end_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])
let x = x as usize;
let y = y as usize;
if x >= LEVEL_WIDTH || y >= LEVEL_HEIGHT {
return None;
}
if self.discovered[x][y] {
return Some(self.structure[x][y]);
}
return Some(LevelElement::Unknown);
}
/// discover the area with in the level around the given position
pub fn discover(&mut self, pos: Position) {
let x = pos.get_x();
let y = pos.get_y();
for x_r in max(x - 1, 0)..=min(x + 1, LEVEL_WIDTH - 1) {
for y_r in max(y - 1, 0)..=min(y + 1, LEVEL_HEIGHT - 1) {
self.discovered[x_r][y_r] = true;
}
}
for x_r in x..=min(x + 2, LEVEL_WIDTH - 1) {
self.discovered[x_r][y] = true;
if self.structure[x_r][y] == LevelElement::Wall {
break;
}
}
for y_r in y..=min(y + 2, LEVEL_HEIGHT - 1) {
self.discovered[x][y_r] = true;
if self.structure[x][y_r] == LevelElement::Wall {
break;
}
}
for x_r in (max(x, 2)..x + 2).rev() {
self.discovered[x_r - 2][y] = true;
if self.structure[x_r - 2][y] == LevelElement::Wall {
break;
}
}
for y_r in (max(y, 2)..y + 2).rev() {
self.discovered[x][y_r - 2] = true;
if self.structure[x][y_r - 2] == LevelElement::Wall {
break;
}
}
}
}
@ -33,6 +104,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);
}

315
src/level_generator.rs Normal file
View File

@ -0,0 +1,315 @@
use std::cmp::{max, min};
use std::ops::Range;
use petgraph::algo::min_spanning_tree;
use petgraph::data::*;
use petgraph::graph::Graph;
use petgraph::graph::UnGraph;
use rand::prelude::SliceRandom;
use rand::Rng;
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,
}
}
/// 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);
}
room_types.push(RoomType::TreasureRoom);
// 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;
let mut end_x: usize = 0;
let mut end_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::TreasureRoom {
let t_x = left + room.offset_x + rng.gen_range(0..room.width);
let t_y = top + room.offset_y + rng.gen_range(0..room.height);
s[t_x][t_y] = LevelElement::Chest{gold: rng.gen_range(2..100)};
}
if room.kind == RoomType::StairDown {
end_x = left + room.offset_x + rng.gen_range(0..room.width);
end_y = top + room.offset_y + rng.gen_range(0..room.height);
}
if room.kind == RoomType::StairDown {
s[end_x][end_y] = LevelElement::StairDown;
}
if room.kind == RoomType::End {
s[end_x][end_y] = LevelElement::End;
}
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;
}
if room.kind == RoomType::Start {
s[start_x][start_y] = LevelElement::Start;
}
}
}
//
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,
discovered: [[false; 1 + ROOMS_HORIZONTAL * ROOM_HEIGHT]; 1 + ROOMS_VERTICAL * ROOM_WIDTH],
start_x,
start_y,
end_x,
end_y,
}
}
}
#[test]
fn test_level_gen() {
let level = LevelGenerator::generate(0);
println!("{:?}", level);
assert_eq!(1, 2);
}

169
src/level_widget.rs Normal file
View File

@ -0,0 +1,169 @@
use ratatui::prelude::*;
use ratatui::widgets::Widget;
use crate::game::Game;
use crate::level::{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: &Level = &self.game.levels[player_pos.get_level()];
let al: u16 = area.left();
let at: u16 = 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::Black, Color::Gray);
}
LevelElement::StairUp => {
self.set_cell(buf, x, y, "<", Color::Black, Color::Gray);
}
LevelElement::Unknown => {
self.set_cell(buf, x, y, "", Color::DarkGray, Color::Gray);
}
LevelElement::Chest{gold} => {
self.set_cell(buf, x, y, "", Color::Black, Color::Gray);
}
LevelElement::Start => {
self.set_cell(buf, x, y, "α", Color::Black, Color::Gray);
}
LevelElement::End => {
self.set_cell(buf, x, y, "Ω", Color::Black, Color::Gray);
}
}
}
}
}
}
// draw player
let player_x = al + player_pos.get_x() as u16;
let player_y = at + player_pos.get_y() as u16;
self.set_cell(buf, player_x, player_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, "");
}

View File

@ -1,16 +1,115 @@
use std::io::{Result, stdout};
use crossterm::{
event::{self, KeyCode, KeyEventKind},
ExecutableCommand,
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
prelude::{CrosstermBackend, Stylize, Terminal},
widgets::Paragraph,
};
use ratatui::prelude::*;
use ratatui::widgets::Block;
use whoami::realname;
use crate::game::Game;
use crate::level::Level;
use crate::level_generator::LevelGenerator;
use crate::level_widget::LevelWidget;
use crate::player::Player;
mod game;
mod player;
mod level;
mod position;
mod level_widget;
mod level_generator;
fn main() {
let g = Game {
player: Player::new("Teddy Tester", 10),
levels: [Level::new();25]
};
println!("{}",g.player.get_name());
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(realname().as_str(), 10),
levels,
};
g.move_player(levels[0].start_x as i16, levels[0].start_y as i16);
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: {}/{}\nGold: {}\n{}/{}/{}",
g.player.get_name(),
g.player.get_life(),
g.player.get_max_life(),
g.player.get_gold(),
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::Char('d') {
;
}
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(())
}

View File

@ -1,18 +1,21 @@
use std::cmp::{max, min};
use crate::position::Position;
pub struct Player {
name: String,
position: Position,
life: i16,
max_life: i16,
gold: usize,
life: usize,
max_life: usize,
}
impl Player {
pub fn new(name: &str, max_life: i16) -> Player {
pub fn new(name: &str, max_life: usize) -> Player {
Player {
name: name.to_string(),
position: Position::new(0, 1, 1),
position: Position::new(0, 0, 0),
gold: 0,
life: max_life,
max_life,
}
@ -20,8 +23,26 @@ impl Player {
pub fn get_name(&self) -> String {
return self.name.clone();
}
pub fn get_life(&self) -> usize { self.life }
pub fn get_max_life(&self) -> usize { self.max_life }
pub fn get_gold(&self) -> usize { self.gold }
pub fn add_gold(&mut self, amount: usize) { self.gold += amount; }
pub fn change_life(&mut self, by: i16) {
self.life = max(0, min(self.max_life, self.life + by));
self.life = max(0,
min(self.max_life,
(self.life as i16 + by) as usize,
),
);
}
pub fn get_position(&self) -> Position {
self.position
}
pub fn change_position(&mut self, dx: i16, dy: i16) {
self.position.change(dx, dy);
}
pub fn set_position(&mut self, level: usize, x: usize, y: usize) {
self.position.set(level, x, y);
}
}

View File

@ -1,15 +1,37 @@
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Position {
level: u8,
x: u8,
y: u8,
level: usize,
x: usize,
y: usize,
}
impl Position {
pub fn new(level: u8, x: u8, y: u8) -> Self {
pub fn new(level: usize, x: usize, y: usize) -> Self {
Self {
level,
x,
y,
}
}
pub fn get_level(&self) -> usize{
self.level
}
pub fn get_x(&self) -> usize {
self.x
}
pub fn get_y(&self) -> usize {
self.y
}
pub fn change(&mut self, dx: i16, dy: i16) {
self.x = ((self.x as i16) + dx) as usize;
self.y = ((self.y as i16) + dy) as usize;
}
pub fn set(&mut self, level: usize, x: usize, y:usize) {
self.level = level;
self.x = x;
self.y = y;
}
}