""" Encoding: UTF-8 """

from math import sqrt
import pygame
from lang_translation import langues
import sys
import time

pygame.init()

pygame.display.set_caption("Jeu De Hex")

logo = pygame.image.load("Icon/Hex_icon.png")
pygame.display.set_icon(logo)

music = pygame.mixer.Sound("Music/Music.ogg")
music.play(256)
sound = pygame.mixer.Sound("Music/button_hover.mp3")

mainClock = pygame.time.Clock()

#-----Restoration of data
cookie = open("info.txt",'r')
all_txt = cookie.readlines()
for i in range(len(all_txt)):
    all_txt[i] = all_txt[i].replace("\n","")
r, g, b, LANG, global_font, volume = all_txt
music.set_volume(int(volume)/100)
#-----Dimensions
#---------------Screen Size
SIZE_X = 1080
SIZE_Y = 720
#----------------BOX
BOX_Y = 600
BOX_X = BOX_Y* sqrt(3)
BOTTOM_BOX=SIZE_Y-25
TOP_BOX = BOTTOM_BOX - BOX_Y
LEFT_BOX = (SIZE_X-BOX_X)/2
RIGHT_BOX = (SIZE_X-BOX_X)/2 + BOX_X
MIDY_BOX = (TOP_BOX + BOTTOM_BOX)/2
#-----------Colors

var_red = var_green = var_blue = False

if int(r) > 235 and int(g) > 235 and int(b) > 235:
    screen_color = (235,235,235)
elif int(r) < 50 and int(g) < 50 and int(b) < 50:
    screen_color = (50, 50, 50)
else:
    screen_color = ( int(r) , int(g) , int(b)) #255 , 224 , 0
print(screen_color)

dark_screen_color = (int(round(float(r)/1.13,0)) , int(round(float(g)/1.13,0)) , int(round(float(b)/1.13,0))) #225, 200, 0

def light_color(x):
    y = int(165.0 + float(90/255)*float(x))
    y = min(y, 255)
    return y

light_effet = (light_color(r), light_color(g), light_color(b)) #252, 244, 164
darker_color = ( max( int(r) - 50 , 0),max( int(g) - 50 , 0),max( int(b) - 50 , 0))
white = (255 , 255 , 255)
black = (0 , 0 , 0)
beige = (230, 215, 188)
gray = (200, 200, 200)
d_gray = (32, 32, 32)
l_gray = (230, 230, 230)

# ----- Screen
screen = pygame.display.set_mode((SIZE_X, SIZE_Y), pygame.RESIZABLE )#, pygame.RESIZABLE
screen.fill(screen_color)
pygame.display.flip()

#---Button
def switch_font(size, bold, italic):
    # --- Roboto
    if LANG in ['fr', 'en', 'gr', 'sw']:
        font =  pygame.font.SysFont(global_font,size, bold, italic)

    # --- Japanese
    elif LANG == 'jp':
        font = pygame.font.Font("Fonts/MPLUSRounded1c-Medium.ttf", size-10)

    # --- Korean
    elif LANG == 'kr':
        font = pygame.font.Font("Fonts/DoHyeon-Regular.ttf", size)
    a_file = open("info.txt", "r")
    list_of_lines = a_file.readlines()
    list_of_lines[4] = str(font)+"\n"

    with open("info.txt", "w") as a_file:
        a_file.writelines(list_of_lines)

    return font

def text(txt,x,y,z,color,bold, italic):
    font = switch_font(z, bold, italic)
    text2 = font.render(langues[txt].get(LANG), True, color)
    screen.blit(text2, (x,y))

def main_button(txt,x,y,color):
    font = switch_font(75,False,False)
    play_text = font.render("> "+langues[txt].get(LANG), True, color)
    rect = pygame.Rect(x, y , SIZE_X/2.5, 80)
    f_rect = pygame.draw.rect(screen, screen_color, rect )
    screen.blit(play_text, (x, y))
    return  f_rect

def exit_sys(event):
    if event.type == pygame.QUIT:
        sys.exit()
'''
def animation(button, text,y ):

    mouse_x , mouse_y = pygame.mouse.get_pos()
    if not button.collidepoint((mouse_x, mouse_y)):
        button = main_button(text,SIZE_X/15,y,black)
        var = True
    try:
        if button.collidepoint((mouse_x, mouse_y)) and var:
            for _ in range(50):
                button = main_button(text,SIZE_X/15+_,y,(int(5.1 * _),int(5.1 * _),int(5.1 * _)))
                pygame.display.flip()
            var = False
    except UnboundLocalError:
        if button.collidepoint((mouse_x, mouse_y)):
            for _ in range(50):
                button = main_button(text,SIZE_X/15+_,y,(int(5.1 * _),int(5.1 * _),int(5.1 * _)))
                pygame.display.flip()
            var = False
'''
def menu():
    screen.fill(screen_color)
    running = True
    click = True
    var_time = 0
    previousClock = 0
    time_loop = 0
    play_button = main_button("play",SIZE_X/15,2*SIZE_Y/5 ,black)
    option_button = main_button("option",SIZE_X/15,3*SIZE_Y/5 - 30,black)
    quit_button = main_button("quit",SIZE_X/15,4*SIZE_Y/5 - 60,black)
    if LANG == 'jp':
        text("hex_game",SIZE_X/20,SIZE_Y/5 - 30, 100, black, False, False)
    else:
        text("hex_game",SIZE_X/20,SIZE_Y/5 - 30, 150, black, False, False)
    text("v",SIZE_X- 75,SIZE_Y - 30, 25, black, False, False)
    rect = pygame.Rect(SIZE_X/15, 2*SIZE_Y/5 , 30, SIZE_Y/2)
    pygame.draw.rect(screen, screen_color, rect )
    while running:

        #-----Play Button
        mouse_x , mouse_y = pygame.mouse.get_pos()

        if not play_button.collidepoint((mouse_x, mouse_y)):
            play_button = main_button("play",SIZE_X/15,2*SIZE_Y/5,black)
            var = True
        if play_button.collidepoint((mouse_x, mouse_y)) and var:
            for _ in range(20):
                play_button = main_button("play",SIZE_X/15+_*2,2*SIZE_Y/5,(int(12.75 * _),int(12.75 * _),int(12.75 * _)))
                pygame.draw.rect(screen, screen_color, rect )
                pygame.display.flip()
            sound.play()
            var = False
        if play_button.collidepoint((mouse_x, mouse_y)) and click:
            game_menu()

        #-------Option Button
        if not option_button.collidepoint((mouse_x, mouse_y)):
            option_button = main_button("option",SIZE_X/15,3*SIZE_Y/5 - 30,black)
            var_opt = True
        if option_button.collidepoint((mouse_x, mouse_y)) and var_opt:
            for _ in range(20):
                option_button = main_button("option",SIZE_X/15+_*2,3*SIZE_Y/5 -30,(int(12.75 * _),int(12.75 * _),int(12.75 * _)))
                pygame.draw.rect(screen, screen_color, rect )
                pygame.display.flip()
            sound.play()

            var_opt = False
        if option_button.collidepoint((mouse_x, mouse_y)) and click:
            langue(0)

        #-------Quit Button
        if not quit_button.collidepoint((mouse_x, mouse_y)):
            quit_button = main_button("quit",SIZE_X/15,4*SIZE_Y/5 - 60,black)
            var_qt = True
        if quit_button.collidepoint((mouse_x, mouse_y)) and var_qt:
            for _ in range(20):
                quit_button = main_button("quit",SIZE_X/15+_*2,4*SIZE_Y/5 - 60,(int(12.75 * _),int(12.75 * _),int(12.75 * _)))
                pygame.draw.rect(screen, screen_color, rect )
                pygame.display.flip()
            sound.play()
            var_qt = False
        if quit_button.collidepoint((mouse_x, mouse_y)) and click:
            sys.exit()
        var_time += pygame.time.get_ticks() - previousClock
        previousClock = pygame.time.get_ticks()
        #print(pygame.time.get_ticks())
        if var_time > 15000:
            var_time = 0
            time_loop += 1
            if time_loop == 4:
                time_loop = 0
            def load_image(x,img_name,img_txt, img_txt2):
                if time_loop == x:
                    #For text bg
                    bg_rect = pygame.Rect(SIZE_X/2, 4*SIZE_Y/5 , SIZE_X/2, 90)
                    pygame.draw.rect(screen, screen_color, bg_rect )
                    # For Image bf
                    SIZE_IMG = 400
                    bg_rect_img = pygame.Rect(4*SIZE_X/5 - 200,4*SIZE_Y/5 - 400,SIZE_IMG,SIZE_IMG)
                    #Image
                    pygame.draw.rect(screen, screen_color, bg_rect_img )
                    image = pygame.image.load("Icon/"+img_name+".png")
                    image = pygame.transform.scale(image, (SIZE_IMG, SIZE_IMG))
                    screen.blit(image, [4*SIZE_X/5 - 200,4*SIZE_Y/5 - 400])
                    #Text to describe image
                    font = switch_font(30, False, False)
                    text_img = font.render(langues[img_txt].get(LANG), True, black)
                    text_rect = text_img.get_rect(center=(4*SIZE_X/5,4*SIZE_Y/5 + 30))
                    text_img2 = font.render(langues[img_txt2].get(LANG), True, black)
                    text_rect2 = text_img2.get_rect(center=(4*SIZE_X/5,4*SIZE_Y/5 + 60))
                    screen.blit(text_img, text_rect)
                    screen.blit(text_img2, text_rect2)
            load_image(0,"github","github","github2")
            load_image(1,"paint","custom_color","custom_color2")
            load_image(2,"logo_menu","mode","mode2")
            load_image(3,"flags","flags"," ")

        click = False
        for event in pygame.event.get():
            exit_sys(event)
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                click = True
        pygame.draw.rect(screen, screen_color, rect )
        pygame.display.flip()

def play(x, img, ico, txt,des,des2):

    #---Rect
    play_rect = pygame.Rect(x,SIZE_Y/3,SIZE_X/5,SIZE_Y/2)
    header_rect = pygame.Rect(x,SIZE_Y/3,SIZE_X/5,SIZE_Y/15)
    text_rect = pygame.Rect(x,SIZE_Y/3 + 0.3 *SIZE_Y,SIZE_X/5,3*SIZE_Y/15)
    pygame.draw.rect(screen, d_gray, header_rect)
    pygame.draw.rect(screen, gray, text_rect)

    #---Image
    image = pygame.image.load("Icon/"+img+".png")
    image = pygame.transform.scale(image, (int(SIZE_X/5), int(SIZE_X/5)))
    screen.blit(image, [x,SIZE_Y/3 + SIZE_Y/15])

    #---icon
    icon = pygame.image.load("Icon/"+ico+".png")
    icon = pygame.transform.scale(icon, (30, 30))
    rect_icon = icon.get_rect(center=(x + SIZE_X/10,SIZE_Y/3 + 0.3 *SIZE_Y+60))
    screen.blit(icon, rect_icon)

    #---Title
    font = switch_font(47, False, False)
    title_header = font.render(langues[txt].get(LANG), True, white)
    header_text = title_header.get_rect(center = ( x + SIZE_X/10 , SIZE_Y/3 + SIZE_Y/30))
    screen.blit(title_header, header_text)

    #---Description
    if LANG == 'gr':
        font_des = switch_font(15, False, False)
    else:
        font_des = switch_font(20, False, False)
    des = font_des.render(langues[des].get(LANG), True, black)
    des_text = des.get_rect(center = ( x + SIZE_X/10 , SIZE_Y/3 + SIZE_Y/2.4))
    screen.blit(des, des_text)

    des2 = font_des.render(langues[des2].get(LANG), True, black)
    des_text2 = des2.get_rect(center = ( x + SIZE_X/10 , SIZE_Y/3 + SIZE_Y/2.25))
    screen.blit(des2, des_text2)

    return play_rect

