Keep getting an error about pygame not being initialised - python

I keep getting an error about system not being initialised. The error is about the pygame.display.update()
Where is this meant to go?
import pygame #IMPORTS THE PYGAME CLASSES, METHODS AND ATTRIBUTES
from pygame.locals import * #IMPORTING ALL PYGAME MODULES
pygame.init() #INITIALISING PYGAME
WIDTH, HEIGHT = 1000, 600
WINDOW = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("On The Run")
blue = 146,244,255 #BACKGROUND COLOUR
width = 80
height = 60
x = 200 #X-POSITION OF THE CHARACTER
y = 100 #Y-POSITION OF THE CHARACTER
player1 = pygame.image.load('assets/characterMove3.jpg') #DISPLAYING THE IMAGE ONTO THE SCREEN
player1 = pygame.transform.scale(player1,(width,height)) #SCALING THE IMAGE TO SUITABLE DIMENSIONS
WINDOW.blit(player1,(x,y))
def game_loop(): #WHERE THE WINDOW IS CREATED
run = True
while run:
WINDOW.fill(blue)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False #WE WILL QUIT THE GAME AS THE VARIABLE run IS NOW FALSE
pygame.quit() #IT WON'T SHOW THE MOST RECENT THING I DREW UNLESS I MANUALLY UPDATE IT
pygame.display.update()
game_loop()

The problem is that pygame.quit() is called in the application loop. pygame.quit() deinitializes all Pygame modules and crashes all subsequent Pygame API calls. pygame.quit() must be the very last Pygame API call. Call pygame.quit() after the application loop:
def game_loop(): #WHERE THE WINDOW IS CREATED
run = True
while run:
WINDOW.fill(blue)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#pygame.quit() <-- DELETE
pygame.display.update()
pygame.quit() # <-- INSERT
game_loop()

Related

Pygame - window opens but fill() doesn't work and no events detected

I'm creating a simple pygame program (PyGame 1.9.6 on Python 3.7), but some of the code inside my while loop doesn't seem to work. When I run the program, the window opens, but the screen doesn't fill with black, nor does the window close when I press "x"
import pygame
# pygame setup
pygame.init()
# Open a window on the screen
width, height = 600, 600
screen = pygame.display.set_mode((width, height))
def main():
running = True
clock = pygame.time.Clock()
BLACK = (0,0,0)
while running:
clock.tick(5) # number of loops per second
print("tick")
screen.fill(BLACK)
for event in pygame.event.get():
print("event detected")
if event == pygame.QUIT:
running = False
pygame.display.update()
main()
In the console, "tick" appears like normal and "event detected" appears after pressing any keys or mouse click. I don't get any errors when I run it.
If event == pygame.QUIT: should be if event.type == pygame.QUIT:
I usually use that event like this:
if event.type == pygame.QUIT:
pygame.quit()
quit()
Just as #Telan said
if event==pygame.QUIT:
should be
if event.type==pygame.QUIT:
However to properly shutdown pygame, pygame.quit() is important to shutdown pygame modules which is the reverse of pygame.init()
While sys.exit() is used to properly shutdown the main python program.
from sys import exit
import pygame
if event.type == pygame.QUIT:
pygame.quit()
exit()
Full code is shown below. Enjoy!
import pygame
from sys import exit
# pygame setup
pygame.init()
# Open a window on the screen
width, height = 600, 600
screen = pygame.display.set_mode((width, height))
def main():
clock = pygame.time.Clock()
BLACK = (0, 0, 0)
while True:
clock.tick(5) # number of loops per second
print("tick")
screen.fill(BLACK)
for event in pygame.event.get():
print("event detected")
if event.type == pygame.QUIT:
pygame.quit()
exit()
pygame.display.update()
if __name__ == "__main__":
main()

Doing something after a period of time: Pygame

I wanted to do something after a period of time. On stack overflow I found a question that helps solve that, (Link) but when I run the program the code works, however it goes away after a millisecond. Whereas I want it to stay there after the amount of time I want it to wait. In this case for a test run I am blitting some text onto the screen. Here is the code:
import pygame
# Importing the modules module.
pygame.init()
# Initializes Pygame
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((800, 600))
# Sets the screen to pygame looks and not normal python looks.
pygame.display.set_caption("Test Run")
# Changes the title
# Heading
headingfont = pygame.font.Font('Bouncy-PERSONAL_USE_ONLY.otf', 45)
headingX = 230
headingY = 10
class Other():
def show_heading():
Heading = headingfont.render("Health Run!", True, (255, 255, 255))
screen.blit(Heading, (headingX, headingY))
pygame.time.set_timer(pygame.USEREVENT, 100)
running = True
while running:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.USEREVENT:
Other.show_heading()
#Update Display
pygame.display.update()
If you want to draw the text permanently, you need to draw it in the application loop. Set a Boolean variable "draw_text" when the timer event occurs. Draw the text depending on draw_text in the application loop:
draw_text = False
running = True
while running:
screen.fill((0,0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.USEREVENT:
draw_text = True
if draw_text:
Other.show_heading()
#Update Display
pygame.display.update()
For more information about timers and timer events, see Spawning multiple instances of the same object concurrently in python, How can I show explosion image when collision happens? or Adding a particle effect to my clicker game and many more.

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()***
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:
handle the events by calling either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by calling either pygame.display.update() or pygame.display.flip()
limit the frames per second to limit CPU usage with pygame.time.Clock.tick

Why is my pymunk program is way too slow?

My pymunk program is way too slow. Every time I run the program it takes 5 seconds while loading. Here is my code. Thanks in advance.
import pymunk # Import pymunk..
import pygame
pygame.init()
display = pygame.display.set_mode((800,800))
clock = pygame.time.Clock()
space = pymunk.Space() # Create a Space which contain the simulation
FPS = 30
def convert_coordinates(point):
return point[0], 800-point[1]
running = True
space.gravity = 0,-1000 # Set its gravity
# Set the position of the body
body = pymunk.Body()
shape = pymunk.Circle(body, 10)
body.position = (400,800)
shape.density = 1
space.add(body,shape)
while running: # Infinite loop simulation
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
clock.tick(FPS)
space.step(1/FPS)
display.fill((255,255,255))
x,y = convert_coordinates(body.position)
sprite = pygame.draw.circle(display,(255,0,0), (int(x),int(y)),10)
pygame.quit()
It's a matter of Indentation. You have to draw the scene in the application loop rather than the event loop:
while running: # Infinite loop simulation
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# <--- INDENTATION
clock.tick(FPS)
space.step(1/FPS)
display.fill((255,255,255))
x,y = convert_coordinates(body.position)
sprite = pygame.draw.circle(display,(255,0,0), (int(x),int(y)),10)
pygame.display.update()
pygame.quit()

video system not initialized

When I run the following code I get an error. Most of the other similar posts talks about pygame.quit()
sys.exit() which I have, but still see the error
import pygame, sys, math
pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode((width, height))
ball = pygame.image.load("GolfBall.png").convert_alpha()
ball_rect= ball.get_rect()
is_playing= True
while is_playing:
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_playing= False
screen.fill((0,0,0))
screen.blit(ball, ball_rect)
pygame.display.flip()
pygame.time.wait(20)
pygame.quit()
sys.exit()
The error is
Traceback (most recent call last):
File "C:/Users/.............................", line 10, in <module>
for event in pygame.event.get():
pygame.error: video system not initialized
pygame.quit() should be out of the loop:
import pygame, sys, math
pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode((width, height))
ball = pygame.image.load("GolfBall.png").convert_alpha()
ball_rect= ball.get_rect()
is_playing= True
while is_playing:
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_playing= False
screen.fill((0,0,0))
screen.blit(ball, ball_rect)
pygame.display.flip()
pygame.time.wait(20)
pygame.quit()
sys.exit()
Otherwise after the first iteration of the loop, pygame.quit() would have been called and on the second iteration the error would have occured.
You have to care about the Indentation
While pygame.quit() has to be done after the main application loop (as mentioned in another answer and the comments), drawing the scene and the update of the display has to be done in the main application loop rather than the event loop:
import pygame, sys, math
pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode((width, height))
ball = pygame.image.load("GolfBall.png").convert_alpha()
ball_rect= ball.get_rect()
# application loop
is_playing= True
while is_playing:
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_playing= False
#<--| INDENTATION
# draw the scene
screen.fill((0,0,0))
screen.blit(ball, ball_rect)
pygame.display.flip()
pygame.time.wait(20)
#<--| INDENTATION
# quit pygame
pygame.quit()
sys.exit()
Note, the event loop is executed once for each event, but the application loop is executed once for each frame.

Categories

Resources