Slowing time, but not the program - python

I'm making a game, where when a player steps outside the screen, the level starts. I wish to show an image of "LEVEL 1" before the game starts, yet the program shows the image too quickly. My framerate is at 60.
I am wondering if there is a way to delay time for about 5 seconds during the screen blitting but after it resumes to it's normal pace. The problem for me with the pygame.time.delay() and wait stuff is that is slows the entire program down.
Is there a easier way?
EDIT______ CODE
#START OF LEVEL 1
if level1:
screen.blit(level1_image,background_position)
pygame.time.delay(500)
level1yay = True
if level1yay:
screen.blit(background,background_position)
#Flip the Display
pygame.display.flip()
clock.tick(time)
#Quit
pygame.quit()
The first image is not displayed and goes directly to the second image

You could set up a timer and keep track of the time. when the timer reaches the delay you want you can do something.
In the example below I set up the timer and I set the level1yay to true only once the timer has reached the delay value.
I added a condition canexit so the game doesn't terminate on the first loop. I assumed that the condition for "if level1: " has been set somewhere else.
mytimer = pygame.time.Clock() #creates timer
time_count = 0 #will be used to keep track of the time
mydelay = 5000 # will delay the main game by 5 seconds
canexit = False
#updates timer
mytimer.tick()
time_count += mytimer.get_time()
#check if mydelay has been reached
if time_count >= mydelay:
level1yay = True
canexit = True
#START OF LEVEL 1
if level1:
screen.blit(level1_image,background_position)
if level1yay:
screen.blit(background,background_position)
#Flip the Display
pygame.display.flip()
clock.tick(time)
#Quit
if canexit == True:
pygame.quit()
EDIT TO INCLUDE ACTIONS PRIOR TO ENTERING LEVEL1:
mytimer = pygame.time.Clock() #creates timer
time_count = 0 #will be used to keep track of the time
mydelay = 5000 # will delay the main game by 5 seconds
canexit = False
start_menu = True # to start with the start menu rather than level1
#Do something before level 1
if start_menu == True:
... do stuff
if start_menu end:
level1 = True
time_count = 0
#START OF LEVEL 1
if level1 == True:
#updates timer
mytimer.tick() # start's ticking the timer
time_count += mytimer.get_time() # add's the time since the last tick to time_count
#check if mydelay has been reached
if time_count >= mydelay:
level1 = False # so that you do not enter level1 again (even though this is redundant here since you will exit the game at the end of the loop... see canexit comment)
level1yay = True # so that you can enter level1yay
canexit = True # so that the game terminates at the end of the game loop
screen.blit(level1_image,background_position)
if level1yay:
screen.blit(background,background_position)
#Flip the Display
pygame.display.flip()
clock.tick(time)
#Quit
if canexit == True:
pygame.quit()

I don't know if this will really work, but you could try displaying the same image of "LEVEL 1" multiple times in a row, so it appears to stay around longer, but the program itself is never actually delayed.

pygame.time.wait(5000) is a delay of 5 seconds, 500 is half a second. You did set the level1 variable to True just before this code fragment, right?

Related

Pygame: Adding an Escape key to exit whole game with stopwatch function

