Exemple #1
0
 def initMap():
     intMap = [
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
         [0,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,0],
         [0,1,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0],
         [0,1,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0],
         [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
         [0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0],
         [0,1,1,1,1,1,0,1,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0],
         [0,0,0,0,0,1,0,1,1,1,1,0,1,1,1,1,0,1,0,0,0,0,0],
         [0,0,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0],
         [0,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0],
         [0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
         [0,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1],
         [0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
         [0,0,0,0,0,1,0,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0],
         [0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0],
         [0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0],
         [0,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,0],
         [0,1,0,0,0,1,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0],
         [0,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,0],
         [0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0],
         [0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,1,0,1,1,1,1,1,0],
         [0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,0],
         [0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,0],
         [0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0],
         [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],]
     newDict = {}
     for x in range(len(intMap)):
         for y in range(len(intMap[x])):
             if intMap[x][y] == 0:
                 newDict[(x,y)] = Room(Point(x,y), "SOLID")
             if intMap[x][y] == 1:
                 newDict[(x,y)] = Room(Point(x,y), "EMPTY")
     return newDict
Exemple #2
0
def set_room(info_rooms):
    """Con la información del diccionario, sacada de la API instancia la habitación y los direrentes objetos

  Args:
      [Player]: información del juegador

  Returns:
      [Objeto clase Room]: biblioteca
      [Objeto clase Object]: mueble_libros, mueble_sentarse, mueble_gabetas
  """
    info_rooms = info_API()
    biblioteca = Room(info_rooms[1]["name"])
    mueble_libros = Object(info_rooms[1]["objects"][0]["name"].title())
    mueble_libros.set_position(info_rooms[1]["objects"][0]["position"])
    mueble_libros.set_game(info_rooms[1]["objects"][0]["game"])
    mueble_sentarse = Object(info_rooms[1]["objects"][1]["name"].title())
    mueble_sentarse.set_position(info_rooms[1]["objects"][1]["position"])
    mueble_sentarse.set_game(info_rooms[1]["objects"][1]["game"])
    mueble_gabetas = Object(info_rooms[1]["objects"][2]["name"].title())
    mueble_gabetas.set_position(info_rooms[1]["objects"][2]["position"])
    mueble_gabetas.set_game(info_rooms[1]["objects"][2]["game"])
    biblioteca.add_object(mueble_libros)
    biblioteca.add_object(mueble_sentarse)
    biblioteca.add_object(mueble_gabetas)
    biblioteca.set_design(designs_room.biblioteca_design())

    return biblioteca, mueble_libros, mueble_sentarse, mueble_gabetas
Exemple #3
0
    def __load_dungeon(self):
        currentX=0
        currentY=0

        if os.path.exists( MAP_PATH + self.id ):
            dgnFile=open( MAP_PATH + self.id,'r')
            d_dict = do_load( dgnFile )
            dgnFile.close()
        else:
            d_dict = load_dungeon_by_id( self.id )

        self.sizeX = d_dict['x']
        self.sizeY = d_dict['y']
        self.theme = d_dict['theme']
        self.name = d_dict['name']
        self.next = d_dict['next']

        for line in d_dict['roomstr']:
            the_room = Room( currentX, currentY, line )
            self.rooms[(currentX,currentY)] = the_room

            if the_room.is_entrance():
                self.start=(currentX,currentY)

            currentX+=1
            if currentX==self.sizeX:
                currentY+=1
                currentX=0

            if currentY>self.sizeY:
                break
Exemple #4
0
def main():

    # Initialize room object
    room = Room()

    # Filename for room
    filename = 'room2015-12-06.pckl'

    # Read in room object from text file
    room.load_room(filename)

    # Print out info
    print "Loading Room from: " + filename
    room.describe()

    # Initialize Figure
    fig, ax = plt.subplots()

    # Define plot parameters
    # plt.xlim(-5, 5)
    # plt.ylim(-5, 5)
    plt.xlabel('X')
    plt.xlabel('Y')

    # Plot the areas and moves within each room
    for area in room.areas:
        plot_area(area, ax)

    plt.show()
Exemple #5
0
def set_room(info_rooms):
    """Con la información del diccionario, sacada de la API instancia la habitación y los direrentes objetos

  Args:
      [Player]: información del juegador

  Returns:
      [Objeto clase Room]: cuarto_servidores
      [Objeto clase Object]: puerta, rack, papelera
  """
    cuarto_servidores = Room(info_rooms[2]["name"])
    puerta = Object(info_rooms[4]["objects"][0]["name"].title())
    puerta.set_position(info_rooms[4]["objects"][0]["position"])
    puerta.set_game(info_rooms[4]["objects"][0]["game"])
    rack = Object(info_rooms[4]["objects"][1]["name"].title())
    rack.set_position(info_rooms[4]["objects"][1]["position"])
    rack.set_game(info_rooms[4]["objects"][1]["game"])
    papelera = Object(info_rooms[4]["objects"][2]["name"].title())
    papelera.set_position(info_rooms[4]["objects"][2]["position"])
    papelera.set_game(info_rooms[4]["objects"][2]["game"])

    cuarto_servidores.add_object(puerta)
    cuarto_servidores.add_object(rack)
    cuarto_servidores.add_object(papelera)
    cuarto_servidores.set_design(designs_room.server_design())

    return cuarto_servidores, puerta, rack, papelera
Exemple #6
0
    def createRoom(self):
        self.rooms = [
            Room(0),
            Room(1),
            Room(2),
            Room(3),
            Room(4),
            Room(5),
            Room(6),
            Room(7),
            Room(8),
            Room(9)
        ]

        passages = [{1, 4}, {0, 2}, {1, 3}, {2, 7}, {0, 5, 8}, {4, 6}, {5, 7},
                    {3, 6, 9}, {4, 9}, {7, 8}]
        pass_ext = [{1, 4}, {0, 2, 5, 7}, {1, 3, 6}, {2, 7}, {0, 5, 8, 9},
                    {4, 6, 1, 8}, {5, 7, 2, 9}, {3, 6, 9, 1}, {4, 9, 5},
                    {7, 8, 4, 6}]

        for index, room in enumerate(self.rooms):
            for otherRoom in passages[index]:
                room.addRoom(self.rooms[otherRoom])
            for otherRoom in pass_ext[index]:
                room.addExtendedRoom(self.rooms[otherRoom])
Exemple #7
0
    def getDailySales(self):
        price = 0
        for i in range(len(self.theRooms)):
            if (Room.isOccupied(self.theRooms[i])):
                price += Room.get__RoomRate(self.theRooms[i])

        print(f'Total cost for occupied rooms: ${price}')
Exemple #8
0
    def __load_dungeon(self):
        currentX = 0
        currentY = 0

        if os.path.exists(MAP_PATH + self.id):
            dgnFile = open(MAP_PATH + self.id, 'r')
            d_dict = do_load(dgnFile)
            dgnFile.close()
        else:
            d_dict = load_dungeon_by_id(self.id)

        self.sizeX = d_dict['x']
        self.sizeY = d_dict['y']
        self.theme = d_dict['theme']
        self.name = d_dict['name']
        self.next = d_dict['next']

        for line in d_dict['roomstr']:
            the_room = Room(currentX, currentY, line)
            self.rooms[(currentX, currentY)] = the_room

            if the_room.is_entrance():
                self.start = (currentX, currentY)

            currentX += 1
            if currentX == self.sizeX:
                currentY += 1
                currentX = 0

            if currentY > self.sizeY:
                break
Exemple #9
0
def renderer():  # to be called every frame to render every image in a list
    """
    ===========================================================================
    Blits everything to the screen that needs to be. Called every frame.
    ===========================================================================
    """

    if Room.prev_room:
        Helper.DISPLAY_SURFACE.blit(Room.prev_room.texture,
                                    Room.prev_room.position)
    Helper.DISPLAY_SURFACE.blit(Room.current_room.texture,
                                Room.current_room.position)
    Helper.DISPLAY_SURFACE.blit(Room.next_room.texture,
                                Room.next_room.position)

    Room.move_room()

    Helper.DISPLAY_SURFACE.blit(Player.Player.playerSurf,
                                Player.Player.playerPos)

    if Player.Player.inventoryIsOpen:
        Helper.DISPLAY_SURFACE.blit(
            ImageFiles.images['UI']['Inventory_Background'],
            Helper.INVENTORY_POSITION)

    for projectile in Projectile.attackSprites:
        Helper.DISPLAY_SURFACE.blit(projectile.sprite,
                                    (projectile.pos_x, projectile.pos_y))

    for enemy in Entity.enemy_list:
        Helper.DISPLAY_SURFACE.blit(enemy.sprite, enemy.pos)

    pygame.time.Clock().tick(Helper.REFRESH_RATE)
    pygame.display.flip()
Exemple #10
0
 def setRooms(self):
     positions_room_out = []
     positions_room_out.append((self.doors[0].x, self.doors[0].y)) #I understand that door 1 is out of the laboratory
     self.roomOut = Room(positions_room_out)
     positions_room1 = []
     for x in range(1,7):
         for y in range(1,3):
             pos = (x, y)
             positions_room1.append(pos)
     room1 = Room(positions_room1)
     positions_room2 = []
     for x in range(1,7):
         for y in range(4,17):
             pos = (x, y)
             positions_room2.append(pos)
     positions_room2.append((self.doors[1].x, self.doors[1].y))
     room2 = Room(positions_room2)
     positions_room3 = []
     for x in range(8,14):
         for y in range(4,10):
             pos = (x, y)
             positions_room3.append(pos)
     positions_room2.append((self.doors[2].x, self.doors[2].y))
     room3 = Room(positions_room3)
     positions_room4 = []
     for x in range(8,14):
         for y in range(11,17):
             pos = (x, y)
             positions_room4.append(pos)
     positions_room2.append((self.doors[3].x, self.doors[3].y))
     room4 = Room(positions_room4)
     self.rooms = [room1, room2, room3, room4, self.roomOut]
Exemple #11
0
def fill_rooms(data_base,letters,cruise_answer,r_type):

  """

  Regresa una lista con objetos tipo room

  cruise_answer representa el crucero seleccionado

  r_type representa el tipo de habitacion

  letters representa la letra del pasillo

  """
  rooms = []
  for r_letter in range(0,data_base[cruise_answer-1]["rooms"][r_type][0]):
    for r_number in range(1,data_base[cruise_answer-1]["rooms"][r_type][1]+1):
      if r_type == "simple":
        room = Room(letters[r_letter],r_number,data_base[cruise_answer-1]["capacity"][r_type],"Sencilla","Disponible",f"S{letters[r_letter]}{r_number}")
      elif r_type == "premium":
        room = Room(letters[r_letter],r_number,data_base[cruise_answer-1]["capacity"][r_type],"Premium","Disponible",f"P{letters[r_letter]}{r_number}")
      else: 
        room = Room(letters[r_letter],r_number,data_base[cruise_answer-1]["capacity"][r_type],"VIP","Disponible",f"V{letters[r_letter]}{r_number}")

      
      rooms.append(room)
  
  return rooms
 def test_init(self):
     """
     This test checks if the room is empty initially
     """
     room = Room()
     self.assertEqual("* * *\n* * *\n* * *\n", room.__str__(),
                      "Room should be empty but is not")
Exemple #13
0
    def __init__(self,
                 name,
                 theme,
                 next,
                 width,
                 height,
                 room_str=None,
                 id=None):
        if id:
            self.id = id
        else:
            self.id = unique_id()

        self.name = name
        self.theme = theme
        self.next = next
        self.width = width
        self.height = height

        self.roomlist = []

        for y in range(0, height):
            room_row = []
            for x in range(0, width):
                if room_str:
                    room_row.append(Room(x, y, room_str.pop(0)))
                else:
                    room_row.append(Room(x, y))
            self.roomlist.append(room_row)
Exemple #14
0
 def foo(self, red = 0, green = 0, blue = 0):
 
     # Insert your code here Kinga
     room = Room(123)
     room.changeColor(red, green, blue)
     # ---------------------------
     return """<html><body><div style="background-color:rgba(""" + red + "," + green + "," + blue + "," + """1); width: 100px; height: 100px;"></div></html></body>"""
Exemple #15
0
def new_game():
    """
    ===========================================================================
    Resets the state of the game.
    ===========================================================================
    """
    Entity.health_bars.clear()
    Entity.enemy_list.clear()
    Projectile.attackSprites.clear()
    Player.Player.is_dead = False
    Player.Player.playerInstances = 0
    Player.Player.playerInstance = Player.Player()
    Player.Player.currentLane = 0
    global current_player_level
    current_player_level = 1

    Room.rooms_list.clear()

    Room.reset_room()

    first_room = Room()
    second_room = Room()

    Room.current_room = first_room
    Room.next_room = second_room

    Helper.LANES['left'][1] = False
    Helper.LANES['middle'][1] = False
    Helper.LANES['right'][1] = False

    populate_current_room()
Exemple #16
0
    def __init__(self, game, size):
        """__init__ method for Dungeon class

        Args:
            game (<class 'Integrate.Game'>): Integrate.Game class object.
            size (<class 'tuple'>): the size of dungeon in a 2 point tuple.

        """
        self.game = game
        self.size = pygame.math.Vector2(size)
        w = int(self.size.x)
        h = int(self.size.y)
        self.room_matrix = [[None for i in range(w)]
                            for j in range(h)]  # Initializing empty rooms 2D
        self.room_list = []  # Initializing empty rooms 1D
        self.current_room_index = [h // 2,
                                   w // 2]  # Starting room set to middle one

        # beginnning room contains doors in all directions
        room_start = Room(self.game, 'NSWE', 'start')
        room_start.pos = [
            self.current_room_index[0], self.current_room_index[1]
        ]
        self.room_matrix[self.current_room_index[0]][
            self.current_room_index[1]] = room_start
        self.room_list.append(room_start)
        self.room_current = self.room_matrix[self.current_room_index[0]][
            self.current_room_index[1]]

        # variables for animation
        self.last_update = 0
        self.current_frame = 0

        self.tileset = random.choice(self.game.imageLoader.tileset_file)
Exemple #17
0
 def add_room(self, source_room, direction):
     newx, newy = source_room.translate(direction)
     new_room = Room(newx, newy, self.rh)
     source_room.exits[direction] = new_room
     source_room.bombs[direction] = False
     new_room.exits[mirror(direction)] = source_room
     self.rooms.append(new_room)
     return new_room
Exemple #18
0
 def enterRoom(self, entityCall, first=False):
     if self.gameType == const.PS and not first:
         if not self.halfway_join and (self.current_round > 0
                                       or self.state != const.ROOM_WAITING):
             entityCall.enterRoomFailed(
                 const.ENTER_FAILED_ROOM_HALFWAY_JOIN)
             return
     Room.enterRoom(self, entityCall, first)
Exemple #19
0
 def enter_room(self, inventory):
     light_sources = inventory.get(LightSource)
     if LightSource.is_one_on(light_sources):
         Room.enter_room(self, inventory)
     else:
         print ("You were eaten by a grue.")
         print ("Game over.")
         exit()
 def get_real_rooms_sector_id_sum(self, room_file):
     valid_sector_id_sum = 0
     for line in room_file:
         room_name = line[:-1]
         room = Room(room_name)
         if room.is_valid():
             valid_sector_id_sum += room.sector_id
     return valid_sector_id_sum
 def find_north_pole_storage(self, room_file):
     for line in room_file:
         room_name = line[:-1]
         room = Room(room_name)
         if room.is_valid():
             decrypted_name = room.get_decrypted_name()
             if 'north' in decrypted_name:
                 print('Potential match: room {:d}, "{:s}"'.format(room.sector_id, decrypted_name))
Exemple #22
0
 def enter_room(self, inventory):
     light_sources = inventory.get(LightSource)
     if LightSource.is_one_on(light_sources):
         Room.enter_room(self, inventory)
     else:
         print("You were killed by a Saitama")
         print("You died!!!")
         exit()
Exemple #23
0
def event_handler(game_state, player):
    """
    ===========================================================================
    Handles keyboard/mouse inputs. Called every frame.

    :param game_state: current state as a string (ie. Main_Menu, Settings, etc)
    :param player: current instance of player class (should only be one)
    :return: input action (ie, moving left or right), new game_state
    ===========================================================================
    """

    now = datetime.datetime.now()
    global game_is_saved
    global room_is_populated
    player_action = 'idle'

    if Entity.Enemy.numberOfOnscreenEnemies == 0 and not game_is_saved:
        game_is_saved = save_game(player)

    for event in pygame.event.get():
        if event.type == Helper.UPDATETIME:
            message = TimeOfDay.TimeOfDay.update_time_of_day(now)
            if message is not None and len(message) > 0:
                display_messages.append(message)
        if event.type == QUIT:
            game_state = 'Quit'
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                game_state = 'Main_Menu'
        elif event.type == MOUSEBUTTONDOWN:
            player_action = Inputs.read_mouse_down(event.pos)
        elif event.type == MOUSEBUTTONUP:
            player_action = Inputs.read_mouse_up(event.pos)

    if not room_is_populated:
        room_is_populated = populate_current_room()
    if not Player.Player.is_moving and not Player.Player.isLeavingRoom:
        if len(Entity.enemy_list) == 0:
            Player.Player.isLeavingRoom = True
            Room.advance_room()
            clean_room()

            # random roll for item

            if random.random() > 0.75:
                display_messages.append('Received a weapon!')
                Player.Player.Inventory.add_item(
                    Item.Weapon(add_to_backpack=True))
                Player.Player.Backpack.add_item(Player.Player.Inventory)

    if Room.current_room.position[1] >= Room.current_room_x\
            and Player.Player.isLeavingRoom:
        Player.Player.isLeavingRoom = False
        game_is_saved = False
        room_is_populated = False

    return player_action, game_state
Exemple #24
0
	def generateRandom(self):
		for i in range(5):
			size_x = random.randint(10, 20)
			size_y = random.randint(5, 10)
			x = random.randint(10, self.size_x - size_x - 10)
			y = random.randint(10, self.size_y - size_y - 10)
			room = Room(x, y, size_x, size_y)
			if not room.isInList(self.room, 4):
				self.room.append(room)
Exemple #25
0
def on_leave(data):
    username = data['username']
    room = data['room']

    Room.find(room).leave(username)

    leave_room(room)
    socketio.send(username + ' has left the room.', room=room)
    print('[noti] ' + username + ' has left the ' + room)
Exemple #26
0
    def index(self):

        # execute stuff
        print "Testing the stuff"
        room = Room(123)
        room.changeColor(0, 0, 0)

        # return page content
        return "<b>Hello world!</b>"
Exemple #27
0
	def createRoom(self,user,data):
		# roomid = "%06d"%(len(self.room)+1)
		remain = len(self.indexs)
		index = random.randint(0, remain)
		print index,remain
		id = str(self.indexs[index])
		room = Room(user,size = 2,id = id)
		self.room[id] = room
		self.indexs.pop(index)
		return {"code":1,"room":room.getRoomInfo(user)}
Exemple #28
0
 def add_edge(self, start, end, distance, edge_type='d'):
     if start not in self.rooms.keys():
         room = Room(start)
         self.rooms[start] = room
     if end not in self.rooms.keys():
         room = Room(end)
         self.rooms[end] = room
     self.rooms[start].add_neighbor(self.rooms[end], distance)
     if edge_type == 'u':
         self.rooms[end].add_neighbor(self.rooms[start], distance)
Exemple #29
0
 def start ( self ):
     """Creates all game object instances. No return.
     
     This is where specific Rooms, Items, Cotrollers, and pygame essentials are
     created.
     
     """
     if(DEBUG):print("Starting");
     pygame.init()
     #Create display
     self.DISPLAY_SURF = pygame.display.set_mode(self.SIZE)
     self.DISPLAY_SURF.fill((0,0,0))
     #Create Pygame objects here
     self.clock = pygame.time.Clock()
     #Player
     self.player = Character(initial_position = [40,600])
     #Veiw Manager
     self.veiwMan = ViewManager([255,255,255], [5,5], [self.WIDTH-10, self.HEIGHT-10], self.player) #Puts a white VeiwManager on screen
     #Control Manager
     self.conMan = ControlManager()
     self.conMan.setAvatar(self.player)
     #Creating Rooms
     greenRoom = pygame.sprite.Sprite()
     greenRoom.image = pygame.Surface([1000, 640])
     greenRoom.rect = greenRoom.image.get_rect()
     greenRoom.image.fill([0,255,0])
     self.room1 = Room(greenRoom, self.player) #Sets background to greenRoom and avatar to self.player
     
     grayRoom = pygame.sprite.Sprite()
     grayRoom.image = pygame.Surface([1000, 640])
     grayRoom.rect = grayRoom.image.get_rect()
     grayRoom.image.fill([100,100,100])
     self.room2 = Room(grayRoom, self.player)
     
     #Creating items
     self.box = Item([400, 600])
     self.box.setTouchEvent(pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room2}))
     self.box2 = Item([200, 600])
     self.box2.setInteractEvent(pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room1}))
     self.room1.addObject(self.box)
     self.room2.addObject(self.box2)
     self.itemGroup = pygame.sprite.RenderPlain(self.box,self.box2)
     
     #Making Text
     #This is not critical code
     if(pygame.font.get_init):
         hello = pygame.font.Font(None,64)
         hello = hello.render("Press Space", False, [0,0,0])
         x,y = self.veiwMan.rect.center
         x = x - (hello.get_width()/2)
         y = y - (hello.get_height()/2)
         self.veiwMan.image.blit(hello, [x,y])
     
     pygame.display.flip()
     self.RUNNING = True
