def make_save_room(room_name, room_desc, x, y, items={}): new_room = Room(name=room_name, description=room_desc, x=x, y=y, items=items) new_room.save()
def generate_rooms(): num_rooms = 115 room_count = 0 previous_room = None while room_count < num_rooms: if 0 <= room_count <= 9: room_direction = "n" elif 10 <= room_count <= 25: if room_count % 2 != 0: room_direction = "n" else: room_direction = "e" elif 26 <= room_count <= 40: if room_count % 2 != 0: room_direction = "s" else: room_direction = "e" elif 40 <= room_count <= 42: if room_count % 2 != 0: room_direction = "s" else: room_direction = "e" elif 42 <= room_count <= 57: if room_count % 2 != 0: room_direction = "n" else: room_direction = "e" elif 58 <= room_count <= 75: if room_count % 2 != 0: room_direction = "s" else: room_direction = "e" elif 76 <= room_count <= 83: room_direction = "s" elif 83 <= room_count <= 116: room_direction = "w" # Create a room in the given direction # room = Room(room_count, "A Generic Room", "This is a generic room.", x, y) #maybe add room_count as the first field to determine id????? room = Room(title=f'Room {room_count}', description=f'This is room # {room_count}') # Note that in Django, you'll need to save the room after you create it # Saving the room room.save() # Connect the new room to the previous room if previous_room is not None: previous_room.connectRooms(room, room_direction) prev_dir = room_direction reverse_dirs = {"n": "s", "s": "n", "e": "w", "w": "e"} reverse_dir = reverse_dirs[prev_dir] room.connectRooms(previous_room,reverse_dir) # Updating iteration variables and prev direction previous_room = room room_count += 1
def prob_add_room(self, x, y, room_count): if random.random() < self.room_prob: new_room = Room(id=room_count, title="Room", description="room desc.") new_room.save() self.grid[y][x] = new_room return True return False
def create_django_rooms(self): # get each room # turn into a django room # save to DB for row in self.grid: for room in row: if room: django_room = DjangoRoom() django_room.title = room.name django_room.description = room.description if room.n_to: django_room.n_to = room.n_to.id if room.s_to: django_room.s_to = room.s_to.id if room.e_to: django_room.e_to = room.e_to.id if room.w_to: django_room.w_to = room.w_to.id django_room.save() # This is what to run in the manage.py python shell: # # from room_gen import RoomGenerator # rg = RoomGenerator() # rg.generate_rooms() # rg.create_django_rooms()
def generate_rooms(self, size_x, size_y, num_rooms): self.grid = [None] * size_y self.width = size_x self.height = size_y for i in range(len(self.grid)): self.grid[i] = [None] * size_x x = -1 y = 0 room_count = 0 direction = 1 previous_room = None while room_count < num_rooms: if direction > 0 and x < size_x - 1: room_direction = "e" x += 1 elif direction < 0 and x > 0: room_direction = "w" x -= 1 else: room_direction = "n" y += 1 direction *= -1 room = Room(title=room_title[room_count], description=room_descriptions[room_count], x=x, y=y) room.save() self.grid[y][x] = room if previous_room is not None: previous_room.connectRooms(room, room_direction) previous_room = room room_count += 1
def generate_rooms(self, size_x, size_y, num_rooms): ''' Fill up the grid, bottom to top, in a zig-zag pattern ''' # Initialize the grid self.grid = [None] * size_y self.width = size_x self.height = size_y for i in range(len(self.grid)): self.grid[i] = [None] * size_x # Start from lower-left corner (0,0) x = -1 # (this will become 0 on the first step) y = 0 room_count = 0 # Start generating rooms to the east direction = 1 # 1: east, -1: west # While there are rooms to be created... previous_room = None while room_count < num_rooms: # Calculate the direction of the room to be created if direction > 0 and x < size_x - 1: room_direction = "e" x += 1 elif direction < 0 and x > 0: room_direction = "w" x -= 1 else: # If we hit a wall, turn north and reverse direction room_direction = "n" y += 1 direction *= -1 # Create a room in the given direction #room = Room(room_count, title="A Generic Room", description="This is a generic room.") # Note that in Django, you'll need to save the room after you create it pepper = random.choice(spicy_choices) pepper_description = "This room is listed at {} on the scoville scale, your discretion is advised".format( spicy_dict[pepper]) room = Room(room_count, title="{} Room".format(pepper), description=pepper_description) # SAVE ROOMS room.save() # Save the room in the World grid self.grid[y][x] = room # Connect the new room to the previous room if previous_room is not None: previous_room.connectRooms(room, room_direction) # Update iteration variables previous_room = room room_count += 1
def get_neighbors( current, visited, count, num_rooms, keys_list, vals_list, random_grid_size, ): holder = [None] * 4 i = 0 directions = ["n_to", "s_to", "e_to", "w_to"] opposites = {"n_to": "s_to", "s_to": "n_to", "e_to": "w_to", "w_to": "e_to"} for direction in directions: # look through our available directions, if this room has that direction available, look to see if there is a room already in that position. If so link these two up, if not create a new room. if getattr(current, direction) is 0: look_y = None look_x = None # For each check we have to see if we stil even have anymore rooms to create, and we have to check the bounds. For example, if the current y is already 0, we cannot place a room north of that! if direction == "n_to" and count < num_rooms and current.y > 0: look_x = current.x look_y = current.y - 1 if ( direction == "e_to" and count < num_rooms and current.x < random_grid_size ): look_x = current.x + 1 look_y = current.y if ( direction == "s_to" and count < num_rooms and current.y < random_grid_size ): look_x = current.x look_y = current.y + 1 if direction == "w_to" and count < num_rooms and current.x > 0: look_x = current.x - 1 look_y = current.y # If look_y or look_x is still None, we don't want to put at room in this direction, continue the loop and start at the next direction if not look_y or not look_x: continue # If there is a room in that direction link these two if visited[look_y][look_x] is not None: another_room = visited[look_y][look_x] current.connectRooms(another_room, direction) another_room.connectRooms(current, opposites[direction]) # otherwise create a new room, increment count, link the two rooms else: another_room = Room( title=keys_list[count], description=vals_list[count]["description"], x=look_x, y=look_y, items=vals_list[count]["items"], ) another_room.save() count += 1 current.connectRooms(another_room, direction) another_room.connectRooms(current, opposites[direction]) visited[look_y][look_x] = another_room # add the linked room to the holder, holder holds all our neighbors, and will be added to the queue holder[i] = another_room i += 1 return [holder, count]
def create_world(w, room_amount): full_map = [] map_row = [] ra = room_amount map_row_size = 0 full_map_height = 0 while ra > 0: title = 'adv' description = 'des' r = Room(title=fun_room_titles(), description=fun_room_descriptions()) r.save() if map_row_size == w: full_map.append(map_row) map_row_size = 0 full_map_height += 1 map_row = [] map_row.append(r) r.x = map_row_size r.y = full_map_height map_row_size += 1 ra -= 1 print(f'{r.title} + {r.description} + x = {r.x} + y = {r.y}') elif map_row_size < w: map_row.append(r) r.x = map_row_size r.y = full_map_height map_row_size += 1 ra -= 1 print(f'{r.title} + {r.description} + x = {r.x} + y = {r.y}') print(full_map) for row in full_map: for node in row: y = node.y x = node.x # North if y > 0: if full_map[y - 1][x]: node.connectRooms(full_map[y - 1][x], "n") y = node.y # East if x < len(row) - 1: if full_map[y][x + 1]: print(full_map[y][x + 1].id) node.connectRooms(full_map[y][x + 1], "e") x = node.x #South if y < len(full_map) - 1: if full_map[y + 1][x]: node.connectRooms(full_map[y + 1][x], "s") y = node.y #West if x > 0: if full_map[y][x - 1]: node.connectRooms(full_map[y][x - 1], "w") x = node.x node.save() return full_map
def addRoom(x, y): # generate random title and description (title, description) = generateRoomDescription() # create room in database newRoom = Room(title=title, description=description, x=x, y=y) # store it newRoom.save() # return it return newRoom
def generate_rooms(self, size_x, size_y, num_rooms): ''' Fill up the grid, bottom to top, in a zig-zag pattern ''' # Initialize the grid self.grid = [None] * size_y self.width = size_x self.height = size_y rooms = generateRooms() for i in range(len(self.grid)): self.grid[i] = [None] * size_x # Start from lower-left corner (0,0) x = -1 # (this will become 0 on the first step) y = 0 room_count = 0 # Start generating rooms to the east direction = 1 # 1: east, -1: west # While there are rooms to be created... previous_room = None while room_count < num_rooms: # Calculate the direction of the room to be created if direction > 0 and x < size_x - 1: room_direction = "e" x += 1 elif direction < 0 and x > 0: room_direction = "w" x -= 1 else: # If we hit a wall, turn north and reverse direction room_direction = "n" y += 1 direction *= -1 # Create a room in the given direction room = Room(room_count, rooms[room_count]["name"], rooms[room_count]["description"], x, y) room.save() # Note that in Django, you'll need to save the room after you create it # Save the room in the World grid self.grid[y][x] = room # Connect the new room to the previous room if previous_room is not None: # print(previous_room) previous_room.connect_rooms(room, room_direction) # Update iteration variables previous_room = room room_count += 1
def generate_rooms(self, titles, descriptions): rooms_list = [] for x in range(0, self.maze_width): for y in range(0, self.maze_height): if self.maze[x][y] == 'X': self.num_rooms += 1 rooms_list.append([x, y]) """ Make a list of all the room Objects with titles and descriptions """ room_objects = [] for room in enumerate(rooms_list): r = Room(title=titles[room[0]], description=descriptions[room[0]], x=room[1][0], y=room[1][1]) r.save() room_objects.append(r) """ Cycle through the room objects and connect them """ for a_room in room_objects: starting_room = a_room starting_point = starting_room.x, starting_room.y surroundings = [] """ get the points around the coordinates """ surroundings = around_list(starting_point) connections = [] """ check if the point around it is a room """ for value in rooms_list: if value in surroundings: connections.append(value) """ add the direction to the connections """ connections_and_direction = [] for items in enumerate(surroundings): if items[1] in connections: if items[0] == 0: connections_and_direction.append([items[1], 'n']) if items[0] == 1: connections_and_direction.append([items[1], 's']) if items[0] == 2: connections_and_direction.append([items[1], 'w']) if items[0] == 3: connections_and_direction.append([items[1], 'e']) """ loop through the connection-direction pairs and connect the objects """ for pointz in connections_and_direction: for outer_room in room_objects: outer_point = [outer_room.x, outer_room.y] if outer_point == pointz[0]: if pointz[1] == 'n': starting_room.connectRooms(outer_room, 'n') if pointz[1] == 's': starting_room.connectRooms(outer_room, 's') if pointz[1] == 's': starting_room.connectRooms(outer_room, 'e') if pointz[1] == 'e': starting_room.connectRooms(outer_room, 'w') """ add the room ID to the maze """ self.maze[starting_room.x][starting_room.y] = starting_room.id return room_objects
def generate_rooms(num_rooms=100): # delete existing rooms and start fresh Room.objects.all().delete() # get data from json file with open("./util/shuffled.json", "r") as json_file: data = json.load(json_file) keys_list = list(data.keys()) vals_list = list(data.values()) # rooms array holds the rooms that will be output to the json file and count keeps track of created rooms. We'll use the queue to keep track of rooms that might still need neighbors # rooms = [] count = 0 q = Queue() # I wanted a square area to start with, but if it one side is the square of the number of the rooms, we'll end up with a boring square grid. random_grid_size = math.floor(math.sqrt(num_rooms) * 1.5) # Get our visited array ready. The visited array exists to help with room collisions. If I want to put a room north of the room I am looking at, how can I tell if there is already a room there? Visited keeps track of that. visited = [[None for i in range(random_grid_size + 1)] for j in range(random_grid_size + 1)] # random start position of first room random_start_x = random.randint(0, random_grid_size) random_start_y = random.randint(0, random_grid_size) # create first room, increment count new_room = Room( title=keys_list[count], description=vals_list[count]["description"], items=vals_list[count]["items"], x=random_start_x, y=random_start_y, ) new_room.save() count += 1 # add the new room to the queue to be evaluated q.enqueue(new_room) visited[random_start_y][random_start_x] = new_room while count < num_rooms: current = q.dequeue() holder, count = get_neighbors( current, visited, count, num_rooms, keys_list, vals_list, random_grid_size, ) # shuffle our neighbors for more variance random.shuffle(holder) for item in holder: if item is not None: q.enqueue(item)
def create_rooms(): Room.objects.all().delete() r_outside = Room(title="Outside Cave Entrance", description="North of you, the cave mount beckons") r_foyer = Room( title="Foyer", description="""Dim light filters in from the south. Dusty passages run north and east.""") r_overlook = Room( title="Grand Overlook", description="""A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm.""") r_narrow = Room(title="Narrow Passage", description="""The narrow passage bends here from west to north. The smell of gold permeates the air.""") r_treasure = Room(title="Treasure Chamber", description="""You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south.""") r_outside.save() r_foyer.save() r_overlook.save() r_narrow.save() r_treasure.save() # Link rooms together r_outside.connectRooms(r_foyer, "n") r_foyer.connectRooms(r_outside, "s") r_foyer.connectRooms(r_overlook, "n") r_overlook.connectRooms(r_foyer, "s") r_foyer.connectRooms(r_narrow, "e") r_narrow.connectRooms(r_foyer, "w") r_narrow.connectRooms(r_treasure, "n") r_treasure.connectRooms(r_narrow, "s") players = Player.objects.all() for p in players: p.currentRoom = r_outside.id p.save()
def generate_rooms(self, size_x, size_y, num_rooms): ''' Fill up the grid, bottom to top, in a zig-zag pattern ''' # Initialize the grid self.grid = [None] * size_y self.width = size_x self.height = size_y for i in range(len(self.grid)): self.grid[i] = [None] * size_x # Start from lower-left corner (0,0) x = -1 # (this will become 0 on the first step) y = 0 room_count = 0 # Start generating rooms to the east direction = 1 # 1: east, -1: west # While there are rooms to be created... previous_room = None while room_count < num_rooms: # Calculate the direction of the room to be created if direction > 0 and x < size_x - 1: room_direction = "e" x += 1 elif direction < 0 and x > 0: room_direction = "w" x -= 1 else: # If we hit a wall, turn north and reverse direction room_direction = "n" y += 1 direction *= -1 # Create a room in the given direction room = Room(room_count, countryList[room_count], f"This is a {random.choice(adjectives)} country", x, y) # Note that in Django, you'll need to save the room after you # create it room.save() # Save the room in the World grid self.grid[y][x] = room # Connect the new room to the previous room opposite = {"w": "e", "e": "w", "s": "n", "n": "s"} if previous_room is not None: previous_room.connectRooms(room, room_direction) room.connectRooms(previous_room, opposite[room_direction]) # Update iteration variables previous_room = room room_count += 1
def generate_rooms(size_x, size_y, num_rooms): grid = [None] * size_y width = size_x height = size_y for i in range(len(grid)): grid[i] = [None] * size_x x = -1 y = 0 room_count = 0 direction = 1 while room_count < num_rooms: if direction > 0 and x < size_x - 1: x += 1 else: y += 1 x = 0 room = Room(room_id=room_count, title="A Generic Room", description="This is a generic room.", x=x, y=y) # Save the room in the World grid grid[y][x] = room room.save() room_count += 1 for row in grid: for room in row: direction_list = ['n', 's', 'e', 'w'] new_y = room.y new_x = room.x num_loops = 0 while num_loops <= 1: direction = random.choice(direction_list) if direction == 'n' and room.x <= 9 and room.y < 9: new_y = room.y + 1 room.connect_rooms(grid[new_y][new_x], direction) elif direction == 's' and room.x <= 9 and room.y > 0: new_y = room.y - 1 room.connect_rooms(grid[new_y][new_x], direction) elif direction == 'e' and room.x >= 0 and room.x < 9 and room.y >= 0 and room.y < 10: new_x = room.x + 1 room.connect_rooms(grid[new_y][new_x], direction) elif direction == 'w' and room.x >= 1 and room.x < 10 and room.y >= 0 and room.y < 10: new_x = room.x - 1 room.connect_rooms(grid[new_y][new_x], direction) num_loops += 1 return grid
def make_rooms(new_map, genre): # make first room (0,0) entrance = Room( map_id=new_map, name='Entrance' ) ###TODO: change Room to have coordinates (maybe, also sorta done?) entrance.save() rooms = {(0, 0): entrance} new_map.save() # create branches (recursion) entrance.north = make_room('south', new_map, coords=(0, 1), rooms=rooms, recursion=1, prev_room=entrance, genre=genre) entrance.save() return rooms
def place_maze_with_validation(self, rooms_created): x = 0 y = 0 if rooms_created == 1: room = Room(rooms_created, f"This is room {rooms_created}", f"This is a generic room called {rooms_created}.", x, y) room.save() self.get_edges(room) self.grid_view[(x, y)] = True return max = len(self.open_spaces) rand = secrets.randbelow(max) rev_dir = {"n": "s", "e": "w", "s": "n", "w": "e"} dir_val = {"n": 1, "e": 1, "s": -1, "w": -1} if self.open_spaces[rand] is not None: rm_id = self.open_spaces[rand][0] curr_rm = Room.objects.filter(id=rm_id)[0] rm_dir = self.open_spaces[rand][1] x = getattr(curr_rm, "x", 0) y = getattr(curr_rm, "y", 0) if rm_dir == "n" or rm_dir == "s": y += dir_val[rm_dir] if rm_dir == "w" or rm_dir == "e": x += dir_val[rm_dir] if (x, y) in self.grid_view: # print("can't place recurse") del self.open_spaces[rand] self.place_maze_with_validation(rooms_created) else: # print("place in space") room = Room(rooms_created, f"This is room {rooms_created}", f"This is a generic room called {rooms_created}.", x, y) room.save() rev_rm_dir = rev_dir[self.open_spaces[rand][1]] curr_rm.connectRooms(room, rm_dir) room.connectRooms(curr_rm, rev_rm_dir) del self.open_spaces[rand] self.grid_view[(x, y)] = True self.get_edges(room) else: self.place_maze_with_validation(rooms_created)
def create_django_rooms(self): # get each room # turn into a django room # save to DB for row in self.rooms: for room in row: if room: django_room = DjangoRoom() django_room.room_id = room.id django_room.title = room.title django_room.description = room.description if room.n_to: django_room.n_to = room.n_to if room.s_to: django_room.s_to = room.s_to if room.e_to: django_room.e_to = room.e_to if room.w_to: django_room.w_to = room.w_to django_room.save()
def place_maze_with_validation(self, rooms_created, prev_room, home, home_start, x, y): # print(f"\nSTART ROOM CREATION") if home == None: # print(f"\nSET HOME") room = Room(rooms_created, f"This is room {rooms_created}", f"This is a generic room called {rooms_created}.", x, y) room.save() self.grid_view[(x, y)] = room.id return {"prev_room": room} rm_dir = ["n", "e", "w", "s"] rvrm_dir = ["s", "w", "e", "n"] ran = secrets.randbelow(4) check_dir = rm_dir[ran] rvcheck_dir = rvrm_dir[ran] dir_values = {"n": 1, "e": 1, "w": -1, "s": -1} if check_dir == "n" or check_dir == "s": y += dir_values[check_dir] elif check_dir == "e" or check_dir == "w": x += dir_values[check_dir] if home_start and getattr(home, f"{check_dir}_to", 0) == 0: # print(f"\nSTART FROM HOME") room = Room(rooms_created, f"This is room {rooms_created}", f"This is a generic room called {rooms_created}.", x, y) room.save() home.connectRooms(room, check_dir) room.connectRooms(home, rvcheck_dir) self.grid_view[(x, y)] = room.id elif getattr(prev_room, f"{check_dir}_to", 0) == 0: # print(f"\nROOM DIRECTION EMPTY") if (x, y) in self.grid_view: # print(f"\nROOM EXISTS SO CANNOT PLACE") rm_id = self.grid_view[(x, y)] nxt_rm = Room.objects.filter(id=rm_id)[0] return self.place_maze_with_validation(rooms_created, nxt_rm, home, False, x, y) else: # print(f"\nPLACE ROOM AT DIRECTION") room = Room(rooms_created, f"This is room {rooms_created}", f"This is a generic room called {rooms_created}.", x, y) room.save() prev_room.connectRooms(room, check_dir) room.connectRooms(prev_room, rvcheck_dir) self.grid_view[(x, y)] = room.id else: # print(f"\nROOM EXISTS") rm_id = getattr(prev_room, f"{check_dir}_to", 0) # print(f"\nROOM: {prev_room.id} | DIRECTIONAL ROOM ID: {rm_id}") # pdb.set_trace() nxt_rm = Room.objects.filter(id=rm_id)[0] # pdb.set_trace() return self.place_maze_with_validation(rooms_created, nxt_rm, home, False, x, y) return {"prev_room": room}
def place_maze_with_validation(self, rooms_created): if rooms_created == 1: room = Room(rooms_created, f"This is room {rooms_created}", f"This is a generic room called {rooms_created}.", 0, 0) room.save() self.get_edges(room) return max = len(self.grid_view) rand = secrets.randbelow(max) rev_dir = {"n":"s", "e":"w", "s":"n", "w":"e"} dir_val = {"n":1, "e":1, "s":-1, "w":-1} if self.grid_view[rand] is not None: x=0; y=0 rm_id = self.grid_view[rand][0] curr_rm = Room.objects.filter(id=rm_id)[0] rm_dir = self.grid_view[rand][1] x = curr_rm["x"] y = curr_rm["y"] if rm_dir = "n" or rm_dir = "s": y += dir_val[rm_dir] if rm_dir = "w" or rm_dir = "e": x += dir_val[rm_dir]
def generate_rooms(self, count): start_room = Room( title='Foyer', description= 'A dingy foyer where the floor is filled with torn papers of an unknown book. What happened here?' ) start_room.save() current_room = start_room # create rooms by looping up to count number for i in range(1, count): random_room = names[math.floor(len(names) * random())] # Create room new_room = Room(title=random_room[0], description=random_room[1], w_to=current_room.id) new_room.save() # mark new_to as next room current_room.connectRooms(new_room, 'e') # change current_room current_room = new_room print(f"{count} rooms created. Enjoy!")
def make_world(self): """ Creates a world based on initial parameters using dfs algorithm """ # Total num of rooms for xi in range(self.width): for yj in range(self.height): newRoom = Room(x=xi, y=yj) newRoom.save() self.grid[xi][yj] = newRoom # Stack for depth first search current_room = self.room_at(self.width // 2, self.height // 2) room_stack = deque([current_room]) while len(room_stack): print(len(room_stack)) neighbours = self.find_valid_neighbours(current_room) if len(neighbours): print(neighbours) # if there are valid neighbours, choose a random one, connect them, direction, next_room = choice(neighbours) current_room.connectRooms(next_room, direction) room_stack.append(current_room) current_room = next_room else: # Reached a dead end, go back current_room = room_stack.pop()
def generate_rooms(self, size_x, size_y, num_rooms): ''' Fill up the grid, bottom to top, in a zig-zag pattern ''' # Initialize the grid self.grid = [None] * size_y self.width = size_x self.height = size_y for i in range( len(self.grid) ): self.grid[i] = [None] * size_x x = (size_x//2) y = (size_y//2) room_count = 0 # Start generating rooms to the east direction = [-1, 1] # -1 = south or west, 1 = north or east vertical_or_horizontal = ['x', 'y'] firstroom = Room(room_count, "Dark Atrium", "You begin your journey in a wide open atrium, covered in the shadow of night. Choose your path carefully going forward.", x, y) self.grid[y][x] = firstroom room_count += 1 firstroom.save() # While the room count is less than the current number of rooms # Navigate randomly (within the set grid boundary) and create rooms/connections accordingly previous_room = firstroom while room_count < num_rooms: ## Pick a direction (x or y) for movement ## Generate -1 or 1 randomly hit_a_wall = False one_or_negative_one = random.choice(direction) x_or_y = random.choice(vertical_or_horizontal) current_title = f"{random.choice(title_adj)} {random.choice(title_noun)}" current_description = f"{random.choice(description_start)} {random.choice(description_end)}" if x_or_y == 'x': #we are moving east or west if one_or_negative_one == 1: #moving east if x < (size_x - 1): room_direction = "e" x += 1 else: hit_a_wall = True else: #moving west if x > 0: room_direction = "w" x -= 1 else: hit_a_wall = True elif x_or_y == 'y': #we are moving north or south if one_or_negative_one == 1: #moving north if y < (size_y - 1): room_direction = "n" y += 1 else: hit_a_wall = True else: #moving south if y > 0: room_direction = "s" y -= 1 else: hit_a_wall = True #check to see if there is a room after moving if hit_a_wall == False and self.grid[y][x] is not None: #connect the room to the previous one if previous_room is not None: previous_room.connect_rooms(self.grid[y][x], room_direction) previous_room = self.grid[y][x] #if there is no room after moving elif hit_a_wall == False and self.grid[y][x] is None: #create a room room = Room(title=current_title, description=current_description, x=x, y=y) room.save() #save the room in the grid self.grid[y][x] = room #connect the room to the previous one if previous_room is not None: previous_room.connect_rooms(room, room_direction) #because we created a room, increment room_count and update previous_room previous_room = room room_count += 1 else: #if we hit this, we hit a wall. So try choosing another direction pass if self.grid[start_y + 1][start_x] is not None: firstroom.connect_rooms(self.grid[start_y + 1][start_x], 'n') if self.grid[start_y - 1][start_x] is not None: firstroom.connect_rooms(self.grid[start_y - 1][start_x], 's') if self.grid[start_y][start_x + 1] is not None: firstroom.connect_rooms(self.grid[start_y][start_x + 1], 'e') if self.grid[start_y][start_x - 1] is not None: firstroom.connect_rooms(self.grid[start_y][start_x - 1], 'w') players = Player.objects.all() for p in players: p.currentRoom=firstroom.id p.save()
items='dagger key') r_waterfall = Room( title="Water Fall", description= """You gaze upon a massive underground waterfall. A large stone apears in front of you. the words "If you drop a yellow hat in the Red Sea, what does it become?" are carved onto its side.""" ) r_library = Room(title="library", description="""You find yourself in a dimly lit room with many high shelves filled with dusty books. The shelves are made of wood and look aged and worn.""", items='magical-book') r_outside.save() r_foyer.save() r_overlook.save() r_narrow.save() r_treasure.save() r_cave.save() r_crossroads.save() r_waterfall.save() r_library.save() # Link rooms together r_outside.connectRooms(r_foyer, "n") r_foyer.connectRooms(r_outside, "s") r_foyer.connectRooms(r_overlook, "n") r_overlook.connectRooms(r_foyer, "s")
"Lots of Zigging and Zagging is happening all around you." }, # Secret Rooms ] for r in rooms: n_to = r['n'] if 'n' in r else -1 s_to = r['s'] if 's' in r else -1 e_to = r['e'] if 'e' in r else -1 w_to = r['w'] if 'w' in r else -1 if 'x' in r: x = r['x'] if 'y' in r: y = r['y'] make_room = Room(id=r["id"], title=r["Title"], description=r["description"], x=x, y=y, n_to=n_to, s_to=s_to, e_to=e_to, w_to=w_to) make_room.save() players = Player.objects.all() for p in players: p.currentRoom = rooms[0]["id"] p.save()
"y": 3, "title": "Room 20", "n": -1, "s": -1, "e": 1, "w": -1, "description": "There is exit to the east", "items": [""] } ] for r in room_list: n = r["n"] if "n" in r else -1 s = r["s"] if "s" in r else -1 e = r["e"] if "e" in r else -1 w = r["w"] if "w" in r else -1 if "x" in r: x = r["x"] if "y" in r: y = r["y"] # make_r = Room(id=r["id"], title=r["title"], # description=r["description"], x=x, y=y, n=n, s=s, e=e, w=w) make_r = Room(id=r["id"], title=r["title"], description=r["description"], x=x, y=y, n=n, s=s, e=e, w=w, items="".join(r["items"])) make_r.save() players = Player.objects.all() for p in players: p.currentRoom = r_outside.id p.save()
def generate_rooms(self, size_x, size_y, num_rooms): # Initialize the grid's height self.grid = [None] * size_y self.width = size_x self.height = size_y # fill the row up with an array of None for i in range(len(self.grid)): self.grid[i] = [None] * size_x # Start from lower-left corner (0,0) x = -1 # (this will become 0 on the first step) y = 0 # set to 1 so id can begin at 1 room_count = 1 # Start generating rooms to the east direction = 1 # 1: east, -1: west # While there are rooms to be created... previous_room = None # use to reverse the direction of the room reverse_dirs = {"n": "s", "s": "n", "e": "w", "w": "e", "err": "err"} # will be used to create chasm break_choices = [False, True, False, False, False] while room_count <= num_rooms: # Calculate the direction of the room to be created if direction > 0 and x < size_x - 1: room_direction = "e" x += 1 elif direction < 0 and x > 0: room_direction = "w" x -= 1 else: # REMOVED THE NORTH SOUTH MAPPING AT THE ENDS OF THE MAP # # If we hit a wall, turn north and reverse direction # set the direction to something useless room_direction = "err" y += 1 direction *= -1 # THIS CREATES A CHASM IN THE EAST-WEST CONNECTION AT RANDOM POINTS # if 1 < y < (size_y - 3) if 1 < y < (size_y - 3): # randomize break_choices choice = random.choice(break_choices) # if true break the connection by setting the room direction to err if choice: room_direction = "err" # Create a room in the given direction room = Room( id=room_count, title=room_titles[room_count - 1], description= "The quest for thy nobly ring burns true and bright. Search on thou famed voyager!", x=x, y=y) # Note that in Django, you'll need to save the room after you create it room.save() # Save the room in the World grid self.grid[y][x] = room # Connect the new room to the previous room if previous_room is not None: previous_room.connectRooms(room, room_direction) room.connectRooms(previous_room, reverse_dirs[room_direction]) # Update iteration variables previous_room = room room_count += 1 # THIS STEP DOWNWARD WILL CREATE NORTH-SOUTH CONNECTIONS AT RANDOM POINTS IN THE MAP # set room_count to zero again room_count = 0 # set x and y to zero x = 0 y = 0 # set another variable index to zero # create an array range to hold choices choices = [False, True, False, False, True] # loop while room_count is less than num_rooms while room_count < num_rooms: # if y is less than size_y if y < size_y - 1: # randomize choices # if true set a northward position if random.choice(choices): # connect with the room to the north self.grid[y][x].connectRooms(self.grid[y + 1][x], "n") self.grid[y + 1][x].connectRooms(self.grid[y][x], "s") # increment x x += 1 # increment room_count room_count += 1 # if x is at the last position increment y and reset x if x == size_x: x = 0 y += 1
def generate_rooms(self, size_x, size_y, num_rooms, Room): ''' Fill up the grid, bottom to top, in a zig-zag pattern ''' import random # Initialize the grid self.grid = [None] * size_x self.width = size_x self.height = size_y for i in range(size_x): self.grid[i] = [None] * size_x list_of_rooms = [] # create a starting room at origin room = Room() room.save() room.x = size_x // 2 room.y = size_y // 2 number_rooms_created = 1 self.grid[room.x][room.y] = room list_of_rooms.append(room) # until we have enough rooms while number_rooms_created < num_rooms: # pick an existing room current_room = random.choice(list_of_rooms) x = current_room.x y = current_room.y # find the viable paths # start with all four directions as options options = ['n', 's', 'e', 'w'] # for room.x: if x == 0, no west; if x == size_x - 1, no east if current_room.x == 0: options.remove('w') if current_room.x == size_x - 1: options.remove('e') # for room.y: if y == 0, no north; if y == size_y - 1, no south if current_room.y == 0: options.remove('n') if current_room.y == size_y - 1: options.remove('s') # for the directions remaining check if space is open - remove from list if not open # if west: check self.grid[x-1][y] -> if not None, remove west if 'w' in options and self.grid[x - 1][y] is not None: options.remove('w') # if east: check self.grid[x+1][y] -> if not None, remove east if 'e' in options and self.grid[x + 1][y] is not None: options.remove('e') # if south: check self.grid[x][y+1] -> if not None, remove south if 's' in options and self.grid[x][y + 1] is not None: options.remove('s') # if north: check self.grid[x][y+1] -> if not None, remove north if 'n' in options and self.grid[x][y - 1] is not None: options.remove('n') # if zero paths, continue if len(options) == 0: continue # choose one or more paths num_options = random.randint(1, len(options)) # create a new room for each path, including x and y positions for _ in range(num_options): direction = random.choice(options) options.remove(direction) new_room = Room() new_room.save() number_rooms_created += 1 if direction == 'w': new_room.x = x - 1 new_room.y = y if direction == 'e': new_room.x = x + 1 new_room.y = y if direction == 's': new_room.x = x new_room.y = y + 1 if direction == 'n': new_room.x = x new_room.y = y - 1 # update grid and list of rooms self.grid[new_room.x][new_room.y] = new_room list_of_rooms.append(new_room) # create connections for each pair of rooms # get connecting room reverse_dirs = {"n": "s", "s": "n", "e": "w", "w": "e"} reverse_dir = reverse_dirs[direction] current_room.connectRooms(new_room, direction) new_room.connectRooms(current_room, reverse_dir) # remove current room to get better pathing list_of_rooms.remove(current_room)
r_foyer = Room(title="Foyer", description="""Dim light filters in from the south. Dusty passages run north and east.""") r_overlook = Room(title="Grand Overlook", description="""A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm.""", room_array=json.dumps(room_arrays_dict['x_axis_void'])) r_narrow = Room(title="Narrow Passage", description="""The narrow passage bends here from west to north. The smell of gold permeates the air.""") r_treasure = Room(title="Treasure Chamber", description="""You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south.""", room_array=json.dumps(room_arrays_dict['y_axis_void'])) r_outside.save() r_foyer.save() r_overlook.save() r_narrow.save() r_treasure.save() # Link rooms together r_outside.connectRooms(r_foyer, "n") r_foyer.connectRooms(r_outside, "s") r_foyer.connectRooms(r_overlook, "n") r_overlook.connectRooms(r_foyer, "s") r_foyer.connectRooms(r_narrow, "e") r_narrow.connectRooms(r_foyer, "w")
r_housing_admin_beta = Room( title="Administration Housing Beta Wing", description= """How those living in the Beta Wing of the Administration Building access their Quarters. You must be living here to go further.""") r_housing_admin_charlie = Room( title="Administration Housing Charlie Wing", description= """How those living in the Charlie Wing of the Administration Building access their Quarters. You must be living here to go further.""") #all saves below r_campus_welcome_center.save() r_campus_courtyard_south.save() r_campus_courtyard_north.save() r_campus_courtyard_mid.save() r_campus_courtyard_east.save() r_campus_courtyard_west.save() r_ds_building.save() r_ds_help.save() r_ds_u1.save() r_ds_u2.save() r_ds_u3.save() r_ds_u4.save() r_ds_hall.save() r_web_building.save()