user12757415
user12757415

Reputation:

deleting an image on pygame

I was just wondering if anyone knew how to delete a picture in pygame once the image collides with another. Right now, my the battery and the e-waste is colliding together and when it does, an explosion happens but that doesn't occur at the correct place yet. My goal is to delete the e-waste image once it collides with the battery. I'm not sure how to do that so can anyone please help? Thanks

import pygame
pygame.init()
import random
SIZE = (width, height) = (1000, 700) #Screen Size
screen = pygame.display.set_mode(SIZE)


#Defining Colours
GREEN = (0,255,0)
BLACK = (0,0,0)
GREY = (48,48,48)
WHITE = (255, 255, 255)
YELLOW = (246, 255, 112)
BLUE = (0, 9, 255)
RED = (255, 0, 0)


#======= initialize Variables =======

in_game = False
shipEats = 0
score = 0
health = 100


#Ship
x_ship_pos = 500 # ship x coord
y_ship_pos = 600 # ship y coord
x_ship_speed = 0 # move ship x coord by x
y_ship_speed = 0 # move ship y coord by y
direction = 360 #Ship faces up


#Battery
is_battery_on_screen = False
x_battery_pos = 0
y_battery_pos = 0
battery_direction = "UP"


#E-Waste
xWastePos = random.randint(0, 300)
yWastePos = random.randint(0, 580)

xWaste2 = random.randint(330, 600)
yWaste2 = random.randint(0, 580)

xWaste3 = random.randint(630, 990)
yWaste3 = random.randint(0, 580)

#Ewaste Explosion
xExplosionPos = xWastePos
yExplosionPos = yWastePos


#Star
xStarPos = xWastePos
yStarPos = yWastePos


#LOADING ALL IMAGES AND SOUNDS FOR GAME
backgroundImage = pygame.image.load("spaceBackground.jpg")
mainscreenImage = pygame.image.load("galaxyy.jpg")
shipImage = pygame.image.load("spaceship.png")
batteryImage = pygame.image.load("battery.png")
ewasteImage = pygame.image.load("ewaste.png")
explosionImage = pygame.image.load("explosion.png")
starImage = pygame.image.load("star.png")
ewaste2Image = pygame.image.load("ewaste2.png")
ewasteImage = pygame.transform.scale(ewasteImage, (340, 150))
batteryImage = pygame.transform.scale(batteryImage, (30, 40))

#------------------------Functions------------------------
def drawScene(screen, mx, my, button): #Draws game screen with space background
    screen.blit(backgroundImage, (0,0))


def display_main_screen(): #MAIN SCREEN IN PYGAME
    screen.blit(mainscreenImage, (0,0)) 

    screen.blit(pygame.transform.scale(ewaste2Image, (180, 200)), (60, 340))
    screen.blit(pygame.transform.scale(ewaste2Image, (180, 200)), (760, 340))

    title = font.render("E-Waste Exploder", 1, WHITE)
    screen.blit(title, (220,160,400,100)) #Displays Text      

    leaderBtn = pygame.Rect(30, 550, 300,120) #Leaderboard Button
    pygame.draw.rect(screen, BLUE, leaderBtn)
    leaderBtn = font3.render("Leaderboard", 1, WHITE)
    screen.blit(leaderBtn, (50,590,400,100)) #Displays Text    

    instrBtn = pygame.Rect(350, 550, 300,120) #How to play Button
    pygame.draw.rect(screen, BLUE, instrBtn)
    instrBtn = font3.render("How to play", 1, WHITE)
    screen.blit(instrBtn, (380,590,400,100)) #Displays Text

    quitBtn = pygame.Rect(670, 550, 300,120) #Quit Button
    pygame.draw.rect(screen, BLUE, quitBtn)
    quitBtn = font3.render("Quit", 1, WHITE)
    screen.blit(quitBtn, (760,590,400,100)) #Displays Text 

    playBtn = pygame.Rect(280, 410, 450,120) #Play Game Button
    pygame.draw.rect(screen, BLUE, playBtn)
    playBtn = font.render("Play", 1, WHITE)
    screen.blit(playBtn, (420,440,400,100)) #Displays Text   


def gamePage(): #Game page
    drawScene(screen, mx, my, button) #Draws a new screen


#-------------DRAWING ALL OBJECTS FOR GAME-------------

def draw_ship(): 
    global shipImage, direction
    # VR - using a different variable, so that every time through here we remember the direction of the original
    newImage = pygame.transform.rotate(shipImage, direction)
    screen.blit(pygame.transform.scale(newImage, (100, 100)), (x_ship_pos, y_ship_pos)) #SPACESHIP 


