2

Me and my acquaintance are working on creating a loading bar that takes forever to load for the fun of it. However, when making this loading bar, it seems to crash within the first second or two. Here's the code:

import pygame
import time
import random

pygame.init()

progress = 0

black = [0, 0, 0]
white = [255, 255, 255]
green = [0, 255, 0]

screenWidth = 600
screenHeigth = 800
size = [screenWidth, screenHeigth]

font = pygame.font.SysFont("Comic Sans MS", 25)

clock = pygame.time.Clock()

screen = pygame.display.set_mode(size)
pygame.display.set_caption('Loading...')


def textObjecte(text, color, size):
    if size == "small":
        textsuraface = font.render(text, True, color)

        return textsuraface, textsuraface.get_rect()


def loading(progress):
    if progress < 100:
        text = font.render("loading: " + str(int(progress)) + "%", True, green)

    screen.blit(text, (300, 100))


def message_to_screen(msg, color, y_displace, size="small"):
    textSurf, textRect = textObjecte(msg, color, size)
    textRect.center = (screenWidth/2), (screenHeigth/2) + y_displace

screen.blit(textSurf, textRect)


while progress/2 < 100:
    timeCount = random.randint(15, 30)
    increase = random.randint(1, 7)
    progress += increase
    screen.fill(black)
    pygame.draw.rect(screen, white, [300, 50, 200, 50])
    pygame.draw.rect(screen, black, [301, 51, 198, 48])

    if (progress/2) > 100:
        pygame.draw.rect(screen, white, [302, 52, 196, 46])
    else:
        pygame.draw.rect(screen, white, [302, 52, progress, 46])

    loading(progress/2)
    pygame.display.flip()

    time.sleep(timeCount)

Any help with the code would be greatly appreciated.

Aemyl
  • 1,501
  • 1
  • 19
  • 34

2 Answers2

0

Your issue is that TextSurf is defined in a function then your trying to use it outside of the function which breaks it.

def message_to_screen(msg, color, y_displace, size="small"):
    textSurf, textRect = textObjecte(msg, color, size)
    textRect.center = (screenWidth/2), (screenHeigth/2) + y_displace

screen.blit(textSurf, textRect)

what you would want it to indent $ screen.blit(textSurf, textRect) so its inside the function

Sam Green
  • 48
  • 6
0

There are two things that need to be changed:

  1. You've got to handle the events (empty the event queue) each frame or the window will become unresponsive. Either call pygame.event.pump() or add an event loop for event in pygame.event.get():.

  2. You have to remove the time.sleep call, because it blocks the program, the events can't be handled and the window will freeze as well (for the specified time).

I'm not sure what you're trying to achieve with the time.sleep, but there's most likely a better way.

skrx
  • 19,980
  • 5
  • 34
  • 48