Untitled

mail@pastecode.io avatarunknown
python
5 days ago
2.2 kB
2
Indexable
Never
import random
import time

# Define the Player class
class Player:
    def __init__(self, name, max_health, attack):
        self.name = name
        self.max_health = max_health
        self.health = max_health
        self.attack = attack

    def take_damage(self, damage):
        self.health -= damage
        if self.health < 0:
            self.health = 0

    def is_alive(self):
        return self.health > 0

    def attack_enemy(self, enemy):
        damage = random.randint(5, self.attack)
        enemy.take_damage(damage)
        print(f"{self.name} attacks {enemy.name} for {damage} damage!")

    def heal(self):
        healing_amount = random.randint(10, 20)
        self.health += healing_amount
        if self.health > self.max_health:
            self.health = self.max_health
        print(f"{self.name} heals for {healing_amount} HP!")

# Create two player objects
player1 = Player("Player 1", 100, 20)
player2 = Player("Computer", 100, 20)

# Main game loop
while player1.is_alive() and player2.is_alive():
    print("\n" + "=" * 30)
    print(f"{player1.name} (Health: {player1.health})")
    print(f"{player2.name} (Health: {player2.health})")
    print("=" * 30)

    # Player 1's turn:
    print(f"{player1.name}'s turn:")
    print("1. Attack")
    print("2. Heal")
    choice = input("Enter your choice (1/2): ")

    if choice == "1":
        player1.attack_enemy(player2)
    elif choice == "2":
        player1.heal()
    else:
        print("Invalid choice! Try again.")
        continue

    # Check if Player 2's health is below zero
    if not player2.is_alive():
        print(f"{player1.name} wins!")
        break

    # Player 2's turn (controlled by the computer)
    time.sleep(1)  # Simulate computer "thinking" for a moment
    computer_choice = random.choice(["1", "2"])  # Randomly choose between attack and heal

    if computer_choice == "1":
        player2.attack_enemy(player1)
    elif computer_choice == "2":
        player2.heal()

    # Check if Player 1's health is below zero
    if not player1.is_alive():
        print(f"{player2.name} wins!")
        break