Search code examples
pythonpython-2.7python-idle

Python text game health bar


I'm making a text adventure I'm using

def do_health
    print health,"/ 200"

to display health but I want to convert it to a percentage and print something like

|----------          |
         50%

depending on what percentage of health the player has left but I can't find anything elsewhere on making a health bar for idle.

Thanks in advance.


Solution

  • All that needs to be done is a few simple conversion to convert your current health into a number of dashes and define the max number of dashes (20 in this case: healthDashes) to be equivalent to your max health (200: maxHealth).

    Consider you have 80 health left. So for example if we take healthDashes(20)/maxHealth(200) you get 10, this is the value that we divide our health by to convert it into the number of dashes that we want. You can then take your current health being 80 and the number of dashes is: 80/10 => 8 dashes. The percentage is straight forward: (health(80)/maxHealth(200))*100 = > 40 percent.

    Now in python you just apply that lodic above and you will get:

    health = 80.0      # Current Health (float so division doesn't make an int)
    maxHealth = 200    # Max Health
    healthDashes = 20  # Max Displayed dashes
    
    def do_health():
      dashConvert = int(maxHealth/healthDashes)            # Get the number to divide by to convert health to dashes (being 10)
      currentDashes = int(health/dashConvert)              # Convert health to dash count: 80/10 => 8 dashes
      remainingHealth = healthDashes - currentDashes       # Get the health remaining to fill as space => 12 spaces
    
      healthDisplay = '-' * currentDashes                  # Convert 8 to 8 dashes as a string:   "--------"
      remainingDisplay = ' ' * remainingHealth             # Convert 12 to 12 spaces as a string: "            "
      percent = str(int((health/maxHealth)*100)) + "%"     # Get the percent as a whole number:   40%
    
      print("|" + healthDisplay + remainingDisplay + "|")  # Print out textbased healthbar
      print("         " + percent)                         # Print the percent
    

    If you call the method you get the result:

    do_health()
    >
    |--------            |
             40%
    

    Here are a few more examples with changing the value of health:

    |----------          |  # health = 100
             50%
    |--------------------|  # health = 200
             100%
    |                    |  # health = 0
             0%
    |------              |  # health = 68
             34%