Ask coding questions

← Back to all posts
Deleting a Block
51LV3RC0D3R (12)

So I am creating a game in pygame
I was wondering how to delete the block in class Level_01.

DudeHexafandra

Comments
hotnewtop
ZhongRietveld (32)

For get what i say, I know what you need to do.
You know that you have 3 lists, so we can remove a list in "level".

        level = [[210, 70, 500, 500],
                 [210, 70, 200, 400],
                 [210, 70,600, 300],
                 ]
        
        
        # Remove's place 2     
        level.pop(1)
        # Go through the array above and add platforms 
        for platform in level:

Just copy and past and you're good to go!
This is for line 177 and 191.

51LV3RC0D3R (12)

@ZhongRietveld The only problem is that I want it so that if I hit the

portal()

then I do

level.pop(1)

but the level.pop(1) is in class Level_01(Level): so i am kinda stuck.

ZhongRietveld (32)

@DudeHexafandra You can put that in class Level_02(Level) to.

51LV3RC0D3R (12)

@ZhongRietveld No, what I am saying is that I want it in

def main()

since that is where the portal is.

[deleted]

@51LV3RC0D3R Sorry for that long to wait. I got a new account (second) so...
But anyway her is the solution to your problem.

import pygame
import sys

Global constants

Colors

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

Screen dimensions

SCREEN_WIDTH = 965
SCREEN_HEIGHT = 430

class Player(pygame.sprite.Sprite):
""" This class represents the bar at the bottom that the player
controls. """

# -- Methods
def __init__(self):
    """ Constructor function """

    # Call the parent's constructor
    super().__init__()

    # Create an image of the block, and fill it with a color.
    # This could also be an image loaded from the disk.
    width = 40
    height = 40
    self.image = pygame.Surface([width, height])
    self.image.fill(RED)

    # Set a referance to the image rect.
    self.rect = self.image.get_rect()

    # Set speed vector of player
    self.change_x = 0
    self.change_y = 0

    # List of sprites we can bump against
    self.level = None

def update(self):
    """ Move the player. """
    # Gravity
    self.calc_grav()

    # Move left/right
    self.rect.x += self.change_x

    # See if we hit anything
    block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
    for block in block_hit_list:
        # If we are moving right,
        # set our right side to the left side of the item we hit
        if self.change_x > 0:
            self.rect.right = block.rect.left
        elif self.change_x < 0:
            # Otherwise if we are moving left, do the opposite.
            self.rect.left = block.rect.right

    # Move up/down
    self.rect.y += self.change_y

    # Check and see if we hit anything
    block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
    for block in block_hit_list:

        # Reset our position based on the top/bottom of the object.
        if self.change_y > 0:
            self.rect.bottom = block.rect.top
        elif self.change_y < 0:
            self.rect.top = block.rect.bottom

        # Stop our vertical movement
        self.change_y = 0

def calc_grav(self):
    """ Calculate effect of gravity. """
    if self.change_y == 0:
        self.change_y = 1
    else:
        self.change_y += .35

    # See if we are on the ground.
    if self.rect.y >= SCREEN_HEIGHT - self.rect.height and self.change_y >= 0:
        self.change_y = 0
        self.rect.y = SCREEN_HEIGHT - self.rect.height

def jump(self):
    """ Called when user hits 'jump' button. """

    # move down a bit and see if there is a platform below us.
    # Move down 2 pixels because it doesn't work well if we only move down
    # 1 when working with a platform moving down.
    self.rect.y += 2
    platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
    self.rect.y -= 2

    # If it is ok to jump, set our speed upwards
    if len(platform_hit_list) > 0 or self.rect.bottom >= SCREEN_HEIGHT:
        self.change_y = -10

# Player-controlled movement:
def go_left(self):
    """ Called when the user hits the left arrow. """
    self.change_x = -6

def go_right(self):
    """ Called when the user hits the right arrow. """
    self.change_x = 6

def stop(self):
    """ Called when the user lets off the keyboard. """
    self.change_x = 0

class Platform(pygame.sprite.Sprite):
""" Platform the user can jump on """

def __init__(self, width, height):
    """ Platform constructor. Assumes constructed with user passing in
        an array of 5 numbers like what's defined at the top of this
        code. """
    super().__init__()

    self.image = pygame.Surface([width, height])
    self.image.fill(GREEN)

    self.rect = self.image.get_rect()

class Level(object):
""" This is a generic super-class used to define a level.
Create a child class for each level with level-specific
info. """

def __init__(self, player):
    """ Constructor. Pass in a handle to player. Needed for when moving platforms
        collide with the player. """
    self.platform_list = pygame.sprite.Group()
    self.enemy_list = pygame.sprite.Group()
    self.player = player
     
    # Background image
    self.background = None

# Update everythign on this level
def update(self):
    """ Update everything in this level."""
    self.platform_list.update()
    self.enemy_list.update()

def draw(self, screen):
    """ Draw everything on this level. """

    # Draw the background
    screen.fill(BLUE)

    # Draw all the sprite lists that we have
    self.platform_list.draw(screen)
    self.enemy_list.draw(screen)

Create platforms for the level

class Level_01(Level):

