import datetime
import math
import sys
import time
import pygame
import random
import os
pi=3.1415926
def baifenbi_grade(len):
    if len==1:
        return 0.00
    elif len==6:
        return 2.58
    elif len==11:
        return 5.64
    elif len==16:
        return 8.98
    else:
        return round(math.atan(len/80)*200/pi,2)
os.environ['SDL_VIDEO_CENTERED']='1'    #游戏能够居中打开
# 初始化游戏
pygame.init()

# 定义游戏窗口尺寸
game_width = 1500
game_height = 800

# 定义游戏窗口
game_screen = pygame.display.set_mode((game_width, game_height))

# 定义游戏标题
pygame.display.set_caption("正版贪吃蛇1.0")

# 定义颜色常量
white = (255, 255, 255)
black = (0, 0, 0)
blue = (66, 66, 255)
blue1 = (99, 99, 255)
red = (255, 66, 66)
black1 = (66,66,66)
red1 = (255,99,99)
# 设置字体和字号
font = pygame.font.SysFont('simHei', 50)

# 定义蛇的长度、速度和方向
cell_size = 50
snake_block = 50
snake_speed = 5
fps=60

ji_imgs=[]     #鸡图像大全
path=r'D:\正版贪吃蛇1.0\image\鸡图大全'
for x in os.listdir(path):
    real_name=path+'\\'+x
    ji_img = pygame.image.load(real_name).convert()     #将目标图像加载到ji_img中，convert()将图像转化成pygame易于处理的形式
    ji_img = pygame.transform.scale(ji_img, (cell_size, cell_size))     #将图像大小压缩至ji_block**2
    ji_imgs.append(ji_img)
# 创建时钟对象
clock = pygame.time.Clock()
egg_loc=r'D:\正版贪吃蛇1.0\image\鸡蛋.jpg'
egg=pygame.image.load(egg_loc).convert()
egg=pygame.transform.scale(egg,(cell_size, cell_size))

chick_loc=r'D:\正版贪吃蛇1.0\image\小鸡.jpg'
chick=pygame.image.load(chick_loc).convert()
chick=pygame.transform.scale(chick,(cell_size, cell_size))
# 定义函数：显示文字
def message(msg,color):
    mesg = font.render(msg, True, color)
    mesg_w,mesg_h=mesg.get_size()
    game_screen.blit(mesg, ((game_width - mesg_w) / 2, (game_height - mesg_h) / 2))

