Skip to content

Instantly share code, notes, and snippets.

@ringodin
Created April 24, 2020 01:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ringodin/5c93877cb3862047df7489c24bd21704 to your computer and use it in GitHub Desktop.
Save ringodin/5c93877cb3862047df7489c24bd21704 to your computer and use it in GitHub Desktop.
This python code allows the snake to grow a tail segment each time it eats food.
from pyglet import app
from pyglet import gl
from pyglet import clock
from pyglet.window import Window
from pyglet.window import key
from pyglet import graphics
from pyglet import image
from pyglet import text
from random import randint
import sys
window = Window(500, 500)
@window.event
def on_draw():
global snk_x, snk_y
if not game_over:
window.clear()
for coords in tail:
draw_square(coords[0], coords[1], snk_size, colour = (255, 0, 255, 0)) #add tail
draw_square(snk_x, snk_y, snk_size) # Draw the snake's head.
draw_square(fd_x, fd_y, snk_size, colour = (0, 255, 0, 0)) #draw food
else:
draw_game_over()
def draw_square(x, y, size, colour = (255, 255, 255, 0)):
img = image.create(size, size, image.SolidColorImagePattern(colour))
img.blit(x, y)
def place_food():
global fd_x, fd_y
fd_x = randint(0, (window.width // snk_size)-1) * snk_size
fd_y = randint(0, (window.height // snk_size)-1) * snk_size
@window.event
def on_key_press(symbol, modifiers):
global snk_dx, snk_dy, app
if not game_over:
if symbol == key.LEFT:
snk_dx = -snk_size
snk_dy = 0
elif symbol == key.RIGHT:
snk_dx = snk_size
snk_dy = 0
elif symbol == key.UP:
snk_dx = 0
snk_dy = snk_size
elif symbol == key.DOWN:
snk_dx = 0
snk_dy = -snk_size
def update(dt):
global snk_x, snk_y, snk_dx, snk_dy, snk_size, app, game_over, window, score
if snk_x + snk_dx < 0 or snk_x + snk_dx > window.width or snk_y + snk_dy < 0 or snk_y + snk_dy > window.height: # Check for collision with edge.
game_over = True
app.exit()
window.close()
return
tail.append((snk_x, snk_y)) #add position of head to tail
snk_x += snk_dx
snk_y += snk_dy
if snk_x == fd_x and snk_y == fd_y:
print('yay!')
place_food()
score += 1
print(f'Your score is {score}.')
#don't remove last tail segment, hence we grow
else:
tail.pop(0) #remove last tail segment
print(tail)
score = 0
snk_size = 20 # Not the length of the snake, but the width and height of a single snake segment.
snk_dx, snk_dy = 0, 0 # The amount by which the snake's x and y coordinates change.
fd_x, fd_y = 0, 0 #defining food variables
snk_x = window.width // snk_size // 2 * snk_size # Start the snake in the middle, ensuring that it doesn't land between cells.
snk_y = window.height // snk_size // 2 * snk_size
place_food()
game_over = False
tail = []
clock.schedule_interval(update, 1/15) # Set how often the update function is called.
app.run() # Start the game.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment