How to run pygame in the background? - pygame

I made a small pygame app that plays certain wav files in keypress using pygame.mixer
All seem to work just fine except the fact that if you minimize the pygame window the program stops working until you open it again. Is there a way to solve this issue or an alternative way to implement sound playing in python?
This is my repository: https://github.com/Souvlaki42/HighPlayer

Try using pygame.mixer.music() but you'll need to convert all your wav files into mp3 files.

Just patch up all my mistakes your code from line 34 onwards should now be:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
event2 = keyboard.read_event()
if event2.name == pygame.K_0:
stopSounds()
sound0.play()
if event2.name == pygame.K_1:
stopSounds()
sound1.play()
if event2.name == pygame.K_2:
stopSounds()
sound2.play()
if event2.name == pygame.K_3:
stopSounds()
sound3.play()
if event2.name == pygame.K_4:
stopSounds()
sound4.play()
if event2.name == pygame.K_5:
stopSounds()
sound5.play()
if event2.name == pygame.K_6:
stopSounds()
sound6.play()
if event2.name == pygame.K_7:
stopSounds()
sound7.play()
if event2.name == pygame.K_8:
stopSounds()
sound8.play()
if event2.name == pygame.K_9:
stopSounds()
sound9.play()

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()

pygame does not receive scroll event after re-init

I'm making a game for school project, and there's scrolling stuffs in my game. I need to reinit pygame to make sure every is reset. But somehow, scrolling stops working after reinit pygame.
I made a simple script to test if that really was the case, and it was.
import pygame
def main():
while True:
pygame.init()
screen = pygame.display.set_mode([1280, 720])
pygame.display.set_caption("PYGAME DOES NOT RECEIVE SCROLL EVENT AFTER RE-INIT?")
frame = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
print("left click")
elif event.button == 4:
print("scroll up")
elif event.button == 5:
print("scroll down")
if event.type == pygame.QUIT:
running = False
frame.tick(30)
pygame.quit()
if __name__ == "__main__":
main()
It gets left click event but not the scrolling ones.
Is there any way to fix this?
don't use pygame.MOUSEBUTTONDOWN for scroll.
I have found another way for you to map scrollling using pygame.MOUSEWHEEL.
Here is the revised code:
import pygame
def main():
while True:
pygame.init()
screen = pygame.display.set_mode([1280, 720])
pygame.display.set_caption("PYGAME DOES NOT RECEIVE SCROLL EVENT AFTER RE-INIT?")
frame = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
print("left click")
if event.button == 3:
print("right click")
if event.type == pygame.MOUSEWHEEL:
if event.y == 1:
print("scroll up")
if event.y == -1:
print("scroll down")
if event.type == pygame.QUIT:
running = False
frame.tick(60)
pygame.quit()
if __name__ == "__main__":
main()
btw, happy new year and good luck mate~

In pygame key read is delayed

import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif (event.type == pygame.KEYDOWN):
if (event.key == pygame.K_LEFT):
print('LEFT')
if (event.key == pygame.K_DOWN):
print('DOWN')
if (event.key == pygame.K_RIGHT):
print('RIGHT')
if (event.key == pygame.K_UP):
print('UP')
print('FRAME')
pygame.display.update()
clock.tick(1)
If you press arrow key just after 'FRAME' is printed, sometimes 'FRAME' is printed for second time before keypressed arrow is printed. Is as if pygame.event.get() is delayed. Example:
FRAME
FRAME
<---- UP pressed here
FRAME
UP
FRAME
FRAME
<---- UP pressed here
FRAME
UP
How could I correct this behaviour?
You are using clock.tick(1), so this is telling pygame that you want 1 fps. This will make everything slower, and pretty much pause your code for a tiny bit. Try changing the 1 to something like 60 or 30.

pygame window opens and instantly closes

So I have a file in the same folder as the file i'm coding right now and when the code runs in pycharm, if I press left arrow the other file is opened, but if I open the file using python straight from the file location it just opens and closes. Here is my code:
import pygame
import sys
import random
import subprocess
pygame.init()
GUI = pygame.display.set_mode((800,600))
pygame.display.set_caption("The incredible guessing game")
x = 284
y = 250
width = 68
length = 250
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run =False
if event.type == pygame.KEYDOWN:
command = "python AhjaiyGame.py"
subprocess.call(command)
pygame.draw.rect(GUI, (255,210,0), (x,y,length,width))
pygame.display.update()
pygame.quit()
Simply put, the program exists because it has completed running.
Python is tabulation based, and in the code you posted, the while loop is not actually doing anything.
You need to indent the code you need looped:
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run =False
if event.type == pygame.KEYDOWN:
command = "python AhjaiyGame.py"
subprocess.call(command)
pygame.draw.rect(GUI, (255,210,0), (x,y,length,width))
pygame.display.update()
pygame.quit()
Notice the tabulation.
In this example, pygame.quit() will only be called when run becomes False and the while loop completes.
import pygame
import sys
import random
import subprocess
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("The incredible guessing game")
x = 40
y = 30
width = 10
height = 20
vel=0.1
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run =False
keys=pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x-=vel
if keys[pygame.K_RIGHT]:
x+=vel
if keys[pygame.K_UP]:
y-=vel
if keys[pygame.K_DOWN]:
y+=vel
win.fill((0,0,0))
pygame.draw.rect(win, (255,0,0), (x,y,width,height))
pygame.display.update()
pygame.quit()

I keep getting this error: Couldn't open "File"

I'm trying to display an image using pygame, but I get this error:
Traceback (most recent call last):
File "H:/profile/desktop/untitled/venv/Scripts/AhjaiyGame.py", line 28, in
start = pygame.image.load(os.path.join(folder, "wecvguh.png"))
pygame.error: Couldn't open H:\profile\desktop\untitled\venv\Scripts\wecvguh.png
Code block:
import sys
import random
import os
import subprocess
import pygame
pygame.init()
GUI = pygame.display.set_mode((800,600))
pygame.display.set_caption("The incredible guessing game")
x = 284
y = 250
width = 68
length = 250
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run =False
if event.type == pygame.KEYDOWN:
command = "python AhjaiyCPT.py"
subprocess.call(command)
pygame.display.update()
folder = os.path.dirname(os.path.realpath(__file__))
start = pygame.image.load(os.path.join(folder, "wecvguh.png"))
def img(x,y):
gameDisplay.blit(start, (x,y))
while run:
gameDisplay.fill(white)
start(x, y)
pygame.quit()
The code has two "run" loops, so it never gets to the second loop.
The code's indentation is confused - maybe from a paste into SO?. The overwhelming majority of programmers use 4 spaces to indent. This is probably a good custom to follow.
The code also loaded the "start" image every loop iteration, this is unnecessary (unless it changes on disk, in this case use os.stat() to check for changes before re-loading it).
Re-worked main loop:
folder = os.path.dirname(os.path.realpath(__file__))
start = pygame.image.load(os.path.join(folder, "wecvguh.png"))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
command = "python AhjaiyCPT.py"
subprocess.call(command)
gameDisplay.fill(white)
gameDisplay.blit(start, (x,y))
pygame.display.update()
pygame.quit()