2

I am trying to make a healthbar in pygame and it is supposed to show in percent. The formula that I'm using is (lives/mlives)*100, mlives stands for max lives.

When the game begins, player has 3 lives to start with. Each time the shielding gets down to 0 or less, -1 is removed from lives.
So on the first run everything works perfectly fine. But when -1 if removed from lives the health bar shows 0 and i have tried to print the formula on terminal without multiplying it with 100 to see what it would show when lives / mlives.

now when player has 3 lives the formula gives 1.0 and that is 100%
when the player has 2 lives the formula gives 0.0 instead of 0.66 which is 66%

player has 3 lives
enter image description here enter image description here

player has 2 lives
enter image description here enter image description here

game.py -- funciton name is draw_health_bar

#!/usr/bin/python
import os, sys, player, enemy, config, random
from os import path

try:
    import pygame
    from pygame.locals import *
except ImportError, err:
    print 'Could not load module %s' % (err)
    sys.exit(2)

# main variables
FPS, BGIMG = 30, 'FlappyTrollbg.jpg'

# initialize game
pygame.init()
screen = pygame.display.set_mode((config.WIDTH,config.HEIGHT))
pygame.display.set_caption("FlappyTroll - Python2.7")

# background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((255,255,255))

img_dir = path.join(path.dirname(__file__), 'img')
class Background(pygame.sprite.Sprite):
    def __init__(self, image_file, location):
        pygame.sprite.Sprite.__init__(self)
        self.width = config.WIDTH
        self.height = config.HEIGHT
        self.image = pygame.image.load(path.join(img_dir,image_file)).convert_alpha()
        self.image = pygame.transform.scale(self.image,(self.width,self.height))
        self.rect = self.image.get_rect()
        #self.rect.left, self.rect.top = location
        self.rect.x, self.rect.y = location
        self.speedx = 5
    def update(self):
        self.rect.x -= self.speedx
        if self.rect.x <= -config.WIDTH:
            self.rect.x = config.WIDTH

def draw_shield_bar(surf, x, y, percent):
    if percent <= 0:
        percent = 0
    bar_length = 100
    bar_height = 10
    fill = (percent / 100) * bar_length
    bar_outline = pygame.Rect(x,y,bar_length,bar_height)
    bar_filled = pygame.Rect(x,y, fill, bar_height)
    pygame.draw.rect(surf, config.green, bar_filled)
    pygame.draw.rect(surf, config.white, bar_outline, 2)

def draw_health_bar(surf, x, y, percent):
    bar_length = 100
    bar_height = 10

    fill = float(percent) * bar_length
    bar_outline = pygame.Rect(x,y,bar_length,bar_height)
    bar_filled = pygame.Rect(x,y, fill, bar_height)
    pygame.draw.rect(surf, config.red, bar_filled)
    pygame.draw.rect(surf, config.white, bar_outline, 2)

def draw_text(surf, text, size, x, y):
        font_ = pygame.font.SysFont("Arial", size)
        show_kills = font_.render(text, True, config.white)
        surf.blit(show_kills, (x, y))
# blitting
screen.blit(background,(0,0))
pygame.display.flip()

# clock for FPS settings
clock = pygame.time.Clock()
def newSprite(group, obj):
    group.add(obj)

def main():
    all_sprites = pygame.sprite.Group()
    bgs = pygame.sprite.Group()
    creature = pygame.sprite.Group()
    attack = pygame.sprite.Group()
    eattack = pygame.sprite.Group()

    bgs.add(Background(BGIMG, [0,0]))
    bgs.add(Background(BGIMG, [config.WIDTH,0]))
    troll = player.FlappyTroll()
    creature.add(troll)

    for i in range(0,4):
        newSprite(all_sprites, enemy.TrollEnemy())
    # variable for main loop
    running = True
    # init umbrella
    # event loop
    while running:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        for e in all_sprites:
            if (pygame.time.get_ticks() - e.starttime) >= e.delay:
                newEAtk = enemy.EnemyAttack(e.rect.x, e.rect.y)
                eattack.add(newEAtk)
                e.starttime = pygame.time.get_ticks()

        keys = pygame.key.get_pressed()
        if (keys[pygame.K_SPACE]) and (pygame.time.get_ticks() - troll.starttime) >= troll.delay:
            newAtk = player.FlappyAttack(troll.rect.x, troll.rect.y)
            attack.add(newAtk)
            troll.starttime = pygame.time.get_ticks()

        b_gets_hit = pygame.sprite.groupcollide(eattack, attack, True, True)
        p_gets_hit_eatk = pygame.sprite.groupcollide(eattack, creature, True, False)
        gets_hit = pygame.sprite.groupcollide(all_sprites, attack, True, True)
        p_gets_hit = pygame.sprite.groupcollide(all_sprites, creature, True, False)
        if gets_hit or p_gets_hit:
            newEnemy = enemy.TrollEnemy()
            newSprite(all_sprites, newEnemy)

        for p in creature:
            if p_gets_hit or p_gets_hit_eatk:
                troll.shield -= random.randint(1,5)*1.5

        if troll.shield <= 0:
            troll.lives -= 1
            troll.shield = 100

        if troll.lives == 0:
            print "#--- GAME OVER ---#"
            break

        screen.fill([255, 255, 255])
        # update
        bgs.update()
        all_sprites.update()
        creature.update()
        attack.update()
        eattack.update()
        # draw
        bgs.draw(screen)
        all_sprites.draw(screen)
        creature.draw(screen)
        attack.draw(screen)
        eattack.draw(screen)

        draw_shield_bar(screen, 5, 5, troll.shield)
        draw_health_bar(screen, 5, 20, (troll.lives/troll.mlives))
        draw_text(screen, ("Lives: "+str(troll.lives)), 20, (config.WIDTH / 2), 0)
        print float(troll.lives/troll.mlives)

        # flip the table
        pygame.display.flip()
    pygame.quit()

if __name__ == '__main__':
    main()

player.py (object name is Troll in game.py)

import pygame, config
from pygame.locals import *
from os import path
from random import randint

img_dir = path.join(path.dirname(__file__), 'img')
class FlappyTroll(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.width = 64
        self.height = 64
        self.image = pygame.image.load(path.join(img_dir,"flappytroll.png")).convert_alpha()
        self.image = pygame.transform.scale(self.image,(self.width,self.height))
        self.rect = self.image.get_rect()
        self.rect.x = self.width*2
        self.rect.y = config.HEIGHT/2-self.height
        self.speedy = 5
        self.starttime = pygame.time.get_ticks()
        self.delay = 500
        self.shield = 100
        self.lives = 3
        self.mlives = 3

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP]:
            self.rect.y -= self.speedy*2
        elif self.rect.y < config.HEIGHT-self.height*1.5:
            self.rect.y += self.speedy
Feelsbadman
  • 1,163
  • 4
  • 17
  • 37

1 Answers1

1

Try dividing by 3.0 rather than just 3. I'm pretty sure this will work as it is what Python 2's integer division is coded as. Hope this helps :-) P.S. If you do any more additions, subtractions, divisions or multiplications, be sure to put .0 at the end unless you want another D.P. e.g. 2 * 7.0.

David Lunt
  • 62
  • 4