pygame window not responding when runing program - pygame

i have been working on a pygame platformer and been trying to run it buy my python window just says not responding and then crashes is ther anything wrong with my code. Here is my code
link to my code: https://drive.google.com/drive/u/0/folders/1QRNYi2hd5RBhIa-EwKdxdRPUdxWHALon

Add this at the top of your code:
done=False
while not done:
#event handler
for event in pygame.event.get():
if event.type==QUIT:
done=True
pygame.quit()

This is the code to open a window, change it to red and then close it when the cross is pressed:
import pygame
#Initialize the game engine
pygame.init()
red = (255, 0, 0)
#Set width and hight
size = [700, 500]
screen = pygame.display.set_mode(size)
#The caption on top of the window
pygame.display.set_caption("My game")
#Loop until the user clicks the button
done = False
#Manages 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
screen.fill(red)
pygame.display.flip()
#Limit to 20 frames per second
clock.tick(20)
#Exits window if the original loop is broken
pygame.quit()
I hope that this helps

Related

Why does the pygame window become unresponsive?

In a 'Pygame loop', I'm trying to ask for user input but when I run the program, the pygame window becomes unresponsive if I hover my mouse over it or click anywhere. Does anyone know what's going wrong?
import pygame
win = pygame.display.set_mode((600, 600))
win.fill((240, 240, 240)) #white
pygame.display.update()
#Game loop
quit = False
while quit == False:
for e in pygame.event.get():
if e.type == pygame.QUIT:
exit()
u_input = input("Enter 'q' to quit or 'n' to fill the window with navy: ")
if u_input == 'q':
quit = True
elif u_input == 'n':
win.fill((60, 55, 100)) #navy
pygame.display.update()
Unresponsive pygame window image
The IDE I'm using is Visual Studio Code
Unfortunately, this is just a nature of pygame. When you ask for an input, the program stops and waits for the user to input something, preventing the pygame.diplay.flip() from occuring.
There is two ways I can think of to fix this. Using, threads, one for powershell (terminal) and one for pygame should work, however I'm not familiar with that at all, so you would need to research for yourself.
A different solution is to listen for user input instead of using terminal prompts
#Game loop
quit = False
while quit == False:
for e in pygame.event.get():
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_q:
quit = True
if e.key == pygame.K_n:
win.fill((60, 55, 100)) #navy
pygame.display.update()

how to add a video to python at the touch of a button? [duplicate]

I'm having a problem. I want to load and play a video in pygame but it doesn't start. The only thing that I am seeing is a black screen. Here is my code:
import pygame
from pygame import display,movie
pygame.init()
screen = pygame.display.set_mode((1024, 768))
background = pygame.Surface((1024, 768))
screen.blit(background, (0, 0))
pygame.display.update()
movie = pygame.movie.Movie('C:\Python27\1.mpg')
mrect = pygame.Rect(0,0,140,113)
movie.set_display(screen, mrect.move(65, 150))
movie.set_volume(0)
movie.play()
Can you help me??
The pygame.movie module is deprecated and not longer supported.
If you only want to show the video you can use MoviePy (see also How to be efficient with MoviePy):
import pygame
import moviepy.editor
pygame.init()
video = moviepy.editor.VideoFileClip("video.mp4")
video.preview()
pygame.quit()
An alternative solution is to use the OpenCV VideoCapture. Install OpenCV for Python (cv2) (see opencv-python). However, it should be mentioned that cv2.VideoCapture does not provide a way to read the audio from the video file.
This is only a solution to show the video but no audio is played.
Opens a camera for video capturing:
video = cv2.VideoCapture("video.mp4")
Get the frames per second form the VideoCapture object:
fps = video.get(cv2.CAP_PROP_FPS)
Create a pygame.time.Clock:
clock = pygame.time.Clock()
Grabs a video frame and limit the frames per second in the application loop:
clock.tick(fps)
success, video_image = video.read()
Convert the camera frame to a pygame.Surface object using pygame.image.frombuffer:
video_surf = pygame.image.frombuffer(video_image.tobytes(), video_image.shape[1::-1], "BGR")
See also Video:
Minimal example:
import pygame
import cv2
video = cv2.VideoCapture("video.mp4")
success, video_image = video.read()
fps = video.get(cv2.CAP_PROP_FPS)
window = pygame.display.set_mode(video_image.shape[1::-1])
clock = pygame.time.Clock()
run = success
while run:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
success, video_image = video.read()
if success:
video_surf = pygame.image.frombuffer(
video_image.tobytes(), video_image.shape[1::-1], "BGR")
else:
run = False
window.blit(video_surf, (0, 0))
pygame.display.flip()
pygame.quit()
exit()
You are not actually blitting it to a screen. You are also not utilizing a clock object so it will play as fast as possible. Try this:
# http://www.fileformat.info/format/mpeg/sample/index.dir
import pygame
FPS = 60
pygame.init()
clock = pygame.time.Clock()
movie = pygame.movie.Movie('MELT.MPG')
screen = pygame.display.set_mode(movie.get_size())
movie_screen = pygame.Surface(movie.get_size()).convert()
movie.set_display(movie_screen)
movie.play()
playing = True
while playing:
for event in pygame.event.get():
if event.type == pygame.QUIT:
movie.stop()
playing = False
screen.blit(movie_screen,(0,0))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
I just got that MELT.MPG from the link provided in the comment. You should be able to simply switch out that string for your actual MPG you want to play and it will work... maybe.
As you probably know, the pygame.movie module is deprecated and no longer exists in the latest version of pygame.
An alternative would be to read in frames of the video one by one and blit them onto the pygame screen using the the cv2 module (OpenCV), that can be installed with the command prompt command:
pip install opencv-python
Then, you can run the code:
import cv2
import pygame
cap = cv2.VideoCapture('video.mp4')
success, img = cap.read()
shape = img.shape[1::-1]
wn = pygame.display.set_mode(shape)
clock = pygame.time.Clock()
while success:
clock.tick(60)
success, img = cap.read()
for event in pygame.event.get():
if event.type == pygame.QUIT:
success = False
wn.blit(pygame.image.frombuffer(img.tobytes(), shape, "BGR"), (0, 0))
pygame.display.update()
pygame.quit()

program only works half the time

for some reason this python program i saw on a youtube tutorial only works sometimes. Whenever i run the code, i get an error in the program telling me the program doesnt answer. But once in a while the code suddenly works perfectly.
import pygame, sys
from sys import exit
# crosshair class
class Crosshair(pygame.sprite.Sprite):
def __init__(self, picture_path):
super().__init__()
self.image = pygame.image.load(picture_path)
self.rect = self.image.get_rect()
def update(self):
self.rect.center = pygame.mouse.get_pos()
# general setup
pygame.init()
clock = pygame.time.Clock()
# create the screen
screen = pygame.display.set_mode((800,400))
pygame.display.set_caption('Runner')
background = pygame.image.load("sprites/graphics/bg.png")
background = pygame.transform.scale(background, (800, 400))
pygame.mouse.set_visible(False)
#crosshair
crosshair = Crosshair('sprites/graphics/crosshair.png')
crosshair_group = pygame.sprite.Group()
crosshair_group.add(crosshair)
# while loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit
exit()
screen.blit(background,(0,0))
crosshair_group.draw(screen)
crosshair_group.update()
clock.tick(60)
pygame.display.update()
You need to do pygame.quit() instead of pygame.quit. Missing the parentheses means that you are not actually calling the function, and the window never closes.
You are getting a not responding message when you attempt to X out the window because exit() is being called, which ends your program, including the event-handling loop. The window is left with no program controlling it or making it respond to inputs such as closing, so you get that message.
Calling the pygame.quit() function will close the window right before the program quits, so it is all taken care of.

Video game not responding correctly to input

I'm developing a pygame video game, and everything was working out perfectly until yesterday. The issues began after I formatted my pc. So when i run the game, the first screen to show up is the 'Menu'. So in this state class I have an event method where when you press the 'p' key it gets you to the 'Play' state. So now it is not working, I don't know why.
I've changed nothing. I just formatted my pc and reinstalled python, pygame and pgu module. But the strange thing comes when I reprogram the videogame so that the first state to show up when you run the game is the 'Play' state, everything works perfectly. It also has an event method where when you press the arrows, the character moves, and when the player presses ESC it takes you to the 'Menu' state.
So again when I'm at the 'Menu' state the game doesn't respond to the input I'm giving to it. I don't really know what's happening.
Here is an example of what I was saying in comments :
Sorry if all comments are not appropriate to your level but I wanted to be sure you understand it all.
import pygame
screen = pygame.display.set_mode((1000, 1000))
class Menu:
pass
class Play:
pass
def main():
running = True # here we define the main variable of the main loop
main_menu = True # when the main loop will begin, main_menu will begin too
game = False # game is false because player didn't press p
options = False # options is false because player didn't go to options
while running: # begin the main loop
while main_menu:
for event in pygame.event.get(): # listen for events
if event.type == pygame.QUIT: # if the player quit, ends up the 'main_menu' loop and 'running' loop too
running = False
main_menu = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p: # if p key is pressed, exit from main menu and begin 'game' loop
main_menu = False
game = True
if event.key == pygame.K_o: # if o key is pressed, exit from main menu and begin 'options' loop
main_menu = False
options = True
screen.fill((255, 0, 0)) # I fill the screen in red to make the example more explicit
pygame.display.flip() # I update the screen every frame
while game:
for event in pygame.event.get(): # listen for events
if event.type == pygame.QUIT: # if the player quit, ends up 'running' and 'options' loop
running = False
game = False
if event.type == pygame.KEYDOWN: # listen for keys
if event.key == pygame.K_BACKSPACE: # if the player press backspace (delete), ends up 'game' loop
game = False # and begin (again) the 'main_menu' loop
main_menu = True
screen.fill((255, 255, 255)) # I fill the screen in white to make the example more explicit
pygame.display.flip() # I update the screen every frame
while options: # same logic for this one
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
options = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_BACKSPACE:
options = False
main_menu = True
screen.fill((0, 255, 0))
pygame.display.flip()
pygame.init() # initialize pygame
main() # begin main loop
pygame.quit() # quit pygame

error: display Surface quit

when i run my program it dosn't fill the screen with white, which it should i think(IM NEW). Iv check other games iv written and i seem to be doing the same stuff but it works in the other ones? here's my program:
import pygame,time,pygame.mixer
from pygame.locals import *
pygame.init()
#set screen to be the window
screen=pygame.display.set_mode((640,480))
#fills screen with white
screen.fill((255,255,255))
#set starting gravity
gravity=0.1
#limits fps
FPS=60
fpstime=pygame.time.Clock()
timer=0
#sets colour codes
red=(255,0,0)
green=(0,255,0)
blue=(0,255,0)
white=(255,255,255)
#set player starting location
playerpos1=320
playerpos2=240
#makes the game loop start
FLYING=True
#game loop
while FLYING:
screen.fill((255,255,255))
gravity+=0.02
timer+=0.001
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
break
pygame.display.update
fpstime.tick(FPS)
One possible issue - you're missing () on pygame.display.update().