Advertisement
Tzuro

lesson 9 project

Jun 29th, 2023
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import pygame
  2. import random
  3. import time
  4. from Direction import Direction
  5. from Snake import Snake
  6. from Apple import Apple
  7.  
  8. # width and height of the display
  9. DISPLAY_WIDTH = 800
  10. DISPLAY_HEIGHT = 608
  11.  
  12. # background creation
  13. background = pygame.Surface((DISPLAY_WIDTH, DISPLAY_HEIGHT))
  14. for i in range(25):
  15. for j in range(19):
  16. image = pygame.image.load("images/background.png")
  17. mask = (random.randrange(0, 20), random.randrange(
  18. 0, 20), random.randrange(0, 20))
  19.  
  20. image.fill(mask, special_flags=pygame.BLEND_ADD)
  21. background.blit(image, (i*32, j*32))
  22.  
  23. # settings
  24. pygame.init()
  25. # display object and game clock
  26. display = pygame.display.set_mode([DISPLAY_WIDTH, DISPLAY_HEIGHT])
  27. clock = pygame.time.Clock()
  28.  
  29. # Snake
  30. snake = Snake()
  31. MOVE_SNAKE = pygame.USEREVENT + 1
  32. event_timer = 200
  33. pygame.time.set_timer(MOVE_SNAKE, event_timer)
  34.  
  35. # apples
  36. apple = Apple()
  37. apples = pygame.sprite.Group()
  38. apples.add(apple)
  39.  
  40. game_on = True
  41. while game_on:
  42. for event in pygame.event.get():
  43. if event.type == pygame.KEYDOWN:
  44. if event.key == pygame.K_ESCAPE:
  45. game_on = False
  46. if event.key == pygame.K_w:
  47. snake.change_direction(Direction.UP)
  48. if event.key == pygame.K_s:
  49. snake.change_direction(Direction.DOWN)
  50. if event.key == pygame.K_a:
  51. snake.change_direction(Direction.LEFT)
  52. if event.key == pygame.K_d:
  53. snake.change_direction(Direction.RIGHT)
  54. if event.key == pygame.K_o:
  55. event_timer += 10
  56. pygame.time.set_timer(MOVE_SNAKE, event_timer)
  57. if event.key == pygame.K_p:
  58. event_timer -= 10
  59. pygame.time.set_timer(MOVE_SNAKE, event_timer)
  60.  
  61. elif event.type == MOVE_SNAKE:
  62. snake.update()
  63. elif event.type == pygame.QUIT:
  64. game_on = False
  65.  
  66. # drawing background
  67. display.blit(background, (0, 0))
  68. # drawing snake's head
  69. display.blit(snake.image, snake.rect)
  70. # drawing apples
  71. for apple in apples:
  72. display.blit(apple.image, apple.rect)
  73.  
  74. pygame.display.flip()
  75. clock.tick(30)
  76.  
  77. time.sleep(3)
  78. pygame.quit()
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement