Pygame, the window becomes irresponsive when I try to click it - python

I'm working on a game with Pygame and it was going well...until it decided to not respond. Here's my code:(sorry if the formatting doesn't work im new to stackoverflow)
#MODULES USED (use from to make calling functions easier)
from random import *
from pygame import *
import pygame
from pygame.locals import *
pygame.init()
from time import *
#INITIALISE THE PYGAME WINDOW
pygame.event.pump()
screen = display.set_mode([500, 500])
blue = [230, 242, 255]
screen.fill(blue)
pygame.display.update()
default = pygame.image.load("default.jpg")
screen.blit(default, (0,0))
pygame.display.update()
click = pygame.mouse.get_pressed()
#BASIC HEXAPAWN
#ALL POSSIBLE COMPUTER'S MOVE BOARDS AS ARRAY HERE
#TThe moves from the board images are left to right
class Board:
def __init__(self, board, moves):
self.board = board
self.moves = moves
boards1 = [pygame.image.load("a1.jpg"), pygame.image.load("a2.jpg"), pygame.image.load("a3.jpg")] #move1 boards
#irrelevant stuff removed, just initialising the other boards.
#GAME MAIN LOOP
while True:
#START GAME - 1st move
print("You play as O, computer is X")
currentboard = "O O O\n# # #\nX X X"
print(currentboard)
#PLAYER MOVE 1
screen.blit(boards1[0], (0, 250))
pygame.display.update()
if boards1[0].get_rect().collidepoint(pygame.mouse.get_pos()) and click:
screen.blit(boards1[0], (0,0))
pmove = 0
#note: I haven't added the other board options yet.
currentboard = boards1[pmove]
#[insert more unnecessary code here]
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
break
pygame.quit()
Basically whenever I run the code, the Pygame window looks alright, but when I try to click on the image it just stops responding. Also the window is always stuck on a loading cursor, idk why.
I've tried everything I could find but, nope, not working.
If anyone can help then I'd appreciate it.
Thanks :)
Eleeza
edit:i didnt know others could edit my posts too
Clearing some stuff up, when I ran my code, there were no errors, no Traceback the only problem is the unresponsive thing.
Also sorry im really bad at explaining things :/

There are a few things going on, but the main one is that you have you click variable set only once when the program starts.
Move click = pygame.mouse.get_pressed() inside of the main loop.
If you do that and it still hangs, you should show the rest of your code.
Also, the full code is not there, so I can't be 100% sure, but I don't think that break should be there.

Related

Pygame : The game stops temporarily when I am moving the window

I'm a new in PyGame and I was making a game. Until I discovered that when you were moving the window to another place of your desktop for example, the game temporarily stops. But ticks of the game still running when I used pygame.time.get_ticks().
So I made a completely new program with only the necessary code and it does the same thing.
Can someone explain me why it does it and if we can resolve this problem?
import pygame
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption('The Test Program')
running = True
update_counter = 1
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
print(str(update_counter) + " updates")
update_counter += 1
pygame.quit()
quit()
# So try to move the window across your screen and you will see that, prints will stop and they will resume when you will release the click
So someone tell me that was normal, so I think it's only on Windows but there are no solutions. I put a script that show a pause symbol on screen when the cursor leave the window to make it normal.

Python Can't load background images in pygame

