-1

I am making a game with pygame and sprite, and the game has birds, gun and bullet classes.

When the gun releases a bullet and the bullet touches the bird, the bird and the bullet suppose to disappear immediately.

My challenge at the moment is to know when the bullet touches the bird and to make the bullet disappear alongside the bird.

One thing that I realized is that somehow my birds are disappearing when I fire a bullet in the bird's direction but I discovered that the bird disappears before the bullet touches bird.

Can someone please look at my code and tell me what I am doing wrong?

import pygame
import os
import random

BACKGROUND_IMAGE = pygame.image.load(
os.path.join("Assets", "2dforest.jpeg"))

BACKGROUND_WIDTH, BACKGROUND_HEIGHT = 900, 500
pygame.display.set_caption("Hunting Birds")

WIN = pygame.display.set_mode((BACKGROUND_WIDTH, BACKGROUND_HEIGHT))
COLOR = (255, 200, 98)


class Birds(pygame.sprite.Sprite):

   def __init__(self, image, width, height, pos_x, pos_y):
      super().__init__()
      self.width = width
      self.height = height
      self.pos_x = pos_x
      self.pos_y = pos_y
      self.image = pygame.image.load(
        os.path.join("Assets", image)).convert_alpha()
      self.image = pygame.transform.scale(self.image, (175, 175))
      self.rect = self.image.get_rect()
      self.rect.center = (self.pos_x, self.pos_y)


class HunterGun(pygame.sprite.Sprite):

  def __init__(self, image, width, height, pos_x, pos_y):
    super().__init__()
    self.width = width
    self.height = height
    self.pos_x = pos_x
    self.pos_y = pos_y
    self.image = pygame.image.load(
        os.path.join("Assets", image)).convert_alpha()
    self.image = pygame.transform.scale(self.image, (175, 175))
    self.rect = self.image.get_rect()
    self.rect.center = (self.pos_x, self.pos_y)


 def move_and_turn(self, mover):
    keys_pressed = pygame.key.get_pressed()
    if (keys_pressed[pygame.K_LEFT]):
        pos_x, pos_y = self.rect.center
        pos_x -= mover
        self.rect.center = (pos_x, pos_y)
    elif (keys_pressed[pygame.K_RIGHT]):
        pos_x, pos_y = self.rect.center
        pos_x += mover
        self.rect.center = (pos_x, pos_y)
    elif (keys_pressed[pygame.K_UP]):
        pos_x, pos_y = self.rect.center
        pos_y -= mover
        self.rect.center = (pos_x, pos_y)
    elif (keys_pressed[pygame.K_DOWN]):
        pos_x, pos_y = self.rect.center
        pos_y += mover
        self.rect.center = (pos_x, pos_y)
        print(self.rect, "Down")
   
def rotate(self, angle):
    self.angle = angle
    self.image = pygame.transform.rotate(
        self.image, self.angle)
    self.pos_y += 2
    self.pos_x -= 18
    print(self.pos_x)
    self.rect.center = (self.pos_x, self.pos_y)
    self.rect = self.image.get_rect(center=(self.rect.center))

def create_bullect(self):
    pos_x, pos_y = self.rect.center

    return Bullet(pos_x + 95, pos_y - 67)


class Bullet(pygame.sprite.Sprite):

  def __init__(self, pos_x, pos_y):
    super().__init__()
    self.pos_x = pos_x
    self.pos_y = pos_y
    self.image = pygame.image.load(
        os.path.join("Assets", "bullet.png")).convert_alpha()
    self.image = pygame.transform.scale(self.image, (50, 80))
    self.rect = self.image.get_rect(center=(pos_x, pos_y))

  def update(self):
    self.rect.x += 13
    self.pos_x
    if(self.rect.x >= BACKGROUND_WIDTH + 200):
        print(self.rect)
        self.kill()
    elif(self.rect.y >= BACKGROUND_HEIGHT + 200):
        self.kill()


birds_sprite = pygame.sprite.Group()
for target in range(10):
new_target = Birds("birds.png", 100, 100,
                   random.randrange(0, BACKGROUND_WIDTH),               random.randrange(0, BACKGROUND_HEIGHT))
birds_sprite.add(new_target)


gunhunter = HunterGun("gunner.png", 100, 100,
                  BACKGROUND_WIDTH // 2, BACKGROUND_HEIGHT//2)
gun_sprite = pygame.sprite.Group()
gun_sprite.add(gunhunter)

bullet_group = pygame.sprite.Group()


pygame.init()
clock = pygame.time.Clock()
run = True

while run:
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         run = False
      keys_pressed = pygame.key.get_pressed()
      if (keys_pressed[pygame.K_k]):
         bullet_group.add(gunhunter.create_bullect())
         pygame.sprite.spritecollideany(
            birds_sprite, bullet_group, True, True)

      if(keys_pressed[pygame.K_r]):
          gunhunter.rotate(3)

    picture = pygame.transform.scale(BACKGROUND_IMAGE, (1000, 540))
    pygame.display.flip()

    WIN.blit(picture, (0, 0))

    birds_sprite.draw(WIN)
    bullet_group.draw(WIN)
    gun_sprite.draw(WIN)

    gunhunter.move_and_turn(4)
    birds_sprite.update()
    gun_sprite.update()
    bullet_group.update()
    clock.tick(60)

pygame.quit()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • "Can someone please look at my code and tell me what I am doing wrong? is not a valid question. Stack Overflow is not a debugging service. The following references give advice on debugging your code. [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/), [Six Debugging Techniques for Python Programmers](https://medium.com/techtofreedom/six-debugging-techniques-for-python-programmers-cb25a4baaf4b) or [Ultimate Guide to Python Debugging](https://towardsdatascience.com/ultimate-guide-to-python-debugging-854dea731e1b). – itprorh66 Oct 28 '22 at 14:01
  • @itprorh66 what I needed was someone to help me understand why my collision is not working properly as it should work. – Chukwuma Kingsley Oct 29 '22 at 14:15
  • @Rabbid76 First of all, I don't think that I would have been able to get the game up to this stage if I had not learned the basics, my code is working the only problem is that the collision is not working correctly sometimes, otherwise everything in my game is working. – Chukwuma Kingsley Oct 29 '22 at 14:47
  • @Rabbid76 I never said that I am perfect in `Python` and `Pygame` I actually started using `Pygame` not a long time ago. So, I will grow as I build more games. – Chukwuma Kingsley Oct 29 '22 at 14:59

1 Answers1

1

See How to get keyboard input in pygame?. pygame.key.get_pressed() is not an event. pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is 1, otherwise 0. So you can calculate the resulting movement when 2 keys are pressed with keys[pygame.K_d] - keys[pygame.K_a] and keys[pygame.K_s] - keys[pygame.K_w]. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action.
Also see How can i shoot a bullet with space bar? and How do I stop more than 1 bullet firing at once?.

The collision detection has to be done in the application loop. Also see How do I detect collision in pygame?

e.g.:

while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
           if event.key == pygame.K_k:
              bullet_group.add(gunhunter.create_bullect())

    if(keys_pressed[pygame.K_r]):
          gunhunter.rotate(3)

    pygame.sprite.spritecollideany(birds_sprite, bullet_group, True, True)
Rabbid76
  • 202,892
  • 27
  • 131
  • 174