Laboratory 6 Solutions
Solution to board.cc code:
/*******************************************************************
* Name: Brenda Student
* Date: 3/19/14
* Course: CSCI 132 Section 01
* Assignment: Lab 6
* Instructor: Royden
* Program: board.cc
* Purpose: Implementation of board class for playing game of eight
***************************************************************************/
#include "board.h"
Board :: Board() {
/*Post: Board is created and all variables initialized to zero */
total = 0;
moves_done = 0;
last_move = 0;
}
int Board::evaluate( ) const {
/*Post: If player 1 wins, returns a value of 9 minus the number of moves taken,
If player 2 wins, returns a value of -9 plus the number of moves taken.
If no winner yet, returns zero. */
int winner = the_winner();
if (winner == 1) {
return 9 - moves_done;
}
else if (winner == 2) {
return moves_done - 9;
} else {
return 0;
}
}
bool Board::better(int value, int old_value) const {
/*Post: Returns true if value is better than old_value for the player who took the
most recent move, returns false otherwise */
if ((moves_done %2) == 1) {
return (value < old_value);
} else {
return (value > old_value);
}
}
int Board::worst_case( ) const {
/*Post: Returns the worst case value for the player who took the most recent move. */
if ((moves_done%2) == 1) {
return 9;
} else {
return -9;
}
}
bool Board :: is_legal(int move) const {
/*Post: Returns true if proposed move is legal, false otherwise */
if ((move < 1) || (move > 3) ) {
return false;
} else if (move == last_move) {
return false;
} else {
return true;
}
}
void Board::play(int move) {
/*Post: If move is legal, increments total by move, sets last_move to move and
increments moves_done. If move is not legal, it prints out an error message.*/
if (is_legal(move)) {
total += move;
last_move = move;
moves_done++;
} else {
cout << "Not a legal move! " << endl;
}
}
int Board::the_winner() const {
/*Post: Returns 1 if player 1 has won, 2 if player 2 has won, and 0 if no winner yet */
if (!done()) {
return 0;
} else if (total > 8) {
return moves_done%2 + 1;
} else {
return 2 - moves_done%2;
}
}
bool Board::done() const {
/*Post: Returns true if the game is over, false otherwise */
if (total >= 8) {
return true;
} else {
return false;
}
}
int Board::getTotal( ) const {
/*Post: Returns total score so far. */
return total;
}
void Board::instructions() {
/*Post: Prints out the instructions for the game. */
cout << "Welcome to the game of eight!" << endl;
cout << "In this game the players take turns choosing a number, 1, 2 or 3."
<< endl;
cout << "You may not choose the last number chosen. " << endl;
cout << "A running total of the numbers is kept." << endl;
cout << "If a player chooses a number to make the total equal to eight, "
<< endl << "that player wins." << endl;
cout << "If a player chooses a number to make the total greater than eight, "
<< endl << "that player loses." << endl << endl;
}
Home | | Syllabus | | Assignments | | Lecture Notes