I'm making a game via Python on a Raspberry Pi. I'm using the GPIOs to light up an LED and detect a button switch.
I wanted to incorporate an ESC on the keyboard so we can exit at any time.
But whenever I add in the ESC key code into the main while loop. It doesn't work. The LED and Buttons work, but when I press on the ESC key, it doesn't do anything.
The loop runs to refresh/run a stopwatch and listen to an LED button via the GPIO.
I wanted some advice on how things like ESC key are handled in games. Especially with fast paced games where the loop and cycles are very fast.
Any tips or suggestions would be greatly appreciated. Thanks in advance.
Please see the code below:
# Importing all libraries
import RPi.GPIO as GPIO
import sys, time, atexit, pygame
# Setup GPIO and Pygame
GPIO.setmode(GPIO.BCM)
pygame.init()
# Define Tuples and Variables
leds = (16,17,22,9,5)
switches = (19,4,27,10,11)
button_pressed = False
taskcomplete = False
# Pygame visual variables
screen = pygame.display.set_mode( (1024,240) )
counterfont = pygame.font.Font('DSEG14Modern-Regular.ttf', 70)
# Set Pygame refresh rate variable = clock
clock = pygame.time.Clock()
# Clock variables
sec_val = 0
sec = 0
mins = 0
hours = 0
# Status variables
paused = False
running = True
# Start the clock
start_time = pygame.time.get_ticks()
# Defining Functions
# Function that renders segment display on screen
def time_convert(sec):
sec = sec % 60
sec_val = ("Timer: {0}".format(round((sec), 2)))
counting_text = counterfont.render(str(sec_val), 3, (134,145,255))
counting_rect = counting_text.get_rect(left = screen.get_rect().left)
screen.fill( (0,0,0) )
screen.blit(counting_text, (300,40))
pygame.display.update()
# Stopwatch function to compute for a SS:MS based stopwatch
def stop_Watch():
end_time = time.time()
time_lapsed = end_time - start_time
sec_val = time_convert(time_lapsed)
# Press Button 1 to start the game
def but_3():
while GPIO.input(switches[2]) == GPIO.LOW:
GPIO.output(leds[2],True)
time.sleep(0.01)
stop_Watch()
GPIO.output(leds[2],False)
print(" Button 3 is pressed! Exit")
start_time = time.time()
def buttonPress(channel):
# This function gets called every time a button is pressed, if the button pressed is the same as the button
# that is illuminated, then we set the "correct_button" variable to True,
# otherwise we set the "incorrect_button" variable to True.
# We need to set some variables to global so that this function can change their value.
button_pressed = True
def exit():
# This function gets called when we exit our script, using Ctrl+C
print("GPIO Clean Up!")
GPIO.cleanup()
pygame.quit()
# This tells our script to use the "exit()" without this, our "exit()" function would never be called.
atexit.register(exit)
#Loop through the leds to set them up
for led in leds:
# Set the led to be an ouput
GPIO.setup(led, GPIO.OUT)
# Turn the led off
GPIO.output(led,False)
# Loop through the switches to set them up
for switch in switches:
# Set the switch to be an input
GPIO.setup(switch, GPIO.IN)
# Add rising edge detection
GPIO.add_event_detect(switch, GPIO.RISING, bouncetime=300)
# Add the function "buttonPress" to be called when switch is pressed.
GPIO.add_event_callback(switch, buttonPress)
# Main sequence code
# Setup Pygame refresh rate to 120 fps
clock.tick(120)
# Start timer
start_time = time.time()
# Main loop
while running:
# Press Button 1 to start the game
while GPIO.input(switches[0]) == GPIO.LOW:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
print("escape pressed")
running = False
GPIO.output(leds[0],True)
time.sleep(0.01)
stop_Watch()
GPIO.output(leds[0],False)
print(" Button 1 is pressed! Exit")
running = False
exit()
It's because it's in another while loop I'm guessing, so it's not in the running while loop anymore. You can add pygame.quit() to make it quit that way though:
# Main loop
while running:
# Press Button 1 to start the game
while GPIO.input(switches[0]) == GPIO.LOW:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
print("escape pressed")
pygame.quit()
running = False
GPIO.output(leds[0],True)
time.sleep(0.01)
stop_Watch()
GPIO.output(leds[0],False)
print(" Button 1 is pressed! Exit")
running = False
exit()
Or, since you have a function named exit() that does the same thing, you can add exit() to those places instead.

Can't click on image again, what's wrong with my pygame code?