Exemple #30
0
	def __init__(self):
		Room.__init__(self)
		self.tiles = []

		# 庄家index
		self.dealer_idx = -1
		# 当前控牌的玩家index
		self.current_idx = 0
		# 对当前打出的牌可以进行操作的玩家的index, 服务端会限时等待他的操作
		# 房间基础轮询timer
		self._poll_timer = None
		# 玩家操作限时timer
		self._op_timer = None
		# 玩家操作限时timer 启动时间
		self._op_timer_timestamp = 0
		# 一局游戏结束后, 玩家准备界面等待玩家确认timer
		self._next_game_timer = None

		self.current_round = 0
		self.last_player_idx = -1
		# 房间开局所有操作的记录(aid, src, des, [data])
		self.op_record = []
		# 房间开局操作的记录对应的记录id
		self.record_id = -1
		# 确认继续的玩家
		self.confirm_next_idx = []
		# 解散房间操作的发起者
		self.dismiss_room_from = -1
		# 解散房间操作开始的时间戳
		self.dismiss_room_ts = 0
		# 解散房间操作投票状态
		self.dismiss_room_state_list = [0] * self.player_num
		self.dismiss_timer = None
		# 房间创建时间
		self.roomOpenTime = time.time()
		# 玩家操作列表
		self.wait_op_info_list = []
		# 抢庄倍数(0不抢, 1:一倍....)
		self.fight_dealer_mul_list = [-1] * self.player_num
		# 叫地主分数
		self.bet_score_list = [-1] * self.player_num
		# 分数倍数
		self.mul_score_list = [0] * self.player_num
		self.cur_allow_op = OP_NONE
		# 续房的标记
		self._continue_room_flag = False
		# 地主的三张牌
		self.host_cards = []
		self.last_discard_idx = -1
		self.discard_record = LimitQueue(3)
		# 上一个win的玩家
		self.last_win_idx = 0
		self.boom_times = 0
		self.op_seconds = FORCE_OP_SECONDS