def draw_explosivebattery(): 
    if is_battery_on_screen: 
        newImage = pygame.transform.rotate(batteryImage, direction)
        screen.blit(newImage, (x_battery_pos, y_battery_pos)) #BATTERY THAT SHOOTS 


def drawEwaste(): #Piles of e-waste displaying in game 
    global xWastePos, yWastePos
    screen.blit(ewasteImage, (xWastePos, yWastePos)) #EWASTE
    yWastePos += 15 #Speed of e-waste yPos
    if yWastePos > height: #Makes e-waste generate randomly from the top going vertically down
        xWastePos = random.randint(0, 500)
        yWastePos = 0 
    return

if xWastePos < 0 or xWastePos > 1000 or yWastePos < 0 or yWastePos > 700: #remove ewaste if off screen
    drawScene()


def drawStars():
    screen.blit(pygame.transform.scale(starImage, (30, 30)), (xStarPos, yStarPos))


def drawExplosion():
    screen.blit(pygame.transform.scale(explosionImage, (200, 200)), (xExplosionPos, yExplosionPos))
    #pygame.mixer.Sound.play(explosionSound)



#~~~~~~~~~~MOVING OBJECTS AND RESETTING POSITIONS~~~~~~~~~~
def move_ship(): #Moving ship
    global x_ship_pos, x_ship_speed, y_ship_pos, y_ship_speed
    x_ship_pos += x_ship_speed
    if x_ship_pos < -25: #Making sure spaceship doesn't go off screen
        x_ship_pos = -25
    elif x_ship_pos > 925:
        x_ship_pos = 925


    y_ship_pos += y_ship_speed
    if y_ship_pos < 0: #Making sure spaceship doesn't go off screen
        y_ship_pos = 0
    elif y_ship_pos > 600:
        y_ship_pos = 600


def move_battery(): #Moving battery
    global x_battery_pos, y_battery_pos, battery_direction, is_battery_on_screen  #GLOBAL VARIABLES
    if is_battery_on_screen:
        if battery_direction == "UP":
            y_battery_pos -= 70 #How fast the battery moves
        elif battery_direction == "DOWN":
            y_battery_pos += 70
        elif battery_direction == "RIGHT":
            x_battery_pos += 70
        elif battery_direction == "LEFT":
            x_battery_pos -= 70

        if x_battery_pos < 0 or x_battery_pos > 1000 or y_battery_pos < 0 or y_battery_pos > 700: #remove battery if off screen
            is_battery_on_screen = False

#--------CHECKING COLLISIONS--------


def ewasteCollision(battery, ewaste): #If battery hits ewaste
    global yWastePos
    if battery.colliderect(ewaste):
        #addEwaste()
        yWastePos += 1 #DOESN"T WORK
        return True
    False


#--------Defning fonts and buttons--------

#Fonts
font = pygame.font.SysFont("Courier", 100) #Font for titles
font2 = pygame.font.SysFont("Courier", 30) #Small Font 
font3 = pygame.font.SysFont("Courier", 60) #Font for small titles


#Defining Buttons
playBtn = pygame.Rect(280, 410, 450,120) #Play Game Button
instrBtn = pygame.Rect(350, 550, 300,120) #Instructions Button
quitBtn = pygame.Rect(680, 550, 300,120) #Quit Button
leaderBtn = pygame.Rect(30, 550, 300,120) #Leaderboard Button
mainMenuBtn = pygame.Rect(870, 20, 120,30) #mainMenuBtn


running = True
myClock = pygame.time.Clock()
mx = my = 0


display_main_screen() #Calling main screen function


#==========GAME LOOP==========

