Time delays on sprites [duplicate] - pygame

While I've been using time.wait in my code since I began learning Python and Pygame, I've been wondering if there are any other ways to do it and what are the advantages and disadvantages of each approach. For example, Pygame also has a pygame.time.wait. What's the difference between python's wait and pygame's wait functions? Which one is better? And are there other ways to wait some time besides using these two functions?

For animation / cooldowns, etc: If you want to 'wait', but still have code running you use: pygame.time.get_ticks
class Unit():
def __init__(self):
self.last = pygame.time.get_ticks()
self.cooldown = 300
def fire(self):
# fire gun, only if cooldown has been 0.3 seconds since last
now = pygame.time.get_ticks()
if now - self.last >= self.cooldown:
self.last = now
spawn_bullet()

For Python in general, you will want to look at the sleep library.
For Pygame, however, using pygame.time.delay() will pause for a given number of milliseconds based on the CPU clock for more accuracy (as opposed to pygame.time.wait).

If you just wait for some time, you can use pygame.time.wait or pygame.time.delay. However, if you want to display a message and then wait some time, you need to update the display beforehand. The display is updated only if either pygame.display.update() or pygame.display.flip()
is called. See pygame.display.flip():
This will update the contents of the entire display.
Further you've to handles the events with pygame.event.pump(), before the update of the display becomes visible in the window. See pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
This all means that you have to call pygame.display.flip() and pygame.event.pump() before pygame.time.delay() or pygame.time.wait():
screen.blit(text, (x, y))
pygame.display.flip()
pygame.event.pump()
pygame.time.delay(delay * 1000) # 1 second == 1000 milliseconds
See also Why doesn't PyGame draw in the window before the delay or sleep?
In any case, this is not the way to wait or delay something in a typical application. The game does not respond while you wait. Use pygame.time.get_ticks() to measure the time.
For instance if you want to show a message on the display, get the current time and calculate the point in time after that the message has to disappear. Display the message as long as the current time is below the calculated time:
message_end_time = 0
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# [...]
current_time = pygame.time.get_ticks()
if something_has_happened:
message_surf = font.render('Important message!', True, (255, 0, 0))
message_end_time = pygame.time.get_ticks() + 3000 # display for 3 seconds
window.fill(0)
# [...]
if current_time < message_end_time:
window.blit(message_surf, (x, y))
pygame.display.flip()
See also How do I stop more than 1 bullet firing at once?
Minimal example: repl.it/#Rabbid76/PyGame-MessageDelay
import pygame
pygame.init()
font = pygame.font.SysFont(None, 50)
text = font.render('press key or mouse', True, (255, 0, 0))
window = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()
message_end_time = pygame.time.get_ticks() + 3000
run = True
while run:
clock.tick(60)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
text = font.render(pygame.key.name(event.key) + ' pressed', True, (255, 0, 0))
message_end_time = pygame.time.get_ticks() + 2000
if event.type == pygame.MOUSEBUTTONDOWN:
text = font.render('button ' + str(event.button) + ' pressed', True, (255, 0, 0))
message_end_time = pygame.time.get_ticks() + 2000
window.fill(0)
if current_time < message_end_time:
window.blit(text, text.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()

Related

How can i move the Instances of the game on shifted y axis? [duplicate]

I'm a beginner programmer who is starting with python and I'm starting out by making a game in pygame.
The game basically spawns circles at random positions and when clicked, it gives you points.
Recently I've hit a roadblock when I want to spawn multiple instances of the same object (in this case circles) at the same time.
I've tried stuff like sleep() and some other code related to counters, but it always results in the next circle spawned overriding the previous one (i.e the program spawns circle 1, but when circle 2 comes in, circle 1 disappears).
Does anyone know a solution to this? I would really appreciate your help!
import pygame
import random
import time
pygame.init()
window = pygame.display.set_mode((800,600))
class circle():
def __init__(self, color, x, y, radius, width,):
self.color = color
self.x = x
self.y = y
self.radius = radius
self.width = width
def draw(self, win, outline=None):
pygame.draw.circle(win, self.color, (self.x, self.y, self.radius, self.width), 0)
run=True
while run:
window.fill((0, 0, 0))
pygame.draw.circle(window, (255, 255, 255), (random.randint(0, 800),random.randint(0, 600)), 20, 20)
time.sleep(1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run=False
pygame.quit()
quit()
It does not work that way. time.sleep, pygame.time.wait() or pygame.time.delay is not the right way to control time and gameplay within an application loop. The game does not respond while you wait. The application loop runs continuously. You have to measure the time in the loop and spawn the objects according to the elapsed time.
pygame.Surface.fill clears the entire screen. Add the newly created objects to a list. Redraw all of the objects and the entire scene in each frame.
See also Time, timer event and clock
You have 2 options. Use pygame.time.get_ticks() to measure the time. Define a time interval after which a new object should appear. Create an object when the point in time is reached and calculate the point in time for the next object:
object_list = []
time_interval = 500 # 500 milliseconds == 0.1 seconds
next_object_time = 0
while run:
# [...]
current_time = pygame.time.get_ticks()
if current_time > next_object_time:
next_object_time += time_interval
object_list.append(Object())
Minimal example:
repl.it/#Rabbid76/PyGame-TimerSpawnObjects
import pygame, random
pygame.init()
window = pygame.display.set_mode((300, 300))
class Object:
def __init__(self):
self.radius = 50
self.x = random.randrange(self.radius, window.get_width()-self.radius)
self.y = random.randrange(self.radius, window.get_height()-self.radius)
self.color = pygame.Color(0)
self.color.hsla = (random.randrange(0, 360), 100, 50, 100)
object_list = []
time_interval = 200 # 200 milliseconds == 0.2 seconds
next_object_time = 0
run = True
clock = pygame.time.Clock()
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
current_time = pygame.time.get_ticks()
if current_time > next_object_time:
next_object_time += time_interval
object_list.append(Object())
window.fill(0)
for object in object_list[:]:
pygame.draw.circle(window, object.color, (object.x, object.y), round(object.radius))
object.radius -= 0.2
if object.radius < 1:
object_list.remove(object)
pygame.display.flip()
pygame.quit()
exit()
The other option is to use the pygame.event module. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. The time has to be set in milliseconds. e.g.:
object_list = []
time_interval = 500 # 500 milliseconds == 0.1 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_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.
Receive the event in the event loop:
while run:
for event in pygame.event.get():
if event.type == timer_event:
object_list.append(Object())
The timer event can be stopped by passing 0 to the time argument of pygame.time.set_timer.
Minimal example:
repl.it/#Rabbid76/PyGame-TimerEventSpawn
import pygame, random
pygame.init()
window = pygame.display.set_mode((300, 300))
class Object:
def __init__(self):
self.radius = 50
self.x = random.randrange(self.radius, window.get_width()-self.radius)
self.y = random.randrange(self.radius, window.get_height()-self.radius)
self.color = pygame.Color(0)
self.color.hsla = (random.randrange(0, 360), 100, 50, 100)
object_list = []
time_interval = 200 # 200 milliseconds == 0.2 seconds
timer_event = pygame.USEREVENT+1
pygame.time.set_timer(timer_event, time_interval)
run = True
clock = pygame.time.Clock()
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == timer_event:
object_list.append(Object())
window.fill(0)
for object in object_list[:]:
pygame.draw.circle(window, object.color, (object.x, object.y), round(object.radius))
object.radius -= 0.2
if object.radius < 1:
object_list.remove(object)
pygame.display.flip()
pygame.quit()
exit()

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

How do I make autonomous movement in pygame?

I'm new to pygame and I'm trying to do the simplest thing ever here really, I just want to have a circle move across the screen with no input from the user. I only seem to find advice online on how to move an object using the keys which isn't what I want I just want it to move on its own and so that the user can watch it move.
Here's what I was trying to use to do this.
Code Start Here:
import pygame module in this program
import pygame
pygame.init()
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0, 0, 0)
red = (255, 0, 0)
X = 400
Y = 400
display_surface = pygame.display.set_mode((X, Y ))
pygame.display.set_caption('Drawing')
display_surface.fill(white)
x,y=[300,50]
pygame.draw.circle(display_surface,green, (x, y), 20, 0)
clock = pygame.time.Clock()
def move():
global y
y=y+1
while True :
clock.tick(30)
move()
for event in pygame.event.get() :
# if event object type is QUIT
# then quitting the pygame
# and program both.
if event.type == pygame.QUIT :
pygame.quit()
quit()
pygame.display.update()
Code End Here:
You have to redraw the scene in every frame:
import pygame
pygame.init()
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0, 0, 0)
red = (255, 0, 0)
X = 400
Y = 400
display_surface = pygame.display.set_mode((X, Y))
pygame.display.set_caption('Drawing')
clock = pygame.time.Clock()
x,y=[300,50]
def move():
global y
y=y+1
# application loop
run = True
while run:
# limit the frames per second
clock.tick(30)
# event loop
for event in pygame.event.get() :
if event.type == pygame.QUIT:
run = False
# update the position of the object
move()
# clear disaply
display_surface.fill(white)
# draw scene
pygame.draw.circle(display_surface,green, (x, y), 20, 0)
# update disaply
pygame.display.update()
pygame.quit()
quit()
The typical PyGame application loop has to:
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
handle the events by calling 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 by calling either pygame.display.update() or pygame.display.flip()