Exemple #31
0
    def __gameSetup__(self):  #Sets up all the rooms for the game
        #(6,[(0,3),(2,6),(3,3),(3,4),(3,5),(4,3)])

        rooms = [
            Room(1, Grid.map1, self.roomResolution),
            Room(2, Grid.map2, self.roomResolution),
            Room(3, Grid.map3, self.roomResolution),
            Room(4, Grid.map4, self.roomResolution),
            Room(5, Grid.map5, self.roomResolution)
        ]
        return rooms
Exemple #32
0
 def findReservation(self, occupantName):
     NOT_FOUND = True
     i = 0
     while NOT_FOUND == True:
         if Room.get__Occupant(self.theRooms[i]) == occupantName:
             Room.set_Occupied(self.theRooms[i], False)
             NOT_FOUND = False
             return i
         else:
             i += 1
         if (len(self.theRooms) == i + 1):
             return -1
Exemple #33
0
    def __init__(self, numSingles, numDoubles, name):
        self.numSingles_ = numSingles
        self.numDoubles_ = numDoubles

        self.listRooms_ = []
        for i in range(numSingles):
            self.listRooms_.append(Room(1, [], name, i))
        for i in range(numDoubles):
            self.listRooms_.append(Room(2, [], name, i + numSingles))

        self.numRooms_ = len(self.listRooms_)
        self.name_ = name
