Advertisement
morimoto_ltd

game_ver2.3.py

Sep 29th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.44 KB | None | 0 0
  1. import random
  2.  
  3. #--Список задач:
  4. #[x] Переделать статистику для увеличение функциональности
  5. #[x] Смена имени компьютера при каждом цикле игры
  6. #[x] Доделать интерфейс
  7. # -  Подогнать под pep8 и pep257
  8. # -  Написать комментарии
  9. #[x] Запустить и проверить работоспособность
  10.  
  11. class mechanics:
  12.     def restart(self):
  13.         human.health.set()
  14.         pc.health.set()
  15.         stats.set()
  16.         pc.name = pc.choose_name()
  17.         self.whose_move = random.choice([0, 1])
  18.         self.move_count = 1
  19.         show.start_game()
  20.  
  21.     def run(self):
  22.             show.move_number()
  23.             if self.whose_move % 2 == 0:
  24.                 moves = {
  25.                          'hit' : human.health.decrease,
  26.                          'hard_hit' : human.health.decrease,
  27.                          'heal' : pc.health.increase
  28.                          }
  29.                 action = pc.think()
  30.                 value = pc.act(action)
  31.                 stats.add('pc', hits=1)
  32.                 characters = [pc, human]
  33.             else:
  34.                 moves = {
  35.                          'hit' : pc.health.decrease,
  36.                          'hard_hit' : pc.health.decrease,
  37.                          'heal' : human.health.increase
  38.                          }
  39.                 while True:
  40.                     show.move_hint()
  41.                     actions_map = {
  42.                                    'q' : 'hit',
  43.                                    'w' : 'hard_hit',
  44.                                    'e' : 'heal'
  45.                                    }
  46.                     action = actions_map.get(input().lower())
  47.                     if action in ['hit', 'hard_hit', 'heal']:
  48.                         break
  49.                 value = human.act(action)
  50.                 stats.add('human', hits=1)
  51.                 characters = [human, pc]
  52.             moves.get(action)(value)
  53.             show.move(action, value, characters[0], characters[1])
  54.             if human.health.value == 0:
  55.                 show.total(pc)
  56.             elif pc.health.value == 0:
  57.                 show.total(human)
  58.             self.move_count += 1
  59.             self.whose_move += 1
  60.  
  61. class statistics:
  62.     def set(self):
  63.         self.data = {'human' : {
  64.                                  'damaged' : 0,
  65.                                  'healed' : 0,
  66.                                  'hits' : 0
  67.                                  },
  68.                       'pc' : {
  69.                               'damaged' : 0,
  70.                               'healed' : 0,
  71.                               'hits' : 0
  72.                               }
  73.                       }
  74.  
  75.     def add(self, who, **add_value):
  76.         for key, value in add_value.items():
  77.             self.data[who][key] += value
  78.  
  79. class interface:
  80.     def start_game(self):
  81.         print('\n========== Игра началась =========='
  82.              f'\n     {pc.name}'
  83.               '\n                VS\n'
  84.              f'                       {human.name.title()}'
  85.               '\n===================================')
  86.  
  87.     def move_number(self):
  88.         print(f'\n         --== Ход #{game.move_count} ==--')
  89.  
  90.     def move_hint(self):
  91.         print('\n      ---- Выберите ход: ----'
  92.               '\n[q]Удар [w]Сильный удар [e]Лечение')
  93.  
  94.     def move(self, action, value, active_player, player):
  95.         actions = {
  96.                    'hit' : ['ударил', 'отняв при этом'],
  97.                    'hard_hit' : ['замахнулся и ударил', 'нанеся урон'],
  98.                    'heal' : ['не тронул', 'восстановив в это время']
  99.                    }
  100.         arrows = {
  101.                   'hit' : ['==', '>>'],
  102.                   'hard_hit' : ['>>', '>>'],
  103.                   'heal' : ['<<', '  ']
  104.                   }
  105.         print(f'\n   {active_player.name} {actions.get(action)[0]} '
  106.               f'{player.name},\n   {actions.get(action)[1]} {value}HP')
  107.         print(f'\n {active_player.name}[{active_player.health.value}] '
  108.               f'{arrows.get(action)[0]}[{value}]{arrows.get(action)[1]} '
  109.               f'{player.name}[{player.health.value}]')
  110.  
  111.     def total(self, winner):
  112.         final_stats = stats.data[winner.health.identity]
  113.         print("\n\n==================================="
  114.              f"\n  Победил {winner.name},"
  115.              f"\n  он нанес {final_stats['damaged']} урона за {final_stats['hits']} ударов"
  116.              f"\n  и восстановив {final_stats['healed']} HP"
  117.               "\n===================================")
  118.  
  119. class player:
  120. # Определение имени и параметров персонажа.
  121.     def __init__(self, identification, name_input=''):
  122.         self.name = name_input
  123.         self.health = self.health()
  124.         self.health.identity = identification
  125.  
  126. # Возвращает значение урона или регенерации, выбранное
  127. # случайным образом в определенном диапазоне.
  128.     def act(self, action):
  129.         range_map = {
  130.                      'hit' : (18, 25),
  131.                      'hard_hit' : (10, 35),
  132.                      'heal' : (18, 25)
  133.                      }
  134.         return random.randrange(range_map.get(action)[0],
  135.                                 range_map.get(action)[1])
  136.  
  137. #===
  138.     class health():
  139.         def set(self):
  140.             self.value = 100
  141.  
  142.         def increase(self, damage):
  143.             self.value = self.value + damage
  144.             self.normalize()
  145.             stats.add(self.identity, healed=damage)
  146.  
  147.         def decrease(self, damage):
  148.             self.value = self.value - damage
  149.             self.normalize()
  150.             stats.add(self.identity, damaged=damage)
  151.  
  152.         def normalize(self):
  153.             if self.value > 100: self.value = 100
  154.             elif self.value < 0: self.value = 0
  155.  
  156. class player_ai(player):
  157. # Выбирает один из трех вариантов, повышая вес варианта "heal",
  158. # когда значение здоровья ниже или равно 35.
  159.     def think(self):
  160.         if self.health.value <= 35:
  161.             return random.choices([
  162.                                    'hit',
  163.                                    'hard_hit',
  164.                                    'heal'
  165.                                    ], weights=[1, 1, 2])[0]
  166.         else:
  167.             return random.choices([
  168.                                    'hit',
  169.                                    'hard_hit',
  170.                                    'heal'
  171.                                    ], weights=[1, 1, 1])[0]
  172.  
  173.     def choose_name(self):
  174.         names = [
  175.                  'Stan',
  176.                  'Francine',
  177.                  'Hayley',
  178.                  'Steve',
  179.                  'Roger',
  180.                  'Klaus',
  181.                  'Jeff'
  182.                  ]
  183.         return random.choice(names)
  184.  
  185. game = mechanics()
  186. show = interface()
  187. stats = statistics()
  188. human = player('human', input("Введите имя: "))
  189. pc = player_ai('pc')
  190.  
  191. while True:
  192.     game.restart()
  193.     while human.health.value > 0 and pc.health.value > 0:
  194.         game.run()
  195.     if input("\nСыграть еще раз или выйти?[r, any]: ").lower() == 'r':
  196.         continue
  197.     break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement