Esempio n. 1
0
def iniciarConjuntoPlayers(numIndividuos,
                           lado,
                           interface,
                           drawNeuralNetwork=False):

    # Estamos trabalhando com interface gráfica?
    if interface == True:
        game_area_ = GAME_AREA
    else:
        game_area_ = False

    playerSet = []
    for i in range(numIndividuos):

        if lado == "direita":
            player = Player([WIDTH - 150, 100], colors.BLACK, player_type,
                            WIDTH, GAME_AREA_HEIGHT, ARCHITECTURE, game_area_,
                            drawNeuralNetwork)
        elif lado == "esquerda":
            player = Player([150, 100], colors.RED, "bot_ball_follow", WIDTH,
                            GAME_AREA_HEIGHT, ARCHITECTURE, game_area_,
                            drawNeuralNetwork)
        else:
            print(
                "Qual lado você quer que o player fique? Corrija esta informação"
            )
            exit()

        playerSet.append(player)
    return playerSet
Esempio n. 2
0
    def __init__(self):

        self.player1 = Player(1, 'rouge')
        self.player2 = Player(2, 'vert')

        # Sauvegarde des points powered
        self.moves = []
        self.playable_points = []
        self.init_game()
Esempio n. 3
0
    def setUpClass(cls):
        cls.player = Player("Theo")
        cls.player2 = Player("Theo")
        cls.deck = []
        cls.suits = ['Clubs', 'Spades', 'Diamonds', 'Hearts']

        for suit in cls.suits:
            for rank in range(1, 14):
                cls.deck.append((suit, rank))
    def __init__(self, number_of_enemies_to_kill=5):
        self.number_of_enemies_to_kill = number_of_enemies_to_kill

        self.action_log = ActionLog()

        player_name = input("Player Name: ").strip()
        self.player = Player(self.action_log, player_name)

        # Add additional enemies here
        self.enemies = [Chicken, Rabbit]

        self.current_enemy = None
Esempio n. 5
0
def get_player_data():

    player_filename = 'game_summary_by_player.csv'
    data_dir = os.getcwd() + '/data/external'
    player_path = os.path.join(data_dir, player_filename)
    output_path = os.path.join(data_dir, 'player_metadata.csv')

    player_game_df = pd.read_csv(player_path)
    players_df = player_game_df[["player_link",
                                 "player_name"]].drop_duplicates()

    if os.path.isfile(player_path):
        addtl_rows_flg = True
        player_metadata_df = pd.read_csv(output_path)
        player_metadata_df = player_metadata_df.drop_duplicates()
    else:
        addtl_rows_flg = False
        player_metadata_df = pd.DataFrame()

    if addtl_rows_flg == True:
        existing_players = list(player_metadata_df["player_link"].unique())

        players_df = players_df[~players_df["player_link"].
                                isin(existing_players)]
        print(
            "number of players already scraped: {} / length of remaining df: {}"
            .format(len(existing_players), len(players_df)))
    output_rows = []
    for idx, row in players_df.iterrows():
        name = row['player_name']
        link = row['player_link']
        print("{}: {} - {}".format(idx, name, link))
        player = Player(name, link)

        #print("{}: {} - {}".format(idx, player.name, player.full_player_url))
        player_dict = player.get_player_data()
        dict_to_csv(player_dict, data_dir, 'player_metadata')
        output_rows.append(player_dict)

    #output_df = pd.DataFrame(output_rows)
    #output_path = os.path.join(data_dir, 'player_metadata.csv' )

    #output_df = output_df[["player_link", "player_name", "position", "draft_pick" ,"height", "weight", "height", "birthdate", "forty_yd", "combine_bench", "combine_broad_jump", "combine_cone", "combine_shuttle", "combine_vert", "combine_year"]]

    #output_df.to_csv(output_path, index = False)
    return
Esempio n. 6
0
	def __setup(self):
		name = ""
		while len(name) == 0:
			name = input("What is your name ? ")

		print("Who are you?")
		print("I'm a...")

		race = 0
		while True:
			print("1) Human")
			print("2) Elf")
			print("3) Dwarf")
			print("4) Halfling")

			try:
				race = int(input("? "))
				if race < 1 or race > 4:
					raise ValueError
			except ValueError:
				print("Not a valid number!")
				continue
			else:
				break 

		cls = 0
		while True:
			print("1) Fighter")
			print("2) Rogue")
			print("3) Mage")
			print("4) Cleric")

			try:
				cls = int(input("? "))
				if cls < 1 or cls > 4:
					raise ValueError
			except ValueError:
				print("Not a valid number!")
				continue
			else:
				break 

		self.player = Player(name, "", Dice.roll(6, 3), Dice.roll(6, 3), Dice.roll(6, 3), race, cls)

		# Starting gold
		if cls == 1:
			self.player.currency("Gold", 150)
		elif cls == 2:
			self.player.currency("Gold", 125)
		elif cls == 3:
			self.player.currency("Gold", 75)
		elif cls == 4:
			self.player.currency("Gold", 120)

		bag = self.__gear["backpack"]
		self.player.bag.add_item(bag, 1)

		self.map = Map()
Esempio n. 7
0
    def __createPlayers(self):
        players = []
        playerCount = 3
        playerID = 0

        while playerCount > 0:
            player = Player(playerID)
            players.append(player)
            playerCount -= 1
            playerID += 1

        return players
 def initSimulation(self):
     self.initializeFunctions()
     # Initialize collision handlers
     self.initializeCollision()
     # Generate terrain information
     self.initializeScene()
     # Generate interactive objects
     self.player = Player(self, self.posX, self.posY)
     self.tsunamiTime = 150 # time for tsunami to hit the coast
     self.tsunami = Water(self)
     # Initialize screen on text
     self.put2D()
Esempio n. 9
0
def get_player_stats_rows(snap_rows, team):
    game_player_stats = []
    for tr in snap_rows:
        player_name = tr.th.a.string if tr.th.a is not None else None
        if player_name is None:
            continue

        player_link = tr.th.a['href']
        position = tr.find("td", {"data-stat": "pos"}).string
        player_game = Player(player_name, player_link, team, position)

        player_stats_dict = player_game.get_player_summary()
        num_snaps, perc_snaps = player_game.get_snaps(tr)
        player_stats_dict["perc_snaps"] = float(perc_snaps)
        player_stats_dict["snaps"] = float(num_snaps)

        pos_stats_flg = player_game.get_pos_stats_flg(tr)
        if pos_stats_flg == True:

            positional_player = player_game.player_class(player_game)
            pos_player_stats = positional_player.get_positional_stats(
                player_game)
            player_stats_dict.update(pos_player_stats)
        game_player_stats.append(player_stats_dict)

    return game_player_stats
