import pygame
import random
pygame. init( )
win_width, win_height = 800 , 600
window = pygame. display. set_mode( ( win_width, win_height) )
pygame. display. set_caption( "Snake Game" )
WHITE = ( 255 , 255 , 255 )
BLACK = ( 0 , 0 , 0 )
GREEN = ( 0 , 255 , 0 )
RED = ( 255 , 0 , 0 )
snake_size = 20
snake_x = win_width // 2
snake_y = win_height // 2
snake_dx = 0
snake_dy = 0
snake_body = [ ]
snake_length = 1
food_x = random. randint( 0 , win_width - snake_size) // snake_size * snake_size
food_y = random. randint( 0 , win_height - snake_size) // snake_size * snake_size
running = True
clock = pygame. time. Clock( ) while running: for event in pygame. event. get( ) : if event. type == pygame. QUIT: running = False if event. type == pygame. KEYDOWN: if event. key == pygame. K_LEFT: snake_dx = - snake_sizesnake_dy = 0 elif event. key == pygame. K_RIGHT: snake_dx = snake_sizesnake_dy = 0 elif event. key == pygame. K_UP: snake_dx = 0 snake_dy = - snake_sizeelif event. key == pygame. K_DOWN: snake_dx = 0 snake_dy = snake_sizesnake_x += snake_dxsnake_y += snake_dyif snake_x < 0 or snake_x >= win_width or snake_y < 0 or snake_y >= win_height: running = False if snake_x == food_x and snake_y == food_y: food_x = random. randint( 0 , win_width - snake_size) // snake_size * snake_sizefood_y = random. randint( 0 , win_height - snake_size) // snake_size * snake_sizesnake_length += 1 snake_body. append( ( snake_x, snake_y) ) if len ( snake_body) > snake_length: del snake_body[ 0 ] if ( snake_x, snake_y) in snake_body[ : - 1 ] : running = False window. fill( BLACK) for body_part in snake_body: pygame. draw. rect( window, GREEN, ( body_part[ 0 ] , body_part[ 1 ] , snake_size, snake_size) ) pygame. draw. rect( window, RED, ( food_x, food_y, snake_size, snake_size) ) pygame. display. update( ) clock. tick( 10 )
pygame. quit( )