Okay, I'am trying to create a Tom and Jerry game with the pygame library.
The game focuses on catching mice by clicking on them as they appear in their holes. The problem
is that sometimes a cat appears instead of a mouse and should the player erroneously click on the
cat (s)he looses all earned points, but the game continues.
The mouse is an image of a mouse and the cat is an image of an cat.
If you click on the mouse, you get mouse, otherwise the cat gets the points.
The code is a mess, that's because I don't know what I'am doing and just set an another event loop because then it works, because it runs after I create the mouse. It works to click on the mouse but then you click somewhere else and after that it's like you did not clicked on the mouse.
The mouse is created in a loop and is supposed to wait for 5 seconds and if you click on the mouse within these seconds then an appropriate message prints out in the console ,,Jerry clicked!" else "1 click". If you don't click on the mouse within 5 seconds a image covers the mouse so she disappears.
Now, what I'am trying to do right now is to print the message 1 click when the player does not click on anything but print 1 click jerry clicked when the player clicks on the mouse. I have a image of the mousehole and then I put the mouse on the mousehole, that is, on an another image.
This code works with one image at least:
pygame.init()
width=350;
height=400
screen = pygame.display.set_mode( (width, height ) )
pygame.display.set_caption('clicked on image')
redSquare = pygame.image.load("images/red-square.png").convert()
x = 20; # x coordnate of image
y = 30; # y coordinate of image
screen.blit(redSquare , ( x,y)) # paint to screen
pygame.display.flip() # paint screen one time
running = True
while (running):
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
# Set the x, y postions of the mouse click
x, y = event.pos
if redSquare.get_rect().collidepoint(x, y):
print('clicked on image')
#loop over, quite pygame
pygame.quit()
My problem is that, when I click on the mouse and then I don't click on the mouse I can't click on the mouse again at another position.
So what's wrong? What I'am doing wrong here?
Here is my code:
import pygame
from pygame import *
from random import *
init()
run = True
screen = (800,800)
screen = display.set_mode(screen)
xpos = 0
ypos = 0
mouseorcatxpos = 5
mouseorcatypos = 0
mousehole = image.load("mousehole.png").convert()
cat = image.load("tom.png")
jerry = image.load("jerry.png")
def makeholes():
global ypos
global xpos
for holey in range(1,9):
for holex in range(1,9):
screen.blit(mousehole,(xpos,ypos))
display.flip()
xpos += 100
ypos += 100
xpos = 0
def mouseorcat():
global xpos
mouseorcatxpos = 5
ypos = 0
for mousecaty in range(1,9):
pygame.event.pump()
for mousecatx in range(1,9):
randommouse = randint(1, 3)
randomcat = randint(1, 10)
if(randommouse == 2):
screen.blit(jerry, (mouseorcatxpos, ypos))
display.flip()
for event in pygame.event.get():
if (event.type == MOUSEBUTTONDOWN):
if jerry.get_rect().collidepoint(xpos, ypos) == False:
print("l clicked!")
x, y = event.pos
if jerry.get_rect().collidepoint(xpos, y):
print("JERRY CLICKED!!")
x, y = event.pos
print(x, y)
time.wait(5000)
#screen.blit(mousehole, (mouseorcatxpos - 5, ypos))
display.flip()
elif(randomcat == 2):
screen.blit(cat, (mouseorcatxpos, ypos))
display.flip()
time.wait(1500)
screen.blit(mousehole, (mouseorcatxpos-5, ypos))
display.flip()
mouseorcatxpos += 100
mouseorcatxpos = 0
ypos += 100
makeholes()
while run == True:
for event in pygame.event.get():
mouseorcat()
if event.type == QUIT:
run = False
I rewrote your game to show you how I would do it.
To keep track of the time and to limit the framerate I used a pygame.time.Clock and a timer variable. The clock returns the time in milliseconds since clock.tick was called the last time, which is used to increase the timer variable. The cat just replaces the mouse after two seconds and the mouse is set to a new position. I use pygame.Rects to store the positions, but you could also use lists or tuples.
import sys
import random
import pygame
pygame.init()
size = (800, 800)
screen = pygame.display.set_mode(size)
# Images replaced by pygame.Surface. Do that too
# in the future before you post your code.
mousehole = pygame.Surface((40, 40)).convert()
mousehole.fill(pygame.Color(30, 30, 30))
cat = pygame.Surface((40, 40)).convert()
cat.fill(pygame.Color(110, 110, 130))
jerry = pygame.Surface((40, 40)).convert()
jerry.fill(pygame.Color(190, 130, 0))
# Create the background image and blit the holes.
background = pygame.Surface(size).convert()
for holey in range(8):
for holex in range(8):
background.blit(mousehole, (holex*100, holey*100))
def new_position():
"""Return a random position between 0-700 in steps of 100."""
return (random.randrange(0, 701, 100), random.randrange(0, 701, 100))
def main():
fps = 30
clock = pygame.time.Clock()
jerry_rect = jerry.get_rect() # Stores jerry's position and size.
jerry_rect.topleft = new_position() # New random position.
# The cat is outside of the screen first.
cat_rect = cat.get_rect(topleft=(-100, -100))
points = 0
timer = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
if jerry_rect.collidepoint(event.pos):
points += 1
print('Jerry caught! Points:', points)
timer = 0
jerry_rect.topleft = new_position()
else:
print('Missed. Points:', points)
# Run logic.
timer += clock.tick(fps) / 1000 # timer + seconds since last tick.
if timer > 2: # Cat catches mouse after 2 seconds.
cat_rect.topleft = jerry_rect.topleft
jerry_rect.topleft = new_position()
timer = 0
points = 0
print('Tom caught Jerry.')
# Draw.
# Clear the screen by blitting the bg.
screen.blit(background, (0, 0))
screen.blit(jerry, jerry_rect)
screen.blit(cat, cat_rect)
pygame.display.flip()
if __name__ == '__main__':
main()
pygame.quit()
sys.exit()
Side notes:
Don't use star imports (from module import *), because that can make code harder to read. If you want you can use from pygame.locals import *, if it's the only star import.
Don't use global variables, because they can make code harder to read, understand and maintain. Pass variables to functions as arguments and then return the result.
Update: Some notes about your program:
The first big problem is that your game has two event loops and the important one is deeply nested inside of two other for loops and a if. The event loop should be directly under the main while loop (one indentation level (when you have more experience you can put it into a function or class method)).
The two for loops seem to have the purpose to let the code run until randommouse or randomcat are 2. To run code until a condition is met is the purpose of a while loop. But in this case you should better just pick a random number and write the if/elif conditions so that they always apply. For example, you want a 2/3 chance for mouse and 1/3 for a cat,
random_number = random.randint(1, 3)
if random_number < 3:
print("2/3 probability. It's a mouse")
else:
print("1/3 probability. It's a cat")
Or use random.choice with a list:
>>> random.choice(['mouse', 'mouse', 'cat'])
'mouse'
time.wait(5000) shouldn't be used because the game just hangs in this time. You can't even close the window. Limit the framerate and get the time since the last tick with a pygame.time.Clock.
pygame.event.pump() is not needed.
If you call get_rect() without an argument, the rect is positioned at (0, 0).
if jerry.get_rect().collidepoint(xpos, y):
That's the reason why clicking on jerry only works in the top row, and because you use the global xpos here. Since xpos is 0, the whole top row counts as Jerry.
You can pass coordinates to get_rect like so (you can also use center or other args instead of topleft):
jerry_rect = jerry.get_rect(topleft=(50, 100))
I'm sorry but I don't think I can simply fix your code. I've tried it several times, but I always end up re-writing it completely.
I begin by extracting the event loop out of the two nested for loops, then remove these loops, create rects for the mouse and cat, fix the collision detection, add a timer and so on. Take a close look at my example and try to rewrite your game in a similar way, and keep asking questions if you don't understand something.

