Skip to content

Commit 82ab56b

Browse files
committed
Return
1 parent 7d19c7c commit 82ab56b

33 files changed

+1043
-562
lines changed

.idea/grid-engine.iml

Lines changed: 6 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/misc.xml

Lines changed: 4 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

grid_engine/8d564/grid.png

-94.4 KB
Binary file not shown.

grid_engine/__init__.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
from . import _grid as Grid
2-
from . import _blueprint as Blueprint
3-
from . import _cell as Cell
4-
from . import _grid_object as GridObject
1+
from . import _grid as grid
2+
from . import _blueprint as blueprint
3+
from . import _cell as cell
4+
from . import _grid_object as grid_object
5+
6+
def create_grid(cell_size=None, dimensions=None):
7+
if cell_size is None:
8+
cell_size = 1
9+
if dimensions is None:
10+
dimensions = (1000, 1000)
11+
g = grid.Grid(cell_size=cell_size, dimensions=dimensions)
12+
return g

grid_engine/__log__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import time
12
import logging
23
from functools import wraps
34

5+
date = time.strftime('%Y-%m-%d', time.localtime())
6+
47
logging.addLevelName(44, 'GRIDENGINE')
58
logger = logging.getLogger('GRIDENGINE')
69

@@ -9,7 +12,7 @@ def gridengine(message):
912
logger.log(44, message)
1013

1114

12-
file_handler = logging.FileHandler('gridengine.log', 'w')
15+
file_handler = logging.FileHandler(f'logs/{date}.log', 'a')
1316
file_handler.setLevel(44)
1417
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(module)s - %(message)s'))
1518
logger.addHandler(file_handler)

grid_engine/__main__.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from grid_engine import Blueprint, Grid
1+
from grid_engine import blueprint, grid
22
import argparse
33
import os
44
import sys
@@ -44,33 +44,33 @@ def print(*args):
4444
raise FileNotFoundError(f'File {args.blueprint} does not exist')
4545
print(f'Loading blueprint from {args.blueprint} ...')
4646
try:
47-
blueprint = Blueprint.load_blueprint(f'{blueprints}{args.blueprint}.pkl', Blueprint.TerrainGridBlueprint)
47+
blueprint = blueprint.load_blueprint(f'{blueprints}{args.blueprint}.pkl', blueprint.TerrainGridBlueprint)
4848
except Exception:
49-
blueprint = Blueprint.load_blueprint(f'{blueprints}{args.blueprint}.pkl', Blueprint.BaseGridBlueprint)
49+
blueprint = blueprint.load_blueprint(f'{blueprints}{args.blueprint}.pkl', blueprint.BaseGridBlueprint)
5050
print('Success! Blueprint loaded.')
5151
else:
5252
if args.rows*args.columns > 1000000:
5353
print(f'{colorama.Fore.RED}WARNING{colorama.Fore.RESET}: The provided parameters will generate a grid composed of {colorama.Fore.LIGHTWHITE_EX}{round((args.rows*args.columns)/1000000, 1)} million{colorama.Fore.RESET} cells. \nThis will consume a significant amount of memory/resources/time. \nIf you have limited amount of memory this could cause your system to hang or crash. \nIf you understand the risks, continue by pressing {colorama.Fore.LIGHTGREEN_EX}ENTER{colorama.Fore.RESET}. Otherwise, press {colorama.Fore.LIGHTRED_EX}CTRL+C{colorama.Fore.RESET} to exit.')
5454
input()
5555
print(f'Generating blueprint with cell size {args.size}, {args.rows} rows and {args.columns} columns. Total_cells: {args.rows*args.columns} ...')
56-
blueprint = Blueprint.TerrainGridBlueprint(cell_size=args.size, grid_dimensions=(args.columns*args.size, args.rows*args.size), noise_scale=args.noise_scale, noise_octaves=args.noise_octaves, noise_roughness=args.noise_roughness)
57-
print(f'Success! Blueprint generated. Dimensions: {blueprint.grid_dimensions}')
56+
bp = blueprint.TerrainGridBlueprint(cell_size=args.size, grid_dimensions=(args.columns*args.size, args.rows*args.size), noise_scale=args.noise_scale, noise_octaves=args.noise_octaves, noise_roughness=args.noise_roughness)
57+
print(f'Success! Blueprint generated. Dimensions: {bp.grid_dimensions}')
5858

