How can instances of classes be automatically generated in python? - python

I am making a small game using pygame in python 3.3 and I have a class for the enemies (see below). If I want to spawn in a new enemy every 10 or so seconds, so that theoretically, the game could go on forever. This however required the instances of the classes to be generated automatically every 10 seconds. Is there a way to create a new instance of the enemy class automatically?
Enemy class:
class Enemy(object):
def __init__(self, image, posx, posy, speed, damage):
self.image = image
self.posx = posx
self.posy = posy
self.speed = speed
self.damage = damage
def move(self):
self.posy = self.posy + self.speed
def draw(self):
screen.blit(self.image, (self.posx, self.posy))
Edit: Sorry! I posted this, not realising I didn't finish writing my explanation. My apologies!

You need to store spawned enemies somewhere. Suppose it's a list:
enemies = []
...
# every 10 secs
enemy = Enemy()
enemies.add(enemy)
Then, when enemy is killed, you'd like to remove it from that list.

look into a module called time
you would need to do something like this:
import time
nSeconds = 11
t0 = time.clock()
dt = 0
enemyCount = 0
# the following would be in an appropriate
# place in the main game loop
if dt < nSeconds:
t1 = time.clock()
dt = t1 - t0
else:
enemyInstance = Enemy()
enemyCount += 1
t0 = time.clock()
dt = 0
you can keep track of the enemy count just in case you want to send a special wave after a number of enemies or give bonus points or whatever.
also have a look at this book about game development in python for other ideas: http://inventwithpython.com/makinggames.pdf

In a game usually there is a main game loop, where inputs are read, the simulation is advanced and the screen is rendered. In that loop, you can check how much time has passed since the last time a enemy was created, and you can create one if enough time flew by.

# before mainloop
enemies = []
time_for_next_enemy = pygame.time.get_ticks() + 10000 # 10 seconds , 1000ms = 1s
# in mainloop
if pygame.time.get_ticks() >= time_for_next_enemy:
enemy = Enemy()
enemies.add(enemy)
time_for_next_enemy = pygame.time.get_ticks() + 10000

Related

Why do I need the time.sleep(x) function in this code for it to work?

from turtle import Screen, Turtle
import time
import snake
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class InitialSnake:
def __init__(self):
self.number_x = 0
self.snake_first = []
self.create_snake()
self.actual_snake = self.snake_first[0]
def create_snake(self):
for number in range(3):
snake = Turtle(shape="square")
snake.penup()
snake.color("white")
snake.goto(self.number_x, 0)
self.number_x -= 20
self.snake_first.append(snake)
def move(self):
for segments_num in range(len(self.snake_first) - 1, 0, -1):
self.snake_first[segments_num].goto(self.snake_first[segments_num - 1].xcor(),
self.snake_first[segments_num - 1].ycor())
self.snake_first[0].forward(MOVE_DISTANCE)
def up(self):
if self.actual_snake.heading() != DOWN:
self.snake_first[0].setheading(UP)
def down(self):
if self.actual_snake.heading() != UP:
self.snake_first[0].setheading(DOWN)
def left(self):
if self.actual_snake.heading() != RIGHT:
self.snake_first[0].setheading(LEFT)
def right(self):
if self.actual_snake.heading() != LEFT:
self.snake_first[0].setheading(RIGHT)
my_screen = Screen()
my_screen.setup(width=600, height=600)
my_screen.bgcolor("black")
my_screen.title("Snake Game")
my_screen.tracer(0)
snake_1 = snake.InitialSnake()
#snake_here.create_snake()
game_is_on = True
my_screen.listen()
my_screen.onkey(snake_1.up, "Up")
my_screen.onkey(snake_1.down,"Down")
my_screen.onkey(snake_1.left,"Left")
my_screen.onkey(snake_1.right,"Right")
while game_is_on:
my_screen.update()
time.sleep(0.1)
snake_1.move()
my_screen.exitonclick()
I did not really understand the concept of the tracer and the update and how this is linked to the sleep function. I understand that when the tracer is called and turned off, it will not refresh the screen until you call the update() function. But shouldn't it still work without time.sleep(0.1) since this is just creating a short delay before the next functions get called. Can someone help me please to understand this? Thanks in advance (:
If you use print() to see snake position
while game_is_on:
my_screen.update()
snake_1.move()
print(snake_1.snake_first[0].ycor(), snake_1.snake_first[0].xcor())
then you will see it moves very, very fast and it left screen - and you simply can't see it.
On my very old computer after few milliseconds its positon was (0, 125700). Probably on the newest computer it would be much bigger value.
So this code use sleep() to slow down snake and to move it with the same speed on all computers.
BTW:
I would use turtle method to repeate code
def game_loop():
snake_1.move()
my_screen.update()
my_screen.ontimer(game_loop, 100) # repeate after 100ms (0.1s)
# start loop
game_loop()
because sleep may blocks some code and ontimer was created for non-blocking delay.