How to play in-game sounds?

I'm trying to create a simple game by using Pygame and I want to add some in-game sounds repeating during play time. However, the game stops running when I apply those codes:
def in-gameSounds():
pygame.mixer.init()
startTime = time.time()
theFile = 'Sounds/gameSound.ogg'
theFile2 = 'Sounds/gameSound2.ogg'
pygame.mixer.music.load(theFile)
pygame.mixer.music.play()
playing = True
while playing == True:
while time.time() <= startTime + 457:
time.sleep(0.01)
pygame.mixer.music.stop()
pygame.mixer.music.load(theFile2)
while time.time() > startTime + 457 and time.time() <= startTime+ 3752:
time.sleep(0.01)
pygame.mixer.music.stop()
for click in pygame.event.get():
if click.type == pygame.KEYDOWN:
if click.key == pygame.K_ESCAPE:
playing = False
startTime -= 3752
pygame.mixer.quit()
Have you tried passing pygame.mixer.music.play() an argument of -1? That makes it loop indefinitely. From there you can use the pause(), unpause(), and rewind() methods.
You could always use pygame.mixer.init() followed by pygame.mixer.music.play(-1) in the top of your program instead of putting it in a function. Since a value of -1 one inside of the () will mean an infinite loop, the music will continuously play unless forced to stop via program killing, Ctrl-C, etc.
pygame.mixer.init() # Initiate pygame.mixer
pygame.mixer.music.load('song_name_here') # Load song to play
pygame.mixer.music.set_volume(0.7) # Change volume
pygame.mixer.music.play(-1) # Play song infinitely

