I have been working on a snake game in Python with PyGame. Its the default traditional snake game that everyone knows... I am walking into 1 issue, i can't find a working way to make the body of the snake follow the head. I have tried multiple things and always get the same result.
Can someone help me find a way to make the body follow the head? :)
Each bodypart of the snake consists of a list, [xPos, yPos, direction, nextDirection]
I am now moving the body with this piece of code, but this is not working correctly:
if i == 0:
pass
elif i == 1:
snake[i][3] = snake[0][2]
else:
snake[i][3] = snake[i-1][2]
Full code:
import sys
import random
def drawBackground():
evenOdd = False
global screenW, screenH, screen, block
for y in range(int(screenH/block)):
for x in range(int(screenW/block)):
if evenOdd == False:
color = (170,215,81)
evenOdd = True
else:
color = (162,209,73)
evenOdd = False
pygame.draw.rect(screen, color, (x * block, y * block, block, block))
def moveSnake():
global nextDir, snake
for i in range(len(snake)):
if snake[i][3] == "LEFT" and snake[i][1] % block == 0:
snake[i][2] = "LEFT"
snake[i][3] = ""
if snake[i][3] == "RIGHT" and snake[i][1] % block == 0:
snake[i][2] = "RIGHT"
snake[i][3] = ""
if snake[i][3] == "UP" and snake[i][0] % block == 0:
snake[i][2] = "UP"
snake[i][3] = ""
if snake[i][3] == "DOWN" and snake[i][0] % block == 0:
snake[i][2] = "DOWN"
snake[i][3] = ""
if snake[i][2] == "LEFT":
snake[i][0] -= 2
elif snake[i][2] == "UP":
snake[i][1] -= 2
elif snake[i][2] == "RIGHT":
snake[i][0] += 2
elif snake[i][2] == "DOWN":
snake[i][1] += 2
for i in range(len(snake)):
if i == 0:
pass
elif i == 1:
snake[i][3] = snake[0][2]
else:
snake[i][3] = snake[i-1][2]
pygame.init()
screen = pygame.display.set_mode((600, 600))
clock = pygame.time.Clock()
screenW,screenH = pygame.display.get_surface().get_size()
block = 40
snake = [[200, 160, "DOWN", ""], [200, 120, "DOWN", ""], [200, 80, "DOWN", ""]]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake[0][2] != "RIGHT":
snake[0][3] = "LEFT"
if event.key == pygame.K_UP and snake[0][2] != "DOWN":
snake[0][3] = "UP"
if event.key == pygame.K_RIGHT and snake[0][2] != "LEFT":
snake[0][3] = "RIGHT"
if event.key == pygame.K_DOWN and snake[0][2] != "UP":
snake[0][3] = "DOWN"
moveSnake()
drawBackground()
for i in range(len(snake)):
if i == 0:
pygame.draw.rect(screen, (70,115,232), (snake[i][0], snake[i][1], block, block))
else:
pygame.draw.rect(screen, (200,100,232), (snake[i][0], snake[i][1], block, block))
pygame.display.update()
clock.tick(120)