Flexible number of queens on field

This commit is contained in:
2025-06-19 20:42:47 +02:00
parent 608faa4c93
commit 451b291b3e

29
P2.py
View File

@@ -64,11 +64,12 @@ class Field:
for row in range(8, 0, -1): # (0:8]
row_string = ""
for line in range(8):
if row is self.state[line]: # is there a Queen in this line (spalte) in this row
if line < len(self.state) and row is self.state[line]: # is there a Queen in this line (spalte) in this row
if (row + line) % 2 == 0:
row_string += "▌Q▐│"
else:
row_string += " Q │"
elif (row + line) % 2 == 0:
row_string += "███│"
else:
@@ -82,11 +83,11 @@ class Field:
class Genetic:
def __init__(self):
def __init__(self, size=100):
self.initial_population = []
self.p_mutation = 0.1
self.p_mutation = 0
for i in range(100):
for i in range(size):
self.initial_population.append(Field())
def random_selection(self, population):
@@ -144,27 +145,33 @@ class Genetic:
if child.get_fitness() > best_field.get_fitness():
best_field = child
if best_field.get_fitness() == 28:
break
current_population = new_population
new_population = []
if best_field.get_fitness() == 28:
break
return best_field
def main():
new_field = Field(
init_state=[6, 3, 5, 7, 1, 4, 2, 8]) # [8, 4, 5, 4, 4, 3, 7, 6] [5, 5, 5, 5, 1, 2, 8, 5] [6,3,5,7,1,4,2,8]
init_state=[1,2,3]) # [8, 4, 5, 4, 4, 3, 7, 6] [5, 5, 5, 5, 1, 2, 8, 5] [6,3,5,7,1,4,2,8]
new_field.print_field()
print(new_field.collisions())
genetic = Genetic()
best_genetic_field = genetic.genetic_algorithm(500)
print("Genetic Algorithm")
genetic = Genetic(500)
best_genetic_field = genetic.genetic_algorithm(100)
best_genetic_field.print_field()
print(best_genetic_field.get_fitness())
main()