import pygame, sys, color
import bike as b
import square as s
import color as c
import powerUps as pu
import json

import pygame
import math
import random
import datetime
from sys import exit

# import tron
from pygame.locals import *

pygame.init()

screen_width=800
screen_height=600

screen=pygame.display.set_mode((screen_width, screen_height))

def text_render(message, textFont, textSize, textColor):
    newFont = pygame.font.Font(textFont, textSize)
    newText = newFont.render(message, 0, textColor)
    return newText

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
ORANGE = (247, 148, 29)
YELLOW = (255, 242, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
PURPLE = (102, 45, 145)
GRAY = (128,128,128)

#Font
font = "Assets/TRON.TTF"
timer_font = "Assets/clock.TTF"
arcade_font = "Assets/ARCADE_N.TTF"

#Framerate
clock = pygame.time.Clock()
FPS=30

grid_cell_scl = 20  # width & height (scale) of each grid cell
grid_margin = 1  # amount of space on all sides of cells (must be odd for pygame line drawing)
grid_width = 40  # grid width cell count
grid_height = 32  # grid height cell count

screen_width = ((grid_margin + grid_cell_scl) * grid_width) + grid_margin  # width of the GUI window
screen_height = ((grid_margin + grid_cell_scl) * grid_height) + grid_margin  # height of the GUI window

CLOCK_SPD = 100  # the base clock speed, or arbitrary framerate - keep at 100
current_spd = CLOCK_SPD  # the current speed of the game (may change)
speed_timer = 0  # used to regulate when the current speed is changed
slow_timer = 0 # used to regulate when the user slows their bike
duration_timer = 0 # Timer used when the speed is activated - lasts for 5 seconds
paused = False # Boolean for when the game is paused or not
game_modes = {"1 V 1" : 2, "2 V 2" : 4, "3 V 1" : 4, "Free For All" : 4} # Dictionary for game modes
menu=True #Menu boolean that is set whenever the user is on the main menu
mode_menu=True #Mode menu boolean that is set whenever the user is on the game mode menu
leaderboard=True #leaderboard menu
pause_song=False #Pauses the song when true

# decide on colors
bike_color = c.YELLOW
powerup_color = c.RED

GRID_BG = c.BLACK
GRID_FG = c.GRID_BLUE

# initialize pygame module
# def initialize():

# plays the music
pygame.mixer.music.load('Assets/theme.mp3')
pygame.mixer.music.play(-1)

screen = pygame.display.set_mode([screen_width, screen_height], pygame.NOFRAME)

pygame.display.set_caption('Prototype II')

first = True
pygame.time.set_timer(USEREVENT+1, 1000)

powerups = []

def save_data(highscores, names, file):
    data = {}
    data['leaderboard'] = []
    data['leaderboard'].append({
        'names': names,
        'highscores': highscores

    })

    with open(file, 'w') as outfile:
        json.dump(data, outfile)

def load_data(file):
    with open(file) as json_file:
        data = json.load(json_file)
        global names
        global highscores
        for p in data['leaderboard']:
            names = p['names']
            highscores = p['highscores']

#takes in the time, bikes and when they died and prints to the topbar
def timer(time, timerbikes, finalTimes):
    bikesleft = len(timerbikes)
    posistion = 40 / (bikesleft + 1)
    for bike in timerbikes:
        if(bike.alive):
            screen.blit(text_render(str(time), timer_font, 40, bike.color), (((posistion * bikesleft) * (grid_cell_scl + grid_margin)), 0))
            bikesleft -= 1
        else:
            if(finalTimes[bikesleft - 1] == 0):
                finalTimes[bikesleft - 1] = time
            screen.blit(text_render(str(finalTimes[bikesleft - 1]), timer_font, 40, bike.color), (((posistion * bikesleft) * (grid_cell_scl + grid_margin)), 0))
            bikesleft -= 1

# draw the background, grid, and squares
def draw(endState, inTeams):
    # erase everything
    screen.fill(GRID_BG)

    # grid x lines (vertical)
    for i in range(grid_width + 1):
        pygame.draw.line(screen, GRID_FG, (grid_margin / 2 + (i * (grid_cell_scl + grid_margin)), 0),
                         (grid_margin / 2 + (i * (grid_cell_scl + grid_margin)), screen_height), grid_margin)

    # grid y lines (horizontal)
    for i in range(grid_height + 1):
        pygame.draw.line(screen, GRID_FG, (0, grid_margin/2 + (i * (grid_cell_scl + grid_margin))),
                         (screen_width, grid_margin / 2 + (i * (grid_cell_scl + grid_margin))), grid_margin)

    # bike glow
    for bike in bikes:
        bike.draw_glow(screen)

    # bike squares
    for bike in bikes:
        bike.draw(screen)

    # powerup
    for powerup in powerups:
        for bike in bikes:
            # Stops the power ups from spawning on a line.
            # Removes the power up from the list so it does not spawn the second a player dies.
            if not bike.overlaps(powerup):
                pygame.draw.rect(screen, powerup.color, powerup.to_rect())
            else:
                powerups.remove(powerup)

    # draw the top bar and the timer
    screen.fill(GRAY, (0, 0, grid_cell_scl * (grid_width + 2), grid_cell_scl * 2 + 2))
    timer(time, timerbikes, finalTimes)

    if(endState):
        screen.fill(GRAY, (screen_width/6, screen_height/3, 2*screen_width/3, screen_height/3))
        if(inTeams == 2 or inTeams == 3):
            if(timerbikes[0].color == bikes[0].color):
                winner_text = text_render("Team 1 Wins", arcade_font, 40, bikes[0].color)
            else:
                winner_text = text_render("Team 2 Wins", arcade_font, 40, bikes[0].color)
        else:
            if(timerbikes[0].left_key == bikes[0].left_key):
                winner_text = text_render("Player 1 Wins", arcade_font, 40, bikes[0].color)
            elif(timerbikes[1].left_key == bikes[0].left_key):
                winner_text = text_render("Player 2 Wins", arcade_font, 40, bikes[0].color)
            elif(timerbikes[2].left_key == bikes[0].left_key):
                winner_text = text_render("Player 3 Wins", arcade_font, 40, bikes[0].color)
            elif(timerbikes[3].left_key == bikes[0].left_key):
                winner_text = text_render("Player 4 Wins", arcade_font, 40, bikes[0].color)
        continue_text = text_render("Press Enter/Return to continue", arcade_font, 15, GRID_FG)
        winner_rect = winner_text.get_rect()
        continue_rect = continue_text.get_rect()
        screen.blit(winner_text, (screen_width/2 - (winner_rect[2]/2), 3*screen_height/7))
        screen.blit(continue_text, (screen_width/2 - (continue_rect[2]/2), 3*screen_height/5))
    # flip the screen (? not sure why needed ?)
    pygame.display.flip()

# instantiate a bike object
def generate_bikes(gamemode):
    global bikes
    global powerups
    if(gamemode == 1):
        bikes = [b.Bike(0, (grid_cell_scl * 2) + 2, b.Bike.Direction.RIGHT, c.PLAYER1, pygame.K_q, pygame.K_w, pygame.K_e),
                b.Bike(screen_width - b.Bike.WEIGHT, screen_height - b.Bike.WEIGHT, b.Bike.Direction.LEFT, c.PLAYER4, pygame.K_i, pygame.K_o, pygame.K_p)]
    if(gamemode == 2):
        bikes = [b.Bike(0, (grid_cell_scl * 2) + 2, b.Bike.Direction.RIGHT, c.PLAYER1, pygame.K_q, pygame.K_w, pygame.K_e),
                b.Bike(screen_width - b.Bike.WEIGHT, grid_cell_scl * 2, b.Bike.Direction.DOWN, c.PLAYER1, pygame.K_i, pygame.K_o, pygame.K_p),
                b.Bike(0, screen_height - b.Bike.WEIGHT, b.Bike.Direction.UP, c.PLAYER4, pygame.K_z, pygame.K_x, pygame.K_c),
                b.Bike(screen_width - b.Bike.WEIGHT, screen_height - b.Bike.WEIGHT, b.Bike.Direction.LEFT, c.PLAYER4, pygame.K_LEFT, pygame.K_DOWN, pygame.K_RIGHT)]
    if(gamemode == 3):
        bikes = [b.Bike(0, (grid_cell_scl * 2) + 2, b.Bike.Direction.RIGHT, c.PLAYER1, pygame.K_q, pygame.K_w, pygame.K_e),
                b.Bike(screen_width - b.Bike.WEIGHT, grid_cell_scl * 2, b.Bike.Direction.DOWN, c.PLAYER1, pygame.K_i, pygame.K_o, pygame.K_p),
                b.Bike(0, screen_height - b.Bike.WEIGHT, b.Bike.Direction.UP, c.PLAYER1, pygame.K_z, pygame.K_x, pygame.K_c),
                b.Bike(screen_width - b.Bike.WEIGHT, screen_height - b.Bike.WEIGHT, b.Bike.Direction.LEFT, c.PLAYER4, pygame.K_LEFT, pygame.K_DOWN, pygame.K_RIGHT)]
    if(gamemode == 4):
        bikes = [b.Bike(0, (grid_cell_scl * 2) + 2, b.Bike.Direction.RIGHT, c.PLAYER1, pygame.K_q, pygame.K_w, pygame.K_e),
                b.Bike(screen_width - b.Bike.WEIGHT, grid_cell_scl * 2, b.Bike.Direction.DOWN, c.PLAYER2, pygame.K_i, pygame.K_o, pygame.K_p),
                b.Bike(0, screen_height - b.Bike.WEIGHT, b.Bike.Direction.UP, c.PLAYER3, pygame.K_z, pygame.K_x, pygame.K_c),
                b.Bike(screen_width - b.Bike.WEIGHT, screen_height - b.Bike.WEIGHT, b.Bike.Direction.LEFT, c.PLAYER4, pygame.K_LEFT, pygame.K_DOWN, pygame.K_RIGHT)]

    powerups.clear()

# Random number decides which power up is first
decidesStartingPowerUp = random.randint(0, 3)
if (decidesStartingPowerUp == 1):
    startingPowerUp = pu.PowerUps.Type.SPEED
elif (decidesStartingPowerUp == 2):
    startingPowerUp = pu.PowerUps.Type.MINE
elif (decidesStartingPowerUp == 3):
    startingPowerUp = pu.PowerUps.Type.PHASE
else:
    startingPowerUp = pu.PowerUps.Type.NUKE

powerups = [pu.PowerUps(screen_width, screen_height, startingPowerUp)]

# start the clock (frames)
clock = pygame.time.Clock()

def main_menu():
    selected="start"
    global menu
    global pause_song

    while menu:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.type == pygame.QUIT:
                    pygame.quit()
                    exit()
                if event.key == pygame.K_UP:
                    selected = "start"
                elif event.key == pygame.K_DOWN:
                    selected = "quit"
                if event.key == pygame.K_m:
                    pause_song = not pause_song
                if event.key == pygame.K_RETURN:
                    if selected == "start":
                        game_mode_menu()
                    if selected == "quit":
                        exit()
        if pause_song:
            pygame.mixer.pause()
        else:
            pygame.mixer.unpause()

        screen.fill(BLACK)
        title = text_render("TRON", font, 90, GRID_FG)
        if selected == "start":
            start_text = text_render("> START <", arcade_font, 50, YELLOW)
        else:
            start_text = text_render("START", arcade_font, 50, WHITE)
        if selected == "quit":
            quit_text = text_render("> QUIT <", arcade_font, 50, YELLOW)
        else:
            quit_text = text_render("QUIT", arcade_font, 50, WHITE)

        title_rect = title.get_rect()
        start_rect = start_text.get_rect()
        quit_rect = quit_text.get_rect()

        # Main Menu Text
        screen.blit(title, (screen_width/2 - (title_rect[2]/2), 80))
        screen.blit(start_text, (screen_width/2 - (start_rect[2]/2), 400))
        screen.blit(quit_text, (screen_width/2 - (quit_rect[2]/2), 480))
        pygame.display.update()
        clock.tick(FPS)
        pygame.display.set_caption("Main Menu")

def game_mode_menu():
    selected = "1 V 1"
    global inTeams
    global mode_menu
    #Esc key brings you back to main menu - Chris work on

    while mode_menu:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.type == pygame.QUIT:
                    mode_menu = False
                    pygame.quit()
                    exit()
                if event.key == pygame.K_ESCAPE:
                    main_menu()
                if event.key == pygame.K_UP:
                    selected = "1 V 1"
                elif event.key == pygame.K_RIGHT:
                    selected = "2 V 2"
                elif event.key == pygame.K_DOWN:
                    selected = "Free For All"
                elif event.key == pygame.K_LEFT:
                    selected = "3 V 1"
                if event.key == pygame.K_RETURN:
                    if selected == "1 V 1":
                        generate_bikes(1)
                        inTeams = 1
                        tutorial_menu()
                    if selected == "2 V 2":
                        generate_bikes(2)
                        inTeams = 2
                        tutorial_menu()
                    if selected == "3 V 1":
                        generate_bikes(3)
                        inTeams = 3
                        tutorial_menu()
                    if selected == "Free For All":
                        generate_bikes(4)
                        inTeams = 4
                        tutorial_menu()

        screen.fill(BLACK)
        title = text_render("Game Modes", font, 75, GRID_FG)
        if selected == "1 V 1":
            one_text = text_render("> 1 V 1 <", arcade_font, 28, YELLOW)
        else:
            one_text = text_render("1 V 1", arcade_font, 28, WHITE)
        if selected == "2 V 2":
            two_text = text_render("> 2 V 2 <", arcade_font, 28, YELLOW)
        else:
            two_text = text_render("2 V 2", arcade_font, 28, WHITE)
        if selected == "3 V 1":
            three_text = text_render("> 3 V 1 <", arcade_font, 28, YELLOW)
        else:
            three_text = text_render(" 3 V 1 ", arcade_font, 28, WHITE)
        if selected == "Free For All":
            free_text = text_render("> Free For All <", arcade_font, 24, YELLOW)
        else:
            free_text = text_render(" Free For All ", arcade_font, 24, WHITE)

        title_rect = title.get_rect()
        one_rect = one_text.get_rect()
        two_rect = two_text.get_rect()
        three_rect = three_text.get_rect()
        free_rect = free_text.get_rect()

        # Main Menu Text
        screen.blit(title, (screen_width/2 - (title_rect[2]/2), 80))
        screen.blit(one_text, (screen_width/2 - (one_rect[2]/2), 300))
        screen.blit(two_text, (screen_width/2 - (two_rect[2]/2)+200, 400))
        screen.blit(three_text, (screen_width/2 - (three_rect[2]/2)-200, 400))
        screen.blit(free_text, (screen_width/2 - (free_rect[2]/2), 525))

        pygame.display.update()
        clock.tick(FPS)
        pygame.display.set_caption("Game Mode")

# Chris notes
# Music for menu and game

def tutorial_menu():
    global mode_menu
    while mode_menu:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.type == pygame.QUIT:
                    mode_menu = False
                    pygame.quit()
                    exit()
                if event.key == pygame.K_ESCAPE:
                    main_menu()
                if event.key == pygame.K_RETURN:
                    game_run()

        screen.fill(BLACK)
        title = text_render("Controls", font, 75, GRID_FG)
        player1_text = text_render("Player 1: Q - Turn Left | W - Slow Bike | E - Turn right", arcade_font, 12, bikes[0].color)
        player2_text = text_render("Player 2: I - Turn Left | O - Slow Bike | P - Turn right", arcade_font, 12, bikes[1].color)
        continue_text = text_render("Press Enter/Return to start game...", arcade_font, 15, GRID_FG)
        title_rect = title.get_rect()
        player1_rect = player1_text.get_rect()
        player2_rect = player2_text.get_rect()
        continue_rect = continue_text.get_rect()

        if len(bikes) > 2:
            position1 = 200
        else:
            position1 = 300

        if len(bikes) > 2:
            position2 = 300
        else:
            position2 = 400

        # Main Menu Text
        screen.blit(title, (screen_width/2 - (title_rect[2]/2), 20))
        screen.blit(player1_text, (screen_width/2 - (player1_rect[2]/2), position1))
        screen.blit(player2_text, (screen_width/2 - (player2_rect[2]/2), position2))
        screen.blit(continue_text, (screen_width/2 - (continue_rect[2]/2), 600))

        #Checks to see if the player count is 4
        if len(bikes) > 2:
            player3_text = text_render("Player 3: Z - Turn Left | X - Slow Bike | C - Turn right", arcade_font, 12, bikes[2].color)
            player4_text = text_render("Player 4: L Arrow - Turn Left | D Arrow - Slow Bike | R Arrow - Turn Right", arcade_font, 11, bikes[3].color)
            player3_rect = player3_text.get_rect()
            player4_rect = player4_text.get_rect()
            screen.blit(player3_text, (screen_width/2 - (player3_rect[2]/2), 400))
            screen.blit(player4_text, (screen_width/2 - (player4_rect[2]/2), 500))

        pygame.display.update()
        clock.tick(FPS)
        pygame.display.set_caption("Game Mode")

def Leader_Board(teams, winnerposition, file):
    global leaderboard
    global namenotassigned
    namenotassigned = True
    while leaderboard:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.type == pygame.QUIT:
                    leaderboard = False
                    pygame.quit()
                    exit()
                if event.key == pygame.K_RETURN:
                    names.pop()
                    highscores.pop()
                    save_data(highscores, names, file)
                    main_menu()

        screen.fill(BLACK)
        title = text_render("LeaderBoard", arcade_font, 50, YELLOW)
        title_rect = title.get_rect()
        screen.blit(title, (screen_width/2 - (title_rect[2]/2), screen_height/60))
        if(teams == 1):
            subtitle = text_render("1 V 1", arcade_font, 40, YELLOW)
            subtitle_rect = subtitle.get_rect()
            screen.blit(subtitle, (screen_width/2 - (subtitle_rect[2]/2), (title_rect[2]/9)))
        elif(teams == 2):
            subtitle = text_render("2 V 2", arcade_font, 40, YELLOW)
            subtitle_rect = subtitle.get_rect()
            screen.blit(subtitle, (screen_width/2 - (subtitle_rect[2]/2), (title_rect[2]/9)))
        elif(teams == 3):
            subtitle = text_render("3 V 1", arcade_font, 40, YELLOW)
            subtitle_rect = subtitle.get_rect()
            screen.blit(subtitle, (screen_width/2 - (subtitle_rect[2]/2), (title_rect[2]/9)))
        elif(teams == 4):
            subtitle = text_render("Free For All", arcade_font, 40, YELLOW)
            subtitle_rect = subtitle.get_rect()
            screen.blit(subtitle, (screen_width/2 - (subtitle_rect[2]/2), (title_rect[2]/9)))

        highscoreLines = []
        highscore_rect = title.get_rect()
        if(len(names) < 11):
            names.insert(winnerposition, "AAA")
        if(len(names) > 11):
            names.pop()
        for x in range(10):
            if(x != 9):
                highscoreLines.append(str(x + 1) + ": " + names[x] + "     " + highscores[x])
            else:
                highscoreLines.append(str(x + 1) + ": " + names[x] + "     " + highscores[x] + " ")

        for x in range(len(highscoreLines)):
            highscore = text_render(highscoreLines[x], arcade_font, 20, YELLOW)
            highscore_rect = highscore.get_rect()
            screen.blit(highscore, (screen_width/2 - (highscore_rect[2]/2), (title_rect[2]/9) + (subtitle_rect[3]) + (highscore_rect[3] * x)))

        letter = ''
        settingNameText = ">A< AA"
        while(namenotassigned):
            if(winnerposition != 10):
                screen.fill(BLACK, (0, 3*screen_height/4, screen_width, screen_height))
                screen.blit(text_render(">", arcade_font, 20, GRID_FG), (screen_width/2 - (highscore_rect[2]/2) - 25,
                                                                (title_rect[2]/9) + (subtitle_rect[3]) + (highscore_rect[3] * winnerposition)))
                settingName = text_render(settingNameText, arcade_font, 40, YELLOW)
                settingName_rect = settingName.get_rect()
                screen.blit(settingName, (screen_width/2 - (settingName_rect[2]/2), (8*screen_height/10)))
                toNextLetter = text_render("Hit enter to lock in the letter", arcade_font, 15, YELLOW)
                toNextLetter_rect = toNextLetter.get_rect()
                screen.blit(toNextLetter, (screen_width/2 - (toNextLetter_rect[2]/2), 9*screen_height/10))
                for event in pygame.event.get():
                    if event.type == pygame.KEYDOWN:
                        if event.type == pygame.QUIT:
                            pygame.quit()
                            exit()
                        if event.key == pygame.K_UP:
                            if(settingNameText.index(">") == 0):
                                letter = settingNameText[1]
                                if(letter == "Z"):
                                    settingNameText = settingNameText.replace(">Z", ">A")

                                else:
                                    letter = chr(ord(letter) + 1)
                                    settingNameText = settingNameText.replace(">" + chr(ord(letter) - 1), ">" + letter)

                            elif(settingNameText.index(">") == 2):
                                letter = settingNameText[3]
                                if(letter == "Z"):
                                    settingNameText = settingNameText.replace(">Z", ">A")

                                else:
                                    letter = chr(ord(letter) + 1)
                                    settingNameText = settingNameText.replace(">" + chr(ord(letter) - 1), ">" + letter)

                            elif(settingNameText.index(">") == 3):
                                letter = settingNameText[4]
                                if(letter == "Z"):
                                    settingNameText = settingNameText.replace(">Z", ">A")

                                else:
                                    letter = chr(ord(letter) + 1)
                                    settingNameText = settingNameText.replace(">" + chr(ord(letter) - 1), ">" + letter)

                        elif event.key == pygame.K_DOWN:
                            if(settingNameText.index(">") == 0):
                                letter = settingNameText[1]
                                if(letter == "A"):
                                    settingNameText = settingNameText.replace(">A", ">Z")

                                else:
                                    letter = chr(ord(letter) - 1)
                                    settingNameText = settingNameText.replace(">" + chr(ord(letter) + 1), ">" + letter)

                            elif(settingNameText.index(">") == 2):
                                letter = settingNameText[3]
                                if(letter == "A"):
                                    settingNameText = settingNameText.replace(">A", ">Z")

                                else:
                                    letter = chr(ord(letter) - 1)
                                    settingNameText = settingNameText.replace(">" + chr(ord(letter) + 1), ">" + letter)

                            elif(settingNameText.index(">") == 3):
                                letter = settingNameText[4]
                                if(letter == "A"):
                                    settingNameText = settingNameText.replace(">A", ">Z")

                                else:
                                    letter = chr(ord(letter) - 1)
                                    settingNameText = settingNameText.replace(">" + chr(ord(letter) + 1), ">" + letter)

                        if event.key == pygame.K_RETURN:
                            if(settingNameText.index(">") == 0):
                                settingNameText = settingNameText.replace(">" + settingNameText[1] + "< A", settingNameText[1] +" >A< ", 1)

                            elif(settingNameText.index(">") == 2):
                                settingNameText = settingNameText.replace(" >" + settingNameText[3] + "< A", settingNameText[3] +" >A<", 1)

                            else:
                                names[winnerposition] = settingNameText[0] + settingNameText[1] + settingNameText[4]
                                namenotassigned = False;
            else:
                namenotassigned = False;
            screen.fill(BLACK, (0, 3*screen_height/4, screen_width, screen_height))
            screen.blit(text_render(">", arcade_font, 20, GRID_FG), (screen_width/2 - (highscore_rect[2]/2) - 25,
                                                            (title_rect[2]/9) + (subtitle_rect[3]) + (highscore_rect[3] * winnerposition)))
            settingName = text_render(settingNameText, arcade_font, 40, YELLOW)
            settingName_rect = settingName.get_rect()
            screen.blit(settingName, (screen_width/2 - (settingName_rect[2]/2), (8*screen_height/10)))
            toNextLetter = text_render("Hit enter to lock in the letter", arcade_font, 15, YELLOW)
            toNextLetter_rect = toNextLetter.get_rect()
            screen.blit(toNextLetter, (screen_width/2 - (toNextLetter_rect[2]/2), 9*screen_height/10))

            pygame.display.update()
            clock.tick(FPS)
            pygame.display.set_caption("LeaderBoard")

        settingName = text_render("Your Score: " + highscores[winnerposition], arcade_font, 35, YELLOW)
        settingName_rect = settingName.get_rect()
        screen.blit(settingName, (screen_width/2 - (settingName_rect[2]/2), 8*screen_height/10))
        toMainMenu = text_render("Hit enter to go to the Main Menu", arcade_font, 15, YELLOW)
        toMainMenu_rect = toMainMenu.get_rect()
        screen.blit(toMainMenu, (screen_width/2 - (toMainMenu_rect[2]/2), 9*screen_height/10))

        pygame.display.update()
        clock.tick(FPS)
        pygame.display.set_caption("LeaderBoard")

def game_run():
    # run while not done
    done = False
    mode_menu = False

    pressed_down = False

    global CLOCK_SPD
    global current_spd
    global duration_timer
    global paused
    global slow_timer
    global endState
    endState = False
    global file
    if(inTeams == 1):
        file = "1v1_leaderboard.txt"
    elif(inTeams == 2):
        file = "2v2_leaderboard.txt"
    elif(inTeams == 3):
        file = "3v1_leaderboard.txt"
    elif(inTeams == 4):
        file = "FFA_leaderboard.txt"
    global highscorezeros
    highscorezeros = ""
    global time
    global finalTimes
    global timerbikes
    timerbikes = bikes.copy()
    finalTimes = [0, 0, 0, 0]
    time = 0
    pygame.time.set_timer(USEREVENT+1, 1000)

    while not done:

        for event in pygame.event.get():
            #increments time every second
            if event.type == USEREVENT+1:
                time += 1
            # click the 'X' to close the window
            if event.type == pygame.QUIT:
                done = True

            # key press events
            if event.type == pygame.KEYDOWN:
                # bike controls
                # press right to turn right
                for bike in bikes:
                    if event.key == bike.right_key:
                        bike.turn(1)
                    elif event.key == bike.slow_key:
                        bike.s_multiplier = 0.4
                        duration_timer = 100
                    elif event.key == bike.left_key:
                        bike.turn(-1)

                # pressing esc also closes the window
                if event.key == pygame.K_ESCAPE:
                    done = True
                    main_menu()

            #Pressing space bar pauses the game
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_SPACE:
                    paused = True

            #Waits for user input to unpause the game
            while paused == True:
                for event in pygame.event.get():
                    if event.type == KEYUP:
                        if event.key == pygame.K_SPACE:
                            paused = False

        # advance the bike in the direction it is goings
        for bike in bikes:
            bike.move()

            # make the bike check if it is 'dead' (see method declaration for more info)
            if bike.check_die(0,  (grid_cell_scl * 2), screen_width, screen_height):
                for timerbike in timerbikes:
                    if(bike.left_key == timerbike.left_key):
                        timerbike.alive = False
                bikes.remove(bike)

            for other in bikes:
                if bike is not other:
                    if bike.phase is not True and bike.color is not other.color:
                        if bike.touches(other) & bike.alive:
                            bike.alive = False
                            for bike in timerbikes:
                                if(bike.left_key == other.left_key):
                                    bike.kills += 1

        delay = 10  # every x seconds, create a powerup
        decidesPowerUp = random.randint(0, 3)
        # Uses a random number to pick a random power up
        if (decidesPowerUp == 1):
            randomPowerUp = pu.PowerUps.Type.SPEED
        elif (decidesPowerUp == 2):
            randomPowerUp = pu.PowerUps.Type.MINE
        elif (decidesPowerUp == 3):
            randomPowerUp = pu.PowerUps.Type.PHASE
        else:
            randomPowerUp = pu.PowerUps.Type.NUKE

        if (pygame.time.get_ticks() % (CLOCK_SPD * delay) == 0):
            powerups.append(pu.PowerUps(screen_width, screen_height, randomPowerUp))

        for powerup in powerups:
            for bike in bikes:
                if (powerup.collides(bike)):
                    if (powerup.type is pu.PowerUps.Type.SPEED or
                        powerup.type is pu.PowerUps.Type.NUKE):
                        pu.PowerUps.apply_to_all(bikes, powerup.type)
                        # After x amount of time, powerup affects disappear
                        duration_timer = 500
                    elif (powerup.type is pu.PowerUps.Type.MINE):
                        p = pu.PowerUps(screen_width, screen_height, pu.PowerUps.Type.ACTUALLY_MINE)
                        p.h *= 2
                        p.w *= 2
                        powerups.append(p)
                    elif (powerup.type is pu.PowerUps.Type.ACTUALLY_MINE):
                        bike.alive = False
                    elif (powerup.type is pu.PowerUps.Type.PHASE):
                        bike.phase = True
                        duration_timer = 500

                    powerups.remove(powerup)

                # Pressing the down key closes the window
                # Starts a timer allowing you to only slow down for a specific amount of time

                # slow_timer -= (1 if slow_timer > 0 else 0)

                # if slow_timer == 0:
                #     bike.s_multiplier = 1
                # if pressed_down:
                #     slow_timer = 500
                #     bike.s_multiplier = .2

                # slow_timer -= (1 if slow_timer > 0 else 0)

                # if slow_timer == 0:
                #     bike.s_multiplier = 1

        duration_timer -= (1 if duration_timer > 0 else 0)
        if duration_timer == 0:
            for x in range(len(bikes)):
                bikes[x].s_multiplier = 1
                bikes[x].phase = False

        # calling the draw method after all the positioning and checking is done
        draw(endState, inTeams)

        # Pause the clock for a frame
        clock.tick(current_spd)

        #check for win
        if(len(bikes) < 4):
            endState = False
            if(len(bikes) == 1):
                endState = True
            elif(len(bikes) == 2):
                if(bikes[0].color == bikes[1].color):
                    endState = True
            elif(len(bikes) == 3):
                if(bikes[0].color == bikes[1].color and bikes[1].color == bikes[2].color):
                    endState = True
        if(endState):
            draw(endState, inTeams)
            winnerhighscore = 0
            killmult = 1
            load_data(file)
            place = 0

            if(inTeams == 2 or inTeams == 3):
                if(timerbikes[0].color == bikes[0].color):
                    if(inTeams == 2):
                        winnerhighscore += finalTimes[0]
                        winnerhighscore += finalTimes[1]
                        killmult += timerbikes[0].kills
                        killmult += timerbikes[1].kills
                        winnerhighscore *= killmult
                        winnerhighscore *= 10
                    else:
                        winnerhighscore += finalTimes[0]
                        winnerhighscore += finalTimes[1]
                        winnerhighscore += finalTimes[2]
                        killmult += timerbikes[0].kills
                        killmult += timerbikes[1].kills
                        killmult += timerbikes[2].kills
                        winnerhighscore *= killmult
                        winnerhighscore *= 10
                else:
                    if(inTeams == 2):
                        winnerhighscore += finalTimes[2]
                        winnerhighscore += finalTimes[3]
                        killmult += timerbikes[2].kills
                        killmult += timerbikes[3].kills
                        winnerhighscore *= killmult
                        winnerhighscore *= 10
                    else:
                        winnerhighscore += finalTimes[3]
                        killmult += timerbikes[3].kills
                        winnerhighscore *= killmult
                        winnerhighscore *= 2
                        winnerhighscore *= 10
            else:
                if(timerbikes[0].left_key == bikes[0].left_key):
                        winnerhighscore += finalTimes[0]
                        killmult += timerbikes[0].kills
                        winnerhighscore *= killmult
                        winnerhighscore *= 10
                elif(timerbikes[1].left_key == bikes[0].left_key):
                        winnerhighscore += finalTimes[1]
                        killmult += timerbikes[1].kills
                        winnerhighscore *= killmult
                        winnerhighscore *= 10
                elif(timerbikes[2].left_key == bikes[0].left_key):
                        winnerhighscore += finalTimes[2]
                        killmult += timerbikes[2].kills
                        winnerhighscore *= killmult
                        winnerhighscore *= 10
                elif(timerbikes[3].left_key == bikes[0].left_key):
                        winnerhighscore += finalTimes[3]
                        killmult += timerbikes[3].kills
                        winnerhighscore *= killmult
                        winnerhighscore *= 10

            for num in range(10 - len(str(winnerhighscore))):
                highscorezeros = highscorezeros + "0"
            winnerscore = highscorezeros + str(winnerhighscore)
            for highscore in highscores:
                if(highscore >= winnerscore):
                    place += 1
            highscores.insert(place, winnerscore)
            print(place)
            print(highscores[10])

            while(endState):
                for event in pygame.event.get():
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_RETURN:
                            print(place)
                            Leader_Board(inTeams, place, file)

# when the loop is done, quit
#Initialize the Game
main_menu()
pygame.quit()
quit()


import wx
import wxFilePy
import database as DB
from datetime import datetime

class MainGui(wxFilePy.MainFrame):
    def __init__(self, parent):
        wxFilePy.MainFrame.__init__(self, parent)
        now = datetime.now()
        date = now.strftime("%A, %d %B %Y")
        self.tanggal.SetLabel(date)
        self.dashboard = DashboardGui(parent=self)
        self.dataKeluarga = DataKeluargaGui(parent=self)
        self.rekomDana = RekomDanaGui(parent=self)
        self.rekapData = RekapDataGui(parent=self)
        self.dashboard.Show()
        self.dataKeluarga.Hide()
        self.rekomDana.Hide()
        self.rekapData.Hide()

    def btn_dashboard_click( self, event ):
        self.dashboard_btn.SetBitmap(wx.Bitmap("picture/btn_pressed_dashboard.png"))
        self.keluarga_btn.SetBitmap(wx.Bitmap("picture/btn_keluarga.png"))
        self.rekom_btn.SetBitmap(wx.Bitmap("picture/btn_rekomen.png"))
        self.rekap_btn.SetBitmap(wx.Bitmap("picture/btn_rekap.png"))
        self.titleMenu.SetLabel("Dashboard")
        self.dashboard.Show()
        self.dataKeluarga.Hide()
        self.rekomDana.Hide()
        self.rekapData.Hide()

        if self.dashboard.keluargaRendah.GetNumberRows() > 0:
            self.dashboard.keluargaRendah.DeleteRows(pos=0, numRows=self.dashboard.keluargaRendah.GetNumberRows())

        lowData = DB.dataKeluarga().lowerTotal()
        count = 0
        for row in lowData:
            self.dashboard.keluargaRendah.AppendRows(1)
            self.dashboard.keluargaRendah.SetRowSize(count, 30)
            self.dashboard.keluargaRendah.SetColSize(0, 280)
            self.dashboard.keluargaRendah.SetColSize(1, 100)
            self.dashboard.keluargaRendah.SetCellAlignment(count, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
            self.dashboard.keluargaRendah.SetCellValue(count, 0, row[1])
            self.dashboard.keluargaRendah.SetCellValue(count, 1, f"Rp{row[3]}")
            count += 1

        if self.dashboard.bantuanBaru.GetNumberRows() > 0:
            self.dashboard.bantuanBaru.DeleteRows(pos=0, numRows=self.dashboard.bantuanBaru.GetNumberRows())

        data = DB.rekap().newestData()
        count = 0
        for row in range(len(data[0])):
            self.dashboard.bantuanBaru.AppendRows(1)
            self.dashboard.bantuanBaru.SetRowSize(count, 30)
            self.dashboard.bantuanBaru.SetColSize(0, 280)
            self.dashboard.bantuanBaru.SetColSize(1, 100)
            self.dashboard.bantuanBaru.SetCellAlignment(count, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
            self.dashboard.bantuanBaru.SetCellValue(count, 0, data[0][row][0][0])
            self.dashboard.bantuanBaru.SetCellValue(count, 1, f"Rp{data[1][row][2]}")
            count += 1

    def btn_keluarga_click( self, event ):
        self.keluarga_btn.SetBitmap(wx.Bitmap("picture/btn_pressed_keluarga.png"))
        self.dashboard_btn.SetBitmap(wx.Bitmap("picture/btn_dashboard.png"))
        self.rekom_btn.SetBitmap(wx.Bitmap("picture/btn_rekomen.png"))
        self.rekap_btn.SetBitmap(wx.Bitmap("picture/btn_rekap.png"))
        self.titleMenu.SetLabel("Data Keluarga")
        self.dataKeluarga.Show()
        self.dataKeluarga.filterSatu.SetSelection(0)
        self.dataKeluarga.filterDua.Hide()
        self.dataKeluarga.filterDua.SetSelection(0)
        self.dataKeluarga.filterValue.Hide()
        self.dataKeluarga.filterValue.SetValue("")
        self.dashboard.Hide()
        self.rekomDana.Hide()
        self.rekapData.Hide()

        lenCols = self.dataKeluarga.dataKeluargaGrid.GetNumberCols()

        if self.dataKeluarga.dataKeluargaGrid.GetNumberRows() > 0:
            self.dataKeluarga.dataKeluargaGrid.DeleteRows(pos=0, numRows=self.dataKeluarga.dataKeluargaGrid.GetNumberRows())
        data = DB.dataKeluarga().showKeluarga()
        count = 0
        for row in data:
            noKK, kepalaKeluarga, anggotaKeluarga, totalPendapatan, alamat = row
            self.dataKeluarga.dataKeluargaGrid.AppendRows(1)
            self.dataKeluarga.dataKeluargaGrid.SetRowSize(count, 30)
            for col in range(lenCols):
                self.dataKeluarga.dataKeluargaGrid.SetColSize(col, 162)
                self.dataKeluarga.dataKeluargaGrid.SetCellAlignment(count, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)
            self.dataKeluarga.dataKeluargaGrid.SetCellValue(count, 0, f"{noKK}")
            self.dataKeluarga.dataKeluargaGrid.SetCellValue(count, 1, kepalaKeluarga)
            self.dataKeluarga.dataKeluargaGrid.SetCellValue(count, 2, f"{anggotaKeluarga}")
            self.dataKeluarga.dataKeluargaGrid.SetCellValue(count, 3, f"Rp{totalPendapatan}")
            self.dataKeluarga.dataKeluargaGrid.SetCellValue(count, 4, alamat)
            count += 1

    def btn_rekom_click( self, event ):
        self.rekom_btn.SetBitmap(wx.Bitmap("picture/btn_pressed_rekomen.png"))
        self.dashboard_btn.SetBitmap(wx.Bitmap("picture/btn_dashboard.png"))
        self.keluarga_btn.SetBitmap(wx.Bitmap("picture/btn_keluarga.png"))
        self.rekap_btn.SetBitmap(wx.Bitmap("picture/btn_rekap.png"))
        self.titleMenu.SetLabel("Rekomendasi Dana")
        self.rekomDana.Show()
        self.rekomDana.umrInput.SetValue("")
        self.rekomDana.rekomGrid.Hide()
        self.dashboard.Hide()
        self.dataKeluarga.Hide()
        self.rekapData.Hide()

    def btn_rekap_click( self, event ):
        self.rekap_btn.SetBitmap(wx.Bitmap("picture/btn_pressed_rekap.png"))
        self.dashboard_btn.SetBitmap(wx.Bitmap("picture/btn_dashboard.png"))
        self.keluarga_btn.SetBitmap(wx.Bitmap("picture/btn_keluarga.png"))
        self.rekom_btn.SetBitmap(wx.Bitmap("picture/btn_rekomen.png"))
        self.titleMenu.SetLabel("Rekap Bantuan")
        self.rekapData.Show()
        self.dashboard.Hide()
        self.dataKeluarga.Hide()
        self.rekomDana.Hide()
        self.rekapData.rekapOption.Show()
        self.rekapData.riwayatBantuan.Hide()

    def searchEnter( self, event ):
        noKK = self.searchEngine.GetValue()
        if DB.dataKeluarga().searchDetailKeluarga(noKK):
            searchModal(parent=self, noKK=noKK).Show()
        else:
            wx.MessageBox("Data yang Anda Masukkan Tidak Ada!", "KESALAHAN")

class DashboardGui(wxFilePy.dashboardPanel):
    def __init__(self, parent):
        wxFilePy.dashboardPanel.__init__(self, parent)

        lowData = DB.dataKeluarga().lowerTotal()
        count = 0
        for row in lowData:
            self.keluargaRendah.AppendRows(1)
            self.keluargaRendah.SetRowSize(count, 30)
            self.keluargaRendah.SetColSize(0, 280)
            self.keluargaRendah.SetColSize(1, 100)
            self.keluargaRendah.SetCellAlignment(count, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
            self.keluargaRendah.SetCellValue(count, 0, row[1])
            self.keluargaRendah.SetCellValue(count, 1, f"Rp{row[3]}")
            count += 1

        data = DB.rekap().newestData()
        count = 0
        for row in range(len(data[0])):
            self.bantuanBaru.AppendRows(1)
            self.bantuanBaru.SetRowSize(count, 30)
            self.bantuanBaru.SetColSize(0, 280)
            self.bantuanBaru.SetColSize(1, 100)
            self.bantuanBaru.SetCellAlignment(count, 1, wx.ALIGN_RIGHT, wx.ALIGN_CENTER)
            self.bantuanBaru.SetCellValue(count, 0, data[0][row][0][0])
            self.bantuanBaru.SetCellValue(count, 1, f"Rp{data[1][row][2]}")
            count += 1

class DataKeluargaGui(wxFilePy.dataKeluargaPanel):
    def __init__(self, parent):
        wxFilePy.dataKeluargaPanel.__init__(self, parent)
        self.lenCols = self.dataKeluargaGrid.GetNumberCols()

    def filterOneSelected( self, event ):
        self.filterValue.SetValue("")
        value = self.filterSatu.GetSelection()
        if value == 0:
            self.filterDua.Hide()
            self.filterValue.Hide()
            if self.dataKeluargaGrid.GetNumberRows() > 0:
                self.dataKeluargaGrid.DeleteRows(pos=0, numRows=self.dataKeluargaGrid.GetNumberRows())
            data = DB.dataKeluarga().showKeluarga()
            count = 0
            for row in data:
                noKK, kepalaKeluarga, anggotaKeluarga, totalPendapatan, alamat = row
                self.dataKeluargaGrid.AppendRows(1)
                self.dataKeluargaGrid.SetRowSize(count, 30)
                for col in range(self.lenCols):
                    self.dataKeluargaGrid.SetColSize(col, 162)
                    self.dataKeluargaGrid.SetCellAlignment(count, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)
                self.dataKeluargaGrid.SetCellValue(count, 0, f"{noKK}")
                self.dataKeluargaGrid.SetCellValue(count, 1, kepalaKeluarga)
                self.dataKeluargaGrid.SetCellValue(count, 2, f"{anggotaKeluarga}")
                self.dataKeluargaGrid.SetCellValue(count, 3, f"Rp{totalPendapatan}")
                self.dataKeluargaGrid.SetCellValue(count, 4, alamat)
                count += 1

        else:
            self.filterDua.Show()
            self.filterDua.SetSelection(0)
            self.filterValue.Show()

    def filterValueChange( self, event ):
        if self.filterValue.GetValue():
            if self.dataKeluargaGrid.GetNumberRows() > 0:
                self.dataKeluargaGrid.DeleteRows(pos=0, numRows=self.dataKeluargaGrid.GetNumberRows())

        value = self.filterSatu.GetSelection()
        if value == 1 and self.filterValue.GetValue():
            if self.filterDua.GetSelection() == 0:
                filterVal = self.filterValue.GetValue()
                data = DB.dataKeluarga().readByTotalAbove(filterVal)
                count = 0
                for row in data:
                    noKK, kepalaKeluarga, anggotaKeluarga, totalPendapatan, alamat = row
                    self.dataKeluargaGrid.AppendRows(1)
                    self.dataKeluargaGrid.SetRowSize(count, 30)
                    for col in range(self.lenCols):
                        self.dataKeluargaGrid.SetColSize(col, 162)
                        self.dataKeluargaGrid.SetCellAlignment(count, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)
                    self.dataKeluargaGrid.SetCellValue(count, 0, f"{noKK}")
                    self.dataKeluargaGrid.SetCellValue(count, 1, kepalaKeluarga)
                    self.dataKeluargaGrid.SetCellValue(count, 2, f"{anggotaKeluarga}")
                    self.dataKeluargaGrid.SetCellValue(count, 3, f"Rp{totalPendapatan}")
                    self.dataKeluargaGrid.SetCellValue(count, 4, alamat)
                    count += 1

            elif self.filterDua.GetSelection() == 1:
                filterVal = self.filterValue.GetValue()
                data = DB.dataKeluarga().readByTotalBelow(filterVal)
                count = 0
                for row in data:
                    noKK, kepalaKeluarga, anggotaKeluarga, totalPendapatan, alamat = row
                    self.dataKeluargaGrid.AppendRows(1)
                    self.dataKeluargaGrid.SetRowSize(count, 30)
                    for col in range(self.lenCols):
                        self.dataKeluargaGrid.SetColSize(col, 162)
                        self.dataKeluargaGrid.SetCellAlignment(count, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)
                    self.dataKeluargaGrid.SetCellValue(count, 0, str(noKK))
                    self.dataKeluargaGrid.SetCellValue(count, 1, kepalaKeluarga)
                    self.dataKeluargaGrid.SetCellValue(count, 2, str(anggotaKeluarga))
                    self.dataKeluargaGrid.SetCellValue(count, 3, str(totalPendapatan))
                    self.dataKeluargaGrid.SetCellValue(count, 4, alamat)
                    count += 1

        elif value == 2 and self.filterValue.GetValue():
            if self.filterDua.GetSelection() == 0:
                filterVal = self.filterValue.GetValue()
                data = DB.dataKeluarga().readByAnggotaAbove(filterVal)
                count = 0
                for row in data:
                    noKK, kepalaKeluarga, anggotaKeluarga, totalPendapatan, alamat = row
                    self.dataKeluargaGrid.AppendRows(1)
                    self.dataKeluargaGrid.SetRowSize(count, 30)
                    for col in range(self.lenCols):
                        self.dataKeluargaGrid.SetColSize(col, 162)
                        self.dataKeluargaGrid.SetCellAlignment(count, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)
                    self.dataKeluargaGrid.SetCellValue(count, 0, str(noKK))
                    self.dataKeluargaGrid.SetCellValue(count, 1, kepalaKeluarga)
                    self.dataKeluargaGrid.SetCellValue(count, 2, str(anggotaKeluarga))
                    self.dataKeluargaGrid.SetCellValue(count, 3, str(totalPendapatan))
                    self.dataKeluargaGrid.SetCellValue(count, 4, alamat)
                    count += 1

            elif self.filterDua.GetSelection() == 1:
                filterVal = self.filterValue.GetValue()
                data = DB.dataKeluarga().readByAnggotaBelow(filterVal)
                count = 0
                for row in data:
                    noKK, kepalaKeluarga, anggotaKeluarga, totalPendapatan, alamat = row
                    self.dataKeluargaGrid.AppendRows(1)
                    self.dataKeluargaGrid.SetRowSize(count, 30)
                    for col in range(self.lenCols):
                        self.dataKeluargaGrid.SetColSize(col, 162)
                        self.dataKeluargaGrid.SetCellAlignment(count, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)
                    self.dataKeluargaGrid.SetCellValue(count, 0, str(noKK))
                    self.dataKeluargaGrid.SetCellValue(count, 1, kepalaKeluarga)
                    self.dataKeluargaGrid.SetCellValue(count, 2, str(anggotaKeluarga))
                    self.dataKeluargaGrid.SetCellValue(count, 3, str(totalPendapatan))
                    self.dataKeluargaGrid.SetCellValue(count, 4, alamat)
                    count += 1

    def btn_tambahData( self, event ):
        addModal(parent=self).ShowModal()

    def btn_ubahData( self, event ):
        changeModal(parent=self).ShowModal()

    def btn_hapusData( self, event ):
        delModal(parent=self).ShowModal()

class addModal(wxFilePy.addData):
    def __init__(self, parent):
        wxFilePy.addData.__init__(self, parent)

    def btn_addKeluarga( self, event ):
        noKK = self.nomorKK.GetValue()
        kepalaKeluarga = self.kepKeluarga.GetValue()
        anggota = self.jumAnggota.GetValue()
        total = self.totalPendapatan.GetValue()
        alamat = self.alamatBaru.GetValue()
        nikKep = self.nikKepala.GetValue()
        insert = DB.anggotaKeluarga().addKeluarga(noKK, kepalaKeluarga, anggota, total, alamat, nikKep)
        if insert:
            wx.MessageBox("Data Berhasil Ditambahkan!", "INFORMASI")
        else:
            wx.MessageBox("Data yang Anda Masukkan Sudah Ada atau \n Form Tidak Boleh Kosong", "KESALAHAN")

class changeModal(wxFilePy.changeData):
    def __init__(self, parent):
        wxFilePy.changeData.__init__(self, parent)
        self.ubahNotebook.SetPageText(0, "Anggota Keluarga")
        self.ubahNotebook.SetPageText(1, "Total Pendapatan")
        self.ubahNotebook.SetPageText(2, "Alamat")

    def btn_ubahAnggota( self, event ):
        noKK = self.nomorKK_anggota.GetValue()
        nama = self.namaAnggota.GetValue()
        nik = self.nikAnggota.GetValue()
        insert = DB.anggotaKeluarga().setAnggota(nik, nama, noKK)
        if insert:
            DB.anggotaKeluarga().updateAnggota(noKK)
            wx.MessageBox("Data Berhasil Ditambahkan!", "INFORMASI")
        else:
            wx.MessageBox("Nomor KK Tidak Ditemukan atau \n NIK Sudah Ada atau \n Form Tidak Boleh Kosong", "KESALAHAN")

    def btn_ubahTotal( self, event ):
        noKK = self.nomorKK_total.GetValue()
        total = self.totalBaru.GetValue()
        insert = DB.dataKeluarga().updateTotalPendapatan(noKK, total)
        if insert:
            wx.MessageBox("Data Berhasil Diubah!", "INFORMASI")
        else:
            wx.MessageBox("Nomor KK Tidak Ditemukan atau \n Form Tidak Boleh Kosong", "KESALAHAN")

    def btn_ubahAlamat( self, event ):
        noKK = self.nomorKK_alamat.GetValue()
        alamat = self.alamatBaru.GetValue()
        insert = DB.dataKeluarga().updateAlamat(noKK, alamat)
        if insert:
            wx.MessageBox("Data Berhasil Diubah!", "INFORMASI")
        else:
            wx.MessageBox("Nomor KK Tidak Ditemukan atau \n Form Tidak Boleh Kosong", "KESALAHAN")

class delModal(wxFilePy.delData):
    def __init__(self, parent):
        wxFilePy.delData.__init__(self, parent)
        self.delNotebook.SetPageText(0, "Data Keluarga")
        self.delNotebook.SetPageText(1, "Anggota Keluarga")

    def btn_delKeluarga( self, event ):
        noKK = self.nomorKK_keluarga.GetValue()
        insert = DB.dataKeluarga().delKeluarga(noKK)
        if insert:
            wx.MessageBox("Data Berhasil Dihapus!", "INFORMASI")
        else:
            wx.MessageBox("Nomor KK Tidak Ditemukan atau \n Form Tidak Boleh Kosong", "KESALAHAN")

    def btn_delAnggota( self, event ):
        noKK = self.nomorKK_anggota.GetValue()
        nik = self.nikAnggota.GetValue()
        insert = DB.anggotaKeluarga().delAnggota(noKK, nik)
        if insert:
            wx.MessageBox("Data Berhasil Dihapus!", "INFORMASI")
        else:
            wx.MessageBox("Nomor KK atau NIK Tidak Ditemukan atau \n Form Tidak Boleh Kosong", "KESALAHAN")

class RekomDanaGui(wxFilePy.rekomDanaPanel):
    def __init__(self, parent):
        wxFilePy.rekomDanaPanel.__init__(self, parent)

    def umrChange( self, event ):
        if self.rekomGrid.GetNumberRows() > 0:
            self.rekomGrid.DeleteRows(pos=0, numRows=self.rekomGrid.GetNumberRows())
        lenCols = self.rekomGrid.GetNumberCols()
        umrValue = self.umrInput.GetValue()
        data = DB.bantuan().analyze(umrValue)
        if data:
            self.rekomGrid.Show()
            count = 0
            for row in range(len(data[0])):
                self.rekomGrid.AppendRows(1)
                self.rekomGrid.SetRowSize(count, 30)
                for col in range(lenCols):
                    self.rekomGrid.SetColSize(col, 205)
                    self.rekomGrid.SetCellAlignment(count, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)
                self.rekomGrid.SetCellValue(count, 0, f"{data[0][row][0]}")
                self.rekomGrid.SetCellValue(count, 1, data[0][row][1])
                self.rekomGrid.SetCellValue(count, 2, data[0][row][4])
                self.rekomGrid.SetCellValue(count, 3, f"Rp{data[1][row]}")
                self.rekomGrid.SetCellFont(count, 3, wx.Font(14, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, "Roboto"))
                count += 1

class RekapDataGui(wxFilePy.rekapDataPanel):
    def __init__(self, parent):
        wxFilePy.rekapDataPanel.__init__(self, parent)

    def catatBantuan_btn( self, event ):
        catatModal(parent=self).ShowModal()

    def riwayatBantuan_btn( self, event ):
        self.riwayatBantuan.Show()
        self.riwayatBantuan.Enable()
        self.rekapOption.Hide()
        lenCols = self.rekapGrid.GetNumberCols()
        if self.rekapGrid.GetNumberRows() > 0:
            self.rekapGrid.DeleteRows(pos=0, numRows=self.rekapGrid.GetNumberRows())
        data = DB.rekap().riwayatBantuan()
        if data:
            count = 0
            for row in range(len(data[0])):
                self.rekapGrid.AppendRows(1)
                self.rekapGrid.SetRowSize(count, 30)
                for col in range(lenCols):
                    self.rekapGrid.SetColSize(col, 205)
                    self.rekapGrid.SetCellAlignment(count, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)
                self.rekapGrid.SetCellValue(count, 0, f"{data[1][row][1]}")
                self.rekapGrid.SetCellValue(count, 1, data[0][row][0][0])
                self.rekapGrid.SetCellValue(count, 2, f"Rp{data[1][row][2]}")
                self.rekapGrid.SetCellValue(count, 3, data[1][row][3])
                count += 1

class catatModal(wxFilePy.catatData):
    def __init__(self, parent):
        wxFilePy.catatData.__init__(self, parent)

    def addCatat_btn( self, event ):
        noKK = self.nomorKK.GetValue()
        dana = self.danaBeri.GetValue()
        insert = DB.rekap().catatBantuan(noKK, dana)
        if insert:
            wx.MessageBox("Data Berhasil Ditambahkan!", "INFORMASI")
        else:
            wx.MessageBox("Nomor KK Tidak Ditemukan atau \n Form Tidak Boleh Kosong", "KESALAHAN")

class searchModal(wxFilePy.searchData):
    def __init__(self, parent, noKK):
        wxFilePy.searchData.__init__(self, parent)
        data = DB.dataKeluarga().searchDetailKeluarga(noKK)
        for x in data[0]:
            nomorKK, kepala, anggota, total, alamat = x
            self.nomorKK.SetLabel(f"{nomorKK}")
            self.kepKeluarga.SetLabel(kepala)
            self.anggota.SetLabel(f"{anggota}")
            self.total.SetLabel(f"Rp{total}")
            self.alamat.SetLabel(alamat)

        if self.searchGrid.GetNumberRows() > 0:
            self.searchGrid.DeleteRows(pos=0, numRows=self.searchGrid.GetNumberRows())

        lenCols = self.searchGrid.GetNumberCols()

        count = 0
        for y in data[1]:
            nik, nama, nokk = y
            self.searchGrid.AppendRows(1)
            self.searchGrid.SetRowSize(count, 30)
            for col in range(lenCols):
                self.searchGrid.SetColSize(col, 320)
                self.searchGrid.SetCellAlignment(count, col, wx.ALIGN_LEFT, wx.ALIGN_CENTER)
            self.searchGrid.SetCellValue(count, 0, f"{nik}")
            self.searchGrid.SetCellValue(count, 1, nama)
            count += 1

app = wx.App()
frame = MainGui(parent=None)
frame.Show()
app.MainLoop()
DB.Database().close()


from pprint import pprint
from nltk.corpus import framenet as fn
import nltk
import xml.dom.minidom as DM
import xml.etree.ElementTree as ET
from xml.etree import ElementTree
from xml.etree.ElementTree import tostring
import os
import zipfile2
import lxml.etree as etree

path = ('/Users/mac/Desktop/fndata-1.7/fulltext')
def metapFilter(path):
    metap_list = [None] * 1
    item = ET.Element("FBL")
    ET.SubElement(item, 'Source').text = 'Metaphor_label'

    for filename in os.listdir(path):
        if not filename.endswith('.xml'):
            continue
        fullname = os.path.join(path, filename)
        tree_0 = ET.parse(fullname)
        tree_1 = tree_0.getroot()
        t = tostring(tree_1)
        t = t.lower()
        tree_2 = ET.fromstring(t)
        for sentence in tree_2:
            for annot in sentence.iter():  # text, annotationSet
                for x, y in annot.attrib.items():

                    if y == 'metaphor':
                        print('Metaphor filter:')
                        print(sentence[0].text)
                        metap_list.append(sentence[0].text)
                        metap_list.append('--------------')
                        annot.append(item)
                        print(filename)

        filename = open('/Users/mac/Desktop/metaphor_label/'+filename, "w")
        filename.write(ET.tostring(tree_2, encoding="unicode"))

def main():
    metapFilter(path)

if __name__ == "__main__":
    main()


import bpy, bmesh
obj = bpy.context.active_object

if obj.mode == 'EDIT':
    bm = bmesh.from_edit_mesh(obj.data)
    vertices = bm.verts

else:
    vertices = obj.data.vertices

print(obj)
verts = [obj.matrix_world @ vert.co for vert in vertices]

# coordinates as tuples
plain_verts = [vert.to_tuple() for vert in verts]
print(len(plain_verts))


import cv2
import sys
import time
import os
import rospy
import numpy as np
from datetime import datetime
from collections import namedtuple
from digit_device import Device
import multiprocessing as mp
from test_hd.msg import state
from get_height.msg import Odometer_result
from get_height.msg import Height

class Odometer:
    R, R_sum, R_selected = np.eye(2), np.eye(2), np.eye(2)
    T, T_sum, T_selected = np.zeros((2,)), np.zeros((2,)), np.zeros((2,))
    is_visualize = True
    is_plot = True
    is_report = False
    is_ros = True
    is_gpu = False

    R_log, T_log = [], []

    def __init__(self):
        border = 0
        self.roi = [0 + border, 240 - border, 0 + border, 320 - border]
        self.feature_params = dict(maxCorners=100, qualityLevel=0.5, minDistance=5, blockSize=2)
        self.lk_params = dict(
            winSize=(20, 20), maxLevel=4, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 1, 0.03)
        )
        self.cms = "Odometer_Init"

    def __ros_callback(self, data):
        self.cms = data.state

    def __ros_listener(self):
        rospy.Subscriber("Cloth_Maipulation_State", state, self.__ros_callback)

    def __ros_publisher(self, height):
        pub = rospy.Publisher("current_height", Height, queue_size=10)
        pub_2 = rospy.Publisher("odometer_result", Odometer_result, queue_size=10)
        rospy.init_node("odometer", anonymous=True)
        rate = rospy.Rate(30)
        while not rospy.is_shutdown():
            rospy.loginfo(f"Odometer | Publishing current height {height.value}")
            pub.publish(height.value)
            rospy.loginfo(f"Odometer | Publishing odometer result {self.T_shared}")
            pub_2.publish([self.T_shared[0], self.T_shared[1]])
            rate.sleep()

    def crop_anything(self, thing, roi):
        return thing[roi[0] : roi[1], roi[2] : roi[3]]

    def reg_svd(self, A, B):
        centroid_A = np.mean(A, axis=0)
        centroid_B = np.mean(B, axis=0)
        AA = A - centroid_A
        BB = B - centroid_B
        H = np.dot(AA.T, BB)
        U, S, Vt = np.linalg.svd(H)
        R = np.dot(Vt.T, U.T)
        if np.linalg.det(R) < 0:
            Vt[1, :] *= -1
            R = np.dot(Vt.T, U.T)
        T = centroid_B.T - np.dot(R, centroid_A.T)
        return R, T

    def odometer(self, frame_queue, result_queue, visualize_queue, T_shared):
        if self.is_plot:
            import matplotlib.pyplot as plt
            import matplotlib.patches as patches

            fig, ax = plt.subplots(figsize=(10, 10), num="Odometer | View Port")
            plt.title("Odometer | View Port")
            plt.xlabel("Pixels")
            plt.ylabel("Pixels")
            ax.set_xlim([-500, 500])
            ax.set_ylim([-500, 500])
            rect_cloth = patches.Rectangle((-400, -400), 800, 800, color="green")
            rect_gelsight = patches.Rectangle((-74, -90), 147, 180, alpha=0.5, color="red", rotation_point="center")
            ax.add_patch(rect_cloth)
            ax.add_patch(rect_gelsight)

        from gelsight import gs3drecon  # import outside will cause error

        model_file_path = "/home/ratiomiith/Development/DigitCloth/ros_workspace/src/get_height/scripts/"
        net_file_path = "nnmini.pt"
        net_path = os.path.join(model_file_path, net_file_path)

        gpuorcpu = "cuda" if self.is_gpu else "cpu"

        Device_Alias = namedtuple("GelSightMini", ["imgw", "imgh"])  # gelsight sdk requires this
        dev_alias = Device_Alias(240, 320)
        nn = gs3drecon.Reconstruction3D(gs3drecon.Finger.R15, dev_alias)
        nn.load_nn(net_path, gpuorcpu)

        frame_count = 0

        try:
            while True:
                tic = time.time()

                frame = frame_queue.get()
                frame_count += 1
                depthmap = nn.get_depthmap(frame, mask_markers=False)
                frame = self.crop_anything(frame, self.roi)  # Discard the Markers area
                gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                if frame_count < 60:
                    prev_gray = gray
                    prev_corners = None
                    continue

                depth_mask = np.zeros_like(depthmap, dtype=np.uint8)
                depth_mask[depthmap < -1.5] = 1
                depth_mask = self.crop_anything(depth_mask, self.roi)

                contact_check = np.sum(depth_mask)
                self.contact_check.value = contact_check

                if (
                    contact_check != 0 and prev_corners is None
                ):  # Set current frame as previous frame if contact is detected
                    prev_corners = cv2.goodFeaturesToTrack(prev_gray, mask=depth_mask, **self.feature_params)
                    prev_gray = gray
                elif contact_check != 0 and prev_corners is not None and len(prev_corners) > 2:
                    # Do odometer
                    curr_corners, _, _ = cv2.calcOpticalFlowPyrLK(prev_gray, gray, prev_corners, None, **self.lk_params)
                    curr_corners = curr_corners.squeeze()
                    prev_corners = prev_corners.squeeze()

                    # Registartion
                    R, T = self.reg_svd(prev_corners, curr_corners)

                    self.R_sum = np.matmul(self.R_sum, R)
                    self.T_sum = self.T_sum + T
                    T_shared[0] = self.T_sum[0]
                    T_shared[1] = self.T_sum[1]

                    if self.cms == "turnL_clock":
                        self.R_selected = np.matmul(self.R_selected, R)
                        self.T_selected = self.T_selected + T

                    if self.is_visualize:
                        self.visualize(frame, prev_corners, curr_corners, depth_mask, visualize_queue)
                    if self.is_plot:
                        # T_scaled = self.T_sum / 17.13  # T_sum counts in pixel, Visualize in mm
                        rect_gelsight.set_angle(np.rad2deg(np.arctan2(self.R_sum[1, 0], self.R_sum[0, 0])))
                        rect_gelsight.set_xy((-74 - self.T_sum[1], -90 - self.T_sum[0]))
                        center_gelsight = rect_gelsight.get_center()
                        # ax.scatter(center_gelsight[0], center_gelsight[1], s=2, c="yellow")  # This causes slow down
                        plt.pause(0.001)

                    prev_corners = cv2.goodFeaturesToTrack(prev_gray, mask=depth_mask, **self.feature_params)
                    prev_gray = gray
                else:
                    prev_corners = None

                packed_results = {"Process": "Odometer", "R": self.R_sum, "T": self.T_sum}
                result_queue.put(packed_results)

                sys.stdout.write(f"FPS: {1/(time.time()-tic):.2f}, Contact Check: {contact_check}, T: {self.T_sum}\r")
        except KeyboardInterrupt:
            print("Odometer | KeyboardInterrupt")

    def visualize(self, frame, prev_corners, curr_corners, depth_mask, output_queue=None):
        canvas = np.zeros_like(frame)
        for i, (new, old) in enumerate(zip(curr_corners, prev_corners)):
            a, b = new.ravel()
            c, d = old.ravel()
            a, b, c, d = int(a), int(b), int(c), int(d)
            cv2.line(canvas, (a, b), (c, d), (0, 255, 0), 2)
            cv2.circle(canvas, (a, b), 5, (0, 0, 255), -1)
        frame_masked = frame.copy()
        frame_masked[depth_mask != 1] = [0, 0, 0]
        result = cv2.add(frame_masked, canvas)

        packed_frames = {
            "Process": "Odometer",
            "result": result,
        }
        output_queue.put(packed_frames)

    def run(self, frame_queue, result_queue, visualize_queue):
        self.processes = []
        manager = mp.Manager()
        self.T_shared = manager.Array("d", [0, 0])  # Shared memory for T
        self.contact_check = manager.Value("d", 0)  # Shared memory for contact check

        if self.is_ros:
            self.processes.append(mp.Process(target=self.__ros_listener))
            self.processes.append(mp.Process(target=self.__ros_publisher, args=(self.contact_check,)))
        self.processes.append(
            mp.Process(target=self.odometer, args=(frame_queue, result_queue, visualize_queue, self.T_shared))
        )

        [p.start() for p in self.processes]

    def save(self):
        self.T_log.append(np.array(self.T_shared))
        sys.stdout.write(f"\nSaved T: {self.T_shared}")

    def stop(self):
        [p.terminate() for p in self.processes]

def main():
    gsmini = Device()
    odometer = Odometer()

    frame_queue = mp.Queue()
    result_queue = mp.Queue()
    visualize_queue = mp.Queue()

    gsmini.run(frame_queue)
    odometer.run(frame_queue, result_queue, visualize_queue)

    time = datetime.now()

    # Visualize
    try:
        while True:
            # packed_results = result_queue.get()
            packed_frames = visualize_queue.get()
            if packed_frames["Process"] == "Odometer":
                cv2.imshow("Odometer | Tracking", packed_frames["result"])
                odometer.save()

            getKey = cv2.waitKey(1)
            if getKey & 0xFF == ord("q"):
                break
            elif getKey == 32:  # Spacebar
                odometer.save()
    finally:
        gsmini.stop()
        odometer.stop()
        time_str = time.strftime("%Y%m%d-%H%M%S")
        np.save("output/T_log_exp_odometer_" + time_str + ".npy", odometer.T_log)

if __name__ == "__main__":
    main()

{'plt': 'matplotlib.pyplot', 'patches': 'matplotlib.patches', 'gs3drecon': 'gelsight.gs3drecon'}


import torch
import torchvision
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms

model = torchvision.models.segmentation.deeplabv3_resnet101(pretrained=True)
model.eval()

# get image from the data-animalpose/images/train/ directory
image = Image.open('../output/cropped_3_0.jpg')

transform = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

# Convert cropped_image to a PyTorch tensor and normalize
input_tensor = transform(image)
input_tensor = input_tensor.unsqueeze(0)

output = model(input_tensor)['out']

# Convert output to a binary mask (assuming the animal class is 1)
mask = torch.argmax(output, dim=1) == 1
foreground = input_tensor * mask.numpy()

# Save the cropped image
plt.imsave('test.jpg', foreground)
# save the output
plt.imsave('output.jpg', output[0, 1, :, :].detach().numpy())


import re
import sys
import time

from PyQt5 import QtCore, QtWidgets
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox, QWidget, QSizePolicy, QSlider, QLabel
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from PyQt5.QtDataVisualization import Q3DBars, QBar3DSeries, QValue3DAxis, QCategory3DAxis, QAbstract3DSeries, \
    QAbstract3DGraph, Q3DCamera, QBarDataItem
import main_UI
import begin_UI
import numpy as np
from PyQt5.QtCore import QThread, pyqtSignal, Qt, QSize, QTimer
import serial
import serial.tools.list_ports

# 串口列表获取线程
class Find_port(QThread):
    '''
    寻找串口线程
    '''
    port_change = pyqtSignal()

    def __init__(self):
        super(Find_port, self).__init__()
        self.old = list(serial.tools.list_ports.comports())

    def run(self):
        while True:
            port_list = list(serial.tools.list_ports.comports())
            if port_list != self.old:
                self.old = port_list
                self.port_change.emit()
                QThread.msleep(1000)

# 获取串口数据线程
class Read_data_1(QThread):
    changeforce = pyqtSignal(int, int)
    '''
    子进程，用于读取数据
    '''
    def __init__(self, port):
        super(Read_data_1, self).__init__()
        self.port = port
        self.old = np.array(re.findall('\d+', str(self.port.readline()))).astype(int)

    def run(self):
        while True:
            # self.dat
            data = str(self.port.readline())
            # print(data, type(data))
            # print(re.findall('\d+', data))
            self.data = np.array(re.findall('\d+', data))
            self.data = self.data.astype(int)
            # print(self.data)
            for i in range(5):
                if self.data[i] != self.old[i]:
                    changevalue = self.data[i] - self.old[i]
                    self.changeforce.emit(i, changevalue)
        pass

class Read_data_2(QThread):
    changeforce = pyqtSignal(int, int)
    '''
    子进程，用于读取数据
    '''
    def __init__(self, port):
        super(Read_data_2, self).__init__()
        self.port = port
        self.old = np.array(re.findall('\d+', str(self.port.readline()))).astype(int)

    def run(self):
        while True:
            # self.dat
            data = str(self.port.readline())
            # print(data, type(data))
            # print(re.findall('\d+', data))
            self.data = np.array(re.findall('\d+', data))
            self.data = self.data.astype(int)
            # print(self.data)
            for i in range(5):
                if self.data[i] != self.old[i]:
                    changevalue = self.data[i] - self.old[i]
                    self.changeforce.emit(i, changevalue)
        pass

class Read_data_3(QThread):
    changeforce = pyqtSignal(int, int)
    '''
    子进程，用于读取数据
    '''
    def __init__(self, port):
        super(Read_data_3, self).__init__()
        self.port = port
        self.old = np.array(re.findall('\d+', str(self.port.readline()))).astype(int)

    def run(self):
        while True:
            # self.dat
            data = str(self.port.readline())
            # print(data, type(data))
            # print(re.findall('\d+', data))
            self.data = np.array(re.findall('\d+', data))
            self.data = self.data.astype(int)
            # print(self.data)
            for i in range(5):
                if self.data[i] != self.old[i]:
                    changevalue = self.data[i] - self.old[i]
                    self.changeforce.emit(i, changevalue)
        pass

class Read_data_4(QThread):
    changeforce = pyqtSignal(int, int)
    '''
    子进程，用于读取数据
    '''
    def __init__(self, port):
        super(Read_data_4, self).__init__()
        self.port = port
        self.old = np.array(re.findall('\d+', str(self.port.readline()))).astype(int)

    def run(self):
        while True:
            # self.dat
            data = str(self.port.readline())
            # print(data, type(data))
            # print(re.findall('\d+', data))
            self.data = np.array(re.findall('\d+', data))
            self.data = self.data.astype(int)
            # print(self.data)
            for i in range(5):
                if self.data[i] != self.old[i]:
                    changevalue = self.data[i] - self.old[i]
                    self.changeforce.emit(i, changevalue)
        pass

class Read_data_5(QThread):
    changeforce = pyqtSignal(int, int)
    '''
    子进程，用于读取数据
    '''
    def __init__(self, port):
        super(Read_data_5, self).__init__()
        self.port = port
        self.old = np.array(re.findall('\d+', str(self.port.readline()))).astype(int)

    def run(self):
        while True:
            # self.dat
            data = str(self.port.readline())
            # print(data, type(data))
            # print(re.findall('\d+', data))
            self.data = np.array(re.findall('\d+', data))
            self.data = self.data.astype(int)
            # print(self.data)
            for i in range(5):
                if self.data[i] != self.old[i]:
                    changevalue = self.data[i] - self.old[i]
                    self.changeforce.emit(i, changevalue)
        pass

class begin(QMainWindow, begin_UI.Ui_Dialog):
    baud = ['9600', '115200']
    def __init__(self):
        super(begin, self).__init__()
        self.setupUi(self)
        # 按钮点击事件处理函数，即连接上所有串口
        self.pushButton.clicked.connect(self.myconnect)
        # 初始化波特率
        self.init_baud()
        # 初始化串口
        self.port_find()
        # 实例化寻找串口线程
        self.thread1 = Find_port()
        # 串口发生变化信号处理函数
        self.thread1.port_change.connect(self.port_find)
        # 线程运行
        self.thread1.start()

    # 初始化波特率
    def init_baud(self):
        self.comboBox_2.addItems(self.baud)
        self.comboBox_4.addItems(self.baud)
        self.comboBox_6.addItems(self.baud)
        self.comboBox_8.addItems(self.baud)
        self.comboBox_10.addItems(self.baud)

    # 链接串口，成功则跳转页面
    def myconnect(self):
        try:
            True
            # self.port1 = serial.Serial(self.comboBox.currentText(), self.comboBox_2.currentText())
            # self.port2 = serial.Serial(self.comboBox_3.currentText(), self.comboBox_4.currentText())
            # self.port3 = serial.Serial(self.comboBox_5.currentText(), self.comboBox_6.currentText())
            # self.port4 = serial.Serial(self.comboBox_7.currentText(), self.comboBox_8.currentText())
            # self.port5 = serial.Serial(self.comboBox_9.currentText(), self.comboBox_10.currentText())
        except:
            box = QMessageBox()
            box.setText('
连接失败！！！
')
            box.setWindowTitle('message')
            box.setStandardButtons(QMessageBox.Ok)  # QMessageBox显示的按钮
            box.button(QMessageBox.Ok).animateClick(1000)  # t时间后自动关闭(t单位为毫秒)
            box.exec_()
        else:
            self.mainwin = main_ui()
            self.hide()
            self.mainwin.show()
        pass

    # 初始化串口及线程串口变化信号处理函数
    def port_find(self):
        self.comboBox.clear()
        self.comboBox_3.clear()
        self.comboBox_5.clear()
        self.comboBox_7.clear()
        self.comboBox_9.clear()
        list1 = []
        port_list = list(serial.tools.list_ports.comports())
        for item in port_list:
            pattern = re.compile('COM[\d]*')
            item = pattern.findall(str(item))[0]
            list1.append(item)
            print(item)
        list1.sort()
        self.comboBox.addItems(list1)
        self.comboBox_3.addItems(list1)
        self.comboBox_5.addItems(list1)
        self.comboBox_7.addItems(list1)
        self.comboBox_9.addItems(list1)

#
class Figure_Canvas(FigureCanvas):
    def __init__(self, parent=None, width=3.9, height=2.7, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=100)
        super(Figure_Canvas, self).__init__(self.fig)
        self.ax = self.fig.add_subplot(111)

# 主界面
class main_ui(QMainWindow, main_UI.Ui_Dialog):

    my_row = ('col 1', 'col 2', 'col 3', 'col 4', 'col 5')
    my_col = ('row 1', 'row 2', 'row 3', 'row 4', 'row 5')

    def __init__(self):
        super(main_ui, self).__init__()
        self.setupUi(self)
        # 存储数据矩阵
        self.data = np.zeros(shape=(5, 5))
        # 初始状态显示
        self.textBrowser.setText('vacant')
        # 阵列触发标志
        self.i = 0
        # 阵列触发时间
        self.beginTime = 0
        # 阵列使用时间
        self.Dtime = 0
        self.hour = 0
        self.miutue = 0
        self.second = 0
        # 定时器
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.countTime)
        # 初始化数据矩阵，即读取相应位置的文本内容
        self.make_list()
        # 初始化视角旋转工具
        self.init_xuanz()
        # 绘制三维柱状图
        self.D3DBar()
        # 文本编辑框内容变化事件处理函数
        self.lineEdit_1.textChanged.connect(self.reprint)
        self.lineEdit_2.textChanged.connect(self.reprint)
        self.lineEdit_3.textChanged.connect(self.reprint)
        self.lineEdit_4.textChanged.connect(self.reprint)
        self.lineEdit_5.textChanged.connect(self.reprint)
        self.lineEdit_6.textChanged.connect(self.reprint)
        self.lineEdit_7.textChanged.connect(self.reprint)
        self.lineEdit_8.textChanged.connect(self.reprint)
        self.lineEdit_9.textChanged.connect(self.reprint)
        self.lineEdit_10.textChanged.connect(self.reprint)
        self.lineEdit_11.textChanged.connect(self.reprint)
        self.lineEdit_12.textChanged.connect(self.reprint)
        self.lineEdit_13.textChanged.connect(self.reprint)
        self.lineEdit_14.textChanged.connect(self.reprint)
        self.lineEdit_15.textChanged.connect(self.reprint)
        self.lineEdit_16.textChanged.connect(self.reprint)
        self.lineEdit_17.textChanged.connect(self.reprint)
        self.lineEdit_18.textChanged.connect(self.reprint)
        self.lineEdit_19.textChanged.connect(self.reprint)
        self.lineEdit_20.textChanged.connect(self.reprint)
        self.lineEdit_21.textChanged.connect(self.reprint)
        self.lineEdit_22.textChanged.connect(self.reprint)
        self.lineEdit_23.textChanged.connect(self.reprint)
        self.lineEdit_24.textChanged.connect(self.reprint)
        self.lineEdit_25.textChanged.connect(self.reprint)
        # 视角复位按钮点击事件处理函数
        self.pushButton.clicked.connect(self.reback)
        # 实例化串口数据读取线程2-6
        # self.thread2 = Read_data_1(beginWin.port1)
        # self.thread2.changeforce.connect(self.ChangeForce1)
        # self.thread2.start()
        # self.thread3 = Read_data_2(beginWin.port2)
        # self.thread3.changeforce.connect(self.ChangeForce2)
        # self.thread3.start()
        # self.thread4 = Read_data_3(beginWin.port3)
        # self.thread4.changeforce.connect(self.ChangeForce3)
        # self.thread4.start()
        # self.thread5 = Read_data_4(beginWin.port4)
        # self.thread5.changeforce.connect(self.ChangeForce4)
        # self.thread5.start()
        # self.thread6 = Read_data_5(beginWin.port5)
        # self.thread6.changeforce.connect(self.ChangeForce5)
        # self.thread6.start()

    # 线程数据变化信号处理函数
    def ChangeForce5(self, i, changevalue):
        if i == 0:
            # print(changevalue, type(changevalue), str(changevalue))
            self.lineEdit_21.setText(str(changevalue))
        if i == 1:
            self.lineEdit_16.setText(str(changevalue))
        if i == 2:
            self.lineEdit_11.setText(str(changevalue))
        if i == 3:
            self.lineEdit_6.setText(str(changevalue))
        if i == 4:
            self.lineEdit_1.setText(str(changevalue))

    # 线程数据变化信号处理函数
    def ChangeForce1(self, i, changevalue):
        if i == 0:
            # print(changevalue, type(changevalue), str(changevalue))
            self.lineEdit_25.setText(str(changevalue))
        if i == 1:
            self.lineEdit_20.setText(str(changevalue))
        if i == 2:
            self.lineEdit_15.setText(str(changevalue))
        if i == 3:
            self.lineEdit_10.setText(str(changevalue))
        if i == 4:
            self.lineEdit_5.setText(str(changevalue))

    # 线程数据变化信号处理函数
    def ChangeForce2(self, i, changevalue):
        if i == 0:
            # print(changevalue, type(changevalue), str(changevalue))
            self.lineEdit_24.setText(str(changevalue))
        if i == 1:
            self.lineEdit_19.setText(str(changevalue))
        if i == 2:
            self.lineEdit_14.setText(str(changevalue))
        if i == 3:
            self.lineEdit_9.setText(str(changevalue))
        if i == 4:
            self.lineEdit_4.setText(str(changevalue))

    # 线程数据变化信号处理函数
    def ChangeForce3(self, i, changevalue):
        if i == 0:
            # print(changevalue, type(changevalue), str(changevalue))
            self.lineEdit_23.setText(str(changevalue))
        if i == 1:
            self.lineEdit_18.setText(str(changevalue))
        if i == 2:
            self.lineEdit_13.setText(str(changevalue))
        if i == 3:
            self.lineEdit_8.setText(str(changevalue))
        if i == 4:
            self.lineEdit_3.setText(str(changevalue))

    # 线程数据变化信号处理函数
    def ChangeForce4(self, i, changevalue):
        if i == 0:
            # print(changevalue, type(changevalue), str(changevalue))
            self.lineEdit_22.setText(str(changevalue))
        if i == 1:
            self.lineEdit_17.setText(str(changevalue))
        if i == 2:
            self.lineEdit_12.setText(str(changevalue))
        if i == 3:
            self.lineEdit_7.setText(str(changevalue))
        if i == 4:
            self.lineEdit_2.setText(str(changevalue))

    # 绘制三维折线图函数，弃用
    def paint(self):
        self.SurfFigure = Figure_Canvas()

        self.X = np.arange(0, 5, step=1)  # X轴的坐标
        self.Y = np.arange(0, 5, step=1)  # Y轴的坐标
        self.make_list()
        self.Z = self.data
        xx, yy = np.meshgrid(self.X, self.Y)  # 网格化坐标
        self.X, self.Y = xx.ravel(), yy.ravel()  # 矩阵扁平化
        self.Z = self.Z.ravel()

        width = height = 0.6  # 每一个柱子的长和宽
        bottom = np.zeros_like(self.X)  # 设置柱状图的底端位值

        layout = QtWidgets.QVBoxLayout(self.groupBox_4)
        layout.addWidget(self.SurfFigure)
        self.SurfFigure.ax.remove()
        self.ax3d = self.SurfFigure.fig.gca(projection='3d')
        self.ax3d.set_title("AirTrack")
        self.ax3d.set_xlabel("x")
        self.ax3d.set_ylabel("y")
        self.ax3d.set_zlabel("z")
        self.figure = self.ax3d.plot(self.X, self.Y, self.Z, c='r')

    # 复位按钮功能
    def reback(self):
        self.m_graph.scene().activeCamera().setCameraPreset(self.m_preset)
        # self.rotationSliderX.value(0)
        # self.rotationSlidery.value(0)

    # 三维柱状图绘制
    def D3DBar(self):
        self.m_graph = Q3DBars()
        self.m_xRotation = 0.0  # 水平旋转角度
        self.m_yRotation = 0.0  # 垂直旋转角度
        self.m_fontSize = 30
        self.m_segments = 4
        self.m_subSegments = 3
        self.m_minval = 0
        self.m_maxval = 5120000
        self.m_temperatureAxis = QValue3DAxis()  # 温度轴
        self.m_yearAxis = QCategory3DAxis()  # 年份轴
        self.m_monthAxis = QCategory3DAxis()  # 月份轴
        self.m_primarySeries = QBar3DSeries()  # 主序列
        self.m_barMesh = QAbstract3DSeries.MeshBevelBar  # 预定义的网格类型
        self.m_smooth = True  # 是否平滑

        # 阴影以柔化的边缘高质量渲染
        self.m_graph.setShadowQuality(QAbstract3DGraph.ShadowQualitySoftMedium)
        # 当前主题Q3DTheme设置背景是否可见
        self.m_graph.activeTheme().setBackgroundEnabled(False)
        # 当前主题Q3DTheme设置字体
        self.m_graph.activeTheme().setFont(
            QFont('Times New Roman', self.m_fontSize))
        # 当前主题Q3DTheme设置标签是使用彩色背景还是使用完全透明的背景绘制
        self.m_graph.activeTheme().setLabelBackgroundEnabled(True)
        # 是否按比例将比例尺设置为单个系列比例尺来缩放比例
        self.m_graph.setMultiSeriesUniform(True)

        self.m_temperatureAxis.setTitle("Average temperature")
        # 轴上的段数。这表明绘制了多少标签。要绘制的网格线的数量使用公式计算：segments * subsegments + 1。预设默认值为5。该值不能低于1
        self.m_temperatureAxis.setSegmentCount(self.m_segments)
        # 轴上每个段内的子段数。
        # 除每个线段外，还在每个子线段之间绘制网格线。预设默认值为1。该值不能低于1。
        self.m_temperatureAxis.setSubSegmentCount(self.m_subSegments)
        self.m_temperatureAxis.setRange(self.m_minval, self.m_maxval)
        self.m_temperatureAxis.setLabelFormat(u"%.1fV")

        self.m_yearAxis.setTitle("row")
        self.m_monthAxis.setTitle("col")

        self.m_graph.setValueAxis(self.m_temperatureAxis)
        # 设置活动行的轴为年份
        self.m_graph.setRowAxis(self.m_yearAxis)
        # 设置活动列的轴为月份
        self.m_graph.setColumnAxis(self.m_monthAxis)

        self.m_primarySeries.setItemLabelFormat(
            "data - @colLabel @rowLabel: @valueLabel")

        # 设置网格类型
        self.m_primarySeries.setMesh(QAbstract3DSeries.MeshBevelBar)
        self.m_primarySeries.setMeshSmooth(False)

        self.m_graph.addSeries(self.m_primarySeries)

        self.m_preset = Q3DCamera.CameraPresetFront

        self.m_graph.scene().activeCamera().setCameraPreset(self.m_preset)

        self.data2 = self.data.tolist()
        dataSet = []
        for row in self.data2:
            dataSet.append([QBarDataItem(v) for v in row])

        self.m_primarySeries.dataProxy().resetArray(dataSet, self.my_col, self.my_row)

        container = QWidget.createWindowContainer(self.m_graph)
        container.setMinimumSize(QSize(700, 400))
        container.setMaximumSize(QSize(700, 400))
        container.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        container.setFocusPolicy(Qt.StrongFocus)
        widget = QWidget()
        layout = QtWidgets.QVBoxLayout(self.widget)
        layout.addWidget(container)
        widget.show()

    # 更新柱状图数据
    def reprint(self):
        self.make_list()
        if self.data.mean() > 20:
            self.i = 1
            self.beginTime = time.time()
            self.timer.start(1000)
        else:
            if self.i == 1:
                self.timer.stop()
            self.i = 0
            self.beginTime = 0
            self.Dtime = 0
            self.textBrowser.setText('vacant')
        self.data2 = self.data.tolist()
        dataSet = []
        for row in self.data2:
            dataSet.append([QBarDataItem(v) for v in row])
        self.m_primarySeries.dataProxy().resetArray(dataSet, self.my_col, self.my_row)

    # 计算使用时间
    def countTime(self):
        # print('b')
        if self.beginTime != 0:
            newTime = time.time()
            self.Dtime = int(newTime - self.beginTime)
            self.hour = int(self.Dtime/3600)
            self.mintue = int(self.Dtime/60) - 24*self.hour
            self.second = self.Dtime - 3600 * self.hour - 60 * self.mintue
            if self.hour != 0:
                self.textBrowser.setText('in use, Usage duration is ' + str(self.hour) + 'h' + str(self.mintue) + 'm' + str(self.second) + 's')
            elif self.mintue != 0:
                self.textBrowser.setText('in use, Usage duration is ' + str(self.mintue) + 'h' + str(self.second) + 's')
            else:
                self.textBrowser.setText('in use, Usage duration is ' + str(self.second) + 's')

    # 字符串转化为整型函数
    def toint(self, str):
        try:
            res = int(str)
        except:
            return 0
        else:
            return res

    # 根据文本框阵列拼凑数据矩阵
    def make_list(self):
        # r = 5120000/X - 1000
        self.data[0][0] = self.toint(self.lineEdit_1.text())
        self.data[0][1] = self.toint(self.lineEdit_2.text())
        self.data[0][2] = self.toint(self.lineEdit_3.text())
        self.data[0][3] = self.toint(self.lineEdit_4.text())
        self.data[0][4] = self.toint(self.lineEdit_5.text())
        self.data[1][0] = self.toint(self.lineEdit_6.text())
        self.data[1][1] = self.toint(self.lineEdit_7.text())
        self.data[1][2] = self.toint(self.lineEdit_8.text())
        self.data[1][3] = self.toint(self.lineEdit_9.text())
        self.data[1][4] = self.toint(self.lineEdit_10.text())
        self.data[2][0] = self.toint(self.lineEdit_11.text())
        self.data[2][1] = self.toint(self.lineEdit_12.text())
        self.data[2][2] = self.toint(self.lineEdit_13.text())
        self.data[2][3] = self.toint(self.lineEdit_14.text())
        self.data[2][4] = self.toint(self.lineEdit_15.text())
        self.data[3][0] = self.toint(self.lineEdit_16.text())
        self.data[3][1] = self.toint(self.lineEdit_17.text())
        self.data[3][2] = self.toint(self.lineEdit_18.text())
        self.data[3][3] = self.toint(self.lineEdit_19.text())
        self.data[3][4] = self.toint(self.lineEdit_20.text())
        self.data[4][0] = self.toint(self.lineEdit_21.text())
        self.data[4][1] = self.toint(self.lineEdit_22.text())
        self.data[4][2] = self.toint(self.lineEdit_23.text())
        self.data[4][3] = self.toint(self.lineEdit_24.text())
        self.data[4][4] = self.toint(self.lineEdit_25.text())

    # 视角旋转初始化
    def init_xuanz(self):
        self.rotationSliderX = QSlider(Qt.Horizontal)
        self.rotationSliderX.setTickInterval(30)
        self.rotationSliderX.setTickPosition(QSlider.TicksBelow)
        self.rotationSliderX.setMinimum(-180)
        self.rotationSliderX.setValue(0)
        self.rotationSliderX.setMaximum(180)
        self.rotationSliderY = QSlider(Qt.Horizontal)
        self.rotationSliderY.setTickInterval(15)
        self.rotationSliderY.setTickPosition(QSlider.TicksAbove)
        self.rotationSliderY.setMinimum(-90)
        self.rotationSliderY.setValue(0)
        self.rotationSliderY.setMaximum(90)
        vLayout = QtWidgets.QVBoxLayout(self.groupBox_5)
        vLayout.addWidget(QLabel("Rotate horizontally"))
        vLayout.addWidget(self.rotationSliderX, 0, Qt.AlignTop)
        vLayout.addWidget(QLabel("Rotate vertically"))
        vLayout.addWidget(self.rotationSliderY, 0, Qt.AlignTop)
        self.rotationSliderX.valueChanged.connect(self.rotateX)
        self.rotationSliderY.valueChanged.connect(self.rotateY)

    # X轴旋转
    def rotateX(self, rotation):
        self.m_xRotation = rotation
        self.m_graph.scene().activeCamera().setCameraPosition(
            self.m_xRotation, self.m_yRotation)

    # Y轴旋转
    def rotateY(self, rotation):
        self.m_yRotation = rotation
        self.m_graph.scene().activeCamera().setCameraPosition(
            self.m_xRotation, self.m_yRotation)

if __name__ == '__main__':
    # 实现不同分辨率下的电脑上的相同显示
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    beginWin = begin()
    beginWin.show()
    sys.exit(app.exec_())


import sys
from collections import defaultdict
import re

lines = sys.stdin.readlines()

mol = "CRnCaCaCaSiRnBPTiMgArSiRnSiRnMgArSiRnCaFArTiTiBSiThFYCaFArCaCaSiThCaPBSiThSiThCaCaPTiRnPBSiThRnFArArCaCaSiThCaSiThSiRnMgArCaPTiBPRnFArSiThCaSiRnFArBCaSiRnCaPRnFArPMgYCaFArCaPTiTiTiBPBSiThCaPTiBPBSiRnFArBPBSiRnCaFArBPRnSiRnFArRnSiRnBFArCaFArCaCaCaSiThSiThCaCaPBPTiTiRnFArCaPTiBSiAlArPBCaCaCaCaCaSiRnMgArCaSiThFArThCaSiThCaSiRnCaFYCaSiRnFYFArFArCaSiRnFYFArCaSiRnBPMgArSiThPRnFArCaSiRnFArTiRnSiRnFYFArCaSiRnBFArCaSiRnTiMgArSiThCaSiThCaFArPRnFArSiRnFArTiTiTiTiBCaCaSiRnCaCaFYFArSiThCaPTiBPTiBCaSiThSiRnMgArCaF"

def applyRule(rule, mol):
    blah = set()
    for (res) in re.finditer(rule[0], mol):
        news = mol[:res.start()] + rule[1].strip() + mol[res.end():]
        #print(news)
        blah.add(news)
    return blah

def applyBackward(right, left, mol):
    return mol.replace(right, left)

backrules = defaultdict(list)
onestep = set()
count = 0

for line in lines:
    rule = line.split(' => ')
    backrules[rule[1].strip()] = rule[0].strip()

while 'Ca' in mol:
    for r in backrules.keys():
        if 'Ca' in r and r in mol:
            mol = applyBackward(r, backrules[r], mol)
            count += 1
print("No ca ", mol)
ArRules = ['SiRnFAr', 'CRnMgAr', 'NRnMgAr', 'ThRnFAr', 'TiRnFAr', 'CRnMgYFAr', 'CRnAlAr',
'CRnFYFAr', 'CRnFYFYFAr', 'CRnFYMgAr', 'NRnFYFAr', 'ORnFAr', 'CRnFAr', 'CRnMgAr', 'NRnFAr']

print(ArRules)

startcount = 0
while startcount != count:
    startcount = count
    for r in ArRules:
        if r in mol:
            mol = applyBackward(r, backrules[r], mol)
            print(mol)
            count += 1

print('count' , count)
print(mol)
#print(len(onestep))


#
# Utility to unpack all data from old data structure.
# Data structure as:
#   e.g.,   completed/2-1/1/info/1-info.out
#           completed/2-1/1/input/1-big.in
#           completed/2-1/1/planets/1/planet1.aei
#

import os
import argparse
import shutil
import re

parser = argparse.ArgumentParser()
parser.add_argument('--completed_old', '-old',
                    action='store',
                    dest='path_old')
parser.add_argument('--completed_new', '-new',
                    action='store',
                    dest='path_new')
parser.add_argument('--resonance', '-res',
                    action='store',
                    dest='res_str_old')
args = parser.parse_args()

path_old = args.path_old
path_new = args.path_new
resonance =  args.res_str_old
res_str_old = '-'.join((resonance[0], resonance[-1]))
res_str_new = ''.join((resonance[0], resonance[-1]))
three_dirs = ['info', 'input', 'planets']

os.mkdir(path_new)
if not os.path.exists('{}/{}'.format(path_new, res_str_new)):
    os.mkdir('{}/{}'.format(path_new, res_str_new))
    for _dir in three_dirs:
        os.mkdir('{}/{}/{}'.format(path_new, res_str_new, _dir))

res_dirs = [d for d in os.listdir('{}/{}'.format(path_old, res_str_old)) if re.match('^[0-9]+$', d)]
for res_dir in res_dirs:
    print(res_dir)
    N_old = len(os.listdir('{}/{}/{}/info/'.format(path_old, res_str_old, res_dir)))
    N_new = len(os.listdir('{}/{}/info/'.format(path_new, res_str_new)))
    for n in range(1, N_old+1):
        shutil.copy('{}/{}/{}/info/{}-info.out'.format(path_old, res_str_old, res_dir, n),
                '{}/{}/info/{}-info.out'.format(path_new, res_str_new, N_new))
        shutil.copy('{}/{}/{}/input/{}-big.in'.format(path_old, res_str_old, res_dir, n),
                '{}/{}/input/{}-big.in'.format(path_new, res_str_new, N_new))
        try:
            shutil.copy('{}/{}/{}/planets/{}/planet1.aei'.format(path_old, res_str_old, res_dir, n),
                    '{}/{}/planets/{}-planet1.aei'.format(path_new, res_str_new, N_new))
        except FileNotFoundError:
            open('{}/{}/planets/{}-planet1_empty.aei'.format(path_new, res_str_new, N_new), 'a').close()
        try:
            shutil.copy('{}/{}/{}/planets/{}/planet2.aei'.format(path_old, res_str_old, res_dir, n),
                '{}/{}/planets/{}-planet2.aei'.format(path_new, res_str_new, N_new))
        except FileNotFoundError:
            open('{}/{}/planets/{}-planet2_empty.aei'.format(path_new, res_str_new, N_new), 'a').close()

        N_new += 1