Python 文字游戏血条

Python text game health bar

我正在使用我的文字冒险

def do_health
    print health,"/ 200"

显示健康,但我想将其转换为百分比并打印类似

的内容
|----------          |
         50%

取决于玩家剩余的生命值百分比,但我在其他地方找不到关于为闲置状态制作生命值条的任何内容。

提前致谢。

所有需要做的只是一些简单的转换,将您当前的健康状况转换为多个破折号并定义破折号的最大数量(在本例中为 20healthDashes) 等于你的最大生命值 (200: maxHealth).

考虑您还剩 80 生命值。因此,例如,如果我们取 healthDashes(20)/maxHealth(200) 你会得到 10,这是我们将健康值除以将其转换为我们想要的破折号数的值。然后,您可以将当前的 health 设为 80,破折号的数量为:80/10 => 8 dashes。百分比是直截了当的:(health(80)/maxHealth(200))*100 = > 40 percent.

现在在 python 中,您只需应用上面的 lodic,您将得到:

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

如果您调用该方法,您将得到结果:

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

这里有几个改变 health 值的例子:

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