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.
>Solution :
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((200, 200))
clock = pygame.time.Clock()
battery_image = pygame.Surface((50, 100))
battery_image.fill("darkgray")
pygame.draw.rect(battery_image, "black", (18, 3, 14, 94))
scale_image = pygame.Surface((10, 90))
sclae_pos = (20, 5)
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.fill("black")
h = battery * scale_image.get_height() // 100
y = scale_image.get_height() - h
pygame.draw.rect(scale_image, "green", (0, y, 10, h))
screen.fill("white")
screen.blit(battery_image, (75, 50))
screen.blit(scale_image, (75 + sclae_pos[0], 50 + sclae_pos[1]))
pygame.display.flip()
pygame.quit()
exit()
