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
示例#2
0
def printConflictAmount(chessBoard):
    totalA, totalB, queenA, rookA, bishopA, knightA, queenB, rookB, bishopB, knightB =\
        Checker.conflictChecker(chessBoard)
    # totalA, queenA, rookA, bishopA, knightA = Checker.conflictChecker(chessBoard)
    # totalB, queenB, rookB, bishopB, knightB = Checker.conflictCheckerB(chessBoard)

    print(str(totalA) + " ", end='')
    print(str(totalB))
示例#3
0
def printConflictAmount(chessBoard):
    totalA, queenA, rookA, bishopA, knightA = Checker.conflictChecker(
        chessBoard)
    # totalB, queenB, rookB, bishopB, knightB = Checker.conflictCheckerB(chessBoard)

    print("Total conflict A : " + str(totalA))
    print("Description:")
    print("  Queen  : " + str(queenA))
    print("  Rook   : " + str(rookA))
    print("  Bishop : " + str(bishopA))
    print("  Knight : " + str(knightA))
示例#4
0
def getBestNeighbour(chessboard):
	counter = 0
	size = len(chessboard)
	
	# Initial Chessboard
	
	BestNeighbour = copy.deepcopy(chessboard)
	ts0, td0, qs0, qd0, rs0, rd0, bs0, bd0, ks0, kd0 = Checker.conflictChecker(BestNeighbour)
	Value = ts0-td0
	# Printer.printChessBoard(BestNeighbour)
	for row in range(size):
		for col in range(size):
		
			# If there is a piece in this box, then move it
			if chessboard[row][col] != ('.', "."):
				
				# Iterate all box in board, search for empty box
				for rowIter in range(size):
					for colIter in range(size):
						
						# If found an empty box, move piece to the empty box
						if chessboard[rowIter][colIter] == ('.', "."):
							counter += 1
							chessboard[rowIter][colIter] = chessboard[row][col]
							chessboard[row][col] = ('.', ".")
							
							# Printer.printChessBoard(chessboard)
							
							# Check value of current state and compare it with BestNeighbour
							ts1, td1, qs1, qd1, rs1, rd1, bs1, bd1, ks1, kd1 = Checker.conflictChecker(chessboard)
							ValueNeighbour = ts1-td1
							if ValueNeighbour <= Value:
								BestNeighbour = copy.deepcopy(chessboard)
								Value = ValueNeighbour
							# Printer.printChessBoard(BestNeighbour)
							# Reset board to initial board
							chessboard[row][col] = chessboard[rowIter][colIter]
							chessboard[rowIter][colIter] = ('.', ".")
	return BestNeighbour
示例#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 evaluate(Neigbour, currentState):
	ts1, td1, qs1, qd1, rs1, rd1, bs1, bd1, ks1, kd1 = Checker.conflictChecker(Neigbour)
	ts2, td2, qs2, qd2, rs2, rd2, bs2, bd2, ks2, kd2 = Checker.conflictChecker(currentState)
	t1 = ts1 - td1
	t2 = ts2 - td2
	return t1 - t2
示例#9
0
def printSolutionToFile(chessBoard, solType):
    # Use now's date and time as filename
    timestr = time.strftime("%Y%m%d-%H%M%S")

    # Create and write file
    outfile = open("Solutions/" + timestr + "-" + solType + ".txt", "w")

    # Check amount of conflict from chess board final state
    totalA, totalB, queenA, rookA, bishopA, knightA, queenB, rookB, bishopB, knightB =\
        Checker.conflictChecker(chessBoard)
    size = len(chessBoard)

    # write to file
    # Remember that chessboard elements is tuple.
    # Tuple structure : (<TYPE>, <COLOR>)
    for row in range(size):
        for col in range(size):

            # no newline if final column has not reached
            if col < size - 1:
                # outfile.write white
                if chessBoard[row][col][1] == "WHITE":
                    if chessBoard[row][col][0] == "QUEEN":
                        outfile.write('Q' + " ")
                    elif chessBoard[row][col][0] == "ROOK":
                        outfile.write('R' + " ")
                    elif chessBoard[row][col][0] == "KNIGHT":
                        outfile.write('K' + " ")
                    elif chessBoard[row][col][0] == "BISHOP":
                        outfile.write('B' + " ")
                    else:
                        outfile.write('.' + " ")
                # outfile.write black
                else:
                    if chessBoard[row][col][0] == "QUEEN":
                        outfile.write('q' + " ")
                    elif chessBoard[row][col][0] == "ROOK":
                        outfile.write('r' + " ")
                    elif chessBoard[row][col][0] == "KNIGHT":
                        outfile.write('k' + " ")
                    elif chessBoard[row][col][0] == "BISHOP":
                        outfile.write('b' + " ")
                    else:
                        outfile.write('.' + " ")

            # newline in outfile.write because final column is reached
            else:
                # outfile.write white
                if chessBoard[row][col][1] == "WHITE":
                    if chessBoard[row][col][0] == "QUEEN":
                        outfile.write('Q' + "\n")
                    elif chessBoard[row][col][0] == "ROOK":
                        outfile.write('R' + "\n", )
                    elif chessBoard[row][col][0] == "KNIGHT":
                        outfile.write('K' + "\n", )
                    elif chessBoard[row][col][0] == "BISHOP":
                        outfile.write('B' + "\n", )
                    else:
                        outfile.write('.' + "\n", )
                # outfile.write black
                else:
                    if chessBoard[row][col][0] == "QUEEN":
                        outfile.write('q' + "\n", )
                    elif chessBoard[row][col][0] == "ROOK":
                        outfile.write('r' + "\n", )
                    elif chessBoard[row][col][0] == "KNIGHT":
                        outfile.write('k' + "\n")
                    elif chessBoard[row][col][0] == "BISHOP":
                        outfile.write('b' + "\n")
                    else:
                        outfile.write('.' + "\n")

    outfile.write("Total conflict A: " + str(totalA) + "\n")
    outfile.write("Total conflict B: " + str(totalB))