Reputation: 31
I am making a game similar to the Binding Of Isaac. I want to have rocks around the screen that block the player's movement.
Where the rock layout is made:
" ",
" ",
" ",
" ",
" jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" "
]
rockxcoord = 0
rockycoord = 0
for row in level:
for col in row:
if col == "j":
rock = rocks(rockxcoord, rockycoord)
rockGroup.add(rock)
rockxcoord +=32
rockycoord += 50
rockxcoord = 0
Where the boundaries are set
for rock in rockGroup:
screen.blit(rock.image, [rock.rect.x, rock.rect.y])
rockCollisionList = pygame.sprite.spritecollide(playerOne, rockGroup, False)
for rock in rockCollisionList:
if playerOne.rect.x < rock.rect.x:
playerOne.rect.x = rock.rect.x - 90
if playerOne.rect.x > rock.rect.x:
playerOne.rect.x = rock.rect.x + 80
I have successfully added boundaries on the x axis. However, when doing the same with the y axis it doesn't work properly.
Upvotes: 1
Views: 235
Reputation: 14906
Use PyGame's Sprites. There's a good tutorial on them too. It's a little bit more work initially, but it will save time later. Really, take the time to learn it. It's worth the investment.
Your walls can just be something simple:
class WallSprite( pygame.sprite.Sprite ):
""" A stationay sprite"""
def __init__( self, position, image ):
pygame.sprite.Sprite.__init__( self )
self.image = image
self.rect = self.image.get_rect()
self.rect.topleft = position
def udpate( self ):
# does not move
pass
Create a bunch of walls. Obviously it's more efficient to make a 10 by 1 unit wall as a single sprite, but for the sake of example we will make walls Lego™ style.
# Create 20 randomly-placed walls
wall_image = pygame.image.load("brick_32.png").convert_alpha()
wall_sprites = pygame.sprite.Group() # a group for all the wall sprites
for i in range(20):
# create a wall at a random position
new_wall = WallSprite( ( random.randrange( 0, WINDOW_WIDTH ), random.randrange( 0, WINDOW_HEIGHT ) ), wall_image )
wall_sprites.add( new_wall ) # put into the sprite group
In your main loop, the sprite groups can be used for both painting the sprites, and the group collide function to see if your player has hit any wall.
# Main loop
done = False
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
# handle direction keys ...
# move / update the player sprite
player_sprite.update()
# handle player <-> wall sprite collisions (for *ALL* walls)
if ( len( pygame.sprite.spritecollide( player_sprite, wall_sprites, False ) ) > 0 ):
player_sprite.stop_moving()
# re-paint the window
screen.fill( GREEN )
wall_sprites.draw() # paints the entire sprite group
player_sprite.draw() # paint the player
pygame.display.flip()
pygame.quit()
Upvotes: 3