Ivah Bmahs
Ivah Bmahs

Reputation: 11

Pygame window opening and closing immediately

So when I set

while not game_over = False

, my window opens properly, but the text doesn't show. Whereas if I set it to True, the text shows but window closes immediately.

Here's the code:

***#Write a Python program to create a simple math quiz.
#Importing libraries
import pygame
import sys
import math
from pygame.locals import *
#Initialising fonts
pygame.init()
pygame.font.init()
#Assigning variables
WIDTH = 600
HEIGHT = 600
#Other important things
background_color = (127,255,0)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
pygame.display.set_caption("Math Game")
screen.fill(background_color)
pygame.display.flip()
font = pygame.font.Font("freesansbold.ttf", 40)
textX=10
textY=10
def show_text(x,y):
    text=font.render("Math Game", True, (0,0,0))
    screen.blit(text,(x,y))
"""
#Adding the Calculator bit
x = input("Enter Your First Nummber To Add: ")
y = input("Enter Your Second Number To Add: ")
z = str(int(x)+int(y))
print(z)
"""
#Game loop
game_over = True
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
show_text(textX, textY)
pygame.display.update()***

Upvotes: 1

Views: 691

Answers (1)

Rabbid76
Rabbid76

Reputation: 210968

It is a matter of Indentation. show_text and pygame.display.update() must be called in the application loop instead of after the application loop.
Additionally you should clear the display in the application loop.

game_over = False
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

# INDENTATION
#-->|
    screen.fill(background_color)
    show_text(textX, textY)
    pygame.display.update()

The typical PyGame application loop has to:

Upvotes: 1

Related Questions