def dig(self, direction): room = self.current_room direction = direction_abbreviations.get(direction, direction) if direction in room.exits: print "There is already an exit in that direction" return cur_pos = room.pos vector = direction_vectors[direction] new_pos = cur_pos+vector print "Digging %s" % (direction,) # Find the room in that direction, if any new_room = self.world.rooms.get(new_pos, None) if new_room is None: new_room = Room(underground_terrain, new_pos) self.world.rooms[new_pos] = room # Link the two rooms together. room.exits[direction] = new_room new_room.exits[opposite_directions[direction]] = room print "You dig into a new room." self.current_room = new_room
def loadRooms(self): import copy rooms = self.db.rooms.find() for i in range(0, rooms.count()): # default is zero newRoom = Room(self, rooms[i]) print newRoom print rooms[i] newRoom.id = rooms[i]['id'] if 'items' in rooms[i]: for item in rooms[i]['items']:# newRoom.items.append(copy.deepcopy(self.items[item])) if 'npcs' in rooms[i]: for mobile in rooms[i]['npcs']: m = Mobile(self.mobile_list[mobile]['name'], self, self.mobile_list[mobile]) m.room = newRoom self.mobiles.append(m) self.rooms.append(newRoom) # have to load all the rooms BEFORE loading the exits for i in range(0, rooms.count()): exits = rooms[i]['exits'] for e in exits: exit = exits[e] target_room = next(room for room in self.rooms if room.id == exit['target']) direction = exit['direction'] self.rooms[i].exits.append(Exit(direction.lower(), target_room))
class MyFactory(ServerFactory): protocol = Echo def __init__(self, clients_max=10): self.clients_max = clients_max self.clients = [] self.room = Room() def startSpeaking(self, client): # 某个客户端开始说话 log.msg("Client start speaking: %s"%hex(id(client))) self.room.startSpeaking(client) def speaking(self, content): log.msg("Client speaking: %d"%len(content)) self.room.speaking(content) def stopSpeaking(self, client): # 某个客户端开始说话 log.msg("Client stop speaking: %s"%hex(id(client))) self.room.stopSpeaking(client) def addClient(self, client): self.clients.append(client) self.room.addClient(client) def removeClient(self, client): self.clients.remove(client) self.room.removeClient(client)
def room_create(sock, data): user = User.find_user_by_sock(sock) target_name = data['details']['new_user'] echo = None if "echo" in data: echo = data['echo'] target_resource = user.resource target_online = User.find_user_by_name(target_name, user.resource) # sock de outro usuario conectado target_offline = None if not target_online: api_mongo.insert_user(target_name, target_resource) target_offline = target_name if user == target_online: info = {"type": "chat", "payload": {"command": "error", "details": "choose_another_less_you"}} send(user, info) else: second_user = None if target_online: second_user = target_online.username if not second_user: second_user = target_offline if second_user: if not Room.check_exist_room([user.username, second_user], user.resource): # se sala nao existe user_temp = [] for username in [user.username, second_user]: user_temp.append({"username": username, "seen": None, "received": None}) room_name = Room.open(user_temp, target_resource) # cria a sala e recebe nome unico a sala new_room = Room.find_room_by_name(room_name) # sock para o nova sala criada new_room.users_name = user_temp # insert two news name users new_room.alias = 'DEFAULT' # insert alias alias = new_room.alias api_mongo.insert_room(user_temp, room_name, alias, target_resource, False, None) info = {"type": "chat", "payload": {"command": "room_id", "alias": new_room.alias, "room_id": room_name, "users": user_temp, "echo": echo, "is_group": False}} send(user, info) else: # se sala ja existe user_temp = [] for username in [user.username, second_user]: user_temp.append({"username": username, "seen": None, "received": None}) room_to_append = Room.find_room_by_users([user.username, second_user], user.resource) room_restore(room_to_append) new_room = Room.find_room_by_name(room_to_append) # sock para o nova sala criada info = {"type": "chat", "payload": {"command": "room_id", "alias": new_room.alias, "room_id": room_to_append, "users": user_temp, "is_group": new_room.is_group}} send(user, info)
def test_room_paths(): center = Room("Center", "Test room in the center.") north = Room("North", "Test room in the north.") south = Room("South", "Test room in the south.") center.add_paths({'north': north, 'south': south}) assert_equal(center.go('north'), north) assert_equal(center.go('south'), south)
def test_player_move_out_of_bounds(self): room = Room(game=None, square_size=GRID_SIZE) room.load_from_file(os.path.join("test-files", "boundaries-test.map")) self.assertEqual(room.width, 10) self.assertEqual(room.height, 6) self.assertFalse(room.player.can_move_to(-1, 0)) self.assertFalse(room.player.can_move_to(10, 0)) self.assertFalse(room.player.can_move_to(0, -1)) self.assertFalse(room.player.can_move_to(0, 6))
def room_rename(sock, data=None): u = User.find_user_by_sock(sock) r = Room.find_room_by_name(data['destination']) r.alias = data['room_rename'] api_mongo.rename_room(data['destination'], data['room_rename']) list_user = Room.find_users_by_room(data['destination']) info = {"type": "chat", "payload": {"command": "room_rename", "room_id": data['destination'], "alias": data['room_rename']}} send_broadcast(list_user, info, u.resource)
def addRoom(self, adjRoom, type, direction=NO_DIR): # print "Add Room Called" # assign the room new coords relative to the adjacent room gridCoord = [0, 0] # if the new room is to the west of adjRoom if direction == WEST: gridCoord[x] = adjRoom.gridCoord[x] - 1 gridCoord[y] = adjRoom.gridCoord[y] # if the new room is to the north of adjRoom elif direction == NORTH: gridCoord[x] = adjRoom.gridCoord[x] gridCoord[y] = adjRoom.gridCoord[y] - 1 # if the new room is to the east of adjRoom elif direction == EAST: gridCoord[x] = adjRoom.gridCoord[x] + 1 gridCoord[y] = adjRoom.gridCoord[y] # if the new room is to the south of adjRoom elif direction == SOUTH: gridCoord[x] = adjRoom.gridCoord[x] gridCoord[y] = adjRoom.gridCoord[y] + 1 alreadyExists = False for room in self.rooms: if room.gridCoord == gridCoord: alreadyExists = True if not alreadyExists: # make the room newRoom = Room(direction, type, [None, None, None, None], gridCoord) newRoom.doors[opposite(direction)] = Door(opposite(direction)) adjRoom.doors[direction] = Door(direction) # update pointers if direction != NO_DIR: adjRoom.adjRooms[direction] = newRoom newRoom.adjRooms[opposite(direction)] = adjRoom newRoom.roomId = len(Dungeon.floorKeys) room = r.randint(0, len(self.rooms) - 1) xPos = r.randint(Room.currentRoom.boundingBox[WEST] + Key.keyImg.width/2, Room.currentRoom.boundingBox[EAST] - Key.keyImg.width/2) yPos = r.randint(Room.currentRoom.boundingBox[NORTH] + Key.keyImg.width/2, Room.currentRoom.boundingBox[SOUTH] - Key.keyImg.width/2) newKey = Key(xPos, yPos, self.rooms[room]) newRoom.rightKey = newKey Dungeon.floorKeys.append(newKey) self.rooms.append(newRoom) self.linkRooms(newRoom) return True if not alreadyExists else False
def __init__(self): cmd.Cmd.__init__(self) self.loc = Room.get_room(1) self.loc.print_room() self.dbfile = tempfile.mktemp() shutil.copyfile("game.db", self.dbfile)
def __init__(self): self.model = Room() self.view = PrintView() self.model.attach(self.view) self.network_listen() print('Listening to port {}...'.format(self.port)) reactor.run()
def move(self, direction): newroom = self.loc.get_neighbor(direction) if newroom is None: print("you can't go this way") else: self.loc = Room.get_room(newroom) self.loc.print_room()
def monitor(sock, data): u = User.find_user_by_sock(sock) print 'command from:', u.username command = data['command'] room_name = data['destination'] if command == 'users': li = [] for el in User.users: if el.username: li.append([el.username, el.network]) print 'Number users on:', len(li), '---', len(User.users) for el in li: print el if command == 'rooms': r = Room.find_room_by_name(room_name) try: print 'room alias:', r.alias print 'room users_name:', adapter(r.users_name) except: print 'no room' if command == 'message': u = User.find_user_by_name('*****@*****.**', 'dev-socialbase') info = {"type": "chat", "payload": {"command": "test_user", "details": str(u)}} u.connection.write_message(info) print 'B.sended to ', u.username, info
def reconnect_rooms(sock, user): li = room_list_by_user(sock=None, data={'sender': user}, call=False) for el in li: r = Room.find_room_by_name(el['room']) for u in adapter(r.users_name): if u == user: s = User.find_user_by_sock(sock) s.connection = sock
def __init__(self): Room.__init__(self) # make the walls (x_pos, y_pos, width, height) # This is a list of walls. Each is in the form [x, y, width, height] walls = [[0, 0, 20, 250, WHT], [0, 350, 20, 250, WHT], [780, 0, 20, 250, WHT], [780, 350, 20, 250, WHT], [20, 0, 760, 20, WHT], [20, 580, 760, 20, WHT], [390, 50, 20, 500, BLU] ] # loop through walls list for item in walls: wall = Wall(item[0], item[1], item[2], item[3], item[4]) self.wall_list.add(wall)
def roomFromShapes(handler): """ here's where we actually do the work. """ rm = Room() rm.eggs = [] rm.food = [] rm.ball = False ff = food.FoodFactory() #print rects for r in handler.rects: r.toGeom(rm) for a in handler.arcs: a.toGeom(rm, ff) if not rm.ball: rm.ball = ball.Ball(rm) return rm
def test_whitelist(): test_room = Room('test') test_user = User('bot', ' ', owner=False) test_room.addUser(test_user) assert not test_room.isWhitelisted(test_user), 'user should not be in white list' print(test_room.addToWhitelist(test_user)) print([usr.id for usr in test_room.tourwhitelist], test_room.isWhitelisted(test_user)) assert test_room.isWhitelisted(test_user), 'user should be in white list'
def room_restore(room_name): ''' Metodo que restaura uma sala em memoria :param room_name: :return: ''' rooms = json.loads(api_mongo.read_room(room_name)) if rooms: data = rooms["payload"]["details"] users_name = data['users_name'] dt = data['dt'] room = data['room'] alias = data['alias'] resource = data['resource'] is_group = data['is_group'] last_message = data['last_message'] Room.restore(users_name, dt, room, alias, resource, is_group, last_message)
class Server: '''A generic game server.''' #TODO: enforce MVC separation. #TODO: improve connection handling. def __init__(self): self.model = Room() self.view = PrintView() self.model.attach(self.view) self.network_listen() print('Listening to port {}...'.format(self.port)) reactor.run() def network_listen(self): self.port = 8800 self.realm = Realm(self.model) checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() checker.addUser("alice", 'camilo') checker.addUser("bob", 'camilo') p = portal.Portal(self.realm, [checker]) reactor.listenTCP(self.port, pb.PBServerFactory(p))
def createWorld(): a = Room("You are in room 1") b = Room("You are in room 2") c = Room("You are in room 3") d = Room("You are in room 4") Room.connectRooms(a, "east", b, "west") Room.connectRooms(c, "east", d, "west") Room.connectRooms(a, "north", c, "south") Room.connectRooms(b, "north", d, "south") i = Item("Rock", "This is just a rock.") i.putInRoom(b) player.location = a Monster("Bob the monster", 20, b)
def loadRooms(self): rooms = self.db.rooms.find() for i in range(0, rooms.count()): # default is zero exists = [r for r in self.rooms if r.id == rooms[i]['id']] if len(exists) > 0: newRoom = exists[0] newRoom.bg = rooms[i]['bg'] if 'bg' in rooms[i] else newRoom.bg newRoom.desc = rooms[i]['description'] if 'description' in rooms[i] else newRoom.desc else: newRoom = Room(self, rooms[i]) newRoom.id = rooms[i]['id'] if newRoom.bg: print "Has a background!", newRoom.bg newRoom.items = [] newRoom.exits = [] if 'items' in rooms[i]: for item in rooms[i]['items']:# newRoom.items.append(Item(self.items[item])) if 'npcs' in rooms[i]: # only respawn if there is NO combat going on in the room to avoid insane duplications! FIX ME currentMobiles = [mobile for mobile in self.mobiles if mobile.room == newRoom and mobile.combat and not mobile.is_player] if not len(currentMobiles) > 0: for mobile in rooms[i]['npcs']: m = Mobile(self.mobile_list[mobile]['name'], self, self.mobile_list[mobile]) m.room = newRoom self.mobiles.append(m) if len(exists) <= 0: self.rooms.append(newRoom) # have to load all the rooms BEFORE loading the exits for i in range(0, rooms.count()): exits = rooms[i]['exits'] for e in exits: exit = exits[e] target_room = next(room for room in self.rooms if room.id == exit['target']) direction = exit['direction'] self.rooms[i].exits.append(Exit(direction.lower(), target_room))
def test_person_entering(self): in_mock = DistanceSensorMock(1) out_mock = DistanceSensorMock(2) adaptor = InOutAdaptor(1,200,1000,in_mock,out_mock) in_mock.distance = 300 out_mock.distance = 300 room = Room() adaptor.add_listener(room) number = room.get_people() in_mock.distance = 300 out_mock.distance = 90 adaptor.start_reading() time.sleep(0.5) in_mock.distance = 90 out_mock.distance = 300 time.sleep(0.5) self.assertEqual(room.get_people(), number+1) adaptor.stop_reading()
def start(self): self.game_over = False self.time = 0 self.room = Room(self, 32) self.room.load_from_file(create_random_map_to_file()) self.screen = pygame.display.set_mode(self.room.canvas_size()) self.create_overlay() self.create_game_over_label() self.loop()
def user_remove(sock, data): # logging.info(' room_leave data{}:\n %r', data) users_to_remove = data['user_remove'] if type(users_to_remove) is unicode: users_to_remove = [data['user_remove']] u = User.find_user_by_sock(sock) users_remove = data['user_remove'] if type(users_remove) is unicode: users_remove = [data['user_remove']] print("USERS REMOVE ", users_remove) destination = data['destination'] # id de sala a ser alterada room_users = Room.find_users_by_room(destination) # Lista de usuarios em uma sala print("ROOOMS USERS", room_users) for el in users_remove: # envia mensagem dos novos nomes send_system_info(sock, destination, 'USER REMOVE', el) # envia message para grupo da saida do user u_list = [] # lista final for el in room_users: if not (el in users_remove): u_list.append(el) new_room = Room.find_room_by_name(destination) # sock para o nova sala alterada new_room.users_name = [{"username": _u, "seen": None, "received": None} for _u in u_list] current_user = User.find_user_by_sock(sock) for uremove in users_to_remove: api_mongo.remove_user_room(destination, uremove) u = User.find_user_by_name(uremove, u.resource) if u: info = {"type": "chat", "payload": {"command": "user_remove", "room_id": destination}} send(u, info)
def load_rooms(self): """Load rooms""" #If requested room is not loaded load it for roomfile in get_rooms_files_list(): roompath=os.path.join(mudlib.rootpath, "data/rooms/%s" % roomfile) #try load data try:data=yaml.load(open(roompath)) except Exception, e: print "EE Cannot load room from %s" % roompath print e continue #create room newroom=Room() newroom.uuid=data["uuid"] newroom.name=data["name"] newroom.desc=data["desc"] newroom.exits=data["exits"] #restore warps newroom.searchitems=data["searchitems"] #Load monsters for monster in data["monsters"]: newmon=globalmonsterloader.get_monster(monster) newroom.monsters.append(newmon) newroom.possible_monsters.append(monster) #for place in places: # # [X,Y,roomUuid] # newroom.places[place[1]][place[0]]=place[2] self.rooms[newroom.uuid]=newroom
def gen_connected_rooms(self): """ Generate a series of rooms, connected with vertical and horizontal tunnels. Each room is connected to the previous one with one tunnel. """ for i in xrange(cfg.MAX_ROOMS): w = SS.map_rand.randrange(cfg.MIN_ROOM_SIZE, cfg.MAX_ROOM_SIZE) h = SS.map_rand.randrange(cfg.MIN_ROOM_SIZE, cfg.MAX_ROOM_SIZE) x = SS.map_rand.randrange(0, self.w - w - 1) y = SS.map_rand.randrange(0, self.h - h - 1) new_room = Room(x, y, w, h) # See if any of the other rooms intersect with this one failed = False for room in self.rooms: if new_room.intersect(room): failed = True break if not failed: # First room if len(self.rooms) == 0: (new_x, new_y) = new_room.center() self.upstairs = (new_x, new_y) self.create_rectangular_room(new_room) self.place_objects(new_room) self.rooms.append(new_room) # Connect the rooms for j in xrange(1, len(self.rooms)): (new_x, new_y) = self.rooms[j].center() (prev_x, prev_y) = self.rooms[j - 1].center() if SS.map_rand.randrange(0, 2): self.create_h_tunnel(prev_x, new_x, prev_y) self.create_v_tunnel(prev_y, new_y, new_x) else: self.create_v_tunnel(prev_y, new_y, prev_x) self.create_h_tunnel(prev_x, new_x, new_y)
def user_change_text(sock, data): destination = data['destination'] tp = data["type"] u = User.find_user_by_sock(sock) list_user = Room.find_users_by_room(destination) info = {"type": "chat", "payload": {"command": "user_change_text", "room_id": destination, "user": u.username, "type": tp}} send_broadcast(list_user, info, u.resource)
def mockList(): firstRoom = Room() secondRoom = Room() thirdRoom = Room() fourthRoom = Room() firstRoom.name = "first" secondRoom.name = "second" thirdRoom.name = "third" fourthRoom.name = "fourth" roomList.append(firstRoom) roomList.append(secondRoom) roomList.append(thirdRoom) roomList.append(fourthRoom)
def room_history(sock=None, data=None): r = Room.find_room_by_name(data['destination']) since = 0 if 'since' in data: since = data['since'] h = r.history_read(since) h2 = json.loads(h) if sock: info = {"type": "chat", "payload": {"command": "room_history", "details": h2}} user_login = User.find_user_by_sock(sock) send(user_login, json.dumps(info))
def __init__(self): Room.__init__(self) walls = [[0, 0, 20, 250, PUR], [0, 350, 20, 250, PUR], [780, 0, 20, 250, PUR], [780, 350, 20, 250, PUR], [20, 0, 760, 20, PUR], [20, 580, 760, 20, PUR] ] # loop through walls list for item in walls: wall = Wall(item[0], item[1], item[2], item[3], item[4]) self.wall_list.add(wall) for x in xrange(100, 800, 100): for y in xrange(50, 451, 300): wall = Wall(x, y, 20, 200, RED) self.wall_list.add(wall) for x in xrange(150, 700, 100): wall = Wall(x, 200, 20, 200, WHT) self.wall_list.add(wall)
def make_rooms(): rooms = [] for x in range(0, 20): random.seed(None) room = Room(random.randrange(5, 20), random.randrange(5, 20), 0, libtcod.blue, char="#", MAP=MAP) room.set_map_coords() if room.map_coords: if room.no_collision(rooms): room.add_to_map() rooms.append(room) return rooms
from room import Room from character import Character, Enemy, Friend from item import Item 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." ) 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("aaaaaghhh") dave.set_weakness("cheese") dining_hall.set_character(dave) tabitha = Enemy("Tabitha", "An enormous spider with countless eyes and furry legs.") tabitha.set_conversation("Sssss....I'm so bored...") tabitha.set_weakness("book") ballroom.set_character(tabitha)
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 mouth 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."""), 'dragon': Room("--- Dragons Chamber", """Before you sits a White Dragon its golden eyes glinting in the dim light as he stares at you, 'Why do you come here? I have nothing for you.'""") } # Put items in rooms room['outside'].add_item('rock') room['foyer'].add_item('sword') room['foyer'].add_item('bow')
import shutil import numpy as np import random import operator from modules.aux_functions import * from room import Room from modules.global_vars import * from modules.reservation_management import get_reservation_code from modules.table_manager import manage_table, write_table_data, get_table_data np.random.seed(583) random.seed(352) my_hotel_path = HOTEL_TABLES_PATH + HOTEL + '/' file_name = '21_double-superior_breakfast_weekend_ls.json' file_to_test = my_hotel_path + file_name hotel_data = {} ara_values = {} # Open the file to read it with open(file_to_test, 'r') as fp: hotel_data = json.load(fp) room_type, season = operator.itemgetter(*[1, 4])( file_name.split(".")[0].split("_")) room = Room(room_type, HOTEL, hotel_data, season, file_name) new_price = room.optimal_price() print(new_price)
# Futurelearn - advenure game from room import Room from character import Enemy, Character, Friend # Kitchen kitchen = Room("Kitchen") # instantiate Kitchen object kitchen.set_description( "A dank and dirty room buzzing with flies. There is a large swinging door to the South, complete with porthole. Looking through it, you see a well-lit dining \ room and a table that seems to be filled with foodstuffs.") # Dining_hall dining_hall = Room("Dining Hall") # instantiate Dining Hall object dining_hall.set_description( "A well-lit room dominated by a large dining table brimming with delectable deserts. The Kitchen is North and the Ballroom is West." ) # Ballroom ballroom = Room("Ballroom") # instantiate Ballroom object ballroom.set_description( "This room is an old dance hall seeming to echo wih past parties from days long gone. There is a door that leads to a seemingly empty Dining Hall" ) # link rooms kitchen.link_room(dining_hall, "south") dining_hall.link_room(kitchen, "north") dining_hall.link_room(ballroom, "west") ballroom.link_room(dining_hall, "east") # set Enemy dave = Enemy("Dave", "A smelly zombie") # initialize enemy
def room_init(self): """ Setup all the rooms, returns a list containing all rooms [corridor, outside, *offices] """ """ The corridor layout is: Outside -------------------- R2 | R0 | R1 | R2 | R0 -------------------- Corridor -------------------- R5 | R3 | R4 | R5 | R3 -------------------- Outside """ # Setup the 'normal' rooms corridor = Room('CC', 273, heat_capacity=46e3, temperature_sensor=Asys.TemperatureSensor( 'CC_temp_sensor', 0)) outside = Room('OO', None, heat_capacity=46e3, temperature_sensor=Asys.TemperatureSensor( 'OO_temp_sensor', 0), static=True) # Setup the offices offices = [] office_names = ['NW', 'NN', 'NE', 'SW', 'SS', 'SE'] office_positions = [(1, -1), (1, 0), (1, 1), (-1, -1), (-1, 0), (-1, 1)] # I want another function to do this # office_temperatures = [303, 300, 294.0, 297, 291, 288] # I want another function to do this # office_requested_temperatures = [303, 300, 294.0, 297, 291, 288]#[293, 297, 295, 294, 298, 291] #print(office_requested_temperatures) # Create the new offices, currently with no temperature for name, position in zip(office_names, office_positions): temp = Asys.TemperatureSensor(f'{name}_temp_sensor', 0) heater = Asys.Heater(f'{name}_Heater', 1500) cooler = Asys.Cooler(f'{name}_Cooler', 1500) controller = Asys.Controller(f'{name}_Controller', 150, 1, heater.name, cooler.name, temp.name) offices.append( Office(name, temperature=None, heat_capacity=46e3, position=position, temperature_sensor=temp, heater=heater, cooler=cooler, controller=controller)) num_offices = len(offices) # Neighbor the North and South sides for i, office in enumerate(offices): if not i % 2 == 0: pass if i >= num_offices // 2: offset = num_offices // 2 else: offset = 0 neighbor_indices = offset + ( (i - 1) % (num_offices // 2)), offset + (((i + 1) % (num_offices // 2))) office.add_neighbors([ offices[neighbor_index] for neighbor_index in neighbor_indices ]) # Neighbor the north and south sides to the corridor and outside for office in offices: office.add_neighbors([corridor, outside]) #return [outside, corridor] + offices self.rooms = [outside, corridor] + offices
import textwrap from room import Room from player import Player from item import Item, LightSource, LockedItem wrapper = textwrap.TextWrapper(initial_indent=" ", subsequent_indent=" ") # Declare all the rooms room = { 'shack': Room( wrapper.fill("Shack"), wrapper.fill( "The thin wooden walls are rotting and the floor is nothing but dirt. It smells pretty bad in here. Light filters in from the door to the south." ), True), 'garden': Room( wrapper.fill("Overgrown Garden"), wrapper.fill( "It used to be a garden, but weeds have sprung up between the neatly planted rows. The air carries a light floral fragrance. You hear the rustling of chickens to the west. An iron gate guards the path east. To the south is a large forest. The small shack is just north." ), True), 'coop': Room( wrapper.fill("Chicken Coop"), wrapper.fill( "Cozy stalls hold about twenty dozing chickens. They look well-fed and content. East is the door to the garden." ), True), 'ruins': Room( wrapper.fill("Ancient Ruins"),
from room import Room start = Room("The Void","You should never see this room...") livingRoom = Room("Living Room","Filled with dust.") diningRoom = Room("Dining Room","Filled with dust.") hall = Room ("Hall","There is an old clock here.") den = Room ("Den","Filled with old sofas.") kitchen = Room("Kitchen","A kitchen.") house = [start, livingRoom, diningRoom, hall, den, kitchen] for room in house: print("Moving to a new room...") print (room)
from room import Room from item import Item from character import Enemy, Character, Friend from rpginfo import RPGInfo spooky_castle = RPGInfo("The Spooky Castle") spooky_castle.welcome() RPGInfo.info() kitchen = Room("Kitchen") kitchen.description = "A dank and dirty room buzzing with flies." dining_hall = Room("Dining Hall") dining_hall.description = "A large room with ornate golden decorations on each wall." ballroom = Room("Ballroom") ballroom.description = "A vast room with a shiny wooden floor. Huge candlesticks guard the entrance." print("There are " + str(Room.number_of_rooms) + " rooms to explore.") 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.conversation = "Brrlgrh... rgrhl... brains..." dave.weakness = "cheese" catrina = Character("Catrina", "A friendly skeleton.") catrina.conversation = "I got your back, my friend" dining_hall.character = dave kitchen.character = catrina cheese = Item("cheese")
def add_room(self, room_name, items): self.rooms_list.append(Room(room_name, items))
def generateRooms(self, numRooms): """ Generate a random graph of rooms """ self.rooms = {} if numRooms < 1: print("Must create at least 1 room") return None # The coordinates of our room. We start from (0,0) xy = [0, 0] # Keep track of which grid spots are occupied self.occupied = set() # Create a set that will hold the IDs of rooms with valid connections available validRooms = set() # Create n rooms for i in range(0, numRooms): # Create a room new_room = Room(f"Room {i}", "You are standing in an empty room.") self.rooms[i] = new_room if i == 0: # Our first room is always valid validRooms.add(i) self.occupied.add(str(xy)) else: # If it's not the first room.... # ...connect to the previous room in a random direction random_dir = None # In case we run into a room with no valid connections, keep looping # until we find a room with valid connections. # Note that there will ALWAYS be a valid room available while random_dir is None: # Get a room that we think is valid connectingRoom = validRooms.pop() # Get the coordinates of that room xy = self.rooms[connectingRoom].xy # See if we can get a random direction from that room random_dir = self.getRandomDirection( self.rooms[connectingRoom], xy) # If our room is valid (i.e. not None) then we put it back in our # set of valid rooms. if random_dir is not None: validRooms.add(connectingRoom) # If it's NOT valid, then we don't put it back into validRooms # and we try again with a different room. # We have a valid direction, so update the room and make the connection xy = self._updateCoordinates(xy, random_dir) self.rooms[connectingRoom].connectRooms(random_dir, new_room) self.occupied.add(str(xy)) new_room.xy = xy validRooms.add(i) # Set the starting room to the first room. Change this if you want a new starting room. self.startingRoom = self.rooms[0] if len(self.occupied) == numRooms: print("World successfully created!") else: print("Something is wrong....") return self.rooms
from room import Room from item import * from weapon_definitions import * from art import * cloakroom = Room("cloakroom", "The door slams closed behind you, shutting out the sound \ of the storm. Water drips off you onto the welcome mat.", "The storm continues to rage on outside; the sound of \ the rain and lightning is almost calming.", "You step into the dusty cloakroom.", item=Potion(name="Tonic",description="Supposedly good for your health.",weight=1,size=3), room_art = cloakroom_art) outside = Room("Outside", "You're hopelessly lost and the storm continues around you. \ That mansion looks rather cosy in comparison.", "There's nothing out here...", "You step out into the pouring rain") central_hallway = Room("Central Hallway", "The hallway is lined with portraits of faces you don't \ recognise.", "You feel like something's watching you...", "You step into the hallway", item=pocket_knife, room_art = central_hallway_art) courtyard = Room("Courtyard", "The rain pelts down on you out here, and the soil in the \ borders has begun to flood onto the paving. The bloodstains do not smudge.", "It's a beautiful sight, ruined by the bloodstains...",
def open_room(): room = Room() cod = str(hash(datetime.datetime.now()))[-5:] ROOMS[cod] = room return cod
async def handler(self, socket, path): self.clients.append(socket) print('Client connected') # 返回房间列表 await socket.send( get_mesg({ 'mesg': 'room_list', 'room_list': [{ 'id': i.roomId, 'type': i.type } for i in self.rooms] })) # 接收前端消息并转换成json对象 data = await socket.recv() data = json.loads(data) print(data) # 判断是添加房间还是加入房间 if data['mesg'] == 'add_room': room = Room(data['type'], data['args'], data['time'], len(self.rooms) + 1) self.rooms.append(room) order = data['order'] for i, c in enumerate(self.clients): if c != socket: try: await c.send( get_mesg({ 'mesg': 'room_list', 'room_list': [{ 'id': i.roomId, 'type': i.type } for i in self.rooms] })) except websockets.exceptions.ConnectionClosedOK: self.clients.remove(c) elif data['mesg'] == 'join': room = self.rooms[int(data['room_id']) - 1] order = room.getOrder() playerId = room.addPlayer(socket, order) # 返回房间和玩家信息 await socket.send( get_mesg({ 'mesg': data['mesg'], 'playerId': playerId, 'type': room.type, 'order': order })) # 等待进一步操作(开始 / 移动 / 悔棋) while True: data = await socket.recv() data = json.loads(data) print(data) if (data['mesg'] == 'start'): await room.start(playerId) elif (data['mesg'] == 'move'): location = data['location'] if data.get('kw') != None: await room.move(playerId, location, data['kw']) else: await room.move(playerId, location) elif (data['mesg'] == 'rollback'): await room.rollback()
def runVisualizer(roomDimensions, microphoneSensitivity, signalPos, sigStrength, micGrid, gridOffset, gridHeight, camPos): # Room parameters width = roomDimensions[0] length = roomDimensions[1] ceiling = roomDimensions[2] # Define room room = Room(width, length, ceiling) # Create a microphone array microphonePositions = helpers.generateMicArray(micGrid[0], micGrid[1], gridOffset, gridHeight) if not helpers.allInRoom(microphonePositions, room): print( "Some microphones fell outside the boundaries of the room, please re-enter data." ) return # Microphone parameters numMicrophones = len(microphonePositions) microphoneArray = [] micSensitivity = microphoneSensitivity # Set up microphone objects for x in range(0, numMicrophones): microphoneArray.append( Microphone(microphonePositions[x], micSensitivity)) # Configure DSP object dsp = DSP(99, microphoneArray) # Set up camera controller cameraPosition = camPos if not helpers.allInRoom([cameraPosition], room): print( "The camera fell outside the boundaries of the room, please re-enter data." ) return cameraOrientation = [0, 0] # pointing along x-axis in degrees cameraController = CameraController(cameraPosition, cameraOrientation, dsp, room) cameraController.setMicSensitivity(micSensitivity) cameraController.setMicPositions(microphonePositions) # Define Signal parameters signalPosition = signalPos if not helpers.allInRoom([signalPosition], room): print( "The signal fell outside the boundaries of the room, please re-enter data." ) return signalStrength = sigStrength # Send signal to all microphones for microphone in microphoneArray: microphone.sendSignal(signalPosition, signalStrength) print( "-> Audio signal at position x: {0}, y: {1}, z: {2} with strength {3} broadcast to all microphones" .format(signalPosition[0], signalPosition[1], signalPosition[2], signalStrength)) # Predict signal location using sphere trilateration predictedSignalLocation = cameraController.getSignalPosition( signalStrength) print("->>> Predicted Signal Location: {0}, Actual Signal Location: {1}". format(predictedSignalLocation, signalPosition)) cameraController.rePositionCamera(predictedSignalLocation) visualize(cameraController, signalStrength, predictedSignalLocation)
from room import Room, LockedRoom from player import Player from item import * # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mouth beckons"), 'foyer': Room( "Foyer", """Dim light filters in from the south. \ Dusty passages run north and east and an opening to a small cavern to the west.""" ), 'cavern': Room("Dusty Cavern", """Junk is strewn about this dusty 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."""), 'narrow': Room( "Narrow Passage", """The narrow passage bends here from west\ to north. The smell of gold permeates the air."""), 'treasure': LockedRoom( "Treasure Chamber", """You've found the long-lost treasure \ chamber! There are some flickering torches lining the room. You can see the overlook \ from here. Sadly, it has already been completely emptied by earlier adventurers. The \ only exit is to the south.""", "OrnateKey"),
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('Honey', "Just in case you come across a bear.")]), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east.""", [Item('Trumpet', "Both a weapon AND a musical instrument.")]), '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('Potion', "Suspicious contents in an unmarked bottle. What could go wrong?")]), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air.""", [Item('Lantern', "This will help you ward off the rats")]), '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('Crown', "What's a ruler without a crown?")]), } # Link rooms together
from room import Room from player import Player from items import Item # 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.""", [(Item('map', 'Map to another treasure in another location.'))]), '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', "an old rusty blade it's been here awhile."))]), 'narrow': Room( "Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air.""", [(Item( 'key', "Old rusty key, it has an inscription on it but it's worn and faded." ))]), 'treasure': Room( "Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by
def test_get_people(): room = Room() room.remove_person(datetime.now(), 0) assert (room.get_people() == 0) room.add_person(datetime.now(), 0) assert (room.get_people() == 1) room.remove_person(datetime.now(), 0) assert (room.get_people() == 0) room.add_person(datetime.now(), 0) assert (room.get_people() == 1) room.add_person(datetime.now(), 0) assert (room.get_people() == 2) room.remove_person(datetime.now(), 0) assert (room.get_people() == 1)
def center_text(text): return text.center(view_width) def show_room(player): print(center_text(player.current_room.get_name())) for line in textwrap.wrap(player.current_room.get_desc(), 40): print(center_text(line)) line_break() # 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(
def test_get_noise(): room = Room() room.set_noise(datetime.now(), 0, 20) assert (room.get_noise(datetime.now()) == 20) room.set_noise(datetime.now(), 1, 30) assert (room.get_noise(datetime.now()) == 25) room.set_noise(datetime.now() + timedelta(hours=1), 0, 30) assert (room.get_noise(datetime.now() + timedelta(hours=1)) == 30) assert (room.get_temperature(datetime.now() + timedelta(days=9)) is None)
############################ ### Compute Solution ### ############################ # Step 1: read input file (pixel-like image) and transform it to a simple polygon (with clearly marked in/out) print('Extracting polygon') polygon, gray_img, xy_to_pixel, meters_per_pixel = extract_polygon(INPUT_FILE, INPUT_YAML, ortho_tolerance=ORTHOGONAL_TOL) is_valid_location = construct_isValidLocation_function(gray_img, xy_to_pixel, ROBOT_RADIUS, meters_per_pixel) # Step 2: a Room object contains not only the boundary, but creates a discretized list of places # for the robot to guard (and list of places where the robot can actually move to) print('Creating room') room = Room(polygon, gray_img, xy_to_pixel, robot_buffer_meters=ROBOT_RADIUS, is_valid_guard=is_valid_location, room_eps=ROOM_EPSILON, guard_eps=ROBOT_EPSILON) if naive_solution: solve_naive(room, ROBOT_HEIGHT, DISINFECTION_THRESHOLD) else: # Step 3: we generate the LP problem and solve it. print('Solving lp') time, waiting_times, intensities = solve_full_lp(room, ROBOT_HEIGHT, ROBOT_RADIUS, ROBOT_WATTAGE, use_strong_visibility, use_strong_distances, scaling_method, DISINFECTION_THRESHOLD) # Step 4: Output a solution print('Total solution time:', time) print(room.guard_grid.shape) print(intensities.shape)
def test_room_paths(): center = Room("Center", "Test room in the center.") north = Room("North", "Test room in the north.") south = Room("South", "Test room in the south.") center.add_paths(['north': north, 'south': south])
from room import Room kitchen = Room("Kitchen") kitchen.set_desc("Where you cook") dining = Room("Dining Room") dining.set_desc("Where you eat") kitchen.link_room(dining, "south", True) kitchen.get_details() dining.get_details()
def test_map(): start = Room("Start", "You can go west and down a hole.") west = Room("Trees", "There are trees here, you can go east.") down = Room("Dungeon", "It's dark down here, you can go up.") start.add_paths(['west': west, 'down': down])
from room import Room from player import Player from item import Item from colors import colors # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons", [Item('Shield', 'Not really a weapon'), Item('Armor', 'also not a weapon')]), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east.""", [Item('Sword', 'A sharp metal thing')]), '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('Knife', 'A shorter metal thing')]), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air.""", [Item('Knife', 'A shorter metal thing')]), '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('Axe', 'Not that cool of a weapon')]), } # Link rooms together room['outside'].n_to = room['foyer']
def test_room(): gold = Room("GoldRoom", """This room has gold in it you can grab. There's a door to the north.""") assert_equal(gold.name, "GoldRoom") assert_equal(gold.paths, [])
from room import Room from item import Item from exit import Exit from game import Game from character import Character from menu import Menu, Option saloon = Room( "saloon", "Saloon du bateau", "Vous êtes dans un saloon qui n'a pas vu la lumière du jour depuis des lustres ! Oui, comme celui tout éclaté qui devait éclairer cette pièce autrefois. La dernière fête qui s'est déroulée ici a dû faire salle comble : les bouteilles jonchent pêle-même de grandes tables. Une immense tapisserie habille le mur du fond." ) myGame = Game(saloon, 300) cuisine = Room( "cuisine", "Cuisine du bateau", "Cette cuisine a connu de meilleurs jours... Mais on y trouve quelques restes !" ) bureau = Room( "bureau", "Bureau du commandant", "Ce bureau semble être la pièce qui a conservé le mieux sa grandeur d'antan. Des objets de valeur s'étalent sur le bureau, quelques feuilles dépassent encore d'un tiroir du bureau, et une peluche décousue vous regarde d'un oeil morne." ) balais = Room( "balais", "Placard à balais", "Dans cette pièce, vous avez à peine la place de vous retourner. Des outils ménagers y ont été jetés et oubliés." ) #ajouter quelques sorties entre ces pièces saloon.addDoubleExit(cuisine, "Cuisine du saloon", "Saloon") saloon.addDoubleExit(bureau, "Bureau du commandant Jackson", "Saloon") bureau.addDoubleExit(balais, "Placard étroit", "Bureau du commandant Jackson")
from room import Room one = Room( 'se', coord=[0, 0], puzzles=2, items=1, desc= # Puzzle-protected item; Room 1 """ You are in room A1.\n""") two = Room( 'ns', coord=[0, 1], monsters=2, desc= # Tiny monsters; Room 1 """ You are in room A2.\n""") three = Room( 'ne', coord=[0, 2], special=1, desc= # Room 1 """ You are in room A3.\n""") four = Room( 's', coord=[0, 3], items=1,
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 every wall.") ballroom = Room("Ballroom") ballroom.set_description("A vast room with a shiny wooden floor. Huge candlesticks guard the entrance.") closet = Room("Closet") closet.set_description("A small closet filled with cleaning supplies.") hallway = Room("Hallway") hallway.set_description ("A long hallway lined with paintings." kitchen.link_room(dining_hall, "south") dining_hall.link_room(kitchen, "north") dining_hall.link_room(ballroom, "west") ballroom.link_room(dining_hall, "east") hallway.link_room(ballroom, "south") ballroom.link_room(hallway, "north") hallway.link_room(closet, "west") closet.link_room(hallway, "east") current_room = kitchen while True: print ("\n") current_room.get_details()
def create_rooms(roomName, id): room = Room(roomName, id) return room