def play_hover(button,x,y,z, img, ico, txt,des,des2,click,function,para):
    if not button.collidepoint((x,y)):
        pygame.draw.rect(screen, screen_color, pygame.Rect(z - 5 ,SIZE_Y/3 - 5 ,SIZE_X/5 +10 ,SIZE_Y/2 + 10))
    elif button.collidepoint((x,y)) and click:
        if para =="":
            function()
        else:
            function(para)
    elif button.collidepoint((x,y)):
        pygame.draw.rect(screen, white, pygame.Rect(z - 5 ,SIZE_Y/3 - 5 ,SIZE_X/5 +10 ,SIZE_Y/2 + 10))
    play(z,img,ico,txt,des,des2)

bool_hover = False
def back_button(mx,my, click):
    global bool_hover
    x=100
    arrow = [ (x,75),
    (x+20,30),
    (x+40,30),
    (x+20,75),
    (x+40,120),
    (x+20,120)
    ]
    anti_arrow = [ (0,28),
    (x+18,28),
    (x-2,75),
    (x+18,122),
    (0,122)
    ]
    anti_anti_arrow = [ (x+42,30),
    (x+22,75),
    (x+42,120),
    (300,120),
    (300,30)
    ]

    s = pygame.Surface((40,90))  # the size of your rect
    s.set_alpha(0)                # alpha level
    s.fill((255,255,255))           # this fills the entire surface
    screen.blit(s, (100,30))
    if not screen.blit(s, (100,30)).collidepoint((mx,my)):
        _extracted_from_back_button_30(arrow, anti_arrow)
        pygame.draw.polygon(screen, dark_screen_color, anti_anti_arrow)
        bool_hover = False
    elif screen.blit(s, (100,30)).collidepoint((mx,my)) and not bool_hover:
        for _ in range(15):
            pygame.draw.polygon(screen, dark_screen_color, arrow)
            pygame.draw.polygon(screen, dark_screen_color, arrow,4)
            x -= 4
            text_rectt = pygame.Rect(x+20,40,-3.5 * (x-100),70)
            pygame.draw.rect(screen, light_effet, text_rectt)
            if LANG in {'jp','kr'}:
                back_font = switch_font(50, False, False)
            else:
                back_font = switch_font(75, False, False)
            text_back = back_font.render(langues["back"].get(LANG), True, black)
            screen.blit(text_back, (70, 53))
            arrow = [ (x,75), (x+20,30),(x+40,30),(x+20,75),(x+40,120),(x+20,120)]
            anti_arrow = [ (0,28),(x+18,28),(x-2,75),(x+18,122),(0,122)]
            _extracted_from_back_button_30(arrow, anti_arrow)
            pygame.display.flip()
        bool_hover = True
    elif screen.blit(s, (100,30)).collidepoint((mx,my)) and click:
        menu()

    return arrow

def _extracted_from_back_button_30(arrow, anti_arrow):
    pygame.draw.polygon(screen, white, arrow)
    pygame.draw.polygon(screen, black, arrow,4)
    pygame.draw.polygon(screen, dark_screen_color, anti_arrow)

def game_menu():

    screen.fill(screen_color)

    #Header
    Header = pygame.Rect(0,0,SIZE_X, 150)
    pygame.draw.rect(screen, dark_screen_color, Header)

    #-----Title
    font = switch_font(100, False, False)

    title = font.render(langues["play"].get(LANG), True, white)
    title_border = font.render(langues["play"].get(LANG), True, black )

    rect_title = title.get_rect(center=(SIZE_X/2,75))
    rect_title_bl = title.get_rect(center=(SIZE_X/2-2,73))
    rect_title_br = title.get_rect(center=(SIZE_X/2+2,73))
    rect_title_tl = title.get_rect(center=(SIZE_X/2-2,77))
    rect_title_tr = title.get_rect(center=(SIZE_X/2+2,77))
    screen.blit(title_border, rect_title_bl)
    screen.blit(title_border, rect_title_br)
    screen.blit(title_border, rect_title_tr)
    screen.blit(title_border, rect_title_tl)
    screen.blit(title, rect_title)

    local_button = play(SIZE_X/25,"local","house","local","des_local","des_local2")
    online_button = play(SIZE_X/5 + (SIZE_X/25)*2,"online","WWW","online","des_online","des_online2")
    ia_button = play(2*(SIZE_X/5)+ (SIZE_X/25)*3,"IA","ai","Computer","des_ia","des_ia2")
    _button = play(3*(SIZE_X/5)+ (SIZE_X/25)*4,"?","?2","?"," ", " ")

    #-------

    click = False
    pygame.display.flip()
    while 1:
        mouse_x , mouse_y = pygame.mouse.get_pos()
        back_button(mouse_x,mouse_y,click)
        play_hover(local_button,mouse_x,mouse_y,SIZE_X/25, "local","house","local","des_local","des_local2",click,choosing_lenght,"")
        play_hover(online_button,mouse_x,mouse_y,SIZE_X/5 + (SIZE_X/25)*2,"online","WWW","online","des_online","des_online2",click,menu,"")
        play_hover(ia_button,mouse_x,mouse_y,2*(SIZE_X/5)+ (SIZE_X/25)*3,"IA","ai","Computer","des_ia","des_ia2",click,menu,"")
        play_hover(_button,mouse_x,mouse_y,3*(SIZE_X/5)+ (SIZE_X/25)*4,"?","?2","?"," ", " ",click,menu,"")

        click = False
        for event in pygame.event.get():
            exit_sys(event)
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                click = True
        pygame.display.flip()

def flag_icon(flag,color,nb,txt,x,y,click,page):
    global LANG
    flag = pygame.image.load(f"Flags/{flag}.png")
    flag.convert()
    #---Rescale
    HEIGHT_FLAG = 33
    WIDTH_FLAG = 50
    flag = pygame.transform.scale(flag, (WIDTH_FLAG, HEIGHT_FLAG))
    margin = 50
    # --- Main
    flag_rect = pygame.Rect(margin,300+nb*80,SIZE_X - 2*margin, 60)
    pygame.draw.rect(screen, l_gray, flag_rect, border_radius= 5)
    # --- Left-border
    flag_rect_lborder = pygame.Rect(margin,300+nb*80,10, 60)
    flag_rect_lborder2 = pygame.Rect(margin+5,300+nb*80,10, 60)
    pygame.draw.rect(screen, color, flag_rect_lborder, border_radius= 5)
    pygame.draw.rect(screen, color, flag_rect_lborder2)
    screen.blit(flag, [margin + 20, 310+nb*80])
    # --- txt
    if LANG in {'jp', 'kr'}:
        flag_font =  switch_font(45, False, False)
    else:
        flag_font =  switch_font(60, False, False)
    flag_txt = flag_font.render(langues[txt].get(LANG), True, black)
    screen.blit(flag_txt,(margin + WIDTH_FLAG + 20,310+nb*80))

    if flag_rect.collidepoint((x,y)) and click:
        LANG = txt
        a_file = open("info.txt", "r")
        list_of_lines = a_file.readlines()
        list_of_lines[3] = str(txt)+"\n"

        with open("info.txt", "w") as a_file:
            a_file.writelines(list_of_lines)

        langue(page)

def underHeaderButton(x,y,nb,txt,click):
    if LANG =='gr':
        under_font =  switch_font(45, False, False)
    else:
        under_font =  switch_font(60, False, False)
    under_rect = pygame.Rect(nb * SIZE_X/3,150,SIZE_X/3,100 )
    under_txt = under_font.render(langues[txt].get(LANG), True, black)
    under_center = under_txt.get_rect(center=( (2*nb+1) * SIZE_X / 6,200))
    if pygame.draw.rect(screen, screen_color,under_rect).collidepoint((x,y)) and click:
        if txt=='languages':
            langue(0)
        elif txt == 'background-color':
            background_color()
        else:
            sound_menu()
    if pygame.draw.rect(screen, screen_color,under_rect).collidepoint((x,y)):
        pygame.draw.rect(screen, darker_color,under_rect)
    screen.blit(under_txt, under_center)

def triangle_back(x,y,click):
    arrow = [(100,30), (100, 120) , (33,75)]
    arrow_rect = pygame.draw.polygon(screen,white,arrow)
    if arrow_rect.collidepoint((x,y)) and click:
        menu()

def langue(page):
    #Header
    screen.fill(light_effet)
    Header = pygame.Rect(0,0,SIZE_X, 150)
    pygame.draw.rect(screen, dark_screen_color, Header)
    underHeader = pygame.Rect(0,150,SIZE_X, 100)
    pygame.draw.rect(screen, screen_color, underHeader)
    #-----Title
    font = switch_font(110, False, False)
    #---LAnguage

    title = font.render(langues["option"].get(LANG), True, white)
    rect_title = title.get_rect(center=(SIZE_X/2,75))
    screen.blit(title, rect_title)
    click = False

    # --- Switch Page

    arrow = font.render(">", True, black)
    rect_arrow = arrow.get_rect(center=(SIZE_X - 25, 490))
    screen.blit(arrow, rect_arrow)

    while 1:

        mouse_x, mouse_y = pygame.mouse.get_pos()

        triangle_back(mouse_x,mouse_y,click)
        underHeaderButton(mouse_x,mouse_y,0,"languages",click)
        underHeaderButton(mouse_x,mouse_y,1,"background-color",click)
        underHeaderButton(mouse_x,mouse_y,2,"music",click)

        if rect_arrow.collidepoint((mouse_x,mouse_y)) and click:
            next_page = page + 1
            if next_page > 1:
                next_page = 0
            langue(next_page)

        if page == 0:
            flag_icon('fr',(0, 85, 164),0,'fr',mouse_x,mouse_y,click,page)
            flag_icon('us',(178, 34, 52),1,'en',mouse_x,mouse_y,click,page)
            flag_icon('jp',(188, 0, 45),2,'jp',mouse_x,mouse_y,click,page)
            flag_icon('kr',(0,0,0),3,'kr',mouse_x,mouse_y,click,page)
            flag_icon('gr',(13, 94, 175),4,'gr',mouse_x,mouse_y,click,page)
        else:
            flag_icon('sw',(0, 106, 168),0,'sw',mouse_x,mouse_y,click,page)
        click = False
        for event in pygame.event.get():
            exit_sys(event)
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                click = True
        pygame.display.flip()

def slider(x,y,nb,color,realcolor):
    global var_red, var_green, var_blue
    change_volume_frame = pygame.Rect(95, SIZE_Y/2 -55+ nb * SIZE_Y/5, SIZE_X - 190, 110 )
    pygame.draw.rect(screen, black, change_volume_frame)
    change_volume_background = pygame.Rect(100, SIZE_Y/2 -50 + nb * SIZE_Y/5 , SIZE_X - 200, 100 )
    pygame.draw.rect(screen, gray, change_volume_background)
    change_volume_basic = pygame.Rect(100, SIZE_Y/2 -50 + nb * SIZE_Y/5, (SIZE_X-100)*int(realcolor)/255-100, 100 )
    if color == 'r':
        pygame.draw.rect(screen, (int(realcolor),0,0), change_volume_basic)
        varf = var_red
    elif color == 'g':
        pygame.draw.rect(screen, (0,int(realcolor),0), change_volume_basic)
        varf = var_green
    else:
        pygame.draw.rect(screen, (0,0,int(realcolor)), change_volume_basic)
        varf = var_blue
    if change_volume_background.collidepoint((x,y)) and varf:
        degre = _extracted_from_slider_18(x, nb, color, change_volume_background)
    if not change_volume_background.collidepoint((x,y)):
        if color == 'r':
            var_red = False
        elif color == 'g':
            var_green = False
        else:
            var_blue = False
    try:
        if degre is None:
            degre = realcolor
    except UnboundLocalError:
        degre = realcolor
    return degre

