Laboratory 6 Solutions
Solution to eight.cc code:
/******************************************************************* * Name: Brenda Student * Date: 3/19/14 * Course: CSCI 132 Section 01 * Assignment: Lab 6 * Instructor: Royden * Program: eight.cc * Purpose: A program that plays the game of eight, using look-ahead * strategy to choose the moves for the computer. ***************************************************************************/ #include <iostream> #include "board.h" using namespace std; int look_ahead(Board &, int, int &); int main(void) { Board gameBoard; //Board for playing game int user_move, computer_move; //Moves made by computer or user int depth = 8; //depth of look ahead by computer gameBoard.instructions(); while(!gameBoard.done()) { //Play until the game is finished cout << "Please enter a number: "; cin >> user_move; while (!gameBoard.is_legal(user_move)) { //Until a legal move is entered. cout << "That move is not legal, choose another number: "; cin >> user_move; } //end while cout << "You have chosen the number " << user_move << "." << endl; gameBoard.play(user_move); //Make user's move cout << "The total score is " << gameBoard.getTotal() << "." << endl << endl; if (!gameBoard.done()) { look_ahead(gameBoard, depth, computer_move); //Choose computer's move cout << "The computer chooses the number " << computer_move << "." << endl; gameBoard.play(computer_move); cout << "The total score is " << gameBoard.getTotal() << "." << endl << endl; } //end if } //end while cout << "The game is over. "; if (gameBoard.the_winner() == 1) { //Ties are not possible in this game cout << "You win!" << endl; } else { cout << "The computer wins!" << endl; } //end if-else return 0; } //end main int look_ahead(Board &game, int depth, int &recommended) { /*Look ahead to end of game or number of levels given by depth to choose next move. Pre: game has been established and depth >=0 Post: value of best option is returned, best move is stored in recommended */ if (game.done() || depth == 0 ) { return game.evaluate(); } else { int value, bestValue = game.worst_case(); //value for look-ahead // and current best value for (int try_it = 1; try_it <= 3; try_it++ ) { if (game.is_legal(try_it)) { int reply; //recommended move for next look-ahead Board temp_board = game; //copy of playing board to try out moves temp_board.play(try_it); //Look ahead from tested move value = look_ahead(temp_board, depth - 1, reply); if (game.better(value, bestValue)) { //Save value if better bestValue = value; recommended = try_it; } // end if } //end if is_legal } //end for return bestValue; } //end if- else } //end look_ahead
Home | | Syllabus | | Assignments | | Lecture Notes