What can I do to make my PyGame window respond? - python-3.x

I am trying to make a window open every time I run my code, but every time I run the code, it shows the window as unresponsive.
My code is as follows:
import os
import time
import sys
pygame.font.init()
WIDTH, HEIGHT = 500, 400
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("EscapeGame")
BG = pygame.transform.scale(pygame.image.load(os.path.join("GameMap1.png")), (WIDTH, HEIGHT))
def main():
fps = 60
clock = pygame.time.Clock()
def redraw_window():
WIN.blit(BG, (0,0))
pygame.display.update()
while True:
clock.tick(fps)
redraw_window()
for event in pygame.event.get():
if event.type == sys.exit:
sys.exit()
input()
main()
I've already tried a few thing with event.get and event.pump, I'm probably missing something very basic. Could someone tell me what else I could try?
Also, I'm new at pygame, so if anyone sees another mistake, please tell me about. I would greatly appreciate it.

The window is unresponsive because you don't handle the events by calling pygame.event.get().
While pygame.event.get() is in your code, it's never executed because
a) it's in a function you never call
b) your code blocks on the input() call
You're code should look like this:
import os
pygame.init()
WIDTH, HEIGHT = 500, 400
def main():
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("EscapeGame")
BG = pygame.transform.scale(pygame.image.load(os.path.join("GameMap1.png")).convert_alpha(), (WIDTH, HEIGHT))
fps = 60
clock = pygame.time.Clock()
while True:
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
WIN.blit(BG, (0,0))
pygame.display.flip()
main()

Related

Pygame gamepad won't run anymore with an Xbox 360 controller and an Ubuntu machine [duplicate]

This code goes into infinite loop. I cant use A button on xbox 360 controller
import pygame
from pygame import joystick
pygame.init()
joystick = pygame.joystick.Joystick(0)
pygame.joystick.init()
print("start")
while True:
if joystick.get_button(0) == 1 :
print("stoped")
break
I cant use A button on xbox 360 controller
Personnaly, I can, so this seems to be possible. You are just missing that pretty much every user input needs to be updated by pygame through pygame.event.get().
From the pygame documentation:
Once the device is initialized the pygame event queue will start receiving events about its input.
So, apparently you need to get the events in the while loop like such to make the joystick work:
import pygame
from pygame.locals import *
pygame.init()
joystick = pygame.joystick.Joystick(0)
while True:
for event in pygame.event.get(): # get the events (update the joystick)
if event.type == QUIT: # allow to click on the X button to close the window
pygame.quit()
exit()
if joystick.get_button(0):
print("stopped")
break
Also,
In the line if joystick.get_button(0) == 1, you don't need to type == 1 because the statement is already True.
You are initializing pygame.joystick twice: through the line pygame.init() and pygame.joystick.init().
You don't need to type from pygame import joystick because you already already have it in the line import pygame.
You can take this as reference and use it in your own way.
import pygame
import sys
pygame.init()
pygame.joystick.init()
clock = pygame.time.Clock()
WIDTH,HEIGHT = 500,500
WHITE = (255,255,255)
BLUE = (0,0,255)
BLUISH = (75,75,255)
YELLOW =(255,255,0)
screen = pygame.display.set_mode((WIDTH,HEIGHT))
smile = pygame.image.load("smile.jpg")
smile = pygame.transform.scale(smile,(WIDTH,HEIGHT))
idle = pygame.image.load("idle.jpg")
idle = pygame.transform.scale(idle,(WIDTH,HEIGHT))
joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.JOYBUTTONDOWN:
if event.button == 0: #press A button to smile
screen.fill(WHITE)
screen.blit(smile,(0,0))
pygame.display.update()
clock.tick(10)
elif event.type == pygame.JOYBUTTONUP:
if event.button == 0:
screen.fill(WHITE)
screen.blit(idle,(0,0))
pygame.display.update()
clock.tick(10)

Why won't my Pygame window background load?

