import random
import pygame
fps=5
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('Змейка',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-300,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('Змейка 2025')

font=pygame.font.Font('freesansbold.ttf',32)

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():
    return {'x' : random.randint(0, cellWidth-1),
            'y' : random.randint(0, cellHeight-1)}

def drawApple(appleCoord):
    x=appleCoord['x']*cellSize
    y=appleCoord['y']*cellSize
    appleRect=pygame.Rect(x,y,cellSize,cellSize)
    pygame.draw.rect(win,red,appleRect)

def drawSnake(snakeCoords):
    for coord in snakeCoords:
        x=coord['x']*cellSize
        y=coord['y']*cellSize
        snakeSegmentRect=pygame.Rect(x,y,cellSize,cellSize)
        pygame.draw.rect(win,darkGreen,snakeSegmentRect)
        snakeInnerSegmentRect=pygame.Rect(x+4,y+4,
                                          cellSize-8,cellSize-8)
        pygame.draw.rect(win,green,snakeInnerSegmentRect)

def showGameOver():
    global record
    global score
    if score>record:
        f=open('record.txt','w')
        f.write(str(score))
        f.close()


    font2=pygame.font.Font('freesansbold.ttf',150)
    game=font2.render('Game',True,white)
    over=font2.render('Over',True,white)
    gameRect=game.get_rect()
    overRect=over.get_rect()
    gameRect.midtop=(winWidth//2,50)
    overRect.midtop=(winWidth//2,190)
    win.blit(game,gameRect)
    win.blit(over,overRect)
    font3=pygame.font.Font('freesansbold.ttf',26)
    press=font3.render('Press key to play',True,darkGray)
    pressRect = press.get_rect()
    pressRect.topleft = (winWidth - 300, winHeight - 30)
    win.blit(press,pressRect)


    pygame.display.update()
    pygame.time.wait(1000)

    while True:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                stopGame()
            elif event.type==pygame.KEYUP:
                return

def runGame():
    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'
    global score
    global record



    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 (snakeCoords[0]['x']==-1 or
            snakeCoords[0]['x']==cellWidth or
            snakeCoords[0]['y']==-1 or
            snakeCoords[0]['y']==cellHeight):
            return

        for coord in snakeCoords[1:]:
            if (coord['x']==snakeCoords[0]['x'] and
                coord['y']==snakeCoords[0]['y']):
                return

        if 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']}
        elif 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}
        snakeCoords.insert(0,newHead)

        if (snakeCoords[0]['x']==appleCoord['x'] and
            snakeCoords[0]['y']==appleCoord['y']):
            appleCoord=getRandomLocApple()
            score += 1
        else:
            del snakeCoords[-1]

        win.fill(black)

        drawGrid()

        font3 = pygame.font.Font('freesansbold.ttf', 26)
        scoreText = font3.render('Score: ' + str(score), True, white)
        scoreTextRect = scoreText.get_rect()
        scoreTextRect.topleft = (winWidth - 150, 10)
        win.blit(scoreText, scoreTextRect)

        scoreText = font3.render('Record: ' + str(record), True, white)
        scoreTextRect = scoreText.get_rect()
        scoreTextRect.topleft = (10, 10)
        win.blit(scoreText, scoreTextRect)

        fioText = font3.render('Кузьмина Александра',True,darkGray)
        fioTextRect=fioText.get_rect()
        fioTextRect.topleft = (10,winHeight-30)
        win.blit(fioText,fioTextRect)

        drawApple(appleCoord)

        drawSnake(snakeCoords)

        pygame.display.update()
        fpsClock.tick(fps)

while True:
    score=0
    try:
        f=open('record.txt','r')
        record=int(f.readline())
        f.close()
    except:
        record=0

    runGame()

    showGameOver()