def _extracted_from_slider_18(x, nb, color, change_volume_background):
    result = int(round((((x -100 )/( SIZE_X -100)) * 100) * (10/8.97), 0))*2.55
    result = min(result, 255)
    result = max(result, 0)
    change_volume = pygame.Rect(100, SIZE_Y/2 -50 + nb * SIZE_Y/5, x-100, 100 )
    a_file = open("info.txt", "r")
    list_of_lines = a_file.readlines()
    if color == 'r':
        color2 = result, 0, 0
        list_of_lines[0] = str(int(result)) + "\n"

    elif color == 'g':
        color2 = 0, result, 0
        list_of_lines[1] = str(int(result)) + "\n"
    else:
        color2 = 0, 0, result
        list_of_lines[2] = str(int(result)) + "\n"

    with open("info.txt", "w") as a_file:
        a_file.writelines(list_of_lines)
    pygame.draw.rect(screen, gray, change_volume_background)
    pygame.draw.rect(screen, color2, change_volume)
    return result

def background_color():
    global var_red, var_green, var_blue
    global r, g, b , screen_color, light_effet, dark_screen_color, darker_color
    Header = pygame.Rect(0,0,SIZE_X, 150)
    underHeader = pygame.Rect(0,150,SIZE_X, 100)
    #-----Title
    font = switch_font(110, False, False)
    #---LAnguage

    title = font.render(langues["option"].get(LANG), True, white)
    rect_title = title.get_rect(center=(SIZE_X/2,75))
    click = False
    while 1:
        screen.fill(light_effet)
        pygame.draw.rect(screen, dark_screen_color, Header)
        pygame.draw.rect(screen, screen_color, underHeader)
        screen.blit(title, rect_title)
        mouse_x, mouse_y = pygame.mouse.get_pos()#54654865424654868
        r = slider(mouse_x,mouse_y,0,'r',r)
        g = slider(mouse_x,mouse_y,1,'g',g)
        b = slider(mouse_x,mouse_y,2,'b',b)

        triangle_back(mouse_x,mouse_y,click)
        underHeaderButton(mouse_x,mouse_y,0,"languages",click)
        underHeaderButton(mouse_x,mouse_y,1,"background-color",click)
        underHeaderButton(mouse_x,mouse_y,2,"music",click)

        # ---- CHanging COLORS

        if int(r) > 235 and int(g) > 235 and int(b) > 235:
            screen_color = (235,235,235)
        elif int(r) < 50 and int(g) < 50 and int(b) < 50:
            screen_color = (50, 50, 50)
        else:
            screen_color = ( int(r) , int(g) , int(b)) #255 , 224 , 0

        dark_screen_color = (int(round(float(r)/1.13,0)) , int(round(float(g)/1.13,0)) , int(round(float(b)/1.13,0))) #225, 200, 0

        light_effet = (light_color(r), light_color(g), light_color(b)) #252, 244, 164
        darker_color = ( max( int(r) - 50 , 0),max( int(g) - 50 , 0),max( int(b) - 50 , 0))

        # -----------

        if click:
            var_red = not var_red
            var_green = not var_green
            var_blue = not var_blue

        click = False
        for event in pygame.event.get():
            exit_sys(event)
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                click = True
        pygame.display.flip()

def sound_menu():

    global volume

    Header = pygame.Rect(0,0,SIZE_X, 150)
    underHeader = pygame.Rect(0,150,SIZE_X, 100)
    #-----Title
    font = switch_font(110, False, False)
    #---LAnguage

    title = font.render(langues["option"].get(LANG), True, white)
    rect_title = title.get_rect(center=(SIZE_X/2,75))

    screen.fill(light_effet)
    pygame.draw.rect(screen, dark_screen_color, Header)
    pygame.draw.rect(screen, screen_color, underHeader)
    screen.blit(title, rect_title)

    back_font = switch_font(50, False, True)
    vol_text = back_font.render( str(volume) + "%", True, black)
    vol_rect = vol_text.get_rect(center=(SIZE_X/2,SIZE_Y/1.75 +100))
    screen.blit(vol_text, vol_rect)

    sound_font = switch_font(70, False, False)
    sound_text = sound_font.render(langues["vol_music"].get(LANG), True, black)
    sound_rect = sound_text.get_rect(center=(SIZE_X/2, SIZE_Y/1.75 -100))

    screen.blit(sound_text, sound_rect)

    change_volume_background = pygame.Rect(100, SIZE_Y/1.75 -50, SIZE_X - 200, 100 )
    change_volume_frame = pygame.Rect(95, SIZE_Y/1.75 -55, SIZE_X - 190, 110 )

    pygame.draw.rect(screen, black, change_volume_frame)
    pygame.draw.rect(screen, screen_color, change_volume_background)

    click = False
    click_slider = False
    while 1:

        mouse_x, mouse_y = pygame.mouse.get_pos()

        triangle_back(mouse_x,mouse_y,click)

        if change_volume_background.collidepoint((mouse_x, mouse_y)) and click_slider:
            volume = round((((mouse_x -100 )/( SIZE_X -100)) * 100) * (10/8.97), 1)
            vol_text = back_font.render( str(volume) + "%", True, black)
            vol_rect = vol_text.get_rect(center=(SIZE_X/2,SIZE_Y/1.75 +100))
            vol_rect2 = pygame.Rect(100,SIZE_Y/1.75 + 55,SIZE_X - 190, 110)
            change_volume = pygame.Rect(100, SIZE_Y/1.75 -50, mouse_x-100, 100 )
            pygame.draw.rect(screen, gray, change_volume_background)
            pygame.draw.rect(screen, screen_color, change_volume)
            pygame.draw.rect(screen, light_effet, vol_rect2)
            screen.blit(vol_text, vol_rect)
            music.set_volume(volume/100)
            a_file = open("info.txt", "r")
            list_of_lines = a_file.readlines()
            list_of_lines[5] = str(int(volume)) + "\n"

            with open("info.txt", "w") as a_file:
                a_file.writelines(list_of_lines)

        if not change_volume_background.collidepoint((mouse_x, mouse_y)):
            click_slider = False

        underHeaderButton(mouse_x,mouse_y,0,"languages",click)
        underHeaderButton(mouse_x,mouse_y,1,"background-color",click)
        underHeaderButton(mouse_x,mouse_y,2,"music",click)

        click = False
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                click_slider = True
                click = True
        pygame.display.flip()

def choosing_lenght():
    """ The Menu to change the lenght of the tray """

    screen.fill(screen_color)
    title_font = switch_font(75, False, False)

    #TITLE
    title = title_font.render(langues["local"].get(LANG), True, (0 , 0 ,0))
    title_rect =title.get_rect(center=(SIZE_X/2, 50))
    screen.blit(title,title_rect)

    K=0

    #Back Button
    button_return = pygame.Rect(10, 10 , 200, 75)
    click_button = pygame.draw.rect(screen, screen_color, button_return)
    back_font = switch_font(50, False, True)
    back_text = back_font.render(" << "+langues["back"].get(LANG), True, black)

    back_center = back_text.get_rect(center=(105, 43))
    pygame.draw.rect(screen, black, button_return, 5)
    screen.blit(back_text, back_center)

    change_lenght_background = pygame.Rect(100, SIZE_Y/2 -50, SIZE_X - 200, 100 )
    change_lenght_frame = pygame.Rect(95, SIZE_Y/2 -55, SIZE_X - 190, 110 )

    pygame.draw.rect(screen, black, change_lenght_frame)
    pygame.draw.rect(screen, gray, change_lenght_background)

    _extracted_from_choosing_lenght_29(70, "tray_lenght", 100)
    # ctc <=> Click to change
    ctc_font = switch_font(20, False, False)
    ctc_text = ctc_font.render(langues["clic_to_change"].get(LANG), True, black)
    ctc_rect = ctc_text.get_rect(bottomright=(SIZE_X - 150, SIZE_Y/2 - 60))
    screen.blit(ctc_text, ctc_rect)

    arrow_file = pygame.image.load("Icon/arrow.png")
    arrow = pygame.transform.scale(arrow_file, (100, 100))
    #---Showing Images
    screen.blit(arrow, [SIZE_X - 150, SIZE_Y/2 - 100])

    #-------Let's GO Button

    WIDTH_BUTTON2 = 300
    HEIGHT_BUTTON2 = 100
    MARGIN_TOP2 = -200 # MARGIN_TOP > HEIGHT_BUTTON

    letsgo_button = pygame.Rect((SIZE_X - WIDTH_BUTTON2)/2, (SIZE_Y - HEIGHT_BUTTON2)/2 - MARGIN_TOP2, WIDTH_BUTTON2, HEIGHT_BUTTON2)
    letsgo_button_2 = pygame.Rect((SIZE_X - WIDTH_BUTTON2)/2, (SIZE_Y - HEIGHT_BUTTON2)/2 - MARGIN_TOP2, WIDTH_BUTTON2 , HEIGHT_BUTTON2/2)
    letsgo_button_4 = pygame.Rect((SIZE_X - WIDTH_BUTTON2)/2 + 50, (SIZE_Y - HEIGHT_BUTTON2)/2 - MARGIN_TOP2, WIDTH_BUTTON2-100 , HEIGHT_BUTTON2/4)

    pygame.draw.rect(screen, dark_screen_color, letsgo_button, border_radius= 5)
    pygame.draw.rect(screen, screen_color, letsgo_button_2, border_radius= 5)
    pygame.draw.rect(screen, light_effet, letsgo_button_4, border_radius= 5)
    pygame.draw.rect(screen, black, letsgo_button, 5 ,border_radius= 5)
    pygame.display.flip()

    _extracted_from_choosing_lenght_29(50, "letsgo", MARGIN_TOP2)
    running = True
    click = False
    while running:
        mouse_x , mouse_y = pygame.mouse.get_pos()

        if click_button.collidepoint((mouse_x, mouse_y)) and click:
            main()

        if change_lenght_background.collidepoint((mouse_x, mouse_y)) and click:
            lenght_plate = int(round((((mouse_x -100 )/( SIZE_X -100)) * 45) * (10/8.97)+5, 0))
            vol_text = back_font.render( str(lenght_plate) + "x" + str(lenght_plate), True, black)
            vol_rect = vol_text.get_rect(center=(SIZE_X/2,SIZE_Y/2 +100))
            change_volume = pygame.Rect(100, SIZE_Y/2 -50, mouse_x-100, 100 )
            pygame.draw.rect(screen, gray, change_lenght_background)
            pygame.draw.rect(screen, white, change_volume)
            pygame.draw.rect(screen, screen_color, vol_rect)
            screen.blit(vol_text, vol_rect)

        if not change_lenght_background.collidepoint((mouse_x, mouse_y)):
            click = False

        if K==8:
            lenght_plate = 100
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                click = True
            if event.type == pygame.MOUSEBUTTONDOWN and letsgo_button.collidepoint((mouse_x, mouse_y)):
                try:
                    game(lenght_plate)
                except UnboundLocalError:
                    game(11)
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and K in {0, 1}:
                    K+=1
                elif event.key == pygame.K_DOWN and K in {2, 3}:
                    K+=1
                elif event.key == pygame.K_LEFT and K in {4, 6}:
                    K+=1
                elif event.key == pygame.K_RIGHT and K in {5, 7}:
                    K+=1
                else:
                    K=0

        pygame.display.flip()

def _extracted_from_choosing_lenght_29(arg0, arg1, arg2):
    lenght_font = switch_font(arg0, False, False)
    lenght_text = lenght_font.render(langues[arg1].get(LANG), True, black)
    lenght_rect = lenght_text.get_rect(center=(SIZE_X/2, SIZE_Y/2 - arg2))
    screen.blit(lenght_text, lenght_rect)