Esempio n. 10
0
def choose_players():
    '''Randomly select two players and return their data in the form of a Player class instance.'''
    #get existing player ids
    player_ids = redis_host.keys()
    max_index = len(player_ids) - 1
    # choose two random players
    i = random.randint(0,max_index)
    j = random.randint(0,max_index)

    decoder = json.JSONDecoder()
    # get the data for the two chosen random players
    player_1_data_raw = decoder.raw_decode(redis_host.get(str(player_ids[i])))
    player_2_data_raw = decoder.raw_decode(redis_host.get(str(player_ids[j])))

    player_1_data = json.loads(player_1_data_raw[0])
    player_2_data = json.loads(player_2_data_raw[0])

    # create data structures for the players for easy access.
    player_1 = Player(player_1_data)
    player_2 = Player(player_2_data)

    return player_1, player_2
Esempio n. 11
0
def generatePlayerObjectFromFile(filePath, playerNumber):
    headerRow = True
    CSV_Data = readListFromCSV(filePath)
    playerObject = Player(playerNumber)

    for line in CSV_Data:
        if headerRow:
            headerRow = False
            continue
        # print(line)
        (timestamp, episodeNumber, roundData, roundOut, finalScore) = isolateCellsWithRoundDataAggregated(line)
        roundObjectList = generateRoundObjects(roundData, episodeNumber)
        playerObject.episodeList.append(Episode(len(roundObjectList), episodeNumber, finalScore, roundObjectList))
    return playerObject
Esempio n. 12
0
def initialize_players():
    """ Prompts players for party size and player names.
    """
    system('cls')
    players = []
    playerCount = input('Enter the numbers of players: ')

    for playerN in range(int(playerCount)):
        playerName = input(f'Enter the name for player {playerN + 1}: ')
        players.append(Player(playerName))

    print("Let's get started!")

    return players
class Game:
    class PlayerDiedException(Exception):
        pass

    def __init__(self, number_of_enemies_to_kill=5):
        self.number_of_enemies_to_kill = number_of_enemies_to_kill

        self.action_log = ActionLog()

        player_name = input("Player Name: ").strip()
        self.player = Player(self.action_log, player_name)

        # Add additional enemies here
        self.enemies = [Chicken, Rabbit]

        self.current_enemy = None

    def run(self):
        try:
            for i in range(self.number_of_enemies_to_kill):
                self.fight()
        except self.PlayerDiedException:
            pass

        self.action_log.write_action_log_to_file()

    def fight(self):
        EnemyClass = self.get_random_enemy()
        self.current_enemy = EnemyClass(self.action_log)

        self.current_enemy.display_enemy_encounter_message()

        self.display_player_and_enemy_info()

        while self.current_enemy.current_health > 0 and self.player.current_health > 0:
            self.player.take_turn(self.current_enemy)
            self.current_enemy.take_turn(self.player)

            self.display_player_and_enemy_info()

        if self.player.current_health <= 0:
            # Adds action to log.txt file
            self.action_log.add_to_action_list("You died!" + "\n")
            raise self.PlayerDiedException("You died!")

        self.player.level_up()
        self.player.rest()

    def get_random_enemy(self):
        return choice(self.enemies)

    def display_player_and_enemy_info(self):
        for line in get_player_and_enemy_info_box_lines(
                self.player, self.current_enemy):
            print(line)

        print()
Esempio n. 14
0
def check():
    """Settings"""
    """====================================================================="""
    new_dir = '../../../Data/invivo_converse/'
    setname = 'test1'
    filenum = 700  #less than 2400 if setname=='train', else less than 800
    """====================================================================="""

    startnum = {'train': 0, 'val': 2400, 'test1': 3200, 'test2': 4000}[setname]
    Dname,Sname,Lname=['Patch','S_est_f','L_est_f'] if setname=='test2'\
                    else ['patch_180','patch_180','patch_180']
    filenum = filenum + startnum
    player = Player()

    D = loadmat('%s/D_data/%s/D%d.mat' % (new_dir, setname, filenum))[Dname]
    S = loadmat('%s/fista/%s/S_fista%d.mat' %
                (new_dir, setname, filenum))[Sname]
    L = loadmat('%s/fista/%s/L_fista%d.mat' %
                (new_dir, setname, filenum))[Lname]
    D = D.reshape([32, 32, 20])
    S = S.reshape([32, 32, 20])
    L = L.reshape([32, 32, 20])

    player.play([D, S, L])
Esempio n. 15
0
    def what_to_create(self, tile, row, col):
        if tile == 'P':
            self.player = Player(self, col, row)
        if tile == 'W':
            Wall(self, col, row)

        if tile == '1':
            Food(self, col, row)

        if tile == 'G':
            Ghost(self, col, row)

        if tile == '2':
            PowerUp(self, col, row)
        if tile == '3':
            CrossRoad(self, col, row)
            Ghost(self, col, row)
Esempio n. 16
0
    def play(self):
        card = Card(0, 0, 100, 175)
        deck = Deck()
        dealer = Dealer()
        player = Player()

        isGame = False

        i = 0
        while True:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:

                    if event.key == pygame.K_a:
                        pass

                    if event.key == pygame.K_s:
                        deck.shuffle()
                        isGame = True

                    if event.key == pygame.K_SPACE:
                        if i < 52:
                            i = i + 1

                    if event.key == pygame.K_ESCAPE:
                        sys.exit()

            self.screen.fill((0, 0, 0))
            self.screen.blit(self.image, self.rect)

            deck.deal(self.screen, dealer, player)

            pygame.display.flip()

            if dealer.get_hand >= player.get_hand:
                msg = "Dealer Wins"
            else:
                msg = "player wins"
            if isGame:
                Tk().wm_withdraw()  # to hide the main window
                messagebox.showinfo("Game", msg)
                isGame = False
Esempio n. 17
0
device = 'cpu'
if mfile[-3:] == 'pkl':
    model = ResNet3dC(gpu)
    state_dict = torch.load(mfile, map_location=device)
    model.load_state_dict(state_dict)
else:
    model = torch.load(mfile)

#Processing
with torch.no_grad():
    data = np.load(data_dir)
    Sum, Bubbles = data['arr_0'], data['arr_1']
    [Sum] = convert.np2torch([Sum], [form_in])
    pred = model(Sum)
[predmv, Sum] = convert.torch2np([pred, Sum], [form_out, form_out])