Python time counter in Pygame-mouse events

I want to calculate the time of user's mouse events in Pygame, if user doesn't move his mouse about 15 seconds, then I want to display a text to the screen. I tried time module for that, but it's not working.
import pygame,time
pygame.init()
#codes
...
...
font = pygame.font.SysFont(None,25)
text = font.render("Move your mouse!", True, red)
FPS = 30
while True:
#codes
...
...
start = time.time()
cur = pygame.mouse.get_pos() #catching mouse event
end = time.time()
diff = end-start
if 15 < diff:
gameDisplay.blit(text,(10,500))
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
Well output is not what I want, I don't know how to calculate it if user doesn't move his mouse.
If I want to write a text when user's mouse in a special area, it's working like;
if 100 < cur[0] < 200 and 100 < cur[1] < 200:
gameDisplay.blit(text,(10,500))
But how can I calculate? I even couldn't find how to tell Python, user's mouse is on the same coordinates or not.Then I can say, if mouse coordinates changes, start the timer, and if it's bigger than 15, print the text.
Edit: You can assume it in normal Python without Pygame module, assume you have a function that catching the mouse events, then how to tell Python if coordinates of mouse doesn't change, start the timer, if the time is bigger than 15 seconds,print a text, then refresh the timer.
To display a text on the screen if there is no mouse movement within the pygame window for 3 seconds:
#!/usr/bin/python
import sys
import pygame
WHITE, RED = (255,255,255), (255,0,0)
pygame.init()
screen = pygame.display.set_mode((300,200))
pygame.display.set_caption('Warn on no movement')
font = pygame.font.SysFont(None, 25)
text = font.render("Move your mouse!", True, RED, WHITE)
clock = pygame.time.Clock()
timer = pygame.time.get_ticks
timeout = 3000 # milliseconds
deadline = timer() + timeout
while True:
now = timer()
if pygame.mouse.get_rel() != (0, 0): # mouse moved within the pygame screen
deadline = now + timeout # reset the deadline
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill(WHITE)
if now > deadline: # no movement for too long
screen.blit(text, (10, 50))
pygame.display.flip()
clock.tick(60) # set fps
You should add:
start = time.time()
cur = None
before while loop.
You should also change start = time.time() in while loop to:
if cur != pygame.mouse.get_pos():
start = time.time()
Also you could use pygame.time (it's similar to time but measure time in milliseconds)
In your code, the while True: code block is continuously running. The cur = pygame.mouse.get_pos() function is non blocking. This means it does not wait for mouse input - it will return straight away. So you need to initialize the start and cur variables before your while True: code block and then check the mouse position constantly in your loop.
If cur has changed since the last time the loop ran, then reset the start variable to the current time, and if the difference between the current time and start becomes larger than your 15 seconds, you can display the text.
You can also do that even without getting time, since you can calculate the pause as an integer counter through your FPS. Consider following example. Note that if the cursor is out of the window, the values of its positon will not change even if you move the cursor.
import pygame
pygame.init()
clock = pygame.time.Clock( )
DISP = pygame.display.set_mode((600, 400))
FPS = 25
Timeout = 15
Ticks = FPS*Timeout # your pause but as an integer value
count = 0 # counter
MC = pygame.mouse.get_pos()
MC_old = MC
MainLoop = True
while MainLoop :
clock.tick(FPS)
pygame.event.pump()
Keys = pygame.key.get_pressed()
if Keys[pygame.K_ESCAPE]:
MainLoop = False
MC = pygame.mouse.get_pos() # get mouse position
if (MC[0]-MC_old[0] == 0) and (MC[1]-MC_old[1] == 0) :
count = count + 1
else : count = 0
if count > Ticks :
print "What are you waiting for"
count = 0
MC_old = MC # save mouse position
pygame.display.flip( )
pygame.quit( )

pygame.key.set_repeat for Joystick

I'm building a menu using pygame and I want to make it navigable using a specific gamepad. Ideally I want to be able to press and hold *down" on the D-pad repeatedly, or get something like on a keyboard where the first button press has a delay before repeatedly entering the same character (seemingly).
I'm trying to emulate the pygame.key.set_repeat(...) function for a Joystick. my approach so far has been
pygame.time.set_timer(pygame.USEREVENT, 10)
DELAY_TIME = 0.250 #ms
y_delay = True
while not done:
for event in pygame.event.get():
y_axis = gamepad.get_axis(1)
if y_axis > 0.5: # pushing down
main_menu.move_down()
redraw() #redraw everything on the surface before sleeping
if y_delay:
time.sleep(DELAY_TIME)
y_delay = False #don't delay the next time the y axis is used
elif y_axis < -0.5: #pushing up
# repetitive I know, but I'm still working on it
main_menu.move_up()
redraw()
if y_delay:
time.sleep(DELAY_TIME)
y_delay = False
else:
y_delay = True # delay the next time
my issue is if someone taps up or down faster than DELAY_TIME they are limited to the DELAY_TIME before they can move again. Also if someone releases and depresses the up/down button within the time.sleep interval, python never sees that it was released at all and doesn't allow for a delay.
Maybe there's a way to do this using events or mapping the joystick to keys somehow? qjoypad doesn't cut it for me, and joy2keys is trash. I would need to do the mapping within the python program.
Sleep causes the program to halt execution, so it's not a viable option. You can also do this without using set_timer and events. I did it using a couple of flags and pygame.time's get_ticks.
import pygame
from pygame.locals import *
def main():
pygame.init()
pygame.display.set_mode((480, 360))
gamepad = pygame.joystick.Joystick(0)
gamepad.init()
delay = 1000
neutral = True
pressed = 0
last_update = pygame.time.get_ticks()
while True:
for event in pygame.event.get():
if event.type == QUIT:
return
move = False
if gamepad.get_axis(1) == 0:
neutral = True
pressed = 0
else:
if neutral:
move = True
neutral = False
else:
pressed += pygame.time.get_ticks() - last_update
if pressed > delay:
move = True
pressed -= delay
if move:
print "move"
last_update = pygame.time.get_ticks()
if __name__ == "__main__":
main()
pygame.quit()
When get_axis indicates no motion, the neutral flag is set, and the pressed timer is reset, causing the move flag to remain unset. When the neutral flag is unset, if it's newly set, the move flag is set. If it's not newly set, the pressed timer increases, and move is set only if the pressed timer is greater than delay.

Categories