I've been trying to figure how to set up pause and unpause function on my game that allows me to use space to pause and then unpause as well. I've been struggling mostly because I'm so new to coding. I feel like I'm not understanding the true and false or rather the binds.
The code is as follows:
import random
from tkinter import *
def paused(window):
PAUSED = False
while True:
pause(window)
canvas.create_text(canvas.winfo_width() / 2, canvas.winfo_height() / 2, font=('consolas', 70), text="PAUSED", fill="white", tag='paused')
window.keys.bind("<space>", paused)
if not paused:
paused = False
window.update()
I am assuming you are using pygame. In pygame, you can listen to pygame.event and check if the space bar has been clicked.
PAUSED = False
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
PAUSED = not PAUSED # inverts PAUSED
if not PAUSED:
draw() # update
clock.tick(60)
Otherwise, you can use the keyboard module.
Related
Okay I've created Space Invaders in Python 3.7.4 and Pygame 1.9.6. I've got everything working no bugs or anything. I've even got the paused button to work great. It's just when the screen puts up 'GAME OVER' text to signify you lost. I would like to pop up a window to ask play again after the text goes away. But I just don't know where to begin at. I've looked at How do I restart a program based on user input? for help, but I couldn't understand where to implement it at or where to look at. This was my first real project/game I created in Pygame.
Code:
paused = False
running = True
while running:
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_p: # Pausing
paused = True
if event.key == pygame.K_u: # Unpausing
paused = False
if not paused:
'''The rest of the code, with the movement key presses, etc.'''
Since everything above the 'while running loop' is constantly being loaded or for data retrieval like the images the coordinates for where the images should be, the background music, etc. So I wanted it to be like the pausing/unpausing part of the code when I press down on say 'r'. I want to replay the program without exiting it. So I would be very grateful for help by people. Thank you all.
You have to create function or methods in object to reset data and use it before every game. You can use external while-loop for this.
# executed only once
pygame.init()
screen = ...
# .. load data ...
player = ...
enemy = ...
gameing = True
while gameing:
# reset data before every game
player.reset()
enemy.reset()
score = 0
paused = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT: # exit game
running = False
gameing = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r: # restart game (but don't exit)
running = False
#gameing = True
if event.key == pygame.K_x: # exit game and program
running = False
gameing = False
if game_over: # restart game (but don't exit)
running = False
#gameing = True
You can also organize it as #Starbuck5 mentioned in commen - but then you should use running to exit program but not to exit game on game over
def reset():
global score, paused, running
player.reset()
enemy.reset()
score = 0
paused = False
running = True
# executed only once
pygame.init()
screen = ...
# .. load data ...
player = ...
enemy = ...
# (re)set data before first game
reset()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT: # exit game
running = False
gameing = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r: # restart game (but don't exit)
#running = False # DON'T DO THIS
reset()
if event.key == pygame.K_x: # exit game and program
running = False
if game_over: # restart game (but don't exit)
#running = False # DON'T DO THIS
reset()
This need use global for every variable which you have to reset so it can be more useful when you have code in classes and you can use self. instead of global
When I want to freeze my pygame window for a few seconds I usually use time.sleep(). However, if I accidentaly press any key on my keyboard meanwhile it detects the key after the time has passed. Is there any way to freeze my pygame window so that the code won’t consider the key pressed?
You have to use pygame.time.wait() rather than time.sleep(). Be aware that the input has to be set in millisecond.
See documentation: time.wait()
Here is an example where the screen will change color every frame. The title bar displays the last key pressed.
If the space bar is pressed, the color change is paused for three seconds. Key presses are ignored, but other events may be handled during this period.
This is accomplished by setting up a custom timer and using a variable to track the paused state.
import pygame
import itertools
CUSTOM_TIMER_EVENT = pygame.USEREVENT + 1
my_colors = ["red", "orange", "yellow", "green", "blue", "purple"]
# create an iterator that will repeat these colours forever
color_cycler = itertools.cycle([pygame.color.Color(c) for c in my_colors])
pygame.init()
pygame.font.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode([320,240])
pygame.display.set_caption("Timer Example")
done = False
paused = False
background_color = next(color_cycler)
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == CUSTOM_TIMER_EVENT:
paused = False
pygame.display.set_caption("")
pygame.time.set_timer(CUSTOM_TIMER_EVENT, 0) # cancel the timer
elif not paused and event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
pygame.time.set_timer(CUSTOM_TIMER_EVENT, 3000)
pygame.display.set_caption("Paused")
paused = True
else:
pygame.display.set_caption(f"Key: {event.key} : {event.unicode}")
if not paused:
background_color = next(color_cycler)
#Graphics
screen.fill(background_color)
#Frame Change
pygame.display.update()
clock.tick(5)
pygame.quit()
EDIT: Change to ignore key-presses during the paused period as the question asked.
I'm using Python 3.5, and I want to make multi-keystroke function.
I mean, I want to make a function that notices Ctrl+S and Q.
But my program doesn't notice it.
Here's my code:
import threading, pygame, sys
from pygame.locals import *
from time import sleep
pygame.init()
screen = pygame.display.set_mode((1160, 640), 0, 0)
screen.fill((255, 255, 255))
pygame.display.flip()
def background():
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if pygame.key.get_mods() & pygame.KMOD_CTRL and event.key == pygame.K_s:
print('GOOD')
def foreground():
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
print('HELLO_WORLD')
if event.type == QUIT:
pygame.quit()
sys.exit()
b = threading.Thread(name='background', target=background)
b.start()
foreground()
By calling b.start(), you let the program go into the infinite loop of listening Ctrl+S event. The event of key combination, once obtained in the background thread, will not be released back into the event queue. and the foreground function won't be able to capture and process it.
If you want your program to be able to process different key combination. You should let one function to listen to key press event, and dispatch the event to different processing functions.
I want to make a FPS game in Pygame in windowed mode.
I need to be able to move my camera around for 360 degrees and more without limitation and with the hidden cursor.
I used Pygame's set_visible and set_pos but it doesn't prevent my mouse going out of the window and blocking on the screen borders.
import pygame
pygame.init()
game_display = pygame.display.set_mode((800,600))
pygame.mouse.set_visible(False)
exit = False
while (not exit):
pygame.mouse.set_pos = (400, 300)
mouse_move = (0,0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit = True
if event.type == pygame.MOUSEMOTION:
mouse_move = event.rel
if mouse_move != (0,0):
print(mouse_move)
pygame.quit()
You have to call pygame.event.set_grab(True) as well.
Better allow the users to exit with the Esc or another key, because they won't be able to click the x button anymore to close the window.
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
exit = True
i want to show an image as long as i hold a key pressed. If the key isn't pressed (KEYUP) anymore, the image should disappear.
In my code the image appears when i hold the key down, but i does not disappears right away. Anyone knows why the image does not stay visible as long as I hold my key pressed=?
button_pressed = False
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_UP:
button_pressed = True
print"True"
if event.type == KEYUP:
if event.key == K_UP:
button_pressed = False
if button_pressed:
DISPLAYSURF.blit(arrow_left, (20, SCREEN_HEIGHT/2 - 28))
Thanks in advance!!
Once you blittet your image to the screen, it will stay there until you draw something over it. It won't disappear by itself.
An easy solution is to just clear the screen every iteration of your main loop, e.g. something like:
while running:
DISPLAYSURF.fill((0, 0, 0)) # fill screen black
for event in pygame.event.get():
# handle events
pass
# I'm using 'key.get_pressed' here because using the KEYDOWN/KEYUP event
# and a variable to track if a key is pressed totally sucks and people
# should stop doing this :-)
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
# only draw image if K_UP is pressed.
DISPLAYSURF.blit(arrow_left, (20, SCREEN_HEIGHT/2 - 28))
pygame.display.flip()