コード例 #1
0
from random import randint
from room import Room
from lexicon import *
from parser import *

ten_forward = Room("Ten Forward", """
This is Ten Forward.  It is the recreational facility on the USS Enterprise,
where officers, crew, and passengers can, um... recreate.
""")
ten_forward.add_items(['riker'])
trois_quarters = Room("Troi's Quarters", """
You are in Troi's quarters.
""")
trois_quarters.add_items(['troi'])
datas_quarters = Room("Troi's Quarters", """
You are in Data's quarters.
""")
datas_quarters.add_items(['data', 'spot'])
hallway = Room("Hallway", """
You are in a hallway on board the USS Enterprise.
""")
ten_forward.add_paths({'south': hallway})
trois_quarters.add_paths({'west': hallway})
datas_quarters.add_paths({'east': hallway})
hallway.add_paths({'north': ten_forward,
                   'east': trois_quarters,
                   'west': datas_quarters})

class Game(object):
    def __init__(self):
        self.current_room = hallway
コード例 #2
0
from room import Room
from player import Player
from item import Item
import getpass
import time

# Declare all the rooms

room = {
    'outside':
    Room(
        "Outside Cave Entrance", "North of you, the cave mount beckons",
        Item(
            "Cracked Axe",
            "While better days have been seen, this blood-soaked axe is better than nothing",
            10, 4, 3)),
    'foyer':
    Room(
        "Foyer", """Dim light filters in from the south. Dusty
passages run north and east.""",
        Item(
            "Coat",
            "It's getting cold in here. No one should notice one missing coat",
            0, 6, 3)),
    'overlook':
    Room(
        "Grand Overlook", """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.""",
        Item("Magic Sandwich",
             "You need to summon your spiritual strength for victory", "0",
コード例 #3
0
from room import Room
from character import Enemy, Character
from character_test import dave

from item import Item

dave.set_conversation("i will beat you")
dave.talk()

kitchen = Room('Kitchen')
kitchen.set_description('A dank and dirty room buzzing with flies.')

dining_hall = Room('Dining Hall')
dining_hall.set_description("A big room with a table and chairs in the center")

ballroom = Room('Ballroom')
ballroom.set_description("where Talented swimmers.")

kitchen.link_room(dining_hall, "south")
dining_hall.link_room(kitchen, "north")
dining_hall.link_room(ballroom, "west")
ballroom.link_room(dining_hall, "east")

dave = Enemy("Dave", "A smelly zombie")
dave.set_conversation("Brrlgrh... rgrhl... brains...")
dave.set_weakness("cheese")
dining_hall.set_character(dave)

cheese = Item("cheese")
cheese.set_description("A larg and smelly block of cheese.")
ballroom.set_item(cheese)
コード例 #4
0
from room import Room
from path_finder_agents import RandAgent, BBAgent

# env = Room(room=[[0, 0, 1], [0, 0, 1], [0, 0, 0]], target=[2, 2])
env = Room(prob=0.2, n=10, plot_on=True)
agent = RandAgent(env)
# agent = BFSAgent(env)
# agent = IDAgent(env)
# agent = AStarAgent(env)
# agent = GreedyAgent(env)
# gent = BBAgent(env,bound=20)

agent.run()
input('Press ENTER to get out of here')
コード例 #5
0
ファイル: adv.py プロジェクト: SethC16/Intro-Python-II
    Item('Worn Dagger', 'An old rusty dagger.'),
    'Sword of Thousand Truths':
    Item('Sword of Thousand Truths', 'Sword destorys all.'),
    'Cloak over 9000':
    Item('Cloak over 9000', 'Cloak has unbearable power.'),
    'Boots of Blinding Speed':
    Item('Boots of Blinding Speed', 'You will be fast but blind.'),
    'The Gatekeepers Key':
    Item('The Gatekeepers Key', 'Must open something valuable.')
}

# Declare all the rooms

room = {
    'outside':
    Room("Outside Cave Entrance", "North of you, the cave mount beckons",
         item['Worn Dagger']),
    'foyer':
    Room(
        "Foyer", """Dim light filters in from the south. Dusty
passages run north and east.""", item['Boots of Blinding Speed']),
    'overlook':
    Room(
        "Grand Overlook", """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.""",
        item['Cloak over 9000']),
    'narrow':
    Room(
        "Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air.""",
        item['The Gatekeepers Key']),
コード例 #6
0
ファイル: app_factory.py プロジェクト: zhaodan2000/MEEP
    def __init__(self,
                 domain,
                 *,
                 agent_class_name=None,
                 agent_model_path=None,
                 user_class_name=None,
                 user_model_path=None,
                 log_path='logs',
                 evaluation_file=None,
                 enable_translate=False,
                 num_rooms=5,
                 starting_evaluation_index=0,
                 user_stories=None,
                 generate_destinations=False,
                 save_logs=True,
                 purge_logs_every_N=0):
        '''
        domain - an instance of domains.Domain
        '''
        self.flask_app = Flask(__name__)
        CORS(self.flask_app)
        # doesn't matter
        self.flask_app.config['SECRET_KEY'] = 'super secret key'
        self.socket = SocketIO(self.flask_app, cors_allowed_origins="*")
        self.domain = domain
        self.save_logs = save_logs

        self._initialize_socket()
        self._initialize_endpoints()

        # create room for each story
        if user_stories is not None:
            # load stories
            with open(user_stories) as f:
                user_stories = json.load(f)
            assert len(user_stories) > 0, "story file is empty."
            print('{} user stories are loaded.'.format(len(user_stories)))
            # get ids of stories that already saved in the log
            saved_stories = set()
            for fn in os.listdir(log_path):
                if not fn.endswith('.json'):
                    continue
                with open(os.path.join(log_path, fn)) as f:
                    log_json = json.load(f)
                    is_sucess = False
                    for e in log_json['events']:
                        if e['event_type'] == 'end_dialog' and e[
                                'success'] == True:
                            is_sucess = True
                    if not is_sucess:
                        continue
                    if 'user_story' not in log_json:
                        continue
                    story = log_json['user_story']
                    if not story or 'id' not in story:
                        continue
                    story_id = story['id']
                    saved_stories.add(story_id)
            print('{} stories are saved in log dir.'.format(
                len(saved_stories)))
            # remove saved stories from the stories to load
            new_stories = []
            for s in user_stories:
                if s['id'] in saved_stories:
                    continue
                new_stories.append(s)
            user_stories = new_stories
            print('{} user stories will be used to create rooms.'.format(
                len(user_stories)))
            num_rooms = len(user_stories)
        else:
            user_stories = [None] * num_rooms

        # create rooms ids
        if None not in user_stories:  # use story id as room id if possible
            room_ids = [story['id'] for story in user_stories]
        else:
            room_ids = [str(i) for i in range(num_rooms)]

        # create rooms
        self.rooms = {}
        agent_shared_state = {}
        user_shared_state = {}
        for i, room_id in enumerate(room_ids):
            handle_end_dialog = functools.partial(self.end_dialog_confirm,
                                                  room_id=room_id)
            self.rooms[room_id] = Room(
                room_id,
                self.socket,
                domain,
                agent_shared_state,
                agent_class_name,
                agent_model_path,
                user_shared_state,
                user_class_name,
                user_model_path,
                handle_end_dialog,
                log_path,
                evaluation_file,
                enable_translate,
                starting_evaluation_index=starting_evaluation_index,
                user_story=user_stories[i],
                generate_destinations=generate_destinations,
                purge_logs_every_N=purge_logs_every_N)

            # Only set up room 0 in evaluation mode
            evaluation_file = None

        for interface in domain.interfaces:
            interface.create_endpoints(self.flask_app, self.rooms)
コード例 #7
0
from room import Room

kitchen = Room("Kitchen")
kitchen.set_description("A dank and dirty room buzzing with flies.")

dining_hall = Room("Dining Hall")
dining_hall.set_description(
    "A large room with ornate golden decorations on each wall.")

ballroom = Room("Ballroom")
ballroom.set_description(
    "A vast room with a shiny wooden floor. Huge candlesticks guard the entrance."
)

main_hall = Room("Main Hall")
main_hall.set_description(
    "An astonishing room with a large wooden staircase and ancient art and decorations."
)

indoor_garden = Room("Indoor Garden")
indoor_garden.set_description(
    "A fascinating botanical room with various plant life that enriches the room."
)

auditorium = Room("Auditorium")
auditorium.set_description(
    "An enormous room with endless seats and a widespread stage")

main_hall.link_room(ballroom, "northwest")
main_hall.link_room(dining_hall, "northeast")
ballroom.link_room(auditorium, "north")
コード例 #8
0
ファイル: test_moderation.py プロジェクト: wlgranados/qbot
def test_findingURL():
    test_room = Room('test')
    assert test_room.moderation.containUrl(
        'http://github.com is a good website'
    ), 'Should find an url in this string'
コード例 #9
0
ファイル: test_moderation.py プロジェクト: wlgranados/qbot
def test_stretching():
    test_room = Room('test')
    assert test_room.moderation.isStretching(
        'oioioioioioio', test_room.users), 'Should be recognized as stretching'
コード例 #10
0
ファイル: b.py プロジェクト: Bubba-che/Adventure-Game
from room import Room

one = Room(
    'sw',
    coord=[1, 0],
    desc=  #  Room 1
    """
You are in room B1.\n""")

two = Room(
    'nse',
    coord=[1, 1],
    monsters=2,
    desc=  #  Tiny monsters; Room 1
    """
You are in room B2.\n""")

three = Room(
    'nsw',
    coord=[1, 2],
    monsters=2,
    desc=  #  Tiny monsters; Room 1
    """
You are in room B3.\n""")

four = Room(
    'ns',
    coord=[1, 3],
    monsters=1,
    desc=  #  Tiny monster
    """
コード例 #11
0
def wonderland():

    # * INTRODUCTION

    title = ('\nWELCOME TO WONDERLAND!\n')

    royal_order = '   By order of the Queen, you are required to enter your name to enter this realm.\n'

    intro_1 = '   Out of the corner of your eye, you see a White Rabbit with a pocketwatch. You start following the White Rabbit and suddenly start falling down down down ...'

    intro_2 = '   You open your eyes and are surrounded in darkness. Slowly your eyes adjust and you see a faint light. You start walking in that direction.'

    intro_commands = 'To see all commands type: commands\nTo quit type: q (or quit)\n'

    print('\n' * 20)
    print(title)
    print(textwrap.fill(royal_order, width=65))
    next_victim = input('\n▸ ')
    print('\n')
    print(textwrap.fill(intro_1, width=65))
    print('\n')
    print(textwrap.fill(intro_2, width=65))
    print('\n')
    print(intro_commands)

    # * ITEMS

    items = {
        'bottle': Item('bottle', 'a bottle that says DRINK ME'),
        'cake': Item('cake', 'a very small cake that says EAT ME'),
        'key': Item('key', 'a tiny golden key'),
        'torch': Item('torch',
                      'in the deepest shadow there is a flicker of light'),
        'coin': Item('coin', 'a golden coin'),
        'pocketwatch': Item('pocketwatch',
                            'a beautiful golden watch on a chain'),
        'chest': Item('chest', 'an empty chest')
    }

    # * ROOMS

    room = {
        'outside':
        Room("Outside Cave Entrance", "North of you, the cave mount beckons.",
             [items['torch']]),
        'foyer':
        Room(
            "Foyer",
            """Dim light filters in from the south. Dusty passages run north \nand east.""",
            [items['bottle'], items['cake'], items['key']]),
        'overlook':
        Room(
            "Grand Overlook",
            """A steep cliff appears before you, falling into the darkness.\nAhead to the north, a light flickers in the distance, but \nthere is no way across the chasm.""",
            [items['coin']]),
        'narrow':
        Room(
            "Narrow Passage",
            """The narrow passage bends here from west to north. The smell of \ngold permeates the air.""",
            [items['pocketwatch']]),
        'treasure':
        Room(
            "Treasure Chamber",
            """You've found the long-lost treasure chamber! Sadly, it has \nalready been completely emptied by earlier adventurers. \nThe only exit is to the south.""",
            [items['chest']]),
    }

    # Link rooms together
    # getattr
    # hasattr
    room['outside'].n_to = room['foyer']
    room['foyer'].s_to = room['outside']
    room['foyer'].n_to = room['overlook']
    room['foyer'].e_to = room['narrow']
    room['overlook'].s_to = room['foyer']
    room['narrow'].w_to = room['foyer']
    room['narrow'].n_to = room['treasure']
    room['treasure'].s_to = room['narrow']

    # * PLAYERS

    # Make a new player object that is currently in the 'outside' room.

    player = Player(next_victim or 'Alice', room['outside'], [])
    print(player)

    rm_key = [k for k, v in room.items() if v == player.curr_room][0]
    rm_desc = room[rm_key]
    rm_inv_list = Room.get_inventory(room[rm_key])

    #  Write a loop that:
    #  Prints the current room name
    #  Prints the current description (the textwrap module might be useful here)
    #  Waits for user input and decides what to do.

    # outside = '{}'.format(player.get_room())
    # print(textwrap.fill(outside, width=50))

    options = '\nChase after the White Rabbit:\n[n] North   [e] East   [s] South   [w] West   [o] Outside   [q] quit\n\nPrepare for the adventure:\ntake <item> || drop <item> || inspect <item> || check inv || <commands>\n'

    all_verbs = ['take', 'drop', 'inspect', 'check']

    next_move = input('\n▸').lower()

    if next_move[0] in list('newsoq'):
        nsew = next_move

    elif next_move[0:4] == 'comm':
        print(options)

    curr_verb = next_move.split()[0]
    curr_obj = next_move.split()[1]

    # print('ITEMS IN ROOM', [i for i in rm_inv_list])

    all_item_keys = list(items.keys())[:]
    if curr_obj not in all_item_keys:
        print('Which item?', list(items.keys()))
    elif curr_verb == 'take':
        # print(player.take_item(curr_obj))
        # print(room[rm_key], curr_obj)
        # print(Room.item_taken(room[rm_key], curr_obj))
        player.take_item(curr_obj)
        Room.item_taken(room[rm_key], rm_inv_list[0])
        print('Current inventory:', player.get_inv())
        # print(Room.get_inventory(room[rm_key]))


#
# Which direction would you like to go?
# [n] North   [e] East   [s] South   [w] West   [o] other   [q] Quit
# other = input()
# * If the user enters a cardinal direction, attempt to move to the room there.
# * Print an error message if the movement isn't allowed.
# * If the user enters "q", quit the game.

    def try_direction(direction, curr_room):
        attribute = direction + '_to'
        if hasattr(curr_room, attribute):
            return getattr(curr_room, attribute)
        else:
            print('Oouch!')
            return curr_room

    room_keys = list(room.keys())[:]
    room_values = list(room.values())[:]

    while next_move[0] != 'q':

        if next_move[0] == 'o':
            player.set_room(room[player.return_outside()])

        elif next_move[0] in list('news'):

            new_room = try_direction(nsew, player.curr_room)
            for i, e in enumerate(room_values):
                if e == new_room:
                    player.set_room(room[room_keys[i]])
                    # print(player.get_room())
        else:
            print(player.get_room())
            next_move = input('\n▸').lower()
            if next_move[0] in list('newsoq'):
                nsew = next_move
        print(player.get_room())
        print(' ')
        # print(room[player.get_room()])
        # print(x.get_inventory())

        next_move = input('\n▸').lower()
        if next_move[0] in list('newsoq'):
            nsew = next_move

        if next_move[0:4] == 'comm':
            print(options)

        curr_verb = next_move.split()[0]
        curr_obj = next_move.split()[1]

        # print('ITEMS IN ROOM', [i for i in rm_inv_list])

        all_item_keys = list(items.keys())[:]
        if curr_obj not in all_item_keys:
            print('Which item?', list(items.keys()))
        elif curr_verb == 'take':
            # print(player.take_item(curr_obj))
            # print(room[rm_key], curr_obj)
            # print(Room.item_taken(room[rm_key], curr_obj))
            player.take_item(curr_obj)
            Room.item_taken(room[rm_key], rm_inv_list[0])
コード例 #12
0
ファイル: handler.py プロジェクト: ScottehMax/pyMon3
async def handle_msg(m, cb):
    messages = m.split('\n')

    if messages[0][0] == '>':
        room = messages.pop(0)[1:]
    else:
        room = 'global'

    for rawmessage in messages:
        print(f'{room}{rawmessage}')
        rawmessage = f'{">" + room}\n{rawmessage}'

        msg = rawmessage.split("|")

        if len(msg) < 2:
            continue

        if room.startswith('battle-') and cb.rooms.get(room):
            await cb.rooms[room].battle.handle(msg)

        downmsg = msg[1].lower()

        if downmsg == 'challstr':
            username = cb.username
            if cb.config[cb.id].get('password'):
                assertion = await login(username, cb.config[cb.id]['password'],
                                        '|'.join(msg[2:4]))
            else:
                assertion = await unreg_login(username, '|'.join(msg[2:4]))

            if len(assertion) == 0 or assertion is None:
                raise Exception('login failed :(')

            await cb.send('', f'/trn {username},0,{assertion}')

        elif downmsg == 'updateuser':
            if '@' in msg[2][1:]:
                user, status = msg[2].rsplit('@', 1)
            else:
                user = msg[2]
            if condense(user) == condense(cb.username):
                print("Logged in!")
                rooms = cb.config[cb.id]['rooms']
                # join rooms
                for room in rooms.split(','):
                    await cb.send('', f'/join {room}')
                # send status to last room
                await cb.send(room, f'/status {cb.status}')

        elif downmsg == 'formats':
            formats = msg[2:]
            res = {}
            format_name = False
            cur_format = None
            for format in formats:
                if format_name:
                    res[format] = []
                    cur_format = format
                    format_name = False
                    continue
                if format[0] == ',':
                    format_name = True
                    continue
                name, type = format.split(',', 1)
                res[cur_format].append({
                    'name': name,
                    'info': get_format_info(type)
                })
            cb.battle_formats = res

        elif downmsg == 'init':
            cb.rooms[room] = Room(room, cb)

        elif downmsg == 'deinit':
            del cb.rooms[room]

        elif downmsg == 'title':
            cb.rooms[room].title = msg[2]

        elif downmsg == 'users':
            cb.rooms[room].users = []
            for user in msg[2].split(',')[1:]:
                cb.rooms[room].users.append(user)
            print(cb.rooms[room].__dict__)

        elif downmsg == ':':
            cb.rooms[room].join_time = int(msg[2])

        elif downmsg == 'j':
            if '@' in msg[2][1:]:
                user, status = msg[2].rsplit('@', 1)
            else:
                user = msg[2]
            if condense(user) not in cb.rooms[room].users:
                cb.rooms[room].users.append(user)

        elif downmsg == 'l':
            if '@' in msg[2][1:]:
                user, status = msg[2].rsplit('@', 1)
            else:
                user = msg[2]
            for existing_user in cb.rooms[room].users:
                if condense(existing_user) == condense(user):
                    cb.rooms[room].users.remove(existing_user)

        elif downmsg == 'n':
            newuser, olduser, userfound = msg[2], msg[3], False
            if '@' in newuser[1:]:
                newuser, status = newuser[1:].rsplit('@', 1)
            for user in cb.rooms[room].users:
                if condense(user) == condense(olduser):
                    cb.rooms[room].users.remove(user)
                    userfound = True
            if userfound:
                cb.rooms[room].users.append(newuser)

        elif downmsg == 'updatechallenges':
            challs = json.loads(msg[2])
            for chall in challs['challengesFrom']:
                if challs['challengesFrom'][chall] == 'gen7doublescustomgame':
                    if cb.teams:
                        team = random.choice(cb.teams['gen7doublescustomgame'])
                        await cb.send('', f'/utm {team}')
                        await cb.send('', f'/accept {chall}')

        if downmsg in ['c', 'c:', 'pm', 'j', 'l', 'html']:
            await handle_chat(msg[1:], room, cb)
コード例 #13
0
murint3 = Wall(0.2, [(8, 4), (8, 7)], murint_materiau)
murint5 = Wall(0.2, [(10, 4), (10, 7)], murint_materiau)
murint4 = Wall(0.2, [(5, 4), (5, 7)], murint_materiau)
murint6 = Wall(0.2, [(3, 2), (8, 2)], murint_materiau)
murint7 = Wall(0.2, [(3, -1), (3, 1)], murint_materiau)

list_walls = [
    murext1, murext2, murext3, murext4, murext5, murext6, murext7, murext8,
    murext9, murext10, murint1, murint2, murint3, murint4, murint5, murint6,
    murint7
]

#
# creation de la pièce
#
room1 = Room()

room1.list_of_walls = list_walls

#
# ajout d'un emetteur dans la pièce
#
transmitter = Transmitter((5, 0), "lambda-demi")
room1.list_of_transmitters.append(transmitter)

#
# ajout de recepteurs couvrant toute la piece
# utiles au calcul de la puissance
#
list_of_receivers_creation(room1, 3, 3)
コード例 #14
0
ファイル: wourld.py プロジェクト: olnavr/MSI_prj
 def addRooms(self, r_list):
     for r in r_list:
         self.rooms.append(Room(*r))
コード例 #15
0
from room import Room
from player import Player
from item import Item
from item import Septre
from item import GoldCoins
from item import HolyGrail
from item import Map

# Declare all the rooms

room = {
    'outside':
    Room("Outside Cave Entrance", "North of you, the cave mount beckons", []),
    'foyer':
    Room(
        "Foyer", """Dim light filters in from the south. Dusty
            passages run north and east.""", [
            Septre(
                'Septre',
                'The septre of the king that could make any one invincible',
                'Gold')
        ]),
    'overlook':
    Room(
        "Grand Overlook", """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.""", [
            Map('Map', 'Helps you find your way to the treasure',
                'Medieval times'),
            GoldCoins('GoldCoins', 'Hidden in the overlook! Find it.',
                      'Millions')
コード例 #16
0
ファイル: test_moderation.py プロジェクト: wlgranados/qbot
def test_caps():
    test_room = Room('test')
    assert test_room.moderation.isCaps(
        'GITHUB IS A GOOD WEBSITE',
        test_room.users), 'should recognize it as caps'
コード例 #17
0
from room import Room
from item import Item, LightSource, Key
from setRoomGraphic import *

# Declare all the rooms

room = {
    'outside':
    Room("Outside Dungeon Entrance", "North of you, the Dungeon beckons",
         outside, dark_viz),
    'foyer':
    Room(
        "Foyer", """Dim light filters in from the south. Dusty
passages run north, west and east. A giant pillar is present at the center of the room.""",
        foyer, dark_viz),
    'overlook':
    Room(
        "Grand Overlook", """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.""", overlook, dark_viz),
    'narrow':
    Room("Narrow Passage",
         """The narrow passage bends here from west
to north. The smell of gold permeates the air.""",
         narrow,
         dark_viz,
         is_light=False),
    'treasure':
    Room("Treasure Chamber",
         """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
コード例 #18
0
ファイル: test_moderation.py プロジェクト: wlgranados/qbot
def test_add_banned_word():
    test_room = Room('test')
    test_room.moderation.addBan('phrase', 'CATFISH')
    assert test_room.moderation.isBanword(
        'catfish'), 'catfish should be a banned phrase'
コード例 #19
0
ファイル: adv.py プロジェクト: troyAmlee/Intro-Python-II
#             EXAMINATION: 'examine',
#             SOLVED: False,
#             UP: 'up', 'north',
#             DOWN: 'down', 'south',
#             LEFT: 'left', 'west',
#             RIGHT: 'right', 'east'
#     }
# }
# Declare all the rooms

room = {
    'outside':
    Room(
        "Outside Cave Entrance", "North of you, the cave mount beckons",
        "You see the sun set, and this beauty is bitter sweet. Unscramble this word ==> `lusunec`",
        "False", 'foyer', "False", "False", "False", [
            Item("Red Stone", "Illuminates a red hue when held to light."),
            Item("Demon Skull", "It makes a faint humming sound."),
            Herb("Healing Leaf", "A minty tasting leaf", 25, "Herb")
        ]),
    'foyer':
    Room(
        "Foyer", """Dim light filters in from the south. Dusty
                     passages run north and east.""",
        'You hear the cries of tortured people.\nThey eagerly would like to know what `avogadros number` is. (4 sig figs)',
        "False", 'overlook', 'outside', "False", 'narrow', []),
    'overlook':
    Room(
        "Grand Overlook", """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.""",
        "The door has locked behind you.\nAnother tortured scientist appears and asks:\nWhat is π/2 radians in degrees?",
コード例 #20
0
ファイル: path_finder_simulation.py プロジェクト: DiegoHMM/ia
from room import Room
from path_finder_agents import RandAgent, DFSAgent, GreedyAgent, BFSAgent, AStarAgent

# env = Room(room=[[0, 0, 1], [0, 0, 1], [0, 0, 0]], target=[2, 2])
env = Room(prob=0.3, n=25, plot_on=True)
# agent = RandAgent(env)
# agent = BFSAgent(env)
# agent = DFSAgent(env)
agent = AStarAgent(env)
# agent = GreedyAgent(env)

agent.run()
input('Press ENTER to get out of here')
コード例 #21
0
from room import Room, Arena
from item import Item, Container, SlingShot, Pebbles, Berries

# Declare rooms in rooms dict.
rooms = {
    'rest_stop':
    Room(
        "\nYou are at a North Cascades Hwy rest-stop. It is a crisp fall morning.",
        "North of you, a little dog barks and dashes down a forest trail. \nTo the South, your warm car "
        "and the open road."),
    'car':
    Room("You head down the road, wondering what could have been.",
         "An 18 wheeler crushes you. Look both ways before entering traffic."),
    'forest_trail':
    Room(
        "The trail opens to snow capped peaks and a lush valley.",
        "To the North, a wild river runs \nOther trails lead to the East and West. \nReturn to the "
        "parking lot to the South."),
    'river_bank':
    Room(
        "The clear, cold Skagit river rushes at your feet.",
        "Attempt to ford the river by heading North \nHead upstream to the East \nMove toward the "
        "Puget Sound by heading downstream, to the West. \nGo back toward the start by moving South"
    ),
    'trail_east':
    Arena(
        "A massive peak looms above.",
        "Climb the peak by continuing East. \nHead North along Kendal Catwalk. \nTo the South is the "
        "difficult Section K of the Pacific Crest Trail. \nThe sweeping valley vistas lie to the West"
    ),
    'trail_west':
コード例 #22
0
from room import Room

kitchen = Room("Kitchen")
kitchen.set_description("A dank and dirty room buzzing with flies.")

dining_hall = Room("Dining Hall")
dining_hall.set_description("Skeletons sit at their seats, their cracked and yellowing skulls staring at the goblets of wine they never got to finish.")

ballroom = Room("Ballroom")
ballroom.set_description("The glow of the moonlight that shines through the dingy windows catches each speck of dust in the air, making the spiderwebs that cling to the abandoned chairs glisten.")

kitchen.link_room(dining_hall, "south")
dining_hall.link_room(kitchen, "north")
dining_hall.link_room(ballroom, "west")
ballroom.link_room(dining_hall, "east")

current_room = kitchen
#print a new line, gets details, makes whatever the player types a variable and moves in that direction
while True:
	print("\n")
	current_room.get_details()
	command = input("> ")
	current_room = current_room.move(command)
コード例 #23
0
def create_room(id_, draft_type_id):
    room_map[id_] = Room(id_, broadcast_to_room, broadcast_to_spectator,
                         draft_types[draft_type_id])
コード例 #24
0
from room import Room
from player import Player
from item import Item

# Declare all the rooms

room = {
    'outside':
    Room("Outside Cave Entrance", "North of you, the cave mount beckons",
         [Item('Flash light', 'gives a bright light')]),
    'foyer':
    Room(
        "Foyer",
        """Dim light filters in from the south. Dusty passages run north and east."""
    ),
    'overlook':
    Room(
        "Grand Overlook", """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.""",
        [Item('Sword', 'handy for defending yourself')]),
    'narrow':
    Room(
        "Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air."""),
    'treasure':
    Room(
        "Treasure Chamber", """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.""",
        [Item('Treasure chest', 'you are reach now!')]),
コード例 #25
0
from room import Room

from player import Player
from item import Item
# Declare all the rooms

room = {
    'outside':
    Room("Outside Cave Entrance", "North of you, the cave mount beckons",
         [Item("Map", "For proper direction")]),
    'foyer':
    Room(
        "Foyer", """Dim light filters in from the south. Dusty
passages run north and east.""", [Item("Sword", "For protection")]),
    'overlook':
    Room(
        "Grand Overlook", """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.""",
        [Item("Key", "Opens Doors")]),
    'narrow':
    Room(
        "Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air.""",
        [Item("Apples", "For refreshment")]),
    'treasure':
    Room(
        "Treasure Chamber", """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.""",
        [Item("Basket", "Empty Treasure basket")]),
コード例 #26
0
from room import Room
from player import Player
from item import Item

# Declare all the rooms

room = {
    "outside": Room(
        "Outside Cave Entrance",
        "North of you, the cave mount beckons",
        [Item("fists", "First Weapon")],
    ),
    "foyer": Room(
        "Foyer",
        """Dim light filters in from the south. Dusty
passages run north and east.""",
        [Item("torch", "the faint glow from this torch can light up a room")],
    ),
    "overlook": Room(
        "Grand Overlook",
        """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.""",
        [Item("shiled", "protection from fire")],
    ),
    "narrow": Room(
        "Passage Narrow",
        """The narrow passage bends here from west
to north. The smell of gold permeates the air.""",
        [Item("sword", "Best weapon for close attack")],
    ),
コード例 #27
0
cooler = Asys.Cooler('Cooler', 5000)
temp = Asys.TemperatureSensor('Temp', temperature=293)
#def __init__(self, setpoint, k_P, k_I,
#heater_id=None, cooler_id=None, indoor_temp_sensor_id='', outdoor_temp_sensor_id=''):
controller = Asys.Controller(298, 5000, 20.00, heater.name, cooler.name,
                             temp.name)
#def __init__(self, name='', temperature=None, heat_capacity=1,
#temperature_sensor=None, position=None, heater=None, cooler=None):
office = Office(name='Asys room',
                temperature=293,
                heat_capacity=46.3e3,
                heater=heater,
                cooler=cooler,
                temperature_sensor=temp,
                controller=controller)
room = Room('Outside', 298, static=True)
office.add_neighbors([room])

dt = 1
time_stop = 20000  #24*3600
timeline = np.arange(0, time_stop + dt, dt)

pr = cProfile.Profile()

print(office.temperature_sensor)
office_temp = np.zeros((len(timeline), ))  #[office.temperature]
office_temp[0] = office.temperature
profile_it = False
if profile_it:
    pr.enable()
start = int(time.time())
コード例 #28
0
ファイル: adv.py プロジェクト: mherbert93/Intro-Python-II
from room import Room
from player import Player
from item import Item
import sys

# Declare all the rooms

room = {
    'outside':  Room("Outside Cave Entrance",
                     "North of you, the cave mount beckons",
                     items=[Item(name='Torch', description='A torch to guide your way')]),

    'foyer':    Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east.""", items=[Item(name='Sword', description='This is a 1 hand sword'),
                                        Item(name='Mace', description='This is a 1 hand mace')]),

    'overlook': Room("Grand Overlook", """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.""", items=[Item(name='Axe',
                                                                    description='This is a 1h axe')]),

    'narrow':   Room("Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air.""", items=[Item(name='Greatsword',
                                                               description='This is a 2 hand sword'),
                                                          Item(name='Shield', description='This is a shield')]),

    'treasure': Room("Treasure Chamber", """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."""),
}
コード例 #29
0
from room import Room

# Declare all the rooms

room = {
    'outside':  Room("Outside Cave Entrance",
                     "North of you, the cave mount beckons"),

    'foyer':    Room("Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),

    'overlook': Room("Grand Overlook", """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."""),

    'narrow':   Room("Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air."""),

    'treasure': Room("Treasure Chamber", """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."""),
}


# Link rooms together

room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
コード例 #30
0
ファイル: servidor.py プロジェクト: jramirez92/SD-P3
    except KeyError:
        response.status = 404
        return dumps({"error_description": f"La habitación {target_id} no está registrada en el sistema."})


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    logging.info('Inicializando Servicio')
    logging.info('\t· Buscando ArchivosServidor/')

    # Detección directorio ArchivosServidor
    try:
        mkdir('ArchivosServidor/')
        logging.info('\t\t No se ha detectado el directorio ArchivosServidor, se ha generado uno nuevo.')
    except FileExistsError:
        logging.info('\t\t Directorio ArchivosServidor/ detectado.')

    # Carga de las habitaciones en memoria
    logging.info('\t · Carga de Habitaciones en memoria')
    for h in listdir('ArchivosServidor/'):
        with open(f'ArchivosServidor/{h}', 'r') as file:
            json_data = load(file)
            try:
                habitacion = Room(json_data['plazas'], json_data['equipamiento'], json_data['precio'], json_data['disponible'], json_data['id'])
                registry[habitacion.id] = habitacion
                logging.info(f'\t\t Habitación {habitacion.id} cargada en memoria.')
            except IndexError:
                logging.error(f'El id {json_data["id"]} ya está cargado en memoria, la habitación no ha sido cargada.')

    logging.info('Inicialización finalizada.')
    run(host='localhost', port=8080)