This model might just be a hidden treasure. It made a perfect snake game the first try.
#2
by
rombodawg
- opened
I used the 5k_m version
Here is the code:
snake.py
import sys
import random
import pygame
from pygame.locals import *
# set up pygame
pygame.init()
mainClock = pygame.time.Clock()
# set up the window
WINDOWWIDTH = 480
WINDOWHEIGHT = 320
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Snake')
# set up the colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
# set up the snake
SNAKECOLOR = GREEN
APPLECOLOR = RED
snakeList = []
snakeLength = 1
applePos = [WINDOWWIDTH/2, WINDOWHEIGHT/2]
direction = 'right'
# set up the apple and snake starting position
for i in range(snakeLength):
x = WINDOWWIDTH/2 - (i * 10)
y = WINDOWHEIGHT/2
snakeList.append([x,y])
# run the game loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# check if the user has pressed a key
key = pygame.key.get_pressed()
if key[K_LEFT]:
direction = 'left'
elif key[K_RIGHT]:
direction = 'right'
elif key[K_UP]:
direction = 'up'
elif key[K_DOWN]:
direction = 'down'
# move the snake in the current direction
if direction == 'left':
head = [snakeList[-1][0]-10, snakeList[-1][1]]
elif direction == 'right':
head = [snakeList[-1][0]+10, snakeList[-1][1]]
elif direction == 'up':
head = [snakeList[-1][0], snakeList[-1][1]-10]
elif direction == 'down':
head = [snakeList[-1][0], snakeList[-1][1]+10]
# check if the snake has hit itself or the edge
if any(head in pos for pos in snakeList[:-1]) or \
not (WINDOWWIDTH > head[0] >= 0 and WINDOWHEIGHT > head[1] >= 0):
pygame.quit()
sys.exit()
# check if the snake has eaten an apple
if head == applePos:
applePos = [random.randint(1, (WINDOWWIDTH-10)/10)*10, random.randint(1, (WINDOWHEIGHT-10)/10)*10]
snakeLength += 1
else:
del snakeList[0]
# add the new head to the front of the list
snakeList.append(head)
# draw the black background onto the surface
windowSurface.fill(BLACK)
# draw the apple onto the surface
pygame.draw.rect(windowSurface, APPLECOLOR, [applePos[0], applePos[1], 10, 10])
# draw the snake onto the surface
for pos in snakeList:
pygame.draw.rect(windowSurface, SNAKECOLOR, [pos[0], pos[1], 10, 10])
# refresh the display
pygame.display.update()
mainClock.tick(40)
Try making snake game in physical logic gates or even pacman