This commit is contained in:
Russell Ballestrini 2024-09-09 14:03:55 -04:00
parent adcae700f8
commit ef127236e1
2 changed files with 1465 additions and 1240 deletions

View file

@ -20,6 +20,7 @@ MUTATION_MULTIPLIERS = {
"parity_weight": 1.5,
"hunt_mode_threshold": 1.0,
"prob_grid_weight": 1.0,
"avoid_edges_weight": 1.0, # Added for avoid_edges_weight
}
@ -30,6 +31,7 @@ class BattleshipStrategy:
PARITY_WEIGHT_RANGE = (0, 10)
HUNT_MODE_THRESHOLD_RANGE = (0.1, 1)
PROB_GRID_WEIGHT_RANGE = (0, 1)
AVOID_EDGES_WEIGHT_RANGE = (0, 1) # New weight range
def __init__(self):
self.adjacent_hit_weight = random.uniform(*self.ADJACENT_HIT_WEIGHT_RANGE)
@ -37,6 +39,9 @@ class BattleshipStrategy:
self.parity_weight = random.uniform(*self.PARITY_WEIGHT_RANGE)
self.hunt_mode_threshold = random.uniform(*self.HUNT_MODE_THRESHOLD_RANGE)
self.prob_grid_weight = random.uniform(*self.PROB_GRID_WEIGHT_RANGE)
self.avoid_edges_weight = random.uniform(
*self.AVOID_EDGES_WEIGHT_RANGE
) # Initialize new weight
self._probability_grid = None
def serialize(self, include_grid=False):
@ -46,6 +51,7 @@ class BattleshipStrategy:
"parity_weight": self.parity_weight,
"hunt_mode_threshold": self.hunt_mode_threshold,
"prob_grid_weight": self.prob_grid_weight,
"avoid_edges_weight": self.avoid_edges_weight, # Include in serialization
}
if include_grid:
data["probability_grid"] = self.probability_grid
@ -83,6 +89,12 @@ class BattleshipStrategy:
):
self.probability_grid[ni][nj] *= self.adjacent_hit_weight
# Apply avoid_edges_weight
for i in range(GRID_SIZE):
for j in range(GRID_SIZE):
if i == 0 or i == GRID_SIZE - 1 or j == 0 or j == GRID_SIZE - 1:
self.probability_grid[i][j] *= 1 - self.avoid_edges_weight
max_prob = max(max(row) for row in self.probability_grid if max(row) > 0)
if max_prob > 0:
for i in range(GRID_SIZE):
@ -220,6 +232,12 @@ def crossover(parent1, parent2):
child.hunt_mode_threshold = random.choice(
[parent1.hunt_mode_threshold, parent2.hunt_mode_threshold]
)
child.prob_grid_weight = random.choice(
[parent1.prob_grid_weight, parent2.prob_grid_weight]
)
child.avoid_edges_weight = random.choice(
[parent1.avoid_edges_weight, parent2.avoid_edges_weight]
)
return child
@ -250,6 +268,13 @@ def mutate(individual):
individual.prob_grid_weight = random.uniform(
*BattleshipStrategy.PROB_GRID_WEIGHT_RANGE
)
if (
random.random()
< BASE_MUTATION_RATE * MUTATION_MULTIPLIERS["avoid_edges_weight"]
):
individual.avoid_edges_weight = random.uniform(
*BattleshipStrategy.AVOID_EDGES_WEIGHT_RANGE
)
return individual
@ -345,7 +370,7 @@ def genetic_algorithm(continue_training=False):
json.dump(
[strategy.serialize() for strategy in population], f, indent=4
)
#tqdm.write(f"Generation {generation + 1} saved successfully.")
# tqdm.write(f"Generation {generation + 1} saved successfully.")
except Exception as e:
tqdm.write(f"Error saving generation {generation + 1}: {e}")