import pygame
import random

score=0
record=0

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('Snake',True,green)
        gameNameRect=gameName.get_rect()
        gameNameRect.center=(winWidth//2,winHeight//2)
        win.blit(gameName,gameNameRect)

        preesKey=font.render('Press key to play',True,darkGray)
        preesKeyRect=preesKey.get_rect()
        preesKeyRect.topleft=(winWidth-250,winHeight-30)
        win.blit(preesKey,preesKeyRect)

        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                stopGame()
            elif event.type==pygame.KEYUP:
                return

        pygame.display.update()
        fpsClock.tick(fps)

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(appleCoord):
    x=appleCoord['x']*cellSize
    y=appleCoord['y']*cellSize
    appleRect=pygame.Rect(x,y,cellSize,cellSize)
    pygame.draw.rect(win,red,appleRect)

def drawSerpent(coords):
    for coord in coords:
        x=coord['x']*cellSize
        y=coord['y']*cellSize
        snakeRect=pygame.Rect(x,y,cellSize,cellSize)
        pygame.draw.rect(win,darkGreen,snakeRect)
        snakeRect2=pygame.Rect(x+4,y+4,cellSize-8,cellSize-8)
        pygame.draw.rect(win,green,snakeRect2)

def showGameOver():
    font=pygame.font.Font('freesansbold.ttf',150)
    game =font.render('Game',True,white)
    gameRect=game.get_rect()
    gameRect.midtop=(winWidth//2,50)
    win.blit(game,gameRect)

    over=font.render('Over',True,white)
    overRect=over.get_rect()
    overRect.midtop=(winWidth//2,200)
    win.blit(over,overRect)

    pygame.time.wait(500)
    font=pygame.font.Font('freesansbold.ttf',24)

    press = font.render('Press a key to play.', True, darkGray)
    pressRect =press.get_rect()
    pressRect.midtop = (winWidth -150, winHeight-30)
    win.blit(press, pressRect)

    pygame.display.update()

    while True:
        for event in pygame.event.get():
            if event.type==pygame.KEYUP:
                return
            elif event.key==pygame.QUIT:
                stopGame()

def runGame():
    global score
    appleCoord=getRandomLocApple()
    startx=random.randint(5,cellWidth-6)
    starty=random.randint(5,cellHeight-6)
    snakeCoord=[{'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_w and direction!='down':
                    direction='up'
                elif event.key==pygame.K_s and direction!='up':
                    direction='down'
                elif event.key==pygame.K_d and direction!='left':
                    direction='right'
                elif event.key==pygame.K_a and direction!='right':
                    direction='left'
                elif event.key==pygame.K_ESCAPE:
                    stopGame()

        if direction=='right':
            newHead={'x':snakeCoord[0]['x']+1,'y':snakeCoord[0]['y']}
        elif direction=='left':
            newHead={'x':snakeCoord[0]['x']-1,'y':snakeCoord[0]['y']}
        elif direction=='up':
            newHead={'x':snakeCoord[0]['x'],'y':snakeCoord[0]['y']-1}
        elif direction=='down':
            newHead={'x':snakeCoord[0]['x'],'y':snakeCoord[0]['y']+1}
        snakeCoord.insert(0,newHead)

        if snakeCoord[0]['x']==appleCoord['x'] and snakeCoord[0]['y']==appleCoord['y']:
            appleCoord=getRandomLocApple()
            score += 1
        else:
            del snakeCoord[-1]

        if snakeCoord[0]['x']==-1 or snakeCoord[0]['x']==cellWidth or snakeCoord[0]['y']==-1 or snakeCoord[0]['y']==cellHeight:
            return

        for coord in snakeCoord[2:]:
            if coord['x']==snakeCoord[0]['x'] and coord['y']==snakeCoord[0]['y']:
                return

        win.fill(black)

        drawGrid()
        drawApple(appleCoord)
        drawSerpent(snakeCoord)

        fontScore=pygame.font.Font('freesansbold.ttf',24)
        scoreText=fontScore.render('Score: '+str(score),True,white)
        scoreTextRect=scoreText.get_rect()
        scoreTextRect.topleft=(winWidth-130,10)
        win.blit(scoreText,scoreTextRect)

        recordText=fontScore.render('Record: '+str(record),True,white)
        recordTextRect=scoreText.get_rect()
        recordTextRect.topleft=(10,10)
        win.blit(recordText,recordTextRect)

        name=fontScore.render('by Музыченко Владимир',True,white)
        nameRect=name.get_rect()
        nameRect.topleft=(10,winHeight-30)
        win.blit(name,nameRect)

        pygame.display.update()
        fpsClock.tick(fps)

pygame.init()


fpsClock=pygame.time.Clock()
win=pygame.display.set_mode((winWidth,winHeight))
pygame.display.set_caption('Snake 2025')
font=pygame.font.Font('freesansbold.ttf',26)

showStartScreen()

while True:
    try:
        f=open('record.txt','r')
        record=int(f.readline())
        f.close()
    except:
        pass
    runGame()
    if score>record:
        f=open('record.txt','w')
        f.write(str(score))
        f.close()
    score = 0
    showGameOver()