How to implement barriers to stop the player moving through walls

Compute the bounding rectangle of the player and compute the grid indices of the corner points and and center point:

player_rect = pygame.Rect(player.x, player.y, wr-3, hr-3)
xC, yC = int(player_rect.centerx / wr), int(player_rect.centery / hr)
x0, y0 = int(player_rect.left / wr), int(player_rect.top / hr)
x1, y1 = int(player_rect.right / wr), int(player_rect.bottom / hr)

Restrict the movement dependent on the direction and walls. For instance:

if player.left_pressed and player_rect.x < xC*wr+2:
    if grid[xC][y0].walls[3] or grid[xC][y1].walls[3]:
        player.x = xC*wr+2
        player.left_pressed = False

Complete collision test:

while not done:
    # [...]

    player_rect = pygame.Rect(player.x, player.y, wr-3, hr-3)
    xC, yC = int(player_rect.centerx / wr), int(player_rect.centery / hr)
    x0, y0 = int(player_rect.left / wr), int(player_rect.top / hr)
    x1, y1 = int(player_rect.right / wr), int(player_rect.bottom / hr)

    if player.left_pressed and player_rect.x < xC*wr+2:
        if grid[xC][y0].walls[3] or grid[xC][y1].walls[3]:
            player.x = xC*wr+2
            player.left_pressed = False
        if player.y != yC*hr+2 and grid[x0][y0].walls[2]:
            player.x = xC*wr+2
            player.left_pressed = False
    
    if player.right_pressed and player_rect.x > xC*wr+2:
        if grid[xC][y0].walls[1] or grid[xC][y1].walls[1]:
            player.x = xC*wr+2
            player.right_pressed = False
        if player.y != yC*hr+2 and grid[x0+1][y0].walls[2]:
            player.x = xC*wr+2
            player.right_pressed = False

    if player.up_pressed and player_rect.y < yC*hr+2:
        if grid[x0][yC].walls[0] or grid[x1][yC].walls[0]:
            player.y = yC*hr+2
            player.up_pressed = False
        if player.x != xC*wr+2 and grid[x0][y0].walls[3]:
            player.y = yC*hr+2
            player.up_pressed = False

    if player.down_pressed and player_rect.y > yC*hr+2:
        if grid[x0][yC].walls[2] or grid[x1][yC].walls[2]:
            player.y = yC*hr+2
            player.down_pressed = False
        if player.x != xC*wr+2 and grid[x0][y0+1].walls[3]:
            player.y = yC*hr+2
            player.down_pressed = False

See also How do I prevent the player from moving through the walls in a maze?

Leave a Comment