def game(x):

    """ The Game """

    POSITION_FOUND2 = False
    screen.fill(screen_color)
    title_font = switch_font(75, False, False)
    title = title_font.render(langues["local"].get(LANG), True, (0 , 0 ,0))
    title_rect =title.get_rect(center=(SIZE_X/2, 50))
    screen.blit(title,title_rect)

    #Back Button
    button_return = pygame.Rect(10, 10 , 200, 75)
    click_button = pygame.draw.rect(screen, screen_color, button_return)
    back_font = switch_font(50, False, True)
    back_text = back_font.render(" << "+langues["back"].get(LANG), True, black)

    back_center = back_text.get_rect(center=(105, 43))

    pygame.draw.rect(screen, black, button_return, 5)
    screen.blit(back_text, back_center)

    #-----Plateau
    #---------------Fond
    box  = [(LEFT_BOX, TOP_BOX),(RIGHT_BOX,TOP_BOX),(RIGHT_BOX,BOTTOM_BOX),(LEFT_BOX, BOTTOM_BOX)]
    bordures = [(SIZE_X/2, TOP_BOX),(RIGHT_BOX,MIDY_BOX),(SIZE_X/2,BOTTOM_BOX),(LEFT_BOX, MIDY_BOX)]
    phase_blanche  = [(SIZE_X/2, TOP_BOX),(SIZE_X/2,BOTTOM_BOX),(RIGHT_BOX,MIDY_BOX),(LEFT_BOX, MIDY_BOX)]

    pygame.draw.polygon(screen, screen_color, box)
    pygame.draw.polygon(screen, black, bordures)
    pygame.draw.polygon(screen, white, phase_blanche)
    #---------------Hexagones
    lenght_plate = x
    border_plate_size = sqrt((BOTTOM_BOX-MIDY_BOX)**2+(RIGHT_BOX-BOX_X/2)**2)
    hex_border = ((border_plate_size)/2)/lenght_plate
    marge = 72.5
    Hexa_color = []
    #print(f"BotBox = {BOTTOM_BOX} / Mid Box = {MIDY_BOX} / border plate size = {border_plate_size}")
    for i in range(lenght_plate):
        for j in range(lenght_plate):
            hexagone = [(LEFT_BOX + marge + hex_border/2 + j*(3/2)*hex_border +i*(3/2)*hex_border , MIDY_BOX + sqrt(3)*hex_border/2 - (sqrt(3)*j/2)*hex_border + (sqrt(3)*i/2)*hex_border),
            (LEFT_BOX + marge + j*(3/2)*hex_border +i*(3/2)*hex_border,MIDY_BOX - (sqrt(3)*j/2)*hex_border+ (sqrt(3)*i/2)*hex_border),
            (LEFT_BOX + marge + hex_border/2 + j*(3/2)*hex_border+i*(3/2)*hex_border, MIDY_BOX - sqrt(3)*hex_border/2 - (sqrt(3)*j/2)*hex_border+ (sqrt(3)*i/2)*hex_border),
            (LEFT_BOX + marge + (3 * hex_border)/2 + j*(3/2)*hex_border+i*(3/2)*hex_border, MIDY_BOX - sqrt(3)*hex_border/2 - (sqrt(3)*j/2)*hex_border+ (sqrt(3)*i/2)*hex_border),
            (LEFT_BOX + marge + 2 * hex_border + j*(3/2)*hex_border+i*(3/2)*hex_border,MIDY_BOX - (sqrt(3)*j/2)*hex_border+ (sqrt(3)*i/2)*hex_border),
            (LEFT_BOX + marge + (3 * hex_border)/2+ j*(3/2)*hex_border+i*(3/2)*hex_border, MIDY_BOX + sqrt(3)*hex_border/2 - (sqrt(3)*j/2)*hex_border+ (sqrt(3)*i/2)*hex_border)]
            Hexa_color+=[beige]
            bounding_rect = pygame.draw.polygon(screen, Hexa_color[(lenght_plate*i)+j], hexagone)
            pygame.draw.polygon(screen, black, hexagone, round(50/lenght_plate))

    pygame.display.flip()
    running = True
    TURN = 'white'
    once_variable = False
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONUP and once_variable and click_button.collidepoint(pygame.mouse.get_pos()):
                game_menu()
            elif event.type == pygame.MOUSEBUTTONUP and once_variable:
                click = True
                FOUND = False
                for i in range(lenght_plate):
                    for j in range(lenght_plate):
                        hexagone = [(LEFT_BOX + marge + hex_border/2 + j*(3/2)*hex_border +i*(3/2)*hex_border , MIDY_BOX + sqrt(3)*hex_border/2 - (sqrt(3)*j/2)*hex_border + (sqrt(3)*i/2)*hex_border),
                        (LEFT_BOX + marge + j*(3/2)*hex_border +i*(3/2)*hex_border,MIDY_BOX - (sqrt(3)*j/2)*hex_border+ (sqrt(3)*i/2)*hex_border),
                        (LEFT_BOX + marge + hex_border/2 + j*(3/2)*hex_border+i*(3/2)*hex_border, MIDY_BOX - sqrt(3)*hex_border/2 - (sqrt(3)*j/2)*hex_border+ (sqrt(3)*i/2)*hex_border),
                        (LEFT_BOX + marge + (3 * hex_border)/2 + j*(3/2)*hex_border+i*(3/2)*hex_border, MIDY_BOX - sqrt(3)*hex_border/2 - (sqrt(3)*j/2)*hex_border+ (sqrt(3)*i/2)*hex_border),
                        (LEFT_BOX + marge + 2 * hex_border + j*(3/2)*hex_border+i*(3/2)*hex_border,MIDY_BOX - (sqrt(3)*j/2)*hex_border+ (sqrt(3)*i/2)*hex_border),
                        (LEFT_BOX + marge + (3 * hex_border)/2+ j*(3/2)*hex_border+i*(3/2)*hex_border, MIDY_BOX + sqrt(3)*hex_border/2 - (sqrt(3)*j/2)*hex_border+ (sqrt(3)*i/2)*hex_border)]
                        bounding_rect = pygame.draw.polygon(screen, Hexa_color[(lenght_plate*i)+j], hexagone)
                        if x < 64:
                            pygame.draw.polygon(screen, d_gray, hexagone, round(50/lenght_plate))
                        else:
                            pass
                        if bounding_rect.collidepoint(pygame.mouse.get_pos()) and not FOUND:
                            if Hexa_color[(lenght_plate * i) + j] != beige:
                                continue
                            if TURN == 'white':
                                Hexa_color[(lenght_plate*i)+j]=white
                                pygame.draw.polygon(screen, white , hexagone)
                                TURN = "black"
                            else:
                                Hexa_color[(lenght_plate*i)+j]=black
                                pygame.draw.polygon(screen, black , hexagone)
                                TURN = "white"
                            pygame.draw.polygon(screen, d_gray, hexagone, round(50/lenght_plate))
                            pygame.display.flip()
                            FOUND = True
                pygame.display.flip()
            else:
                once_variable = True
                continue

            once_variable = True
        #========GAME

        turn_font = switch_font(50, False, False)
        white_text = turn_font.render(langues["white"].get(LANG), True, black)
        black_text = turn_font.render(langues["black"].get(LANG), True, black)
        screen.blit(white_text,[10, 100])
        black_rect = black_text.get_rect(topright=(SIZE_X-10,100))
        screen.blit(black_text, black_rect)

        if TURN == "white":
            arrow_left = turn_font.render("<", True, black)
            arrow_right = turn_font.render(">", True, screen_color)
        elif TURN == "black":
            arrow_left = turn_font.render("<", True, screen_color)
            arrow_right = turn_font.render(">", True, black)
        screen.blit(arrow_left,[120, 100])
        if LANG in {'jp', 'gr'}:
            screen.blit(arrow_right,[SIZE_X-200, 100])
        else:
            screen.blit(arrow_right,[SIZE_X-127, 100])
        pygame.display.flip()
        Z = 1
        WIN = True
        WHITE_WON = False
        for i in range(lenght_plate):
            if Z==0:
                WIN=False
            else:
                Z = 0
            for j in range(lenght_plate):
                if Hexa_color[(lenght_plate*i)+j]==white:
                    Z = 1
                else:
                    continue
        if Z == 0:
            WIN = False
        elif Z == 1 and WIN:
            solution = []
            next_solution = []
            for j in range(lenght_plate):
                if Hexa_color[j]==white:
                    solution.append(j)
                else:
                    continue
            passed = []
            solutionLoop = []
            CanWin = True
            SOL_AND_PASSE = False
            POSITION_FOUND2 = False
            def solw(x):
                if Hexa_color[VALUE_SOLUTION+x]==white:
                    next_solution.append(VALUE_SOLUTION  + x)

            while CanWin and not WHITE_WON:
                if next_solution != []:
                    solution = next_solution
                for sol in solution:
                    for passe in passed:
                        if sol == passe:
                            SOL_AND_PASSE = True
                        else:
                            x=0
                    if not SOL_AND_PASSE:
                        solutionLoop.append(sol)
                    else:
                        x=0
                    SOL_AND_PASSE = False
                solution = []
                next_solution = []
                solution = solutionLoop
                solutionLoop = []
                #print(f"WHITE \ \n Solution = {solution} \n \n Passed = {passed} \n \n \n")
                if solution == []:
                    CanWin = False
                else:
                    for k in solution:
                        VALUE_SOLUTION = k
                        POSITION_FOUND2 = False
                        if VALUE_SOLUTION >= lenght_plate ** 2 - lenght_plate:
                            WHITE_WON = True
                        elif not WHITE_WON:
                            #print(VALUE_SOLUTION)
                            solw(lenght_plate)
                            for x in range(lenght_plate):
                                if VALUE_SOLUTION >= lenght_plate and VALUE_SOLUTION == x * lenght_plate - 1: #Black Border-Right
                                    solw(-lenght_plate)
                                    solw(-1)
                                    solw(-lenght_plate-1)
                                    POSITION_FOUND2 = True
                                elif VALUE_SOLUTION >= lenght_plate and VALUE_SOLUTION == x * lenght_plate: #Black Border-Left
                                    solw(-lenght_plate)
                                    solw(-lenght_plate+1)
                                    solw(1)
                                    POSITION_FOUND2 = True
                            if VALUE_SOLUTION == lenght_plate - 1: #White Border and Black Border-Right
                                solw(-1)
                                solw(lenght_plate -1)
                                POSITION_FOUND2 = True

                            elif VALUE_SOLUTION == "0": #White Border and Black Border-Left
                                solw(1)
                                POSITION_FOUND2 = True
                            elif VALUE_SOLUTION < lenght_plate:#White Border
                                if Hexa_color[VALUE_SOLUTION-1]==white:
                                    next_solution.append(VALUE_SOLUTION  - 1)
                                if Hexa_color[VALUE_SOLUTION+1]==white:
                                    next_solution.append(VALUE_SOLUTION + 1 )
                                if Hexa_color[VALUE_SOLUTION+lenght_plate-1]==white:
                                    next_solution.append(VALUE_SOLUTION  + lenght_plate - 1)
                                POSITION_FOUND2 = True

                            elif not POSITION_FOUND2:
                                if Hexa_color[VALUE_SOLUTION-lenght_plate]==white:
                                    next_solution.append(VALUE_SOLUTION  -lenght_plate)
                                if Hexa_color[VALUE_SOLUTION-lenght_plate+1]==white:
                                    next_solution.append(VALUE_SOLUTION  - lenght_plate + 1)
                                if Hexa_color[VALUE_SOLUTION-1]==white:
                                    next_solution.append(VALUE_SOLUTION  - 1)
                                if Hexa_color[VALUE_SOLUTION+1]==white:
                                    next_solution.append(VALUE_SOLUTION + 1 )
                                if Hexa_color[VALUE_SOLUTION+lenght_plate-1]==white:
                                    next_solution.append(VALUE_SOLUTION  + lenght_plate - 1)
                            passed.append(VALUE_SOLUTION)
                            #print("next solution of",k,":",next_solution)

        # BLACK
        if not WHITE_WON:
            Z=1
            WIN = True
            BLACK_WON = False
            for i in range(lenght_plate):
                if Z==0:
                    WIN=False
                else:
                    Z = 0
                for j in range(lenght_plate):
                    if Hexa_color[(lenght_plate*j)+i]==black:
                        Z = 1
                    else:
                        continue
            if Z == 0:
                WIN = False
            elif Z == 1 and WIN:
                solution = []
                next_solution = []
                for j in range(lenght_plate):
                    if Hexa_color[j*lenght_plate]==black:
                        solution.append(j*lenght_plate)
                    else:
                        continue
                passed = []
                solutionLoop = []
                CanWin = True
                SOL_AND_PASSE = False
                POSITION_FOUND = False
                def solb(x):
                    global POSITION_FOUND
                    if Hexa_color[VALUE_SOLUTION+x]==black:
                        next_solution.append(VALUE_SOLUTION  + x)
                        POSITION_FOUND = True
                while CanWin and not BLACK_WON:
                    if next_solution != []:
                        solution = next_solution
                    for sol in solution:
                        for passe in passed:
                            if sol == passe:
                                SOL_AND_PASSE = True
                            else:
                                x=0
                        if not SOL_AND_PASSE:
                            solutionLoop.append(sol)
                        else:
                            x=0
                        SOL_AND_PASSE = False
                    solution = []
                    solution = solutionLoop
                    solutionLoop = []
                    #print(f"BLACK/ \nSolution = {solution} \n \nPassed = {passed} \n \n \n")
                    if solution == []:
                        CanWin = False
                    else:
                        for k in solution:
                            VALUE_SOLUTION = k
                            POSITION_FOUND = False
                            for x in range(lenght_plate):
                                if VALUE_SOLUTION== x * (lenght_plate) - 1 :
                                    BLACK_WON = True

                            if not BLACK_WON:
                                if Hexa_color[VALUE_SOLUTION+1]==black:
                                    next_solution.append(VALUE_SOLUTION +1)
                                for x in range(lenght_plate):
                                    if VALUE_SOLUTION == x*lenght_plate and VALUE_SOLUTION!=0 and VALUE_SOLUTION != lenght_plate**2 - lenght_plate : #Black Border
                                        solb(lenght_plate)
                                        solb(-lenght_plate+1)
                                        solb(-lenght_plate)
                                        POSITION_FOUND =True

                                if VALUE_SOLUTION == lenght_plate**2 - lenght_plate: #Black Border and white Border-Bottom
                                    solb(-lenght_plate+1)
                                    solb(-lenght_plate)
                                elif VALUE_SOLUTION == 0: #Black Border and white Border-Top
                                    solb(lenght_plate)
                                elif VALUE_SOLUTION > lenght_plate**2 - lenght_plate: #White Border-Bottom
                                    solb(-1)
                                    solb(-lenght_plate +1)
                                    solb(-lenght_plate)
                                elif VALUE_SOLUTION <= (lenght_plate-1) : #WHite Border-Top
                                    solb(lenght_plate)
                                    solb(lenght_plate-1)
                                    solb(-1)

                                elif not POSITION_FOUND:
                                    if Hexa_color[VALUE_SOLUTION-lenght_plate]==black:
                                        next_solution.append(VALUE_SOLUTION - lenght_plate)
                                    if Hexa_color[VALUE_SOLUTION-lenght_plate+1]==black:
                                        next_solution.append(VALUE_SOLUTION - lenght_plate+1)
                                    if Hexa_color[VALUE_SOLUTION-1]==black:
                                        next_solution.append(VALUE_SOLUTION - 1)
                                    if Hexa_color[VALUE_SOLUTION+lenght_plate-1]==black:
                                        next_solution.append(VALUE_SOLUTION + lenght_plate-1)
                                    if Hexa_color[VALUE_SOLUTION+lenght_plate]==black:
                                        next_solution.append(VALUE_SOLUTION + lenght_plate )
                                passed.append(VALUE_SOLUTION)

        else:
            X=0
        X=0
        title_font = switch_font(50, False, False)
        win_rect = pygame.Rect(325, 110, SIZE_X - 650, 75)
        if WHITE_WON:
            winmessage = title_font.render(langues["white_won"].get(LANG), True, (0 , 0 ,0))
            pygame.draw.rect(screen,white,win_rect)
        elif BLACK_WON:
            winmessage = title_font.render(langues["black_won"].get(LANG), True, (255 , 255 ,255))
            pygame.draw.rect(screen,black,win_rect)
        else:
            continue
        l = 50
        restart = [(SIZE_X - 100, SIZE_Y-10),
        (SIZE_X - 100 - l*(sqrt(3)/2), SIZE_Y-10-l/2 ),
        (SIZE_X - 100 - l*(sqrt(3)/2), SIZE_Y-10-(3*l)/2 ),
        (SIZE_X - 100, SIZE_Y - 20 - (sqrt(3)*l)),
        (SIZE_X - 100 + l*(sqrt(3)/2), SIZE_Y-10-(3*l)/2 ),
        (SIZE_X - 100 + l*(sqrt(3)/2), SIZE_Y-10-l/2 )
         ]

         #---------ARRORW
        res_polygon = pygame.draw.polygon(screen, dark_screen_color,restart)
        pygame.draw.polygon(screen, black,restart, 5)
        pygame.draw.line(screen, black,(SIZE_X - 100, SIZE_Y-30),(SIZE_X - 100 - l*(sqrt(3)/2)+20, SIZE_Y-10-l/2 -10),5)
        pygame.draw.line(screen, black,(SIZE_X - 100 - l*(sqrt(3)/2)+20, SIZE_Y-10-l/2 -10),(SIZE_X - 100 - l*(sqrt(3)/2)+20, SIZE_Y-10-(3*l)/2 +10),5)
        pygame.draw.line(screen,black,(SIZE_X - 100 - l*(sqrt(3)/2)+20, SIZE_Y-10-(3*l)/2 +10), (SIZE_X - 100, SIZE_Y - (sqrt(3)*l)),5)
        pygame.draw.line(screen, black, (SIZE_X - 100, SIZE_Y - (sqrt(3)*l)),(SIZE_X - 100 + l*(sqrt(3)/2) - 20, SIZE_Y-10-(3*l)/2 +10),5)
        pygame.draw.line(screen, black, (SIZE_X - 100 + l*(sqrt(3)/2) - 20, SIZE_Y-10-(3*l)/2 +10),(SIZE_X - 100 + l*(sqrt(3)/2)-20, SIZE_Y-10-l/2 -10),5)
        pygame.draw.line(screen, black, (SIZE_X - 100 + l*(sqrt(3)/2)-20, SIZE_Y-10-l/2 -10),(SIZE_X - 95+ (sqrt(3)/4) * 12 , SIZE_Y-25 - l/4),5)
        pygame.draw.line(screen, black,(SIZE_X - 95+ (sqrt(3)/4) * 12 , SIZE_Y-25 - l/4),(SIZE_X - 95+ (sqrt(3)/4) * 12 , SIZE_Y-25 - l/4 -20),5)
        pygame.draw.line(screen, black,(SIZE_X - 95+ (sqrt(3)/4) * 12 , SIZE_Y-25 - l/4),(SIZE_X - 95+ (sqrt(3)/4) * 12 +20 , SIZE_Y-25 - l/4),5)
        #-------------

        if res_polygon.collidepoint(pygame.mouse.get_pos()) and click:
            choosing_lenght()

        middle = winmessage.get_rect(center=(SIZE_X/2,147))
        screen.blit(winmessage,middle)
        pygame.display.flip()
        click = False

