2023-09-24 18:17:51 -05:00
|
|
|
#include "chess.hpp"
|
|
|
|
#include <iostream>
|
|
|
|
#include <random>
|
|
|
|
|
|
|
|
std::default_random_engine generator;
|
|
|
|
|
|
|
|
void InitializeGenerator(void) {
|
|
|
|
generator.seed(std::random_device{}());
|
|
|
|
}
|
|
|
|
|
|
|
|
int GenerateRandomNumber(int generationLimit) {
|
|
|
|
int generatedNumber;
|
|
|
|
std::uniform_int_distribution<> distribution(0, generationLimit - 1);
|
|
|
|
generatedNumber = distribution(generator);
|
|
|
|
return generatedNumber;
|
|
|
|
}
|
|
|
|
|
|
|
|
GeneticDefaults::GeneticDefaults(void) {
|
|
|
|
size = 8;
|
|
|
|
length = 8;
|
|
|
|
}
|
|
|
|
|
|
|
|
GeneticDefaults::GeneticDefaults(unsigned int size, unsigned int length) {
|
|
|
|
this->size = size;
|
|
|
|
this->length = length;
|
|
|
|
}
|
|
|
|
|
|
|
|
GeneticChess::GeneticChess(void) {
|
|
|
|
generationCount = 0;
|
|
|
|
InitializeGenerator();
|
|
|
|
// population init part of vector resize
|
|
|
|
board.resize(genetics.size, 0);
|
|
|
|
for (int i = 0; i < board.size(); ++i) {
|
|
|
|
board.at(i) = GenerateRandomNumber(genetics.size);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
void GeneticChess::Print(void) {
|
|
|
|
std::cout << generationCount << ':' << std::endl;
|
|
|
|
for (int i : board) {
|
|
|
|
std::cout << '[';
|
|
|
|
for (int j = 0; j < genetics.size; ++j) {
|
|
|
|
if (j == i) { std::cout << "Q"; }
|
|
|
|
else { std::cout << ' '; }
|
|
|
|
}
|
|
|
|
std::cout << ']';
|
|
|
|
std::cout << std::endl;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Gets the fitness of the population
|
|
|
|
unsigned int GeneticChess::GetFitness(void) {
|
|
|
|
int fitness = 0;
|
|
|
|
for (int i : board) {
|
|
|
|
if (!IsQueenThreatened(i)) { fitness++; }
|
|
|
|
}
|
|
|
|
return fitness;
|
|
|
|
}
|
|
|
|
|
|
|
|
//
|
|
|
|
void GeneticChess::Selection(void) {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// Crossover on the population
|
|
|
|
void GeneticChess::Crossover(void) {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// Mutates the population
|
|
|
|
void GeneticChess::Mutation(void) {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
// Checks if the passed in queen is threatened on the board
|
|
|
|
// Impossible for queens to be threatened by same row
|
|
|
|
bool GeneticChess::IsQueenThreatened(const unsigned int queenRow) {
|
|
|
|
int queenCol = board.at(queenRow);
|
|
|
|
int diffRow, diffCol;
|
|
|
|
for (int i = 0; i < genetics.size; ++i) {
|
|
|
|
if (i == queenRow) { continue; }
|
|
|
|
diffCol = queenCol - board.at(i);
|
|
|
|
diffRow = queenRow - i;
|
|
|
|
if (diffCol == 0) { return true; } // Column threat
|
|
|
|
if (diffCol == diffRow) { return true; }
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|