Exemple #34
0
def chat_add(_id):
    try:
        Room.get(_id)
    except:
        return jsonify(error='No room with that name exists'), 400
    user = current_user.id
    message = u'[%s]: %s' % (user, request.form['message'])
    l = logging.getLogger(_id)
    l.info(message)
    red = redis.Redis(connection_pool=pool)
    red.publish(_id, message)
    return jsonify(success='message posted')
Exemple #35
0
def event_handler(game_state, player):
    """
    ===========================================================================
    Handles keyboard/mouse inputs. Called every frame.

    :param game_state: current state as a string (ie. Main_Menu, Settings, etc)
    :param player: current instance of player class (should only be one)
    :return: input action (ie, moving left or right), new game_state
    ===========================================================================
    """

    now = datetime.datetime.now()
    global game_is_saved
    global room_is_populated
    player_action = 'idle'

    if Entity.Enemy.numberOfOnscreenEnemies == 0 and game_is_saved is False:
        game_is_saved = save_game(player)

    for event in pygame.event.get():
        if event.type == Helper.UPDATETIME:
            TimeOfDay.TimeOfDay.update_time_of_day(now)
        if event.type == QUIT:
            game_state = 'Quit'
        elif event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                game_state = 'Main_Menu'
            elif event.key == K_m:
                print_data()
        elif event.type == MOUSEBUTTONDOWN:
            player_action = Inputs.read_mouse_movements(event.pos)

    if not room_is_populated:
        room_is_populated = populate_current_room()
    # if Entity.Enemy.numberOfOnscreenEnemies < 3:
    #     Entity.enemy_list.append(Entity.Enemy())
    # elif event.key == K_h and Entity.Enemy.numberOfOnscreenEnemies > 0:
    #     for enemy in Entity.enemy_list:
    #         enemy.__del__() todo: remove
    if not Player.Player.is_moving and not Player.Player.isLeavingRoom:
        if len(Entity.enemy_list) == 0:
            Player.Player.isLeavingRoom = True
            Room.advance_room()
            clean_room()

    if Room.current_room.position[1] >= Room.current_room_x\
            and Player.Player.isLeavingRoom:
        Player.Player.isLeavingRoom = False
        game_is_saved = False
        room_is_populated = False

    return player_action, game_state
Exemple #36
0
def createRoom(roomName, serving):
    if checkUniqueRoom(roomName):
        room = Room(roomName, serving)
        room.addUser(serving)
        rooms[roomName] = room
        msg = messageMaker("Se ha creado la habitacion: " + roomName,
                           "[Servidor]", MessageEvents.MESSAGE)
        serving.transport.send(msg)
    else:
        msg = messageMaker(
            "Ya existe una habitacion con ese nombre, usa uno distinto",
            "[Servidor]", MessageEvents.MESSAGE)
        serving.transport.send(msg)
Exemple #37
0
def chat_get_or_create():
    name = request.form['name']
    module = Module(request.form['module_user'],
                    request.form['module_name'],
                    request.form['module_version'])
    try:
        Room.get(name)
    except:
        Room.add(name, module)
        l = logging.getLogger(name)
        h = logging.FileHandler(os.path.join(app.config['LOG_DIR'], name + '.log'))
        l.setLevel(logging.INFO)
        l.addHandler(h)
    return jsonify(room=dict(name=name))
Exemple #38
0
class Machine:
    """A machine operates cells within a room according to it's neighbourhood-law"""
    def __init__(self):
        self._room = Room()

    def initialise(self, number):
        """Initialises a machine with a number of cells"""
        for index in range(number):
            coordinate = self._room.getNextCoordinate()
            cell = Cell()
            self._room.add(coordinate, cell)

    def cycle(self):
        """Cycles through the Automat according to Conways rules"""
        # Implements the rules of Conways Game of Life
        past_room = self._room  # Calculate all operations on the expired room

        for coordinate in past_room._space.keys():
            neighbours = past_room.neighbours(coordinate)
            if len(neighbours) > 2 or len(neighbours) > 3:
                self._room.killCell(coordinate)
            elif len(neighbours) == 2 or len(neighbours) == 3:
                pass
            elif len(neighbours) == 3 and past_room.getCellColor(
                    coordinate) == Color.black:  # if dead
                self._room.spawnCell(coordinate)

    def __str__(self):
        """Returns a string representation of a machine"""
        # TODO: This is a bit performance-consuming
        border = self._room.border
        str = ''
        while (
                border % 2
        ) > 0 or border > self._room.border:  # Find the next matching number for 2 sane rasters
            border = border - 1

        columns = range(int(border / 2))
        first_colum = min(columns)

        def getSign(coordinate):
            if self._room.exists(coordinate):
                if self._room.getCellColor == Color.black:
                    return 'B'
                else:
                    return 'W'
            else:
                return 'N'

        for x in columns:
            if x is not first_colum:
                str = str + '\n'  # Start a new line
            for y in columns:
                coordinate = Coordinate(x, y)
                if y is first_colum:
                    str = str + getSign(coordinate) + ' '
                else:
                    str = str + getSign(coordinate) + ' '

        return str.format()
