#include #include "AIController.h" AIController::AIController(Player *pPlayer, Field& field, int inhibitDelay, int randomThreshold): Controller(pPlayer), m_field(field), m_inhibitDelay(inhibitDelay), m_randomThreshold(randomThreshold) { m_inhibit = 0; } AIController::~AIController(void) { } void AIController::reset() {} void AIController::think() { Coordinates coord = m_pPlayer->getCoordinates(); VelocityVector velocity = m_pPlayer->getVelocity(); // assume either x or y is null int speed = max(abs(velocity.x), abs(velocity.y)); int sgn_x = velocity.x == 0 ? 0 : (velocity.x > 0 ? 1 : -1); int sgn_y = velocity.y == 0 ? 0 : (velocity.y > 0 ? 1 : -1); for (int i = 1; i <= m_inhibitDelay*speed+1 ; ++i ) { try { if (m_field.getCell(Coordinates(coord.x+i*sgn_x, coord.y+i*sgn_y)).getState()) { turnRandom(); } } catch (std::out_of_range e) { turnRandom(); } } if (rand() % 100 <= m_randomThreshold) turnRandom(); m_inhibit = max(0,m_inhibit-1); } void AIController::turnRandom() { if (m_inhibit == 0) { VelocityVector oldVelocity = m_pPlayer->getVelocity(); VelocityVector leftVelocity = VelocityVector(- oldVelocity.y, oldVelocity.x); // right = -left int sgn_x = leftVelocity.x == 0 ? 0 : (leftVelocity.x > 0 ? 1 : -1); int sgn_y = leftVelocity.y == 0 ? 0 : (leftVelocity.y > 0 ? 1 : -1); Coordinates coord = m_pPlayer->getCoordinates(); uint freeSpaceLeft = 1; uint freeSpaceRight = 1; try { while (1) { if (m_field.getCell(Coordinates(coord.x+freeSpaceLeft*sgn_x, coord.y+freeSpaceLeft*sgn_y)).getState()) break; freeSpaceLeft++; } } catch (std::out_of_range e) {} try { while (1) { if (m_field.getCell(Coordinates(coord.x-freeSpaceRight*sgn_x, coord.y-freeSpaceRight*sgn_y)).getState()) break; freeSpaceRight++; } } catch (std::out_of_range e) {} if (max(freeSpaceRight,freeSpaceLeft) > m_inhibitDelay*max(abs(leftVelocity.x),abs(leftVelocity.y))+1) { (freeSpaceLeft > freeSpaceRight) ? m_pPlayer->turnLeft() : m_pPlayer->turnRight(); m_inhibit = m_inhibitDelay; } } }