menu()


x_ = []
y_ = []

for i in range(3):
        x, y = map(int, input().split())
        x_.append(x)
        y_.append(y)

for i in range(3):
        if x_.count(x_[i]) == 1:            # 두 개의 리스트에서 각 인덱스에 위치한 요소의 개수가 한개인지 찾기
                x = x_[i]
        if y_.count(y_[i]) == 1:
                y = y_[i]
print(x, y)


from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html', phrase = "Welcome to your Profile", times=5)

@app.route('/<name>')
def personalize(name):
    return render_template("index2.html", namevar=name)

@app.route('/lists')
def render_lists():
    student_info = [
        {'name': 'Michael', 'age': 35},
        {'name': 'John', 'age': 30},
        {'name': 'Mark', 'age': 25},
        {'name': 'KB', 'age': 27}
    ]
    return render_template("lists.html", random_numbers = [3,1,5], students = student_info)

@app.route('/users')
def render_list():
    users = [
        {'first_name': 'Michael', 'last_name': 'choi'},
        {'first_name': 'John', 'last_name': 'Suppy'},
        {'first_name': 'Mark', 'last_name': 'Gilly'},
        {'first_name': 'KB', 'last_name': 'Tony'}
    ]
    greeting = 'hellooo'
    return render_template("users.html", user_list=users, greeting=greeting)

if __name__=="__main__":
    app.run(debug=True)


# coding: utf-8

"""
    YNAB API Endpoints

    Our API uses a REST based design, leverages the JSON data format, and relies upon HTTPS for transport. We respond with meaningful HTTP response codes and if an error occurs, we include error details in the response body.  API Documentation is at https://api.youneedabudget.com  # noqa: E501

    The version of the OpenAPI document: 1.0.0
    Generated by: https://openapi-generator.tech
"""

import inspect
import pprint
import re  # noqa: F401
import six

from pynab.openapi.configuration import Configuration

