Warning, file /games/knavalbattle/src/ai/ai.cpp was not indexed or was modified since last indexation (in which case cross-reference links may be missing, inaccurate or erroneous).

0001 /*
0002     SPDX-FileCopyrightText: 2007 Paolo Capriotti <p.capriotti@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #include "ai.h"
0008 #include <QRandomGenerator>
0009 
0010 AI::AI(Sea::Player player, Sea* sea, const BattleShipsConfiguration* config)
0011 : m_player(player)
0012 , m_sea(sea)
0013 , m_config(config)
0014 {
0015 }
0016 
0017 Coord AI::desperateMove() const
0018 {
0019     Sea::Player opp = Sea::opponent(m_player);
0020     for (int i = 0; i < m_sea->size().x; i++)
0021     for (int j = 0; j < m_sea->size().y; j++) {
0022         if (m_sea->at(opp, Coord(i,j)).free()) {
0023             return Coord(i,j);
0024         }
0025     }
0026     return Coord::invalid();
0027 }
0028 
0029 void AI::setShips()
0030 {
0031     // set up computer ships
0032     // set first the biggest ship, it is more difficult to reach impossible combinations
0033     // TODO: Another placing algorithm, create a list of available places and choose randomly from them.
0034     // number of repetitions because the random place is over a previous ship = 0
0035     bool canFinish = true;
0036     auto *generator = QRandomGenerator::global();
0037     do {
0038         for (int size = m_config->longestShip(); size >= 1; size--) {
0039             for (unsigned int j = 1; j <= m_config->numberOfShipsOfSize(size); j++) {
0040                 Ship* ship = nullptr;
0041                 while (ship == nullptr && canFinish) {
0042                     Coord c(generator->bounded(m_sea->size().x), generator->bounded(m_sea->size().y));
0043                     Ship::Direction dir = generator->bounded(2) == 0 ? Ship::LEFT_TO_RIGHT : Ship::TOP_DOWN;
0044                     if (m_sea->canAddShip(m_player, c, size, dir)) {
0045                         ship = new Ship(size, dir, c);
0046                         m_sea->add(m_player, ship);
0047                     }
0048                     else {
0049                         canFinish = m_sea->canAddShipOfSize(m_player, size);
0050                     }
0051                 }
0052             }
0053         }
0054     } while ( !canFinish );
0055 }