This question already has an answer here:
Trying to delay a specific function for spawning enemy after a certain amount of time
(1 answer)
Closed 1 year ago.
I am making a spaceship game where you control a spaceship and fire bullets to defeat enemies. I have already accomplished the goal where enemies spawn on top of the screen. The problem is, Hundreds of thousands of enemies spawn on top of the screen. I tried using the sleep function from the time module, but that didn't work. Instead, the game crashed right when I ran it! Can anybody help me?
This is my current code:
import pygame
from pygame.locals import *
from random import randint
from time import sleep
pygame.init()
screen = pygame.display.set_mode((800, 500))
screen.fill((255, 255, 255))
class Spaceship(pygame.sprite.Sprite):
def __init__(self, s, x, y):
pygame.sprite.Sprite.__init__(self)
self.screen = s
self.x, self.y = x, y
self.image = pygame.image.load("C:/eqodqfe/spaceship.png")
self.image = pygame.transform.scale(self.image, (175, 175))
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
def update(self):
self.rect.center = (self.x, self.y)
class Bullet(pygame.sprite.Sprite):
def __init__(self, s, x, y):
pygame.sprite.Sprite.__init__(self)
self.screen = s
self.x, self.y = x, y
self.image = pygame.image.load("C:/eqodqfe/bullet.png")
self.image = pygame.transform.scale(self.image, (100, 100))
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
def update(self):
self.y -= 5
self.rect.center = (self.x, self.y)
if self.y < 0:
self.kill()
class Enemy(pygame.sprite.Sprite):
def __init__(self, s, x, y):
pygame.sprite.Sprite.__init__(self)
self.screen, self.x, self.y = s, x, y
self.image = pygame.image.load("C:/eqodqfe/enemy.png")
self.image = pygame.transform.scale(self.image, (240, 210))
self.rect = self.image.get_rect()
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
def update(self):
self.rect.center = (self.x, self.y)
spaceship = Spaceship(screen, 400, 400)
bullets = pygame.sprite.Group()
enemies = pygame.sprite.Group()
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == MOUSEBUTTONDOWN:
bullet = Bullet(screen, spaceship.x, spaceship.y - 20)
bullets.add(bullet)
bullets.update()
key = pygame.key.get_pressed()
amount = 5
if key[pygame.K_a]:
spaceship.x -= amount
elif key[pygame.K_d]:
spaceship.x += amount
elif key[pygame.K_w]:
spaceship.y -= amount
elif key[pygame.K_s]:
spaceship.y += amount
spaceship.update()
screen.fill((255, 255, 255))
screen.blit(spaceship.image, spaceship.rect)
enemy = Enemy(screen, randint(-200, 800), 0)
enemies.add(enemy)
sleep(5)
bullets.draw(screen)
enemies.draw(screen)
pygame.display.update()
clock.tick(60)
Use a timer event to spawn enemies.
In pygame exists a timer event. Use pygame.time.set_timer() to repeatedly create a USEREVENT in the event queue. The time has to be set in milliseconds. e.g.:
enemy_interval = 1000 # 1000 milliseconds == 1 seconds
enemy_event = pygame.USEREVENT + 1
pygame.time.set_timer(enemy_event, enemy_interval)
Create a new enemy when the event occurs:
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == MOUSEBUTTONDOWN:
bullet = Bullet(screen, spaceship.x, spaceship.y - 20)
bullets.add(bullet)
if event.type == enemy_event:
enemy = Enemy(screen, randint(-200, 800), 0)
enemies.add(enemy)
# [...]
# DELETE
# enemy = Enemy(screen, randint(-200, 800), 0)
# enemies.add(enemy)
# sleep(5)
# [...]
Related
This question already has answers here:
How can i shoot a bullet with space bar?
(1 answer)
How do I stop more than 1 bullet firing at once?
(1 answer)
Closed 10 months ago.
Im continuing practicing in pygame, and now the problem is that collisions between player and enemy dont work and player doesnt shoot. I watched at least 5 or 6 guides, googled, but it just doesnt work in my case. Game works even after player and enemy collide, and shoot when i shoot nothing happens.
import pygame, random
pygame.init()
pygame.font.init()
width, height = 924, 500
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Priest Beast')
clock = pygame.time.Clock()
BG = pygame.transform.scale2x(pygame.image.load('art/background.png')).convert_alpha()
music = pygame.mixer.Sound('sound/music.mp3')
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.transform.scale2x(pygame.image.load('art/Player.png')).convert_alpha()
self.x = x
self.y = y
self.rect = self.image.get_rect(center = (800, 300))
def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
self.rect.x -= 3
if keys[pygame.K_d]:
self.rect.x += 3
if self.rect.x >= 810:
self.rect.x = 810
if self.rect.x <= -30:
self.rect.x = -30
if keys[pygame.K_SPACE]:
self.shoot
def shoot(self):
bullet = Bullet(self.x, self.y)
bullets.add(bullet)
def update(self):
self.move()
self.shoot()
class Enemy(pygame.sprite.Sprite):
def __init__(self,x,y):
super().__init__()
self.image = pygame.transform.scale2x(pygame.image.load('art/Enemy.png'))
self.image.convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def move(self):
self.rect.x += 3
if self.rect.x >= 900:
self.kill
def update(self):
self.move()
class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y):
super().__init__()
self.image = pygame.image.load("art/bullet.png").convert_alpha()
self.rect = self.image.get_rect()
self.x = x
self.y = y
self.speed = -10
def update(self):
self.rect.x -= self.speed
if self.rect.x <= -100:
self.kill()
player = pygame.sprite.GroupSingle(Player(800,200))
enemy_list = pygame.sprite.Group()
obstacle_timer = pygame.USEREVENT + 1
timer = pygame.time.set_timer(obstacle_timer,4000)
bullets = pygame.sprite.Group()
hit = pygame.sprite.groupcollide(player, enemy_list, False, False)
bullethit = pygame.sprite.groupcollide(bullets, enemy_list, False, False)
#Loop and exit
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == obstacle_timer:
enemy_list.add(Enemy(random.randint(-1000, -30), 210))
if event.type == hit:
running = False
if event.type == bullethit:
print("hit!")
# Sounds
#music.play()
#music.set_volume(0.1)
screen.blit(BG, (0, 0))
enemy_list.draw(screen)
enemy_list.update()
bullets.update()
player.draw(screen)
player.update()
pygame.display.update()
clock.tick(60)
I am making a pygame game where you control a spaceship and fire bullets to hit the enemies. As of right now, I am trying to make an enemy appear on the screen. Not making it move yet. However, when I ran my following code, Nothing but the spaceship appeared. The spaceship also was able to move and fire bullets.
This is my current code:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800, 500))
screen.fill((255, 255, 255))
class Spaceship(pygame.sprite.Sprite):
def __init__(self, s, x, y):
pygame.sprite.Sprite.__init__(self)
self.screen = s
self.x, self.y = x, y
self.image = pygame.image.load("C:/eqodqfe/spaceship.png")
self.image = pygame.transform.scale(self.image, (175, 175))
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
def update(self):
self.rect.center = (self.x, self.y)
class Bullet(pygame.sprite.Sprite):
def __init__(self, s, x, y):
pygame.sprite.Sprite.__init__(self)
self.screen = s
self.x, self.y = x, y
self.image = pygame.image.load("C:/eqodqfe/bullet.png")
self.image = pygame.transform.scale(self.image, (100, 100))
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
def update(self):
self.y -= 1
self.rect.center = (self.x, self.y)
if self.y < 0:
self.kill()
class Enemy(Spaceship):
def __init__(self, s, x, y):
Spaceship.__init__(self, s, x, y)
self.image = pygame.image.load("C:/eqodqfe/enemy.png")
self.image = pygame.transform.scale(self.image, (175, 175))
self.rect = self.image.get_rect()
spaceship = Spaceship(screen, 400, 400)
enemy = Enemy(screen, 100, 100)
bullets = pygame.sprite.Group()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == MOUSEBUTTONDOWN:
bullet = Bullet(screen, spaceship.x, spaceship.y - 20)
bullets.add(bullet)
bullets.update()
key = pygame.key.get_pressed()
if key[pygame.K_a]:
spaceship.x -= 0.5
elif key[pygame.K_d]:
spaceship.x += 0.5
elif key[pygame.K_w]:
spaceship.y -= 0.5
elif key[pygame.K_s]:
spaceship.y += 0.5
spaceship.update()
screen.blit(enemy.image, enemy.rect)
enemy.update()
screen.fill((255, 255, 255))
screen.blit(spaceship.image, spaceship.rect)
bullets.draw(screen)
pygame.display.update()
What is wrong?
You have to draw the enemy after drawing the background. If you draw the enemy before the background, the background will hide the enemy:
running = True
while running:
# [...]
# screen.blit(enemy.image, enemy.rect) <-- DELETE
enemy.update()
screen.fill((255, 255, 255))
screen.blit(enemy.image, enemy.rect) # <-- INSERT
screen.blit(spaceship.image, spaceship.rect)
bullets.draw(screen)
pygame.display.update()
I know that this question has already been answered in other forms, but I can't seem to make it work for my game. I'm trying to make the sprite move and keep him in the place he moved to. This is part of my code:
class player(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
def draw(self, x, y):
player = pygame.image.load("stand_down.png").convert_alpha()
player = pygame.transform.scale(player, (100, 200))
screen.blit(player, (x, y))
pygame.display.update()
for event in pygame.event.get():
key = pygame.key.get_pressed()
if event.type == KEYDOWN :
if key [K_LEFT] :
player = pygame.image.load("standleft.png").convert_alpha()
player = pygame.transform.scale(player, (100, 200))
x -= 50
screen.blit(player, (x, y))
pygame.display.update()
pygame.sprite.Sprite.update(player)
if key [K_RIGHT]:
player = pygame.image.load("standright.png").convert_alpha()
player = pygame.transform.scale(player, (100, 200))
x += 50
screen.blit(player, (x, y))
pygame.display.update()
pygame.sprite.Sprite.update(player)
def update(self):
pygame.sprite.Sprite.update(player)
And then this is part of my main function:
player.draw(screen, x, y)
player.update(screen)
I've tried everything I can think of, but the player just keeps flashing at a different point, then returning to the previous position. If you could help, it would be much appreciated!
I can't test it but I would do this
# --- classes ---
class Player(pygame.sprite.Sprite): # UpperCaseName for class
def __init__(self, x, y):
super().__init__()
temp_image = pygame.image.load("stand_down.png").convert_alpha()
self.image_down = pygame.transform.scale(temp_image, (100, 200))
temp_image = pygame.image.load("standleft.png").convert_alpha()
self.image_left = pygame.transform.scale(temp_image, (100, 200))
temp_image = pygame.image.load("standright.png").convert_alpha()
self.image_right = pygame.transform.scale(temp_image, (100, 200))
self.image = self.image_down
# keep position and size in pygame.Rect()
# to use it in collision checking
self.rect = self.image.get_rect(x=x, y=y)
def draw(self, screen):
screen.blit(self.image, self.rect)
def handle_event(self):#, event)
self.image = self.image_down
key = pygame.key.get_pressed()
if key[K_LEFT]:
self.rect.x -= 50
self.image = self.image_left
if key[K_RIGHT]:
self.rect.x += 50
self.image = self.image_right
def update(self, enemy):
# check collision with eneny
if self.rect.colliderect(enemy.rect):
print("I'm killed by enemy")
# --- main ---
player = Player(400, 400)
enemy = Enemy(100, 100)
while True:
# - events -
for event in pygame.event.get():
#player.handle_event(event)
player.handle_event()
# - updates -
enemy.update()
player.update(enemy)
# - draws -
screen.fill( (0,0,0) )
player.draw(screen)
enemy.draw(screen)
pygame.display.update()
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
i'm having a problem with my code. So, I want to create a game, in Pygame, where the bananas fall from the sky, and the monkey have to grab them. I'm having quite a hard time creating a collision between those two (spent hours trying already).
So, this is my code:
import pygame, sys, random, time, os
from pygame.locals import *
#Variáveis necessárias
banana_speed = 5
monkey_speed = 20
WIDTH = 800
HEIGHT = 800
pontos = 0
vidas = 3
#Nome do jogo
pygame.display.set_caption("Catch the fruit")
#Tamanho do ecrã do jogo
screen = pygame.display.set_mode((WIDTH, HEIGHT))
class Macaco(pygame.sprite.Sprite):
def __init__(self):
self.image = pygame.image.load('monkey.png')
self.rect = self.image
self.x = 300
self.y = 640
def keyboard(self):
key = pygame.key.get_pressed()
if key[pygame.K_RIGHT]:
self.x += monkey_speed
elif key[pygame.K_LEFT]:
self.x -= monkey_speed
def draw (self, screen):
screen.blit(self.rect, (self.x, self.y))
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
class Banana(pygame.sprite.Sprite):
def __init__(self):
self.image = pygame.image.load('banana.png')
self.rect = self.image
self.x = random.randrange(0,WIDTH)
self.y = -50
def draw(self, screen):
self.y = self.y + banana_speed
screen.blit(self.rect,(self.x, self.y))
#Funções necessárias para o Loop
macaco = Macaco()
banana = Banana()
Background = Background('background.png', [0,0])
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
while vidas > 0:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
screen.blit(Background.image, Background.rect)
pressed_keys = pygame.key.get_pressed()
macaco.keyboard()
macaco.draw(screen)
banana.draw(screen)
pygame.display.update()
edit:
So i'm trying another solution and did this:
import pygame, sys, random, time, os
from pygame.locals import *
#Variáveis necessárias
banana_speed = 5
monkey_speed = 20
WIDTH = 800
HEIGHT = 800
pontos = 0
vidas = 3
green = (0, 0 , 255)
#Nome do jogo
pygame.display.set_caption("Catch the fruit")
#Tamanho do ecrã do jogo
screen = pygame.display.set_mode((WIDTH, HEIGHT))
class Macaco(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.rect = pygame.image.load('monkey.png')
self.image = pygame.Surface([WIDTH, HEIGHT])
self.x = 300
self.y = 640
self.image.fill(green)
def keyboard(self):
key = pygame.key.get_pressed()
if key[pygame.K_RIGHT]:
self.x += monkey_speed
elif key[pygame.K_LEFT]:
self.x -= monkey_speed
def draw (self, screen):
screen.blit(self.rect, (self.x, self.y))
class Background(pygame.sprite.Sprite):
def __init__(self, image_file, location):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
class Banana(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.rect = pygame.image.load('banana.png')
self.image = pygame.Surface([WIDTH, HEIGHT])
self.x = random.randrange(0, WIDTH)
self.y = -50
def draw(self, screen):
self.y = self.y + banana_speed
screen.blit(self.rect,(self.x, self.y))
#Funções necessárias para o Loop
macaco = Macaco()
banana = Banana()
Background = Background('background.png', [0,0])
os.environ["SDL_VIDEO_CENTERED"] = "1"
pygame.init()
while vidas > 0:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
screen.blit(Background.image, Background.rect)
pressed_keys = pygame.key.get_pressed()
macaco.keyboard()
macaco.draw(screen)
banana.draw(screen)
blocks_hit_list = pygame.sprite.spritecollide(macaco, banana, True)
for blocks in blocks_hit_list:
pontos +=1
pygame.display.update()
Could you give me some help please?
I've created two sprite groups: all_sprites which contains all sprites and is used to update and draw them with just two lines of code, and the bananas group which is used to check for collisions between the macaco and the bananas. Then we need the pygame.sprite.spritecollide function to get the collided sprites. You have to pass a sprite instance and a sprite group and it'll check for you if the sprite has collided with the sprites in the group. It returns the collided bananas as a list over which you can iterate to do something with them or for example to increment a points counter.
You have to call the __init__ method of the parent class in your sprites to be able to use them correctly with sprite groups (do that with the super function super().__init__() (in Python 2 super(Macaco, self).__init__()).
To update the positions of your sprites, set their topleft (or center) attribute to the new x, y coordinates.
To get a rect from an image call self.rect = self.image.get_rect().
import sys
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
class Macaco(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((30, 30))
self.image.fill((190, 140, 20))
self.rect = self.image.get_rect()
self.x = 300
self.y = 640
self.speed = 20
def keyboard(self, keys):
if keys[pygame.K_RIGHT]:
self.x += self.speed
elif keys[pygame.K_LEFT]:
self.x -= self.speed
def update(self):
self.rect.topleft = self.x, self.y
class Banana(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((30, 30))
self.image.fill((230, 230, 40))
self.rect = self.image.get_rect()
self.x = random.randrange(0, 770)
self.y = -50
self.speed = 5
def update(self):
self.y += self.speed
self.rect.topleft = self.x, self.y
macaco = Macaco()
banana = Banana()
all_sprites = pygame.sprite.Group(macaco, banana)
bananas = pygame.sprite.Group(banana)
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
keys = pygame.key.get_pressed()
macaco.keyboard(keys)
all_sprites.update()
# Collision detection. Check if macaco collided with bananas group,
# return collided bananas as a list. dokill argument is True, so
# that collided bananas will be deleted.
collided_bananas = pygame.sprite.spritecollide(macaco, bananas, True)
for collided_banana in collided_bananas:
print('Collision.')
screen.fill((70, 40, 70))
all_sprites.draw(screen)
pygame.display.update()
clock.tick(30)
pygame.quit()
sys.exit()
Basically the rocket moves up and down, stops when it reaches the top or bottom and recognizes that the spacebar is being pressed. However the bullet won't shoot from the ship. I'm new to python and pygame. Anyways here is the code, thank you for any help!:
import pygame
import sys
from pygame.locals import*
bg_color = (0, 191, 255)
d_w = 1200
d_h= 800
class Rocket(object):
def __init__(self):
self.image = pygame.image.load('Rocket.bmp')
self.x = 0
self.y = d_h/2
def handle_keys(self):
key = pygame.key.get_pressed()
dist = 6.5
if key[pygame.K_UP]:
if self.y > 0:
self.y -= dist
elif key[pygame.K_DOWN]:
if self.y < 775:
self.y += dist
elif key[pygame.K_SPACE]:
Bullet.update(Bullet)
def draw(self, surface):
surface.blit(self.image, (self.x, self.y))
class Bullet(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface([2, 5])
self.image.fill(0, 0, 0)
self.rect = self.image.get_rect()
def update(self):
""" Move the bullet. """
self.image = pygame.Surface([2, 5])
self.image.fill((0, 0, 0))
self.rect = self.image.get_rect()
self.rect.x += 3
pygame.init()
screen = pygame.display.set_mode((d_w, d_h))
pygame.display.set_caption("Game Character")
Mario = pygame.image.load('Mario_Sprite.bmp')
rocket = Rocket()
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
rocket.handle_keys()
screen.fill(bg_color)
rocket.draw(screen)
pygame.display.update()
clock.tick(72)
Bullet.update(Bullet)
You're calling update statically. You need to create an instance of the class and then update that instance, as in:
bullet = Bullet()
...
bullet.update()