How to use 'snake game code in python' in Python

Every line of 'snake game code in python' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
119def run_game():
120 # this function runs the game
121 snake = Snake()
122 apple = Apple()
123 while True:
124 for event in pygame.event.get():
125 if event.type == pygame.QUIT:
126 pygame.quit()
127 sys.exit()
128 elif event.type == pygame.KEYDOWN:
129 if event.key == pygame.K_ESCAPE:
130 pygame.quit()
131 sys.exit()
132 # don't move in the opposite direction
133 elif event.key == pygame.K_LEFT and snake.dir != 'r':
134 snake.dir = 'l'
135 elif event.key == pygame.K_RIGHT and snake.dir != 'l':
136 snake.dir = 'r'
137 elif event.key == pygame.K_UP and snake.dir != 'd':
138 snake.dir = 'u'
139 elif event.key == pygame.K_DOWN and snake.dir != 'u':
140 snake.dir = 'd'
141
142 if snake.eat(apple):
143 # make a new apple
144 apple = Apple()
145 else:
146 # remove the last segment from the snake (it stayed the same size)
147 del snake.coords[-1]
148
149 snake.move()
150 if snake.hit():
151 # dead - play the hit sound and return the score
152 snake.hit_snd.play()
153 return len(snake.coords) - 3
154
155 # Update screen
156 screen.fill(BGCOLOR)
157 draw_grid()
158 draw_score(len(snake.coords) - 3)
159 snake.draw()
160 apple.draw()
161 pygame.display.flip()
162 clock.tick(FPS)

Related snippets