示例#1
0
def mutation(child):  #mutation function
    BoardHandler.updateBoard(child.board, child.piecesLocation)
    member = randint(0, len(child.piecesLocation) - 1)
    row = randint(0, 7)
    col = randint(0, 7)
    while child.board[row][col] != ('.', "."):
        row = randint(0, 7)
        col = randint(0, 7)

    child.piecesLocation[member][0][0] = row
    child.piecesLocation[member][0][1] = col
def simulatedAnnealing(maxTry, chessBoard):
    # Initialization
    mTry = iterator = maxTry

    # Copy initiate board and count the value
    bestResult = copy.deepcopy(chessBoard)
    ts0, td0, qs0, qd0, rs0, rd0, bs0, bd0, ks0, kd0 = Checker.conflictChecker(bestResult)
    Value = ts0 - td0
    
    # Improved and accepted states counter
    improved = accepted = 0

    # Outer loop, which randomizes state until a number of steps
    while iterator > 0 :
        # Function that set the temperature
        T = math.log(mTry - iterator + 1, math.exp(1))
        
        # Generate a random state
        tempBoard = copy.deepcopy(bestResult)
        tempList = BoardHandler.createPiecesListWithPos(tempBoard)
        randPiece = tempList[randint(0, len(tempList)-1)]

        # Randomizes a piece's position
        randRow = randint(0, 7)
        randCol = randint(0, 7)
        while tempBoard[randRow][randCol] != ('.', "."):
            randRow = randint(0, 7) 
            randCol = randint(0, 7)
        tempBoard[randPiece[3]][randPiece[2]] = ('.', ".")
        tempBoard[randRow][randCol] = (randPiece[0], randPiece[1])

        # Count the randomized board value
        ts1, td1, qs1, qd1, rs1, rd1, bs1, bd1, ks1, kd1 = Checker.conflictChecker(tempBoard)
        tempValue = ts1 - td1
        
        # If the next state value is better, accept it
        if tempValue <= Value :
            bestResult = copy.deepcopy(tempBoard)
            Value = tempValue
            improved += 1
        # If the next state value is worse, accept with probability of it is higher than a random number
        elif tempValue > Value :

            sigmoidFunc = math.floor(math.exp(-T)) * 100
            randomNum = randint(0, 100)
            if sigmoidFunc > randomNum:
                bestResult = copy.deepcopy(tempBoard)
                Value = tempValue
                accepted += 1
        
        # Iterator value decreased
        iterator -= 1

    # Result of improved states
    print(improved)
    # Result of accepted states
    print(accepted)
    Printer.printSolutionToFile(bestResult, "SimulatedAnnealing")
    return bestResult
示例#3
0
def mutationDouble(
        child):  # mutation function if there are some positions that clash
    BoardHandler.updateBoard(child.board, child.piecesLocation)

    while checkDouble(child):
        double = listDouble(child)
        member = choice(double)

        row = randint(0, 7)
        col = randint(0, 7)

        while child.board[row][col] != ('.', "."):
            row = randint(0, 7)
            col = randint(0, 7)

        child.piecesLocation[member][0][0] = row
        child.piecesLocation[member][0][1] = col
示例#4
0
def mainMenu():
    chessBoard = []
    while True:
        if os.name == 'nt':  # Windows
            os.system('cls')
        elif os.name == 'posix':  # Linux
            os.system('clear')

        print(colorize(header, 'pink'))
        i = 1
        for item in menuItems:
            print("[" + str(i) + "] " + colorize(item, 'blue'))
            i += 1

        choice = int(input(">> "))

        try:
            if choice < 1:
                raise ValueError

            # Call the matching function
            if choice == 1:
                Printer.printDir("Inputs/")
                chessBoard = BoardHandler.createChessboard()
            elif choice == 2:
                Printer.printDir("Inputs/")
                chessBoard = BoardHandler.readChessboard()
            elif choice == 3:
                Printer.printChessBoard(chessBoard)
            elif choice == 7:
                credit()
            elif choice == 8:
                exit(0)
            else:
                print(">> That is not a valid input.")
        except (ValueError, IndexError):
            pass

        while True:
            text = input("\n>> Press enter to continue.")
            if text == "":
                break
            else:
                print("\n>> You did not press enter.")

        print("\n\n")
示例#5
0
def initialize_population(chessList):  # initialize the population
    population = []
    for i in range(100):
        chromosome = Chromosome()
        chromosome.board = []
        chromosome.piecesLocation = BoardHandler.random_genetic(
            chromosome.board, chessList)
        conflict = Checker.conflictChecker(chromosome.board)
        chromosome.fitness = conflict[0] - conflict[1]
        population.append(chromosome)

    populationSort(population)  # sort population by highest fit
    deleteLeastFit(population)  # delete half of least fit population

    return population
示例#6
0
def initialize_population(chessList):  #initialize the population
    population = []
    for i in range(100):
        chromosome = Chromosome()
        chromosome.board = []
        chromosome.piecesLocation = BoardHandler.random_genetic(
            chromosome.board, chessList)
        chromosome.fitness = Checker.conflictChecker(chromosome.board)[0]

        population.append(chromosome)

    Printer.printChessBoard(population[0].board)
    print(population[0].piecesLocation)
    print(population[0].fitness)

    return population
示例#7
0
def updateBoardandFitness(
        child):  #update chromosome board and fitness score after cross over
    BoardHandler.updateBoard(child.board, child.piecesLocation)
    child.fitness = Checker.conflictChecker(child.board)[0]
示例#8
0
def mainMenu():
    chessBoard = []

    # Clear screen
    while True:
        if os.name == 'nt':  # Windows
            os.system('cls')
        elif os.name == 'posix':  # Linux
            os.system('clear')

        # Print header & menu options
        print(colorize(header, 'pink'))
        i = 1
        for item in menuItems:
            print("[" + str(i) + "] " + colorize(item, 'blue'))
            i += 1

        choice = int(input(">> "))

        try:
            if choice < 1:
                raise ValueError

            # Call the matching function
            if choice == 1:
                Printer.printDir("Inputs/")
                chessBoard = BoardHandler.createChessboard()
            elif choice == 2:
                Printer.printDir("Inputs/")
                chessBoard = BoardHandler.readChessboard()
            elif choice == 3:
                Printer.printChessBoard(chessBoard)
            elif choice == 4:
                maxTry = int(input(">> Enter maximum try : "))
                Printer.printChessBoard(hc.hillC(maxTry, chessBoard))
            elif choice == 5:
                maxTry = int(input(">> Enter maximum try : "))
                Printer.printChessBoard(
                    SimulatedAnnealing.simulatedAnnealing(maxTry, chessBoard))
            elif choice == 6:
                Genetic.GeneticAlgorithm(
                    BoardHandler.createPiecesList(chessBoard))
            elif choice == 7:
                helpMe()
            elif choice == 8:
                credit()
            elif choice == 9:
                exit(0)
            else:
                print(">> That is not a valid input.")
        except (ValueError, IndexError):
            pass

        # Users need to press enter to continue using program (refresh the display)
        while True:
            text = input("\n>> Press enter to continue.")
            if text == "":
                break
            else:
                print("\n>> You did not press enter.")

        print("\n\n")