Exemple #39
0
    def __loadRoom(self, roomID):
        fileName = '{0}/rooms/{1}.json'.format(self.__absPath, roomID)
        with io.open(fileName) as fp:
            jsObj = json.load(fp)

        room = Room()
        room.id = roomID
        room.name = jsObj['name']
        if 'objects' in jsObj:
            room.objects = jsObj['objects']
        if 'directions' in jsObj:
            room.directions = jsObj['directions']
        if 'onUse' in jsObj:
            room.onUse = jsObj['onUse']
        if 'onEnter' in jsObj:
            room.onEnter = jsObj['onEnter']

        utils.defaultRoom(room)

        for obj in room.objects:
            utils.defaultObject(obj)

        for direction in room.directions:
            utils.defaultDirection(direction)

        self.__rooms[roomID] = room
Exemple #40
0
def main():
    '''
        Runs main robot Sense-Plan-Act loop
    '''

    print "Importing functions ..."

    # from python_mysql_connect import connect, insert_current_pos, query_current_pos
    from motor import GPIOclean
    from Room import Room
    import navigation
    # from maptool import pull_map
    # from slam import slamfunc

    # print "Connecting to database ..."
    # connect()

    # print "Downloading map from database ..."
    # pull_map()

    room = Room()

    if len(sys.argv) > 1:
        print "Loading up Room: " + str(sys.argv[1])
        room.load_room()
    else:
        print "No Room specified, using empty Room ..."

    print "Starting main exploration loop ..."

    for i in range(0, params.p['MAX_ITER']):

        # Explore (Move to a new area)
        room = navigation.explore(room)

    print "Exited main exploration loop ..."

    print "Storing room to file..."
    room.store_room()

    # print "Pushing map to database ..."
    # push_map()

    print "Clean up motor GPIO ..."
    GPIOclean()
Exemple #41
0
def chat_code(_id):
    r = Room.get(_id)
    if r.module is None:
        return jsonify(error='no module of that name'), 404
    return jsonify(module=dict(
        user=r.module.user,
        name=r.module.name,
        version=r.module.version,
        encrypt=r.module.encrypt,
        decrypt=r.module.decrypt,
        comms=r.module.comms))
    def __init__(self):
        pygame.init()
        
        # screen size
        root = tk.Tk()
        self.WIDTH = int(root.winfo_screenwidth()*0.58565)
        self.HEIGHT = int(root.winfo_screenheight()*0.78125)
        
        # movement booleans
        self.up_pressed = False
        self.down_pressed = False
        self.left_pressed = False
        self.right_pressed = False
        
        # pygame inits
        self.game_display = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
        pygame.display.set_caption('Sneaky Santa')
        self.clock = pygame.time.Clock()
        self.gameExit = False

        # init game objects
        self.santa = Santa(50, 50)
        self.obstacles = [Obstacle(100, 100)]
        self.room = Room(self.obstacles, self.santa)
class Game:
    def __init__(self):
        pygame.init()
        
        # screen size
        root = tk.Tk()
        self.WIDTH = int(root.winfo_screenwidth()*0.58565)
        self.HEIGHT = int(root.winfo_screenheight()*0.78125)
        
        # movement booleans
        self.up_pressed = False
        self.down_pressed = False
        self.left_pressed = False
        self.right_pressed = False
        
        # pygame inits
        self.game_display = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
        pygame.display.set_caption('Sneaky Santa')
        self.clock = pygame.time.Clock()
        self.gameExit = False

        # init game objects
        self.santa = Santa(50, 50)
        self.obstacles = [Obstacle(100, 100)]
        self.room = Room(self.obstacles, self.santa)

    def game_loop(self):
        stop = False
        while not self.gameExit:
            self.game_display.fill( (255, 255, 255) )
            self.game_display.blit(self.room.getimg(), (0, 0))
            for o in self.obstacles:
                self.game_display.blit(o.getimg(), o.getpos())
            self.game_display.blit(self.santa.getimg(), self.santa.getpos())
            if stop == False:
                count = 0 
                self.controls()
                self.santa.setvel(self.up_pressed, self.down_pressed, self.left_pressed, self.right_pressed)
                collision_status = self.room.check_collision(self.santa)
                stop = self.collision_handler(collision_status)
            
            count = count + 1
            if count == 15:
                stop = False

            self.santa.update()
            pygame.display.update()

    def controls(self):
        for event in pygame.event.get():
                                    
            if event.type == pygame.QUIT:
                self.gameExit = True

            # key pressed
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    self.up_pressed = True
                
                if event.key == pygame.K_DOWN:
                    self.down_pressed = True
                
                if event.key == pygame.K_LEFT:
                    self.left_pressed = True
                    
                if event.key == pygame.K_RIGHT:
                    self.right_pressed = True

            # key released
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_UP:
                    self.up_pressed = False
                
                if event.key == pygame.K_DOWN:
                    self.down_pressed = False
                
                if event.key == pygame.K_LEFT:
                    self.left_pressed = False
                    
                if event.key == pygame.K_RIGHT:
                    self.right_pressed = False

    def collision_handler(self, status):
        if status == "NO_COLLISION":
            return False
        elif status == "HARD_OBJECT":
            stop = self.santa.hard_object()
Exemple #44
0
def index():
    current_user.modules = list(Module.getall(current_user))
    return render_template('index.html', user=current_user, page='index', rooms=list(Room.getall()))
