class AttackOfTheOrcs: def __init__(self): self.huts = [] self.player = None def get_occupants(self): """Return a list of occupant types for all huts. .. todo:: Prone to bugs if self.huts is not populated. Chapter 2 talks about catching exceptions """ return [x.get_occupant_type() for x in self.huts] def show_game_mission(self): """Print the game mission in the console""" print_bold("Mission:") print(" 1. Fight with the enemy.") print(" 2. Bring all the huts in the village under your control") print("---------------------------------------------------------\n") def _process_user_choice(self): """Process the user input for choice of hut to enter""" verifying_choice = True idx = 0 print("Current occupants: %s" % self.get_occupants()) while verifying_choice: user_choice = raw_input("Choose a hut number to enter (1-5): ") try: idx = int(user_choice) if idx < 1: raise NegativeHutNumberError elif idx > 5: raise HutNumberGreaterThanFiveError if self.huts[idx - 1].is_acquired: print( "You have already acquired this hut. Try again." "<INFO: You can NOT get healed in already acquired hut.>" ) else: verifying_choice = False except ValueError as e: print("Invalid input, args: %s \n" % e.args) continue except HutError as e: print(e.error_message) print("Invalid input: ", idx) print("Number should be in the range 1-5. Try again") continue return idx def _occupy_huts(self): """Randomly occupy the huts with one of: friend, enemy or 'None'""" for i in range(5): choice_lst = ['enemy', 'friend', None] computer_choice = random.choice(choice_lst) if computer_choice == 'enemy': name = 'enemy-' + str(i + 1) self.huts.append(Hut(i + 1, OrcRider(name))) elif computer_choice == 'friend': name = 'knight-' + str(i + 1) self.huts.append(Hut(i + 1, Knight(name))) else: self.huts.append(Hut(i + 1, computer_choice)) def play(self): self.player = Knight() self._occupy_huts() acquired_hut_counter = 0 self.show_game_mission() self.player.show_health(bold=True) while acquired_hut_counter < 5: idx = self._process_user_choice() self.player.acquire_hut(self.huts[idx - 1]) if self.player.health_meter <= 0: print_bold("YOU LOSE :( Better luck next time") if self.huts[idx - 1].is_acquired: acquired_hut_counter += 1 if acquired_hut_counter == 5: print_bold("Congratulations! YOU WIN!!!")
class AttackofTheOrcs: def __init__(self, hut_number=HUT_NUMBER): self.huts = [] self.hut_number = hut_number self.player = None @staticmethod def show_game_mission(): print_bold('任务1:') print('1、打败所有敌人') print('2、调查所有木屋,获取所有木屋的控制权') print_dotted_line() def get_occupants(self): return [x.get_occupant_type() for x in self.huts] def _occupy_huts(self): print_bold('发现{}座木屋!'.format(self.hut_number)) """Randomly occupy the hut with one of : friend, enemy or None""" for i in range(self.hut_number): choice_list = ['敌人', '朋友', None] computer_choice = random.choice(choice_list) # 根据计算机随机选择木屋里是敌人、队友或是空的 if computer_choice == '敌人': name = '敌人-' + str(i + 1) self.huts.append(Hut(i + 1, OrcRider(name))) elif computer_choice == '朋友': name = '骑士-' + str(i + 1) self.huts.append(Hut(i + 1, Knight(name))) else: self.huts.append(Hut(i + 1, computer_choice)) def _process_user_choice(self): """"Process the user input for choice of hut to enter""" print("木屋调查情况: %s" % self.get_occupants()) idx = 0 verifying_choice = True while verifying_choice: user_choice = input('选择一个木屋进入(1-%d):' % self.hut_number) # exception process for non-integer user_choice try: idx = int(user_choice) except ValueError as e: print('无效输入,参数不是整数( %s )' % e.args) continue try: assert idx > 0 if self.huts[idx - 1].is_acquired: print('你已经调查过这个木屋,请再尝试一次。\n' '提示:不能再已调查的木屋得到治疗') else: verifying_choice = False except IndexError: print('无效输入,你输入的木屋号超过了可选择范围(1-%d)!' % self.hut_number) continue # If idx <= 0 except AssertionError: print('无效输入,你输入的木屋号超过了可选择范围(1-%d)!' % self.hut_number) continue return idx def setup_game_scenario(self): """ Create player - a Knight and huts, then randomly pre-occupy huts """ self.player = Knight() self.player.info() self.player.show_health(bold=False) self._occupy_huts() def play(self): """" Workhorse method to play the game""" # Initialize the game setup self.show_game_mission() self.setup_game_scenario() # main game play logic begins acquires_hut_counter = 0 while acquires_hut_counter < self.hut_number: idx = self._process_user_choice() self.player.acquire_hut(self.huts[idx - 1]) if self.player.health_meter <= 0: print_bold('你输了!祝下次好运!') break if self.huts[idx - 1].is_acquired: acquires_hut_counter += 1 if acquires_hut_counter == self.hut_number: print_bold('祝贺你!你已经调查完所有的木屋') def test(self): self.player = Knight() self.player.info() self.player.show_health(bold=False) knight = self.player knight.jump() knight.jump = can_not_jump knight.jump() knight.equip_with_accessory('ironjacket') knight.equip_with_accessory('superlocket') knight.show_details() print_dotted_line() orc = OrcRider('Orc战士') orc.info() orc.equip_with_accessory('powersuit') orc.equip_with_accessory('magiclocket') orc.show_details()
class AttackOfTheOrcs: def __init__(self): self.huts = [] # 创建一个hut类的实例表 self.player = None # 实例化player # 获取木屋的占据信息 def get_occupants(self): return [x.get_occupant_type() for x in self.huts] # 展示游戏任务 def show_game_mission(self): print("Mission:") print("\t1. fight with the enemy!") print("TIP:") print("\tbring all the huts in the villege under your control") print_dotted() # 确认用户的选择 def _process_user_choice(self): verify_choice = True idx = 0 print("Current occupant: %s" % self.get_occupants()) while verify_choice: user_choice = input("Choose a number to enter (1-5):") try: idx = int(user_choice) except GameUnitError as e: # 异常ValueError print("Invalid input: %s" % e.args) continue try: if self.huts[idx-1].is_acquire: print("You have try again!") else: verify_choice = False except IndexError: # 异常IndexError print("Invalid input:", idx) print("Number should be in the range 1 - 5, Please try again.") continue return idx # hut类的实例化和分配(占据木屋) def occupy_huts(self): occupants = ['enemy', 'friend', None] # 木屋占有人的类型 # Randomly append 'enemy' or 'friend' or None to the huts list for i in range(5): computer_choice = random.choice(occupants) if computer_choice == 'enemy': name = 'enemy-' + str(i+1) self.huts.append(Hut(i+1, OrcRider(name))) elif computer_choice == 'friend': name = 'friend-' + str(i+1) self.huts.append(Hut(i+1, Knight(name))) else: self.huts.append(Hut(i+1, computer_choice)) # 开始游戏 def play(self): self.player = Knight() self.occupy_huts() # 确认木屋全部检查过 acquire_hut_count = 0 # 游戏人物及人物血量 self.show_game_mission() self.player.show_health(bold=True) # 开始War while acquire_hut_count < 5: # 玩家选择攻占的木屋 idx = self._process_user_choice() # 开始占据木屋 self.player.acquire_hut(self.huts[idx-1]) # 结束条件 if self.player.health_meter <= 0: print("You Lose, Better luck next time!") break if self.huts[idx-1].is_acquire: acquire_hut_count += 1 if acquire_hut_count == 5: print("Congratulation for you! You Win!!!")
class AttackOfTheOrcs: """Main class with the high level logic to play Attack of The Orcs game :ivar huts: List object to hold instances of `Hut` class. :ivar player: Represents the player playing this game. This is an instance of class `Knight` in current implementation. .. seealso:: :py:meth:`self.play` where the main action happens. """ def __init__(self): self.huts = [] self.player = None def get_occupants(self): """Return a list of occupant types for all huts. This is mainly used for printing information on current status of the hut (whether unoccupied or acquired etc) If the occupant is not `None` the occupant type will be 'enemy' or 'friend'. But if there is no occupant or is already 'acquired' the occupant_type will display that information instead. See `Hut.get_occupant_type()` for more details. Return a list that collects this information from all the huts. This is a list comprehension example. More on the list comprehension in a chapter on Performance. :return: A list containing occupant types (strings) .. seealso:: :py:meth:`Hut.get_occupant_type` """ return [x.get_occupant_type() for x in self.huts] def show_game_mission(self): """Print the game mission in the console""" print_bold("Mission:") print(" 1. Fight with the enemy.") print(" 2. Bring all the huts in the village under your control") print("---------------------------------------------------------\n") def _process_user_choice(self): """Process the user input for choice of hut to enter Returns the hut number to enter based on the user input. This method makes sure that the hut number user has entered is valid. If not, it prompts the user to re-enter this information. :return: hut index to enter. """ verifying_choice = True idx = 0 print("Current occupants: %s" % self.get_occupants()) while verifying_choice: user_choice = input("Choose a hut number to enter (1-5): ") # -------------------------------------------------------------- # try...except illustration for chapter on exception handling. # (Attack Of The Orcs v1.1.0) # -------------------------------------------------------------- try: idx = int(user_choice) except ValueError as e: print("Invalid input, args: %s \n" % e.args) continue try: if self.huts[idx - 1].is_acquired: print( "You have already acquired this hut. Try again." "<INFO: You can NOT get healed in already acquired hut.>" ) else: verifying_choice = False except IndexError: print("Invalid input : ", idx) print("Number should be in the range 1-5. Try again") continue return idx def _occupy_huts(self): """Randomly occupy the huts with one of, friend, enemy or 'None' .. todo:: Here we assume there are exactly 5 huts. As an exercise, make it a user input. Note that after such change, the unit test is expected to fail! """ for i in range(5): choice_lst = ['enemy', 'friend', None] computer_choice = random.choice(choice_lst) if computer_choice == 'enemy': name = 'enemy-' + str(i + 1) self.huts.append(Hut(i + 1, OrcRider(name))) elif computer_choice == 'friend': name = 'knight-' + str(i + 1) self.huts.append(Hut(i + 1, Knight(name))) else: self.huts.append(Hut(i + 1, computer_choice)) def play(self): """Workhorse method to play the game. Controls the high level logic to play the game. This is called from the main program to begin the game execution. In summary, this method has the high level logic that does the following by calling appropriate functionality: * Set up instance variables for the game * Accept the user input for hut number to enter * Attempt to acquire the hut ( :py:meth:`Knight.acquire_hut` ) * Determine if the player wins or loses. .. seealso:: :py:meth:`Knight.acquire_hut` """ self.player = Knight() self._occupy_huts() acquired_hut_counter = 0 self.show_game_mission() self.player.show_health(bold=True) while acquired_hut_counter < 5: idx = self._process_user_choice() self.player.acquire_hut(self.huts[idx - 1]) if self.player.health_meter <= 0: print_bold("YOU LOSE :( Better luck next time") break if self.huts[idx - 1].is_acquired: acquired_hut_counter += 1 if acquired_hut_counter == 5: print_bold("Congratulations! YOU WIN!!!")
class AttackOfTheOrcs: """Main class to play attack of the Orcs game""" def __init__(self): self.huts = [] self.player = None def get_occupants(self): """Return a list of occupant types for all huts. .. todo:: Prone to bugs if self.huts is not populated. Chapter 2 talks about catching exceptions """ return [x.get_occupant_type() for x in self.huts] def show_game_mission(self): """Print the game mission in the console""" print_bold("Mission:") print(" 1. Fight with the enemy.") print(" 2. Bring all the huts in the village under your control") print("----------------------------------------------------------") def _process_user_choice(self): """Process the user input for choice of hut to enter""" verifying_choice = True idx = 0 print("Current occupants: %s" % self.get_occupants()) while verifying_choice: user_choice = input("Choose a hut number to enter (1-5): ") try: idx = int(user_choice) except ValueError as e: print("Invalid Input, args: %s \n" % e.args) continue try: if self.huts[idx - 1].is_acquired: print("You have already acquired this hut. Try again." "<INFO: You can Not get healed in already " / "acquired hut.") else: verifying_choice = False except IndexError: print("Invalid input : ", idx) print("Number should be in range 1-5. Try again") continue return idx def _occupy_huts(self): """Randomly occupy thte huts with one of: friend, enemy or 'None'""" for i in range(5): choice_list = ['enemy', 'friend', None] computer_choice = random.choice(choice_list) if computer_choice == 'enemy': name = 'enemy-' + str(i + 1) self.huts.append(Hut(i + 1, OrcRider(name))) elif computer_choice == 'friend': name = 'knight-' + str(i + 1) self.huts.append(Hut(i + 1, Knight(name))) else: self.huts.append(Hut(i + 1, computer_choice)) def setup_game_scenario(self): """Create player and huts and then randomly pre occupy huts""" self.player = Knight() self._occupy_huts() self.show_game_mission() self.player.show_health(bold=True) def play(self): """ Workhorse method to play the game """ # Create a Knight instance , create huts and preoccupy them # with a game character instance (or leave empty) self.setup_game_scenario() acquired_hut_counter = 0 while acquired_hut_counter < 5: idx = self._process_user_choice() self.player.acquire_hut(self.huts[idx - 1]) if self.player.health_meter <= 0: print_bold("Your Lose :( Better Luck Next Time!!!") break if self.huts[idx - 1].is_acquired: acquired_hut_counter += 1 if acquired_hut_counter == 5: print_bold("Congratulations!!! You Win!!!")
class AttackOfTheOrcs: def __init__(self): self.huts: List[Hut] = [] self.player = None def get_occupants(self): current_occupants = [] for hut in self.huts: current_occupants.append(hut.get_occupant_type()) return str(current_occupants) def show_game_mission(self): print(bold('Mission:')) print('\t1. Fight with the enemy.') print('\t2. Bring all the huts in the village under your control.') print('-' * 72) print() def _process_user_choice(self) -> int: """Process the user input for choice of hut to enter""" verifying_choice = True idx = 0 print(f'Current occupants:{self.get_occupants()}') while verifying_choice: try: user_choice = input('Choose a hut number to enter (1-5): ') try: idx = int(user_choice) except ValueError: raise HutError(103) try: if self.huts[idx - 1].isacquired: raise HutError(104) except IndexError: raise HutError(101) else: if idx not in range(1, 6): raise HutError(102) except HutError: continue else: verifying_choice = False return int(idx) def _occupy_huts(self): """Randomly occupy the huts with one of: friend enemy or 'None'""" for i in range(5): choice_lst = ['enemy', 'friend', None] computer_choice = random.choice(choice_lst) if computer_choice == 'enemy': name = 'enemy-' + str(i + 1) self.huts.append(Hut(i + 1, OrcRider(name))) elif computer_choice == 'friend': name = 'knight-' + str(i + 1) self.huts.append(Hut(i + 1, Knight(name))) else: self.huts.append(Hut(i + 1, computer_choice)) def play(self): self.player = Knight() self._occupy_huts() acquired_hut_counter = 0 self.show_game_mission() self.player.show_health(bold_str=True, end='\r\n') while acquired_hut_counter < 5: idx = self._process_user_choice() self.player.acquire_hut(self.huts[idx - 1]) if self.player.health_meter <= 0: print(bold("YOU LOSE :( Better luck next time")) break if self.huts[idx - 1].isacquired: acquired_hut_counter += 1 if acquired_hut_counter == 5: print(bold("Congratulations! YOU WIN!!!"))
class AttackOfTheOrcs: """Glavna klasa za igru napad orkova Stavite opis metode i parametre (argumenti ili atributi) i što funkcija vraća. """ def __init__(self): self.huts = [] self.player = None def get_occupants(self): """Vraca listu okupanata za sve kucice. Stavite opis metode i parametre (argumenti ili atributi) i što funkcija vraća. """ return [x.get_occupant_type() for x in self.huts] def show_game_mission(self): """Ispis misije igre""" print_bold("Misija:") print(" 1. Bori se s neprijateljem.") print(" 2. Stavi sve kucice pod svoju kontrolu") print("---------------------------------------------------------\n") def _process_user_choice(self): # zasticena metoda """metoda za obradu korisnickog unosa broja kucice Stavite opis metode i parametre (argumenti ili atributi) i što funkcija vraća. """ verifying_choice = True idx = 0 print("Trenutni okupanti: {}".format(self.get_occupants())) while verifying_choice: user_choice = input("Odaberite broj kucice (1-5): ") # hvataj iznimku ako se ne unese broj try: idx = int(user_choice) except ValueError: raise HutError(104) if idx > 5: raise HutError(101) if idx == 0: raise HutError(103) if idx < 0: raise HutError(102) # hvataj iznimku ako se unese neodgovarajuci indeks try: if self.huts[idx - 1].is_acquired: print( "Ova kucica je vec pod vasom kontrolom. Pokusajte ponovno." "<INFO: Ne možete ozdraviti u kucici koja je vec pod vasom kontrolom.>" ) else: verifying_choice = False except IndexError: print('Krivi unos: ', idx) print('Broj mora biti u rasponu 1-5. Pokušaj ponovno!') return idx def _occupy_huts(self): """Metoda koja koristi random funkciju za nastambu kucica s prijatelj, neprijatelj ili 'None'""" for i in range(5): choice_lst = ['neprijatelj', 'prijatelj', None] computer_choice = random.choice(choice_lst) if computer_choice == 'neprijatelj': name = 'neprijatelj-' + str(i + 1) self.huts.append(Hut(i + 1, OrcRider(name))) elif computer_choice == 'prijatelj': name = 'vitez-' + str(i + 1) self.huts.append(Hut(i + 1, Knight(name))) else: self.huts.append(Hut(i + 1, computer_choice)) def setup_game_scenario(self): """stvori igrača i kućice i raspodjeli okupante u kućice.""" self.player = Knight() self._occupy_huts() self.show_game_mission() self.player.show_health(bold=True) def play(self): """Metoda za pokretanje igre. Metoda se pokreće iz glavnog programa. Stavite opis metode, parametre i atribute, seealso i todo. """ self.setup_game_scenario() # inicijalno postavljanje je gotovo ... acquired_hut_counter = 0 while acquired_hut_counter < 5: try: idx = self._process_user_choice() self.player.acquire_hut(self.huts[idx - 1]) if self.player.health_meter <= 0: print_bold("Izgubili ste :(") break if self.huts[idx - 1].is_acquired: acquired_hut_counter += 1 except KeyboardInterrupt: print('nKorisnik je izašao iz igre.') # izadji iz programa sys.exit(1) if acquired_hut_counter == 5: print_bold("Cestitke! Pobijedili ste!!!")
class AttackOfTheOrcs(object): def __init__(self): self.huts = [] self.player = None def _occupy_huts(self, n=5): occupants = ['friend', 'enemy', None] for i in range(n): computer_choose = random.choice(occupants) if computer_choose == 'friend': name = 'friend' + str(i + 1) self.huts.append(Hut(i + 1, Knight(name))) elif computer_choose == 'enemy': name = 'enemy' + str(i + 1) self.huts.append(Hut(i + 1, OrcRider(name))) else: self.huts.append(Hut(i + 1, computer_choose)) def get_hut_occupants(self): return [x.get_occupant_type() for x in self.huts] def show_mission(self): print_bold('MISSION:', end='\n') print('\t1.you see some huts') print('\t2.you must fight with Orc to occupy all the huts') def _play_choose(self): print('\tCurrent occupants:%s' % self.get_hut_occupants()) idx = 0 flag = True while flag: try: idx = int(input('choose the hut from 1-5:')) if idx <= 0: raise IdxTooBigError('not in 1-5!', 103) # raise GameUnitError('not in 1-5!',101) except ValueError as e: print_bold( 'the idx type must be int,but %s. please try again' % e) continue except IdxTooBigError as e: print(e) print(e.error_message) continue try: if self.huts[idx - 1].is_acquired: print( 'The hut which you choose has been required,choose another one' ) else: flag = False except IndexError as e: print_bold( 'index range out ,must be 1-5,but %s. please try again' % e) continue return idx def play(self): self.show_mission() dotted_line() self._occupy_huts() # continu_play=True self.player = Knight() occupant_nums = 0 #已占领数量 while occupant_nums < 5: idx = self._play_choose() self.player.acquire_hut(self.huts[idx - 1]) if self.player.health_meter <= 0: print('You lost:(better luck next time') break if self.huts[idx - 1].is_acquired: occupant_nums += 1 if occupant_nums == 5: print_bold('\nCongratulation! you win')