0

I'm trying to run a Pygame program I wrote 4 years ago but it is not working as it should. When the player collides with a trash sprite, the trash sprite is supposed to disappear and the "pocket" value is supposed to increase. However, when the player collides with the trash sprites, nothing occurs. I am rusty at Python/Pygame and need help in determining what is going wrong here semantically. The trash list is a set of images and copies. Let me know if I should include the sprite files.

Edit: The aforementioned action should happen when the space bar is pressed when the player is currently colliding with the trash sprite.

import pygame
import sys
import random
import time
from trash_sprite import Trash
from player import Player
from tide_waves import tide
from basket import basket
pygame.init()

# Initialization
check_errors = pygame.init()  # should be (6, 0), 6 is processes initialized, 0 is errors
if check_errors[1] > 0 : 
    print("Error!: Had {0} initializing errors, quitting ...".format(check_errors[1]))
    print("Errors: " + str(check_errors))
else :
    print("(+) Pygame successfully intialized!")
 
#Screen Display    
screen_width = 720
screen_height = 460
#screen = pygame.display.set_mode((screen_width, screen_height))
screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
background = pygame.image.load("images/Beach.png")
pygame.display.set_caption("Beach Cleanup")


# Sprites
all_sprites_list = pygame.sprite.Group()

#Player
player = Player(340, 200)
all_sprites_list.add(player)

# Tide
tide = tide(0,-250)

all_sprites_list.add(tide)

# Basket
basket = basket(24,415)
all_sprites_list.add(basket)

# Trash List
trash_list = pygame.sprite.Group()
# Images for separate trash pieces
trashy = ["images/apple.png", "images/banana.png", "images/bucket.png", "images/cigarette.png", "images/diaper.png"]
for i in range(65):
    trash = Trash(200,200)
    trash_image = random.choice(trashy)
    trash.image = pygame.image.load(trash_image).convert_alpha()
    trash.rect.x = random.randrange(50,screen_width-50)
    trash.rect.y = random.randrange(150,screen_height-40)
    trash_list.add(trash)
    all_sprites_list.add(trash)

# Player Facing Direction
direction = 'up'

# Score
score = 0
red = (233,21,68)
def showScore() :
    sFont = pygame.font.SysFont('monaco', 24)
    Ssurf = sFont.render("Score: {0}".format(score), True, red)
    Srect = Ssurf.get_rect()
    Srect.midtop = (50, 25)
    screen.blit(Ssurf,Srect)

# Pocket Function
pocket = 0
def showPocket():
    sFont = pygame.font.SysFont('monaco', 24)
    Psurf = sFont.render("Pocket: {0}".format(pocket), True, red)
    Prect = Psurf.get_rect()
    Prect.midtop = (54, 45)
    screen.blit(Psurf,Prect)

# Timer Variables
clock = pygame.time.Clock()
start_ticks=pygame.time.get_ticks() #starter tick
def gameTimer():
    seconds=int((pygame.time.get_ticks()-start_ticks)/1000) #calculate how many seconds
    font = pygame.font.SysFont('monaco', 24)
    print (seconds) #print how many seconds
    text = font.render("Timer: {0}".format(30-seconds), True, red)
    trect = text.get_rect()
    trect.midtop = (50, 65)
    screen.blit(text, trect)    
    return seconds

# Basket Collision
def collided_with(self,player,basket):
    global score
    global pocket
    col = pygame.sprite.spritecollide(player,basket)
    if col == True:
        score += 1
        pocket = 0
        
def timesup():
    sFont = pygame.font.SysFont('monaco', 56)
    Gsurf = sFont.render("Time's Up!", True, red)
    Grect = Gsurf.get_rect()
    Grect.midtop = (360, 230)
    screen.blit(Gsurf,Grect)    

# Gameloop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type==pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE :
                pygame.event.post(pygame.event.Event(pygame.QUIT))            
        
        # Main sprite movement
    keys = pygame.key.get_pressed()
    if keys[pygame.K_RIGHT] or keys[pygame.K_d]:
        player.moveRight(4)
        direction = 'right'
    if keys[pygame.K_LEFT] or keys[pygame.K_a]:
        player.moveLeft(4)
        direction = 'left'
    if keys[pygame.K_UP] or keys[pygame.K_w]:
        player.moveUp(4)
        direction = 'up'
    if keys[pygame.K_DOWN] or keys[pygame.K_s]:
        player.moveDown(4 )
        direction = 'down'
    
    if player.rect.x > screen_width:
        player.rect.x -= screen_width
    elif player.rect.x < 0:
        player.rect.x += screen_width
    if player.rect.y > screen_height:
        player.rect.y -= screen_height
    elif player.rect.y < 0:
        player.rect.y += screen_height
    
    # Sprite Collision:
    trash_hit_list = pygame.sprite.spritecollide(player, trash_list, False)
    for trash in trash_hit_list:
        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            if pocket < 7:
                pocket += 1
                score += 1
                trash_list.remove(trash)
                trash_list.update
                all_sprites_list.remove(trash)
    
    col = pygame.sprite.collide_rect(player,basket)
    if col == True:
        if pocket <= 7 and pocket!=0:
            if event.type == pygame.KEYDOWN and event.key == pygame.K_LSHIFT:
                score += 2
                pocket = 0            
                
    # Player Graphic
    if direction == 'right':
        player.image = pygame.image.load("images/character_right.png").convert_alpha()
    if direction == 'left':
        player.image = pygame.image.load("images/character_left.png").convert_alpha()
    if direction == 'up':
        player.image = pygame.image.load("images/character_up.png").convert_alpha()
    if direction == 'down':
        player.image = pygame.image.load("images/character_down.png").convert_alpha()
       
    # Display
    screen.blit(background,(0,0))
    trash_list.draw(screen)
    basket.draw(screen)
    player.draw(screen)
    tide.draw(screen)
    
    #Timer
    seconds = gameTimer()
    
    # Tide
    tide.tide_movement()
    
    # Update
    showScore()
    showPocket()
    pygame.display.flip()
    clock.tick(30) 
    print(pygame.time.get_ticks())
    if seconds == 30:
        timesup()
        pygame.display.flip()
        time.sleep(6)
        break
pygame.quit()
Peter O.
  • 32,158
  • 14
  • 82
  • 96
ShinyDino
  • 1
  • 2

1 Answers1

0

pygame.sprite.spritecollide doesn't return a Boolean value, but a list containing all Sprites in a Group that intersect with another Sprite

if col == True:

col = pygame.sprite.spritecollide(player,basket)
if col:
    score += 1
    pocket = 0

See also How do I check if a list is empty?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174