Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- #--Список задач:
- #[x] Переделать статистику для увеличение функциональности
- #[x] Смена имени компьютера при каждом цикле игры
- #[x] Доделать интерфейс
- # - Подогнать под pep8 и pep257
- # - Написать комментарии
- #[x] Запустить и проверить работоспособность
- class mechanics:
- def restart(self):
- human.health.set()
- pc.health.set()
- stats.set()
- pc.name = pc.choose_name()
- self.whose_move = random.choice([0, 1])
- self.move_count = 1
- show.start_game()
- def run(self):
- show.move_number()
- if self.whose_move % 2 == 0:
- moves = {
- 'hit' : human.health.decrease,
- 'hard_hit' : human.health.decrease,
- 'heal' : pc.health.increase
- }
- action = pc.think()
- value = pc.act(action)
- stats.add('pc', hits=1)
- characters = [pc, human]
- else:
- moves = {
- 'hit' : pc.health.decrease,
- 'hard_hit' : pc.health.decrease,
- 'heal' : human.health.increase
- }
- while True:
- show.move_hint()
- actions_map = {
- 'q' : 'hit',
- 'w' : 'hard_hit',
- 'e' : 'heal'
- }
- action = actions_map.get(input().lower())
- if action in ['hit', 'hard_hit', 'heal']:
- break
- value = human.act(action)
- stats.add('human', hits=1)
- characters = [human, pc]
- moves.get(action)(value)
- show.move(action, value, characters[0], characters[1])
- if human.health.value == 0:
- show.total(pc)
- elif pc.health.value == 0:
- show.total(human)
- self.move_count += 1
- self.whose_move += 1
- class statistics:
- def set(self):
- self.data = {'human' : {
- 'damaged' : 0,
- 'healed' : 0,
- 'hits' : 0
- },
- 'pc' : {
- 'damaged' : 0,
- 'healed' : 0,
- 'hits' : 0
- }
- }
- def add(self, who, **add_value):
- for key, value in add_value.items():
- self.data[who][key] += value
- class interface:
- def start_game(self):
- print('\n========== Игра началась =========='
- f'\n {pc.name}'
- '\n VS\n'
- f' {human.name.title()}'
- '\n===================================')
- def move_number(self):
- print(f'\n --== Ход #{game.move_count} ==--')
- def move_hint(self):
- print('\n ---- Выберите ход: ----'
- '\n[q]Удар [w]Сильный удар [e]Лечение')
- def move(self, action, value, active_player, player):
- actions = {
- 'hit' : ['ударил', 'отняв при этом'],
- 'hard_hit' : ['замахнулся и ударил', 'нанеся урон'],
- 'heal' : ['не тронул', 'восстановив в это время']
- }
- arrows = {
- 'hit' : ['==', '>>'],
- 'hard_hit' : ['>>', '>>'],
- 'heal' : ['<<', ' ']
- }
- print(f'\n {active_player.name} {actions.get(action)[0]} '
- f'{player.name},\n {actions.get(action)[1]} {value}HP')
- print(f'\n {active_player.name}[{active_player.health.value}] '
- f'{arrows.get(action)[0]}[{value}]{arrows.get(action)[1]} '
- f'{player.name}[{player.health.value}]')
- def total(self, winner):
- final_stats = stats.data[winner.health.identity]
- print("\n\n==================================="
- f"\n Победил {winner.name},"
- f"\n он нанес {final_stats['damaged']} урона за {final_stats['hits']} ударов"
- f"\n и восстановив {final_stats['healed']} HP"
- "\n===================================")
- class player:
- # Определение имени и параметров персонажа.
- def __init__(self, identification, name_input=''):
- self.name = name_input
- self.health = self.health()
- self.health.identity = identification
- # Возвращает значение урона или регенерации, выбранное
- # случайным образом в определенном диапазоне.
- def act(self, action):
- range_map = {
- 'hit' : (18, 25),
- 'hard_hit' : (10, 35),
- 'heal' : (18, 25)
- }
- return random.randrange(range_map.get(action)[0],
- range_map.get(action)[1])
- #===
- class health():
- def set(self):
- self.value = 100
- def increase(self, damage):
- self.value = self.value + damage
- self.normalize()
- stats.add(self.identity, healed=damage)
- def decrease(self, damage):
- self.value = self.value - damage
- self.normalize()
- stats.add(self.identity, damaged=damage)
- def normalize(self):
- if self.value > 100: self.value = 100
- elif self.value < 0: self.value = 0
- class player_ai(player):
- # Выбирает один из трех вариантов, повышая вес варианта "heal",
- # когда значение здоровья ниже или равно 35.
- def think(self):
- if self.health.value <= 35:
- return random.choices([
- 'hit',
- 'hard_hit',
- 'heal'
- ], weights=[1, 1, 2])[0]
- else:
- return random.choices([
- 'hit',
- 'hard_hit',
- 'heal'
- ], weights=[1, 1, 1])[0]
- def choose_name(self):
- names = [
- 'Stan',
- 'Francine',
- 'Hayley',
- 'Steve',
- 'Roger',
- 'Klaus',
- 'Jeff'
- ]
- return random.choice(names)
- game = mechanics()
- show = interface()
- stats = statistics()
- human = player('human', input("Введите имя: "))
- pc = player_ai('pc')
- while True:
- game.restart()
- while human.health.value > 0 and pc.health.value > 0:
- game.run()
- if input("\nСыграть еще раз или выйти?[r, any]: ").lower() == 'r':
- continue
- break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement