Skip to content

Instantly share code, notes, and snippets.

@Pinacolada64
Created October 27, 2021 21:19
Show Gist options
  • Save Pinacolada64/8b08ef0813932e3f378f8eea5b2f8033 to your computer and use it in GitHub Desktop.
Save Pinacolada64/8b08ef0813932e3f378f8eea5b2f8033 to your computer and use it in GitHub Desktop.
Testing map functions
from prompt_toolkit import prompt
# Test walking around on a map
"""
# * Room number (rm)
# * Location name (lo$)
# * items: monster, item, weapon, food
# * exits: north, east, south, west
# RC (room command: 1=move up,
# 2=move down),
# RT (Room exit transports you to:
# room #, or 0=Shoppe)
"""
game_map = dict(number=1, room_name="MERCHANT LOBBY", alignment="neutral", items=[0, 62, 0, 0],
exits=dict(north=0, east=0, south=0, west=0, up=0, down='Shoppe'),
desc="You are at the entrance to the store. There is a passage leading downward to the market area.")
item_dict = dict(number=62, name="ADVENTURER'S GUIDE")
"""
'number': '1',
'room_name': "MERCHANT LOBBY",
'alignment': 'neutral',
'items': [monster=0, item=62, weapon=0, food=0],
'exits': [north='0', east='0', south='13', west='0', up='0', down='Shoppe'],
'desc': "You are at the entrance to the store. There is a passage leading downward to the market area."),
tanabi:
game_map = {
"number": 1,
"room_name": "MERCHANT LOBBY",
etc etc
}
"""
def grammatical_list(item_list):
result_list = []
for item in item_list:
if item.endswith("s"):
result_list.append(f"some {item}")
elif item.startswith(('a', 'e', 'i', 'o', 'u')):
result_list.append(f"an {item}")
else:
result_list.append(f"a {item}")
# Add 'and' if we need it - tanabi
if len(result_list) > 1:
result_list[-1] = f"and {result_list[-1]}"
# Join it together
return ", ".join(result_list)
def room_info(room_num):
if debug:
print("Room #: ", game_map['number']) # should print '1'
print("Alignment: ", game_map['alignment'])
items_in_room = []
item = game_map['items'[2]] # FIXME: i want the 2nd item from the 'items' list, not 2nd char
if item:
items_in_room.append(item)
if len(items_in_room):
print("You see: ", items_in_room, sep=', ')
class Exit(object):
def __init__(self, target_id, desc, message):
self.target_id = target_id
self.desc = desc
self.message = message
def show_message(self):
print(self.message)
class Room(object):
room_sequence = 0
def __init__(self, number, name, alignment, items, desc):
self.number = number
self.name = name
self.alignment = alignment
self.items = items
self.exits = []
self.desc = desc
@staticmethod
def create_room(name, alignment, items, desc):
Room.room_sequence += 1
return Room(Room.room_sequence, name, alignment, items, desc)
class Map(object):
def __init__(self):
self.db = {}
def add_room(self, name, alignment, items, desc):
new_room = Room.create_room(name, alignment, items, desc)
self.db[new_room.number] = new_room
return new_room.number
def link_room(self, source_room, dest_room, desc, message):
new_exit = Exit(dest_room, desc, message)
if source_room not in self.db:
raise RuntimeError(f"{source_room} does not exist")
if dest_room not in self.db:
raise RuntimeError(f"{dest_room} does not exist")
self.db[source_room].exits.append(new_exit)
def show_room(room_number):
"""Show room name, alignment, players/NPCs here, exits"""
print(f'{map.db[room_number].name}', end='')
if debug:
print(f' (#{room_number}) ', end='')
print(f'{map.db[room_number].alignment}')
if descriptions:
print() # blank line
print(f'{map.db[room_number].desc}')
def move(room, direction):
"""FIXME"""
pass
if __name__ == '__main__':
debug = True
descriptions = True
# room_info(1) # FIXME
# should print "You see some bells, an apple, and a candle":
stuff_here = grammatical_list(['accordion'])
print(f'You see: {stuff_here}')
stuff_here = grammatical_list(['large chest', 'dry bones'])
print(f'You see: {stuff_here}')
stuff_here = grammatical_list(["bells", 'apple', 'candle'])
print(f'You see: {stuff_here}.')
# Create your world
map = Map()
# name, alignment, items[list], description
first_room_id = map.add_room("MERCHANT'S LOBBY +", "neutral", ["Adventurer's Guide"],
"""You are at the entrance to the store.
There is a passage leading downward to the market area.""")
second_room_id = map.add_room("Second Room", "foxy", [], "This is the second room.")
third_room_id = map.add_room("CAVERN HEAD +", "neutral", ["M.SAND CRAB"],
"You have reached the entrance to a large cavern.")
"""
items: 3,0,0,0
exits: 1,14,0,24,0,0
"""
map.link_room(first_room_id, second_room_id, "To Second Room", "You go to the second room.")
map.link_room(second_room_id, first_room_id, "To First room", "You go to the first room.")
# map.db has your rooms in it.
print(f'Second room name: {map.db[second_room_id].name}')
# Where does your exit link to?
print(f'First room links to: {map.db[map.db[first_room_id].exits[0].target_id].name}')
# FIXME: Show room exits - ryan
# print(f'Room exits: {map.db[map.db[first_room_id].exits[0]]}')
# Normally, exits are listed thusly:
# Ye may travel: North, West and Up.
# TODO: "Goggles of Cartography" item could expand exits by listing room names thusly:
# Ye may travel: North (to DRAGON DROP), West (to WATERSDEEP), and Up (to SNOWY PEAK).
# answer = prompt('Give me some input: ') # this no worky on Win10
# print(f'You said: {answer}.')
player_room = 1
show_room(player_room)
@Pinacolada64
Copy link
Author

