Skip to content

Instantly share code, notes, and snippets.

@sgeos
Last active July 27, 2023 03:08
Show Gist options
  • Save sgeos/872c545110bbd8a6b201aa07717fab42 to your computer and use it in GitHub Desktop.
Save sgeos/872c545110bbd8a6b201aa07717fab42 to your computer and use it in GitHub Desktop.
Took no_std Rust generated by ChatGPT 4 and cleaned it up a bit. The original code did not compile, but it was close and the core approach was sound.
#![no_std]
extern crate alloc;
extern crate libc;
use alloc::{ vec, vec::Vec, };
use core::convert::TryInto;
use libc::{ c_int, printf, };
struct Room {
x: usize,
y: usize,
width: usize,
height: usize,
}
impl Room {
pub fn new(x: usize, y: usize, width: usize, height: usize) -> Self {
Room { x, y, width, height }
}
pub fn intersect(&self, other: &Room) -> bool {
self.x <= other.x + other.width &&
self.x + self.width >= other.x &&
self.y <= other.y + other.height &&
self.y + self.height >= other.y
}
}
struct Map {
width: usize,
height: usize,
tiles: Vec<Vec<char>>,
}
impl Map {
pub fn new(width: usize, height: usize) -> Self {
let tiles = vec![vec!['"'; height]; width];
Map { width, height, tiles }
}
pub fn carve_rect(&mut self, room: &Room, material: char, margin: usize) {
for x in (room.x + margin)..(room.x + room.width - margin) {
for y in (room.y + margin)..(room.y + room.height - margin) {
self.tiles[x][y] = material;
}
}
}
pub fn carve_room(&mut self, room: &Room) {
self.carve_rect(room, '#', 0);
self.carve_rect(room, '.', 1);
}
pub fn add_room(&mut self, room: &Room, rooms: &Vec<Room>) -> bool {
for other_room in rooms {
if room.intersect(other_room) {
return false;
}
}
self.carve_room(room);
true
}
pub fn print_map(&self) {
for y in 0..self.height {
for x in 0..self.width {
let c_as_u8 = self.tiles[x as usize][y as usize] as u8;
let c_as_c_char: c_int = c_as_u8.try_into().unwrap_or(0);
unsafe {
printf(b"%c\0".as_ptr() as *const _, c_as_c_char);
}
}
unsafe {
printf(b"\n\0".as_ptr() as *const _);
}
}
}
}
fn generate_dungeon(map_width: usize, map_height: usize, min_room_size: usize, max_room_size: usize) {
let mut map = Map::new(map_width, map_height);
let mut rooms = Vec::new();
let margin = 1;
for _ in 0..(map_width/2 + map_height/2) {
let w = min_room_size + 2*margin + rand::random::<usize>() % (max_room_size + 2*margin);
let h = min_room_size + 2*margin + rand::random::<usize>() % (max_room_size + 2*margin);
let x = rand::random::<usize>() % (map.width - w - 2*margin) + margin;
let y = rand::random::<usize>() % (map.height - h - 2*margin) + margin;
let room = Room::new(x, y, w, h);
if map.add_room(&room, &rooms) {
rooms.push(room);
}
}
map.print_map();
}
fn main() {
generate_dungeon(128, 64, 4, 32);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment