Pygame Window not Loading Image - python

Today is my first day of pygame and I cannot understand why this code doesn't work, the pygame windows is black doesn't respond and no image is displayed
import pygame
pygame.init()
screen_width=800
screen_height=800
screen=pygame.display.set_mode([screen_width,screen_height])
screen.fill((255,255,255))
Quit=input("Press'Y' is you want to quit")
if Quit == "Y":
pygame.display.quit()
Board = pygame.image.load("TicTacToeBoard.jpg")
screen.blit(Board,(0,0))
pygame.display.flip()

All PyGame programs have an Event Loop. This is a continual loop that accepts events from the window manager / operating environment. Events are things like mouse movements, button clicks and key presses. If you program does not accept events, eventually the launching program will consider it to have stopped responding and perhaps prompt the user to terminate it.
Your existing code grabs input from the console. This can be done in PyGame if you use a thread, and then post an event back to the main loop. But generally it's easier to just handle exiting as an event. In the code below I've handled exiting with the QUIT event, and pressing Q.
import pygame
pygame.init()
screen_width=800
screen_height=800
screen=pygame.display.set_mode([screen_width,screen_height])
Board = pygame.image.load("TicTacToeBoard.jpg")
clock = pygame.time.Clock()
# Main Event Loop
exiting = False
while not exiting:
# Handle events
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
exiting = True
elif ( event.type == pygame.MOUSEBUTTONUP ):
# On mouse-click
mouse_pos = pygame.mouse.get_pos()
print( "Mouse Click at "+str( mouse_pos ) )
elif ( event.type == pygame.KEYUP ):
if ( event.key == pygame.K_q ):
# Q is quit too
exiting = True
# Paint the screen
screen.fill((255,255,255))
screen.blit(Board,(0,0))
pygame.display.flip()
# Limit frame-rate to 60 FPS
clock.tick_busy_loop(60)
Additionally, this code also limits the frame-rate to 60 FPS.

Related

Pygame window doesn't close after clicking red cross

I'm new to pygame. I have written the following code, but the generated window doesn't allow me to close it.
import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
Looping and the game running are two different things. If you want to close the game after the loop ends, you should do so with pygame.quit(). Importing sys and adding sys.exit() as afterwards lets you exit the Python script altogether. Depending on which IDE you use, this may not happen automatically.
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((800,600))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
sys.exit()

why do I get the error: pygame.error: video system not initialized

Like the title says I am confused why I get the error: pygame.error: video system not initialized
As far as i understand this error is raised if you forget to initialize your code with pygame.init() but I did, here's my code and thanks in advance:
import pygame
from pygame.locals import *
pygame.init()
screen_height = 700
screen_width = 1000
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("platformer")
# load images
sun_img = pygame.image.load("img/sun.png")
backround_img = pygame.image.load("img/sky.png")
run = True
while run:
screen.blit (backround_img,(0,0))
screen.blit(sun_img, (100, 50))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
pygame.display.update()
the error does not crash the window or anything and it works as intended
its just somewhat annoying.
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
pygame.display.update()
When the event loop happens, if you close the window, you call pygame.quit(), which quits pygame. Then it tries to do:
pygame.display.update()
But pygame has quit, which is why you are getting the message.
separate the logic out. Events in one function or method, updating in another, and drawing and updating the display in another to avoid this.

Pygame : Keyboard event not detected (Following Catalina Update Mac)

I am trying to run the code below using python and pygame and I tried many things but i could find the solution for the program to detect the keyboard (arrows) events... And I am beginning to think that it is linked to the Catalina update of my Mac OS. Before the update, this code was working alright... I guess it has to do with the "Accessibility" between Python/Terminal and the rights I give to these 2 applications but I can't find the exact "right access" that solves the problem...
Anyone has an idea ? :)
# coding=utf-8
# imports the Pygame library
import pygame
def main():
# initializes Pygame
pygame.init()
# sets the window title
pygame.display.set_caption(u'Keyboard events')
# sets the window size
pygame.display.set_mode((400, 400))
# infinite loop
while True:
# gets a single event from the event queue
# event = pygame.event.wait()
pygame.event.pump()
# if the 'close' button of the window is pressed
if event.type == pygame.QUIT:
# stops the application
break
# captures the 'KEYDOWN' and 'KEYUP' events
if event.type in (pygame.KEYDOWN, pygame.KEYUP):
# gets the key name
key_name = pygame.key.name(event.key)
# converts to uppercase the key name
key_name = key_name.upper()
# if any key is pressed
if event.type == pygame.KEYDOWN:
# prints on the console the key pressed
print("{} key pressed".format(key_name))
# if any key is released
elif event.type == pygame.KEYUP:
# prints on the console the released key
print("{} key released".format(key_name))
# finalizes Pygame
pygame.quit()
if __name__ == '__main__':
main()
If you want to process keyboard events, use a for loop. For example:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
elif event.type == pygame.KEYDOWN:
print(f"{event.key} key pressed")
I'm not sure how your code worked before.

pygame.error: video system not initialized python code error

After running this code, I got an error:
pygame.error: video system not initialized
My code:
import sys
import pygame
def run_game():
# Initialize game and create a screen object.
pygame.init()
screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Alien Invasion")
# Start the main loop for the game.
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Make the most recently drawn screen visible.
pygame.display.flip()
run_game()
Can anyone help me and explain what this error means and how to rectify it?
The error is raised because pygame.event.get is called without an initialized display (pygame.display.set_mode). The problem is that your while loop is not indented correctly, so it is executed before the run_game function is called. The loop should be inside of the run_game function.
import sys
import pygame
def run_game():
# Initialize game and create a screen object.
pygame.init()
screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Alien Invasion")
# Start the main loop for the game.
while True:
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Make the most recently drawn screen visible.
pygame.display.flip()
run_game()
put your code:
run_game()
before while statment`

Pygame screen freezes when I close it

The code loads up a pygame screen window, but when I click the X to close it, it becomes unresponsive. I'm running on a 64-bit system, using a 32-bit python and 32-bit pygame.
from livewires import games, color
games.init(screen_width = 640, screen_height = 480, fps = 50)
games.screen.mainloop()
Mach1723's answer is correct, but I would like to suggest another variant of a main loop:
while 1:
for event in pygame.event.get():
if event.type == QUIT: ## defined in pygame.locals
pygame.quit()
sys.exit()
if event.type == ## Handle other event types here...
## Do other important game loop stuff here.
I'd recommend the following code. First, it includes Clock so your program doesn't eat the CPU doing nothing but polling for events. Second, it calls pygame.quit() which prevents the program from freezing when running under IDLE on windows.
# Sample Python/Pygame Programs
# Simpson College Computer Science
# http://cs.simpson.edu/?q=python_pygame_examples
import pygame
# Define some colors
black = ( 0, 0, 0)
white = ( 255, 255, 255)
green = ( 0, 255, 0)
red = ( 255, 0, 0)
pygame.init()
# Set the height and width of the screen
size=[700,500]
screen=pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
#Loop until the user clicks the close button.
done=False
# Used to manage how fast the screen updates
clock=pygame.time.Clock()
# -------- Main Program Loop -----------
while done==False:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
# Set the screen background
screen.fill(black)
# Limit to 20 frames per second
clock.tick(20)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit ()
This is a pretty simple issue, you need to handle the "QUIT" event, see the event documentation at: http://www.pygame.org/docs/ref/event.html
EDIT:
It occurs to me now that you might be handling the "QUIT" event and its not working
but without more details to your code I dunno.
A quick example of a simple way to handle the "QUIT" event:
import sys
import pygame
# Initialize pygame
pygame.init()
pygame.display.set_mode(resolution=(640, 480))
# Simple(ugly) main loop
curEvent = pygame.event.poll()
while curEvent.type != pygame.QUIT:
# do something
curEvent = pygame.event.poll()
In using pygame, you have to handle all events including QUIT so if you don't handle the quit event, your program will not quit. Here's a code.
import sys
import pygame
from pygame.locals import *
def main():
running = True
while running:
for event in pygame.event.get():
if event.type==QUIT: #QUIT is defined at pygame.locals
runnning = False
#other game stuff to be done
if __name__=='__main__':
pygame.init()
pygame.display.set_mode((640,480))
main()

Categories

Resources