Alright so running the code draws the snake, but I can't move it at all. Trying to make it so that the snake doesn't stop when it starts moving. I'm new to programming in general so sorry if I'm dumb, but for the love of god I can't figure out how to make this work, please help. The grid function works just fine, but the move functions don't at all.
Here's the code
# Snake game
import pygame
pygame.init()
pygame.display.set_caption("Snake Game and AI")
WIDTH = 24
HEIGHT = 24
SCREEN = pygame.display.set_mode((500, 500))
RED = (255, 0, 0)
BLACK = (0, 0, 0)
GREEN = (0, 128, 0)
WHITE = (255, 255, 255)
SPEED = 25
x_head = 251
y_head = 251
keys = pygame.key.get_pressed()
direction = None
def grid():
for x in range(25, 500, 25):
pygame.draw.rect(SCREEN, WHITE, (x, 25, 1, 450))
for y in range(25, 500, 25):
pygame.draw.rect(SCREEN, WHITE, (25, y, 450, 1))
def press_key():
global direction
global keys
if keys[pygame.K_RIGHT] and direction != 'left':
direction = 'right'
if keys[pygame.K_LEFT] and direction != 'right':
direction = 'left'
if keys[pygame.K_UP] and direction != 'down':
direction = 'up'
if keys[pygame.K_DOWN] and direction != 'up':
direction = 'down'
def move_snake():
global x_head
global y_head
global SCREEN
global WIDTH
global HEIGHT
while direction == 'right':
x_head += SPEED
while direction == 'left':
x_head -= SPEED
while direction == 'up':
y_head -= SPEED
while direction == 'down':
y_head += SPEED
pygame.draw.rect(SCREEN, GREEN, (x_head, y_head, WIDTH, HEIGHT))
is_running = True
while is_running:
pygame.time.delay(150)
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_running = False
press_key()
SCREEN.fill(BLACK)
grid()
move_snake()
pygame.display.update()
pygame.quit()