5959
print('Building grid from blueprint ...')
60-
grid = Grid.Grid(blueprint=blueprint, with_terrain=True)
60+
g = grid.Grid(gblueprint=bp, with_terrain=True)
6161
print('Success! Grid generated.')
6262

6363
if args.save:
6464
print('Pickling grid ...')
65-
Grid.save_grid(grid=grid)
65+
grid.save_grid(grid=g)
6666
print('Success!')
6767
print('Pickling blueprint ...')
68-
Blueprint.save_blueprint(blueprint=blueprint)
68+
blueprint.save_blueprint(blueprint=bp)
6969
print('Success!')
7070

7171
if args.ascii:
7272
print('Writing ascii to file ...')
73-
with open(f'{saves_dir}{grid.grid_id[-5:]}/grid.txt', 'w') as f:
73+
with open(f'{saves_dir}{g.grid_id[-5:]}/grid.txt', 'w') as f:
7474
rows = []
7575
string = ''
7676
for row in grid.rows:
@@ -81,13 +81,13 @@ def print(*args):
8181
f.write('\n'.join(rows))
8282
print('Success!')
8383

84-
cdata = Grid.extract_cell_data(grid)
85-
cell_size = grid.cell_size
86-
grid_id = grid.grid_id[-5:]
87-
height = grid.blueprint.grid_height
88-
width = grid.blueprint.grid_width
84+
cdata = grid.extract_cell_data(g)
85+
cell_size = g.cell_size
86+
grid_id = g.grid_id[-5:]
87+
height = g.blueprint.grid_height
88+
width = g.blueprint.grid_width
8989
del blueprint
90-
del grid
90+
del g
9191

9292
from grid_engine import _utility as utility
9393

grid_engine/_blueprint/__main__.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,12 @@ def print(*args):
3434
if args.output is not None:
3535
if not isinstance(args.output, str) or not args.output.endswith('.json'):
3636
raise ValueError('Output file name must be a string ending with .json')
37-
if not os.listdir(f'{os.getcwd()}{os.sep}blueprint{os.sep}blueprints').count(args.output):
38-
args.output = f'{os.getcwd()}{os.sep}blueprint{os.sep}blueprints{os.sep}{args.output}'
37+
if not os.listdir(f'{os.getcwd()}{os.sep}grid_engine{os.sep}_blueprint{os.sep}blueprints').count(args.output):
38+
args.output = f'{os.getcwd()}{os.sep}grid_engine{os.sep}_blueprint{os.sep}blueprints{os.sep}{args.output}'
3939
else:
4040
raise FileExistsError(f'File {args.output} already exists')
4141
else:
42-
args.output = f'{os.getcwd()}{os.sep}src{os.sep}blueprint{os.sep}blueprints{os.sep}grid.json'
42+
args.output = f'{os.getcwd()}{os.sep}grid_engine{os.sep}blueprint{os.sep}blueprints{os.sep}grid.json'
4343

