/** Plays the game automatically for the user */ private void AI() { isAI = true; // This tells other function that the AI is calling them AIUsed = true; // This stops the score being added to the low score list once the AI is used moveMade = false; // This is so the AI knows if it has made a move boolean isLegal = false; for (int i = 4; i < cardStrings.size() + 1; i++) { // Starts at i=4 as that is the first position in which jumping 2 piles is possible isLegal = piles.movePileTwoPlacesLeft( isLegal, i - 1, moveMade); // Checks if it is legal for that pile if (isLegal) { // If one of the piles can legally move moveMade = true; movePileTwoPlacesLeft(i, isAI, isLegal); // Move the pile over 2 piles to the left break; } } if (!moveMade) { // If up until here no move was made, then start checking if any card can move // to cards next to them for (int i = 1; i < cardStrings.size(); i++) { // Starts at i=1 as its the first position this move is possible isLegal = piles.movePileOntoPrevious(isLegal, i, moveMade); // Checks if it is legal if (isLegal) { // If it is legal moveMade = true; movePileOntoPrevious(i, isAI, isLegal); // Makes the move break; } } } if (!moveMade) { // If here, then no moves were possible, so (try to) draw a card if (drawCard) { // If drawing a card is possible dealCard(); // Deal a new card } } isAI = false; moveMade = false; }
/** * Move the last pile onto the previous if it is possible * * @param cardSelected The card to be moved * @param isAI Whether the AI has called this function * @param isLegal Whether the move is legal */ private void movePileOntoPrevious(int cardSelected, boolean isAI, boolean isLegal) { if (cardStrings.size() > 1 && cardSelected > 0 && cardSelected < cardStrings.size()) { if (!isAI) { // If the AI is calling this function, isLegal has already been decided, so // shouldn't be changed isLegal = false; } int pileToMove = cardSelected; int pileToRemove = cardSelected - 1; if (!isAI) { isLegal = piles.movePileOntoPrevious(isLegal, pileToMove, moveMade); } if (isLegal) { cardStrings.remove(pileToRemove); // Remove the pile from the table saveLog(); // Calls the function to log the turn } printFrame(); // Updates the frame } else { if (!isAI) { System.out.println("There are no pile to move the last pile onto"); } } isLegal = false; }