# 定义函数：显示蛇
def draw_snake(snake_block,snake_list,direction):
    for x in snake_list[:-1]:
        pygame.draw.rect(game_screen, red1, [x[0], x[1], snake_block, snake_block])
    pygame.draw.rect(game_screen,red,[snake_list[-1][0], snake_list[-1][1], snake_block, snake_block])
    if direction=='right' or direction=='':
        pygame.draw.rect(game_screen, black, [snake_list[-1][0]+3*snake_block//5, snake_list[-1][1]+snake_block//5, snake_block//5, snake_block//5])
        pygame.draw.rect(game_screen, black, [snake_list[-1][0]+3*snake_block//5, snake_list[-1][1]+3*snake_block//5, snake_block//5, snake_block//5])
    elif direction=='left':
        pygame.draw.rect(game_screen, black,
                         [snake_list[-1][0] + snake_block // 5, snake_list[-1][1] + snake_block // 5,
                          snake_block // 5, snake_block // 5])
        pygame.draw.rect(game_screen, black,
                         [snake_list[-1][0] + snake_block // 5, snake_list[-1][1] + 3 * snake_block // 5,
                          snake_block // 5, snake_block // 5])
    elif direction=='up':
        pygame.draw.rect(game_screen, black,
                         [snake_list[-1][0] + snake_block // 5, snake_list[-1][1] + snake_block // 5,
                          snake_block // 5, snake_block // 5])
        pygame.draw.rect(game_screen, black,
                         [snake_list[-1][0] + 3*snake_block // 5, snake_list[-1][1] + snake_block // 5,
                          snake_block // 5, snake_block // 5])
    elif direction == 'down':
        pygame.draw.rect(game_screen, black,
                         [snake_list[-1][0] + snake_block // 5, snake_list[-1][1] + 3*snake_block // 5,
                          snake_block // 5, snake_block // 5])
        pygame.draw.rect(game_screen, black,
                         [snake_list[-1][0] + 3 * snake_block // 5, snake_list[-1][1] + 3*snake_block // 5,
                          snake_block // 5, snake_block // 5])

        # 运行游戏
def gameLoop():
    #初始化音乐
    pygame.mixer.init()
    pygame.mixer.music.load(r'D:\正版贪吃蛇1.0\music\Masque_Jupiter - 菊次郎的夏天（纯钢琴）.mp3')  # 游戏的背景音乐
    pygame.mixer.music.play(-1)
    t1 = datetime.datetime.now()

    # 定义游戏状态
    grade=0
    game_exit = False
    game_over = False

    # 初始化蛇的位置和长度以及方向
    snake_list = []
    length_of_snake = 1
    x1 = game_width / 2
    y1 = game_height / 2
    x1_change1=0
    y1_change1=0
    x1_change = 0
    y1_change = 0
    direction=''
    # 随机生成食物的位置
    count=0
    num1=random.choice([x for x in range(5,15)])
    num2=random.choice([x for x in range(3,5)])
    foodx = round(random.randrange(0, game_width - snake_block) / snake_block) * snake_block
    foody = round(random.randrange(0, game_height - snake_block) / snake_block) * snake_block
    while (foodx, foody) in snake_list:
        foodx = round(random.randrange(0, game_width - snake_block) / snake_block) * snake_block
        foody = round(random.randrange(0, game_height - snake_block) / snake_block) * snake_block
    ji_chuxin_flag=0
    food=egg
    # 游戏循环
    while not game_exit:
        # 游戏窗口背景色填充
        game_screen.fill(blue)
        # 画线
        for i in range(cell_size, game_width, cell_size):
            pygame.draw.line(game_screen, blue1, (i, 0), (i, game_height - 1))
        for i in range(cell_size, game_height, cell_size):
            pygame.draw.line(game_screen, blue1, (0, i), (game_width - 1, i))
        # 绘制食物
        game_screen.blit(food, (foodx, foody))
        text='得分：{0}'.format(grade)
        message(text,white)
        # 处理按键事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_exit = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and (x1_change!=snake_speed or length_of_snake==1):
                    direction='left'
                    x1_change1=-snake_speed
                    y1_change1=0
                elif event.key == pygame.K_RIGHT and (x1_change!=-snake_speed or length_of_snake==1):
                    direction = 'right'
                    x1_change1 = snake_speed
                    y1_change1 = 0
                elif event.key == pygame.K_UP and (y1_change != snake_speed or length_of_snake==1):
                    direction = 'up'
                    x1_change1 = 0
                    y1_change1 = -snake_speed
                elif event.key == pygame.K_DOWN and (y1_change != -snake_speed or length_of_snake==1):
                    direction = 'down'
                    x1_change1 = 0
                    y1_change1 = snake_speed

                   # 处理蛇头移动
        if x1%cell_size==0 and y1%cell_size==0:
            x1_change=x1_change1
            y1_change=y1_change1
        x1 += x1_change
        y1 += y1_change
            #如果蛇出界就死
        if x1 >= game_width or x1 < 0 or y1 >= game_height or y1 < 0:
            game_over = True

        # 判断是否吃到食物
        if x1 == foodx and y1 == foody:
            count+=1
            if food in ji_imgs:     #如果吃到动画鸡哥就播放鸡叫并且鸡叫后需要将音乐切回，分数增加10000+3egg
                pygame.mixer.music.load(r'D:\正版贪吃蛇1.0\music\鸡_爱给网_aigei_com.mp3')
                pygame.mixer.music.play(1)
                time.sleep(0.15)
                t2 = datetime.datetime.now()
                dt = (t2 - t1).seconds%135
                pygame.mixer.music.load(r'D:\正版贪吃蛇1.0\music\Masque_Jupiter - 菊次郎的夏天（纯钢琴）.mp3')
                pygame.mixer.music.play(-1, dt - 0.15)
                grade=grade+100

            elif food == egg:   #吃到鸡蛋就普通加鸡蛋的分数
                grade=grade+5

            elif food == chick:     #吃到小鸡加两倍鸡蛋的分数
                grade=grade+20

            if count==num2: #每num2个食物出现一只小鸡
                food=chick
            elif count==num1:   #每num1个食物出现一个鸡哥
                food=random.choice(ji_imgs)
                count=0
            else:   #其余食物都为鸡蛋
                food=egg

            #更新食物位置
            foodx = round(random.randrange(0, game_width - snake_block) / snake_block) * snake_block
            foody = round(random.randrange(0, game_height - snake_block) / snake_block) * snake_block
            #蛇的长度增加5
            length_of_snake += 10
            #如果食物的位置刷新在蛇的身上就重新刷新
            while [foodx,foody] in snake_list:
                foodx = round(random.randrange(0, game_width - snake_block) / snake_block) * snake_block
                foody = round(random.randrange(0, game_height - snake_block) / snake_block) * snake_block


        # 更新蛇的长度
        snake_head = []
        snake_head.append(x1)
        snake_head.append(y1)
        snake_list.append(snake_head)
        if len(snake_list) > length_of_snake:
            del snake_list[0]

        #如果吃到自己的身体也死
        for x in snake_list[:-1]:
            if x == snake_head:
                game_over = True

        # 更新蛇的位置
        draw_snake(snake_block, snake_list,direction)

        # 游戏结束处理
        while game_over == True:
            cai_chuxin=pygame.image.load(r'D:\正版贪吃蛇1.0\image\鸡之处刑曲.jpg').convert()
            cai_chuxin=pygame.transform.scale(cai_chuxin, (game_width, game_height))
            game_screen.blit(cai_chuxin, (0, 0))
            message("你的成绩为{0}分,超过了{1}%的IKUN".format(grade,baifenbi_grade(length_of_snake)), black)
            messa="提示:按空格重新开始游戏，按回车退出游戏"
            messaa=font.render(messa,True,black)
            messa_w,messa_h=messaa.get_size()
            game_screen.blit(messaa, ((game_width - messa_w) / 2, game_height/2 + 0.65*messa_h))
            pygame.display.update()
            pygame.mixer.music.stop()
            pygame.mixer.music.load(r'D:\正版贪吃蛇1.0\music\ji2.mp3')
            if ji_chuxin_flag==0:
                ji_chuxin_flag=1
                pygame.mixer.music.play(1)
                time.sleep(4)
                pygame.mixer.music.stop()
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == 13:
                        game_exit = True
                        game_over = False
                    elif event.key == 32:
                        gameLoop()
                if event.type == pygame.QUIT:
                    game_exit = True
                    game_over = False
        # 更新信息
        pygame.display.update()
        # 控制游戏速度
        clock.tick(fps)
    # 退出游戏
    pygame.quit()
    sys.exit(0)
# 运行游戏循环
gameLoop()对这段贪吃蛇的代码加上前端的开始游戏按钮以及难度选择按钮，在游戏结束后添加一个分数排名系统