Whenever I run my code, the window opens just fine but the background image will not load. Although the image won't load immediately, if I minimize the window and open it again, the image loads just fine.
This is my code:
import pygame
import os
pygame.init()
WIDTH, HEIGHT = 500, 365
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
BG = pygame.transform.scale(pygame.image.load(os.path.join("GameMap3.png")).convert_alpha(), (WIDTH, HEIGHT))
PLAYER1 = pygame.image.load(os.path.join("PlayerType1.gif"))
fps = 60
main_font = pygame.font.SysFont("comicsans", 50)
player_vel = 5
clock = pygame.time.Clock()
def Main():
global BG
while True:
WIN.blit(BG, (0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
Main()
You missed to update the display with either pygame.display.update() or pygame.display.flip()
def Main():
global BG
while True:
WIN.blit(BG, (0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
pygame.display.update() # <--- this is missing
Main()
The typical PyGame application loop has to:
handle the events with either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display with either pygame.display.update() or pygame.display.flip()
limit the frames per second to limit CPU usage with pygame.time.Clock.tick

My score system in Pygame overlaps over and over again [duplicate]

This question already has an answer here:
How can I move the ball instead of leaving a trail all over the screen in pygame?
(1 answer)
Closed 2 years ago.
I have looked at many YouTube videos and information online but is seems I can't find the answer. Every time I run the code the text appears with a zero but when clicking the enemy to earn points the number 1 overlaps with the zero and it doesn't change. This problem repeats over and over again. What do/can I do? I am new to the python code and there might be some unnecessary code so please bare that in mind if you see a rookie mistake thank you.
import pygame
import time
import random
pygame.init()
from pygame.locals import *
white = (255,255,255)
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("Extended Essay game")
BADGUY = pygame.image.load('enemy.png')
pygame.font.init()
#Enemy char
class Enemy():
def __init__(self, x, y):
self.x = x
self.y = y
def main():
run = True
FPS = 60
x = 0
enemies = 0
clock = pygame.time.Clock()
font = pygame.font.Font('freesansbold.ttf', 32)
window.fill((255,255,255))
window.blit(BADGUY,(0,0))
def update():
text = font.render("Enemies: " + str(enemies), True, (0,0,0))
window.blit(text, (200, 300))
pygame.display.update()
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
window.blit(BADGUY, (random.randint(0, 700), random.randint(0 , 700)))
enemies += 1
update()
main()
You need to clear the screen before putting new stuff on it. Put this at the beginning of update() or right before it is called in the loop:
window.fill((255, 255, 255))

How to prompt user to open a file with python3?

I'm making a game and I want the user to be able to click a button which opens the file manager and asks them to open a game save file. Is there a module / how could I put this in my game? If there's no good gui way how would I make a text input thing (without using the terminal)? Thanks!
Pygame is a low-level library, so it doesn't have the kind of built-in dialogs you're after. You can create such, but it will be quicker to use the tkinter module which is distributed with Python and provides an interface to the TK GUI libraries. I'd recommend reading the documentation, but here's a function that will pop up a file selection dialog and then return the path selected:
def prompt_file():
"""Create a Tk file dialog and cleanup when finished"""
top = tkinter.Tk()
top.withdraw() # hide window
file_name = tkinter.filedialog.askopenfilename(parent=top)
top.destroy()
return file_name
Here's a small example incorporating this function, pressing Spacebar will popup the dialog:
import tkinter
import tkinter.filedialog
import pygame
WIDTH = 640
HEIGHT = 480
FPS = 30
def prompt_file():
"""Create a Tk file dialog and cleanup when finished"""
top = tkinter.Tk()
top.withdraw() # hide window
file_name = tkinter.filedialog.askopenfilename(parent=top)
top.destroy()
return file_name
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
f = "<No File Selected>"
frames = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
f = prompt_file()
# draw surface - fill background
window.fill(pygame.color.Color("grey"))
## update title to show filename
pygame.display.set_caption(f"Frames: {frames:10}, File: {f}")
# show surface
pygame.display.update()
# limit frames
clock.tick(FPS)
frames += 1
pygame.quit()
Notes: This will pause your game loop, as indicated by the frame counter but as events are being handled by the window manager, this shouldn't be an issue.
I'm not sure why I needed the explicit import tkinter.filedialog, but I get an AttributeError if I don't.
As for string entry in pygame, you might want to do this natively, in which case you'd be handling KEYUP events for letter keys to build the string and perhaps finishing when the user presses Enter or your own drawn button. You could continue down the tk path, in which case you'll want to use something like tkinter.simpledialog.askstring(…)
It is possible to make a file dialogue (though not using the native file explorer) using the pygame_gui module.
Simply create an instance of UIFileDialog and grab the path when the user hits 'ok':
file_selection = UIFileDialog(rect=Rect(0, 0, 300, 300), manager=manager, initial_file_path='C:\\')
if event.ui_element == file_selection.ok_button:
file_path = file_selection.current_file_path
If you want to allow selecting a directory set allow_picking_directories to True, but note that it does not allow picking an initial_file_path.
file_selection = UIFileDialog(rect=Rect(0, 0, 300, 300), manager=manager, allow_picking_directories=True)
Here's the above code in a simple program that allows you to pick a file when the button is clicked:
#!/usr/bin/env python
import pygame
import pygame_gui
from pygame_gui.windows.ui_file_dialog import UIFileDialog
from pygame_gui.elements.ui_button import UIButton
from pygame.rect import Rect
pygame.init()
window_surface = pygame.display.set_mode((800, 600))
background = pygame.Surface((800, 600))
background.fill(pygame.Color('#000000'))
manager = pygame_gui.UIManager((800, 600))
clock = pygame.time.Clock()
file_selection_button = UIButton(relative_rect=Rect(350, 250, 100, 100),
manager=manager, text='Select File')
while 1:
time_delta = clock.tick(60) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
if event.type == pygame.USEREVENT:
if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
if event.ui_element == file_selection_button:
file_selection = UIFileDialog(rect=Rect(0, 0, 300, 300), manager=manager, allow_picking_directories=True)
if event.ui_element == file_selection.ok_button:
print(file_selection.current_file_path)
manager.process_events(event)
manager.update(time_delta)
window_surface.blit(background, (0, 0))
manager.draw_ui(window_surface)
pygame.display.update()

Key Pressing System PyGame

I'm making a basic pong game and want to make a system where a button press makes the paddle goes up or down. I'm fairly new to PyGame and here's my code so far.
import pygame, sys
from pygame.locals import*
def Pong():
pygame.init()
DISPLAY=pygame.display.set_mode((600,400),0,32)
pygame.display.set_caption("Pong")
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
DISPLAY.fill(BLACK)
while True:
def P(b):
pygame.draw.rect(DISPLAY,WHITE,(50,b,50,10))
xx=150
P(xx)
for event in pygame.event.get():
if event.type==KEYUP and event.key==K_W:
P(xx+10)
xx=xx+10
pygame.display.update()
elif event.type==QUIT:
pygame.quit()
sys.exit()
Please read some tutorials and/or docs. This is really basic and if you don't get this right it will bite you later.
Anyway, here's how it could look:
import pygame
pygame.init()
DISPLAY = pygame.display.set_mode((600,400))
paddle = pygame.Rect(0, 0, 10, 50)
paddle.midleft = DISPLAY.get_rect().midleft
speed = 10
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit(0)
keystate = pygame.key.get_pressed()
dy = keystate[pygame.K_s] - keystate[pygame.K_w]
paddle.move_ip(0, dy * speed)
DISPLAY.fill(pygame.Color("black"))
pygame.draw.rect(DISPLAY, pygame.Color("white"), paddle)
pygame.display.update()
clock.tick(30)
That is ok for Pong but I still wouldn't write my game like this. So read some tutorials and maybe try CodeReview if you really want to improve your code.

Resources