i try to load backgroud.png using pygame.image.load(),but i get nothing.here is my code,please help me ,thanks.
import pygame
pygame.init()
# screen
screen = pygame.display.set_mode((480, 700))
# 1.load_image
bg = pygame.image.load("./images/background.png")
# 2.blit
screen.blit(bg, (0, 0))
# 3.update
pygame.display.update()
while True:
pass
pygame.quit()
here is my sreen:it get nothing
With a game you're making all stuff that needs to be refreshed needs to be in the main game loop, your problem is, is you are drawing the image outside that game loop, meaning it gets drawn once then cleared and never drawn again.
To fix your code this is how you would write it:
import pygame
pygame.init()
# screen
screen = pygame.display.set_mode((480, 700))
# 1.load_image
bg = pygame.image.load("./images/background.png")
while True:
# 2.blit
screen.blit(bg, (0, 0))
# 3.update
pygame.display.update()
pygame.quit()
But notice how the bg=pygame.image... is outside the loop, this is because if it was inside the loop it would create a new instance of that image every time the loop happens.
The main game loop works by looping through all your functions and other stuff and then doing again and again, and again.
A game loop is how fps works, basically it is the measurement of how many times per second that game loop happens.
Make sure whenever you are doing anything in the loop it actually has a place there, for example loading an image doesn't, but updating where the player is on the screen does.
If you want to have a look at a good game loop that can be applied to most game engines this website will help you. But don't look at the most complex one when using pygame as it isn't built for that. Fix Your Timestep!
But your original problem of the image not loading isn't the case, it was loading but you were drawing your image in the wrong way, if you want a basic tutorial on pygame watch these videos: Game Development in Python 3 With PyGame - 1 - Intro
A better system to ease development
import pygame
bg = None
def load_resources():
bg = pygame.image.load("./images/background.png")
# all other resources
def render():
screen.blit(bg, (0,0))
def update():
# all logic updates for example movement of entities.
### start of game
load_resources()
while True:
update()
render()
pygame.display.update()
pygame.quit()
I think you should not write pass inside while loop because of it the output window will stop responding. Also you should write the screen blit and display.update inside while loop and you should write the correct image extension in the path. You can also write the full path of the file like ==> pygame.image.load(r"C:\Users\Desktop\back_ground.jpg")
import pygame
pygame.init()
# screen
screen = pygame.display.set_mode((480, 700))
# 1.load_image
bg = pygame.image.load("back_ground.jpg")
while True:
# 2.blit
screen.blit(bg, (0, 0))
# 3.update
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

Tab out of Pygame fullscreen window without crashing it

So I'm using Pygame to create a fancy display for a program I am writing. I chose Pygame because it's easy to get started and does a great job with animations. I want the display to be as big as I can make it so as much information can be shown as possible. Here is the kicker however, I still want to be able to get to the console of the program.
Pygame forces a fullscreen window to the front, so you cant tab out, and moving the windows to another windows desktop crashes the display. I would do a key trick to switch the pygame mode, but I cannot use pygame.event.get() because of how the program the threaded.
Is there a way to make it a full-screen window so that I can tab out and leave it up in the background? I dont really want it to just be a normal window because it is not as big that way.
The display crashes after I tab out and back in, here is what that looks like:
I also get a non-zero exit code: -805306369 (0xCFFFFFFF)
Here is a broken down version of the code that still gives me this error, you'll notice there are some things in here you wouldn't have if this was your full program, but I wanted to retain as much architecture as I could.
import pygame
import os
BACKGROUND = (9, 17, 27)
os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0"
pygame.init()
pygame.font.init()
infoObject = pygame.display.Info()
SIZE = (infoObject.current_w, infoObject.current_h)
X_CENTER = SIZE[0]/2
Y_CENTER = SIZE[1]/2
# create a borderless window that's as big as the entire screen
SCREEN = pygame.display.set_mode((SIZE[0], SIZE[1]), pygame.NOFRAME)
clock = pygame.time.Clock()
TextFont = pygame.font.SysFont('Courant', 30)
class DisplayState:
state = type(bool)
def __init__(self):
self.state = True
def get_state(self):
return self.state
def change_state(self, new_state):
self.state = new_state
def main(display_state_object):
running = True
while running:
if display_state_object.get_state():
SCREEN.fill(BACKGROUND)
pygame.display.flip()
else:
return 1
return
if __name__ == "__main__":
main(DisplayState())
EDIT
I think it is a multi-threading problem! See this code:
Produces Error
def start_display():
display(params)
def display(params):
pygame loop
if __name__ == "__main__":
display_thread = threading.Thread(target=start_display)
display_thread.start()
Does not produce error
def display(params):
pygame loop
if __name__ == "__main__":
display_thread = threading.Thread(target=display(params))
display_thread.start
# marker
One problem with the version that does work, the program does not seem to be continuing forwards outside the thread (ie the marker is never reached). Is this how the threading library works? It may explain why I had the middle man function present. Maybe this is a different problem and deserves its own question?
EDIT
Setting up the thread like this allows the main thread to continue, but brings back the pygame error:
threading.Thread(target=display, args=(DisplayState(),))
There's no easy way to do this on windows/sdl using the real fullscreen mode, and the usual way to solve this is to use a borderless window.
Here's how to create such a "fake" fullscreen window in pygame:
import pygame
import os
# you can control the starting position of the window with the SDL_VIDEO_WINDOW_POS variable
os.environ['SDL_VIDEO_WINDOW_POS'] = "0,0"
pygame.init()
# now let's see how big our screen is
info = pygame.display.Info()
# and create a borderless window that's as big as the entire screen
screen = pygame.display.set_mode((info.current_w, info.current_h), pygame.NOFRAME)
You have to call one of the pygame event functions (e.g. pygame.event.pump() or pygame.event.get()) each frame or the window will become unresponsive and the program will appear to have crashed. If you call one of those functions, you should be able to press Alt+Tab (in Windows) to get back to the desktop without crashing the program (if you select the desktop, the window will be minimized and if you select another window, it will just be brought to the front).
def main(display_state_object):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
# Press Esc to quit.
if event.key == pygame.K_ESCAPE:
running = False
if display_state_object.get_state():
SCREEN.fill(BACKGROUND)
pygame.display.flip()
else:
return 1
return