def __init__(self, player):

    # Call the parent constructor
    Level.__init__(self, player)

    # Array with width, height, x, and y of platform
    level = [[210, 70, 500, 500],
             [210, 70, 200, 400],
             [210, 70, 600, 300],
             ]
    
    
    # Go through the array above and add platforms
    for platform in level:
        block = Platform(platform[0], platform[1])
        block.rect.x = platform[2]
        block.rect.y = platform[3]
        block.player = self.player
        self.platform_list.add(block)

class Level_02(Level):
def init(self, player):

# Call the parent constructor
    Level.__init__(self, player)
    # Array with width, height, x, and y of platform
    level = [[210, 70, 500, 500],
             [210, 70, 300, 400],
             [210, 70, 600, 200],
             ]

    for platform in level:
        block = Platform(platform[0], platform[1])
        block.rect.x = platform[2]
        block.rect.y = platform[3]
        block.player = self.player
        self.platform_list.add(block)

def main():
""" Main Program """
pygame.init()

# Set the height and width of the screen
size = [SCREEN_WIDTH, SCREEN_HEIGHT]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Embercell")
player = Player()
nLevel1 = Level_01(player)
nLevel2 = Level_02(player)
# Create the player
try:

  current_level_no = 0
  if current_level_no == 1:
    pygame.quit()

  level_list = [nLevel1, nLevel2]

  # Create all the levels
  
  level_list.append(level_list[current_level_no])
  # Set the current level
except:
  pygame.quit()


active_sprite_list = pygame.sprite.Group()
player.level = level_list[current_level_no]

player.rect.x = 340
player.rect.y = SCREEN_HEIGHT - player.rect.height
active_sprite_list.add(player)

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# -------- Main Program Loop -----------
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                player.go_left()
            if event.key == pygame.K_RIGHT:
                player.go_right()
            if event.key == pygame.K_UP:
                player.jump()

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT and player.change_x < 0:
                player.stop()
            if event.key == pygame.K_RIGHT and player.change_x > 0:
                player.stop()

    # Update the player.
    active_sprite_list.update()

    # Update items in the level
    level_list[current_level_no].update()

    # If the player gets near the right side, shift the world left (-x)
    if player.rect.right > SCREEN_WIDTH:
        player.rect.right = SCREEN_WIDTH

    # If the player gets near the left side, shift the world right (+x)
    if player.rect.left < 0:
        player.rect.left = 0

    # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
    level_list[current_level_no].draw(screen)
    active_sprite_list.draw(screen)

    # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

    # Limit to 60 frames per second
    clock.tick(30)
    font = pygame.font.SysFont(None, 24)
    img = font.render('hello', True, BLUE)
    screen.blit(img, (20, 20))    
    portal = pygame.draw.rect(screen, BLACK, pygame.Rect(960, 0, 40, 430))
    if player.rect.colliderect(portal):
      current_level_no += 1
      player.rect.x = 50

      
    

    # Go ahead and update the screen with what we've drawn.
      pygame.display.flip()
    pygame.display.flip()  

# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()

if name == "main":
main()

51LV3RC0D3R (12)

@Tercoder I don't get what you changed...

[deleted]

@51LV3RC0D3R What do you mean?

[deleted]

@51LV3RC0D3R The portals are working.

51LV3RC0D3R (12)

@Tercoder Isn't what you wrote exactly what I have in my program, because I don't see what you changed..

[deleted]

@51LV3RC0D3R What I did changed is: I make from the class Level_01 and Level_02 the levels to put into a level array called "level_list". Then i took the current level the get the level you're playing in. That is also the level from the player so you get player.level = level_list[current_level_no]. A few lines of code need this to (level_list[current_level_no]). Then the 'try' and 'except' block. This is to get no errors when the list index of 'level_list' is out of range. The program then stops.

[deleted]

@Tercoder Is this what you mean?

ZhongRietveld (32)

Example

level.pop(1) #This remove's place 2 in the array (we count from 0 in Python)

51LV3RC0D3R (12)

@ZhongRietveld I don't get what you are saying. I tried screen.pop(1) because I couldn't use level as I was in line 291 in the function main(). So when I tried running it, it said that 'pygame.Surface' has no attribute pop.

ZhongRietveld (32)

@DudeHexafandra No, you use the varible name from the array so,

level.pop(1)

ZhongRietveld (32)

@ZhongRietveld Is this what you neat to let is work as you want to?

51LV3RC0D3R (12)

@ZhongRietveld I tried it and I think I get what you are doing, but the problem is that I am writing my

level.pop(1)

in

def main():

and it says that level is undefined.

ZhongRietveld (32)

@DudeHexafandra that is, because its a local var so you have to return it

#return level
#Use the function with the return
new_level=<class_name>.<function_name()
#function name is option, because the init()
#Is always executed

51LV3RC0D3R (12)

@ZhongRietveld So just to make sure I got what you said the

<class_name>

is Level.02 and the

function_name()

is what exactly in this case?
Sorry, i am just a little new to pygame.

ZhongRietveld (32)

@DudeHexafandra A bit what i mean is that you use <funtcion_name> from a class only when the builtin function is not init().

ZhongRietveld (32)

With

level.pop(<The place in your array you want to delete>)