4444
if not args.size or not args.columns or not args.rows:
4545
raise ValueError('Invalid cell size, row count or column count')
@@ -68,4 +68,3 @@ def print(*args):
6868
json.dump(data, open(args.output, 'w'), indent=4)
6969
print(f'Grid written to {args.output}')
7070
print('Success!')
71-
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
from uuid import uuid4
2+
3+
class _AbstractRoom:
4+
_grid_blueprint = None
5+
_room_id = None
6+
_room_name = None
7+
_room_type = None
8+
_room_dimensions = None
9+
_room_position = None
10+
_room_doors = None
11+
_room_cells = None
12+
_room_cell_data = None
13+
14+
@property
15+
def grid_blueprint(self):
16+
return self._grid_blueprint
17+
18+
@property
19+
def room_id(self):
20+
return self._room_id
21+
22+
@room_id.setter
23+
def room_id(self, value):
24+
self._room_id = value
25+
26+
@property
27+
def room_name(self):
28+
return self._room_name
29+
30+
@room_name.setter
31+
def room_name(self, value):
32+
self._room_name = value
33+
34+
@property
35+
def room_type(self):
36+
return self._room_type
37+
38+
@room_type.setter
39+
def room_type(self, value):
40+
self._room_type = value
41+
42+
@property
43+
def room_dimensions(self):
44+
return self._room_dimensions
45+
46+
@room_dimensions.setter
47+
def room_dimensions(self, value):
48+
self._room_dimensions = value
49+
50+
@property
51+
def room_position(self):
52+
return self._room_position
53+
54+
@room_position.setter
55+
def room_position(self, value):
56+
self._room_position = value
57+
58+
@property
59+
def room_doors(self):
60+
return self._room_doors
61+
62+
@room_doors.setter
63+
def room_doors(self, value):
64+
self._room_doors = value
65+
66+
@property
67+
def room_cells(self):
68+
return self._room_cells
69+
70+
@room_cells.setter
71+
def room_cells(self, value):
72+
self._room_cells = value
73+
74+
@property
75+
def room_cell_data(self):
76+
return self._room_cell_data
77+
78+
@room_cell_data.setter
79+
def room_cell_data(self, value):
80+
self._room_cell_data = value
81+
82+
class BaseRoom(_AbstractRoom):
83+
def __init__(
84+
self,
85+
grid_blueprint,
86+
room_position: tuple[int, int],
87+
room_dimensions: tuple[int, int],
88+
room_id: str = None,
89+
room_name: str = None,
90+
room_type: str = None,
91+
room_doors: list[tuple[int, int]] = None,
92+
room_cells: list[tuple[int, int]] = None,
93+
room_cell_data: list[tuple[int, int]] = None
94+
):
95+
self.grid_blueprint = grid_blueprint
96+
self.room_position = room_position
97+
self.room_dimensions = room_dimensions
98+
self.room_id = room_id if room_id else uuid4().hex
99+
self.room_name = room_name if room_name else f"Room {self.room_id[-4:]}"
100+
self.room_type = room_type if room_type else "Generic"
101+
self.room_doors = room_doors
102+
self.room_cells = room_cells
103+
self.room_cell_data = room_cell_data
104+
105+
class
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import numpy as np
2+
import networkx as nx
3+
4+
MIN_ROOM_WIDTH = 0.1
5+
MIN_ROOM_HEIGHT = 0.1
6+
MAX_ROOM_WIDTH = 0.6
7+
MAX_ROOM_HEIGHT = 0.3
8+
MIN_ROOM_COUNT = 0.5
9+
MAX_ROOM_COUNT = 0.75
10+
MAX_ROOM_AREA = 0.5
11+
MIN_ROOM_HALL_COUNT = 1
12+
MAX_ROOM_HALL_COUNT = 5
13+
14+
def initialize_grid(row_count, col_count):
15+
return np.zeros((row_count, col_count))
16+
17+
def does_intersect(room_a, room_b):
18+
return not (room_a[0] + room_a[2] + 3 < room_b[0] or room_a[0] > room_b[0] + room_b[2] + 3 or room_a[1] + room_a[3] + 3 < room_b[1] or room_a[1] > room_b[1] + room_b[3] + 3)
19+
20+
def gen_count(dimensions, cell_size): # gen_count((100, 100), 1)
21+
x_min = int((dimensions[0] // cell_size) * MIN_ROOM_COUNT) # x_min = 50
22+
y_min = int((dimensions[1] // cell_size) * MIN_ROOM_COUNT) # y_min = 50
23+
size_factor = int((dimensions[0] * MIN_ROOM_WIDTH)) # size_factor = 10
24+
if x_min > y_min: # if 50 > 50:
25+
min_count = (x_min + (x_min - y_min)) # min_count = 50 + (50 - 50) // 10 ~ 5
26+
else: # else:
27+
min_count = (y_min + (y_min - x_min)) # min_count = 50 + (50 - 50) // 10 ~ 5
28+
x_max = int((dimensions[0] // cell_size) * MAX_ROOM_COUNT) # x_max = 70
29+
y_max = int((dimensions[1] // cell_size) * MAX_ROOM_COUNT) # y_max = 70
30+
if x_max > y_max: # if 70 > 70:
31+
max_count = x_max + (x_max - y_max) # max_count = 70 + (70 - 70) // 10 ~ 7
32+
else: # else:
33+
max_count = y_max + (y_max - x_max) # max_count = 70 + (70 - 70) // 10 ~ 7
34+
return np.random.randint(min_count, max_count) // 10 # return random.randint(5, 7)
35+
36+
def gen_room_coords(grid):
37+
min_room_width = int(grid.shape[1] * MIN_ROOM_WIDTH)
38+
min_room_height = int(grid.shape[0] * MIN_ROOM_HEIGHT)
39+
max_room_width = int(grid.shape[1] * MAX_ROOM_WIDTH)
40+
max_room_height = int(grid.shape[0] * MAX_ROOM_HEIGHT)
41+
room_x = np.random.randint(3, grid.shape[1] - max_room_width -3)
42+
room_y = np.random.randint(3, grid.shape[0] - max_room_height - 3)
43+
room_width = np.random.randint(min_room_width, max_room_width)
44+
room_height = np.random.randint(min_room_height, max_room_height)
45+
room_area = room_width * room_height
46+
max_room_area = int(grid.shape[0] * grid.shape[1] * MAX_ROOM_AREA)
47+
if room_area > max_room_area:
48+
excess = room_area - max_room_area
49+
room_width -= excess // room_height
50+
return room_x, room_y, room_width, room_height
51+
52+
def generate_rooms(room_count, grid):
53+
rooms = []
54+
while len(rooms) < room_count:
55+
new_room = gen_room_coords(grid)
56+
if not any(does_intersect(new_room, room) for room in rooms):
57+
rooms.append(new_room)
58+
return rooms
59+
60+
def find_rooms_edges(rooms, grid):
61+
for room in rooms:
62+
grid[room[1]:room[1]+room[3], room[0]:room[0]+room[2]] = 1
63+
grid[room[1]:room[1]+1, room[0]:room[0]+room[2]] = 2 # Top edge
64+
grid[room[1]+room[3]-1:room[1]+room[3], room[0]:room[0]+room[2]] = 2 # Bottom edge
65+
grid[room[1]:room[1]+room[3], room[0]:room[0]+1] = 2 # Left edge
66+
grid[room[1]:room[1]+room[3], room[0]+room[2]-1:room[0]+room[2]] = 2 # Right edge
67+
return grid
68+
69+
def generate_floorplan(cell_size: int = None, dimensions: tuple[int, int] = None):
70+
grid = initialize_grid(dimensions[1] // cell_size, dimensions[0] // cell_size)
71+
room_count = gen_count(dimensions, cell_size)
72+
rooms = generate_rooms(room_count, grid)
73+
grid = find_rooms_edges(rooms, grid)
74+
return grid
75+
76+
def print_floorplan(floorplan):
77+
for row in floorplan:
78+
print(''.join(str(int(cell)) for cell in row))
79+
print()
80+

0 commit comments

Comments
 (0)