tangledmind/utils.py

128 lines
3.5 KiB
Python

# -*- coding: UTF-8 -*-
### Tangled Mind
### Author: Arthur 'Grizzly' Grisel-Davy
from glob import glob
import random
import pygame
def fetch_rooms(path):
"""Fetch all the basic tiles asset from the path.
Return a dictionary
"""
wildcard = '*-*.png'
filenames = glob(path+wildcard)
print(f"Found {len(filenames)} rooms")
assembly = {'T':[],
'R':[],
'D':[],
'L':[],}
for filename in filenames:
label = filename.split("/")[-1].split('-')[0]
if 'T' in label:
assembly['D'].append((label,filename))
if 'R' in label:
assembly['L'].append((label,filename))
if 'D' in label:
assembly['T'].append((label,filename))
if 'L' in label:
assembly['R'].append((label,filename))
background = glob(path+'*back*')[0]
return assembly,background
def check_map(carte):
"""Function to check if a map is valid i.e. if no two rooms are at the same location
"""
positions = []
for room in carte:
if room[2] in positions:
return(False)
else:
positions.append(room[2])
return(True)
def map_generator(n):
"""Map generator generate a map with a main path of n rooms
"""
start_poss = {'T':(500,50),'R':(950,500),'D':(500,950),'L':(50,500)}
room_side = 1000
assembly,back_path = fetch_rooms('./maps/rooms/')
#assembly = {'T/R/D/L':[(label1,path1),(label2,path2),...]}
start_key = random.choice(list(assembly.keys()))
start_label,start_room = random.choice(assembly[start_key])
# Place the first room in the list
positions = []
position = [0,0]
asset = pygame.image.load(start_room).convert_alpha()
mask = pygame.mask.from_surface(asset)
carte = [(asset,mask,position)]
# Select an arbitrary first direction of arrival
dir_from = random.choice(start_label)
start_pos = start_poss[dir_from]
current_label = start_label
counter = 0
while counter < n:
# select the next direction, can't be the direction of arrival
dir_next = random.choice(current_label.replace(dir_from,''))
# Select the next room
next_label,next_room = random.choice(assembly[dir_next])
asset = pygame.image.load(next_room).convert_alpha()
mask = pygame.mask.from_surface(asset)
# Compute the position of the next tile
if dir_next == 'T':
next_position = [position[0],position[1]-room_side]
dir_from = 'D'
if dir_next == 'R':
next_position = [position[0]+room_side,position[1]]
dir_from = 'L'
if dir_next == 'D':
next_position = [position[0],position[1]+room_side]
dir_from = 'T'
if dir_next == 'L':
next_position = [position[0]-room_side,position[1]]
dir_from = 'R'
# Check if we are not overwriting an existing room and store the current one.
if next_position not in positions:
counter += 1
# Build the map
carte.append((asset,mask,next_position))
positions.append(position)
# Update the variables for next turn
current_label = next_label
position = next_position
positions.append(position)
background = pygame.image.load(back_path).convert()
if not check_map(carte):
print("Invalid Map.")
else:
print("Map checked and valid!")
return(carte,start_pos,background)