def perceptual_quality_evaluation(good_source, bad_source):
    '''
    Perceputal Quality evaluation simulation
    Inner Loop
    '''

    # Imports are done in the function so that it can be easily
    # parallelized
    import numpy as np
    from scipy.io import wavfile
    from scipy.signal import resample
    from os import getpid

    from Room import Room
    from beamforming import Beamformer, MicrophoneArray
    from trinicon import trinicon

    from utilities import normalize, to_16b, highpass
    from phat import time_align
    from metrics import snr, pesq
    
    # number of number of sources
    n_sources = np.arange(1,12)
    S = n_sources.shape[0]

    # we the speech samples used
    speech_sample1 = 'samples/fq_sample1_8000.wav'
    speech_sample2 = 'samples/fq_sample2_8000.wav'

    # Some simulation parameters
    Fs = 8000
    t0 = 1./(Fs*np.pi*1e-2)  # starting time function of sinc decay in RIR response
    absorption = 0.90
    max_order_sim = 10
    SNR_at_mic = 20          # SNR at center of microphone array in dB

    # Room 1 : Shoe box
    room_dim = [4, 6]

    # microphone array design parameters
    mic1 = [2, 1.5]         # position
    M = 8                   # number of microphones
    d = 0.08                # distance between microphones
    phi = 0.                # angle from horizontal
    shape = 'Linear'        # array shape

    # create a microphone array
    if shape is 'Circular':
        mics = Beamformer.circular2D(Fs, mic1, M, phi, d*M/(2*np.pi)) 
    else:
        mics = Beamformer.linear2D(Fs, mic1, M, phi, d) 

    # create a single reference mic at center of array
    ref_mic = MicrophoneArray(mics.center, Fs)

    # define the array processing type
    L = 4096                # frame length
    hop = 2048              # hop between frames
    zp = 2048               # zero padding (front + back)
    mics.setProcessing('FrequencyDomain', L, hop, zp, zp)

    # data receptacles
    beamformer_names = ['Rake-DS',
                        'Rake-MaxSINR',
                        'Rake-MaxUDR']
    bf_weights_fun   = [mics.rakeDelayAndSumWeights,
                        mics.rakeMaxSINRWeights,
                        mics.rakeMaxUDRWeights]
    bf_fnames = ['1','2','3']
    NBF = len(beamformer_names)

    # receptacle arrays
    pesq_input = np.zeros(2)
    pesq_trinicon = np.zeros((2,2))
    pesq_bf = np.zeros((2,NBF,S))
    isinr = 0
    osinr_trinicon = np.zeros(2)
    osinr_bf = np.zeros((NBF,S))

    # since we run multiple thread, we need to uniquely identify filenames
    pid = str(getpid())

    file_ref  = 'output_samples/fqref' + pid + '.wav'
    file_suffix = '-' + pid + '.wav'
    files_tri = ['output_samples/fqt' + str(i+1) + file_suffix for i in xrange(2)]
    files_bf = ['output_samples/fq' + str(i+1) + file_suffix for i in xrange(NBF)]
    file_raw  = 'output_samples/fqraw' + pid + '.wav'

    # Read the two speech samples used
    rate, good_signal = wavfile.read(speech_sample1)
    good_signal = np.array(good_signal, dtype=float)
    good_signal = normalize(good_signal)
    good_signal = highpass(good_signal, rate)
    good_len = good_signal.shape[0]/float(Fs)

    rate, bad_signal = wavfile.read(speech_sample2)
    bad_signal = np.array(bad_signal, dtype=float)
    bad_signal = normalize(bad_signal)
    bad_signal = highpass(bad_signal, rate)
    bad_len = bad_signal.shape[0]/float(Fs)

    # variance of good signal
    good_sigma2 = np.mean(good_signal**2)

    # normalize interference signal to have equal power with desired signal
    bad_signal *= good_sigma2/np.mean(bad_signal**2)

    # pick good source position at random
    good_distance = np.linalg.norm(mics.center[:,0] - np.array(good_source))
    
    # pick bad source position at random
    bad_distance = np.linalg.norm(mics.center[:,0] - np.array(bad_source))

    if good_len > bad_len:
        good_delay = 0
        bad_delay = (good_len - bad_len)/2.
    else:
        bad_delay = 0
        good_delay = (bad_len - good_len)/2.

    # compute the noise variance at center of array wrt good signal and SNR
    sigma2_n = good_sigma2/(4*np.pi*good_distance)**2/10**(SNR_at_mic/10)

    # create the reference room for freespace, noisless, no interference simulation
    ref_room = Room.shoeBox2D(
        [0,0],
        room_dim,
        Fs,
        t0 = t0,
        max_order=0,
        absorption=absorption,
        sigma2_awgn=0.)
    ref_room.addSource(good_source, signal=good_signal, delay=good_delay)
    ref_room.addMicrophoneArray(ref_mic)
    ref_room.compute_RIR()
    ref_room.simulate()
    reference = ref_mic.signals[0]
    reference_n = normalize(reference)

    # save the reference desired signal
    wavfile.write(file_ref, Fs, to_16b(reference_n))

    # create the 'real' room with sources and mics
    room1 = Room.shoeBox2D(
        [0,0],
        room_dim,
        Fs,
        t0 = t0,
        max_order=max_order_sim,
        absorption=absorption,
        sigma2_awgn=sigma2_n)

    # add sources to room
    room1.addSource(good_source, signal=good_signal, delay=good_delay)
    room1.addSource(bad_source, signal=bad_signal, delay=bad_delay)

    # Record first the degraded signal at reference mic (center of array)
    room1.addMicrophoneArray(ref_mic)
    room1.compute_RIR()
    room1.simulate()
    raw_n = normalize(highpass(ref_mic.signals[0], Fs))

    # save degraded reference signal
    wavfile.write(file_raw, Fs, to_16b(raw_n))

    # Compute PESQ and SINR of raw degraded reference signal
    isinr = snr(reference_n, raw_n[:reference_n.shape[0]])
    pesq_input[:] = pesq(file_ref, file_raw, Fs=Fs).T
        
    # Now record input of microphone array
    room1.addMicrophoneArray(mics)
    room1.compute_RIR()
    room1.simulate()

    # Run the Trinicon algorithm
    double_sig = mics.signals.copy()
    for i in xrange(2):
        double_sig = np.concatenate((double_sig, mics.signals), axis=1)
    sig_len = mics.signals.shape[1]
    output_trinicon = trinicon(double_sig)[:,-sig_len:]

    # normalize time-align and save to file
    output_tri1 = normalize(highpass(output_trinicon[0,:], Fs))
    output_tri1 = time_align(reference_n, output_tri1)
    wavfile.write(files_tri[0], Fs, to_16b(output_tri1))
    output_tri2 = normalize(highpass(output_trinicon[1,:], Fs))
    output_tri2 = time_align(reference_n, output_tri2)
    wavfile.write(files_tri[1], Fs, to_16b(output_tri2))

    # evaluate
    # Measure PESQ and SINR for both output signals, we'll sort out later
    pesq_trinicon = pesq(file_ref, files_tri, Fs=Fs)
    osinr_trinicon[0] = snr(reference_n, output_tri1)
    osinr_trinicon[1] = snr(reference_n, output_tri2)

    # Run all the beamformers
    for k,s in enumerate(n_sources):

        ''' 
        BEAMFORMING PART
        '''
        # Extract image sources locations and create noise covariance matrix
        good_sources = room1.sources[0].getImages(n_nearest=s, 
                                                    ref_point=mics.center)
        bad_sources = room1.sources[1].getImages(n_nearest=s,
                                                    ref_point=mics.center)
        Rn = sigma2_n*np.eye(mics.M)

        # run for all beamformers considered
        for i, bfr in enumerate(beamformer_names):

            # compute the beamforming weights
            bf_weights_fun[i](good_sources, bad_sources,
                                    R_n = sigma2_n*np.eye(mics.M), 
                                    attn=True, ff=False)

            output = mics.process()
            output = normalize(highpass(output, Fs))
            output = time_align(reference_n, output)

            # save files for PESQ evaluation
            wavfile.write(files_bf[i], Fs, to_16b(output))

            # compute output SINR
            osinr_bf[i,k] = snr(reference_n, output)

            # compute PESQ
            pesq_bf[:,i,k] = pesq(file_ref, files_bf[i], Fs=Fs).T

            # end of beamformers loop

        # end of number of sources loop

    return pesq_input, pesq_trinicon, pesq_bf, isinr, osinr_trinicon, osinr_bf
Exemple #46
0
#!/usr/bin/env python
import sys
from Game import Game
from Inventory import Inventory
from Room import Room 
from Object import Object
from Action import Action
from Person import Person
from Topic import Topic
from Trigger import Trigger
#TODO: Do the hula hula

Cellar = Room("the Cellar")
CellarDefault = Object("default",[Action("look","You stand in a dark cellar. There is a [window] on the southern wall and a door to the [east]")])
CellarDefault.actions["look"].addTrigger(Trigger('showObject',["cellar","window"]))
Cellar.addObject(CellarDefault)
CellarWindow = Object("window",[Action("look","The window has [bars], so you are unable to look out. The only thing you see are mountains in the distance.")])
CellarWindow.actions["look"].addTrigger(Trigger('showObject',["cellar","bars"]))
Cellar.addObject(CellarWindow)
CellarBars = Object("bars",[Action("look","The bars are made of steel and look very sturdy."),Action("push","Who do you think you are, Superman?")])
Cellar.addObject(CellarBars)
Cellar.exits["east"] = "restroom"

