|
| 1 | +import random |
| 2 | + |
| 3 | +# Define player and enemy classes |
| 4 | + |
| 5 | +class Character: |
| 6 | + |
| 7 | + def __init__(self, name, max_health, attack): |
| 8 | + |
| 9 | + self.name = name |
| 10 | + |
| 11 | + self.max_health = max_health |
| 12 | + |
| 13 | + self.current_health = max_health |
| 14 | + |
| 15 | + self.attack = attack |
| 16 | + |
| 17 | + def take_damage(self, damage): |
| 18 | + |
| 19 | + self.current_health -= damage |
| 20 | + |
| 21 | + if self.current_health < 0: |
| 22 | + |
| 23 | + self.current_health = 0 |
| 24 | + |
| 25 | + def is_alive(self): |
| 26 | + |
| 27 | + return self.current_health > 0 |
| 28 | + |
| 29 | + def attack_target(self, target): |
| 30 | + |
| 31 | + damage = random.randint(1, self.attack) |
| 32 | + |
| 33 | + target.take_damage(damage) |
| 34 | + |
| 35 | + print(f"{self.name} attacks {target.name} for {damage} damage.") |
| 36 | + |
| 37 | +class Player(Character): |
| 38 | + |
| 39 | + def __init__(self, name, max_health, attack, potions): |
| 40 | + |
| 41 | + super().__init__(name, max_health, attack) |
| 42 | + |
| 43 | + self.potions = potions |
| 44 | + |
| 45 | + def use_potion(self): |
| 46 | + |
| 47 | + if self.potions > 0: |
| 48 | + |
| 49 | + self.current_health += 20 |
| 50 | + |
| 51 | + self.potions -= 1 |
| 52 | + |
| 53 | + print(f"{self.name} drinks a health potion and restores 20 health.") |
| 54 | + |
| 55 | + else: |
| 56 | + |
| 57 | + print("You don't have any potions left!") |
| 58 | + |
| 59 | +class Enemy(Character): |
| 60 | + |
| 61 | + pass |
| 62 | + |
| 63 | +# Define the game loop |
| 64 | + |
| 65 | +def game_loop(): |
| 66 | + |
| 67 | + player = Player("Player", 100, 20, 3) |
| 68 | + |
| 69 | + enemy = Enemy("Enemy", 50, 10) |
| 70 | + |
| 71 | + print("You have encountered an enemy! Prepare to battle!") |
| 72 | + |
| 73 | + while player.is_alive() and enemy.is_alive(): |
| 74 | + |
| 75 | + action = input("What do you want to do? (attack, potion) ") |
| 76 | + |
| 77 | + if action == "attack": |
| 78 | + |
| 79 | + player.attack_target(enemy) |
| 80 | + |
| 81 | + if enemy.is_alive(): |
| 82 | + |
| 83 | + enemy.attack_target(player) |
| 84 | + |
| 85 | + elif action == "potion": |
| 86 | + |
| 87 | + player.use_potion() |
| 88 | + |
| 89 | + enemy.attack_target(player) |
| 90 | + |
| 91 | + else: |
| 92 | + |
| 93 | + print("Invalid action! Try again.") |
| 94 | + |
| 95 | + if player.is_alive(): |
| 96 | + |
| 97 | + print("Congratulations! You have defeated the enemy!") |
| 98 | + |
| 99 | + else: |
| 100 | + |
| 101 | + print("You have been defeated. Game over.") |
| 102 | + |
| 103 | +# Start the game |
| 104 | + |
| 105 | +game_loop() |
| 106 | + |
0 commit comments