Pyton - Pygame - stuck refreshing blitting image on screen [duplicate]

This question already has answers here:
Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
(1 answer)
Why is my PyGame application not running at all?
(2 answers)
Closed 1 year ago.
Hi there and thank you for your time reading this.
This is related to the project I'm making. It's a reaction test game. Basically, Arcade buttons with LEDs light up, and players need to press them to score points. Whack-a-Mole style.
The game is timed, 30 seconds. But instead of using a numerical timer, I'm using a progress bar moving across the screen to indicate the remaining time instead.
image below:
game screenshot
I added this as an image blit in the code, but it doesn't refresh correctly. You can see it only at the start of the game, and when players press a button.
It needs to be constantly blitting across the screen.
Maybe I'm just missing something or my indentation is wrong?
Would really appreciate any inputs on this.
Main game loop code is below:
# MAIN GAME SEQUENCE CODE ---------------------------------------------------------------------------------------------
# Setup Pygame refresh rate to 120 fps
clock.tick(60)
while game_running:
# Idle Screen
idle_scrn()
# Instructions
inst_seq()
# GAME PLAY SECTION --------
score = 0
time_Out = 0
leds.off()
start_Time = pygame.time.Clock()
start = int(time.time())
time_move = -500
random_num = random.randint(0, 11)
leds.on(random_num)
print(random_num)
while time_Out != 30:
screen.blit(Timebar, (time_move,1000))
time_move += 50
pygame.display.update()
for event in pygame.event.get():
print("For Event started, Game screen started")
screen.fill((255,255,255))
screen.blit(Game_screen[6], (0,0))
score_textback = score_fontback.render("00", 3, (199,199,199))
score_text = score_font.render(str(score), 3, (255,37,24))
ctr = 1110
if score >= 10:
ctr -= 155
center_pos = (ctr, 580)
score_rect = score_text.get_rect(center = center_pos)
screen.blit(score_textback, (645, 390))
screen.blit(score_text, score_rect)
if event.type == pygame.JOYBUTTONDOWN:
print("If for event JOYBUTTONDOWN")
if event.button == random_num:
B = event.button
print(B, " button pressed, CORRECT")
leds.off()
butt_Sound.play()
random_num = random.randint(0, 11)
leds.on(random_num)
score += 1
pygame.display.update()
current_Time = int(time.time())
time_Out = current_Time - start
#pygame.display.update()
#print("TIMER: ", time_Out)
#print(type(start_Time))
#print(current_Time)
#print(type(current_Time))
#pygame.display.update()
# FINAL SCORE ------------------------
final_Score()
exit()
The image is Timebar. in the code, we move it 50 pixels across the screen in every refresh.
Thank you in advance.
Here's a minimal example, perhaps you'll find it useful:
import pygame
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
fps = 60
clock = pygame.time.Clock()
progress_width = 0 # initialse progress tracker
total_time = 0
target_time = 10_000 # ten seconds in milliseconds
finished = False
while not finished:
# Handle Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
elif event.type == pygame.KEYDOWN:
progress_width = 0 # reset progress
total_time = 0
# Update Game State
dt = clock.tick(fps) # limit FPS and return time since last call
total_time += dt
progress_width += width * dt / target_time # scale bar width
progress_rect = pygame.Rect(0, height-20, int(progress_width), 20)
# Draw Background
screen.fill(pygame.Color("black"))
# Draw Sprites
pygame.draw.rect(screen, pygame.Color("red"), progress_rect)
# Update Display
pygame.display.flip()
# Display the elapsed time in the title bar
pygame.display.set_caption(f"Simple Progress {total_time:,d} ms")
pygame.quit()
It calculates the time elapsed and updates the progress bar width. It takes ten seconds to fill the screen width and pressing a key resets the progress.
Your main loop should look something like:
Handle Events
Update Game State
Draw sprites
Update Screen
If you're trying to update the screen or handle events in multiple places, things get confusing pretty quickly.