All I know is some block of code is in the wrong place. :(

from prompt_toolkit import prompt

# Test walking around on a map

game_map = dict(number=1, room_name="MERCHANT LOBBY", alignment="neutral", items=[0, 62, 0, 0],
                exits=dict(north=0, east=0, south=0, west=0, up=0, down='Shoppe'),
                desc="You are at the entrance to the store. There is a passage leading downward to the market area.")

item_dict = dict(number=62, name="ADVENTURER'S GUIDE")

"""
tanabi:
game_map = {
    "number": 1,
    "room_name": "MERCHANT LOBBY",
     etc etc
}
"""


def grammatical_list(item_list, simple=False):
    """If 'simple' is True, we will make a comma list that looks like:

    x, y, and z

    if 'simple' is False, then we will parse each item name and add a plural.
    """

    result_list = []

    if simple:
        result_list = item_list

    else:
        for item in item_list:
            if item.endswith("s"):
                result_list.append(f"some {item}")
            elif item.startswith(('a', 'e', 'i', 'o', 'u')):
                result_list.append(f"an {item}")
            else:
                result_list.append(f"a {item}")

    # Add 'and' if we need it - tanabi
    if len(result_list) > 1:
        result_list[-1] = f"and {result_list[-1]}"

    # Join it together
    return ", ".join(result_list)


class Exit(object):
    def __init__(self, target_id, desc, message):
        self.target_id = target_id
        self.desc = desc
        self.message = message

    def show_message(self):
        print(self.message)


class Room(object):
    room_sequence = 0

    def __init__(self, number, name, alignment, items, desc):
        self.number = number
        self.name = name
        self.alignment = alignment
        self.items = items
        self.exits = []
        self.desc = desc

    @staticmethod
    def create_room(name, alignment, items, desc):
        Room.room_sequence += 1
        return Room(Room.room_sequence, name, alignment, items, desc)

    def list_exists(self):
        print(f"Ye may travel: {grammatical_list([x.desc for x in self.exits], simple=True)}")

    def show_room(self, room_number):
        """Show room name, alignment, players/NPCs here, exits"""
        print(f'{map.db[room_number].name}', end='')
        if debug:
            print(f' (#{room_number}) ', end='')
        print(f'{map.db[room_number].alignment}')
        if descriptions:
            print()  # blank line
            print(f'{map.db[room_number].desc}')
            map.db[room_number].list_exits()  # see here


class Map(object):
    def __init__(self):
        self.db = {}

    def add_room(self, name, alignment, items, desc):
        new_room = Room.create_room(name, alignment, items, desc)
        self.db[new_room.number] = new_room
        return new_room.number

    def link_room(self, source_room, dest_room, desc, message):
        new_exit = Exit(dest_room, desc, message)

        if source_room not in self.db:
            raise RuntimeError(f"{source_room} does not exist")

        if dest_room not in self.db:
            raise RuntimeError(f"{dest_room} does not exist")

        self.db[source_room].exits.append(new_exit)


def move(room, direction):
    """FIXME"""
    pass


if __name__ == '__main__':
    debug = True
    descriptions = True

    # should print "You see some bells, an apple, and a candle":
    stuff_here = grammatical_list(['accordion'])
    print(f'You see: {stuff_here}')

    stuff_here = grammatical_list(['large chest', 'dry bones'])
    print(f'You see: {stuff_here}')

    stuff_here = grammatical_list(["bells", 'apple', 'candle'])
    print(f'You see: {stuff_here}.')

    # Create your world

    map = Map()

    # name, alignment, items[list], description
    first_room_id = map.add_room("MERCHANT'S LOBBY +", "neutral", ["Adventurer's Guide"],
                                 """You are at the entrance to the store.
There is a passage leading downward to the market area.""")

    second_room_id = map.add_room("Second Room", "foxy", [], "This is the second room.")

    third_room_id = map.add_room("CAVERN HEAD +", "neutral", ["M.SAND CRAB"],
                                 "You have reached the entrance to a large cavern.")

    """
    items: 3,0,0,0
    exits: 1,14,0,24,0,0
    """

    map.link_room(first_room_id, second_room_id, "To Second Room", "You go to the second room.")
    map.link_room(second_room_id, first_room_id, "To First room", "You go to the first room.")

    # map.db has your rooms in it.
    print(f'Second room name: {map.db[second_room_id].name}')

    # Where does your exit link to?
    print(f'First room links to: {map.db[map.db[first_room_id].exits[0].target_id].name}')

    # FIXME: Show room exits - ryan
    # print(f'Room exits: {map.db[map.db[first_room_id].exits[0]]}')

    # Normally, exits are listed thusly:
    # Ye may travel: North, West and Up.
    # TODO: "Goggles of Cartography" item could expand exits by listing room names thusly:
    # Ye may travel: North (to DRAGON DROP), West (to WATERSDEEP), and Up (to SNOWY PEAK).

    # answer = prompt('Give me some input: ')  # this no worky on Win10
    # print(f'You said: {answer}.')

    player_room = 1

    show_room(player_room)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment