Advertisement
morimoto_ltd

game_ver2.5.py

Sep 29th, 2019
422
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.51 KB | None | 0 0
  1. import random
  2.  
  3.  
  4. # The main class that controls the game.
  5. # Other classes initializing in him
  6. # and most of them are communicating there.
  7. class game:
  8.     def __init__(self):
  9.         self.show = interface()
  10.         self.stats = statistics()
  11.         self.human = player('human', input("Введите имя: "))
  12.         self.pc = playerAi('pc')
  13.  
  14.     # A function that resets the values of the game
  15.     # and prints a start message. It needs for restarting
  16.     # with saving player name variable.
  17.     def reset(self):
  18.         self.human.health.set()
  19.         self.pc.health.set()
  20.         self.stats.set()
  21.         self.pc.name = self.pc.choose_name()
  22.         self.whose_move = random.choice([0, 1])
  23.         self.move_count = 1
  24.         self.show.start_game(self.pc.name, self.human.name)
  25.  
  26.     # A main cycle of the game.
  27.     # Here it is determined whose move is now,
  28.     # using the corresponding variable, on even
  29.     # numbers of which -- pc goes, and on odd -- people.
  30.     #
  31.     # It operates with functions from other classes,
  32.     # determining what action the character will perform
  33.     # and how much damage it will cause,
  34.     # displaying the corresponding messages.
  35.     #
  36.     # After the health value of one of the characters,
  37.     # it displays a results message.
  38.     def moves(self):
  39.         self.show.next_move(self.move_count)
  40.         if self.whose_move % 2 == 0:
  41.             moves = {
  42.                      'hit': self.human.health.decrease,
  43.                      'hard_hit': self.human.health.decrease,
  44.                      'heal': self.pc.health.increase
  45.                      }
  46.             action = self.pc.think()
  47.             value = self.pc.act(action)
  48.             self.stats.add('pc', action, value)
  49.             characters = [self.pc, self.human]
  50.         else:
  51.             moves = {
  52.                      'hit': self.pc.health.decrease,
  53.                      'hard_hit': self.pc.health.decrease,
  54.                      'heal': self.human.health.increase
  55.                      }
  56.             while True:
  57.                 self.show.move_hint()
  58.                 actions_map = {
  59.                                'q': 'hit',
  60.                                'w': 'hard_hit',
  61.                                'e': 'heal'
  62.                                }
  63.                 action = actions_map.get(input().lower())
  64.                 if action in ['hit', 'hard_hit', 'heal']:
  65.                     break
  66.             value = self.human.act(action)
  67.             self.stats.add('human', action, value)
  68.             characters = [self.human, self.pc]
  69.         moves.get(action)(value)
  70.         self.show.move(action, value, characters[0], characters[1])
  71.         if self.human.health.value == 0:
  72.             self.show.total(self.pc, self.stats)
  73.         elif self.pc.health.value == 0:
  74.             self.show.total(self.human, self.stats)
  75.         self.move_count += 1
  76.         self.whose_move += 1
  77.  
  78.     # A cycle, that runs the game, and ends when
  79.     # one of the characters goes out of health.
  80.     def run(self):
  81.         self.reset()
  82.         while self.human.health.value > 0 and self.pc.health.value > 0:
  83.             self.moves()
  84.  
  85.  
  86. # Class, that collects the stats of the characters.
  87. # It creates a Nested Dictionary and put the stats in there.
  88. class statistics:
  89.     # Create or reset the stats dictionary.
  90.     def set(self):
  91.         self.data = {'human': {
  92.                                'damaged': 0,
  93.                                'healed': 0,
  94.                                'hits': 0
  95.                                },
  96.                      'pc': {
  97.                             'damaged': 0,
  98.                             'healed': 0,
  99.                             'hits': 0
  100.                             }
  101.                      }
  102.  
  103.     # Adds values to the keys in the stats dictionary
  104.     # and counts a number of hits.
  105.     def add(self, who, action, value):
  106.         mapping = {
  107.                    'hit': 'damaged',
  108.                    'hard_hit': 'damaged',
  109.                    'heal': 'healed'
  110.                    }
  111.         self.data[who]['hits'] += 1
  112.         self.data[who][mapping.get(action)] += value
  113.  
  114.  
  115. # Class, that helps to display the messages.
  116. class interface:
  117.     def start_game(self, pc_name, human_name):
  118.         print('\n========== Игра началась =========='
  119.               f'\n     {pc_name}'
  120.               '\n                VS\n'
  121.               f'                       {human_name.title()}'
  122.               '\n===================================')
  123.  
  124.     def next_move(self, move_number):
  125.         print(f'\n         --== Ход #{move_number} ==--')
  126.  
  127.     def move_hint(self):
  128.         print('\n      ---- Выберите ход: ----'
  129.               '\n[q]Удар [w]Сильный удар [e]Лечение')
  130.  
  131.     def move(self, action, value, active_player, player):
  132.         actions = {
  133.                    'hit': ['ударил', 'отняв при этом'],
  134.                    'hard_hit': ['замахнулся и ударил', 'нанеся урон'],
  135.                    'heal': ['не тронул', 'восстановив в это время']
  136.                    }
  137.         arrows = {
  138.                   'hit': ['==', '>>'],
  139.                   'hard_hit': ['>>', '>>'],
  140.                   'heal': ['<<', '  ']
  141.                   }
  142.         print(f'\n   {active_player.name} {actions.get(action)[0]} '
  143.               f'{player.name},\n   {actions.get(action)[1]} {value}HP')
  144.         print(f'\n {active_player.name}[{active_player.health.value}] '
  145.               f'{arrows.get(action)[0]}[{value}]{arrows.get(action)[1]} '
  146.               f'{player.name}[{player.health.value}]')
  147.  
  148.     def total(self, winner, statistics):
  149.         stats = statistics.data[winner.health.identity]
  150.         print("\n\n==================================="
  151.               f"\n  Победил {winner.name},"
  152.               f"\n  он нанес {stats['damaged']} урона "
  153.               f"за {stats['hits']} ударов"
  154.               f"\n  и восстановив {stats['healed']} HP"
  155.               "\n===================================")
  156.  
  157.  
  158. # A class for human characters.
  159. # Providing functions, that makes the character act.
  160. class player:
  161.     def __init__(self, identification, name_input=''):
  162.         self.name = name_input
  163.         self.health = self.health()
  164.         self.health.identity = identification
  165.  
  166.     # Returns a value of the damage.
  167.     def act(self, action):
  168.         range_map = {
  169.                      'hit': (18, 25),
  170.                      'hard_hit': (10, 35),
  171.                      'heal': (18, 25)
  172.                      }
  173.         return random.randrange(range_map.get(action)[0],
  174.                                 range_map.get(action)[1])
  175.  
  176.     # An inner class of the 'player' class.
  177.     # Creates and performs operations with 'health' variable.
  178.     class health():
  179.         def set(self):
  180.             self.value = 100
  181.  
  182.         def increase(self, damage):
  183.             self.value = self.value + damage
  184.             self.normalize()
  185.  
  186.         def decrease(self, damage):
  187.             self.value = self.value - damage
  188.             self.normalize()
  189.  
  190.         def normalize(self):
  191.             if self.value > 100: self.value = 100
  192.             elif self.value < 0: self.value = 0
  193.  
  194.  
  195. # Child class to the player.
  196. # Inherits properties of the parent class and adds the ai.
  197. class playerAi(player):
  198.     # Randomly chooses one of three options,
  199.     # increasing the weight of the 'heal' option
  200.     # when the health value is below or equal to 35.
  201.     def think(self):
  202.         if self.health.value <= 35:
  203.             return random.choices([
  204.                                    'hit',
  205.                                    'hard_hit',
  206.                                    'heal'
  207.                                    ], weights=[1, 1, 2])[0]
  208.         else:
  209.             return random.choices([
  210.                                    'hit',
  211.                                    'hard_hit',
  212.                                    'heal'
  213.                                    ], weights=[1, 1, 1])[0]
  214.  
  215.     # Randomely choose a name from the list.
  216.     def choose_name(self):
  217.         names = [
  218.                  'Stan',
  219.                  'Francine',
  220.                  'Hayley',
  221.                  'Steve',
  222.                  'Roger',
  223.                  'Klaus',
  224.                  'Jeff'
  225.                  ]
  226.         return random.choice(names)
  227.  
  228.  
  229. if __name__ == '__main__':
  230.     game = game()
  231.     while True:
  232.         game.run()
  233.         if input("\nСыграть еще или выйти?[r, any]: ").lower() == 'r':
  234.             continue
  235.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement