Creating window in pygame [duplicate] - python

I'm using jupyter notebook to make a py-game. I've noticed that EVERY TIME I render some text in the game, the notebook will collapse. It works when I run the game and the text is shown as expected. However, when I close the game's window and try to run the code for a second time it will collapse. Some times it will work for a couple of tries, but it'll collapse at some point. Other times, the notebook just collapses as soon as I close the game's window.
The relevant part of the code would be:
import pygame
pygame.init()
run=True
#screensize
screensize = (width,height)=(600,600)
screen = pygame.display.set_mode(screensize)
#font used for the text
myfont = pygame.font.SysFont('Comic Sans MS', 30)
#the text that will be rendered. It is usually some variable value, but the problem remains even if it is constant:
vel=3.001
while run:
pygame.time.delay(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run=False
screen.fill((0,0,0))
########rendering the text############
textsurface = myfont.render(str(int(vel)), False, (0, 100, 100))
screen.blit(textsurface,(200,400))
######################################
pygame.display.update()
pygame.quit()
Lets say I run the code and the I close the window. If I try to run the code again, the message is:
Le noyau semble planté. Il va redémarrer automatiquement.
(the kernel appears to have died. it will restart automatically)
I've been advised not to use pygame with jupyter notebook, but I jus't can't code outside that environment.

As suggested by user 'furas' above, activating pygame once and replacing pygame.init() for pygame.display.init(); and pygame.quit() by pygame.display.quit() solved this problem for me. Not sure if it implies more resources being used, but so far it has shown no problems in my rather basic laptop.
import pygame
pygame.init()
In a different cell:
pygame.display.init()
run=True
#screensize
screensize = (width,height)=(600,600)
screen = pygame.display.set_mode(screensize)
#font used for the text
myfont = pygame.font.SysFont('Comic Sans MS', 30)
#the text that will be rendered. It is usually some variable value, but the problem remains even if it is constant:
vel=3.001
while run:
pygame.time.delay(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run=False
screen.fill((0,0,0))
########rendering the text############
textsurface = myfont.render(str(int(vel)), False, (0, 100, 100))
screen.blit(textsurface,(200,400))
######################################
pygame.display.update()
pygame.display.quit()

Related

How do I start a pygame app in maximized mode on Linux?

Before I start, this is not a duplicate of How do you start Pygame window maximized?
I am on Linux which the win32gui and win32con libraries do not run on.
What I'm trying to do as stated by the title is maximize my pygame window when it is run. I do not want the game to be fullscreen by using the pygame.FULLSCREEN tag in pygame.display.set_mode(). I want it to be maximized.
My current way of getting it maximized is by creating the window with the pygame.RESIZEABLE flag which allows me to get the pygame.VIDEOEXPOSE event as shown in the example below.
import pygame, sys
SCREEN_WIDTH,SCREEN_HEIGHT = 1280,720
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.RESIZABLE, 32, vsync=1)
objects = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.VIDEORESIZE:
SCREEN.blit(pygame.transform.scale(objects, event.dict['size']), (0, 0))
pygame.display.update()
elif event.type == pygame.VIDEOEXPOSE: # handles window minimising/maximising
SCREEN.fill((0, 0, 0))
SCREEN.blit(pygame.transform.scale(objects, SCREEN.get_size()), (0, 0))
pygame.display.update()
pygame.display.update()
The objects surface is simply a surface I draw my game objects to in order to scale them when the window is resized. If you're wondering why I'm not just setting the screen width and height to the size of the screen by getting it using system info is because that way my objects aren't scaled properly. The only way I've been able to get my objects scaled properly is by using the VIDEORESIZE and VIDEOEXPOSE events. If there is a way to automatically press the maximize button or just start maximized in pygame that would be great.
Just found this issue on the pygame github for anyone who needs this. Essentially just use the library that pygame uses to draw windows which is cross platform.
This is the code snippet on the issue which worked for me.
import sys
import pygame
import pygame._sdl2
import time
pygame.init()
screen = pygame.display.set_mode((400, 400), pygame.RESIZABLE)
window = pygame._sdl2.Window.from_display_module()
clock = pygame.time.Clock()
window.maximize()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((255, 255, 255))
pygame.display.flip()
clock.tick(30)
I hope this helps anyone having similar issues.

Pycharm - pygame shows only black screen

Here is the code
import pygame
pygame.init()
screen_width = 480
screen_height = 640
screen = pygame.display.set_mode((screen_width, screen_height))
background = pygame.image.load("D:/Python/Pygame_200830/Background.png")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#screen.fill((0, 0, 255))
screen.blit(background, (0, 0))
pygame.display.update()
pygame.quit()
if I open this with VS code, it works well but, when I do this with Pycham. I can't see "backgound.png"
it's just only black display... and the only difference is IDE program.
I already added external function or something... only that backgound is the problem.
Could you let me know what is the reason...?
It is likely that the root cause of your problem is from Pycharm configurations or venv. see if you can open the python console. If you're new to pycharm, you can find the 'python console' option at the bottom of the screen.
Also here's a link that might help you. try some of the solutions there:
https://www.reddit.com/r/learnpython/comments/au6lvd/pycharm_code_works_but_doesnt_display_output/

Pygame keeps crashing on mac [duplicate]

This question already has answers here:
Why is my PyGame application not running at all?
(2 answers)
Closed 2 years ago.
I started learning pygame, wrote a simple program to display some text on the screen.
import pygame, time
pygame.init()
window = pygame.display.set_mode((600,300))
myfont = pygame.font.SysFont("Arial", 60)
label = myfont.render("Hello Pygame!", 1, (255, 255, 0))
window.blit(label, (100, 100))
pygame.display.update()
time.sleep(15)
pygame.quit()
But it keeps crashing.
I am using python2.7
The issue is that you are running the code only once and not repeating the lines of code that need to be repeated for every frame.
Then you are calling pygame.quit() without exiting the Python thread with quit() which results in the windows just "crashing" or not responding.
To fix this problem:
Include some code inside a while loop that will run on every frame and thus keep the program running and responding.
Make sure that initialization code is only ran once.
Add in some event handling to let the user exit the program when the "X" button is clicked.
Some useful additions:
Included a Clock which allows for an FPS-cap.
Filled the screen with black every frame
Exited the game properly with pygame.quit() to exit the pygame window and sys.exit() to exit the Python thread.
A Clock in pygame game allows you to specify an FPS. At the end of every main game loop iteration (frame) you call clock.tick(FPS) to wait the amount of time that will ensure the game is running at the specified framerate.
Here is the revised code example:
import pygame
import sys
# this code only needs to be ran once
pygame.init()
window = pygame.display.set_mode((600,300))
myfont = pygame.font.SysFont("Arial", 60)
label = myfont.render("Hello Pygame!", 1, (255, 255, 0))
clock = pygame.time.Clock()
FPS = 30
while True:
#allows user to exit the screen
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# this code should be ran every frame
window.fill((0, 0, 0))
window.blit(label, (100, 100))
pygame.display.update()
clock.tick(FPS)
I hope that this answer has helped you and if you have any further questions please feel free to post a comment below!

Pygame display not responding

I'm slowly trying to get to know pygame and write my first game in it and honestly, I didn't expect problems so early. So far I've only set a display, that is supposed to be there indefinitely (I just wanted to try it out):
import pygame
pygame.init()
(width, height) = (1000, 700)
screen = pygame.display.set_mode((width, height))
while True:
pygame.display.flip()
But when the window appears it says it's "not responding". I tried deleting the loop so that display would just blink once and vanish, because programm would die immiedately after it's created, but I get the same "not responding" window. I'm using pygame 1.9.2 and python 3.5. I wonder if the trouble may be because of anaconda - the window is opened as subcart for anaconda by default.
Edit: So far I discovered that when I open it not from spyder, but just click on a file it works just fine. Is there any way to make it work by simple run and compile while in spyder or it's just how it's supposed to work?
Add this to your loop. For me the only time it isnt responding is when I click the X and this could be to do with the fact that pygame doesn't know what to do when that happens.
import sys
for evt in pygame.event.get():
if evt.type == pygame.QUIT:
pygame.quit()
sys.exit()
#Try This
import pygame
(width, height) = (1000, 700)
screen=pygame.display.set_mode((width, height))
pygame.display.update()
while True:
for event in pygame.event.get():``
if event.type == pygame.QUIT:
pygame.quit()
quit()

"Text has zero width" error after reinitializing Pygame display?

I have a project in Pygame 1.9.2 where I reinitialize the display multiple times, and draw text to the display surface. It works fine until I close the Pygame display and re-initialize it again.
It follows a structure like this:
from pygame import *
init() # this is pygame.init()
running = True
while running:
display.set_mode((800,600))
visible = True
textFont = font.SysFont("Comic Sans MS", 12)
while visible:
for evt in event.get():
if evt.type == QUIT:
visible = False
if evt.type == KEYDOWN:
if evt.key == K_ESCAPE:
visible = running = False
textPic = textFont.render("Hello world!", True, (255,255,255))
display.get_surface().blit(textPic, (0,0))
display.flip()
quit()
This program works until the display is closed for the first time and then reinitialized, after which I receive the following error when trying to use textFont.render:
pygame.error: Text has zero width
I'm tearing my hair out trying to figure out what's wrong... I know that "Hello world!" has a width greater than zero. How do I fix this problem?
The problem is that pygame.quit() was called before the program was finished. This causes every Pygame module (e.g. pygame.font) to be uninitialized.
Instead of relying on pygame.quit to close the Pygame display, use pygame.display.quit at the end of every while running loop. Then put pygame.quit at the very end of the script to unload the rest of the modules after they're done being used.
(Calling pygame.init() again before rendering text won't fix this issue either, because it causes the Pygame display to stop responding. (This might be a bug with Pygame 1.9.2)
I found a solution that worked for me: just delete the font element before calling pygame.display.quit(), ie just del font every time you're done using it.
The font element is the one you created using the command:
font.SysFont("Comic Sans MS", 12)
but that I personally create using pygame.font.Font(None, font_size)

Categories