class SaveAccount(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'name': 'str',
        'type': 'str',
        'balance': 'int'
    }

    attribute_map = {
        'name': 'name',
        'type': 'type',
        'balance': 'balance'
    }

    def __init__(self, name=None, type=None, balance=None, local_vars_configuration=None):  # noqa: E501
        """SaveAccount - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._name = None
        self._type = None
        self._balance = None
        self.discriminator = None

        self.name = name
        self.type = type
        self.balance = balance

    @property
    def name(self):
        """Gets the name of this SaveAccount.  # noqa: E501

        The name of the account  # noqa: E501

        :return: The name of this SaveAccount.  # noqa: E501
        :rtype: str
        """
        return self._name

    @name.setter
    def name(self, name):
        """Sets the name of this SaveAccount.

        The name of the account  # noqa: E501

        :param name: The name of this SaveAccount.  # noqa: E501
        :type name: str
        """
        if self.local_vars_configuration.client_side_validation and name is None:  # noqa: E501
            raise ValueError("Invalid value for `name`, must not be `None`")  # noqa: E501

        self._name = name

    @property
    def type(self):
        """Gets the type of this SaveAccount.  # noqa: E501

        The account type  # noqa: E501

        :return: The type of this SaveAccount.  # noqa: E501
        :rtype: str
        """
        return self._type

    @type.setter
    def type(self, type):
        """Sets the type of this SaveAccount.

        The account type  # noqa: E501

        :param type: The type of this SaveAccount.  # noqa: E501
        :type type: str
        """
        if self.local_vars_configuration.client_side_validation and type is None:  # noqa: E501
            raise ValueError("Invalid value for `type`, must not be `None`")  # noqa: E501
        allowed_values = ["checking", "savings", "creditCard", "cash", "lineOfCredit", "otherAsset", "otherLiability"]  # noqa: E501
        if self.local_vars_configuration.client_side_validation and type not in allowed_values:  # noqa: E501
            raise ValueError(
                "Invalid value for `type` ({0}), must be one of {1}"  # noqa: E501
                .format(type, allowed_values)
            )

        self._type = type

    @property
    def balance(self):
        """Gets the balance of this SaveAccount.  # noqa: E501

        The current balance of the account in milliunits format  # noqa: E501

        :return: The balance of this SaveAccount.  # noqa: E501
        :rtype: int
        """
        return self._balance

    @balance.setter
    def balance(self, balance):
        """Sets the balance of this SaveAccount.

        The current balance of the account in milliunits format  # noqa: E501

        :param balance: The balance of this SaveAccount.  # noqa: E501
        :type balance: int
        """
        if self.local_vars_configuration.client_side_validation and balance is None:  # noqa: E501
            raise ValueError("Invalid value for `balance`, must not be `None`")  # noqa: E501

        self._balance = balance

    def to_dict(self, serialize=False):
        """Returns the model properties as a dict"""
        result = {}

        def convert(x):
            if hasattr(x, "to_dict"):
                args = inspect.getargspec(x.to_dict).args
                if len(args) == 1:
                    return x.to_dict()
                else:
                    return x.to_dict(serialize)
            else:
                return x

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            attr = self.attribute_map.get(attr, attr) if serialize else attr
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: convert(x),
                    value
                ))
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], convert(item[1])),
                    value.items()
                ))
            else:
                result[attr] = convert(value)

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, SaveAccount):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, SaveAccount):
            return True

        return self.to_dict() != other.to_dict()


class Product:

    def __init__(self, id, nazwa, cena):
        self.id = id
        self.nazwa = nazwa
        self.cena = cena

    def __str__(self):
        return f"{self.nazwa}({self.id}), cena: {self.cena:.2f}"

    def print_info(self):
        print(f"Produkt: {self.nazwa!r}, id: {self.id}, cena: {self.cena} PLN")

class Basket:

    def __init__(self):
        self._products = {}

    def add_product(self, produkt, qty):
        if produkt in self._products:
            #key == produkt
            self._products[produkt] += qty
        else:
            self._products[produkt] = qty

    def count_total_price(self):
        total_price = 0
        for product, quantity in self._products.items():
            total_price += product.cena * quantity
        return total_price

    def generate_report(self):
        result = "Produkty w koszyku:\n"
        for product, quantity in self._products.items():
            result += f"- {product} x {quantity}\n"
        result += f"W sumie: {self.count_total_price():.2f}"
        return result

    @classmethod
    def from_products(cls, given_products):
        basket = cls()
        for product in given_products:
            basket.add_product(product, 1)
        return basket

if __name__ == "__main__":
    basket = Basket()
    product = Product(1, "Woda", 10.99)
    product2 = Product(2, "Chleb", 3.24)
    basket.add_product(product,5)
    basket.add_product(product2,2)
    # print(basket._products)
    basket.count_total_price()
    print(basket.generate_report())

def test_basket_empty_price():
    b = Basket()
    assert b.count_total_price() == 0

def test_basket_one_product_price():
    b = Basket()
    p = Product(1, "Woda", 10.0)
    b.add_product(p, 3)
    assert b.count_total_price() == 3 * 10

def test_basket_multiple_products_price():
    b = Basket()
    woda = Product(1, "Woda", 10.0)
    chleb = Product(2, "Chleb", 20.0)
    b.add_product(woda, 3)
    b.add_product(chleb, 1)
    b.add_product(woda, 1)
    assert b.count_total_price() == 4 * 10 + 1 * 20

def test_basket_one_product_report():
    b = Basket()
    p = Product(1, "Woda", 10.0)
    b.add_product(p, 3)
    expected = """Produkty w koszyku:
- Woda(1), cena: 10.00 x 3
W sumie: 30.00"""
    assert b.generate_report() == expected

def test_basket_multiple_product_report():
    b = Basket()
    p1 = Product(1, "Pierogi", 10.0)
    p2 = Product(2, "Choinka", 20.0)
    p3 = Product(3, "Prezenty", 30.0)
    b.add_product(p1, 10)
    b.add_product(p2, 1)
    b.add_product(p3, 4)
    assert len(b.generate_report().splitlines()) == 2 + 3

def test_basket_from_products():
    p1 = Product(1, "Pierogi", 10.0)
    p2 = Product(2, "Choinka", 20.0)
    p3 = Product(3, "Prezenty", 30.0)
    b = Basket.from_products([p1, p2, p3])
    assert len(b.generate_report().splitlines()) == 2 + 3


from django import forms
from django.core.validators import RegexValidator
from django.contrib.auth.forms import UserCreationForm
from django.forms import ModelForm
from django.forms import TextInput
from .models import Customer, Contact, Order

class Registr_new_user(UserCreationForm):
    email = forms.EmailField(required=True)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$')
    telefon = forms.CharField(validators=[phone_regex], max_length=17)
    imie = forms.CharField(max_length=20)
    nazwisko = forms.CharField(max_length=20)
    adres = forms.CharField(max_length=120)

    class Meta:
        model = Customer
        fields = ["username", "email", "password1", "password2", "telefon", "imie", "nazwisko", "adres"]

class ContactForm(ModelForm):
    class Meta:
        model = Contact
        fields = '__all__'

class Calc(forms.Form):
    Jestes = [('Mężczyzna', "Mężczyzna"), ('Kobieta', "Kobieta")]
    Ile_razy_w_tygodniu_uprawiasz_60_min_sportu = [('0', "0"), ('1', "1"), ('2', '2'), ('3', "3"), ('4', "4"),
                                                   ('5', '5'), ('6', "6"), ('7', '7')]
    Jaki_masz_cel = [('Chcę schudnąć', "Chcę schudnąć"), ('Chcę zdrowo jeść', "Chcę zdrowo jeść"),
                     ('Chcę zbudować mięśnie', 'Chcę zbudować mięśnie')]
    Wiek = forms.IntegerField()
    Jestes = forms.ChoiceField(choices=Jestes)
    Waga = forms.IntegerField()
    Wzrost = forms.IntegerField()
    Ile_razy_w_tygodniu_uprawiasz_60_min_sportu = forms.ChoiceField(choices=Ile_razy_w_tygodniu_uprawiasz_60_min_sportu)
    Jaki_masz_cel = forms.ChoiceField(choices=Jaki_masz_cel)

PROD_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 31)]

class CartaddForm(forms.Form):
    Ilość = forms.TypedChoiceField(choices=PROD_QUANTITY_CHOICES, coerce=int)
    o_Ilość = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)

class OrderCreateForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = [ 'address', 'kod_pocztowy', ]
        widgets = {
            'user': TextInput(attrs={'readonly': 'readonly'})
        }


from mathutils import Vector
from uplogic.nodes import ULActionNode
from uplogic.utils import is_invalid
from uplogic.utils import is_waiting
from uplogic.utils import not_met

class ULTranslate(ULActionNode):
    def __init__(self):
        ULActionNode.__init__(self)
        self.condition = None
        self.moving_object = None
        self.local = None
        self.vect = None
        self.speed = None
        self._t = None
        self._old_values = None

    def evaluate(self):
        condition = self.get_input(self.condition)
        if not_met(condition):
            self._set_value(False)
            return self._set_ready()
        moving_object = self.get_input(self.moving_object)
        vect = self.get_input(self.vect)
        dx = vect.x
        dy = vect.y
        dz = vect.z
        speed = self.get_input(self.speed)
        local = self.get_input(self.local)
        if is_waiting(
            vect,
            dx,
            dy,
            dz,
            speed,
            local
        ):
            return
        if is_invalid(moving_object):
            return
        self._set_ready()
        if dx is None:
            return
        if dy is None:
            return
        if dz is None:
            return
        if speed is None:
            return
        if local is None:
            return
        new_values = (moving_object, dx, dy, dz, speed, local)
        if new_values != self._old_values:
            start_pos = (
                moving_object.localPosition if
                local else moving_object.worldPosition
            )
            end_pos = Vector((
                start_pos.x + dx, start_pos.y + dy, start_pos.z + dz
            ))
            distance = (start_pos - end_pos).length
            time_to_destination = distance / speed
            t_speed = 1.0 / time_to_destination
            self._old_values = new_values
            self._start_pos = start_pos.copy()
            self._end_pos = end_pos.copy()
            self._d_pos = (end_pos - start_pos)
            self._t_speed = t_speed
            self._t = 0.0
        t = self._t
        dt = self._t_speed * self.network.time_per_frame
        t += dt
        if t >= 1.0:
            self._set_value(True)
            self._t = 0.0
            if local:
                moving_object.localPosition = self._end_pos.copy()
            else:
                moving_object.worldPosition = self._end_pos.copy()
        else:
            npos = self._start_pos + (self._d_pos * t)
            if local:
                moving_object.localPosition = npos
            else:
                moving_object.worldPosition = npos
            self._t = t
            self._set_value(False)


"""
File for classes to use in the tribe simulator
"""

import random

TRAITS = (
    'strength',
    'bravery',
    'discipline',
    'aggression',
    'wisdom',
    'endurance',
    'belief',
    'desire',
    'synergy'
)

TRIBES = (
    'Tribe 1',
    'Tribe 2',
    'Tribe 3',
    'Tribe 4',
    'Tribe 5',
)
# initialize arbitrary traits, tribe names

class Tribe:
    """
    Tribe class
    """

    def __init__(self, tribe_id):
        """
        Attributes are name, tribe ID and set of warriors ID's
        """
        self.name = TRIBES[tribe_id]
        self.tribe_id = tribe_id
        self.warriors = set()

    def add_warrior(self, warrior_id):
        """
        Add warrior to tribe
        """
        self.warriors.add(warrior_id)

    def kill_warrior(self, warrior_id):
        """
        Remove warrior from tribe
        """
        self.warriors.remove(warrior_id)

    def __len__(self):
        """
        Return number of warriors in tribe
        """
        return len(self.warriors)

    def random_warrior(self):
        """
        Return a random warrior from tribe
        """
        warrior = self.warriors.pop()
        self.warriors.add(warrior)
        return warrior

    def __str__(self):
        """
        Return a text representation of the tribe
        """
        ret = f"Tribe's name is {self.name}\n"
        ret += f"Tribe's warriors are {sorted(self.warriors)}\n"
        return ret

class Warrior:
    """
    Warrior class
    """
    def __init__(self, tribe, friends, warrior_id):
        """
        Attributes are tribe, traits, set of friends, age and ID
        """
        self.tribe = tribe
        self.traits = {trait: random.randint(-12, 15) for trait in TRAITS}
        self.friends = friends
        self.age = 0
        self.warrior_id = warrior_id

    def increase_trait(self, trait, inc):
        """
        Increase a trait's value by inc (max trait value is 100)
        """
        if (self.traits[trait] +
                inc) < 100 and (self.traits[trait] + inc) > -100:
            self.traits[trait] += inc
        elif inc > 0:
            self.traits[trait] = 100
        else:
            self.traits[trait] = -100

    def add_friend(self, friend):
        """
        Add a friend to friend list
        """
        if friend not in self.friends:
            self.friends.add(friend)

    def del_friend(self, friend):
        """
        Remove a friend from friend list
        """
        if friend in self.friends:
            self.friends.remove(friend)

    def inc_age(self):
        """
        Increment age
        """
        self.age += 1
        return self.age >= 60


"""
나머지 구하기
"""

def solution(num1, num2):
    return num1 % num2

print(solution(-3,2))

"""
중앙값 구하기

1) array 계산

2) list 계산

