import random
import pygame
from pygame.locals import *

pygame.init()

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
CELL_SIZE = 20
BACKGROUND_COLOR = (40, 40,40)
SNAKE_COLOR =(255,255,255)
HEAD_COLOR = (0,255,0)
RED_FOOD=(255,0,0)
GREEN_FOOD=(0,255,0)

snake=[
    [200,200],
    [180,200],
    [160,200]
]

current_direction="right"
next_direction="right"
player_score=0
game_speed=2
lest_food_time=0

food_position=[0,0]
food_type=GREEN_FOOD

game_window=pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
game_clock=pygame.time.Clock()


def create_new_food():
    global food_position,food_type,lest_food_time

    while True:

        food_position=[
            random.randrange(0,SCREEN_WIDTH//CELL_SIZE)*CELL_SIZE,
            random.randrange(0,SCREEN_HEIGHT//CELL_SIZE)*CELL_SIZE
        ]
        if food_position not in snake:
            break

    food_type=random.choice([RED_FOOD,GREEN_FOOD])

    if food_type==RED_FOOD:
        lest_food_time=pygame.time.get_ticks()

create_new_food()


def draw_background_grid():
    for y in range(0,SCREEN_HEIGHT,CELL_SIZE):
        pygame.draw.line(game_window,BACKGROUND_COLOR,(0,y),(SCREEN_WIDTH,y))

    for x in range(0,SCREEN_WIDTH,CELL_SIZE):
        pygame.draw.line(game_window,BACKGROUND_COLOR,(x,0),(x,SCREEN_HEIGHT))

def draw_snake_body():

   for index,segment in enumerate(snake):
       color=HEAD_COLOR if index==0 else SNAKE_COLOR
       pygame.draw.rect(game_window,color,
                        (segment[0],segment[1],CELL_SIZE,CELL_SIZE))


def show_game_info():
    info_font=pygame.font.SysFont("Hone",36)

    score_text=info_font.render(f"分数{player_score}",True,SNAKE_COLOR)
    game_window.blit(score_text,(SCREEN_WIDTH-150,10))


    if food_type==RED_FOOD:
        time_passed = pygame.time.get_ticks()-lest_food_time
        remaining=8-time_passed//1000
        time_text=info_font.render(f"分数{max(0,remaining)}秒",True,SNAKE_COLOR)
        game_window.blit(time_text,(SCREEN_WIDTH-150,50))

def update_difficulty():
    global game_speed
    if player_score>20:
        game_speed=40
    elif player_score>10:
        game_speed=30
    elif player_score>5:
        game_speed=20

def handle_collisions(new_head):
    global player_score,is_game_running

    if new_head in snake[1:]:
        is_game_running=False
    if new_head==food_position:
        if food_type==GREEN_FOOD:
            player_score+=1
            snake.insert(0,new_head)
        else:
            player_score=max(0,player_score-1)
            snake.insert(0,new_head)
            for _ in range(2):
                if len(snake)>1:
                    snake.pop()
        create_new_food()

    else:
        snake.insert(0,new_head)
        snake.pop()

is_game_running=True
while is_game_running:
    game_clock.tick(game_speed)
    for event in pygame.event.get():
        if event.type==QUIT:
            is_game_running=False
        elif event.type==KEYDOWN:
            if event.key==K_RIGHT and current_direction!="left":
                next_direction="right"
            elif event.key==K_LEFT and current_direction!="right":
                next_direction="left"
            elif event.key==K_DOWN and current_direction!="up":
                next_direction="down"
            elif event.key==K_UP and current_direction!="down":
                next_direction="up"

    current_direction=next_direction
    head_x,head_y=snake[0]
    direction_moves={
        "right":(CELL_SIZE,0),
        "left":(-CELL_SIZE,0),
        "down": (0,CELL_SIZE),
        "up":(0,-CELL_SIZE)
    }
    dx,dy=direction_moves[current_direction]
    new_head=[
        (head_x+dx)%SCREEN_WIDTH,
        (head_y+dy)%SCREEN_HEIGHT
    ]

    current_time=pygame.time.get_ticks()
    if food_type==RED_FOOD and current_time-lest_food_time>8000:
        create_new_food()

    handle_collisions(new_head)
    update_difficulty()

    game_window.fill((0,0,0))
    draw_background_grid()
    pygame.draw.rect(game_window,food_type,
                     (food_position[0],food_position[1],CELL_SIZE,CELL_SIZE))
    draw_snake_body()
    show_game_info()
    pygame.display.flip()

pygame.quit()