def print_item_type(item_type): clear_screen() items = [] counter = 1 print(f"You have these {item_type} available:\n") for i, item in enumerate(self.backpack): if item.item_type == item_type: items.append(item) item_param_name, item_param_value = self.find_parameter( item) print( f'[{counter}] {item.name} --> {item_param_name} + {item_param_value}' ) counter += 1 if items: item_choice = int_input( "Choose item index to put on\n" "Your choice ", len(items)) return items[item_choice - 1] else: clear_screen() input( "You don't have any item that type!\n Press any key to resume game" ) return False
def run_main_menu(player_name): while True: clear_screen() cprint("CHOOSE ONE OF BELOW OPTIONS\n", COLOR.YELLOW) user_choice = int_input("[1] PLAY NEW GAME\n" "[2] RESUME GAME\n" "[3] LOAD GAME\n" "[4] ABOUT US\n" "[5] HIGH SCORES\n" "[6] EXIT\n" "Your choice: ", 6) # TODO with W /from db some stats, how many monsters, level, name, type of hero if user_choice == 1: game = create_new_game(player_name) # !!! <-- Uncomment for full version # game = create_new_game_mock() # !!! <-- Comment for full version game_engine(game) elif user_choice == 2: if load_exist(player_name): game = load_game(player_name, resume_game=True) game_engine(game) elif user_choice == 3: if load_exist(player_name): game = load_game(player_name) game_engine(game) elif user_choice == 4: about_us() elif user_choice == 5: high_scores() elif user_choice == 6: exit()
def create_new_game(player_name): clear_screen() create_new_folder(f'db/saves/{player_name}') choose_difficult = int_input('Please choose difficulty level:\n' '[1] EASY\n' '[2] NORMAL\n' '[3] HARD\n' '[4] IMPOSSIBLE\n\n' 'Your choice: ', number_of_options=4) if choose_difficult == 1: difficulty_level = DIFFICULTY_LEVEL.EASY elif choose_difficult == 2: difficulty_level = DIFFICULTY_LEVEL.NORMAL elif choose_difficult == 3: difficulty_level = DIFFICULTY_LEVEL.HARD elif choose_difficult == 4: difficulty_level = DIFFICULTY_LEVEL.IMPOSSIBLE hero = create_new_hero(player_name) game = Game(player_name=player_name, game_name="RESUME_GAME", difficulty_level=difficulty_level, start_board_index=0, hero=hero) hero.game = game start_board = create_new_board(game, board_index=0) game.boards.append(start_board) return game
def show_stats_breed(self): clear_screen() statistic = self.stats_info() label_len = 16 valid = True while valid: clear_screen() print(f"{' ' * 5}{self.breed} level: {self.level}") for k, v in statistic.items(): espace = int((label_len - len(k)) / 2) if isinstance(v, list): print( f"%s{COLOR.CBLACK}{STYLES.BOLD}{v[0]}{espace * ' '} {k} {v[1]}{espace * ' '}{v[2]}" % (' ' * 8)) else: print(f"%s ({k}:{v})" % (' ' * 8)) keyx = key_pressed() if keyx == 'j': valid = False else: print("Please eneter [j] to exit stats!") time.sleep(1) valid = True pass
def load_exist(player_name): if os.path.isfile(f'db/saves/{player_name}/RESUME_GAME.pickle'): return True else: clear_screen() print("There is no game to load") input("Press any key to continue...") return False
def omx_launch(ssh_client, media_link): flags = [" --timeout 30"] launch = "omxplayer" + " ".join(flags) + media_link stdin, stdout, stderr = ssh_client.exec_command(launch) time.sleep(5) utils.clear_screen() controller_loop_omx(stdin)
def vlc_launch(ssh_client, media_link): flags = ["-f", "-I rc"] launch = "DISPLAY=:0 vlc " + " ".join(flags) + " " + media_link print(launch) stdin, stdout, stderr = ssh_client.exec_command(launch) time.sleep(5) utils.clear_screen() controller_loop_vlc(stdin)
def select_videofile(directory): videos = [] for root, dirs, files in os.walk(directory): for file in files: # Better way to find videofiles would be good if file.endswith((".mp4", ".mkv", "avi")): videos.append(os.path.join(root, file)) utils.clear_screen() return utils.file_menu(videos)
def on_meet(self, hero): """ Function to out if hero meet NPC :param hero: :return:pass """ clear_screen() conversation_effects = self.__conversation(self.dialog_path(hero), hero) return self.__do_after_conversation(conversation_effects, hero)
def print_inventory(self): clear_screen() cprint("+---------------------------------------------------------+", COLOR.PINK, STYLES.BOLD) cprint( f"|----------------|| {self.name.upper()}'S INVENTORY ||-----------------|", COLOR.PURPLE, STYLES.BOLD) cprint("+---------------------------------------------------------+\n", COLOR.PINK, STYLES.BOLD) if all([v is None for k, v in self.inventory.items()]): cprint(" You are naked! Go and find something to put on you!", COLOR.YELLOW, STYLES.BOLD) else: for k, v in self.inventory.items(): if v is not None: cprint(f" You are wearing {k} called {v.name}", COLOR.CYAN) else: cprint(f" You are not wearing any {k}", COLOR.CYAN) cprint("\n+---------------------------------------------------------+", COLOR.PINK, STYLES.BOLD) cprint( f"|---------------|| {self.name.upper()}'S BACKPACK ||-------------------|", COLOR.PURPLE, STYLES.BOLD) cprint("+---------------------------------------------------------+", COLOR.PINK, STYLES.BOLD) # --- printing coins ---- if self.coins > 0: print( f" {self.coins} gold coins are ringing in your pocket\n") else: print( " You are very poor, go and earn some money, lazy b...ear ;)" ) # --- printing any other things in backpack --- cprint(f"You have these items in your backpack:\n", COLOR.YELLOW, STYLES.BOLD) for item in self.backpack: cprint( f"You have {self.how_many_items(item.name)} {item.name} --> {item.item_type}", COLOR.YELLOW) choose_option = int_input( "\n Do you want to put on you something from backpack?\n [1] YES, please!\n [2] NO, maybe next time\n", 2) if choose_option == 1: self.put_on_from_backpack() else: pass self.game.current_board().print_board()
def show_end_game_scenario(self): clear_screen() if self.hero.is_alive(): print_image("classes/Game/crown.txt") input('Press any key to continue...') else: print_image("classes/Game/skull.txt") input('Press any key to continue...') # send stats to highscores :TODO del self
def player_menu(): video_dir = os.path.expanduser( utils.load_settings()["files"]["video_directory"]) video_path = select_videofile(video_dir) print(video_path) menu_items = { "Play media locally": play_locally, "Send media to Raspberry pi": stream_to_pi.play_pi, } utils.clear_screen() function_to_exec = utils.menu(menu_items) function_to_exec(video_path)
def pause_game_menu(game): board = game.current_board() hero = game.hero clear_screen() player_choice = None while player_choice is not 2: player_choice = int_input( '[1] Show active quest\'s\n' '[2] Back to game\n' '> ', 2) if player_choice == 1: show_quests(hero.quests) if player_choice == 2: board.print_board()
def print_add_points(self): clear_screen() choice_possiblities = ['strength', 'agility', 'stamina', 'energy'] for k, v in self.stats_info().items(): if isinstance(v, list) and k == choice_possiblities[ self.current_choice_index]: print( f"%s{COLOR.CBLACK}{STYLES.BOLD}{BG_COLOR.LIGHTGREY}{k} {int(v[1])}{v[3]}{v[2]}" % (' ' * 8)) elif isinstance(v, list): print( f"%s{COLOR.CBLACK}{STYLES.BOLD}{v[0]}{k} {int(v[1])}{v[3]}{v[2]}" % (' ' * 8)) else: print(f"%s ({k}:{v})" % (' ' * 8))
def watch(scan, function_name): scan.seek(0) while True: clear_screen() try: # Hack me here globals()[function_name](scan) time.sleep(5) except KeyboardInterrupt: sys.exit(0) except Exception, e: print('Exception: %s' % e) sys.exit(1)
def put_on_from_backpack(self): """choosing by player what to wear""" def print_item_type(item_type): clear_screen() items = [] counter = 1 print(f"You have these {item_type} available:\n") for i, item in enumerate(self.backpack): if item.item_type == item_type: items.append(item) item_param_name, item_param_value = self.find_parameter( item) print( f'[{counter}] {item.name} --> {item_param_name} + {item_param_value}' ) counter += 1 if items: item_choice = int_input( "Choose item index to put on\n" "Your choice ", len(items)) return items[item_choice - 1] else: clear_screen() input( "You don't have any item that type!\n Press any key to resume game" ) return False clear_screen() choosed_item = int_input( f"Which item you want to put on you?\n" " [1] gloves\n" " [2] helmet\n" " [3] armor\n" " [4] shield\n" " [5] belt\n" " [6] boots\n" " [7] trousers\n" "Your choice: ", 6) item_type = Item.item_types()[choosed_item] item = print_item_type(item_type) self.add_to_inventory_from_backpack(item)
def __do_after_conversation(self, func, hero): """ Run function despite of conversation result :param func:STRING: returned from txt.file string interpretation of functions :param hero: that take part in conversation with NPC :return:False if hero can't move after conversation else True """ if func == "BATTLE": battle(hero, self, hero.game.battle_mode) return True if func == "TRADE": self.trade(hero) if func == "END": clear_screen() if func.startswith("QUEST"): quest_index = func.split('T')[1] self.quest_func[int(quest_index)](hero) return False
def watch(scan_log_filename, scan, function_name): scan.seek(0) while True: try: # Hack me here output = globals()[function_name](scan_log_filename, scan) except KeyboardInterrupt: sys.exit(0) except Exception, e: print('Exception: %s' % e) sys.exit(1) else: if output is not None: output.to_console() time.sleep(5) clear_screen()
def watch(scan_log_filename, scan, function_name): scan.seek(0) while True: try: # Hack me here output = globals()[function_name](scan_log_filename, scan) except KeyboardInterrupt: sys.exit(0) except Exception as e: print('Exception: %s' % e) sys.exit(1) else: if output is not None: output.to_console() time.sleep(5) clear_screen()
def show_menu_and_get_selection(): clear_screen() menu_text = """ Welcome to BrIW v0.1! Please, select an option below by entering a number: [1] Make drink from user input [2] Make new person from user input [3] Print list of people [4] Print list of drinks [5] Make round [6] Select preference [7] Print preference list [8] Exit and save to DB """ print(menu_text) while True: try: return int(input("Enter a number: ")) except ValueError: print("Please enter a valid number.")
def show_stats_with_add_points(self): temp_skill_add_points = self.points_for_level labled = True while labled: clear_screen() val = True if labled: labled, skill_choice = self.add_statistic() if labled == False: break while val: add_rmv = key_pressed() if add_rmv == '+': if self.points_for_level < 1: val = False else: self.points_for_level -= 1 self.add_rmv_points(skill_choice, add_rmv) self.calculate_extra_attributes( skill_choice, self.stats_ratio, add_rmv) elif add_rmv == '-': if self.points_for_level >= temp_skill_add_points: val = False else: self.points_for_level += 1 self.add_rmv_points(skill_choice, add_rmv) self.calculate_extra_attributes( skill_choice, self.stats_ratio, add_rmv) elif ord(add_rmv) == 13: val = False labled = True elif add_rmv == 'j': val = False labled = False else: print( 'You have select wrong keys possible: j, +, -, enter') time.sleep(2) self.print_add_points()
def add_statistic(self): stats_key_pressed = False choice_possiblities = ['strength', 'agility', 'stamina', 'energy'] S = 115 W = 119 ENTER = 13 while stats_key_pressed is not 'j': clear_screen() print('Select by [w]/[s] and press[enter] to select skill.') if stats_key_pressed == 'w': self.current_choice_index -= 1 if stats_key_pressed == 's': self.current_choice_index += 1 if self.current_choice_index >= len(choice_possiblities): if ord(stats_key_pressed) == S: self.current_choice_index = 0 elif ord(stats_key_pressed) == W: self.current_choice_index = 2 else: if self.current_choice_index == len( choice_possiblities) and ord(stats_key_pressed) == S: self.current_choice_index = 0 if self.current_choice_index < 0: self.current_choice_index = len(choice_possiblities) - abs( self.current_choice_index) self.print_add_points() stats_key_pressed = key_pressed() if ord(stats_key_pressed) == ENTER: return True, self.current_choice_index if stats_key_pressed == 'j': return False, self.current_choice_index
def create_new_hero(player_name): valid_key = False # change to True if key is valid AND move is possible current_key = 4 while not valid_key: clear_screen() print('Select class you want to play [w/s] and press enter:') for k, v in select_type.items(): if k == str(current_key): print(f"%s{COLORS.BG_COLOR.LIGHTGREY} {v[1]} {v[2]}" % (' ' * 8)) else: print(f"%s{v[0] + v[0]} {v[1]} {v[2]}" % (' ' * 8)) key = key_pressed() if ord(key) == 115: current_key += 1 elif ord(key) == 119: current_key -= 1 elif ord(key) == 13: if current_key == 4: print("Please press [w or s] and then press enter") time.sleep(0.5) continue else: return select_type[str(current_key)][3](player_name) else: print("not [w] or [s] pressed") time.sleep(0.5) if current_key >= 3: if ord(key) == 115: current_key = 0 elif ord(key) == 119: current_key = 2 else: if current_key == 3 and ord(key) == 115: current_key = 0 if current_key < 0: current_key = 3 - abs(current_key)
def open_treasure(self, hero): """ opening chest, choosing item in it this return is giving info to board is field is empty or not if hero has already this item, he gets 100 coins instead """ print(self.message_in_field) if self.is_locked: clear_screen() cprint("You have found closed chest, do you want to look into? ", INFO) answer = int_input("[1] Yes\n[2] No\n", 2) if answer == 1: if hero.is_in_backpack("Golden key"): loot = self.which_item_in_chest(treasure) # if loot[0].item_type in hero.backpack: if loot[0].item_type == "coins": hero.coins += 100 hero.add_to_message_box(f'You have gain 100 coins!') else: hero.add_to_message_box( f'You took from chest {loot[0].name}') hero.backpack.append(loot[0]) return True else: hero.add_to_message_box( f"You don't have key in your inventory") return False else: hero.add_to_message_box("You left closed chest on it\'s place") return False else: hero.add_to_message_box( "You have found a chest and you've opened it") loot = self.which_item_in_chest(treasure) hero.add_to_message_box(f'You took from chest {loot[0].name}') hero.backpack.append(loot[0]) return True
def take_picture(self): clear_screen() self._cam.open(self.__camera) ret, frame = self.__show_video() self._event.set() # self._cam.release() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) img = transforms.functional.to_tensor(frame) img = img.unsqueeze(0) img = torch.nn.functional.interpolate(img, size=(224, 224)) result = None with torch.no_grad(): # import matplotlib.pyplot as plt # plt.imshow(img.squeeze(0).permute(1,2,0)) # plt.show() if self.label == 0: result = self.model.get_feature_vector(img) self._loop.create_task(self.send_features_vector(result, 0)) clear_screen() self._label0_event.clear() self._event.clear() return elif self.label == 1: result = self.model.get_feature_vector(img) self._loop.create_task(self.send_features_vector(result, 1)) clear_screen() self._label1_event.clear() self._event.clear() return else: predictions = self.model(img) result = torch.argmax(predictions, 1).squeeze(0) print(f"Label: {'CORRECT' if result.item() == 1 else 'INCORRECT'}") self._event.clear() return result.item()
def print_board(self): self.update_board() border_field = f"{BG_COLOR.BLUE} {STYLES.RESET}" # MIDDLE LOGIC middle_border = [] max_row_length = 0 for i, list_of_fields in enumerate(self.game_board_in_class): if i == 0: middle_fileds = f"{border_field}{' ' * 5}" elif i == 1 or i == self.height + 1: middle_fileds += '' else: middle_fileds = f"\n{border_field}{' ' * 6}" for j, field in enumerate(list_of_fields): if field.symbol_on_map not in symbols_to_txt_draw.keys(): if field.symbol_on_map == "6": middle_fileds += BG_COLOR.RED + STYLES.BOLD + COLOR.WHITE + self.boss[ self.counter] + STYLES.RESET self.counter += 1 else: middle_fileds += self.board_map[i - 1][ j].field_color + field.color_on_board + field.symbol_on_map + STYLES.RESET else: middle_fileds += field.field_color + field.color_on_board + field.symbol_on_map + STYLES.RESET additonal_info = '' if i == 1: additonal_info = f"{' ' * 2}Nickname: {self.hero.name} " if i == 2: additonal_info = f"{' ' * 2}Level: {self.hero.level} " if i == 3: additonal_info = f"{' ' * 2}Class: {self.hero.breed} " if i == 4: additonal_info = f"{' ' * 2}HP: {int(self.hero.hp)}/{int(self.hero.max_hp)} " if i == 5: additonal_info = f"{' ' * 2}MANA: {int(self.hero.mana)}/{int(self.hero.max_mana)} " if i == 6: additonal_info = f"{' ' * 2}EXP: {self.hero.exp}/{self.hero.exp_to_next_level} " if i == 7: additonal_info = f"{' ' * 2}CORDS: x:{self.hero.position_x} | y:{self.hero.position_y}" additonal_info += f"{' ' * (6 - len(str(self.hero.position_x)) - len(str(self.hero.position_y)))}" if i == 8: if self.hero.points_for_level > 0: additonal_info = f"{' ' * 2}Press [j] to add points " if i == 9: additonal_info = f"{' ' * 2}|H|:HP |M|:MANA |I|:Inventory" middle_fileds += additonal_info if i is len(self.game_board_in_class) - 1: row_length = self.width + 11 + len(additonal_info) else: row_length = self.width + 10 + len(additonal_info) if i not in [0, len(self.game_board_in_class) - 2]: middle_border.append([row_length, middle_fileds]) if row_length > max_row_length: max_row_length = row_length if len(self.name) + 2 > max_row_length: max_row_length = len(self.name) + 2 # GENERAL new_empty_line = f"\n{border_field}{' ' * (max_row_length - 4)}{border_field}" # TOP PRINT AND LOGIC map_name = f"{border_field}{' ' * 2} Map: {self.name}{' ' * (max_row_length - len(self.name) - 12)}{border_field}" top = f"{BG_COLOR.BLUE}{' ' * max_row_length}{STYLES.RESET}\n" # logo = f"{border_field}{' ' * 2}{self.logo}{STYLES.RESET}{' ' * (max_row_length - len(self.logo) - 6)}{border_field}\n" top += map_name + new_empty_line clear_screen() print(top) self.counter = 0 # MIDDLE mid = [] for i, item in enumerate(middle_border): mid.append( f"{item[1]}{' ' * (max_row_length - item[0])}{border_field}") print(''.join(mid), new_empty_line) # LAST MESSAGE FROM HERO if not self.is_boss_on_map: nothing_happened_messages = [ "Nothing happened... this time around", f"{self.hero.name}: Did I hear something?", "Angry trolls are watching you...", "Such a strange place...", f"{self.hero.name}: I hear huge creatures near here", f"{self.hero.name}: What was that?!", "Keep rolin' rolin'", f"{self.hero.name}: Toss a coin to your {self.hero.name}... nanana" ] else: nothing_happened_messages = [ "Belzedup: MUAHAHAHA, I will eat your brain", "Belzedup: I feel smell of your fear", "Belzedup: Come to my room of pain, little kitty", "Belzedup: Come here, I'm waiting for you!" ] if not self.last_move_message: self.last_move_message.append(choice(nothing_happened_messages)) for last_message in self.last_move_message: number_of_lines = math.ceil( len(last_message) / (max_row_length - 6)) one_line_len = int(len(last_message) / number_of_lines) last_message_chunks = [ last_message[i:i + one_line_len] for i in range(0, len(last_message), one_line_len) ] last_message_chunks = [f"{border_field}{' ' * int((max_row_length - 4 - math.ceil(len(item))) / 2)}{item}" \ f"{' ' * int((max_row_length - 3 - math.floor(len(item))) / 2)}{border_field}" for item in last_message_chunks] last_message_chunks = [ f"{BG_COLOR.BLUE}{' ' * max_row_length}{STYLES.RESET}" ] + last_message_chunks print('\n'.join(last_message_chunks)) self.last_move_message = [] print( f"{new_empty_line[1:]}\n{BG_COLOR.BLUE}{' ' * max_row_length}{STYLES.RESET}" )
operation_choice = input(">>> ").upper() # Check for valid input if operation_choice not in {"E", "D"}: utils.exit_check(operation_choice) raise ValueError('Enter "E" to encrypt or "D" to decrypt') except ValueError: utils.print_invalid_entry_message() continue else: return (OPERATION_ENCRYPT if operation_choice == "E" else OPERATION_DECRYPT) if __name__ == '__main__': # Begin UI flow utils.clear_screen() print("Welcome to the Cipher Machine!\n" "Follow the prompts to encrypt or decrypt messages.\n" "You can always enter 'Q' or 'quit' to leave the program.\n\n") while (True): selected_operation = select_encrypt_decrypt() print("\n{} from which cipher?".format(selected_operation)) selected_cipher = select_cipher() # Affine cipher requires input of key values if selected_cipher == ciphers[1]: selected_cipher.prompt_for_variables() print("a: {}".format(selected_cipher.a)) print("b: {}".format(selected_cipher.b))
def train_DQNs (sess, DQNs, spec_params, tester, curriculum, show_print, render): # Initializing parameters dqns = DQNs[spec_params.ltl_spec] training_params = tester.training_params testing_params = tester.testing_params env = Game(spec_params) obs_proxy = Obs_Proxy(env) agents = env.agents action_set = env.get_actions(agents[0]) # NOTE: only if they all have the same action set # All the agents have the same observation num_features = len(obs_proxy.get_observation(env, env.agents[0])) max_steps = training_params.max_timesteps_per_spec Replay_buffers = {} for agent in agents: Replay_buffers[str(agent)] = IDQNReplayBuffer( training_params.replay_size) exploration = LinearSchedule( schedule_timesteps = int(training_params.exploration_frac \ * max_steps), initial_p=1.0, final_p = training_params.final_exploration) training_reward = 0 last_ep_rew = 0 episode_count = 0 # episode counter rew_batch = np.zeros(100) if show_print: print("Executing ", max_steps, " steps...") if render: env.show_map() #We start iterating with the environment for t in range (max_steps): actions = [] for agent, dqn in zip(agents.values(), dqns.values()): # Getting the current state and ltl goal s1 = obs_proxy.get_observation(env, agent) # Choosing an action to perform if random.random() < exploration.value(t): act = random.choice(action_set) # take random actions else: act = Actions(dqn.get_best_action(s1.reshape((1,num_features)))) # print("Act", act) actions.append(act) dqn.add_step() # updating the curriculum curriculum.add_step() # Executing the action reward = env.execute_actions(actions) if render and ep_c%30 is 0: time.sleep(0.01) clear_screen() env.show_map() training_reward += reward for agent, dqn, act in zip(agents.values(), dqns.values(), actions): # Saving this transition s2 = obs_proxy.get_observation(env, agent) # adding the DFA state to the features done = env.ltl_game_over or env.env_game_over dqn.save_transition(s1, act, reward, s2, done) # Learning if dqn.get_steps() > training_params.learning_starts and \ dqn.get_steps() % training_params.values_network_update_freq \ == 0: dqn.learn() # Updating the target network if dqn.get_steps() > training_params.learning_starts and \ dqn.get_steps() % training_params.target_network_update_freq\ == 0: dqn.update_target_network() # Printing if show_print and (dqns['0'].get_steps()+1) \ % training_params.print_freq == 0: print("Step:", dqns['0'].get_steps()+1, "\tTotal reward:", last_ep_rew, "\tSucc rate:", "%0.3f"%curriculum.get_succ_rate(), "\tNumber of episodes:", episode_count) # Testing if testing_params.test and (curriculum.get_current_step() \ % testing_params.test_freq == 0): tester.run_test(curriculum.get_current_step(), sess, _test_DQN, DQNs) # Restarting the environment (Game Over) if done: # Game over occurs for one of three reasons: # 1) DFA reached a terminal state, # 2) DFA reached a deadend, or # 3) The agent reached an environment deadend (e.g. a PIT) # Restarting env = Game(spec_params) obs_proxy = Obs_Proxy(env) agents = env.agents rew_batch[episode_count%100]= training_reward episode_count+=1 last_ep_rew = training_reward training_reward = 0 # updating the hit rates curriculum.update_succ_rate(t, reward) # Uncomment if want to stop learning according to succ. rate # if curriculum.stop_spec(t): # last_ep_rew = 0 # if show_print: print("STOP SPEC!!!") # break # checking the steps time-out if curriculum.stop_learning(): if show_print: print("STOP LEARNING!!!") break if show_print: print("Done! Last reward:", last_ep_rew)
def __correct_stdout(self): clear_screen() print(f'{self.__get_prompt()}', flush=True)
def battle(hero, monster, battle_mode, hero_start=True): """ :param hero_start:[bool] True if hero start fight, False if monster, npc :param hero:[object] :param monster:[object] :param battle_mode:[string]:[IMMEDIATE_FIGHT, AUTOMATE_FIGHT, MANUAL_FIGHT] :return: pass """ def wait(wait_time): """ :param wait_time:[float] amount of time to wait in seconds :return: pass """ if battle_mode == BATTLE_MODES.MANUAL_FIGHT: time.sleep(wait_time) def battle_image(): with open("events/battle.txt", "r") as f: for row in f: cprint((row[:-1]), COLOR.RED, STYLES.BOLD) def calculate_dmg(v2, v3): if v2 == 'magic': return hero.magic_dmg * v3 elif v2 == 'physical': return hero.phys_dmg * v3 elif v2 == 'magic_and_physical': return hero.magic_dmg * hero.phys_dmg * v3 elif v2 == 'energy_and_stamina': return (hero.energy * hero.stamina) / 2 def block_skill_counter(): pass def use_potions(): key_pressed = key_service.key_pressed() if key_pressed.lower() == 'h': hero.use_hpotion() elif key_pressed.lower() == 'm': hero.use_mana() def how_many_potions(kind_of_potion): counter = 0 for potion in hero.backpack: if potion.item_type == kind_of_potion: counter += 1 return counter def print_skill_selection(): spell_name_print = '' max_key = 2 for k, v in hero.spells.items(): if k is 9: spell_name_print += f"{' ' * 8}[{k}]{' ' * 2}Hero HP:{hero.hp}{' ' * 4}| {' ' * 2}Hero Mana: {hero.mana}\n" spell_name_print += f"{' ' * 11}{'-' * 40}\n" spell_name_print += f"{' ' * 20}HP Potions | MANA Potions \n" spell_name_print += f"{' ' * 4}[key:quantity] H:{how_many_potions('healing_potion')}{' ' * 11}" \ f"M: {how_many_potions('mana')}" else: if hero.energy >= v[4]: if v[2] == 'energy_and_stamina': spell_name_print += f"{' ' * 8}[{k}] {v[0]} (mana cost:{v[1]})\n" else: skill = calculate_dmg(v[2], v[3]) spell_name_print += f"{' ' * 8}[{k}] {v[0]} [dmg:{int(skill)}] (mana cost:{v[1]})\n" max_key += 1 spell_name_print += '\nYour choice how to fight: ' return max_key, spell_name_print def hero_move(): if battle_mode == BATTLE_MODES.MANUAL_FIGHT: valid = True while valid: max_key, spell_name_print = print_skill_selection() max_key_options = [item for item in range(1, max_key - 1)] max_key_options += [9] hero_attack = int_input(spell_name_print, options=max_key_options) if hero_attack == 9: print( "Press [h] to use hp potion or [m] to use mana potion") time.sleep(0.5) use_potions() continue else: spell_mana_cost = hero.spells[hero_attack][1] wait(0.5) if spell_mana_cost >= hero.mana: print( f"You dont have enough mana ({hero.mana}) to use this spell." ) time.sleep(0.5) valid = True else: hero.mana -= spell_mana_cost valid = False if hero.spells[hero_attack][2] == 'energy_and_stamina': if 0 < hero.special_buff_iter <= 6: print('You have already this buff on') time.sleep(1) continue else: hero.special_buff_flag = True hero.special_buff(hero.special_buff_dmg, '+') else: calc_dmg = calculate_dmg(hero.spells[hero_attack][2], hero.spells[hero_attack][3]) hero.attack(monster, calc_dmg) # Battle start messages if hero_start: clear_screen() battle_image() time.sleep(1) clear_screen() cprint(f"You attacked {monster.name}!", ERROR, start_enter=1, wait_after=1) else: clear_screen() battle_image() time.sleep(1) clear_screen() cprint(f'{hero.name} has been attacked by {monster.name}!', ERROR, start_enter=1, wait_after=1) cprint(f"Battle start! {hero.name} vs {monster.name}", COLOR.PURPLE, start_enter=1, end_enter=1) hero.start_fight_message() monster.start_fight_message() # Battle whose_turn = False round_counter = 0 while monster.is_alive(): round_counter += 1 cprint(f"Round: {round_counter}", COLOR.PURPLE) if hero.special_buff_flag: if hero.special_buff_iter >= 0 and hero.special_buff_iter <= 3: hero.special_buff_iter += 1 print( f"{BG_COLOR.RED}{STYLES.BOLD}{COLOR.WHITE}hero defense + {hero.special_buff_dmg}{STYLES.RESET}\n" ) else: hero.special_buff(hero.special_buff_dmg, '-') print( f"{BG_COLOR.RED}{STYLES.BOLD}{COLOR.WHITE}hero defense - {hero.special_buff_dmg}{STYLES.RESET}\n" ) hero.special_buff_iter = 0 hero.special_buff_flag = False if whose_turn is False: cprint(f'{hero.name} attacks!', hero.color_in_battle) hero_move() cprint(f"Monster's hp: {monster.hp}/{monster.max_hp}", COLOR.RED) whose_turn = True wait(1) print("\n") if monster.is_alive() and whose_turn == True: monster.attack(hero, monster.strength) hero.print_hp() hero.print_mana() whose_turn = False wait(1) else: if hero.special_buff_flag: hero.special_buff_iter = 0 hero.special_buff(hero.special_buff_dmg, '-') hero.special_buff_flag = False monster.print_hp() monster.on_defeat() wait(1) break if not hero.is_alive(): hero.print_hp() input("You die!") return True # Battle end cprint(f'You have got {monster.exp} exp.', SUCCESS) hero.get_exp(monster.exp) hero.add_to_backpack(monster.loot) hero.print_loot(monster.loot) input("\nPress enter to exit fight report...\n") hero.add_to_message_box( f"Glorious victory! {monster.name} has been vanquished!") if monster.name == "Belzedup": hero.game.endgame = True pass
def main(): clear_screen() cprint("WELCOME IN ANGRY TROLLS!\n", COLOR.BLUE) player_name = log_in() run_main_menu(player_name)