#Display
plt.close('all')
player = Player()
player.play([Sum, predmv, Bubbles], note=note, cmap=cmap)

#Save gif
if saveGif:
    mat2gif([Sum, predmv, Bubbles],
            save_gif_dir,
            note=note,
            cmap=cmap,
            tit=['Input', 'Prediction', 'Ground Truth'])
#Save matrix
if saveMat:
    savemat(save_mat_dir, {'D': Sum, 'S': Bubbles, 'Sp': predmv})
Esempio n. 18
0
list_of_container_objects = Factory.container_factory(items)
containers = ContainerManager(list_of_container_objects)

list_of_investigatable_objects = Factory.investigatable_factory()
investigatables = InvestigatableManager(list_of_investigatable_objects)

list_of_character_objects = Factory.character_factory()
characters = CharacterManager(list_of_character_objects)

list_of_location_objects = Factory.location_factory(characters, items,
                                                    containers,
                                                    investigatables)
locations = LocationManager(list_of_location_objects)

player = Player("Detective Joe Smith")

time = Time()
narrative = Narrative(time, disp, locations, player, items, characters)
from events import add_events
add_events(narrative)


def main():  #KYLE

    # for line in logo:
    #     disp.type(line,0.000001)

    # get_location returns a location object from the name of a location
    # In this case, we are starting at scotland yard, so we get the scotland yard location
    starting_location = locations.get_location("Scotland Yard")
Esempio n. 19
0
cmap='hot'
"""========================================================================="""

#load model
net=ResNet3dC(gpu)

#device='cuda:0' if torch.cuda.is_available() else 'cpu'
device='cpu'
if mfile[-3:]=='pkl':
    state_dict=torch.load(mfile,map_location=device)
    #state_dict=delitems(state_dict)
    net.load_state_dict(state_dict)
else:
    net=torch.load(mfile)

#process        
process_dataset(net,data_dir,setname,patch_dir)
#display
if display:
    startnum={'train':0,'val':2400,'test1':3200,'test2':4000}[setname]
    Dname='Patch' if setname=='test2' else 'patch_180'
    D=loadmat('%s/D_data/%s/D%d.mat'%(data_dir,setname,startnum))[Dname]
    Si=loadmat('%s/data0.mat'%(patch_dir))['data']
    D=D.reshape([32,32,20])
    Si=Si.reshape([32,32,20])
    
    player=Player()
    player.play([D,Si],tit=['Input','Prediction'],
                cmap=cmap,note=note,minDB=minDB)
    
Esempio n. 20
0
    state_dict = torch.load(mfile, map_location=device)
    #state_dict=delitems(state_dict)
    net.load_state_dict(state_dict)
else:
    net = torch.load(mfile)

#Processing
D, Sp = process_patch(net, data_dir, arange)
brow, erow, bcol, ecol, bt, et = arange
if Sfile[-3:] == 'mat':
    S = loadmat(Sfile)['vid'][brow:erow, bcol:ecol, bt:et]
else:
    S = np.load(Sfile)['arr_0'][brow:erow, bcol:ecol, bt:et]

#Display
player = Player()
player.play([D, Sp, S],
            cmap=cmap,
            note=note,
            tit=['Input', 'Prediction', 'Fista'])

#save as gif
if saveGif:
    mat2gif([D, Sp, S],
            save_gif_dir,
            cmap=cmap,
            note=note,
            tit=['Input', 'Prediction', 'Fista'],
            play=False)
#save the matrices
if saveMat:
Esempio n. 21
0
    #state_dict=delitems(state_dict)
    net.load_state_dict(state_dict)  
else:
    net=torch.load(mfile)
print('done.')

"""========================================================================="""
"""                               Load data                                 """
"""========================================================================="""
print('Loading phase...')
print('----------------')

#Dataset, converter and player
data_dir={'invivo':d_invivo,'sim_pm':d_simpm,'sim':d_sim}[prefix]
conter=Converter()
player=Player()
formshow={'pre':'concat','shape':(32,32,20)}
formlist=[]
for i in range(6):
    formlist.append(formshow)
minloss=np.inf

#validation - MSE calculations are performed on the validation set
val_dataset = ImageDataset(round(ValInstances),shape_dset, 
                         train=1,data_dir=data_dir)
val_loader  = data.DataLoader(val_dataset,batch_size=ValBatchSize,shuffle=False)
print('Finished loading.\n')

"""========================================================================="""
"""          Compute the MSE as a function of increasing layers             """
"""========================================================================="""
Esempio n. 22
0
    def begin(self):

        Program.set_mode(self.screen_size, self.full_screen, False)
        Program.set_fps(self.fps)
        pygame.mouse.set_visible(False)

        self.playlist = Playlist()

        self.player = Player()

        self.state = State()

        #print "State volume: {0}".format(self.state.volume)
        #print "State channel: {0}".format(self.state.channel)

        self.encoders_board = EncodersBoard(0x40, 0, 20, self.state.volume, 0, len(self.playlist.playlist) - 1, self.state.channel);

        self.pt2314 = PT2314()
        self.pt2314.setVolume(self.state.volume*5)
	#self.pt2314.setAttenuation(0)
        self.pt2314.setBass(0)
        self.pt2314.setTreble(12)
        self.pt2314.selectChannel(0)
        self.pt2314.loudnessOn()
        self.pt2314.muteOff()
        time.sleep(0.1)

        self.last_volume = self.state.volume
        self.last_channel = self.state.channel
        self.last_played_channel = self.last_channel

        station_url = self.playlist.playlist[self.state.channel].url
        self.player.load("radio")
	self.player.play(self.state.channel)

        self.scene = AppRadio(self)

        while True:
            try:
                micro = self.get_micro()
                
                self.encoders_board.read()

                self.volume = self.encoders_board.get_value1()
                if self.volume > 20:
                    self.volume = 20
                    self.encoders_board.set_value1(self.volume)
                    self.encoders_board.set_max_value1(self.volume)
                    self.encoders_board.write()

                self.channel = self.encoders_board.get_value2()
                if self.channel > len(self.playlist.playlist) - 1:
                    self.channel = len(self.playlist.playlist) - 1
                    self.encoders_board.set_value2(self.channel)
                    self.encoders_board.set_max_value2(self.channel)
                    self.encoders_board.write()

                self.buttons = self.encoders_board.get_buttons()

                if self.last_volume != self.volume:
                    self.pt2314.setVolume(self.volume*5)
                    self.last_volume = self.volume
                    self.last_volume_changed_time = micro

                if self.last_channel != self.channel:
                    self.last_channel = self.channel
                    self.last_channel_changed_time = micro

                if self.last_buttons != self.buttons and micro - self.last_buttons_changed_time > 100:
                    self.last_buttons = self.buttons
                    self.last_buttons_changed_time = micro
                    self.need_change_buttons = True

                if self.last_played_channel != self.channel and micro - self.last_channel_changed_time > 1000:
                    self.need_change_song = True

                if self.state.volume != self.volume and micro - self.last_volume_changed_time > 5000:
                    self.state.volume = self.volume
                    self.need_save_state = True

                if self.state.channel != self.channel and micro - self.last_channel_changed_time > 5000:
                    self.state.channel = self.channel
                    self.need_save_state = True

		if micro - self.last_currentsong_time > 1000:
		    self.icy_current_song = self.player.currentsong()
		    #print self.icy_current_song
		    self.last_currentsong_time = micro

                global ring_bell
                if ring_bell:
                    #print "Doorbell detected";
                    ring_bell = False
                    self.player.stop()
                    self.pt2314.setVolume(95)
		    os.system('mplayer ' + Config.bell)
                    time.sleep(0.5)
                    self.pt2314.setVolume(self.volume*5)
                    self.need_change_song = True

                if self.need_change_song:
                    self.need_change_song = False
                    self.last_played_channel = self.channel
		    time.sleep(0.5)
		    self.player.play(self.channel)

                if self.need_save_state:
                    self.need_save_state = False
                    self.state.save()

		if self.need_change_buttons:
		    self.need_change_buttons = False
		    if (self.last_buttons & Config.BTN_POWER):
			subprocess.call(["poweroff"])
		    if (self.last_buttons & Config.BTN_ALARM):
			subprocess.call(["reboot"])

            except Exception:
                pass

            yield