##ADDING SOME DUDE###



Restroom = Room("the Restroom")
RestroomDefault = Object("default",[Action("look","You find yourself in a very small restroom. You notice a bad smell coming from the [toilet]. There is also a worn [sink].")])
RestroomDefault.actions["look"].addTrigger(Trigger("showObject",["restroom","sink"]))
RestroomDefault.actions["look"].addTrigger(Trigger("showObject",["restroom","toilet"]))
Exemple #47
0
from Room import Room
from Table import Table

room = Room();
firstTable = Table("table one")
firstTable.seatPlayer("James")
firstTable.seatPlayer("Brian")
firstTable.seatPlayer("Joel")
room.addTable(firstTable)
secondTable = Table("table two")
secondTable.seatPlayer("Sarah")
secondTable.seatPlayer("William")
secondTable.seatPlayer("Lauren")
secondTable.seatPlayer("Alyssa")
room.addTable(secondTable)

room.printTables()
Exemple #48
0
    def load(self):
        '''
        Loads a map from the key point. This is dynamic, so map dimensions are determined by
        whether a room loads successfully or not
        '''

        #yup, copy paste. That's right. COPY FRIGGEN PASTE!!
        roomX = 1
        roomY = 1
        roomZ = 1

        tempX = self.originCoord.x

        columnEnd = False
        levelEnd = False
        rowEnd = False

        columns = 1
        columnEnd = False
        while not (columnEnd and levelEnd and rowEnd):
            tempY = self.originCoord.y
            roomY = 1

             # used for determining end conditions
            levelEnd = False
            levels = 1
            while not (levelEnd and rowEnd):
                tempZ = self.originCoord.z
                rZ = 1
                rowEnd = False

                rows = 1
                while not (rowEnd):

                    roomCoord = Coord(rows, levels, columns)
                    mapCoord = roomCoord.addCoord(self.originCoord)
                    mapCoord.y = tempY - 12
                    roomOriginCoord = Coord(tempX, tempY, tempZ)

                    room = Room(roomCoord, roomOriginCoord, self.level, mapCoord)

                    if (room.load() == True):
                        self.addRoom(room, roomX, roomY, roomZ)
                        tempZ -= Room.WIDTH + 1
                        roomZ += 1
                        rows += 1
                        #This is the end condition determiner. The process will run until
                        #this flag is hit twice in a row. Every time a room is found we reset this
                        columnEndOnce = False
                        #we also have to use this with the levels
                        levelEndOnce = False
                    else:
                        #fun with ifs, this determines when to stop reading the map!
                        logging.debug("JEFF - LoadCoords: %d %d %d", roomX, roomY, roomZ)
                        if (roomZ > 1):
                            logging.debug("JEFF - rowEnd")
                            rowEnd = True

                        if (roomY > 1):
                            if (levelEndOnce == True):
                                logging.debug("JEFF - LevelEnd")
                                levelEnd = True
                                rowEnd = True
                            else:
                                levelEndOnce = True


                        if (roomX > 1 and not (rowEnd and levelEnd)):
                            logging.debug("JEFF - columnEnd")
                            if (columnEndOnce == True):
                                columnEnd = True
                                levelEnd = True
                                rowEnd = True
                            else:
                                columnEndOnce = True



                tempY += self.LEVEL_HEIGHT
                roomY += 1
            tempX += Room.LENGTH + 1
            roomX += 1
def choice():
	global auto_feed
	global people
	global rooms
	global player
	a = input("Choose what to do: ")
	# From here on out, a.split()[0] is used to cut out the first word of the
	# input and compare it individually.
	if len(a) > 0:
		# Allows player to build new rooms. Checks if player has components to
		# build room.
		if a.split()[0] == "build":
			potential_room = ''
			for x in a.split()[1:]:
				if len(potential_room) == 0:
					potential_room = x
				else:
					potential_room = potential_room + " " + x
			#print_line("The potential room is",potential_room)
			if len(a.split()) < 2:
				print_line("You have to input 2 or more words to build a room.")
			elif not check_room(potential_room):
				print_line("Checking for room:", potential_room)
				print_line("This room doesn't exist.")
			elif check_built_room(potential_room):
				print_line("You've already built this room.")
			else:
				room = Room(potential_room,player)
				checked = []  # Stores components already checked. Useful. If there's 5 pieces of wood in the components list, the loop is only run once, instead of 5 times
				can_craft = 1
				for component in room.components:
					if component not in checked:  # Only runs check if item hasn't been encountered before
						if room.count_component(component) > count_item(
								component, "player"):  # If player doesn't have enough
							print_line(
								"You don't have enough",
								component,
								"to build",
								potential_room)
							can_craft = 0
							# break #I don't break so the users will see
							# everything they don't have.
						checked.append(component)
				if can_craft == 1:
					print_line("You have built a", a.split()[1])
					player=player
					build(potential_room,player)

		elif a.split()[0] == "craft":
			# Checks to see if crafting possible.
			if a.split()[1] not in all_items:
				print_line("Invalid item. Try again.")
			else:
				can_craft = 1
				# Creates an instance of the item, so it's attributes can be
				# fetched.
				actual_item = Item(a.split()[1])
				if len(actual_item.components) == 0:
					print_line("This is a basic item and so cannot be crafted.")
				else:
					checked = []
					for component in actual_item.components:
						if component not in checked:
							number_available = count_item(component, "player")
							number_needed = actual_item.count_component(
								component)
							if number_needed > number_available:
								print_line(
									"You don't have enough",
									component,
									"to craft",
									a.split()[1])
								can_craft = 0
							checked.append(component)
					if can_craft == 1:
						print_line("You have crafted a", a.split()[1])
						craft(a.split()[1])
Exemple #50
0
# Author: Hugo P.
# Project: https://github.com/HugoCMU/SolarTree
# Description: Program reads in Room object and clusters/connects areas in the room

from Room import Room
from Move import Move
from Area import Area

# Initialize room object
room = Room()

# Read in room object from text file
room.read_from_text('room2015-11-30.txt')

# Perform knn clustering on areas
room.cluster()

# Connect remaining areas with moves
room.connect_areas()
Exemple #51
0
def chat_stream(_id):
    try:
        Room.get(_id)
    except:
        return jsonify(error='No room with that name exists'), 400
    return Response(stream(_id), mimetype="text/event-stream")