2) 라이브러리 활용
"""
def solution(array):
    size = len(array)
    """
    for i in range(len(array)):
        k = i
        for j in range(i+1, len(array)):
            if array[j] < array[k]:
                k = j
        temp = array[i]
        array[i] = array[k]
        array[k] = temp
    return array[size//2]
    """

    array.sort()
    return array

print(solution([9, -1, 0]))

"""
최빈값 구하기
"""
def solution(array):
    answer = 0
    countMap = dict()
    cKey = []

    for i in range(len(array)):
        if array[i] in countMap:
            countMap[array[i]] += 1
        else:
            countMap[array[i]] = 1

    cKey = list(countMap.keys())
    print(countMap, cKey)

    if len(cKey) == 1:
        return array[0]

    # else
    answer = cKey[0]
    check = False

    for i in range(1, len(cKey)):
        if countMap[cKey[i]] == countMap[answer]:
            check = True
        if countMap[cKey[i]] > countMap[answer]:
            check = False
            answer = cKey[i]

    if check == True:
        return -1

    else:
        return answer

print(solution([1]))

"""
짝수는 싫어요
"""

def solution(n):
    answer = []

    for i in range(1, n+1):
        if (i % 2) != 0:
            answer.append(i)
    return answer

print(solution(15))


liste1 = ["öyle", "üçe","beşe", "bakamam"] # Listemiz

liste1.sort() # Listenin içindeki elemanları sıralar. Burada liste elemanlarının string, int vb.
# veri tiplerine uygun olarak sıralanacağı unutulmamalıdır.

print(liste1)

liste1.sort(reverse = True) # Sıralamanın küçükten büyüğe değil de tam tersi olması için kullanılan fonksiyondur.

print(liste1)


# encoding:utf-8
import pygame

import function as f
from chess import Chess,BigChess
from button import Button
from settings import Settings
from windows import Windows

def run_game():
    pygame.init()   #初始化
    st = Settings()
    screen = pygame.display.set_mode(st.setmode) #500*600的屏幕
    pygame.display.set_caption('TicTacToe')         #标题

    image = pygame.image.load('materials/chessboard.bmp') #载入棋盘
    chess = Chess()
    bigchess = BigChess()
    retract_button = Button(screen, (170,50,150,40),text='Retract')      #悔棋按钮
    replay_button = Button(screen, (170,110,150,40),text='Replay')      #重玩按钮
    windows = Windows(screen,'Replay?','Yes','No',150,200)
    while True:
        screen.fill(st.bg_color)      #背景色
        screen.blit(image,st.top_left_corner)#在棋盘左上角位置绘制棋盘，注意跟棋盘的中心位置有关

        f.check_keydown(chess,bigchess,windows,screen,st,retract_button,replay_button)#检测鼠标按动

        retract_button.draw_button()    #绘制悔棋按钮
        replay_button.draw_button()     #绘制重玩按钮
        f.draw(chess,bigchess,screen,windows,st)    #绘制棋子，框等
        pygame.display.update()     #更新屏幕

run_game()


from bs4 import BeautifulSoup
import requests
import json
from name import *

haveNew = False

def getAllBlogPic(member,listNewestDate):

    count = 0

    allPic = []

    for i in keyakizaka:
        if(member == i['name']):
            memberLink = 'https://www.keyakizaka46.com/s/k46o/diary/member/' + \
                i['blog']

    # main page of one member's blog
    init_response = requests.get((memberLink))

    # 以 Beautiful Soup 解析 HTML 程式碼
    soup = BeautifulSoup(init_response.text, 'html.parser')

    # find the newest blog
    newestLinkWrap = soup.find('li', class_='singlePage')
    newestLink = 'https://www.keyakizaka46.com' + \
        newestLinkWrap.select_one('a').get('href')

    while (True):

        # member's newest blog
        next_response = requests.get((newestLink))

        # 以 Beautiful Soup 解析 HTML 程式碼
        soup = BeautifulSoup(next_response.text, 'html.parser')

        blogWrap = soup.find('div', class_='box-main')

        # get img list
        img_tags = blogWrap.find_all('img',{"src":True})

        ##### get info for list #####
        # get date
        datediv = blogWrap.find('div', class_='box-bottom')
        dateli = datediv.find('li')
        print(dateli.get_text().strip())
        date = dateli.get_text().strip()

        if date==listNewestDate:
            return allPic

        # get title
        titlediv = blogWrap.find('div', class_='box-ttl')
        titleli = titlediv.find('h3')
        print(titleli.get_text().strip())
        print(newestLink)
        title = titleli.get_text().strip()

        oneBlog = {'date': date, 'title': title, 'link': newestLink, 'img': []}

        for tag in img_tags:

            print(tag['src'])
            oneBlog['img'].append(tag['src'])

        allPic.append(oneBlog)
        ##### end of appending dict to list #####

        if (date=='2018/06/07 02:37' and title=='スキマスイッチさん。'): #a page error in saitou shiori's blog found
            print('Error blog skipped')
            newestLink = 'https://www.keyakizaka46.com/s/k46o/diary/detail/15602?ima=0000&cd=member'
            continue

        print("-----------------")

        if soup.find('div', class_='btn-navi btn-prev') == None:
            print("Finish")
            break
        else:
            prev_blog = soup.find('div', class_='btn-navi btn-prev')
            newestLink = 'https://www.keyakizaka46.com' + \
                prev_blog.select_one('a').get('href')

    return allPic

def writeMemberJSON(member):

    fileName = "./memberdata/" + member + ".json"

    with open(fileName, "w", encoding='utf-8') as file:
        json.dump(getAllBlogPic(member,0), file)

    file.close()

def writeAllMemberJSON():

    for i in keyakizaka:
        if i['gen']==2.5:
            writeMemberJSON(i['name'])

def updateMemberJSON(member):
    fileName = "./memberdata/" + member + ".json"

    with open(fileName, "r+", encoding='utf-8') as file:
        data = json.loads(file.read())

    # print(data[0])
    tempList = getAllBlogPic(member,data[0]['date'])

    tempList.extend(data)

    with open(fileName, "w", encoding='utf-8') as file:
        json.dump(tempList, file)

def updateAllMemberJSON():

    for i in keyakizaka:
        updateMemberJSON(i['name'])

def createMemberJSON():

    for i in keyakizaka:
        fileName = "./memberdata/" + i['name'] + ".json"

        with open(fileName, "w", encoding='utf-8') as file:
            json.dump("", file)

updateAllMemberJSON()


from server3.service.elasticsearch_service import ElasticSearchSearvice
from server3.business.project_business import ProjectBusiness
from server3.business.user_business import UserBusiness
from server3.business.user_request_business import UserRequestBusiness
from server3.business.event_business import EventBusiness
from server3.business.app_business import AppBusiness
from server3.business.module_business import ModuleBusiness
from server3.business.data_set_business import DatasetBusiness
import copy
import jieba
import numpy as np

bus_type_mapper = {
    "app": AppBusiness,
    "module": ModuleBusiness,
    "dataset": DatasetBusiness,
}

INDICATE_SEARCH = ['app:', 'module:', 'dataset:', 'requests:', 'users:']

MAPPING = ['app', 'module', 'dataset', 'user', 'request', 'code_snippet']

FIELDS = {'app': ['display_name', 'description'],
            'module': ['display_name', 'description'],
            'dataset': ['display_name', 'description'],
            'user': ['username', 'bio'],
            'request': ['request_title', 'description'],
          'code_snippet': ['code_name', 'code_des', 'code_tags', 'code_source', 'detail_url']}

COMBINEKEYS = ['app', 'module', 'dataset']

class SearchService:
    @classmethod
    def __split_with_advanced_search(cls, values):
        selected = ''
        copy_values = values
        for index in INDICATE_SEARCH:
            if index in values:
                selected = index
                break
        if selected != '':
            # 定向搜索
            wait_for_search_values = values.split(selected)[1]
            copy_values = copy.deepcopy(wait_for_search_values)
            # for v_index in range(len(wait_for_search_values)):
            #     if wait_for_search_values[v_index] == '' or wait_for_search_values[v_index] == ' ':
            #         del copy_values[v_index]
            #     else:
            #         continue
        selected = selected.split(':')[0]
        if selected in MAPPING:
            selected += 's'
        return selected, copy_values

    @classmethod
    def __add_project_info(cls, project_id, sample_dict):
        try:
            project = ProjectBusiness.repo.read_by_id(project_id)
            view_num = EventBusiness.get_number({project.type: project, 'action': "view"})
            fork_num = EventBusiness.get_number({project.type: project, 'action': "fork"})
            star_num = EventBusiness.get_number({project.type: project, 'action': "star"})
            sample_dict['view_num'] = view_num
            sample_dict['favor_num'] = fork_num
            sample_dict['star_num'] = star_num
            sample_dict['user_ID'] = project.user.user_ID
            sample_dict['avatarV'] = project.user.avatarV
            sample_dict['avatar_url'] = project.user.avatar_url if project.user.avatar_url else ''
            sample_dict['status'] = project.status
            return sample_dict
        except Exception as e:
            print('项目被删除')
            return False

    @classmethod
    def __add_user_info(cls, user_ID, sample_dict):
        user = UserBusiness.repo.read_by_user_ID(user_ID)
        if 'username' not in sample_dict:
            sample_dict['username'] = user.username
        return sample_dict

    @classmethod
    def __add_request_info(cls, request_id, sample_dict):
        try:
            request = UserRequestBusiness.repo.read_by_id(request_id)
            sample_dict['view_num'] = EventBusiness.get_number({'request': request, 'action': "view"})
            sample_dict['star_num'] = len(request.favor_users)
            sample_dict['favor_num'] = len(request.star_users)
            sample_dict['user_ID'] = request.user.user_ID
            sample_dict['avatarV'] = request.user.avatarV
            sample_dict['create_time'] = str(request.create_time)
            sample_dict['avatar_url'] = request.user.avatar_url if request.user.avatar_url else ''
            return sample_dict
        except Exception as e:
            print('request不存在')
            return False

    @classmethod
    def __pre_process_results(cls, results, search_text, is_title=False):
        if len(results.values()) > 0:
            key = list(results.keys())[0]
            values = results[key]['hits']
            total = values['total']
            hits = values['hits']
            pre_process = []
            for hit in hits:
                if 'highlight' not in hit:
                    continue
                highlight = hit['highlight']
                source = hit['_source']
                search_id = hit['_id']
                sample_data = {}
                # if key[-1] == 's':
                #     fields = FIELDS[key[:-1]]
                # else:
                #     fields = FIELDS[key]
                for field in source:
                    if field in highlight:
                        sample_data[field] = highlight[field][0]
                    else:
                        sample_data[field] = source[field]
                sample_data['id'] = search_id
                # 添加字段
                if not is_title:
                    if 'app' in key or 'module' in key or 'dataset' in key:
                        sample_data = cls.__add_project_info(sample_data['id'], sample_data)
                    elif 'request' in key:
                        sample_data = cls.__add_request_info(sample_data['id'], sample_data)
                if sample_data:
                    pre_process.append(sample_data)
            return key, total, pre_process

    @classmethod
    def __single_table_search(cls, results, selected, search_text, is_title=False):
        hits = results['hits']['hits']
        total = results['hits']['total']
        pre_process = []
        for hit in hits:
            if 'highlight' not in hit:
                continue
            highlight = hit['highlight']
            source = hit['_source']
            search_id = hit['_id']
            for field in highlight.keys():
                source[field] = highlight[field][0]
            source['id'] = search_id
            if not is_title:
                # 添加字段
                if 'app' in selected or 'module' in selected or 'dataset' in selected:
                    source = cls.__add_project_info(source['id'], source)
                # elif 'user' in selected:
                #     source = cls.__add_user_info(source['id'], source)
                elif 'request' in selected:
                    source = cls.__add_request_info(source['id'], source)
                elif 'code_snippet' in selected:
                    source = cls.__add_request_info(source['id'], source)
            if source:
                pre_process.append(source)
        return total, pre_process

    @classmethod
    def search_title(cls, values, start=0, size=3):
        selected, copy_values = cls.__split_with_advanced_search(values)
        # print("copy_valuescopy_values:", copy_values)
        copy_values = jieba.lcut_for_search(copy_values)
        # 处理后的结果
        processed_data = []

        if ElasticSearchSearvice.is_available():
            if selected != '':
                if len(copy_values) > 0:
                    results, count_info = ElasticSearchSearvice.search_title(copy_values, index=selected)
                    total, pre_process = cls.__single_table_search(results, selected, copy_values)
                    # total, data = cls.__single_table_search(results, selected, copy_values, is_title=True)
                    # 单表查询
                    processed_data.append({selected:
                                           {'total': total, 'hits': pre_process}})
                else:
                    # 没有输入就什么也不查询
                    results = {'message': 'no data'}
                    return results
            else:
                # 全局搜索
                # values.split(' ')
                wait_for_search_values = copy_values
                results, count_info = ElasticSearchSearvice.search_title(search_value=wait_for_search_values)
                # 所有表查询结果
                for result in results:
                    # analysis = cls.__pre_process_results(result, wait_for_search_values, is_title=True)
                    # if analysis:
                    #     key, total, pre_process = analysis
                    selected = list(result.keys())[-1]
                    values = list(result.values())[-1]
                    total, pre_process = cls.__single_table_search(values, selected, copy_values)
                    processed_data.append({selected: {'total': total, 'hits': pre_process}})
        else:
            processed_data = []
            count_info = {'apps': 0, 'modules': 0, 'datasets': 0}
        return processed_data, count_info

    @classmethod
    def __get_the_type_array(cls, results):
        apps = []
        modules = []
        datasets = []
        hits = results['hits']['hits']
        for hit in hits:
            source = hit['_source']
            source['id'] = hit['_id']
            source = cls.__add_project_info(project_id=source['id'], sample_dict=source)
            if source['type'] == 'app':
                apps.append(source)
            elif source['type'] == 'module':
                modules.append(source)
            else:
                datasets.append(source)
        return apps, modules, datasets

    @classmethod
    def __parse_search_tag(cls, results, index):
        hits = results['hits']['hits']
        back = []
        for hit in hits:
            values = hit['_source']
            if index == 'project':
                values = cls.__add_project_info(hit['_id'], values)
            else:
                values = cls.__add_request_info(hit['_id'], values)
            back.append(values)
        return back

    @classmethod
    def search_tags(cls, tags, start=0, size=10, index='all', project_type='app'):
        if not isinstance(tags, list):
            tags = tags.split(',')

        if ElasticSearchSearvice.is_available():
            if index == 'all':
                projects, requests = ElasticSearchSearvice.search_tags(tags, start=start, size=size,
                                                                       index=index, project_type=project_type)

                project_total_num = projects['hits']['total']
                request_total_num = requests['hits']['total']

                projects = cls.__parse_search_tag(projects, 'project')

                requests = cls.__parse_search_tag(requests, 'request')

                back_data = {'projects': {'total': project_total_num, 'hits': projects},
                             'requests': {'total': request_total_num, 'hits': requests}}
            else:
                requests = ElasticSearchSearvice.search_tags(tags, start=start, size=size,
                                                             index=index, project_type=project_type)
                request_total_num = requests['hits']['total']
                results = cls.__parse_search_tag(requests, index)
                back_data = {'projects': {'total': request_total_num,
                                          'hits': {project_type: results}}}
        else:
            back_data = {'projects': {'total': 0, 'hints': {}}}

        return back_data

    @classmethod
    def __split_request(cls, datas):
        apps = []
        modules = []
        datasets = []
        for data in datas:
            print(data)
            if data.get('type') == 'app':
                apps.append(data)
            elif data.get('type') == 'module':
                modules.append(data)
            elif data.get('type') == 'dataset':
                datasets.append(data)
        return apps, modules, datasets

    @classmethod
    def search_code_snippet(cls, search_value, start=0, size=10, request_type=None):
        if not isinstance(search_value, list):
            search_value = jieba.lcut_for_search(search_value)
        # print(search_value)
        if ElasticSearchSearvice.is_available():
            results = ElasticSearchSearvice.search_code_snippet(fields=['code_name', 'code_des', 'code_tags', 'code_source'],
                                                                index='code_snippets', search_values=search_value,
                                                                start=start, size=size)
            hits = results['hits']['hits']
            # print(hits)
            total = results['hits']['total']
            pre_process = []
            for hit in hits:
                source = hit['_source']
                search_id = hit['_id']
                # source['id'] = search_id
                source['code_from'] = search_id
                pre_process.append(source)
            # total, pre_process = cls.__single_table_search(results, 'code_snippets', search_value)
            return {'total': total, 'hits': pre_process}
        else:
            print('空的')
            return {'total': 0, 'hints': []}

    @classmethod
    def search(cls, search_value, index='app', start=0, size=3, request_type=None):
        if not isinstance(search_value, list):
            search_value = jieba.lcut_for_search(search_value)
        if index in MAPPING:
            selected = index + 's'
        else:
            selected = index

        if ElasticSearchSearvice.is_available():
            results, count_info = ElasticSearchSearvice.search_fields(fields=FIELDS[index],
                                                                      index=selected, search_values=search_value,
                                                                      start=start, size=size, request_type=request_type)
            print(results, count_info)
            # print(results)
            # 数据处理
            total, pre_process = cls.__single_table_search(results, selected, search_value)
            # if 'request' in selected:
            #     apps, modules, datasets = cls.__split_request(pre_process)
            #     return {selected: {'total': total, 'hits': {'apps': apps, 'modules': modules, 'datasets': datasets}},
            #             'count': count_info}
            # if not count_info['project_nums'] and 'dataset' in selected:
            #     pre_process = []
            return {selected: {'total': total, 'hits': pre_process}, 'count': count_info}
        return {selected: {'total': 0, 'hints': []}, 'count': {}}

    @classmethod
    def related_projects(cls, **args):
        if ElasticSearchSearvice.is_available():
            page_no = args.get('page_no')
            page_size = args.get('page_size')
            project_id = args.get('project_id')
            project_type =args.get('project_type')
            project = ProjectBusiness.get_by_id(project_id)
            tags = [tag.id for tag in project.tags]
            projects = []
            for tag in tags:
                ps = bus_type_mapper[project_type].repo.search(tag, {'tags': 'icontains'})
                ps = ps(status='active')
                for p in ps:
                    if 'tutorial' not in p.display_name.lower():
                        projects.append(p)
                # projects.extend(ps)
            np.random.shuffle(projects)
            if not isinstance(projects, list):
                projects = projects.tolist()
            return projects[(page_no - 1) * page_size: page_no * page_size], len(projects)
        return [], 0

    @classmethod
    def add_all(cls):
        ElasticSearchSearvice.add_all()

    @classmethod
    def delete_all(cls):
        ElasticSearchSearvice.delete_all()

    @classmethod
    def refresh_all(cls):
        ElasticSearchSearvice.refresh_index()

    @classmethod
    def add_user(cls, user_ID, username, bio, avatarV, avatar_url):
        if ElasticSearchSearvice.is_available():
            ElasticSearchSearvice.add_user(user_ID, username, bio, avatarV, avatar_url)

    @classmethod
    def add_project(cls, project_id, display_name, description, tags, project_type, img_v, photo_url, username):

        if ElasticSearchSearvice.is_available():
            cls.project = ElasticSearchSearvice.add_project(project_id, display_name, description, tags, project_type,
                                                            img_v, photo_url, username)

    @classmethod
    def add_request(cls, request_title, description, request_type, username, request_id):
        if ElasticSearchSearvice.is_available():
            ElasticSearchSearvice.add_request(request_title, description, request_type, username, request_id)

    @classmethod
    def add_code_snippet(cls, code_snippet_id,  code_name, code_des, code_tags, code_source, detail_url, insert_num):
        if ElasticSearchSearvice.is_available():
            ElasticSearchSearvice.add_code_snippet(code_snippet_id,  code_name, code_des, code_tags,
                                                   code_source, detail_url, insert_num)

    @classmethod
    def delete_project(cls, project_id):
        if ElasticSearchSearvice.is_available():
            ElasticSearchSearvice.delete_project(project_id)

    @classmethod
    def delete_code_snippet(cls, code_snippet_id):
        if ElasticSearchSearvice.is_available():
            ElasticSearchSearvice.delete_project(code_snippet_id)

    @classmethod
    def delete_users(cls, user_ID):
        if ElasticSearchSearvice.is_available():
            ElasticSearchSearvice.delete_project(user_ID)

    @classmethod
    def delete_request(cls, request_id):
        if ElasticSearchSearvice.is_available():
            ElasticSearchSearvice.delete_request(request_id)

# MARK: 单元测试
if __name__ == '__main__':
    # test_titles1 = 'chentiyun'
    # test_titles2 = 'module: g'
    # test_tags = ['video']
    # # 提取部分
    # import time
    # from pprint import pprint
    # start = time.time()
    # print(SearchService.search_title(test_titles1))
    # # SearchService.search_title(test_titles2)
    # print(SearchService.search(test_titles1))
    from pprint import pprint
    # pprint(SearchService.search_code_snippet('print'))
    # pprint(SearchService.search_tags(tags=test_tags, index='all'))
    # print('end time:', time.time() - start)
    ElasticSearchSearvice.delete_all()
    ElasticSearchSearvice.add_all()

    # 测试删除
    # SearchService.delete_project('5b83fc930c11f3302f4d07c6')


# Imports
from flask import Flask, request, jsonify, render_template, make_response
from firebase_admin import credentials, firestore, initialize_app
import os
import time

app = Flask(__name__)

# Initialize Firestore DB
cred = credentials.Certificate('key.json')
default_app = initialize_app(cred)
db = firestore.client()
rest_ref = db.collection('restaurants')

# Index
@app.route('/')
def index():
    """
        Return index webpage
    """
    return render_template('index.html')

# Add restaurants to DB
@app.route('/add', methods=['POST'])
def create():
    """
        Add entry to Cloud Firestore collection
        Ensure you pass a custom ID as part of json body in post request
        Example: json={'id': '1', 'coord': [40.0, -3.0], 'title': 'Restaurant 1' ...}
    """
    try:
        id = request.json['id']
        rest_ref.document(id).set(request.json)
        return jsonify({"success": True}), 200
    except Exception as e:
        return f"An Error Occured: {e}"

# Read restaurants from DB
@app.route('/list', methods=['GET'])
def read():
    """
        Get entries from Firestore collection as JSON
        rest : Return document that matches query ID
        all_rest : Return all documents
    """
    try:
        # Check if ID was passed to URL query
        rest_id = request.args.get('id')
        if rest_id:
            rest = rest_ref.document(rest_id).get()
            return jsonify(rest.to_dict()), 200
        else:
            all_rest = [doc.to_dict() for doc in rest_ref.stream()]
            return jsonify(all_rest), 200
    except Exception as e:
        return f"An Error Occured: {e}"

# Update restaurants in DB
@app.route('/update', methods=['POST', 'PUT'])
def update():
    """
        Update entry in Firestore collection
        Ensure you pass a custom ID as part of json body in post request
        Example: json={'id': '1', 'coord': [40.0, -3.0], 'title': 'Restaurant 2' ...}
    """
    try:
        id = request.json['id']
        rest_ref.document(id).update(request.json)
        return jsonify({"success": True}), 200
    except Exception as e:
        return f"An Error Occured: {e}"

# Delete restaurants from DB
@app.route('/delete', methods=['GET', 'DELETE'])
def delete():
    """
        Delete an entry Firestore collection
    """
    try:
        # Check for ID in URL query
        rest_id = request.args.get('id')
        rest_ref.document(rest_id).delete()
        return jsonify({"success": True}), 200
    except Exception as e:
        return f"An Error Occured: {e}"

# Run Flask App in localhost at port 8080
if __name__ == '__main__':
  app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))


"""
Клиент Kafka.

Создание топиков и сообщений для тестов.

"""

from etl.src.core.settings import kafka_settings
from kafka import KafkaAdminClient, KafkaProducer, errors
from kafka.admin import NewTopic

class KafkaClient:

    def __init__(self):
        self.admin_client = KafkaAdminClient(bootstrap_servers=kafka_settings.bootstrap_servers)
        self.producer = KafkaProducer(bootstrap_servers=kafka_settings.bootstrap_servers)

    def create_topics(self, topics: list):
        topics = [
            NewTopic(name=topic_name, num_partitions=1, replication_factor=1)
            for topic_name in topics
        ]
        try:
            self.admin_client.create_topics(topics)
        except errors.TopicAlreadyExistsError:
            pass

    def delete_topics(self, topics: list):
        self.admin_client.delete_topics(topics)

    def produce(self, topic: str, messages: list):
        for message in messages:
            self.producer.send(
                topic=topic,
                value=message,
            )