char countEndangered(char f[SIZEX][SIZEY], char p) { unsigned char x,y,danger; danger = 0; for(x = 0; x < SIZEX; ++x) { for(y = 0; y < SIZEY; ++y) { if(getOwner(f, x, y) == p && computeDanger(f, p, x, y)) ++danger; } } return danger; }
// Recommend a move for a player at (r,c): A false return means the // recommendation is that the player should stand; otherwise, bestDir is // set to the recommended direction to move. bool recommendMove(const Arena& a, int r, int c, int& bestDir) { // How dangerous is it to stand? int standDanger = computeDanger(a, r, c); // if it's not safe, see if moving is safer if (standDanger > 0) { int bestMoveDanger = standDanger; int bestMoveDir = NORTH; // arbitrary initialization // check the four directions to see if any move is // better than standing, and if so, record the best for (int dir = 0; dir < NUMDIRS; dir++) { int rnew = r; int cnew = c; if (attemptMove(a, dir, rnew, cnew)) { int danger = computeDanger(a, rnew, cnew); if (danger < bestMoveDanger) { bestMoveDanger = danger; bestMoveDir = dir; } } } // if moving is better than standing, recommend move if (bestMoveDanger < standDanger) { bestDir = bestMoveDir; return true; } } return false; // recommend standing }
int thinkAI() { unsigned char x,y,size,owner; signed int tmp,score; unsigned int result; enableTurbo(); size = SIZEX * SIZEY; // compute the field score for the opposing player score = -32000; for(x = 0; x < SIZEX; ++x) { for(y = 0; y < SIZEY; ++y) { owner = getOwner(field, x, y); if(owner == PLAYERAI || owner == 0) { // we can use this cell memcpy(fieldAI, field, size); // create working copy tmp = 0; // it makes little sense to add atoms to endangered cells // unless they can start a chain reaction if(computeDanger(fieldAI, PLAYERAI, x, y) > 0 && isCritical(fieldAI, x, y) == 0) { tmp -= 10; } // let the reaction run putAtom(fieldAI, PLAYERAI, x, y, 0); react(fieldAI, 0); // evaluate the resulting field constellation tmp += evaluateField(fieldAI, PLAYERAI); if(tmp > score || (tmp == score && (rand() & 0x01))) { score = tmp; result = (x << 8) | y; } } } } disableTurbo(); return result; }