예제 #1
0
def GeneticAlgorithm(chessList):  #the process of genetic algorithm
    population = initialize_population(chessList)

    # for chromosome in population :
    # 	print(chromosome.fitness)
    i = 1
    while (population[0].fitness != 0):

        print("Generation :", i)

        populationSort(population)
        deleteLeastFit(population)

        # for chromosome in population :
        # 	print(chromosome.fitness)
        # 	print("===============")
        # 	print("PieceList")
        # 	print(chromosome.piecesLocation)

        # print("Crossover")
        # print("===============")

        index = 0
        while index < maxPopulation / 2:
            parent1, parent2 = getParents(population, index)
            if not (samePosition(parent1, parent2)):
                crossOver(population, parent1, parent2)

            index = index + 2

        # index = 0
        # parent1 , parent2 = getParents(population, index)
        # crossOver(population, parent1, parent2)

        populationSort(population)
        print("Fittest : ", population[0].fitness)
        # for chromosome in population :
        # 	print(chromosome.fitness)
        # for chromosome in population :
        # 	Printer.printChessBoard(chromosome.board)
        #

        # populationSort(population)
        i = i + 1

    print(population[0].piecesLocation)
    # BoardHandler.updateBoard(population[0].board, population[0].piecesLocation)
    Printer.printChessBoard(population[0].board)
예제 #2
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
예제 #3
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")
예제 #4
0
def GeneticAlgorithm(chessList):  # the process of genetic algorithm
    population = initialize_population(chessList)
    generationCount = 1
    count = 1
    maxFitness = 0

    while generationCount <= maxGeneration:
        newGeneration = []
        index = 0
        while index < (maxPopulation / 2 - 1):
            parent1, parent2 = getParents(population, index)
            crossOver(newGeneration, parent1, parent2)
            index = index + 1
        population = newGeneration + population  # add new generation to current population
        populationSort(population)
        deleteLeastFit(population)
        print("Generation :" + str(generationCount) + ", Fittest : ",
              abs(population[0].fitness))
        if population[0].fitness != maxFitness:
            maxFitness = population[0].fitness
            count = 1
        else:
            count += 1

        if count == 100:  # if in 100 gen there is no change in fittest score
            print("Same fitness for " + str(count) + " gen")
            print("Terminate")
            time.sleep(1)
            break
        else:
            generationCount = generationCount + 1

    # print (population[0].piecesLocation)
    if generationCount == maxGeneration:
        print("Max iteration reach")
        time.sleep(1)
    Printer.printChessBoard(population[0].board)
    Printer.printSolutionToFile(population[0].board, "Genetic")
예제 #5
0
def hillC(maxTry, chessboard):
	# Generate initial state
	currentState = copy.deepcopy(chessboard)
	# Iterate Try times
	for i in range(maxTry):
		print(i)
		bestNeighbour = copy.deepcopy(getBestNeighbour(currentState))
		
		# Compare current state with best neighbour, if current state is better return current state, 
		if evaluate(bestNeighbour, currentState) > 0:
			Printer.printChessBoard(currentState)
			Printer.printSolutionToFile(currentState, "HillClimbing")
			return currentState
		Printer.printChessBoard(currentState)
		# else assign current state with best neighbour
		currentState = copy.deepcopy(bestNeighbour)
	
	# Return current state if function HC cannot find maximum until try times
	Printer.printChessBoard(currentState)
	Printer.printSolutionToFile(currentState, "HillClimbing")
	return currentState
예제 #6
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")