How can I add objects every three seconds? [duplicate] - python

This question already has answers here:
Countdown timer in Pygame
(8 answers)
How do I use a PyGame timer event? How to add a clock to a pygame screen using a timer?
(1 answer)
How do I continuously trigger an action at certain time intervals? Enemy shoots constant beam instead of bullets in pygame [duplicate]
(1 answer)
How can one continuously generate and track several random objects with a time delay in pygame? [duplicate]
(1 answer)
Closed 4 years ago.
i would like to spawn a 'boss' Sprite after a certain time has passed or x amount of mobs have spawned and how could i display the timer on the screen.
Images
Current Code
class for boss
class Boss(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.transform.scale(boss_img, (150, 200))
self.image.set_colorkey(Black)
self.rect = self.image.get_rect()
self.rect.center = ((Width / 2, -70))
self.speedy = 1
self.shoot_delay = 250
self.last_shot = pygame.time.get_ticks()
self.hp = 150
self.dead = False
def update(self):
if self.hp <= 25:
self.speedy = 3
if self.rect.top > Height + 10:
player.lives = 0

There are several ways to implement a timer in pygame. You can use the time that pygame.Clock.tick returns to increase or decrease a timer variable, calculate the time difference with pygame.time.get_ticks or use a custom event in conjunction with pygame.time.set_timer.
Example 1 - delta time:
import sys
import random
import pygame as pg
class Block(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = pg.Surface((40, 40))
self.image.fill(pg.Color('sienna1'))
self.rect = self.image.get_rect(topleft=pos)
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
font = pg.font.Font(None, 30)
all_sprites = pg.sprite.Group()
# Delta time is the time that has passed since clock.tick
# was called the last time.
dt = 0
# We'll subtract dt (delta time) from this timer variable.
timer = 1 # 1 means one second.
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
# Decrease timer to get a countdown.
timer -= dt
# When the timer is below or equal to 0, we spawn
# a new block.
if timer <= 0:
all_sprites.add(Block((random.randrange(600),
random.randrange(440))))
# Reset the countdown timer to one second.
timer = 1
all_sprites.update()
screen.fill(pg.Color('gray15'))
all_sprites.draw(screen)
timer_surface = font.render(
str(round(timer, 3)), True, pg.Color('yellow'))
screen.blit(timer_surface, (20, 20))
pg.display.flip()
# dt = time in seconds that passed since last tick.
# Divide by 1000 to convert milliseconds to seconds.
dt = clock.tick(30) / 1000
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()
If you want to spawn exactly 1 sprite, you can add another variable like boss_spawned = False and change the timer only if the boss hasn't spawned:
if not boss_spawned:
timer -= dt
if timer <= 0:
all_sprites.add(Block((random.randrange(600),
random.randrange(440))))
boss_spawned = True
Or set the timer to exactly 0 after the spawn and only decrease the timer if it's != 0.
if timer != 0:
timer -= dt
if timer <= 0:
all_sprites.add(Block((random.randrange(600),
random.randrange(440))))
timer = 0
Example 2 - pygame.time.get_ticks (replace the main function above):
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
font = pg.font.Font(None, 30)
all_sprites = pg.sprite.Group()
# Start time.
now = pg.time.get_ticks()
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
# If the time difference is greater than 1000
# milliseconds, spawn a block.
time_difference = pg.time.get_ticks() - now
if time_difference >= 1000:
all_sprites.add(Block((random.randrange(600),
random.randrange(440))))
# Reset the start time.
now = pg.time.get_ticks()
all_sprites.update()
screen.fill(pg.Color('gray15'))
all_sprites.draw(screen)
timer_surface = font.render(
str(time_difference/1000), True, pg.Color('yellow'))
screen.blit(timer_surface, (20, 20))
pg.display.flip()
clock.tick(30)
If you just want to count the kills or spawned mobs, you can increment a counter variable and then spawn the enemy boss when it exceeds some limit. The following example just counts the mouse clicks and spawns a block after 3 clicks.
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
font = pg.font.Font(None, 30)
all_sprites = pg.sprite.Group()
# We'll just count mouse clicks in this example.
# You can replace it with the kill count in your game.
clicks = 0
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if event.type == pg.MOUSEBUTTONDOWN:
clicks += 1
if clicks >= 3:
all_sprites.add(Block((random.randrange(600),
random.randrange(440))))
clicks = 0
all_sprites.update()
screen.fill(pg.Color('gray15'))
all_sprites.draw(screen)
clicks_surface = font.render(str(clicks), True, pg.Color('yellow'))
screen.blit(clicks_surface, (20, 20))
pg.display.flip()
clock.tick(30)

Related

How would I make it so I am able to summon more enemies. using pygame for a school project and can't seem to figure it out [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()

How do I create another object after a certain amount of time in Pygame? [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()

Why does my game freeze when using pygame.time.wait or pygame.time.delay? [duplicate]

This question already has answers here:
How to run multiple while loops at a time in Pygame
(1 answer)
Spawning multiple instances of the same object concurrently in python
(1 answer)
How to wait some time in pygame?
(3 answers)
Closed 2 years ago.
I created a small example to explain:
import pygame
pygame.init()
class Player(pygame.sprite.Sprite):
def __init__(self, color):
super().__init__()
self.image = pygame.Surface([25, 25])
self.image.fill(color)
self.color = color
self.rect = self.image.get_rect()
class Block(pygame.sprite.Sprite):
def __init__(self, color):
super().__init__()
self.image = pygame.Surface([25, 25])
self.image.fill(color)
self.color = color
self.rect = self.image.get_rect()
def update(self):
self.rect.y +=5
pygame.time.wait(500)
# Color
red = (255, 0, 0)
black = (0, 0, 0)
white = (255, 255, 255)
screen = pygame.display.set_mode([500,500])
# Sprite List
sprite_list = pygame.sprite.Group()
block_list = pygame.sprite.Group()
# Player
player = Player(red)
player.rect.x = 250
player.rect.y = 250
sprite_list.add(player)
# Block
block = Block(black)
block.rect.x = 250
block.rect.y = 0
block_list.add(block)
sprite_list.add(block)
notDone = True
clock = pygame.time.Clock()
while notDone:
for event in pygame.event.get():
if event.type == pygame.QUIT:
notDone = False
sprite_list.update()
block_collide = pygame.sprite.spritecollide(player, block_list, False)
for block in block_collide:
print("Collision")
notDone = False
screen.fill(white)
sprite_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
I wanted to create this so the block does not move every clock tick and rather move, then wait half a second, and then move once again. I wasn't exactly sure how to delay within a loop, so I simply used pygame.time.wait, however this caused my game to freeze upon start up (when I decided to run the code). Why does this keep happening?
You can not wait inside the application loop. pygame.time.wait halts the loop and makes the application irresponsible.
Use pygame.time.get_ticks() to return the number of milliseconds since pygame.init() was called. Calculate the point in time when the block needs to be move. When the time is reached, move the block and calculate the time when the block has to be moved again:
next_block_move_time = 0
while notDone:
# [...]
# sprite_list.update() <--- DELETE
current_time = pygame.time.get_ticks()
if current_time > next_block_move_time:
# set next move time
next_block_move_time = current_time + 500 # 500 milliseconds = 0.5 seconds
# move blocks
block_list .update()

"if" command is only running once and not repeating

I'm very new to python and Pygame and am trying to create a game.
I would like a "powerup" to appear after a set time, then repeat every time the timer hits so many seconds.
In the code, the "powerup" appears and drops down the screen after 5 seconds, the timer resets, but the next time the timer reaches 5 seconds, it continues to count and no "powerup" is produced.
I've spent hours trying to work out why this isn't working.
import pygame
import random
WIDTH = 480
HEIGHT = 600
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
time_difference = 0
font_name = pygame.font.match_font('arial')
def draw_text(surf, text, size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
class HealthPack(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 40))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.radius = 50
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-150, -100)
self.speedy = 6
self.speedx = 0
def update(self):
self.rect.y += self.speedy
if self.rect.top > HEIGHT:
self.kill()
all_sprites = pygame.sprite.Group()
healthpack = HealthPack()
running = True
while running:
clock.tick(FPS)
time_difference = pygame.time.get_ticks()
if time_difference >= 5000:
all_sprites.add(healthpack)
time_difference -= 5000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
all_sprites.update()
screen.fill(BLACK)
all_sprites.draw(screen)
draw_text(screen, str(time_difference), 18, WIDTH / 2, 55)
pygame.display.flip()
pygame.quit()
You're not calculating the time difference since the previous powerup. time_difference is always the time since the game started. You need to save the ticks each time you want to reset the timer, and compare with that.
prev_time = pygame.time.get_ticks() #initialize tick counter
while running:
clock.tick(FPS)
time_difference = pygame.time.get_ticks() - prev_time
if time_difference >= 5000:
all_sprites.add(healthpack)
prev_time = pygame.time.get_ticks() # reset counter
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
all_sprites.update()
screen.fill(BLACK)
all_sprites.draw(screen)
draw_text(screen, str(time_difference), 18, WIDTH / 2, 55)
pygame.display.flip()
#Barmar has given part of the answer. He is correct in his fix for time_difference, but there is another problem with your code as well.
The other issue is with the healthpack. You are doing this all_sprites.add(healthpack), which just puts the old healthpack back in the all_sprites list. That sprite is off the screen and descending. You need a new instance of HealthPack. So you need to modify #Barmar's solution like this:
prev_time = pygame.time.get_ticks() #initialize tick counter
while running:
clock.tick(FPS)
time_difference = pygame.time.get_ticks() - prev_time
if time_difference >= 5000:
healthpack = HealthPack() # <----------------- add this line
all_sprites.add(healthpack)
prev_time = pygame.time.get_ticks() # reset counter

Is there a way to run a function every x seconds? (DPS)

My original Solution was from this Comment on a similar question. However, if I do that and implement this
into different parts of my code, it stops counting up the in-game Counter of CASH.
CASH = 0
DPS = 5
HPofMonster = 10
starttime=time.time()
def handle_monster():
global HPofMonster, CASH
if pygame.mouse.get_focused():
event = pygame.event.poll()
mouse_x, mouse_y = pygame.mouse.get_pos()
if GEN1.collidepoint(mouse_x, mouse_y) and event.type == MOUSEBUTTONDOWN and event.button == 1:
HPofMonster -= 1
print('click')
pass
else:
print('Not Pushed OR not on Monster')
pass
else:
print('Mouse not focused')
pass
if HPofMonster < 0:
CASH += 5
HPofMonster = 10
print('reset')
def handle_dps():
global HPofMonster
HPofMonster -= DPS
print("tick")
time.sleep(1.0 - ((time.time() - starttime) % 1.0))
def game_loop():
while True:
handle_dps()
handle_monster()
update_text()
handle_events()
def main():
pygame.display.set_caption('Clicker')
game_loop()
main()
When I donĀ“t move my Mouse, my console looks like this:
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
reset
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
reset
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
tick
Not Pushed OR not on Monster
reset
Mouse not focused
Process finished with exit code 0
Here is the entire code:
import pygame, threading, time
from threading import Event, Thread
from pygame.locals import *
pygame.init()
WIDTH = 800
HEIGHT = 600
WINDOW = pygame.display.set_mode((WIDTH, HEIGHT))
CASH = 0
DPS = 5
HPofMonster = 10
BACKGROUND_COLOR = (0, 0, 0)
BUTTON_COLOR = (0, 255, 0)
starttime=time.time()
FONT = pygame.font.SysFont('monospace', 15)
# Main Screen for drawing buttons
DRAW_SCREEN = pygame.Surface((WIDTH, HEIGHT))
DRAW_SCREEN.fill(BACKGROUND_COLOR)
# Buttons
GEN1 = pygame.draw.rect(DRAW_SCREEN, BUTTON_COLOR, pygame.Rect(200, 200, 200, 200), 1)
GEN1_LABEL = FONT.render('Defeat the Monster', 1, (255, 255, 0))
def handle_monster():
global HPofMonster, CASH
if pygame.mouse.get_focused():
event = pygame.event.poll()
mouse_x, mouse_y = pygame.mouse.get_pos()
if GEN1.collidepoint(mouse_x, mouse_y) and event.type == MOUSEBUTTONDOWN and event.button == 1:
HPofMonster -= 1
print('click')
pass
else:
print('Not Pushed OR not on Monster')
pass
else:
print('Mouse not focused')
pass
if HPofMonster < 0:
CASH += 5
HPofMonster = 10
print('reset')
def handle_events():
event_dict = {
pygame.QUIT: exit,
}
for event in pygame.event.get():
if event.type in event_dict:
event_dict[event.type]()
def update_text():
global CASH_LABEL, DPS_LABEL, GEN1_LABEL, DPS, CASH
WINDOW.blit(DRAW_SCREEN, (0, 0))
WINDOW.blit(GEN1_LABEL, (10, 108))
CASH_LABEL = FONT.render('Total Cash: ${}'.format(CASH), 1, (255, 255, 0))
DPS_LABEL = FONT.render('Total DPS: ${}'.format(DPS), 1, (255, 65, 0))
WINDOW.blit(CASH_LABEL, (0, 0))
WINDOW.blit(DPS_LABEL, (0, 20))
pygame.display.flip()
def handle_dps():
global HPofMonster
HPofMonster -= DPS
print("tick")
def game_loop():
while True:
handle_dps()
handle_monster()
update_text()
handle_events()
def main():
pygame.display.set_caption('Clicker')
game_loop()
main()
Do not use time.sleep() in a event-driven program. It blocks the event-loop, and on some systems the window manager or outlying operating system will consider the program to have stopped and/or crashed. The program must continually process incoming events.
An easy way to do this in pygame is to use the real-time system clock function pygame.time.get_ticks() which returns the number of milliseconds since the program started, and it keeps increasing forever. If you want something to trigger in the future, set a timestamp like:
future_timestamp = pygame.time.get_ticks() + 15000 # 15 seconds from now
...
# somewhere else in the code, maybe in the main loop
time_now = pygame.time.get_ticks()
if ( future_timestamp < time_now ):
# do the thing that had to happen
do_that_thing()
# re-set the timer for next time
future_timestamp = time_now + 15000
Another simple way to implement something that happens periodically is to setup a pygame timer:
pygame.time.set_timer( pygame.USEREVENT + 1, 3500 ) # Cash every 3500 milliseconds
# Main Loop
while not exiting:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
elif ( event.type == pygame.USEREVENT + 1 ):
CASH += 1
# reset the event-timer
pygame.time.set_timer( pygame.USEREVENT + 1, 3500 )
Instead of time.sleep use pygame.time.delay()or pygame.time.wait().
Here is the link of official pygame time events: https://www.pygame.org/docs/ref/time.html

Categories

Resources