Video game not responding correctly to input - pygame

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

Related

Making a countdown timer in a Quiz game with pygame [duplicate]

I started using pygame and I want to do simple game. One of the elements which I need is countdown timer.
How can I do the countdown time (eg 10 seconds) in PyGame?
Another easy way is to simply use pygame's event system.
Here's a simple example:
import pygame
pygame.init()
screen = pygame.display.set_mode((128, 128))
clock = pygame.time.Clock()
counter, text = 10, '10'.rjust(3)
pygame.time.set_timer(pygame.USEREVENT, 1000)
font = pygame.font.SysFont('Consolas', 30)
run = True
while run:
for e in pygame.event.get():
if e.type == pygame.USEREVENT:
counter -= 1
text = str(counter).rjust(3) if counter > 0 else 'boom!'
if e.type == pygame.QUIT:
run = False
screen.fill((255, 255, 255))
screen.blit(font.render(text, True, (0, 0, 0)), (32, 48))
pygame.display.flip()
clock.tick(60)
On this page you will find what you are looking for http://www.pygame.org/docs/ref/time.html#pygame.time.get_ticks
You download ticks once before beginning the countdown (which can be a trigger in the game - the key event, whatever).
For example:
start_ticks=pygame.time.get_ticks() #starter tick
while mainloop: # mainloop
seconds=(pygame.time.get_ticks()-start_ticks)/1000 #calculate how many seconds
if seconds>10: # if more than 10 seconds close the game
break
print (seconds) #print how many seconds
In pygame exists a timer event. Use pygame.time.set_timer() to repeatedly create an USEREVENT. e.g.:
timer_interval = 500 # 0.5 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event , timer_interval)
Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case pygame.USEREVENT+1 is the event id for the timer event.
To disable the timer for an event, set the milliseconds argument to 0.
Receive the event in the event loop:
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == timer_event:
# [...]
The timer event can be stopped by passing 0 to the time parameter.
See the example:
import pygame
pygame.init()
window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 100)
counter = 10
text = font.render(str(counter), True, (0, 128, 0))
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, 1000)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == timer_event:
counter -= 1
text = font.render(str(counter), True, (0, 128, 0))
if counter == 0:
pygame.time.set_timer(timer_event, 0)
window.fill((255, 255, 255))
text_rect = text.get_rect(center = window.get_rect().center)
window.blit(text, text_rect)
pygame.display.flip()
pygame.time.Clock.tick returns the time in milliseconds since the last clock.tick call (delta time, dt), so you can use it to increase or decrease a timer variable.
import pygame as pg
def main():
pg.init()
screen = pg.display.set_mode((640, 480))
font = pg.font.Font(None, 40)
gray = pg.Color('gray19')
blue = pg.Color('dodgerblue')
# The clock is used to limit the frame rate
# and returns the time since last tick.
clock = pg.time.Clock()
timer = 10 # Decrease this to count down.
dt = 0 # Delta time (time since last tick).
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
timer -= dt
if timer <= 0:
timer = 10 # Reset it to 10 or do something else.
screen.fill(gray)
txt = font.render(str(round(timer, 2)), True, blue)
screen.blit(txt, (70, 70))
pg.display.flip()
dt = clock.tick(30) / 1000 # / 1000 to convert to seconds.
if __name__ == '__main__':
main()
pg.quit()
There are several ways you can do this- here's one. Python doesn't have a mechanism for interrupts as far as I know.
import time, datetime
timer_stop = datetime.datetime.utcnow() +datetime.timedelta(seconds=10)
while True:
if datetime.datetime.utcnow() > timer_stop:
print "timer complete"
break
There are many ways to do this and it is one of them
import pygame,time, sys
from pygame.locals import*
pygame.init()
screen_size = (400,400)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("timer")
time_left = 90 #duration of the timer in seconds
crashed = False
font = pygame.font.SysFont("Somic Sans MS", 30)
color = (255, 255, 255)
while not crashed:
for event in pygame.event.get():
if event.type == QUIT:
crashed = True
total_mins = time_left//60 # minutes left
total_sec = time_left-(60*(total_mins)) #seconds left
time_left -= 1
if time_left > -1:
text = font.render(("Time left: "+str(total_mins)+":"+str(total_sec)), True, color)
screen.blit(text, (200, 200))
pygame.display.flip()
screen.fill((20,20,20))
time.sleep(1)#making the time interval of the loop 1sec
else:
text = font.render("Time Over!!", True, color)
screen.blit(text, (200, 200))
pygame.display.flip()
screen.fill((20,20,20))
pygame.quit()
sys.exit()
This is actually quite simple. Thank Pygame for creating a simple library!
import pygame
x=0
while x < 10:
x+=1
pygame.time.delay(1000)
That's all there is to it! Have fun with pygame!
Another way to do it is to set up a new USEREVENT for a tick, set the time interval for it, then put the event into your game loop
'''
import pygame
from pygame.locals import *
import sys
pygame.init()
#just making a window to be easy to kill the program here
display = pygame.display.set_mode((300, 300))
pygame.display.set_caption("tick tock")
#set tick timer
tick = pygame.USEREVENT
pygame.time.set_timer(tick,1000)
while 1:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.USEREVENT:
if event.type == tick:
## do whatever you want when the tick happens
print('My tick happened')

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

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

pygame window not responding when runing program

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

How to cycle 3 images on a rect button?

Just started learning Python/Pygame watching videos and reading to learn . I would like to see a example code to cycle 3 images on a rect button from a mouse press and return to first image. Really I want the pictures to be three options and return different results. So be able to cycle image be able to select option and option when triggered execute choice.
Example
import pygame
pygame.init()
screen = pygame.display.set_mode((300,200))
# three images
images = [
pygame.Surface((100,100)),
pygame.Surface((100,100)),
pygame.Surface((100,100)),
]
images[0].fill((255,0,0))
images[1].fill((0,255,0))
images[2].fill((0,0,255))
# image size and position
images_rect = images[0].get_rect()
# starting index
index = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# check mouse position and pressed button
if event.button == 1 and images_rect.collidepoint(event.pos):
# cycle index
index = (index+1) % 3
screen.blit(images[index], images_rect)
pygame.display.flip()
pygame.quit()
Example using class - to create many buttons
import pygame
class Button(object):
def __init__(self, position, size):
self._images = [
pygame.Surface(size),
pygame.Surface(size),
pygame.Surface(size),
]
self._images[0].fill((255,0,0))
self._images[1].fill((0,255,0))
self._images[2].fill((0,0,255))
self._rect = pygame.Rect(position, size)
self._index = 0
def draw(self, screen):
screen.blit(self._images[self._index], self._rect)
def event_handler(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1 and self._rect.collidepoint(event.pos):
self._index = (self._index+1) % 3
pygame.init()
screen = pygame.display.set_mode((320,110))
button1 = Button((5, 5), (100, 100))
button2 = Button((110, 5), (100, 100))
button3 = Button((215, 5), (100, 100))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
button1.event_handler(event)
button2.event_handler(event)
button3.event_handler(event)
button1.draw(screen)
button2.draw(screen)
button3.draw(screen)
pygame.display.flip()
pygame.quit()
If I understood the question correctly, you need a single button that changes the look every time you click on it, and changes its relative function accordingly.
You should be able to solve your problem by creating a class that takes two list and a counter
1) list of images
2) list of functions
3) the counter tells you which image/function is selected.
The functions needs to be built in the class, but you can provide the image that you want in the class argument (actually, you could pass them as arguments, but I don't think is worth it).
Here is the code, I commented some lines with their intended meaning (in line comments)
import pygame
import sys
pygame.init()
width = 600
height = 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Magic Buttons")
background = pygame.Surface(screen.get_size())
clock = pygame.time.Clock()
class Buttons:
def __init__(self, posX, posY, image1, image2, image3):
self.image_list = [image1, image2, image3] # static list of images
self.function_list = [self.button_function_1,self.button_function_2,self.button_function_3 ]
self.rect_position = (posX, posY) # this is a tuple to identify the upper left corner of the rectangle of the image
self.button_type = 0 # initial value of the button, both for the function and the image
self.image = pygame.image.load(self.image_list[0]) #default image, index number 0 of image_list
self.rect = pygame.Rect(posX, posY, self.image.get_width(), self.image.get_height()) # create a rectangle object same size of the images
def check(self, pos):
if self.rect.collidepoint(pos) ==True:
self.change_button()
else:
pass
def change_button(self):
self.button_type = (self.button_type +1)%3
self.image = pygame.image.load(self.image_list[self.button_type ]) # load the image relative to button_type
self.function_list[self.button_type -1]() # execute the function relative to the new value of button_type
self.draw_button()
def draw_button(self):
screen.blit(self.image, self.rect_position) # blit the new button image
def button_function_1(self):
print ("function 1 in action")
def button_function_2(self):
print ("function 2 in action")
def button_function_3(self):
print ("function 3 in action")
multibutton = Buttons(100,100,"button1.png","button2.png","button3.png") # create an istance of the button in the x=100, y = 100, with the three image button
while True:
background.fill((0,0,0))
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONUP:
pos = pygame.mouse.get_pos() # fetch the position of the mouse
multibutton.check(pos) # check if the mouse is on the button
multibutton.draw_button()
pygame.display.flip()