Collision detection with walls and objects

As @Chrisir has commented, there’s no easy way here.

If you have just a few walls, you might get by with AABB collision –

player_x = 0
player_width = 10
wall_x = 45
wall_width = 30

def draw():
    global player_x
    background(200)
    noStroke()
    fill('#00FF00')
    
    if (player_x+player_width > wall_x and 
        player_x < wall_x+wall_width):
        # fill the wall red if there's a collision
        fill('#FF0000')
    
    # draw the wall in green or red
    rect(wall_x, 0, wall_width, height)
    # draw the player in blue
    fill('#0000FF')
    square(player_x, height/2, player_width)
    player_x += 0.5

Of course, this code doesn’t check y-values, but it’s not difficult to modify the if statement to include those.

preview

However, this approach to collision detection can grow unwieldy very quickly when you’re adding multiple walls, picks-up, etc. You can optimize the code – add some classes, functions, split it into modules, and so on – but @Chrisir’s suggestion is more scalable. You can look into tilemaps for more on the topic. I’ll provide a high-level overview of the concept.

You create a tile-set, like this one from Super Mario Bros, adapted by Michael Hadley.

tileset

You use a list to define your level layout. Some tilemap software can prove handy here.

level = [
  [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0 ],
  [  0,   1,   2,   3,   0,   0,   0,   1,   2,   3,   0 ],
  [  0,   5,   6,   7,   0,   0,   0,   5,   6,   7,   0 ],
  [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0 ],
  [  0,   0,   0,  14,  13,  14,   0,   0,   0,   0,   0 ],
  [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0 ],
  [  0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0 ],
  [  0,   0,  14,  14,  14,  14,  14,   0,   0,   0,  15 ],
  [  0,   0,   0,   0,   0,   0,   0,   0,   0,  15,  15 ],
  [ 35,  36,  37,   0,   0,   0,   0,   0,  15,  15,  15 ],
  [ 39,  39,  39,  39,  39,  39,  39,  39,  39,  39,  39 ]
]

You use that list to render your level. Think: a loop statement to render the tiles using the list values. In the result (depicted below), note how the tiles correspond to the numbers in the list (that correspond to the tile labels above).

result

Now, you can program the collision-detection logic by comparing your player position with the level list. Certain tiles – like tile #14 – are solid, so the player cannot advance to that location.

One of the advantages of tilemaps is that you can generate level layouts quickly!

As @paulgoux has pointed out, defining a few classes will help dramatically optimize your development process.