Repeated key down event hangs/stops firing after some time

Consider the following program:
import pygame, sys
from pygame.locals import *
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
class Player(object):
def __init__(self, world):
self.x = 100
self.y = 100
self.size = 30
self.world = world
def draw(self, windowSurface):
pos = (self.x, self.y, self.size, self.size)
pygame.draw.rect(windowSurface, WHITE, pos)
def moveUp(self):
self.y -= 1
def moveDown(self):
self.y += 1
def moveLeft(self):
self.x -= 1
def moveRight(self):
self.x += 1
class OpenIsaac(object):
def __init__(self):
pygame.init()
self.windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption('OpenIsaac')
pygame.key.set_repeat(1, 2)
self.player = Player(self)
self.objects = [self.player]
def mainLoopStep(self):
self.windowSurface.fill(BLACK)
for object_ in self.objects:
object_.draw(self.windowSurface)
pygame.display.update()
def doQuit(self):
pygame.quit()
sys.exit()
def handleQuit(self, event):
if event.type != QUIT:
return
self.doQuit()
def handleKeyboard(self, event):
if event.type != KEYDOWN:
return
if pygame.key.get_pressed()[K_ESCAPE]:
self.doQuit()
if pygame.key.get_pressed()[K_LEFT]:
self.player.moveLeft()
if pygame.key.get_pressed()[K_RIGHT]:
self.player.moveRight()
if pygame.key.get_pressed()[K_DOWN]:
self.player.moveDown()
if pygame.key.get_pressed()[K_UP]:
self.player.moveUp()
def run(self):
while True:
for event in pygame.event.get():
self.handleQuit(event)
self.handleKeyboard(event)
self.mainLoopStep()
pygame.event.pump()
if __name__ == '__main__':
OpenIsaac().run()
When I move the character pressing one or two keys for some time, the character stops movement at some point. I need to release the key and press it again to restore movement. What could cause that?
It is because when Pygame receives one key press, it will move the sprite once according to the code and only once. You will need to find a way to make the program recognize that the key is being held down, and let the program keep the sprite moving. One way is to use pygame.key.set_repeat. It looks similar to this:
delay = 100
interval = 50
pygame.key.set_repeat(delay, interval)
delay is number of milliseconds the game "waits" before repeating the keys. interval is the amount of milliseconds between each key event. For example, I put delay at 100. The game will wait for 100 milliseconds before repeating the key events. Setting interval at 50 will have each key event be 50 milliseconds apart.
Python 2.x
Place these three lines right before the while loop. The lines should not belong in a function or functions. Holding the key down will repeat the appropriate event, such as continuing moving, jumping, etc.
Python 3.x
I'm new to it, so you might have to find that out through Youtube or Pygame Docs. Sorry!
Setting delay to 1 will terminate the key.set_repeat. Making it higher to like 100 will have no effect and the user won't notice it. Same goes to your interval value. I hope it helps you now!