Search code examples
pythonpygame

Constant movement in snake game


I am trying to make a snake game, but I am stuck. I want the snake to move in constant movement.

However, the snake moves only when I pressing the arrow. If I release the arrow the snake stops moving.

Here is my current code:

import sys, pygame
window_size = ( 400, 400 )

white = ( 255, 255, 255 )

class Player():
  image = pygame.image.load( 'snikebodydraw.png')
  rect = image.get_rect()

player = Player()

screen = pygame.display.set_mode( window_size )

done = False

while not done:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      sys.exit()

    if event.type == pygame.KEYDOWN:


      if event.key == pygame.K_LEFT:
        move = (-10, 0 )
        player.rect = player.rect.move(move)
      if event.key == pygame.K_RIGHT:
        move = ( 10, 0 )
        player.rect = player.rect.move(move)
      if event.key == pygame.K_UP:
        move = ( 0,-10 )
        player.rect = player.rect.move(move)
      if event.key == pygame.K_DOWN:
        move = ( 0, 10 )
        player.rect = player.rect.move(move)

  screen.fill( white )
  screen.blit( player.image, player.rect )

  pygame.display.flip()

how can i change this code to make the snake keep moving even without pressing the arrow key?


Solution

  • Instead of only moving when a key is pressed, the movement should happen on all iterations of the while loop and pressing a key should only change the direction of the movement.

    import sys, pygame
    window_size = ( 400, 400 )
    
    white = ( 255, 255, 255 )
    
    class Player():
      image = pygame.image.load( 'snikebodydraw.png')
      rect = image.get_rect()
    
    player = Player()
    
    screen = pygame.display.set_mode( window_size )
    
    move = ( 0, 0 ) # init movement
    
    done = False
    
    while not done:
      for event in pygame.event.get():
        if event.type == pygame.QUIT:
          sys.exit()
    
        if event.type == pygame.KEYDOWN:
        
        
          if event.key == pygame.K_LEFT:
            move = ( -10, 0 )
          if event.key == pygame.K_RIGHT:
            move = ( 10, 0 )
          if event.key == pygame.K_UP:
            move = ( 0, -10 )
          if event.key == pygame.K_DOWN:
            move = ( 0, 10 )
    
      player.rect = player.rect.move( move )
    
      screen.fill( white )
      screen.blit( player.image, player.rect )
    
      pygame.display.flip()