Python pygame window keeps crashing

Whenever I run my code the Python Window that shows up does not respond.
Is there something wrong with my code or do I have to re-install pygame and python?
I get a black pygame window and then it turns white and says not responding?
Also I am new to this so please make this as simple as possible. I tried looking everywhere for the answer but could not get it in a way that I could understand.
Please help me out. Thanks :)
1 - Import library
import pygame
from pygame.locals import *
2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
3 - Load Images
player = pygame.images.load("resources/images/dude.png")
4 - keep looping through
while 1:
# 5 - clear the screen before drawing it again
screen.fill(0)
# 6 - draw the screen elements
screen.blit(player, (100,100))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
Don't import pygame.locals. It is actually unnecessary, since you are already importing pygame.
Also, as #furas said, it should be:
player = pygame.image.load("resources/images/dude.png")
Not:
player = pygame.images.load("resources/images/dude.png")
This will clear up some of the problems in your code.
From my personal experience,if you run pygame code from IDLE it often does not respond at all.Try saving your project as a .py file and then run it with python.exe.It always works for me.
And as furas said use
player = pygame.image.load("resources/images/dude.png")
instead of
player = pygame.images.load("resources/images/dude.png")
Replace that for loop with this
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

PyGame: pygame.image.load() does not show anything

I am doing an assignment with pyGame, a very simple one, we have to load an image in a window, but it does not load! And the IDLE does not show any errors..I tried relative paths to my image (room.png) also absolute paths (C:...\room.png) but nothing. Here is my code.
import pygame, sys #import pygame and system library
from pygame import * #import all pygame sublibs
pygame.init()
screen = display.set_mode((385,384)) #set screen size
display.set_caption("Blit example")
#this one gets the current working directory
background_file_name = "room.png" #import bg
background_surface = pygame.image.load(background_file_name) #use bg
while True:
for e in pygame.event.get():
if e.type==QUIT: #break the loop and quit
pygame.quit()
sys.exit()
break
screen.fill((255,0,255)) #fill the screen with magenta
screen.blit(background_surface, (0,0))
display.update()
Your indentation is messed up.
You only start drawing after the application has ended.
Try putting the drawing code into your main loop.
Since you said in a comment you had no idea about programming, you probably don't know that indenting is important in python. Your while loop is running continuously, waiting for an exit signal. But the display is only performed after that...
while True:
for e in pygame.event.get():
if e.type==QUIT: #break the loop and quit
pygame.quit()
sys.exit()
break
screen.fill((255,0,255)) #fill the screen with magenta
screen.blit(background_surface, (0,0))
display.update()
now the display code is inside the while loop

Categories

Resources