fork download
  1. def game_loop():
  2. while True:
  3. game_over = False
  4. game_close = False
  5.  
  6. x = WIDTH / 2
  7. y = HEIGHT / 2
  8.  
  9. x_change = 0
  10. y_change = 0
  11.  
  12. snake_blocks = []
  13. snake_length = 1
  14.  
  15. food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / 20.0) * 20.0
  16. food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / 20.0) * 20.0
  17.  
  18. while not game_over:
  19.  
  20. while game_close:
  21. screen.fill(BLACK)
  22. message("You Lost! Press Q-Quit or C-Play Again", RED)
  23. pygame.display.update()
  24.  
  25. for event in pygame.event.get():
  26. if event.type == pygame.KEYDOWN:
  27. if event.key == pygame.K_q:
  28. pygame.quit()
  29. sys.exit()
  30. if event.key == pygame.K_c:
  31. game_over = True # Exit inner loop to restart
  32.  
  33. for event in pygame.event.get():
  34. if event.type == pygame.QUIT:
  35. pygame.quit()
  36. sys.exit()
  37. if event.type == pygame.KEYDOWN:
  38. if event.key == pygame.K_LEFT:
  39. x_change = -BLOCK_SIZE
  40. y_change = 0
  41. elif event.key == pygame.K_RIGHT:
  42. x_change = BLOCK_SIZE
  43. y_change = 0
  44. elif event.key == pygame.K_UP:
  45. y_change = -BLOCK_SIZE
  46. x_change = 0
  47. elif event.key == pygame.K_DOWN:
  48. y_change = BLOCK_SIZE
  49. x_change = 0
  50.  
  51. x += x_change
  52. y += y_change
  53.  
  54. if x >= WIDTH or x < 0 or y >= HEIGHT or y < 0:
  55. game_close = True
  56.  
  57. screen.fill(BLACK)
  58. pygame.draw.rect(screen, RED, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])
  59.  
  60. snake_head = [x, y]
  61. snake_blocks.append(snake_head)
  62.  
  63. if len(snake_blocks) > snake_length:
  64. del snake_blocks[0]
  65.  
  66. for block in snake_blocks[:-1]:
  67. if block == snake_head:
  68. game_close = True
  69.  
  70. draw_snake(snake_blocks)
  71.  
  72. pygame.display.update()
  73.  
  74. if x == food_x and y == food_y:
  75. food_x = round(random.randrange(0, WIDTH - BLOCK_SIZE) / 20.0) * 20.0
  76. food_y = round(random.randrange(0, HEIGHT - BLOCK_SIZE) / 20.0) * 20.0
  77. snake_length += 1
  78.  
  79. clock.tick(15)
  80.  
Success #stdin #stdout 0.1s 14148KB
stdin
Standard input is empty
stdout
Standard output is empty