コード例 #1
0
def algorithm():
    start = time.time()
    node = State(start_state)
    unexplored_queue = PriorityQueue()  # openSet!
    unexplored_queue.put(
        ((node.manhattan_distance(coordinates) + node.pathCost), 0,
         node))  #frontier for priority only!(queue)
    explored = set()  # closed Set!

    priorityCounter = 1

    while unexplored_queue.not_empty:
        node = unexplored_queue.get()[2]
        if node.flattened == goal_flat:
            end = time.time()
            allPaths = reconstruct_path(node)
            print_path(allPaths)
            print(end - start)
            return
        else:
            explored.add(node)
            children = node.get_all_children()
            #for child in children:
            for child in children - explored:
                unexplored_queue.put(
                    ((child.manhattan_distance(coordinates) + child.pathCost),
                     priorityCounter, child))
                priorityCounter += 1
コード例 #2
0
def geneticAlgorithm(populationSize, reproductionRate, mutationProbability,
                     gammaK, gammaTheta, timeLimitInSeconds):

    initialTime = time()

    population = [State().randomize() for i in range(populationSize)]
    populationReproductions = int(populationSize * reproductionRate)

    for state in population:
        state.evaluate()
    population.sort(key=lambda state: state.value)
    bestState = population[0]
    print('Best =', bestState.value, end='\n')
    print('Mean =', mean(population), end='\n')

    while population[0].value > 0 and time() - initialTime < timeLimitInSeconds:

        reproducePopulation(population, populationReproductions,
                            mutationProbability, gammaK, gammaTheta)

        population.sort(key=lambda state: state.value)
        if population[0].value < bestState.value:
            bestState = population[0]

        print('\033[2ABest =',
              bestState.value,
              '\nMean =',
              mean(population),
              end='\n')

    return bestState
コード例 #3
0
def reproducePopulation(population, numberOfReproductions, mutationProbability,
                        gammaK, gammaTheta):
    populationSize = len(population)

    while numberOfReproductions > 0:
        # escolher pais utilizando distribuicao gamma
        fatherIndex = int(gammavariate(gammaK, gammaTheta)) % populationSize
        motherIndex = fatherIndex
        while motherIndex == fatherIndex:
            motherIndex = int(gammavariate(gammaK,
                                           gammaTheta)) % populationSize
        father = population[fatherIndex]
        mother = population[fatherIndex]

        # determinar qual o pai mais forte
        if father.value < mother.value:
            stronger = father
            weaker = mother
        else:
            stronger = mother
            weaker = father

        # quanto mais forte o pai mais cromossomos passa, pais fracos (valor > 8) passam em media metade dos cromossomos
        separationRandomization = gammavariate(stronger.value % 8 + 1, 1 / 2)
        separationIndex = int(round(separationRandomization)) % 4 + 1

        # chance de swap de maneira que ambos extremos dos cromossomos do mais forte possam ser passados
        if random() < 0.5:
            stronger, weaker = weaker, stronger
            separationIndex = 8 - separationIndex

        # gera filho
        child = State()
        i = 0
        while i < separationIndex:
            child.queen[i] = stronger.queen[i]
            i += 1
        while i < 8:
            child.queen[i] = weaker.queen[i]
            i += 1
        # mutacao
        if random() < mutationProbability:
            child.queen[randrange(8)] = randrange(8)

        child.evaluate()

        # filho eh inserido na populacao no lugar de alguem escolhido de acordo com uma distribuicao gamma
        replaceIndex = populationSize - int(gammavariate(
            gammaK, gammaTheta)) % populationSize - 1
        #print(populationSize, replaceIndex)	#debug
        population.pop(replaceIndex)
        population.insert(0, child)

        numberOfReproductions -= 1
コード例 #4
0
class Game:
    def __init__(self, player, opponent):
        self.player = player
        self.opponent = opponent
        self.state = State()
        self.turn = 0

    def play(self):
        while not self.state.gameOver():
            if not self.turn & 1:
                move = (self.player.move(copy(self.state), 1), 1)
                #print "VALID" if self.state.validMove(*move) else "INVALID"
                while not self.state.validMove(*move):
                    move = (random.randint(0, 6), 1)
                self.state.makeMove(*move)
            else:
                move = (self.opponent.move(copy(self.state), 2), 2)
                while not self.state.validMove(*move):
                    move = (random.randint(0, 6), 2)
                self.state.makeMove(*move)
            self.turn += 1
        print self.state
        return self.state.winState()
コード例 #5
0
from board import Board, State
import os

dir_path = os.path.dirname(os.path.realpath(__file__))
state = State.generateFromTxt(dir_path + "/../levels/2.txt")

print(state)
コード例 #6
0
ファイル: player.py プロジェクト: Ben1152000/CCS-1L
        return random.choice(moves)

    def result(self, state, turn, depth):  # return (move, heuristic)
        if depth == 1: return 0
        results = []
        for move in range(len(state.board)):
            if not state.validMove(move, turn):
                results.append(-1000)
            else:
                movedState = deepcopy(state)
                movedState.makeMove(move, turn)
                if state.gameOver():
                    if state.winState() == turn: results.append(1)
                    elif state.winState() == 0: results.append(0)
                    else: results.append(-1)
                else:
                    results.append(-self.result(movedState, turn % 2 +
                                                1, depth - 0.5))
        return max(results)


if __name__ == "__main__":
    b = Breadth()
    s = State()
    s.makeMove(3, 1)
    s.makeMove(3, 1)
    #s.makeMove(3, 1)
    s.makeMove(4, 2)
    s.makeMove(4, 2)
    s.makeMove(4, 2)
    print b.move(s, 1)
コード例 #7
0
 def __init__(self, player, opponent):
     self.player = player
     self.opponent = opponent
     self.state = State()
     self.turn = 0
コード例 #8
0
ファイル: main.py プロジェクト: rockerbacon/8queens_ai
# Program call:
# 	python3 main.py <file containing initial state> HILL_CLIMBING <maximum number of sideway steps allowed>
#		Recommended value for sideway steps: 3-5. The hill climbing algorithm will accept a solution that's as good as the one currently set as the best one using this value as the number of times it's allowed to do so.
#	python3 main.py <file containing initial state> SIMULATED_ANNEALING <initial temperature> <cooling rate>
# 		Recommended values: <initial temperature> = 10-1000, <cooling rate> = 0.005-0.01
#	python3 main.py GENETIC_ALGORITHM <population size> <reproduction rate> <mutation probability> <gamma k> <gamma theta>
#		Recommended values: <population size> = 1000, <reproduction rate> = 0.5, <mutation probability> = 0.15, <gamma k> = 2, <gamma theta> = <population size>/(4 x <gamma k>)
#		The values of k and theta determine who will be selected for reproduction and substitution. The recomended values will make so that, in general, the 25% best will reproduce and the 25% worst will be replaced (Average = k x theta). Smaller values of k increase the elitism, while smaller values get the distribution closer to a normal distribution
#
#
# The file contains 8 integers where each represent the colum the queen in that line is
#
# In case it's not possible to find a solution with the given initial state, the state is shuffled and the choses algorithm runs again using the shuffled state.
	
solution = State()
tries = 0
	
if sys.argv[2] == 'HILL_CLIMBING':
	solution.readFromFile( open(sys.argv[1], 'r') )
	solution.evaluate()
	sidewayLimit = int(sys.argv[3])
	
	while solution.value > 0:
		tries += 1
		solution = hillClimb(solution, sidewayLimit)
		
		if solution.value > 0:
			solution.randomize()
			solution.evaluate()