Esempio n. 23
0
    def begin(self):

        Program.set_mode(self.screen_size, self.full_screen, False)
        Program.set_fps(self.fps)
        pygame.mouse.set_visible(False)

        self.playlist = Playlist()

        self.player = Player()

        self.state = State()

        #print "State volume: {0}".format(self.state.volume)
        #print "State channel: {0}".format(self.state.channel)

        self.encoders_board = EncodersBoard(0x40, 0, 20, self.state.volume, 0,
                                            len(self.playlist.playlist) - 1,
                                            self.state.channel)

        self.pt2314 = PT2314()
        self.pt2314.setVolume(self.state.volume * 5)
        #self.pt2314.setAttenuation(0)
        self.pt2314.setBass(0)
        self.pt2314.setTreble(12)
        self.pt2314.selectChannel(0)
        self.pt2314.loudnessOn()
        self.pt2314.muteOff()
        time.sleep(0.1)

        self.last_volume = self.state.volume
        self.last_channel = self.state.channel
        self.last_played_channel = self.last_channel

        station_url = self.playlist.playlist[self.state.channel].url
        self.player.load("radio")
        self.player.play(self.state.channel)

        self.scene = AppRadio(self)

        while True:
            try:
                micro = self.get_micro()

                self.encoders_board.read()

                self.volume = self.encoders_board.get_value1()
                if self.volume > 20:
                    self.volume = 20
                    self.encoders_board.set_value1(self.volume)
                    self.encoders_board.set_max_value1(self.volume)
                    self.encoders_board.write()

                self.channel = self.encoders_board.get_value2()
                if self.channel > len(self.playlist.playlist) - 1:
                    self.channel = len(self.playlist.playlist) - 1
                    self.encoders_board.set_value2(self.channel)
                    self.encoders_board.set_max_value2(self.channel)
                    self.encoders_board.write()

                self.buttons = self.encoders_board.get_buttons()

                if self.last_volume != self.volume:
                    self.pt2314.setVolume(self.volume * 5)
                    self.last_volume = self.volume
                    self.last_volume_changed_time = micro

                if self.last_channel != self.channel:
                    self.last_channel = self.channel
                    self.last_channel_changed_time = micro

                if self.last_buttons != self.buttons and micro - self.last_buttons_changed_time > 100:
                    self.last_buttons = self.buttons
                    self.last_buttons_changed_time = micro
                    self.need_change_buttons = True

                if self.last_played_channel != self.channel and micro - self.last_channel_changed_time > 1000:
                    self.need_change_song = True

                if self.state.volume != self.volume and micro - self.last_volume_changed_time > 5000:
                    self.state.volume = self.volume
                    self.need_save_state = True

                if self.state.channel != self.channel and micro - self.last_channel_changed_time > 5000:
                    self.state.channel = self.channel
                    self.need_save_state = True

                if micro - self.last_currentsong_time > 1000:
                    self.icy_current_song = self.player.currentsong()
                    #print self.icy_current_song
                    self.last_currentsong_time = micro

                global ring_bell
                if ring_bell:
                    #print "Doorbell detected";
                    ring_bell = False
                    self.player.stop()
                    self.pt2314.setVolume(95)
                    os.system('mplayer ' + Config.bell)
                    time.sleep(0.5)
                    self.pt2314.setVolume(self.volume * 5)
                    self.need_change_song = True

                if self.need_change_song:
                    self.need_change_song = False
                    self.last_played_channel = self.channel
                    time.sleep(0.5)
                    self.player.play(self.channel)

                if self.need_save_state:
                    self.need_save_state = False
                    self.state.save()

                if self.need_change_buttons:
                    self.need_change_buttons = False
                    if (self.last_buttons & Config.BTN_POWER):
                        subprocess.call(["poweroff"])
                    if (self.last_buttons & Config.BTN_ALARM):
                        subprocess.call(["reboot"])

            except Exception:
                pass

            yield
Esempio n. 24
0
# length of 9

from classes.Inputs import Inputs
from classes.Player import Player
from classes.NN import NN
from classes.Board import Board
import numpy as np
import random
from random import randint

# create 100 players
# for every round pair them up and get the victor
# those with higher fitness will then breed
# and also mutate

players = [Player(NN.randWeights(), 0.5) for _ in range(100)]
games = []


def comp(x):
    return x.score


