from tkinter.font import names

import pygame
import random

score=0
record=0

fps=3
winWidth=640
winHeight=480
cellSize=20
cellWidth=winWidth//cellSize
cellHeight=winHeight//cellSize

white=(255,255,255)
black=(0,0,0)
red=(255,0,0)
green=(0,255,0)
darkGreen=(0,155,0)
darkGray=(40,40,40)

def stopGame():
    pygame.quit()

def showStartScreen():
    while True:
        win.fill(black)
        gameName=font.render('SNAKE',True,green)
        gameNameRect=gameName.get_rect()
        gameNameRect.center=(winWidth//2,winHeight//2)
        win.blit(gameName,gameNameRect)

        pressKey=font.render('Press key to play',True,darkGray)
        pressKeyRect=pressKey.get_rect()
        pressKeyRect.topleft=(winWidth-250,winHeight-30)
        win.blit(pressKey, pressKeyRect)

        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                stopGame()
            elif event.type==pygame.KEYUP:
                return

        pygame.display.update()
        fpsClock.tick(fps)

pygame.init()
fpsClock=pygame.time.Clock()
win=pygame.display.set_mode((winWidth,winHeight))
pygame.display.set_caption('Zmeika 2025 Зе БЕСТ гейм ин жлобин')

font=pygame.font.Font('freesansbold.ttf',26)

showStartScreen()

def drawGrid():
    for x in range(0,winWidth,cellSize):
        pygame.draw.line(win,darkGray,(x,0),
                         (x,winHeight))
    for y in range(0,winHeight,cellSize):
        pygame.draw.line(win,darkGray,(0,y),
                         (winWidth,y))

def getRandomLocApple():
    x= random.randint(0,cellWidth-1)
    y= random.randint(0,cellHeight-1)
    return {'x':x,'y':y}

def drawApple(coord):
    x=coord['x']*cellSize
    y=coord['y']*cellSize
    appleRect=pygame.Rect(x,y,cellSize,cellSize)
    pygame.draw.rect(win,red,appleRect)

def drawSnake(coords):
    for coord in coords:
        x = coord['x'] * cellSize
        y = coord['y'] * cellSize
        segmentRect=pygame.Rect(x,y,cellSize,cellSize)
        pygame.draw.rect(win,darkGreen,segmentRect)
        innerSegmentRect=pygame.Rect(x+4,y+4,cellSize-8,cellSize-8)
        pygame.draw.rect(win,green,innerSegmentRect)

def showGameOver():
    font=pygame.font.Font('freesansbold.ttf',100)
    game=font.render('Game',False,white)
    over = font.render('Over', False, white)
    gameRect=game.get_rect()
    overRect=over.get_rect()
    gameRect.midtop=(winWidth//2,10)
    overRect.midtop=(winWidth//2,125)
    win.blit(game, gameRect)
    win.blit(over, overRect)

    pygame.time.wait(500)
    font=pygame.font.Font('freesansbold.ttf',26)
    press=font.render('Press a key to play.',False,green)
    pressRect=press.get_rect()
    pressRect.topleft=(315,winHeight-50)
    win.blit(press,pressRect)
    pygame.display.update()

    while True:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                stopGame()
            elif event.type==pygame.KEYUP:
                return



def runGame():
    global score
    appleCoord=getRandomLocApple()
    startx=random.randint(5,cellWidth-6)
    starty=random.randint(5,cellHeight-6)
    snakeCoords=[{'x':startx,'y':starty},
                 {'x':startx-1,'y':starty},
                 {'x':startx-2,'y':starty}]
    direction='right'

    while True:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                stopGame()
            elif event.type==pygame.KEYDOWN:
                if event.key==pygame.K_LEFT and direction!='right':
                    direction='left'
                elif event.key==pygame.K_RIGHT and direction!='left':
                    direction='right'
                elif event.key==pygame.K_UP and direction!='down':
                    direction='up'
                elif event.key==pygame.K_DOWN and direction!='up':
                    direction='down'
                elif event.key==pygame.K_ESCAPE:
                    stopGame()

        if direction=='up':
            newHead={'x':snakeCoords[0]['x'],
                     'y':snakeCoords[0]['y']-1}
        elif direction=='down':
            newHead={'x':snakeCoords[0]['x'],
                     'y':snakeCoords[0]['y']+1}
        elif direction=='right':
            newHead={'x':snakeCoords[0]['x']+1,
                     'y':snakeCoords[0]['y']}
        elif direction=='left':
            newHead={'x':snakeCoords[0]['x']-1,
                     'y':snakeCoords[0]['y']}
        snakeCoords.insert(0,newHead)

        if (snakeCoords[0]['x']==appleCoord['x'] and
                snakeCoords[0]['y']==appleCoord['y']):
            appleCoord=getRandomLocApple()
            score += 1
        else:
            del snakeCoords[-1]

        for coord in snakeCoords[2:]:
            if coord['x']==snakeCoords[0]['x'] and coord['y']==snakeCoords[0]['y']:
                return

        if (snakeCoords[0]['x']==-1 or snakeCoords[0]['x']==cellWidth
            or snakeCoords[0]['y']==-1 or snakeCoords[0]['y']==cellHeight):
            return



        win.fill(black)

        drawGrid()

        drawApple(appleCoord)

        drawSnake(snakeCoords)

        font3=pygame.font.Font('freesansbold.ttf',16)

        recordText=font3.render('Record:'+str(record),       True,white)
        recordRect=recordText.get_rect()
        recordRect.topleft=(10,10)
        win.blit(recordText,recordRect)

        scoreText = font3.render('Score: ' + str(score), True, white)
        scoreRect = scoreText.get_rect()
        scoreRect.topleft = (winWidth-100,10)
        win.blit(scoreText, scoreRect)

        nameText = font3.render('BY DENIS KRYT', True, white)
        nameRect = scoreText.get_rect()
        nameRect.topleft = (10,winHeight-30)
        win.blit(nameText, nameRect)



        pygame.display.update()
        fpsClock.tick(fps)

while True:
    try:
        f=open('record.txt','r')
        record=int(f.readline())
        f.close()
    except:
        record=0
    runGame()
    if score>record:
        f=open('record.txt','w')
        f.write(str(score))
        f.close()
    showGameOver()
    score=0