Hey can someone tell me why I dont see the objects falling from the top? In this case The "Münzen, Scheine, and Sack". I am new to pygame and maybe there is an easy way. My game should be like this:
The walking man should catch money falling down and get points for it.
https://gyazo.com/d2ce52cb54e8658e92ae9e5f3d1e7cca
import random
from pygame.sprite import Sprite
pygame.init()
#Display
win = pygame.display.set_mode((900,780))
pygame.display.set_caption("The Collector")
#Laufanimation
walkRight = [pygame.image.load('Assets/R1.png'), pygame.image.load('Assets/R2.png'), pygame.image.load('Assets/R3.png'), pygame.image.load('Assets/R4.png'), pygame.image.load('Assets/R5.png'), pygame.image.load('Assets/R6.png'), pygame.image.load('Assets/R7.png'), pygame.image.load('Assets/R8.png'), pygame.image.load('Assets/R9.png')]
walkLeft = [pygame.image.load('Assets/L1.png'), pygame.image.load('Assets/L2.png'), pygame.image.load('Assets/L3.png'), pygame.image.load('Assets/L4.png'), pygame.image.load('Assets/L5.png'), pygame.image.load('Assets/L6.png'), pygame.image.load('Assets/L7.png'), pygame.image.load('Assets/L8.png'), pygame.image.load('Assets/L9.png')]
#Hintergrund
bg = pygame.image.load('City.jpg')
bg = pygame.transform.scale(bg, (900,780))
#Charakter
char = pygame.image.load('Assets/R1.png')
# Geld
Münzen2 = pygame.image.load("Assets/coin.png")
Schein2 = pygame.image.load("Assets/schein.png")
Sack2 = pygame.image.load("Assets/sack.png")
# Geld
Münzen = pygame.image.load("Assets/coin.png")
Schein = pygame.image.load("Assets/schein.png")
Sack = pygame.image.load("Assets/sack.png")
clock = pygame.time.Clock()
class player():
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 20
self.left = False
self.right = False
self.walkCount = 0
self.hitbox = (self.x + 20, self.y, 28, 60)
def draw(self, win):
if self.walkCount + 1 >= 27:
self.walkCount = 0
if self.left:
win.blit(walkLeft[self.walkCount//3], (self.x,self.y))
self.walkCount += 1
elif self.right:
win.blit(walkRight[self.walkCount//3], (self.x,self.y))
self.walkCount +=1
else:
win.blit(char, (self.x,self.y))
self.hitbox = (self.x + 215, self.y + 230, 220, 70) # NEW
pygame.draw.rect(win, (255,0,0), self.hitbox,2)
class Laser:
def __init__(self, x, y, img):
self.x = x
self.y = y
self.img = img
def draw(self, window):
window.blit(self.img, (self.x, self.y))
def move(self, vel):
self.y += vel
def off_screen(self, height):
return not(self.y <= height and self.y >= 0)
def collision(self, obj):
return collide(self, obj)
def redrawGameWindow():
win.blit(bg, (0,0))
collector.draw(win)
pygame.display.update()
class Ship:
COOLDOWN = 30
def __init__(self, x, y, health=100):
self.x = x
self.y = y
self.health = health
self.ship_img = None
self.laser_img = None
self.lasers = []
self.cool_down_counter = 0
def draw(self, window):
window.blit(self.ship_img, (self.x, self.y))
for laser in self.lasers:
laser.draw(window)
def move_lasers(self, vel, obj):
self.cooldown()
for laser in self.lasers:
laser.move(vel)
if laser.off_screen(HEIGHT):
self.lasers.remove(laser)
elif laser.collision(obj):
obj.health -= 10
self.lasers.remove(laser)
def cooldown(self):
if self.cool_down_counter >= self.COOLDOWN:
self.cool_down_counter = 0
elif self.cool_down_counter > 0:
self.cool_down_counter += 1
def shoot(self):
if self.cool_down_counter == 0:
laser = Laser(self.x, self.y, self.laser_img)
self.lasers.append(laser)
self.cool_down_counter = 1
def get_width(self):
return self.ship_img.get_width()
def get_height(self):
return self.ship_img.get_height()
class Enemy(Ship):
COLOR_MAP = {
"red": (Münzen, Münzen2),
"green": (Schein, Schein2),
"blue": (Sack, Sack2)
}
def __init__(self, x, y, color, health=100):
super().__init__(x, y, health)
self.ship_img, self.laser_img = self.COLOR_MAP[color]
self.mask = pygame.mask.from_surface(self.ship_img)
def move(self, vel):
self.y += vel
def shoot(self):
if self.cool_down_counter == 0:
laser = Laser(self.x-20, self.y, self.laser_img)
self.lasers.append(laser)
self.cool_down_counter = 1
def collide(obj1, obj2):
offset_x = obj2.x - obj1.x
offset_y = obj2.y - obj1.y
return obj1.mask.overlap(obj2.mask, (offset_x, offset_y)) != None
#mainloop
collector = player(200, 410, 64,64)
run = True
while run:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and collector.x > -180 -collector.width -collector.vel:
collector.x -= collector.vel
collector.left = True
collector.right = False
elif keys[pygame.K_RIGHT] and collector.x < 550 - collector.width - collector.vel:
collector.x += collector.vel
collector.right = True
collector.left = False
else:
collector.right = False
collector.left = False
collector.walkCount = 0
redrawGameWindow()
pygame.quit()````
[1]: https://i.stack.imgur.com/FYFkB.png
It seems like you copy/pasted your code together, so let's drop it and start from scratch. Feel free to look some stuff up the documentation as we go along.
First, we need a mainloop to keep our game running. I usually start with something like this:
import pygame
RESOLUTION = 800, 600
FPS = 60
def main():
pygame.init()
screen = pygame.display.set_mode(RESOLUTION)
dt, clock = 0, pygame.time.Clock()
sprites = pygame.sprite.Group()
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
screen.fill('black')
sprites.update(dt, events)
sprites.draw(screen)
pygame.display.flip()
dt = clock.tick(FPS) / 1000
if __name__ == "__main__":
main()
This will create a window and manage our sprites that we will create later on and add to the sprites container. Not much to see here currently:
Now, we want a player that can move left and right. Here's how I would do it, making use of some pygame features, like the Rect and Sprite class. There's no magic involved. A Sprite is basically just a class that has an image attribute (you already guessed that this is, well, the image to use), and a rect attribute, with contains the position of where we want to draw the image.
Here's the Player class:
TILESIZE = 32
PLAYER_SPEED = 600
class Player(pygame.sprite.Sprite):
def __init__(self, pos, *grps):
super().__init__(*grps)
self.image = pygame.Surface((TILESIZE, TILESIZE))
self.image.fill('dodgerblue')
self.rect = self.image.get_rect(topleft=pos)
def update(self, dt, events):
d = 0
pressed = pygame.key.get_pressed()
if pressed[pygame.K_a]: d -= 1
if pressed[pygame.K_d]: d += 1
self.rect.move_ip(d * dt * PLAYER_SPEED, 0)
display_rect = pygame.display.get_surface().get_rect()
self.rect.clamp_ip(display_rect)
and now let's add a Player to our game:
...
sprites = pygame.sprite.Group()
Player((300, 500), sprites)
while True:
...
Note that you don't have to draw/blit anything manually. Give our class an image and rect attribute, subclass Sprite, add the instance to a Group, and call draw on this group.
Now for the falling coins and other stuff. We should create a class for them, something like this:
from random import choice
FALLING_SPEED = 400
class FallingStuff(pygame.sprite.Sprite):
def __init__(self, pos, *grps):
super().__init__(*grps)
self.image = pygame.Surface((TILESIZE, TILESIZE))
self.image.fill(choice(['red', 'yellow', 'green']))
self.rect = self.image.get_rect(topleft=pos)
def update(self, dt, events):
self.rect.move_ip(0, FALLING_SPEED * dt)
display_rect = pygame.display.get_surface().get_rect()
if self.rect.top > display_rect.bottom:
self.kill()
In your final game, you can easily replace the mono coloured image with an image you loaded from a file. Here, I just randomly choose red, yellow or green.
As you have already guessed, all the behaviour of our game objects is inside the update method of the sprite classes. The FallingStuff just moves its rect downward and kills itself when it goes out of screen. 'killing' as sprite just means it removes itself from all of its Group-containers. Another reason to use these instead of plain lists.
Of course, we want to generate multiple falling objects. There are dozen ways to do this but let's use pygame's time module to create an event because why not:
from random import randint
...
CREATE_STUFF = pygame.USEREVENT + 1
pygame.time.set_timer(CREATE_STUFF, randint(1000, 2000), True)
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
if e.type == CREATE_STUFF:
pygame.time.set_timer(CREATE_STUFF, randint(1000, 2000), True)
FallingStuff((randint(50, 550), -TILESIZE), sprites)
screen.fill('black')
sprites.update(dt, events)
sprites.draw(screen)
pygame.display.flip()
dt = clock.tick(FPS) / 1000
The only thing left is to check if we could catch one of the falling objects.
Full code below:
import pygame
import pygame.freetype
from random import choice, randint
RESOLUTION = 800, 600
FPS = 60
TILESIZE = 32
PLAYER_SPEED = 600
FALLING_SPEED = 400
class Player(pygame.sprite.Sprite):
def __init__(self, pos, falling_stuff, *grps):
super().__init__(*grps)
self.image = pygame.Surface((TILESIZE, TILESIZE))
self.image.fill('dodgerblue')
self.rect = self.image.get_rect(topleft=pos)
self.falling_stuff = falling_stuff
self.score = 0
def update(self, dt, events):
d = 0
pressed = pygame.key.get_pressed()
if pressed[pygame.K_a]: d -= 1
if pressed[pygame.K_d]: d += 1
self.rect.move_ip(d * dt * PLAYER_SPEED, 0)
display_rect = pygame.display.get_surface().get_rect()
self.rect.clamp_ip(display_rect)
for stuff in pygame.sprite.spritecollide(self, self.falling_stuff, True):
self.score += 1
class FallingStuff(pygame.sprite.Sprite):
def __init__(self, pos, *grps):
super().__init__(*grps)
self.image = pygame.Surface((TILESIZE, TILESIZE))
self.image.fill(choice(['red', 'yellow', 'green']))
self.rect = self.image.get_rect(topleft=pos)
def update(self, dt, events):
self.rect.move_ip(0, FALLING_SPEED * dt)
display_rect = pygame.display.get_surface().get_rect()
if self.rect.top > display_rect.bottom:
self.kill()
def main():
pygame.init()
screen = pygame.display.set_mode(RESOLUTION)
dt, clock = 0, pygame.time.Clock()
sprites = pygame.sprite.Group()
falling_stuff = pygame.sprite.Group()
player = Player((300, 500), falling_stuff, sprites)
font = pygame.freetype.SysFont('Arial', 54)
CREATE_STUFF = pygame.USEREVENT + 1
pygame.time.set_timer(CREATE_STUFF, randint(1000, 2000), True)
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
if e.type == CREATE_STUFF:
pygame.time.set_timer(CREATE_STUFF, randint(1000, 2000), True)
FallingStuff((randint(50, 550), -TILESIZE), falling_stuff, sprites)
screen.fill('black')
font.render_to(screen, (20, 20), f'Score: {player.score}', 'white')
sprites.update(dt, events)
sprites.draw(screen)
pygame.display.flip()
dt = clock.tick(FPS) / 1000
if __name__ == "__main__":
main()
And here's the same with animations and a hitbox:
import pygame
import pygame.freetype
import os
from random import choice, randint
from itertools import cycle
RESOLUTION = 800, 600
FPS = 60
TILESIZE = 32
PLAYER_SPEED = 300
FALLING_SPEED = 400
ANIM_THRESHOLD = 0.05
def load_images(dir):
path = os.path.dirname(os.path.realpath(__file__))
path = os.path.join(path, dir)
for f in os.listdir(path):
yield pygame.image.load(os.path.join(path, f)).convert_alpha()
class Player(pygame.sprite.Sprite):
def __init__(self, pos, falling_stuff, *grps):
super().__init__(*grps)
idle_images = list(load_images('1-Idle'))
run_images = list(load_images('2-Run'))
self.images = {
'IDLE': {
'RIGHT': cycle(idle_images),
'LEFT': cycle(pygame.transform.flip(s, True, False) for s in idle_images)
},
'RUN': {
'RIGHT': cycle(run_images),
'LEFT': cycle(pygame.transform.flip(s, True, False) for s in run_images)
}
}
self.state = 'IDLE'
self.direction = 'RIGHT'
self.image = next(self.images['IDLE']['RIGHT'])
self.animation_counter = 0
self.rect = self.image.get_rect(topleft=pos)
self.falling_stuff = falling_stuff
self.score = 0
self.hitbox = pygame.Rect(0, 0, 30, 20)
self.hitbox.center = self.rect.center
self.hitbox.move_ip(-10, -10)
def update_image(self, dt, new_state):
self.animation_counter += dt
if self.animation_counter > ANIM_THRESHOLD or self.state != new_state:
self.image = next(self.images[new_state][self.direction])
self.animation_counter = 0
def update(self, dt, events):
d = 0
pressed = pygame.key.get_pressed()
if pressed[pygame.K_a]: d -= 1
if pressed[pygame.K_d]: d += 1
self.rect.move_ip(d * dt * PLAYER_SPEED, 0)
display_rect = pygame.display.get_surface().get_rect()
self.rect.clamp_ip(display_rect)
if d == 1:
new_state = 'RUN'
self.direction = 'RIGHT'
if d == -1:
new_state = 'RUN'
self.direction = 'LEFT'
if d == 0:
new_state = 'IDLE'
for stuff in self.falling_stuff:
if self.hitbox.colliderect(stuff.rect):
stuff.kill()
self.score += 1
self.update_image(dt, new_state)
self.state = new_state
self.hitbox.center = self.rect.center
self.hitbox.move_ip(10 if self.direction == 'LEFT' else -10, -10)
pygame.draw.rect(pygame.display.get_surface(), 'red', self.hitbox, 2)
class FallingStuff(pygame.sprite.Sprite):
def __init__(self, pos, *grps):
super().__init__(*grps)
self.image = pygame.Surface((TILESIZE, TILESIZE))
self.image.fill(choice(['red', 'yellow', 'green']))
self.rect = self.image.get_rect(topleft=pos)
def update(self, dt, events):
self.rect.move_ip(0, FALLING_SPEED * dt)
display_rect = pygame.display.get_surface().get_rect()
if self.rect.top > display_rect.bottom:
self.kill()
def main():
pygame.init()
screen = pygame.display.set_mode(RESOLUTION)
dt, clock = 0, pygame.time.Clock()
sprites = pygame.sprite.Group()
falling_stuff = pygame.sprite.Group()
player = Player((300, 500), falling_stuff, sprites)
font = pygame.freetype.SysFont('Arial', 54)
CREATE_STUFF = pygame.USEREVENT + 1
pygame.time.set_timer(CREATE_STUFF, randint(1000, 2000), True)
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
if e.type == CREATE_STUFF:
pygame.time.set_timer(CREATE_STUFF, randint(1000, 2000), True)
FallingStuff((randint(50, 550), -TILESIZE), falling_stuff, sprites)
screen.fill('black')
font.render_to(screen, (20, 20), f'Score: {player.score}', 'white')
sprites.draw(screen)
sprites.update(dt, events)
pygame.display.flip()
dt = clock.tick(FPS) / 1000
if __name__ == "__main__":
main()
Sprites by Pixel Frog
First, you should consider to use "ae, oe, ue" or just the English translations instead of "ä, ö, ü", this can cause a few problems. Also, why don't you have included pygame?
Second of all, try not to use fixed values for window size, if you want to change it later on, you have to change a few values and easily run into problems when you forget one. I would recommend using a variable for width and height you can change later on.
But to your specific problem:
I think the reason you don't see any objects falling is that there are none. The part of your code that actually runs is in the while-loop and as long as I didn't miss anything, neither is there anything about your dropping objects, nor about them falling (any kind of acceleration or velocity).
Also I would highly recommend (as the comment of "oskros" already said) to test your code before asking. This is also an important part of programming and can be done like this for example:
You go in every function and write a "print" statement there, so you know that this function has run (by the output on the console). If one doesn't run, try to look at the point where it was supposed to be run and go on fixing from this point.
You can apply this technique to basically any debugging, stackoverflow is mostly for asking more specific questions and not "why does this not work, can you fix my code?" (at least for a whole program)
import pygame.freetype
from random import choice, randint
pygame.init()
RESOLUTION = 900, 780
FPS = 60
TILESIZE = 32
PLAYER_SPEED = 600
FALLING_SPEED = 400
coin = pygame.image.load('coin.png')
coin = pygame.transform.scale(coin, (60, 60))
sack = pygame.image.load('sack.png')
sack = pygame.transform.scale(sack, (60, 60))
money = pygame.image.load('schein.png')
money = pygame.transform.scale(money, (60, 60))
char = pygame.image.load ("L1.png")
walkRight = [pygame.image.load('Assets/R1.png'), pygame.image.load('Assets/R2.png'), pygame.image.load('Assets/R3.png')]
bg = pygame.image.load('City.jpg')
bg = pygame.transform.scale(bg, (900,780))
pygame.mixer.music.load('Music/Titel.mp3')
pygame.mixer.music.play(0)
class Player(pygame.sprite.Sprite):
def __init__(self, pos, falling_stuff, *grps):
super().__init__(*grps)
self.image = char
self.rect = self.image.get_rect(topleft=pos)
self.falling_stuff = falling_stuff
self.score = 0
def update(self, dt, events):
d = 0
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]: d -= 1
if pressed[pygame.K_RIGHT]: d += 1
self.rect.move_ip(d * dt * PLAYER_SPEED, 0)
display_rect = pygame.display.get_surface().get_rect()
self.rect.clamp_ip(display_rect)
for stuff in pygame.sprite.spritecollide(self, self.falling_stuff, True):
self.score += 1
class FallingStuff(pygame.sprite.Sprite):
def __init__(self, pos, *grps):
super().__init__(*grps)
self.image = choice([coin,sack,money])
self.rect = self.image.get_rect(topleft=pos)
def update(self, dt, events):
self.rect.move_ip(0, FALLING_SPEED * dt)
display_rect = pygame.display.get_surface().get_rect()
if self.rect.top > display_rect.bottom:
self.kill()
def main():
pygame.init()
screen = pygame.display.set_mode(RESOLUTION)
dt, clock = 0, pygame.time.Clock()
sprites = pygame.sprite.Group()
falling_stuff = pygame.sprite.Group()
player = Player((400, 700), falling_stuff, sprites)
font = pygame.freetype.SysFont('ComicSans', 70)
CREATE_STUFF = pygame.USEREVENT + 1
pygame.time.set_timer(CREATE_STUFF, randint(1000, 2000), True)
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
if e.type == CREATE_STUFF:
pygame.time.set_timer(CREATE_STUFF, randint(1000, 2000), True)
FallingStuff((randint(50, 550), -TILESIZE), falling_stuff, sprites)
screen.blit(bg, (0,0))
font.render_to(screen, (30, 30), f'Score: {player.score}', 'white')
sprites.update(dt, events)
sprites.draw(screen)
pygame.display.flip()
dt = clock.tick(FPS) / 1000
if __name__ == "__main__":
main()
Related
This question already has answers here:
Spawning multiple instances of the same object concurrently in python
(1 answer)
Issues with pygame.time.get_ticks() [duplicate]
(1 answer)
How to make instances spawn automatically around the player? [duplicate]
(1 answer)
Closed 1 year ago.
I am creating a game similar to the "Internet T-rex Game", Right now my game creates enemy blocks according to how many I manually create. I want it to be created by itself. My game is not fully completed yet, so please ignore the empty functions.
Heres my main.py
import pygame as pg
import random
from settings import *
from sprites import *
from os import path
class Game(object):
"""docstring for Game"""
def __init__(self):
# initialise game
global points , game_speed
pg.init()
self.screen = pg.display.set_mode((s_HEIGHT , s_WIDTH))
pg.display.set_caption(TITLE)
self.icon = pg.image.load("C:/Users/DELL/Documents/Jump Cube/Img/cube.png")
pg.display.set_icon(self.icon)
self.clock = pg.time.Clock()
self.running = True
self.game_speed = 14
points = 0
font = pygame.font.Font('freesansbold.ttf', 20)
self.load_data()
def load_data(self):
self.dir = path.dirname(__file__)
img_dir = path.join(self.dir, "Img")
#load spritesheet image
self.spritesheet = Spritesheet(path.join(img_dir, SPRITESHEET))
def new(self):
# Stars a new game
self.all_sprites = pg.sprite.Group()
self.platforms = pg.sprite.Group()
self.ene = pg.sprite.Group()
self.player = Player(self)
self.all_sprites.add(self.player)
pl = Platform(0, s_HEIGHT - 230, 800, 40)
en1 = Enemy(700, 517, 50, 50)
en2 = Enemy(600, 517, 50, 50)
en3 = Enemy(500, 517, 50, 50)
self.all_sprites.add(pl)
self.platforms.add(pl)
self.all_sprites.add([en1, en2, en3])
self.ene.add([en1, en2, en3])
self.Run()
def Run(self):
# Game Loop
self.playing = True
while self.playing:
self.clock.tick(FPS)
self.Events()
self.Update()
self.Draw()
self.score()
def Update(self):
# Game Loop - Update
self.all_sprites.update()
hits = pg.sprite.spritecollide(self.player, self.platforms, False)
if hits:
self.player.pos.y = hits[0].rect.top
self.player.vel.y = 0
pass
def score(self):
global points , game_speed
points += 1
if points % 100 == 0:
game_speed += 1
text = font.render("Points : " + str(points), True, WHITE)
textrec = text.get_rect()
textrec.center = (700, 50)
self.screen.blit(text, textrec)
def Events(self):
# Game Loop - Events
for event in pg.event.get():
if event.type == pg.QUIT:
if self.playing:
self.playing = False
self.running = False
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
self.player.jump()
if event.type == pg.KEYDOWN:
if event.key == pg.K_RIGHT:
self.player.mover()
elif event.key == pg.K_LEFT:
self.player.movel()
def Draw(self):
# Game Loop - Draw
self.screen.fill(BLACK)
self.score()
self.all_sprites.draw(self.screen)
pg.display.update()
pass
def start_screen(self):
# shows the start screen
pass
def end_screen(self):
# shows the end screen
pass
g = Game()
g.start_screen()
while g.running:
g.new()
g.end_screen()
pg.quit()
sprites.py
import pygame as pg
from settings import *
vec = pg.math.Vector2
class Spritesheet():
# utility class for laoding and parsing spritesheets
def __init__(self, filename):
self.spritesheet = pg.image.load(filename).convert()
def get_image(self, x, y, width, height):
# grabs images from large spritesheets
image = pg.Surface((width, height))
image.blit(self.spritesheet, (0,0), (x, y, width, height))
image = pg.transform.scale(image , (50, 85))
return image
class Player(pg.sprite.Sprite):
def __init__(self, game):
pg.sprite.Sprite.__init__(self)
self.game = game
self.image = self.game.spritesheet.get_image(614, 1063, 120, 191)
self.image.set_colorkey(BLACK1)
self.rect = self.image.get_rect()
self.rect.center = (s_WIDTH / 2, s_HEIGHT / 2)
self.pos = vec(100, 600)
self.vel = (0, 0)
self.acc = (0, 0)
def jump(self):
#jump only if standing on plat
self.rect.y += 1
hits = pg.sprite.spritecollide(self, self.game.platforms, False)
self.rect.y -= 1
if hits:
self.vel.y = -8
def mover(self):
#move right
self.vel.x = 5
def movel(self):
#move right
self.vel.x = -5
def update(self):
self.acc = vec(0, PLAYER_GRAV)
self.vel += self.acc
self.pos += self.vel + 0.5 * self.acc
self.rect.midbottom = self.pos
class Platform(pg.sprite.Sprite):
def __init__(self, x, y, w, h):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((w, h))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
class Enemy(pg.sprite.Sprite):
def __init__(self, x, y, w1, h1):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((w1, h1))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def update(self):
self.rect.x -= game_speed
settings.py
import pygame
pygame.init()
#game options
TITLE = "Ninja Jump"
s_WIDTH = 600
s_HEIGHT = 800
FPS = 60
game_speed = 14
points = 0
font = pygame.font.Font('freesansbold.ttf', 20)
SPRITESHEET = "spritesheet_jumper.png"
#player properties
PLAYER_ACC = 0.5
PLAYER_GRAV = 0.3
#colors
WHITE = (199, 198, 196)
BLACK = (23, 23, 23)
GRAY = (121, 121, 120)
GREEN = (72, 161, 77)
BLACK1 = (0,0,0)
GRAY1 = (162, 162, 162)
Thanks for any help and let me know if the problem needs more clarification.
Spawn the enemies by a time interval. In pygame the system time can be obtained by calling pygame.time.get_ticks(), which returns the number of milliseconds since pygame.init() was called. Define a time interval to spawn enemies. Continuously compare the current time with the time when the next enemy must appear. When the time comes, spawn an enemy and set the time the next enemy must spawn:
class Game(object):
# [...]
def Run(self):
self.next_enemy_time = 0
self.enemy_time_interval = 1000 # 1000 milliseconds == 1 second
# Game Loop
self.playing = True
while self.playing:
current_time = pygame.time.get_ticks()
if current_time > self.next_enemy_time:
self.next_enemy_time += self.enemy_time_interval
new_enemy = Enemy(700, 517, 50, 50)
self.all_sprites.add(new_enemy)
self.ene.add(new_enemy)
self.clock.tick(FPS)
self.Events()
self.Update()
self.Draw()
self.score()
For some reason, all my enemies are slowing down after they collide with the bullet. Why is this occurring? I have attached a GIF below. This game is incomplete and I am fairly new to pygame. Give any advice as needed. I made a previous post with a different, please reply to that as well if possible.
Attached GIF
import pygame, sys, random
from pygame.locals import *
pygame.init()
screen_height = 870
screen_width = 1530
screen = pygame.display.set_mode((screen_width, screen_height))
fpsfunc = pygame.time.Clock()
enemy_speed = 6
enemy_motion = 1
SPAWNENEMY = USEREVENT + 1
SPAWNEASY = USEREVENT + 2
SPAWNMED = USEREVENT + 3
SPAWNHARD = USEREVENT + 4
pygame.time.set_timer(SPAWNENEMY, 1000)
cenx = screen_width / 2
ceny = screen_height / 2
gen1 = [cenx-200,ceny-200,cenx-100,ceny-100,cenx,ceny,cenx+100,ceny+100,cenx+200,ceny+200]
gen2 = []
gen3 = []
choices = [gen1]
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.surf = pygame.Surface((50, 50))
self.surf.fill((255, 0, 0))
self.rect = self.surf.get_rect(center=(screen_width / 2,
screen_height - 100))
def update(self, pressed_keys):
if pressed_keys[K_d]:
self.rect.move_ip(3, 0)
if pressed_keys[K_a]:
self.rect.move_ip(-3, 0)
if pressed_keys[K_w]:
self.rect.move_ip(0, -5)
if pressed_keys[K_s]:
self.rect.move_ip(0, 2)
if self.rect.left <= 0:
self.rect.left = 0
if self.rect.top <= 0:
self.rect.top = 0
if pressed_keys[K_SPACE]:
bullet_sprites.add(player.create_bullet())
def create_bullet(self):
return PlayerBullet(self.rect.x + 25, self.rect.y)
class PlayerBullet(pygame.sprite.Sprite):
def __init__(self, pos_x, pos_y):
super().__init__()
self.image = pygame.Surface((10, 30))
self.image.fill((0, 255, 255))
self.rect = self.image.get_rect(center=(pos_x, pos_y))
def update(self):
self.rect.y -= 5
if self.rect.y + 30 < 0:
self.kill()
class Enemy(pygame.sprite.Sprite):
def __init__(self, cenx, ceny):
super(Enemy, self).__init__()
self.image = pygame.Surface((35,35))
self.image.fill((0,0,255))
self.rect = self.image.get_rect(center = (cenx, ceny))
def update(self):
global enemy_motion, enemy_speed, cycle
if pygame.sprite.spritecollide(self, bullet_sprites, True):
self.kill()
for enemy in enemy_sprites:
if enemy not in enemy_dir_data:
enemy_dir_data[enemy] = 1
if enemy.rect.right >= screen_width:
enemy_dir_data[enemy] = -1
if enemy.rect.left <= 0:
enemy_dir_data[enemy] = 1
enemy.rect.x += enemy_speed * enemy_dir_data[enemy]
def createnem(pos1, pos2):
return Enemy(pos1, pos2)
player = Player()
bullet_sprites = pygame.sprite.Group()
enemy_sprites = pygame.sprite.Group()
enemy_dir_data = {}
start_ticks=pygame.time.get_ticks()
while True:
seconds=(pygame.time.get_ticks()-start_ticks)/1000
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
bullet_sprites.add(player.create_bullet())
#print(seconds)
if seconds >= 10:
enemy_sprites.empty()
if len(enemy_sprites) == 0:
selected = random.choice(choices)
for create in range(0,len(selected),2):
x = create
y = create + 1
print(selected[x],selected[y])
enemy_sprites.add(createnem(gen1[x], gen1[y]))
enemy_dir_data = {}
start_ticks=pygame.time.get_ticks()
pressed_keys = pygame.key.get_pressed()
screen.fill((0, 0, 0))
screen.blit(player.surf, player.rect)
bullet_sprites.draw(screen)
enemy_sprites.draw(screen)
player.update(pressed_keys)
enemy_sprites.update()
bullet_sprites.update()
pygame.display.update()
fpsfunc.tick(60)
The speed of your enemies depends on the number of enemies because of the for loop in Enemy.update. update is called once for each enemy in the Group. Because of the for loop each enemy is moved multiple times per frame.
Read about Method Objects and move just the "self" instance object in update:
class Enemy(pygame.sprite.Sprite):
# [...]
def update(self):
global enemy_motion, enemy_speed, cycle
if pygame.sprite.spritecollide(self, bullet_sprites, True):
self.kill()
if self not in enemy_dir_data:
enemy_dir_data[self] = 1
if self.rect.right >= screen_width:
enemy_dir_data[self] = -1
if self.rect.left <= 0:
enemy_dir_data[self] = 1
self.rect.x += enemy_speed * enemy_dir_data[self]
pygame.sprite.Group.draw() and pygame.sprite.Group.update() are methods which are provided by pygame.sprite.Group.
The former delegates the to the update mehtod of the contained pygame.sprite.Sprites - you have to implement the method. See pygame.sprite.Group.update():
Calls the update() method on all Sprites in the Group [...]
The later uses the image and rect attributes of the contained pygame.sprite.Sprites to draw the objects - you have to ensure that the pygame.sprite.Sprites have the required attributes. See pygame.sprite.Group.draw():
Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect. [...]
You don't need the dictionary enemy_dir_data at all. Instead add an attribute enemy_dir to the Enemy class:
class Enemy(pygame.sprite.Sprite):
def __init__(self, cenx, ceny):
super(Enemy, self).__init__()
self.image = pygame.Surface((35,35))
self.image.fill((0,0,255))
self.rect = self.image.get_rect(center = (cenx, ceny))
self.enemy_dir = 1
def update(self):
global enemy_motion, enemy_speed, cycle
if pygame.sprite.spritecollide(self, bullet_sprites, True):
self.kill()
if self.rect.right >= screen_width:
self.enemy_dir = -1
if self.rect.left <= 0:
self.enemy_dir = 1
self.rect.x += enemy_speed * self.enemy_dir
Try:
pygame.sprite.Sprite.kill(self)
Instead of self.kill
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I've been redoing a lot of my game in order to make it more efficient, before I had functions for each level and it had about 300+ repeated lines of code for each level, I've taken it out however I'm trying to get level one to function properly now. Below is my code, any help as to how to get my code to play level1 when I run the game as right now it only displays the background screen and none of the enemies, platforms or the character.
import pygame
import time
import random
from pygame.math import Vector2 as vec
pygame.init()
# Set the screen size
screen = pygame.display.set_mode([700, 500])
# Define the colours for text
black = (0,0,0)
white = (255,255,255)
green = (0,51,0)
light_green = (51,102,0)
PLAYER_FRICTION = 0.0
PLAYER_ACC = 3
HEIGHT = 500
WIDTH = 700
FPS = 60
# Set Display
pygame.display.set_caption('Jungle Blast')
clock = pygame.time.Clock()
class Character(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("TheoHills.png")
self.rect = self.image.get_rect(topleft=(50, 300))
self.x = 50
self.y = 300
self.pos = vec(50, 300)
self.vel = vec(0,0)
self.acc = vec(0,0)
def characterJump(self,platforms):
self.rect.y += 1
hits = pygame.sprite.spritecollide(self, platforms, False)
self.rect.y -= 1
if hits:
self.vel.y = -18
def update(self):
self.acc = vec(0, 0.5)
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
self.acc.x = -PLAYER_ACC
if keys[pygame.K_d]:
self.acc.x = PLAYER_ACC
# apply friction
self.vel.x *= PLAYER_FRICTION
self.vel += self.acc
self.pos += self.vel
self.rect.midbottom = self.pos
if self.pos.y == 500:
background_image = pygame.image.load("Lose Screen.png")
if self.pos.x > 699:
level2()
class Bullet(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load("Bullet.png").convert()
self.image.set_colorkey(black)
self.rect = self.image.get_rect()
def update(self):
self.rect.x += 10
class levelInd(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("1 out of 5.png")
self.rect = self.image.get_rect(topleft=(20, 20))
self.pos = vec(20, 20)
class Platform(pygame.sprite.Sprite):
def __init__(self, x, y, w, h):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((100, 88))
self.image.fill(black)
self.image = pygame.image.load("Platform1.png")
self.rect = self.image.get_rect(topleft=(x, y))
class Enemy(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((100, 50))
self.image = pygame.image.load("RobberStanding.png")
self.rect = self.image.get_rect(topleft=(x,y))
def draw_text(surface, text, size, x, y,font_name):
font = pygame.font.SysFont(str(font_name), size)
text_surface = font.render(text, True, black)
text_rect = text_surface.get_rect()
text_rect.topleft = (x, y)
surface.blit(text_surface, text_rect)
class levels():
levelind = levelInd()
character = Character()
all_sprites = pygame.sprite.Group()
platforms = pygame.sprite.Group()
enemies = pygame.sprite.Group()
bullet_list = pygame.sprite.Group()
background_image = pygame.image.load("JungleBackground.png")
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
character.characterJump(platforms)
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
bullet = Bullet()
bullet.rect.x = character.rect.x + 10
bullet.rect.y = character.rect.y + 50
bullet_list.add(bullet)
all_sprites.add(bullet)
for bullet in bullet_list:
# See if the enemy is hit
enemyHit = pygame.sprite.spritecollide(bullet,enemies,True)
if enemyHit:
enemies.remove(Enemy)
score1 += 10
if bullet.rect.x > 700:
bullet_list.remove(bullet)
if character.rect.y >= 500:
background_image = pygame.image.load("Lose Screen.png")
pygame.display.update()
all_sprites.empty()
death = pygame.sprite.spritecollide(character, enemies, True)
if len(death) > 0:
background_image = pygame.image.load("Lose Screen.png")
all_sprites.empty()
all_sprites.update()
hits = pygame.sprite.spritecollide(character, platforms, False)
for platform in hits:
if character.vel.y > 0:
character.rect.bottom = character.rect.bottom
character.vel.y = 0
elif character.vel.y < 0:
character.rect.top = character.rect.top
character.vel.y = 3
character.pos.y = character.rect.bottom
screen.blit(background_image,[0,0])
all_sprites.draw(screen)
pygame.display.flip()
def level1():
done = False
clock = pygame.time.Clock()
font_name = pygame.font.match_font("Arial")
black = ( 0, 0, 0)
white = ( 255, 255, 255)
x = 300
y = 88
e1 = Enemy(250, 125)
enemies.add(e1)
all_sprites.add(character)
all_sprites.add(levelind)
all_sprites.add(e1)
p1 = Platform(-80, 400, WIDTH - 400, HEIGHT - 10)
p2 = Platform(175, 210, WIDTH - 400, HEIGHT - 10)
p3 = Platform(500, 400, WIDTH - 400, HEIGHT - 10)
all_sprites.add(p1, p2, p3)
platforms.add(p1, p2, p3)
score1 = 0
level1()
This is the image that shows up whenever the game is run.
I Think you should take a look at your "levels" Class.
Give it a proper init method, for example.
I got the game running by modifing the class as follows:
class levels():
def __init__(self):
self.levelind = levelInd()
self.character = Character()
self.all_sprites = pygame.sprite.Group()
self.platforms = pygame.sprite.Group()
self.enemies = pygame.sprite.Group()
self.bullet_list = pygame.sprite.Group()
self.background_image = pygame.image.load("1LPqX.png")
self.score1 = 0
self.running = True
def run(self):
while self.running:
self.level1()
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
pygame.display.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
self.haracter.characterJump(self.platforms)
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
bullet = Bullet()
bullet.rect.x = self.character.rect.x + 10
bullet.rect.y = self.character.rect.y + 50
self.bullet_list.add(bullet)
self.all_sprites.add(bullet)
for bullet in self.bullet_list:
# See if the enemy is hit
enemyHit = pygame.sprite.spritecollide(bullet, self.enemies, True)
if enemyHit:
self.enemies.remove(Enemy)
self.score1 += 10
if bullet.rect.x > 700:
self.bullet_list.remove(bullet)
if self.character.rect.y >= 500:
self.background_image = pygame.image.load("1LPqX.png")
pygame.display.update()
self.all_sprites.empty()
death = pygame.sprite.spritecollide(self.character, self.enemies, True)
if len(death) > 0:
self.background_image = pygame.image.load("1LPqX.png")
self.all_sprites.empty()
self.all_sprites.update()
hits = pygame.sprite.spritecollide(self.character, self.platforms, False)
for platform in hits:
if self.character.vel.y > 0:
self.character.rect.bottom = self.character.rect.bottom
self.character.vel.y = 0
elif self.character.vel.y < 0:
self.character.rect.top = self.character.rect.top
self.character.vel.y = 3
self.character.pos.y = self.character.rect.bottom
screen.blit(self.background_image, [0, 0])
self.all_sprites.draw(screen)
pygame.display.flip()
def level1(self):
done = False
clock = pygame.time.Clock()
font_name = pygame.font.match_font("Arial")
black = (0, 0, 0)
white = (255, 255, 255)
x = 300
y = 88
e1 = Enemy(250, 125)
self.enemies.add(e1)
self.all_sprites.add(self.character)
self.all_sprites.add(self.levelind)
self.all_sprites.add(e1)
p1 = Platform(-80, 400, WIDTH - 400, HEIGHT - 10)
p2 = Platform(175, 210, WIDTH - 400, HEIGHT - 10)
p3 = Platform(500, 400, WIDTH - 400, HEIGHT - 10)
self.all_sprites.add(p1, p2, p3)
self.platforms.add(p1, p2, p3)
self.score1 = 0
# level1()
(seems like the indentation was not copied properly, everything below "class levels()" has to be indented 4 more spaces)
and adding
if __name__ == '__main__':
game = levels()
game.run()
at the bottom of the file.
In my game I can place cannons anywhere on the screen. I want my cannons to be able to fire bullets and the bullets should be reset after they travel 100 pixels. Given below is my cannon class, I'm still new to OOP so I require some help however I wasn't able to accomplish this task using lists either. Thank you for your help.
class Cannon():
global cannon_list
global bullet_list
def __init__(self, x, y, track, old_x):
self.x = x
self.y = y
self.track = track
self.old_x = old_x
def spawnBullet(self):
for j in bullet_list:
self.old_x = self.x
self.track = j[2]
screen.blit(bullet, (j[0], j[1]))
def moveBullet(self):
if self.x <= self.track:
self.x += 3
def resetBullet(self):
if self.x >= self.track:
self.x = self.old_x
def spawnCannon(self):
for i in cannon_list:
screen.blit(cannon, i)
Using the cannon class. this is under redrawGamewindow.
for j in bullet_list:
cannonsAndBullets = Cannon(j[0], j[1], j[2], j[0])
cannonsAndBullets.spawnCannon()
cannonsAndBullets.spawnBullet()
cannonsAndBullets.moveBullet()
cannonsAndBullets.resetBullet()
Given below is what I have appended into bullet_list and cannon_list. x an y are the position of my player
cannon_list.append([x,y])
bullet_list.append([x,(y+25),100, x])
Edits in my class
class Cannon():
global cannon_list
global bullet_list
def __init__(self, x, y, track, old_x):
self.x = x
self.y = y
self.track = track
self.old_x = old_x
def spawnBullet(self):
# for j in bullet_list:
# self.x, self.y, self.track, self.old_x = j
screen.blit(bullet, (self.x, self.y))
def moveBullet(self):
# for j in bullet_list:
# self.x, self.y, self.track, self.old_x = j
if self.track <= 100:
print(self.track)
self.track += 3
self.x += 3
def resetBullet(self):
# for j in bullet_list:
# self.x, self.y, self.track, self.old_x = j
if self.track >= 100:
print(self.track)
self.x = self.old_x
def spawnCannon(self):
for i in cannon_list:
screen.blit(cannon, i)
Let's discard everything and start from scratch and make use of pygame features like sprites and vector math.
We begin with a basic skeleton of a pygame game, a simple window:
import pygame
def main():
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
screen.fill(pygame.Color('grey'))
pygame.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
Now, we want to place some Sprites. Let's create a Sprite class that represents the cannons, and let's place them with the mouse:
import pygame
class Cannon(pygame.sprite.Sprite):
def __init__(self, pos, *grps):
super().__init__(*grps)
self.image = pygame.Surface((32, 32))
self.image.fill(pygame.Color('darkred'))
self.rect = self.image.get_rect(center=pos)
def main():
all_sprites = pygame.sprite.Group()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
if e.type == pygame.MOUSEBUTTONDOWN:
Cannon(e.pos, all_sprites)
all_sprites.update()
screen.fill(pygame.Color('grey'))
all_sprites.draw(screen)
pygame.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
Now we want the cannons to shoot bullets. To do that, we're making use of some OOP features, like polymorphism. Bullets and cannons are different types, but they provide the same interface: update and draw. And that's it. Note how our mainloop does not need to know what types exactly our sprites are.
We also make sure that all the logic for bullets is in the Bullet class, and all the logic for the cannon is in the Cannon class:
import pygame
class Bullet(pygame.sprite.Sprite):
def __init__(self, pos, *grps):
super().__init__(*grps)
self.image = pygame.Surface((4, 4))
self.image.fill(pygame.Color('black'))
self.rect = self.image.get_rect(center=pos)
self.pos = pygame.Vector2(pos)
self.travelled = pygame.Vector2(0, 0)
direction = pygame.Vector2(pygame.mouse.get_pos()) - self.pos
if direction.length() > 0:
self.direction = direction.normalize()
else:
self.kill()
def update(self, dt):
v = self.direction * dt / 5
self.pos += v
self.travelled += v
self.rect.center = self.pos
if self.travelled.length() > 100:
self.kill()
class Cannon(pygame.sprite.Sprite):
def __init__(self, pos, *grps):
super().__init__(*grps)
self.image = pygame.Surface((32, 32))
self.image.fill(pygame.Color('darkred'))
self.rect = self.image.get_rect(center=pos)
self.timer = 200
def update(self, dt):
self.timer = max(self.timer - dt, 0)
if self.timer == 0:
self.timer = 200
Bullet(self.rect.center, self.groups()[0])
def main():
all_sprites = pygame.sprite.Group()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
dt = 1
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
if e.type == pygame.MOUSEBUTTONDOWN:
Cannon(e.pos, all_sprites)
all_sprites.update(dt)
screen.fill(pygame.Color('grey'))
all_sprites.draw(screen)
pygame.display.flip()
dt = clock.tick(60)
if __name__ == '__main__':
main()
Using a vector and simply adding the distance travelled each frame makes it easy to check for each Bullet if it already travelled 100 pixels. If true, simply calling kill will remove it.
I'm trying to make a bullet-hell style game and I've almost got it to work except the opponent won't change from shooting one bullet pattern to another.
It's supposed to shoot 3 blue bullets 8 times, then switch to shooting 2 purple bullets 8 times. There's a sequence of patterns but I've only got two.
So it should iterate through each pattern every time the current pattern shoots a certain amount of times. When all the patterns are done it should stop shooting completely.
I've seen people try to make these but it's always java and I'm on python.
The code is very long but I can't cut it down any more. The original is in multiple files but I've put it into one script. It's virtually impossible to simplify.
import sys
import time
import itertools
import pygame
from pygame.locals import *
class Player(pygame.sprite.Sprite):
#this sprite variable is a placeholder
sprite = pygame.image.load("Sprites/player.png")
def __init__(self, *groups):
super().__init__(*groups)
self.image = Player.sprite
self.rect = self.image.get_rect(topleft=(445, 550))
self.pos = pygame.Vector2(self.rect.topleft)
def update(self):
key = pygame.key.get_pressed()
dist = 3
if key[pygame.K_DOWN]:
self.rect.y += dist
elif key[pygame.K_UP]:
self.rect.y -= dist
if key[pygame.K_RIGHT]:
self.rect.x += dist
elif key[pygame.K_LEFT]:
self.rect.x -= dist
class Spell:
def __init__(self, bullet, pattern, speed, loop, tick_delay):
self.bullet = bullet
self.pattern = pattern
self.speed = speed
self.loop = loop
self.tick_delay = tick_delay
class Opponent(pygame.sprite.Sprite):
def __init__(self, sprite, sequence, *groups):
super().__init__(*groups)
self.image = sprite
self.rect = self.image.get_rect(topleft=(425, 30))
self.pos = pygame.Vector2(self.rect.topleft)
self.path = itertools.cycle((self.rect.topleft, ))
self.next_point = pygame.Vector2(next(self.path))
self.speed = 1
self.ticks = 1000
self.queue = []
self.sequence = sequence
self.spellno = 0
self.currentspell = sequence[self.spellno]
def update(self):
#this function basically does most of the stuff in this class
move = self.next_point - self.pos
move_length = move.length()
if move_length != 0:
move.normalize_ip()
move = move * self.speed
self.pos += move
#later on down the line i want to make the opponent sprite move
if move.length() == 0 or move_length < self.speed:
self.next_point = pygame.Vector2(next(self.path))
self.rect.topleft = self.pos
for i in range(0, self.currentspell.loop):
if pygame.time.get_ticks() - self.ticks > self.currentspell.tick_delay:
self.ticks = pygame.time.get_ticks()
self.shoot()
time_gone = pygame.time.get_ticks() - self.ticks
for bullet in self.queue:
if bullet[0] <= time_gone:
Bullet(self.rect.center, bullet[1], self.currentspell.bullet, sprites, bullets)
self.queue = [bullet for bullet in self.queue if bullet[0] > time_gone]
return
def shoot(self):
pattern = self.currentspell.pattern
self.queue = pattern
class Bullet(pygame.sprite.Sprite):
def __init__(self, pos, direction, image, *groups):
super().__init__(*groups)
self.image = image
self.rect = self.image.get_rect(topleft=pos)
self.direction = direction
self.pos = pygame.Vector2(self.rect.topleft)
def update(self):
self.pos += self.direction
self.rect.topleft = (self.pos.x, self.pos.y)
if not screen.get_rect().colliderect(self.rect):
self.kill()
sprites = pygame.sprite.Group()
bullets = pygame.sprite.Group()
opponentgroup = pygame.sprite.Group()
mi1 = Spell(pygame.image.load("Sprites/lightblue-glowey.png"),(
(0, pygame.Vector2(-0.5, 1) * 4),
(0, pygame.Vector2(0, 1) * 4),
(0, pygame.Vector2(0.5, 1) * 4)),
10, 8, 340
)
mi2 = Spell(pygame.image.load("Sprites/purple-glowey.png"),(
(0, pygame.Vector2(1, 1) * 4),
(0, pygame.Vector2(-1, 1) * 4)),
4, 8, 340
)
minty_spells = [mi1, mi2]
player = Player(sprites)
Minty = Opponent(pygame.image.load("Sprites/minty.png"), minty_spells, opponentgroup)
opponents = [Minty]
pygame.init()
SCREENWIDTH = 1000
SCREENHEIGHT = 650
screen = pygame.display.set_mode([SCREENWIDTH, SCREENHEIGHT])
screen.fill((255, 123, 67))
pygame.draw.rect(screen, (0, 255, 188), (50, 50, 900, 575), 0)
background = screen.copy()
clock = pygame.time.Clock()
currentopponent = 0
def closegame():
pygame.quit()
return
def stage(opponent, background, bgm):
currentopponent = opponent
for spell in opponents[opponent].sequence:
op = opponents[opponent]
op.update()
op.spellno += 1
def main():
running = True
while running:
for events in pygame.event.get():
if events.type == pygame.QUIT:
pygame.quit()
return
# update all sprites
sprites.update()
sprites.add(opponents[currentopponent])
# draw everything
screen.blit(background, (0, 0))
stage(0, "", "") # "" means placeholder. i'm working on them
sprites.draw(screen)
pygame.display.update()
clock.tick(100)
if __name__ == '__main__':
main()
Original Code and assets on my GitHub: https://github.com/E-Lee-Za/Eleeza-Crafter-The-Game
Here's a working (and simplified) version of your code. The loop attribute of the current spell gets decremented every time when the bullets are created. When loop is 0,
the self.spellno is incremented and the spell gets changed, otherwise if the spellno is >= len(self.sequence), self.currentspell gets set to None so that it stops shooting (just add if self.currentspell is not None to the conditional statement).
import pygame
class Spell:
def __init__(self, bullet, pattern, speed, loop, tick_delay):
self.bullet = bullet
self.pattern = pattern
self.speed = speed
self.loop = loop
self.tick_delay = tick_delay
class Opponent(pygame.sprite.Sprite):
def __init__(self, sprite, sequence, *groups):
super().__init__(*groups)
self.image = sprite
self.rect = self.image.get_rect(topleft=(425, 30))
self.start_time = pygame.time.get_ticks()
self.sequence = sequence
self.spellno = 0
self.currentspell = sequence[self.spellno]
def update(self):
time_gone = pygame.time.get_ticks() - self.start_time
# Only create bullets if self.currentspell is not None.
if self.currentspell is not None and time_gone > self.currentspell.tick_delay:
self.start_time = pygame.time.get_ticks()
for bullet in self.currentspell.pattern:
if bullet[0] <= time_gone:
Bullet(self.rect.center, bullet[1], self.currentspell.bullet, sprites, bullets)
# Decrement the loop attribute of the current spell and
# switch to the next spell when it's <= 0. When all spells
# are done, set self.currentspell to None to stop shooting.
self.currentspell.loop -= 1
if self.currentspell.loop <= 0:
self.spellno += 1
if self.spellno >= len(self.sequence):
self.currentspell = None
else:
self.currentspell = self.sequence[self.spellno]
class Bullet(pygame.sprite.Sprite):
def __init__(self, pos, direction, image, *groups):
super().__init__(*groups)
self.image = image
self.rect = self.image.get_rect(topleft=pos)
self.direction = direction
self.pos = pygame.Vector2(self.rect.topleft)
def update(self):
self.pos += self.direction
self.rect.topleft = (self.pos.x, self.pos.y)
if not screen.get_rect().colliderect(self.rect):
self.kill()
sprites = pygame.sprite.Group()
bullets = pygame.sprite.Group()
opponentgroup = pygame.sprite.Group()
img = pygame.Surface((30, 40))
img.fill((0, 100, 200))
mi1 = Spell(
img,
((0, pygame.Vector2(-0.5, 1) * 4), (0, pygame.Vector2(0, 1) * 4),
(0, pygame.Vector2(0.5, 1) * 4)),
10, 8, 340
)
img2 = pygame.Surface((30, 30))
img2.fill((110, 0, 220))
mi2 = Spell(
img2,
((0, pygame.Vector2(1, 1) * 4), (0, pygame.Vector2(-1, 1) * 4)),
4, 8, 340
)
minty_spells = [mi1, mi2]
img3 = pygame.Surface((30, 50))
img3.fill((220, 0, 200))
Minty = Opponent(img3, minty_spells, opponentgroup)
sprites.add(Minty)
pygame.init()
SCREENWIDTH = 1000
SCREENHEIGHT = 650
screen = pygame.display.set_mode([SCREENWIDTH, SCREENHEIGHT])
screen.fill((255, 123, 67))
pygame.draw.rect(screen, (0, 255, 188), (50, 50, 900, 575), 0)
background = screen.copy()
clock = pygame.time.Clock()
def main():
while True:
for events in pygame.event.get():
if events.type == pygame.QUIT:
pygame.quit()
return
sprites.update()
screen.blit(background, (0, 0))
sprites.draw(screen)
pygame.display.update()
clock.tick(100)
if __name__ == '__main__':
main()