Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.60 KB | None | 0 0
  1. from __future__ import annotations
  2. from typing import Tuple, List
  3. import pygame
  4. import random
  5. import sys
  6.  
  7.  
  8. # screen width & height and block size
  9. bg_width = 500
  10. bg_height = 500
  11. block_size = 10
  12.  
  13. # direction strings
  14. left = "LEFT"
  15. right = "RIGHT"
  16. up = "UP"
  17. down = "DOWN"
  18.  
  19. # colors (RGB)
  20. bg_color = black = (0, 0, 0)
  21. yellow = (255, 255, 0)
  22. green = (0, 128, 0)
  23. red = (255, 0, 0)
  24. blue = (0, 0, 255)
  25.  
  26. # pygame & font initialization
  27. pygame.init()
  28. window = pygame.display.set_mode((bg_width, bg_height))
  29. pygame.display.set_caption("Snake")
  30. font = pygame.font.SysFont('Times New Roman', 20)
  31. text_colour = pygame.Color('White')
  32. fps = pygame.time.Clock()
  33.  
  34.  
  35. class Snake:
  36. """This class represents a snake object. Every snake object consists of a head
  37. and its body.
  38. ===Attributes===
  39. head: snake head
  40. color: snake color
  41. body: snake body
  42. direction: direction of head
  43. size: size of snake (head and body)
  44. """
  45. head: List[int, int]
  46. color: Tuple[int, int, int]
  47. body: List[List[int, int]]
  48. direction: str
  49. size: int
  50.  
  51. def __init__(self, color: Tuple[int, int, int]) -> None:
  52. self.head = [int(10*block_size), int(5*block_size)]
  53. self.color = color
  54. self.body = [self.head, [9*block_size, 5*block_size]]
  55. self.direction = right
  56. self.size = 2
  57.  
  58. def change_dir(self, direc: str) -> None:
  59. if self.direction != left and direc == right:
  60. self.direction = right
  61. elif self.direction != right and direc == left:
  62. self.direction = left
  63. elif self.direction != down and direc == up:
  64. self.direction = up
  65. elif self.direction != up and direc == down:
  66. self.direction = down
  67.  
  68. def move(self) -> None:
  69. if self.direction == right:
  70. self.head[0] += block_size
  71. elif self.direction == left:
  72. self.head[0] -= block_size
  73. elif self.direction == up:
  74. self.head[1] -= block_size
  75. elif self.direction == down:
  76. self.head[1] += block_size
  77. self.body.insert(0, list(self.head))
  78. self.body.pop()
  79. if self.body[0] != self.head:
  80. self.head = self.body[0]
  81.  
  82. def add_to_tail(self) -> None:
  83. new_part = [self.body[-1][0], self.body[-1][1]]
  84. self.body.append(new_part)
  85. self.size += 1
  86.  
  87. def get_body(self) -> List[List[int, int]]:
  88. return self.body
  89.  
  90.  
  91. class Food:
  92. """This class represents a food object. Each food object has an x
  93. and a y value, a color and a state.
  94. ===Attributes===
  95. x: x-coordinate of food object
  96. y: y-coordinate of food object
  97. color: color of food object
  98. state: whether food object is on screen or not
  99. position: x,y-coordinates pair of food object
  100. """
  101. x: int
  102. y: int
  103. color: Tuple[int, int, int]
  104. state: bool
  105. position: Tuple[int, int]
  106.  
  107. def __init__(self, color: Tuple[int, int, int]) -> None:
  108. self.x = random.randint(0, bg_width//block_size - 1)*block_size
  109. self.y = random.randint(0, bg_height//block_size - 1)*block_size
  110. self.color = color
  111. self.state = True
  112. self.position = self.x, self.y
  113.  
  114. def spawn(self) -> Tuple[int, int]:
  115. if self.state:
  116. return self.x, self.y
  117. else:
  118. self.state = True
  119. self.x = random.randint(0, bg_width // block_size-1) * block_size
  120. self.y = random.randint(0, bg_height // block_size-1) * block_size
  121. return self.x, self.y
  122.  
  123. def update(self, state) -> None:
  124. self.state = state
  125.  
  126.  
  127. def collision(snake_: Snake, food_target_x: int, food_target_y: int) -> int:
  128. snake_rect = pygame.Rect(*snake_.head, block_size, block_size)
  129. food_rect = pygame.Rect(food_target_x, food_target_y, block_size,
  130. block_size)
  131. if snake_rect == food_rect:
  132. snake_.add_to_tail()
  133. return 1
  134. return 0
  135.  
  136.  
  137. def wall_collision(s: Snake) -> bool:
  138. if (s.head[0] < 0) or (s.head[0] > bg_width-block_size) or (s.head[1] < 0)
  139. or (s.head[1] > bg_height-block_size):
  140. return True
  141. return False
  142.  
  143.  
  144. def game():
  145.  
  146. # initialize food and snake
  147. food = Food(blue)
  148. snake = Snake(green)
  149.  
  150. # initialize loop logic
  151. running = True
  152. is_over = False
  153.  
  154. # initialize score
  155. score = 0
  156.  
  157. # game loop
  158. while running:
  159.  
  160. # Game over Screen
  161. while is_over:
  162. text_on_screen = font.render("You scored: " + str(score) +
  163. ", Press R to play again or Q to quit",
  164. True, text_colour)
  165. window.blit(text_on_screen, [55, 225])
  166. for event in pygame.event.get():
  167. pressed_key = pygame.key.get_pressed()
  168. if event.type == pygame.QUIT:
  169. pygame.quit()
  170. sys.exit()
  171. if pressed_key[pygame.K_q]:
  172. pygame.quit()
  173. sys.exit()
  174. if pressed_key[pygame.K_r]:
  175. game()
  176. pygame.display.update()
  177.  
  178. # check events
  179. for event in pygame.event.get():
  180. if event.type == pygame.QUIT:
  181. pygame.quit()
  182. sys.exit()
  183. pressed = pygame.key.get_pressed()
  184. if pressed[pygame.K_RIGHT] or pressed[pygame.K_d]:
  185. snake.change_dir(right)
  186. elif pressed[pygame.K_LEFT] or pressed[pygame.K_a]:
  187. snake.change_dir(left)
  188. elif pressed[pygame.K_UP] or pressed[pygame.K_w]:
  189. snake.change_dir(up)
  190. elif pressed[pygame.K_DOWN] or pressed[pygame.K_s]:
  191. snake.change_dir(down)
  192.  
  193. # fill window and draw snake
  194. window.fill(black)
  195. for item in snake.get_body():
  196. pygame.draw.rect(window, snake.color, [item[0], item[1], block_size,
  197. block_size])
  198.  
  199. # move snake
  200. snake.move()
  201.  
  202. # check for collision with wall:
  203. collision_with_wall = wall_collision(snake)
  204. if collision_with_wall:
  205. is_over = True
  206.  
  207. # check if food is still on screen and draw it
  208. food_pos = food.spawn()
  209. collision_ = collision(snake, *food_pos)
  210. if collision_ == 1:
  211. score += 1
  212. food.update(False)
  213. pygame.draw.rect(window, food.color, [food_pos[0], food_pos[1],
  214. block_size, block_size])
  215.  
  216. # renders display
  217. pygame.display.flip()
  218.  
  219. # time delay
  220. pygame.time.delay(60)
  221. fps.tick(30)
  222.  
  223. pygame.quit()
  224. quit()
  225.  
  226.  
  227. game()
  228. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement