title: How to code collision detection in Pygame to collide with an image?
body: <p>I've tried everything I can think of for this PyGame collision detection with the &quot;maze.png&quot; image. (player collides with maze) The player will still just go through the maze. This code is just the maze (image) in the position I want it and a player (rect) which can be moved with the arrow keys. Modify this code in any way to make the player collide with the maze. I need help!
  Thanks.</p>
  <pre><code>    #Imports needed libraries.
  import pygame
  #Initialises PyGame.
  pygame.init()
  #Sets window resolution, icon &amp; title. Also gets required images.
  win = pygame.display.set_mode((512,320))
  pygame.display.set_caption(&quot;Maze Game&quot;)
  window_icon = pygame.image.load(&quot;C:\\Users\\chizl\\Documents\\Images\\project_icon.png&quot;)
  pygame.display.set_icon(window_icon)
  level = pygame.image.load(&quot;C:\\Users\\chizl\\Documents\\Images\\bg-1.png&quot;)
  #The necessary values for the player.
  x = 48
  y = 48
  width = 16
  height = 16
  vel = 16
  keys = pygame.key.get_pressed()
  #While loop for window (put all code here).
  run = True
  while run:
      pygame.time.delay(128)
      for event in pygame.event.get():
          if event.type == pygame.QUIT:
              run = False
      #Key presses.
      keys = pygame.key.get_pressed()
      if keys[pygame.K_LEFT]:
          x -= vel
      if keys[pygame.K_RIGHT]:
          x += vel
      if keys[pygame.K_UP]:
          y -= vel
      if keys[pygame.K_DOWN]:
          y += vel
          
      #Window properties.
      win.fill((255,255,255))
      win.blit(level, (0,0))
      pygame.draw.rect(win, (0,0,0), (x, y, width, height))
      pygame.display.update() 
      
  pygame.quit()
  #CL 2022
  </code></pre>