Dec-11-2017, 06:00 PM
I have been following a class on udemy for pygame and were starting with this snake game. I get no errors but there has to be something I am missing in the code because the snake doesn't move with the controls I made, WASD, or the arrow keys. Hopefully someone can help me figure out why!
import pygame, sys, random, time
pygame.init()
# Play surface
playSurface = pygame.display.set_mode((720, 460))
pygame.display.set_caption('Snake')
# Colors
red = pygame.Color(255, 0, 0) #gameover
green = pygame.Color(0, 255, 0) #snake
black = pygame.Color(0, 0, 0) #score
white = pygame.Color(255, 255, 255) #background
gold = pygame.Color(255, 215, 0) #food
#FPS Controller
fpsController = pygame.time.Clock()
#Important variables
snakePos = [100, 50]
snakeBody = [[100, 50], [90, 50], [80, 50]]
foodPos = [random.randrange(1,72)*10, random.randrange(1,46)*10]
foodSpawn = True
direction = 'RIGHT'
changeTo = direction
#Game Over Function
def gameOver():
myFont = pygame.font.SysFont('monaco', 72)
GOsurf = myFont.render('You Suck', True, red)
GOrect = GOsurf.get_rect()
GOrect.midtop = ((360, 15))
playSurface.blit(GOsurf, GOrect)
pygame.display.update()
time.sleep(5)
pygame.QUIT() #pygame exit
sys.exit() #console exit
#Main Logic
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT or event.key == ord('d'):
changeto = 'RIGHT'
if event.key == pygame.K_LEFT or event.key == ord('a'):
changeto = 'LEFT'
if event.key == pygame.K_UP or event.key == ord('w'):
changeto = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
changeto = 'DOWN'
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.event(QUIT))
# validation of direction
if changeTo == 'RIGHT' and not direction == 'LEFT':
direction = 'RIGHT'
if changeTo == 'LEFT' and not direction == 'RIGHT':
direction == 'LEFT'
if changeTo == 'UP' and not direction == 'DOWN':
direction == 'UP'
if changeTo == 'DOWN' and not direction == 'UP':
direction == 'DOWN'
if direction == 'RIGHT':
snakePos[0] += 10
if direction == 'LEFT':
snakePos[0] -= 10
if direction == 'UP':
snakePos[1] -= 10
if direction == 'DOWN':
snakePos[1] += 10
# Snake body mechanics
snakeBody.insert(0, list(snakePos))
if snakePos[0] == foodPos[0] and snakePos[1] == foodPos[1]:
foodSpawn = False
else:
snakeBody.pop()
# Food spawn
if foodSpawn == False:
foodPos = [random.randrange(1,72)*10, random.randrange(1,46)*10]
foodSpawn = True
playSurface.fill(white)
for pos in snakeBody:
pygame.draw.rect(playSurface, green, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.display.update()
fpsController.tick(25)
