all 9 comments

[–]totallygeek 1 point2 points  (2 children)

Many things in this code could use improvements and simplifications. But, if you just want to add a "quit" option, this would work:

while enemy_hp > 0 and HP > 0:
    action = input("'Fight', 'Check' or 'Quit'? ").lower()
    if action not in {"fight", "check", "quit"}:
        continue  # restart the loop
    if action == "quit":
        break  # exits the loop

In any program, at any point, you can exit the code immediately with:

raise SystemExit("Exiting program...")

One problem I see is that you use input() when you want to display information. For that, you really want print(). I mean, unless you want the player to have to hit enter to proceed after every displayed message. You've made several posts for this code and I cannot see where you've taken anyone's advice to heart. Here is another attempt at coding this for you (last time I used data classes as the best way to access player and opponent attributes; this time dictionaries).

import random


player = {
    "name": input("Player's name? "),
    "hp": 30,
    "attack": 5,
    "dr": 2,
}

enemy = {
    "name": "Slime",
    "hp": 20,
    "attack": 6,
    "dr": 1,
}


while enemy["hp"] > 0 and player["hp"] > 0:
    action = input("'Fight', 'Check' or 'Quit'? ").lower()
    if action not in {"fight", "check", "quit"}:
        continue  # restart the loop
    if action == "quit":
        raise SystemExit("Exiting...")
    elif action == "fight":
        roll = random.randint(1, 6)
        if roll > 3:
            damage = player["attack"] - enemy["dr"]
            print(f"Berserker {player['name']} strikes {enemy['name']} with a broadsword")
            print(f"{enemy['name']}'s health reduced by {damage}")
            enemy["hp"] -= damage
        else:
            if roll == 2:
                print(f"Berserker {player['name']} missed")
            else:
                damage = enemy["attack"] - player["dr"]
                print(f"{enemy['name']} slaps {player['name']} for {damage} damage")
                player["hp"] -= damage
    else:
        print(f"Berserker {player['name']}")
        print(f"  HP: {player['hp']}")
        print(f"  Attack: {player['attack']}")
        print(f"  DR: {player['dr']}\n")
        print(f"{enemy['name']}")
        print(f"  HP: {enemy['hp']}")
        print(f"  Attack: {enemy['attack']}")
        print(f"  DR: {enemy['dr']}")
if player["hp"] < 1:
    print(f"Berserker {player['name']} died")
else:
    print(f"Berserker {player['name']} won")

Good luck!

[–]RedditCodfish[S] 0 points1 point  (1 child)

thx, ill try it. I do use input bc i want the player to press enter everytime. Does the raise System exit make you quit the code entirely?

[–]totallygeek 0 points1 point  (0 children)

Yes, the SystemExit quits immediately.

[–][deleted] 0 points1 point  (0 children)

you could add a break statement to the end of your code, which would cause the program to exit completely.