Pygame - How to Fill an object gradually from bottom to top?

Viewed 114

I'm currently working on a game based around working a restaurant, and one of the aspects im working on is filling a cup up with water, i'm choosing not to do water simulations as i'm no expert ahah but my idea of filling a cup up using rectangles one a top another when the mouse button is held is not working. Here's the section of code im trying to fix, any and all feedback is appreciated : ).

while True:
   e = pygame.event.wait()
   if e.type == pygame.MOUSEBUTTONDOWN:
       DrawWater = True       
   if e.type == pygame.MOUSEBUTTONUP:
           print("Lol")
           WaterLine = False
   
   if DrawWater:
       pygame.draw.rect(screen, [0, 0, 255], [300, WaterLine, 400, 1])
       WaterLine -= 1
   pygame.display.flip() 

1 Answers

pygame.event.wait() wait for a single event from the queue and halts the application loop. Implement an event loop and use pygame.event.get:

Use pygame.time.Clock to control the frames per second and thus the game speed.

The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick().

This method should be called once per frame.

That means that the loop:

clock = pygame.time.Clock()
run = True
while run:
   clock.tick(60)

runs 60 times per second.

clock = pygame.time.Clock()
run = True
while run:
   clock.tick(60)
   for event in pygame.event.get():
       if event.type == pygame.QUIT:
           run = False
       if event.type == pygame.MOUSEBUTTONDOWN:
           DrawWater = True       
       if event.type == pygame.MOUSEBUTTONUP:
           print("Lol")
           WaterLine = False
   
   if DrawWater:
       pygame.draw.rect(screen, [0, 0, 255], [300, WaterLine, 400, 1])
       WaterLine -= 1
   pygame.display.flip() 

Alternatively you can use pygame.mouse.get_pressed():

import pygame

pygame.init()
screen = pygame.display.set_mode((300, 400))

WaterLine = 300

clock = pygame.time.Clock()
run = True
while run:
   clock.tick(60)
   for event in pygame.event.get():
       if event.type == pygame.QUIT:
           run = False
   
   if any(pygame.mouse.get_pressed()):
       pygame.draw.rect(screen, [0, 0, 255], [100, WaterLine, 100, 1])
       WaterLine -= 1
   pygame.display.flip() 

The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released.
pygame.mouse.get_pressed() returns a list of Boolean values ​​that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down.

Related