Explosions Sprite Despears Way To Fast When Enemy is Killed How Do Fix This?

on my draw I did this but the explosion doesnt event last a sec and just dispears
is there a better way I could do this instead of saying if the enemy health is greater then this load this?
for enemys in enemying:
if enemys.health < -4
for explode in explodes:
explode.draw((enemys.hitbox, enemys.hitbox))
my explosion class
class explode:
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.explode = [
pygame.image.load("spark_01.png"),
pygame.image.load("spark_02.png"),
pygame.image.load("spark_03.png"),
pygame.image.load("spark_04.png"),
pygame.image.load("spark_05.png"),
pygame.image.load("spark_06.png"),
pygame.image.load("spark_07.png")]
self.explode = [pygame.transform.scale(image,(image.get_width()//5,image.get_height()//5)) for image in self.explode]
self.rect = pygame.Rect(x,y,height,width)
self.direction = "blobright"
self.anim_index = 0
def draw(self,x):
self.rect.topleft = (self.x,self.y)
if self.direction == "blobright":
window.blit(self.explode[self.anim_index], self.rect)
self.anim_index += 1
if self.anim_index == len(self.explode):
self.anim_index = 0
black = (0,0,0)
explode1 = explode(400,450,50,50,black)
explodes = [explode1]
this is where I delete the enemys
for enemyshoot in enemyshooting:
for bullet in bullets:
if bullet.rect.colliderect(enemyshoot.hitbox):
if enemyshoot.health > -8:
enemyshoot.health -= 1
bullets.pop(bullets.index(bullet))
else:
del enemyshooting[one]
Here is the example I promised. Notice how the system clock and a flag
are used to control animation speed so that different actions can happen on the screen at different speeds. This program is written quick-and-dirty. There are MUCH more efficient ways to handle the animation so that the screen is only drawn to when it is time for something to move, and ONLY those parts of the screen that have changed are drawn and refreshed. But don't worry about that. The lesson here is how to use the clock to slow down your animation speed. What's the old saying? Code now, refactor later? Words to live by.
import pygame
from pygame.locals import * # Pygame Constants such as FULLSCREEN and KEYDOWN.
from pygame import Color
pygame.init()
import time
# ==============================================================
# Disable Windows Auto-scaling
# The windows auto-scaling feature can mess with pygame graphics.
# Windows-Specific: Delete if you are not on a Windows machine
# If you are on Windows, comment section to see the effect.
import ctypes
awareness = ctypes.c_int()
errorCode = ctypes.windll.shcore.GetProcessDpiAwareness(0, ctypes.byref(awareness))
errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2) # Awareness levels can be 0, 1 or 2:
# ===============================================================
# I will base the example on your explode class. If I were writing the
# game, I would use a sprite class along with a sprite group to simplify
# the code. However, these topics are an entirely different branch of study
# so I won't use them in the example. Forgive my quick-and-dirty code.
# I don't have your image files, but it looks as though
# you have an actual animation to use for your explosion that is
# made up of several different frames. We will emulate this for the
# sake of our demonstration.
class EXPLODE:
def create_spark(self):
TRANSPARENT = (254,255,255) # You can chose your own transparent color.
# Lacking the spark files, let's draw our own.
spark_img = pygame.Surface((31,31))
spark_img.fill(TRANSPARENT)
spark_img.set_colorkey(TRANSPARENT)
spark_rec = spark_img.get_rect()
left_center = (spark_rec.left,spark_rec.centery)
right_center = (spark_rec.right,spark_rec.centery)
top_center = (spark_rec.centerx,spark_rec.top)
bottom_center = (spark_rec.centerx,spark_rec.bottom)
top_left = spark_rec.topleft
top_right = spark_rec.topright
bottom_left = spark_rec.bottomleft
bottom_right = spark_rec.bottomright
pygame.draw.circle(spark_img,Color("yellow"),spark_rec.center,spark_rec.width//2,0)
pygame.draw.line(spark_img,Color("indianred"),left_center,right_center,2)
pygame.draw.line(spark_img,Color("red"),top_center,bottom_center,2)
pygame.draw.line(spark_img,Color("burlywood3"),top_left,bottom_right,3)
pygame.draw.line(spark_img,Color("orange"),top_right,bottom_left,3)
# Now crop line segments that fall outside the spark circle..
pygame.draw.circle(spark_img,TRANSPARENT,spark_rec.center,spark_rec.width//2+8,8)
return spark_img
def __init__(self,window,x,y,height,width,color = (255,0,0)):
self.window = window # Needed so class can draw to the screen.
self.T0 = time.time() # Holds the starting time for the timer.
self.x = x
self.y = y
self.height = height
self.width = width
self.anim_index = 0
image = self.create_spark()
# Standing in for actual animation pages, we scale up the spark image.
self.explode = [
image,
pygame.transform.scale(image,(image.get_width()*2,image.get_height()*2)),
pygame.transform.scale(image,(image.get_width()*4,image.get_height()*4)),
pygame.transform.scale(image,(image.get_width()*6,image.get_height()*6)),
pygame.transform.scale(image,(image.get_width()*8,image.get_height()*8))]
'''
# Or you can load your spark frames as before.
self.explode = [
pygame.image.load("spark_01.png"),
pygame.image.load("spark_02.png"),
pygame.image.load("spark_03.png"),
pygame.image.load("spark_04.png"),
pygame.image.load("spark_05.png"),
pygame.image.load("spark_06.png"),
pygame.image.load("spark_07.png")]
# All of the loaded images are scaled down to 1/5 their size.
self.explode = [pygame.transform.scale(image,(image.get_width()//5,image.get_height()//5)) for image in self.explode]
'''
self.rect = image.get_rect()
self.direction = "blobright" # <-- I don't know what this is, so I've ignored it.
self.anim_index = 0
def draw(self,enemy_rec,anin_speed): # Create an animation method to handle the draw routine.
clock = time.time()
elapsed_time = clock - self.T0
finish_flg = False
if elapsed_time > anin_speed: # Animation Speed Controlled Here!!
self.anim_index +=1
self.T0 = time.time() # Reset the start time.
if self.anim_index == len(self.explode)-1:
finish_flg = True
frame = self.explode[self.anim_index]
rec = frame.get_rect()
rec.center = enemy_rec.center
self.window.blit(frame,rec)
return finish_flg # The finish flag lets the main program know it can delete the enemy.
# ================== MAIN() ===================
# ----------------------------------------------
def main(): # By using a 'main()' function, your code will run faster!
screen = pygame.display.set_mode((3000,2000),pygame.FULLSCREEN,32)
screen_rec = screen.get_rect()
screen.fill(Color("steelblue1"))
# Declare and initialie an instance of the EXPLODE class.
# Only one enemy can blow up at the same time for any give instance
# of the class, so you may want each ship to have its own instance
# if there is a chance of simultanious explosions.
# I wouldn't normally use this aproach, but I wanted to stay
# as close as possible to your existing code.
explode = EXPLODE(screen,screen_rec.centerx,screen_rec.centery,30,20,Color('blue'))
# Let's create some "enemy" units.
# You would use an enemy class for this (and for drawing them)
# but this example is qick and dirty, so.. Two enemies coming up!
# One enemy to blow up when it hits the wall.
enemy1_img = pygame.Surface((30,30))
enemy1_rec = enemy1_img.get_rect()
enemy1_img.fill(Color("Green"))
pygame.draw.rect(enemy1_img,Color("Red"),enemy1_rec,5)
# And one 'enemy' to move while the other is blowing up.
enemy2_img = enemy1_img.copy()
enemy2_rec = enemy2_img.get_rect()
# Give enemies screen positions.
enemy1_rec.center = (screen_rec.centerx-300, screen_rec.centery-300)
enemy2_rec.center = (screen_rec.centerx-800,screen_rec.centery-300)
# Create a wall for a ship to crash into.
wall_img = pygame.Surface((100,60))
wall_img.fill(Color("Indianred"))
wall_rec = wall_img.get_rect()
wall_rec.center = screen_rec.center
wall_rec = wall_rec.move((400,0))
# Oh, this list is ugly. Forgive me! Used instead of a list of Enemy-Class objects.
enemy_list = [[10,enemy1_img,enemy1_rec,(2,1)],[10,enemy2_img,enemy2_rec,(3,0)]] # [Life, Image, Rectangle, Speed]
# Ok, the setup is finished. Time for some action!
# =============== BODY ===================
# ------------------------------------------
anin_speed = 0.3 # You can control explosion speed here!
pygame.mouse.set_visible(False)
run_cycle = True
while run_cycle == True:
# There are much better ways to erase images, but this will do for now.
screen.fill(Color("steelblue1")) # Erase old sprites.
screen.blit(wall_img,wall_rec) # Put the wall back in place.
# Because it is bad idea to modify an object being looped through,
# we will construct a new list, called 'hold', and copy it back at the end.
hold = []
for enmy in enemy_list:
life,enemy_img,enemy_rec,speed = enmy
if life > 4:
screen.blit(enemy_img,enemy_rec) # If enemy is healthy, put it on the screen.
enemy_rec = enemy_rec.move(speed)
if enemy_rec.colliderect(wall_rec) == True:
life = 0
if enemy_rec.left > screen_rec.right+10: # End the program after top ship leaves the screen.
run_cycle = False
hold.append([life,enemy_img,enemy_rec,speed])
else: # Otherwise draw the explosion.
finish_flg = explode.draw(enemy_rec,anin_speed)
if finish_flg == False: # If TRUE the enemy is ommitted from the hold list!
hold.append(enmy)
enemy_list = hold.copy() # And now the possibly modified list is copied back to the enemy_list.
pygame.display.flip()
# ================
# Main
# ----------------
main() # Hint! For technical reasons related to the compiler being able
# to control scope and predict variable sizes, keeping your
# main body encapsulated in a function like this will improve
# efficiency and run speeds.
You have a great start. If nothing needs to happen while the explosion is going on, you could use a sleep command in your loop. >> time.sleep(0.01)
If the action has to continue on the screen during the explosion, then you will need to use a timer and keep returning to that function after each duration to draw the next frame. Just initialize using >> T0 = time.time() before the explosion, visit the function when time.time()-T0 > 0.01 seconds (for example) and reset T0 = time.time() after each frame is drawn. Return a 'finished' value when the animation is over, so you can remove it from your enemy list.
In the __init__() for explode note the time when it is called and save it.
In the explodes draw() only increment self.anim_index when enough time has passed since the last time it was incremented (based on the time value you saved in the __init__()). This will let you go more slowly through the frames of the exploding animation.
There is really no difference between this and any other object animation, other than once the cycle completes the object (the explosion) goes a way.

How to make a wave timer in pygame

So, I'm totally new to programming (been doing it for a couple of months) and decided to try coding a game.
On that note, a big thanks to Chris Bradfield for his series of tutorials in pygame coding, they are absolutely great!
However, now that I'm done with the tutorials and need to work on my own, I've come across a problem. I'm making a top-down shooter and making it wave-based. So, when zombies in one wave die, I want to show a timer that counts down until the next wave begins. I THINK I'm down the right path atm, let me show you what I'm working with.
def new(self)
'''
self.timer_flag = False
self.x = threading.Thread(target=self.countdown, args=(TIME_BETWEEN_WAVES,))
'''
def countdown(self, time_between_waves):
self.wave_timer = time_between_waves
for i in range(TIME_BETWEEN_WAVES):
while self.timer_flag:
self.wave_timer -=
time.sleep(1)
def update(self)
'''
self.countdown_has_run = False
if len(self.mobs) == 0:
self.timer_flag = True
if not self.countdown_has_run:
self.countdown_has_run = True
self.x.start()
'''
Now, I also draw my timer when the timer_flag is True, but it doesn't decrement, so I assume the problem lies somewhere in calling/starting the threaded countdown function?
Also, it's my first time posting here, so please let me know what to do to format better etc for you to be able to help
Don't bother with threads. No need to make your live complicated.
Usually, you use a Clock anyway in your game (if not, you should start using it) to limit the framerate, and to ensure that your world moves at a constant rante (if not, you should start doing it).
So if you want to trigger something in, say, 5 seconds, just create a variable that holds the value 5000, and substract the time it took to process your last frame (which is returned by Clock.tick):
clock = pygame.time.Clock()
dt = 0
timer = 5000
while True:
...
timer -= dt
if timer <= 0:
do_something()
dt = clock.tick(60)
I hacked together a simple example below. There, I use a simple class that is also a Sprite to draw the remaining time to the screen. When the timer runs out, it calls a function that creates a new wave of zombies.
In the main loop, I check if there's no timer running and no zombies, and if that's the case, a new timer is created.
Here's the code:
import pygame
import pygame.freetype
import random
# a dict that defines the controls
# w moves up, s moves down etc
CONTROLS = {
pygame.K_w: ( 0, -1),
pygame.K_s: ( 0, 1),
pygame.K_a: (-1, 0),
pygame.K_d: ( 1, 0)
}
# a function that handles the behaviour a sprite that
# should be controled with the keys defined in CONTROLS
def keyboard_controlled_b(player, events, dt):
# let's see which keys are pressed, and create a
# movement vector from all pressed keys.
move = pygame.Vector2()
pressed = pygame.key.get_pressed()
for vec in (CONTROLS[k] for k in CONTROLS if pressed[k]):
move += vec
if move.length():
move.normalize_ip()
move *= (player.speed * dt/10)
# apply the movement vector to the position of the player sprite
player.pos += move
player.rect.center = player.pos
# a function that let's a sprite follow another one
# and kill it if they touch each other
def zombie_runs_to_target_b(target):
def zombie_b(zombie, events, dt):
if target.rect.colliderect(zombie.rect):
zombie.kill()
return
move = target.pos - zombie.pos
if move.length():
move.normalize_ip()
move *= (zombie.speed * dt/10)
zombie.pos += move
zombie.rect.center = zombie.pos
return zombie_b
# a simple generic sprite class that displays a simple, colored rect
# and invokes the given behaviour
class Actor(pygame.sprite.Sprite):
def __init__(self, color, pos, size, behavior, speed, *grps):
super().__init__(*grps)
self.image = pygame.Surface(size)
self.image.fill(color)
self.rect = self.image.get_rect(center=pos)
self.pos = pygame.Vector2(pos)
self.behavior = behavior
self.speed = speed
def update(self, events, dt):
self.behavior(self, events, dt)
# a sprite class that displays a timer
# when the timer runs out, a function is invoked
# and this sprite is killed
class WaveCounter(pygame.sprite.Sprite):
font = None
def __init__(self, time_until, action, *grps):
super().__init__(grps)
self.image = pygame.Surface((300, 50))
self.image.fill((3,2,1))
self.image.set_colorkey((3, 2, 1))
self.rect = self.image.get_rect(topleft=(10, 10))
if not WaveCounter.font:
WaveCounter.font = pygame.freetype.SysFont(None, 32)
WaveCounter.font.render_to(self.image, (0, 0), f'new wave in {time_until}', (255, 255, 255))
self.timer = time_until * 1000
self.action = action
def update(self, events, dt):
self.timer -= dt
self.image.fill((3,2,1))
WaveCounter.font.render_to(self.image, (0, 0), f'new wave in {int(self.timer / 1000) + 1}', (255, 255, 255))
if self.timer <= 0:
self.action()
self.kill()
def main():
pygame.init()
screen = pygame.display.set_mode((600, 480))
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
dt = 0
sprites_grp = pygame.sprite.Group()
zombies_grp = pygame.sprite.Group()
wave_tm_grp = pygame.sprite.GroupSingle()
# the player is controlled with the keyboard
player = Actor(pygame.Color('dodgerblue'),
screen_rect.center,
(32, 32),
keyboard_controlled_b,
5,
sprites_grp)
# this function should be invoked once the timer runs out
def create_new_wave_func():
# let's create a bunch of zombies that follow the player
for _ in range(15):
x = random.randint(0, screen_rect.width)
y = random.randint(-100, 0)
Actor((random.randint(180, 255), 0, 0),
(x, y),
(26, 26),
zombie_runs_to_target_b(player),
random.randint(2, 4),
sprites_grp, zombies_grp)
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
# no timer, no zombies => create new timer
if len(wave_tm_grp) == 0 and len(zombies_grp) == 0:
WaveCounter(5, create_new_wave_func, sprites_grp, wave_tm_grp)
sprites_grp.update(events, dt)
screen.fill((80, 80, 80))
sprites_grp.draw(screen)
pygame.display.flip()
dt = clock.tick(60)
if __name__ == '__main__':
main()
It looks to me you are lacking the mechanism to check how many mobs are left on screen. I imagine it could be something like this:
class CountdownClock:
def __init__(self):
self.start_no = 1
self.time_between_waves = 5
self.t = threading.Thread(target=self.check_mobs_left)
self.t.start()
def check_mobs_left(self):
self.mobs = ["mob" for _ in range(randint(2, 7))] #generate 2-7 mobs per level
print (f"Wave {self.start_no} : Total {len(self.mobs)} mobs found!")
while self.mobs:
print (f"Still {len(self.mobs)} mobs left!")
time.sleep(1)
del self.mobs[-1] #simulate mob kill - remove this line from your actual setting
self.next_wave(self.time_between_waves)
self.time_between_waves +=2 #increased time for each wave
def next_wave(self,time_between_waves):
self.time_left = time_between_waves
print(f"Wave {self.start_no} cleared!")
self.start_no += 1
while self.time_left:
print (f"Next wave in...{self.time_left}")
self.time_left -=1
time.sleep(1)
self.t = threading.Thread(target=self.check_mobs_left)
self.t.start()
a = CountdownClock()
You will have this up constantly without the need to call the method every round and set flag and stuff.

How to implement a Pygame timed game loop?

I am looking to write a better game loop in Python using pygame.time.Clock(), and I understand the concept of keeping time and de-coupling rendering from the main game loop in order to better utilise the ticks. I also understand about passing time lag into the rendering so that it renders the correct amount of movement, but the only examples I've found are written in C# and although I first thought it fairly simple to convert to Python, it's not behaving.
I've figured out that Pygame's Clock() already works out the milliseconds between the last 2 calls to .tick, and I've tried to adapt the sample code I found, but I really need to see a working example written in Python. Here's what I've come up with so far:
FPS = 60
MS_PER_UPDATE = 1000 / FPS
lag = 0.0
clock = pygame.time.Clock()
running = True
# Do an initial tick so the loop has 2 previous ticks.
clock.tick(FPS)
while running:
clock.tick(FPS)
lag += clock.get_time()
user_input()
while lag >= MS_PER_UPDATE:
update()
lag -= MS_PER_UPDATE
render(lag / MS_PER_UPDATE)
I'm not sure if this is all worth it in Pygame, or if it's already taken care of in some of it's time functions already? My game runs slower on the laptop (expected) but I thought doing this might even out the FPS a bit between my main PC and laptop by de-coupling the rendering. Does anyone have experience doing these advanced game loops in Pygame? I just want it to be as good as it can be...
Just take the time it took to render the last frame (called delta time) and pass it to your game objects so they can decide what to do (e.g. move more or less).
Here's a super simple example:
import pygame
class Actor(pygame.sprite.Sprite):
def __init__(self, *args):
super().__init__(*args)
self.image = pygame.Surface((32, 32))
self.rect = pygame.display.get_surface().get_rect()
self.image.fill(pygame.Color('dodgerblue'))
def update(self, events, dt):
self.rect.move_ip((1 * dt / 5, 2 * dt / 5))
if self.rect.x > 500: self.rect.x = 0
if self.rect.y > 500: self.rect.y = 0
def main():
pygame.init()
screen = pygame.display.set_mode((500, 500))
sprites = pygame.sprite.Group()
Actor(sprites)
clock = pygame.time.Clock()
dt = 0
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
sprites.update(events, dt)
screen.fill((30, 30, 30))
sprites.draw(screen)
pygame.display.update()
dt = clock.tick(60)
if __name__ == '__main__':
main()
If your game slows down below 60 (or whatever) FPS, dt gets bigger, and Actor moves more to make up for the lost time.

how to make an animation in pygame [duplicate]

This question already has answers here:
Animated sprite from few images
(4 answers)
Closed 1 year ago.
i am trying to make an animation of when my player gets shot to make it seem like he is falling to the ground.
i have tried the code below but that doesn't seem to work. it slows down the frames and only shows the last image of my animation is there a simpler way of animation in pygame?
if player2_hit_sequence == True:
stage1 = True
if stage1 == True:
game_display.blit(dying1_p2, (player2X, player2Y))
time.sleep(0.2)
stage1 = False
stage2 = True
if stage2 == True:
game_display.blit(dying2_p2, (player2X, player2Y))
time.sleep(0.2)
stage2 = False
stage3 = True
if stage3 == True:
game_display.blit(dying3_p2, (player2X, player2Y))
time.sleep(0.2)
is there a function to make a sequence of images or something like that?
Ok so for animation you need a bunch of images, and a timer.
I'm presenting some code snippets based around a pygame sprite. Maybe this doesn't exactly fit the question, but it seems like a better solution then painting/blitting images manually.
So first the code starts with a sprite class:
class AlienSprite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.base_image = pygame.image.load('alien.png').convert_alpha()
self.image = self.base_image
self.rect = self.image.get_rect()
self.rect.center = ( WINDOW_WIDTH//2, WINDOW_HEIGHT//2 )
# Load warp animation
self.warp_at_time = 0
self.warp_images = []
for filename in [ "warp1.png", "warp2.png", "warp3.png" ]:
self.warp_images.append( pygame.image.load(filename).convert_alpha() )
So the idea is the Alien Sprite has a "normal" image, but then when it "warps" (teleports) an animation plays. The way this is implemented is to have a list of animation images. When the animation starts, the sprite's image is changed from base_image to the first of the warp_images[]. As time elapses, the sprites image is changed to the next frame, and then the next, before finally reverting back to the base image. By embedding all this into the sprite update() function, the normal updating mechanism for sprites handles the current "state" of the alien sprite, normal or "warp". Once the "warp"-state is triggered, it runs without any extra involvement of the pygame main loop.
def update(self):
# Get the current time in milliseconds (normally I keep this in a global)
NOW_MS = int(time.time() * 1000.0)
# Did the alien warp? (and at what time)
if (self.warp_at_time > 0):
# 3 Frames of warp animation, show each for 200m
ms_since_warp_start = NOW_MS - self.warp_at_time
if ( ms_since_warp > 600 ):
# Warp complete
self.warp_at_time = 0
self.image = self.base_image # return to original bitmap
# Move to random location
self.rect.center = ( random.randrange( 0, WINDOW_WIDTH ), random.randrange( 0, WINDOW_HEIGHT ) )
else:
image_number = ms_since_warp // 200 # select the frame for this 200ms period
self.image = self.warp_images[image_number] # show that image
def startWarp(self):
# Get the current time in milliseconds (normally I keep this in a global)
NOW_MS = int(time.time() * 1000.0)
# if not warping already ...
if (self.warp_at_time == 0):
self.warp_at_time = NOW_MS
So the first thing to notice, is that the update() uses the clock to know the number of elapsed milliseconds since the animation started. To keep track of the time I typically set a global NOW_MS in the game loop.
In the sprite, we have 3 frames of animation, with 200 milliseconds between each frame. To start a sprite animating, simply call startWarp() which obviously just kicks-off the timer.
SPRITES = pygame.sprite.Group()
alien_sprite = AlienSprite()
SPRITES.add(alien_sprite)
...
# Game Loop
done = False
while not done:
SPRITES.update()
# redraw window
screen.fill(BLACK)
SPRITES.draw(screen)
pygame.display.update()
pygame.display.flip()
if (<some condition>):
alien_sprite.startWarp() # do it
Obviously all those frame timings & what-not should be member variables of the sprite class, but I didn't do that to keep the example simple.

Categories