import pygame, random
score=0
record=0
fps=17
winWidth=640
winHeight=480
cellSize=20
cellWidth=winWidth//cellSize
cellHeight=winHeight//cellSize
white=(255,255,255)
black=(0,0,0)
red=(0,0,255)
green=(0,255,0)
darkOrange=(255, 69, 0)
darkGrey=(40,40,40)

def stopGame():
    pygame.quit()

def showStartScreen():
    while True:
        win.fill(black)
        gameName = font.render('I am INTEL', False, darkOrange)
        gameNameRect = gameName.get_rect()
        gameNameRect.center=(winWidth//2,winHeight//2)
        win.blit(gameName,gameNameRect)
        press=font.render('Press a key to play',False,darkGrey)
        pressRect=press.get_rect()
        pressRect.topleft=(winWidth-200,winHeight-30)
        win.blit(press,pressRect)

        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,darkOrange,(x,0),(x,winHeight),)

    for y in range(0,winHeight,cellSize):
        pygame.draw.line(win,green,(0,y), (winWidth,y))

def drawSnake(snakeCoords):
    for coord in snakeCoords:
        x=coord['x']*cellSize
        y=coord['y']*cellSize
        segmentRect=pygame.Rect(x,y,cellSize,cellSize)
        pygame.draw.rect(win,white,segmentRect)
        segment2Rect=pygame.Rect(x+4,y+4,cellSize-8,cellSize-8)
        pygame.draw.rect(win,darkGrey,segment2Rect)

def getRandomLoc():
    return {'x':random.randint(0,cellWidth-1),
            'y':random.randint(0,cellHeight)}
def drawApple(appleCoord):
    x=appleCoord['x']*cellSize
    y=appleCoord['y']*cellSize
    appleRect=pygame.Rect(x,y,cellSize,cellSize)
    startx=random.randint(5,cellWidth-6)
    pygame.draw.rect(win,darkOrange,appleRect)
def drawScore(score ,record):
    scoreText=font.render('Score:' +str(score),True,white)
    scoreRect=scoreText.get_rect()
    scoreRect.topleft=(winWidth-120,10)
    win.blit(scoreText,scoreRect)
    recordText=font.render('your RECORD'+str(record),True,white)
    recordRect=recordText.get_rect()
    recordRect.topleft=(10,10)
    win.blit(recordText,recordRect)
    creatorText=font.render('2024 create by Misha Tarasov',True,white)
    creatorRect=creatorText.get_rect()
    creatorRect.topleft=(10,winHeight-30)
    win.blit(creatorText , creatorRect)


def runGame():
    global score,record
    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}]
    appleCoord=getRandomLoc()
    direct='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_a and direct!='right':
                    direct='left'
                elif event.key==pygame.K_d and direct!='left':
                    direct='right'
                elif event.key==pygame.K_w and direct!='down':
                    direct='up'
                elif event.key==pygame.K_s and direct!='up':
                    direct='down'

        if (snakeCoords[0] ['x']==appleCoord['x'] and snakeCoords[0] ['y']==appleCoord ['y']):
            appleCoord=getRandomLoc()
        else:
            del snakeCoords[-1]

        for coord in snakeCoords[1:]:
            if coord['x']==snakeCoords[0]['x'] and coord['y']==snakeCoords[0]['y']:
                return

        if snakeCoords[0] ['x'] == -1:
            snakeCoords[0] ['x'] = cellWidth - 1
        elif snakeCoords [0] ['x'] == cellWidth:
            snakeCoords [0] ['x'] = 0
        elif snakeCoords[0]['y'] == -1:
            snakeCoords[0]['y'] = cellHeight-1
        elif snakeCoords[0]['y'] == cellHeight:
            snakeCoords[0]['y'] = 0



        if direct=='up':
            new={'x':snakeCoords[0]['x'],'y':snakeCoords[0]['y']-1}
        if direct=='down':
            new={'x':snakeCoords[0]['x'],'y':snakeCoords[0]['y']+1}
        if direct == 'left':
            new = {'x': snakeCoords[0]['x']-1, 'y': snakeCoords[0]['y']}
        if direct == 'right':
            new = {'x': snakeCoords[0]['x']+1, 'y': snakeCoords[0]['y']}
        snakeCoords.insert(0,new)

        win.fill(black)

        drawGrid()
        drawSnake(snakeCoords)
        drawApple(appleCoord)
        score=len(snakeCoords)-3
        drawScore(score, record)



        pygame.display.update()
        fpsClock.tick(fps)


pygame.init()
fpsClock=pygame.time.Clock()
win=pygame.display.set_mode((winWidth,winHeight))
pygame.display.set_caption('Outcore')
font=pygame.font.Font('freesansbold.ttf',18)
showStartScreen()

while True:
    try:
        f=open('recors.txt','r')
        record=int(f.readline())
    except:
        record=0
        f=open('record.txt','w')
        f.write('0')
        f.close()
    runGame()
    print(score,record)
    if score>record:
        f=open('record.txt','w')
        f.write(str(score))
        f.close()