for _ in range(200):
    print(_)
    random.shuffle(players)

    games = [
        Board(players[2 * i], players[2 * i + 1])
        for i in range(len(players) // 2)
    ]
Esempio n. 25
0
class Game:
	"""The main game functionality"""

	__weapons = {}
	__armour = {}
	__gear = {}
	__npc = {}

	def __init__(self):
		# Want to have a set "Gold" Item, because currency is the same everywhere
		self.copper = Item("Copper coin", "", 0.01, 0)
		self.silver = Item("Silver coin", "", 0.1, 0)
		self.gold = Item("Gold coin", "", 1, 0)
		self.platinum = Item("Platinum coin", "", 10, 0)

		# Same thing with items
		weapons = parse("weapons.csv")
		armour = parse("armour.csv")
		gear = parse("gear.csv")
		npc = parse("npc.csv")

		for weapon in weapons:
			# {'Name': 'Spear', 'Price': 2, 'Slots': 2, 'Roll': [1, 8], 'Range': 6, 'Ranged': 0, 'Quest': 0}
			self.__weapons[weapon['Name'].lower()] = Weapon(weapon['Name'], weapon['Price'], weapon['Quest'], weapon['Range'], weapon['Roll'], weapon['Slots'], weapon['Ranged'])

		for armor in armour:
			# {'Name': 'Tower Shield', 'Price': 30, 'Slots': 1, 'Bonus': 4, 'Class': 3, 'Quest': 0}
			self.__armour[armor['Name'].lower()] = Armour(armor['Name'], armor['Price'], armor['Bonus'], armor['Slots'], armor['Class'], armor['Quest'])

		for item in gear:
			#{'Name': 'Winter Blanket', 'Description': '', 'Value': '0.5', 'Quest': 0, 'Container': 0, 'Capacity': 0}
			if item['Container'] == 0:
				self.__gear[item['Name'].lower()] = Gear(item['Name'], item['Description'], item['Value'], 3, item['Quest'], item['Container'], item['Capacity'])
			else:
				self.__gear[item['Name'].lower()] = Container(item['Name'], item['Description'], 0, item['Capacity'])

		for creature in npc:
			#{'Attack': [4, 8, 2], 'Armor': 14, 'Effect': [1, 2, -2], 'Damage': [1, 2, -2], 'Name': 'Scorpion'}
			self.__npc[creature['Name'].lower()] = Npc(creature['Name'], creature['Description'], creature['Race'], 1, creature['Damage'], creature['Effect'], creature['Intelligence'])

		self.map = Map()

	def run(self):
		self.__setup()
		self.__intro()
		loose_items = {"map":{}}

		location = self.map.location.inspect()

		if len(location[2]) > 0:
			for k, item in enumerate(location[2]):
				# loose_items["map"]["copper"] = [50, Item Object]
				if item[1] in loose_items["map"]:
					loose_items["map"][item[1]][0] += item[0]
				else:
					loose_items["map"][item[1]] = [item[0], item[4]]

		while True:
			action = input("? ").lower()
			location = self.map.location.inspect()

			if "help" in action or action == "h":
				print("Available commands:")
				print("")
				print("Look (at) [something]")
				print("Look (at) me/self")
				print("Go [direction]")
				print("Open [something]")
				print("Open my [something]")
				print("Fight [someone]")
				print("Talk (to) [someone]")
				print("Take [something]")
				print("Drop [something]")
				print("")
				print("[quit] to Quit")
				print("")
			elif action == "quit":
				break
			else:
				action = action.split(" ")
				target = False

				if len(action) > 2:
					if action[1] == "at" or action[1] == "to":
						target = " ".join(action[2:])
					else:
						target = " ".join(action[1:])
				elif len(action) > 1:
					target = action[1]

				if "go" in action[0]:
					movement = self.map.move(action[1])

					if movement == False:
						print("You can't go there")
					else:
						# Reset the takeable loose items
						loose_items = {"map":{}}
						print("")
						print(movement[0])
						print("")
						print(movement[1])

						location = self.map.location.inspect()
						if len(location[2]) > 0:
							for k, item in enumerate(location[2]):
								# loose_items["map"]["copper"] = [50, Item Object]
								if item[1] in loose_items["map"]:
									loose_items["map"][item[1]][0] += item[0]
								else:
									loose_items["map"][item[1]] = [item[0], item[4]]

				elif "look" in action[0]:
					if len(action) == 1 or (len(action) == 2 and action[1] == "at"):
						print("")
						print(location[0])
						print("")
						print(location[1])
						print("")

						if len(location[2]) > 0:
							print("You can see these items: ")

							for k, item in enumerate(location[2]):
								print("%dx %s" % (item[0], item[1]))

							print("")

						if len(location[3]) > 0:
							print("Here are: ")

							for k, item in enumerate(location[3]):
								print("%dx level %d %s" % (item[0], item[3], item[1]))

					elif target == "self" or target == "me":
						items = self.player.bag.open()

						print("You have:")

						for k, item in enumerate(items):
							print("%dx %s" % (item[0], item[1]))

					else:
						item = self.map.location.find(target)
						if not item:
							print("That's not here")
						else:
							print("%dx %s" % (item[0], item[1]))
							print(item[2])

				elif "open" in action[0]:
					if "my " in target:
						t = target.split(" ")
						items = self.player.bag.open()
						found = False

						for k, item in enumerate(items):
							if t[1] == item[1].lower():
								found = True
								if isinstance(item[3], Container):
									gear = item[3].open()

									if not gear:
										print("It's empty")
									else:
										print("Inside you find:")

										for k, g in enumerate(gear):
											print("%dx %s" % (g[0], g[1]))
											print(item[2])
								else:
									print("You can't open tahat")

						if not found:
							print("You don't have this")

					else:
						item = self.map.location.find(target)

						if item == False:
							print("That isn't here")
						else:
							result = item[3].open()
							if not result:
								print("It's empty")
							else:
								print("Inside you find:")

								for k, item in enumerate(result):
									print("%dx %s" % (item[0], item[1]))
									print(item[2])

									if target not in loose_items:
										loose_items[target] = {}

									# loose_items["chest"]["copper"] = [50, Item Object]
									if item[1] in loose_items[target]:
										loose_items[target][item[1]][0] += item[0]
									else:
										loose_items[target][item[1]] = [item[0], item[3]]

				elif "take" in action[0]:
					item = False

					for location in loose_items:
						for name, i in loose_items[location].items():
							if name.lower() == target:
								item = i
								break

					bag = self.player.bag.open()
					bag = bag[0][3]

					if item == False:
						print("That isn't here")
					else:
						bag.add_item(item[1], item[0])
						print("Put %s in your bag" % item[1].name)

				elif "drop" in action[0]:
					bag = self.player.bag.open()
					bag = bag[0][3]
					item = self.__gear[target]

					if bag.remove_item(item, 1):
						print("Dropped %s" % item.name)
						self.map.location.add_item(item, 1)
					else:
						print("Don't have %s to drop" % item.name)

				elif "fight" in action[0] or "attack" in action[0]:
					print(target)
					foe = self.__npc[target]
					print(foe)
					print(foe.name)

				elif "talk" in action[0]:
					# TODO: ?????
					print(target)
					npc = self.__npc[target]

			print("")

	def __setup(self):
		name = ""
		while len(name) == 0:
			name = input("What is your name ? ")

		print("Who are you?")
		print("I'm a...")

		race = 0
		while True:
			print("1) Human")
			print("2) Elf")
			print("3) Dwarf")
			print("4) Halfling")

			try:
				race = int(input("? "))
				if race < 1 or race > 4:
					raise ValueError
			except ValueError:
				print("Not a valid number!")
				continue
			else:
				break 

		cls = 0
		while True:
			print("1) Fighter")
			print("2) Rogue")
			print("3) Mage")
			print("4) Cleric")

			try:
				cls = int(input("? "))
				if cls < 1 or cls > 4:
					raise ValueError
			except ValueError:
				print("Not a valid number!")
				continue
			else:
				break 

		self.player = Player(name, "", Dice.roll(6, 3), Dice.roll(6, 3), Dice.roll(6, 3), race, cls)

		# Starting gold
		if cls == 1:
			self.player.currency("Gold", 150)
		elif cls == 2:
			self.player.currency("Gold", 125)
		elif cls == 3:
			self.player.currency("Gold", 75)
		elif cls == 4:
			self.player.currency("Gold", 120)

		bag = self.__gear["backpack"]
		self.player.bag.add_item(bag, 1)

		self.map = Map()

	def __intro(self):
		chest = Container("Old chest", "A ruggedy old chest, half-buried in the sand", 0, 10)
		chest.add_item(self.__gear["bell"], 1)

		self.map.location.add_item(chest, 1)

		print("Welcome Adventurer!")
		print("If you need help, just type in [h] or [help].")
		print("Quit with [quit] and move around with 'Go [direction]'")
		print("Usable stuff is brought out by '[' and ']'.")

		location = self.map.location.inspect()

		print("")
		print(location[0])
		print("")
		print(location[1])
Esempio n. 26
0
class Main(Process):

    playlist = None
    player = None
    state = None
    pt2314 = None

    channel = 0
    volume = 0
    buttons = 0

    icy_current_song = None

    last_channel = 0
    last_played_channel = 0
    last_volume = 0
    last_buttons = 0

    current_time = 0
    last_channel_changed_time = 0
    last_volume_changed_time = 0
    last_buttons_changed_time = 0
    last_currentsong_time = 0
    last_mpd_poll = 0
    need_save_state = False
    need_change_song = False
    need_change_buttons = False

    screen_size = None
    fps = None
    full_screen = False

    scene = None

    def __init__(self):

        self.screen_size = Config.default_screen_size
        self.fps = Config.fps
        self.full_screen = Config.full_screen

        os.environ["SDL_FBDEV"] = Config.fb_dev

	self.serv = HTTPServer( ("0.0.0.0", 8000), HttpProcessor)
        thread = threading.Thread(target = self.serv.serve_forever)
        thread.daemon = True
        thread.start()

        super(Main, self).__init__()

    def begin(self):

        Program.set_mode(self.screen_size, self.full_screen, False)
        Program.set_fps(self.fps)
        pygame.mouse.set_visible(False)

        self.playlist = Playlist()

        self.player = Player()

        self.state = State()

        #print "State volume: {0}".format(self.state.volume)
        #print "State channel: {0}".format(self.state.channel)

        self.encoders_board = EncodersBoard(0x40, 0, 20, self.state.volume, 0, len(self.playlist.playlist) - 1, self.state.channel);

        self.pt2314 = PT2314()
        self.pt2314.setVolume(self.state.volume*5)
	#self.pt2314.setAttenuation(0)
        self.pt2314.setBass(0)
        self.pt2314.setTreble(12)
        self.pt2314.selectChannel(0)
        self.pt2314.loudnessOn()
        self.pt2314.muteOff()
        time.sleep(0.1)

        self.last_volume = self.state.volume
        self.last_channel = self.state.channel
        self.last_played_channel = self.last_channel

        station_url = self.playlist.playlist[self.state.channel].url
        self.player.load("radio")
	self.player.play(self.state.channel)

        self.scene = AppRadio(self)

        while True:
            try:
                micro = self.get_micro()
                
                self.encoders_board.read()

                self.volume = self.encoders_board.get_value1()
                if self.volume > 20:
                    self.volume = 20
                    self.encoders_board.set_value1(self.volume)
                    self.encoders_board.set_max_value1(self.volume)
                    self.encoders_board.write()

                self.channel = self.encoders_board.get_value2()
                if self.channel > len(self.playlist.playlist) - 1:
                    self.channel = len(self.playlist.playlist) - 1
                    self.encoders_board.set_value2(self.channel)
                    self.encoders_board.set_max_value2(self.channel)
                    self.encoders_board.write()

                self.buttons = self.encoders_board.get_buttons()

                if self.last_volume != self.volume:
                    self.pt2314.setVolume(self.volume*5)
                    self.last_volume = self.volume
                    self.last_volume_changed_time = micro

                if self.last_channel != self.channel:
                    self.last_channel = self.channel
                    self.last_channel_changed_time = micro

                if self.last_buttons != self.buttons and micro - self.last_buttons_changed_time > 100:
                    self.last_buttons = self.buttons
                    self.last_buttons_changed_time = micro
                    self.need_change_buttons = True

                if self.last_played_channel != self.channel and micro - self.last_channel_changed_time > 1000:
                    self.need_change_song = True

                if self.state.volume != self.volume and micro - self.last_volume_changed_time > 5000:
                    self.state.volume = self.volume
                    self.need_save_state = True

                if self.state.channel != self.channel and micro - self.last_channel_changed_time > 5000:
                    self.state.channel = self.channel
                    self.need_save_state = True

		if micro - self.last_currentsong_time > 1000:
		    self.icy_current_song = self.player.currentsong()
		    #print self.icy_current_song
		    self.last_currentsong_time = micro

                global ring_bell
                if ring_bell:
                    #print "Doorbell detected";
                    ring_bell = False
                    self.player.stop()
                    self.pt2314.setVolume(95)
		    os.system('mplayer ' + Config.bell)
                    time.sleep(0.5)
                    self.pt2314.setVolume(self.volume*5)
                    self.need_change_song = True

                if self.need_change_song:
                    self.need_change_song = False
                    self.last_played_channel = self.channel
		    time.sleep(0.5)
		    self.player.play(self.channel)

                if self.need_save_state:
                    self.need_save_state = False
                    self.state.save()

		if self.need_change_buttons:
		    self.need_change_buttons = False
		    if (self.last_buttons & Config.BTN_POWER):
			subprocess.call(["poweroff"])
		    if (self.last_buttons & Config.BTN_ALARM):
			subprocess.call(["reboot"])

            except Exception:
                pass

            yield

    def get_micro(self):
        return int(round(time.time() * 1000))

    def get_current_time(self):
        return datetime.now().strftime("%H:%M")

    def unicodify(self, text, min_confidence=0.5):
        guess = chardet.detect(text)
        if guess["confidence"] < min_confidence:
            raise UnicodeDecodeError
        decoded = text.decode(guess["encoding"])
        return decoded

    def fetch_song_title(self):

        if self.icy_current_song is not None and self.icy_current_song != '':
	    try:
                title = self.unicodify(self.icy_current_song)
		#title = self.icy_current_song
                return title.upper()
            except Exception as e:
                return ''
        else:
            return ''

    def fetch_station_title(self):
        station = self.playlist.playlist[self.channel]
        return station.name.upper()
Esempio n. 27
0
    model=UnfoldedNet3dC(params_net)
    state_dict=torch.load(mfile,map_location=device)
    model.load_state_dict(state_dict)
else:
    model=torch.load(mfile)

#Processing
with torch.no_grad():
    data=np.load(data_dir)
    Sum,Bubbles,Tissue=data['arr_0'],data['arr_1'],data['arr_2']
    [Sum]=convert.np2torch([Sum],[form_in])
    predL,predS=model(Sum)
[predL,predS,Sum]=convert.torch2np([predL,predS,Sum],[form_out,form_out,form_out])

#Display
plt.close('all')
player=Player()
player.play([Sum,Bubbles,Tissue,None,predS,predL],note=note,cmap=cmap,
            tit=['Input','Ground Truth S','Ground Truth L',
                 None,'Prediction S','Prediction L'])

#Save gif
if saveGif:
    mat2gif([Sum,Bubbles,Tissue,None,predS,predL],save_gif_dir,
            note=note,cmap=cmap,
            tit=['Input','Ground Truth S','Ground Truth L',
                 None,'Prediction S','Prediction L'])
#Save matrix
if saveMat:
    savemat(save_mat_dir,{'D':Sum,'S':Bubbles,'L':Tissue,
                          'Sp':predS,'Lp':predL})
Esempio n. 28
0
Created on Wed Aug 15 13:48:39 2018

@author: Yi Zhang
"""

import numpy as np
import sys
sys.path.append('../')
from classes.Player import Player
from SimPlatform.ZoneTissue import ZoneTissue
from SimPlatform.ZoneBubbles import ZoneBubbles
from SimPlatform.Simulator import Simulator
from SimPlatform.Functions import Envelope
from SimPlatform.Parameters import params_default

player=Player()

# =============================================================================
# #zTissue=ZoneTissue()
# zTissue=ZoneTissue()
# 
# T=30
# shape=params_default['shape']
# Tissue=np.zeros([shape[0],shape[1],T],dtype=np.complex128)
# 
# for i in range(T):
#     Tissue[:,:,i]=zTissue.image()
#     zTissue.refresh()
#     
# player.play([Tissue])
# =============================================================================
Esempio n. 29
0
 def __init__(self):
     self._players = [Player(0), Player(1)]
     self._current_player = 0
     self._board = Board()
     self._gameUI = GameUI(self._players[0])
Esempio n. 30
0
#Processing
D, Sp, Lp = process_patch(net, data_dir, arange)
brow, erow, bcol, ecol, bt, et = arange
if Sfile[-3:] == 'mat':
    S = loadmat(Sfile)['vid'][brow:erow, bcol:ecol, bt:et]
else:
    S = np.load(Sfile)['arr_0'][brow:erow, bcol:ecol, bt:et]

if Lfile[-3:] == 'mat':
    L = loadmat(Lfile)['vid'][brow:erow, bcol:ecol, bt:et]
else:
    L = np.load(Lfile)['arr_0'][brow:erow, bcol:ecol, bt:et]

#Display
player = Player()
player.play(
    [D, S, L, None, Sp, Lp],
    cmap=cmap,
    note=note,
    tit=['Input', 'Fista S', 'Fista L', None, 'Prediction S', 'Prediction L'])

#save as gif
if saveGif:
    mat2gif([D, S, L, None, Sp, Lp],
            save_gif_dir,
            cmap=cmap,
            note=note,
            tit=[
                'Input', 'Fista S', 'Fista L', None, 'Prediction S',
                'Prediction L'
Esempio n. 31
0
folder='../../../Data/Sim1/'
setname='val'
numInst=16

Dname,Sname,Lname=['patch_180','patch_180','patch_180']\
                  if setname!='test2' else ['Patch','S_est_f','L_est_f']
#the start number of .mat file                      
numstart={'train':0, 'val':2400, 'test1':3200, 'test2':4000}[setname] 

params=params_default
shape=(128,128)
T=20
params['shape']=shape
rIter=int(shape[0]/32)
cIter=int(shape[1]/32)
player=Player()

nIter=int(numInst/shape[0]/shape[1]/T*32*32*20)

print('total iterations and instances: %d, %d'%(nIter,numInst))
numf=numstart
for i in range(nIter):
    print('current iteration: %d, file number: %d to %d'%(i,numf,numf+rIter*cIter))
    simtor=Simulator(params)
    Sum,Bubbles,Tissue=simtor.generate(T)
    for rr in range(rIter):
        for cc in range(cIter):
            D=Sum[rr*32:(rr+1)*32,cc*32:(cc+1)*32,0:20]
            S=Bubbles[rr*32:(rr+1)*32,cc*32:(cc+1)*32,0:20]
            L=Tissue[rr*32:(rr+1)*32,cc*32:(cc+1)*32,0:20]
            
Esempio n. 32
0
from classes.helpers import Address
from classes.Map import Map
from classes.Column import Column
from classes.Player import Player
from classes.Game import Game
from classes.Entity import HealFloor, Warrior

if __name__ == '__main__':

    a1 = Address("127.0.0.1 ", 3331)
    w1 = Warrior((0, 0))
    p1 = Player(a1, "p1", w1)

    a2 = Address("127.0.0.1 ", 3332)
    w2 = Warrior((0, 0))
    p2 = Player(a2, "p2", w2)

    hf1 = HealFloor((2, 1))

    columnList = [
        [Column((0, 0), 1, []),
         Column((1, 0), 1, []),
         Column((2, 0), 1, [])],
        [Column((0, 1), 1, []),
         Column((1, 1), 2, []),
         Column((2, 1), 2, [])],
        [Column((0, 2), 1, []),
         Column((1, 2), 2, []),
         Column((2, 2), 2, [])],
    ]
    map = Map(1, (3, 3), columnList)
Esempio n. 33
0
class Main(Process):

    playlist = None
    player = None
    state = None
    pt2314 = None

    channel = 0
    volume = 0
    buttons = 0

    icy_current_song = None

    last_channel = 0
    last_played_channel = 0
    last_volume = 0
    last_buttons = 0

    current_time = 0
    last_channel_changed_time = 0
    last_volume_changed_time = 0
    last_buttons_changed_time = 0
    last_currentsong_time = 0
    last_mpd_poll = 0
    need_save_state = False
    need_change_song = False
    need_change_buttons = False

    screen_size = None
    fps = None
    full_screen = False

    scene = None

    def __init__(self):

        self.screen_size = Config.default_screen_size
        self.fps = Config.fps
        self.full_screen = Config.full_screen

        os.environ["SDL_FBDEV"] = Config.fb_dev

        self.serv = HTTPServer(("0.0.0.0", 8000), HttpProcessor)
        thread = threading.Thread(target=self.serv.serve_forever)
        thread.daemon = True
        thread.start()

        super(Main, self).__init__()

    def begin(self):

        Program.set_mode(self.screen_size, self.full_screen, False)
        Program.set_fps(self.fps)
        pygame.mouse.set_visible(False)

        self.playlist = Playlist()

        self.player = Player()

        self.state = State()

        #print "State volume: {0}".format(self.state.volume)
        #print "State channel: {0}".format(self.state.channel)

        self.encoders_board = EncodersBoard(0x40, 0, 20, self.state.volume, 0,
                                            len(self.playlist.playlist) - 1,
                                            self.state.channel)

        self.pt2314 = PT2314()
        self.pt2314.setVolume(self.state.volume * 5)
        #self.pt2314.setAttenuation(0)
        self.pt2314.setBass(0)
        self.pt2314.setTreble(12)
        self.pt2314.selectChannel(0)
        self.pt2314.loudnessOn()
        self.pt2314.muteOff()
        time.sleep(0.1)

        self.last_volume = self.state.volume
        self.last_channel = self.state.channel
        self.last_played_channel = self.last_channel

        station_url = self.playlist.playlist[self.state.channel].url
        self.player.load("radio")
        self.player.play(self.state.channel)

        self.scene = AppRadio(self)

        while True:
            try:
                micro = self.get_micro()

                self.encoders_board.read()

                self.volume = self.encoders_board.get_value1()
                if self.volume > 20:
                    self.volume = 20
                    self.encoders_board.set_value1(self.volume)
                    self.encoders_board.set_max_value1(self.volume)
                    self.encoders_board.write()

                self.channel = self.encoders_board.get_value2()
                if self.channel > len(self.playlist.playlist) - 1:
                    self.channel = len(self.playlist.playlist) - 1
                    self.encoders_board.set_value2(self.channel)
                    self.encoders_board.set_max_value2(self.channel)
                    self.encoders_board.write()

                self.buttons = self.encoders_board.get_buttons()

                if self.last_volume != self.volume:
                    self.pt2314.setVolume(self.volume * 5)
                    self.last_volume = self.volume
                    self.last_volume_changed_time = micro

                if self.last_channel != self.channel:
                    self.last_channel = self.channel
                    self.last_channel_changed_time = micro

                if self.last_buttons != self.buttons and micro - self.last_buttons_changed_time > 100:
                    self.last_buttons = self.buttons
                    self.last_buttons_changed_time = micro
                    self.need_change_buttons = True

                if self.last_played_channel != self.channel and micro - self.last_channel_changed_time > 1000:
                    self.need_change_song = True

                if self.state.volume != self.volume and micro - self.last_volume_changed_time > 5000:
                    self.state.volume = self.volume
                    self.need_save_state = True

                if self.state.channel != self.channel and micro - self.last_channel_changed_time > 5000:
                    self.state.channel = self.channel
                    self.need_save_state = True

                if micro - self.last_currentsong_time > 1000:
                    self.icy_current_song = self.player.currentsong()
                    #print self.icy_current_song
                    self.last_currentsong_time = micro

                global ring_bell
                if ring_bell:
                    #print "Doorbell detected";
                    ring_bell = False
                    self.player.stop()
                    self.pt2314.setVolume(95)
                    os.system('mplayer ' + Config.bell)
                    time.sleep(0.5)
                    self.pt2314.setVolume(self.volume * 5)
                    self.need_change_song = True

                if self.need_change_song:
                    self.need_change_song = False
                    self.last_played_channel = self.channel
                    time.sleep(0.5)
                    self.player.play(self.channel)

                if self.need_save_state:
                    self.need_save_state = False
                    self.state.save()

                if self.need_change_buttons:
                    self.need_change_buttons = False
                    if (self.last_buttons & Config.BTN_POWER):
                        subprocess.call(["poweroff"])
                    if (self.last_buttons & Config.BTN_ALARM):
                        subprocess.call(["reboot"])

            except Exception:
                pass

            yield

    def get_micro(self):
        return int(round(time.time() * 1000))

    def get_current_time(self):
        return datetime.now().strftime("%H:%M")

    def unicodify(self, text, min_confidence=0.5):
        guess = chardet.detect(text)
        if guess["confidence"] < min_confidence:
            raise UnicodeDecodeError
        decoded = text.decode(guess["encoding"])
        return decoded

    def fetch_song_title(self):

        if self.icy_current_song is not None and self.icy_current_song != '':
            try:
                title = self.unicodify(self.icy_current_song)
                #title = self.icy_current_song
                return title.upper()
            except Exception as e:
                return ''
        else:
            return ''

    def fetch_station_title(self):
        station = self.playlist.playlist[self.channel]
        return station.name.upper()
from classes.Player import Player
from classes.Birth import Birth
from classes.Hotel import Hotel
from classes.Hotelgast import Hotelgast
from classes.Hotelkamer import Hotelkamer

bob3 = Birth(12, 2, 1996)
bob4 = Birth(12, 2, 200)
p1 = Player("bob", "jos", 15, bob3)
p2 = Player("h", "ij", 48, bob4)
bob = Birth(12, 2, 1996)
bob2 = Birth.randomNumber()
print(p1)

# print(Birth.toonAantal())
# print(bob)
# print(bob2)
# print(Birth.randomList(5))
# print(bob == bob2)
# print(bob == bob3)
# print(bob.sameDay(bob4))
# print(bob.sameDay(bob2))
# for i in hotel1.dic().keys():