How would I make a battery meter in pygame?

84 Views Asked by At

I made a program in Python with a flashlight and want to make the battery meter change when the flashlight is on. I made a simpler version where it only changes like this:

high = pygame.image.load("battery_high.jpeg")
medium = pygame.image.load("battery_med.jpeg")
low = pygame.image.load("battery_low.jpeg")

battery = 100

while True:
    battery -= 0.1;
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break
    game_display.fill(WHITE)

    battery_img = None

    if battery > 66:
        battery_img = high;
    elif battery > 33:
        battery_img = medium;
    else:
        battery_img = low;
    display.blit(battery_img, (0, 0));
    
    pygame.display.flip()

The battery change isn't that smooth, if I have 60% battery I want the meter to be 60% full. How do I do this? I think the fix is to cut off the image, but I don't know how.

1

There are 1 best solutions below

2
Rabbid76 On BEST ANSWER

You only have 3 images. Either you need more images or you have to draw the scale in Pygame. Here is a piece of simple code that draws a dynamic scale on an image. The scale is just a rectangle that changes in height depending on the battery charge:

import pygame

pygame.init()
screen = pygame.display.set_mode((300, 200))
clock = pygame.time.Clock()

battery_image_v = pygame.Surface((50, 100))
battery_image_v.fill("darkgray")
pygame.draw.rect(battery_image_v, "black", (18, 3, 14, 94))
scale_image_v = pygame.Surface((10, 90))

battery_image_h = pygame.Surface((100, 50))
battery_image_h.fill("darkgray")
pygame.draw.rect(battery_image_h, "black", (3, 18, 94, 14))
scale_image_h = pygame.Surface((90, 10))

battery = 100

run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 
    
    battery -= 1
    if battery < 0:
        battery = 100

    scale_image_v.fill("black")
    h = battery * scale_image_v.get_height() // 100
    y = scale_image_v.get_height() - h
    pygame.draw.rect(scale_image_v, "green", (0, y, 10, h))

    scale_image_h.fill("black")
    w = battery * scale_image_h.get_width() // 100
    pygame.draw.rect(scale_image_h, "green", (0, 0, w, 10))

    screen.fill("white")
    screen.blit(battery_image_v, battery_image_v.get_rect(center = (100, 100)))
    screen.blit(scale_image_v, scale_image_v.get_rect(center = (100, 100)))
    screen.blit(battery_image_h, battery_image_h.get_rect(center = (200, 100)))
    screen.blit(scale_image_h, scale_image_h.get_rect(center = (200, 100)))
    pygame.display.flip()

pygame.quit()
exit()