while running:
    button = 0
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False  
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = event.pos #Gets mouse position
            if in_game == False:
                if playBtn.collidepoint(mouse_pos):
                    gamePage()
                    in_game = True              
                elif quitBtn.collidepoint(mouse_pos):
                    running = False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                direction = 0
                y_ship_speed = -20 #Spaceship speed
                if is_battery_on_screen == False:
                    battery_direction = "UP" #Saves direction as up
            if event.key == pygame.K_DOWN:
                y_ship_speed = 20 #Spaceship speed
                direction = 180
                if is_battery_on_screen == False:
                    battery_direction = "DOWN" #Saves direction as down
            if event.key == pygame.K_LEFT:
                x_ship_speed = -20 #Spaceship speed
                direction = 90
                if is_battery_on_screen == False:
                    battery_direction = "LEFT" #Saves direction as left
            if event.key == pygame.K_RIGHT:
                x_ship_speed = 20 #Spaceship speed
                direction = 270
                if is_battery_on_screen == False:
                    battery_direction = "RIGHT" #Saves direction as right

            if event.key == pygame.K_SPACE:
                if is_battery_on_screen == False: #Shoots battery
                    is_battery_on_screen = True
                    x_battery_pos = x_ship_pos + 32
                    y_battery_pos = y_ship_pos + 26

            if event.key == pygame.K_ESCAPE:
                in_game = False
                display_main_screen() #Goes back to main menu

            if event.key == pygame.K_p:
                gamePage()
                in_game = True

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                y_ship_speed = 0
            elif event.key == pygame.K_DOWN:
                y_ship_speed = 0
            elif event.key == pygame.K_LEFT:
                x_ship_speed = 0
            elif event.key == pygame.K_RIGHT:
                x_ship_speed = 0  

    if in_game:
        #Calling action functions
        move_ship()
        move_battery()

        #Clearing the screen
        drawScene(screen, mx, my, button)

        #drawing objects to the screen
        draw_ship()
        draw_explosivebattery()
        drawEwaste()

        if is_battery_on_screen == True: #Collision with battery and ewaste
            batteryRect = pygame.Rect(x_battery_pos, y_battery_pos, batteryImage.get_width(), batteryImage.get_height()) #Dimensions of battery
            ewasteRect = pygame.Rect(xWastePos + 100, yWastePos, 150, 120) #Dimensions of ewaste
            if ewasteCollision(batteryRect, ewasteRect) == True: #If its true, ewaste explodes and disappears
                is_battery_on_screen = False
                drawExplosion()
                drawStars() #Stars appear for user to collect 

    pygame.display.flip()

    myClock.tick(120)

pygame.quit()```

Upvotes: 2

Views: 364

Answers (1)

furas
furas

Reputation: 142631

I can't test it but you should check collsion before drawing and use result to draw objects or explosion

if in_game:
    #Calling action functions
    move_ship()
    move_battery()

    #Clearing the screen
    drawScene(screen, mx, my, button)

    #drawing objects to the screen
    draw_ship()

    if is_battery_on_screen == True: 
        batteryRect = pygame.Rect(x_battery_pos, y_battery_pos, batteryImage.get_width(), batteryImage.get_height()) #Dimensions of battery
        ewasteRect = pygame.Rect(xWastePos + 100, yWastePos, 150, 120) #Dimensions of ewaste

        if ewasteCollision(batteryRect, ewasteRect) == True: #If its true, ewaste explodes and disappears
            is_battery_on_screen = False
            drawExplosion()
            drawStars() #Stars appear for user to collect
        else:                
            draw_explosivebattery()
            drawEwaste()

BTW:

You should keep size and position in Rect() and change rect.x rect.y instead of recreating again and again Rect().

You could also separate moves, collisions and draws.

Example:

battery_rect = pygame.Rect(x_battery_pos, y_battery_pos, batteryImage.get_width(), batteryImage.get_height()) #Dimensions of battery
ewaste_rect = pygame.Rect(xWastePos, yWastePos, 150, 120) #Dimensions of ewaste
is_battery_on_screen = True
is_ewaste_on_screen = True
is_explosion_on_screen = False
is_stars_on_screen = False

# in mainloop

if in_game:

    # --- moves --- (without collisions and draws)

    move_ship()

    if is_battery_on_screen: 
        move_battery()

    if is_ewaste_on_screen:
        ewaste_rect.x += 100 # move without creating again `Rect()`

    # --- collisions --- (without moves and draws)

    if is_battery_on_screen and is_ewaste_on_screen: 
        if ewaste_collision(battery_rect, ewaste_rect):
            is_battery_on_screen = False
            is_ewaste_on_screen = False
            is_explosion_on_screen = True
            is_stars_on_screen = True

    # --- draws --- (without moves and collisions)

    draw_scene(screen, mx, my, button)
    draw_ship()

    if is_battery_on_screen: 
        draw_explosivebattery()

    if is_ewaste_on_screen:
        draw_ewaste()

    if is_explosion_on_screen:
        draw_explosion()

    if is_stars_on_screen:
        draw_stars()

BTW: using Rect() to keep positions you can easily center text on button and you don't have to calculate it manually.

text = font.render(....)
text_rect = text.get_rect()

text_rect.center = button_rect.center

pygame.draw.rect(screen, BLUE, button_rect)
screen.blit(text, text_rect)

Frankly, at start you could generate surface with button and text and later only blit it without generating button again and again.

Upvotes: 1

Related Questions