Exemple #52
0
    def _grow_room( self, seed, direction, growing ):
        """grow new room, maintaining contraints
           * each room can have at most one neighbor of each color
           * new rooms should connect to existing neighbors unless that
             would violate the color constraint, or they fail a random
             connectedness test
           * to keep from just filling all available space, randomly fail
             to create new rooms with increasing probability as more
             rooms are added, with initial probability given by
             completeness arg
        """
        # fail randomly to create new rooms increasingly often as number
        # of rooms approaches maximum
        if randrange( 0, 90 ) < self._fullness() - self.completeness:
            return
        
        # get new room's location
        delta = self.DIRECTIONS[direction]
        loc = tuple([ seed.loc[i] + delta[i] for i in range(2) ])

        # if new location is not in bounds return
        if( loc[0] < 0 or loc[0] >= self.columns
            or loc[1] < 0 or loc[1] >= self.rows ):
            return

        # if there is already a room in new location return
        if self.rooms.has_key( loc ):
            return
        
        # get seed room's free color list, return if len is 0
        free_colors = seed.get_free_colors()
        if len( free_colors ) < 1:
            return

        # get new room's neighbors
        neighbor_colors = set([ seed.color ]) # no 2 neighbors of same color
        neighbors = {}
        neighbor_dirs = [0, 1, 2, 3] # check in each direction
        neighbor_dirs.remove( (direction + 2) % 4 ) # skip seed room
        while neighbor_dirs:

            # process neighbor dirs in random order
            neighbor_dir = neighbor_dirs.pop( randrange(0, len(neighbor_dirs)) )

            # calculate location from direction and seed location
            neighbor_delta = self.DIRECTIONS[neighbor_dir]
            neighbor_loc = tuple([ loc[i] + neighbor_delta[i]
                                  for i in range(2) ])
            if self.rooms.has_key( neighbor_loc ):
                neighbor = self.rooms[neighbor_loc]

                # get intersection of free colors sets
                neighbor_free_colors = neighbor.get_free_colors()
                combined_colors = set(free_colors) & set(neighbor_free_colors)

                # if intersection of current free color set and neighbor's free
                # color set is not empty and there is not already a room of
                # this color connected, test if we should randomly fail to
                # connect this room, otherwise add it to neighbor set
                if( len( combined_colors ) > 0
                    and neighbor.color not in neighbor_colors
                    and randrange(0, 100) > 99 - self.connectedness ):
                    neighbors[neighbor_dir] = neighbor
                    free_colors = list( combined_colors )
                    neighbor_colors.add( neighbor.color )

        # pick color from free colors
        color = free_colors.pop( randrange(0, len(free_colors)) )
        
        # make room
        room = Room( maze=self, loc=loc, color=color, size=self.room_size )
        self.rooms[loc] = room
        growing.add( room )

        # connect seed and neighbors
        seed.connected[direction] = room
        room.connected[(direction + 2) % 4] = seed
        for neighbor_dir, neighbor in neighbors.iteritems():
            room.connected[neighbor_dir] = neighbor
            neighbor.connected[(neighbor_dir + 2) % 4] = room
Exemple #53
0
def chat_list():
    return jsonify(rooms=Room.getall())
Exemple #54
0
class Config:
    DEBUG = True
    SECRET_KEY = 'abc'
    MODULE_PATH = './modules/'
    LOG_DIR = './logs/'

app = Flask(__name__)
app.config.from_object('mercury.Config')
app.config.from_envvar('MERCURY_CONFIG_PATH')
Module.PATH = app.config['MODULE_PATH']

pool = redis.ConnectionPool()
Room.REDIS = redis.Redis(connection_pool=pool)
User.REDIS = redis.Redis(connection_pool=pool)

for r in Room.getall():
    l = logging.getLogger(r.name)
    h = logging.FileHandler(os.path.join(app.config['LOG_DIR'], r.name + '.log'))
    l.setLevel(logging.INFO)
    l.addHandler(h)


login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.login_message = u'Please log in to access this page.'


@login_manager.user_loader
def load_user(username):
    try:
        return User(username)
Exemple #55
0
class Fey ( ):
    def __init__ ( self ):
        """Sets game instance fields and sets RUNNING to True. No return."""
        
        if(DEBUG):print("Initializing");
        self.RUNNING = True
        self.DISPLAY_SURF = None
        self.SIZE = self.WIDTH, self.HEIGHT = 800, 640
        
    def start ( self ):
        """Creates all game object instances. No return.
        
        This is where specific Rooms, Items, Cotrollers, and pygame essentials are
        created.
        
        """
        if(DEBUG):print("Starting");
        pygame.init()
        #Create display
        self.DISPLAY_SURF = pygame.display.set_mode(self.SIZE)
        self.DISPLAY_SURF.fill((0,0,0))
        #Create Pygame objects here
        self.clock = pygame.time.Clock()
        #Player
        self.player = Character(initial_position = [40,600])
        #Veiw Manager
        self.veiwMan = ViewManager([255,255,255], [5,5], [self.WIDTH-10, self.HEIGHT-10], self.player) #Puts a white VeiwManager on screen
        #Control Manager
        self.conMan = ControlManager()
        self.conMan.setAvatar(self.player)
        #Creating Rooms
        greenRoom = pygame.sprite.Sprite()
        greenRoom.image = pygame.Surface([1000, 640])
        greenRoom.rect = greenRoom.image.get_rect()
        greenRoom.image.fill([0,255,0])
        self.room1 = Room(greenRoom, self.player) #Sets background to greenRoom and avatar to self.player
        
        grayRoom = pygame.sprite.Sprite()
        grayRoom.image = pygame.Surface([1000, 640])
        grayRoom.rect = grayRoom.image.get_rect()
        grayRoom.image.fill([100,100,100])
        self.room2 = Room(grayRoom, self.player)
        
        #Creating items
        self.box = Item([400, 600])
        self.box.setTouchEvent(pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room2}))
        self.box2 = Item([200, 600])
        self.box2.setInteractEvent(pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room1}))
        self.room1.addObject(self.box)
        self.room2.addObject(self.box2)
        self.itemGroup = pygame.sprite.RenderPlain(self.box,self.box2)
        
        #Making Text
        #This is not critical code
        if(pygame.font.get_init):
            hello = pygame.font.Font(None,64)
            hello = hello.render("Press Space", False, [0,0,0])
            x,y = self.veiwMan.rect.center
            x = x - (hello.get_width()/2)
            y = y - (hello.get_height()/2)
            self.veiwMan.image.blit(hello, [x,y])
        
        pygame.display.flip()
        self.RUNNING = True


    def handleEvent(self, event):
        """Pipes given event to relivant reciver. No return.
        
        This method handles event calls and sorts them either to the main game instance,
        to the game's ControlManager, or the game's VeiwManager. It may be better to put
        this functionality into a standalone class.
        
        """
        if(DEBUG):print("Event check");
        if event.type == pygame.QUIT:
            self.RUNNING = False
        #Events are handled here
        if event.type == pygame.KEYDOWN and event.key == K_ESCAPE:
            self.RUNNING = False
        elif event.type == pygame.KEYDOWN and event.key == K_SPACE:
            callChange = pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room1})
            pygame.event.post(callChange)
        elif event.type == pygame.KEYDOWN and event.key == K_DOWN:
            callChange = pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room2})
            pygame.event.post(callChange)
        elif(event.type == Events.ROOM_CHANGE):
            self.veiwMan.setCurrentView(event.room)
        else:
            self.conMan.handle(event)

    def update(self):
        """Main update function. Should be called every cicle. No return.
        
        This function calls the update functions of all active game objects.
        
        """
        if(DEBUG):print("Updating");
        #Objects will update themselves (movement, calculation, etc)
        self.veiwMan.update()

    def render(self):
        """Draws the final frame onto the display. No return.
        
        This function calls the ViewManager to blit (draw) all active objects 
        to itself, then blits itself onto the main display, and then calls the
        display to flip the changes to the screen.
        
        """
        if(DEBUG):print("Rendering");
        #ViewManager draws apropriate surfaces to itself
        self.veiwMan.drawView()
        self.DISPLAY_SURF.blit(self.veiwMan.image, self.veiwMan.rect) #Dependant on VeiwManager
        pygame.display.flip()
        pass

    def cleanup(self):
        """Runs the pygame.quit() function, which closes the display safely."""
        if(DEBUG):print("Cleaning up");
        pygame.quit()

    def run(self):
        """Starts the game's main loop."""
        if(DEBUG):print("Attempting to run");
        if self.start() == False:
            self.RUNNING = False

        if(DEBUG):print("Running");
        while(self.RUNNING):
            self.clock.tick(30)
            for event in pygame.event.get():
                self.handleEvent(event)
            self.update()
            self.render()
        self.cleanup()