Table of Contents
:
Chapter 8 Exercise 8
Chapter 8 Exercise12
Chapter 2 Exercise 13
Chapter 8 Exercise 17
Video Game Struct Task
Student Class
Employee Class
TV Show Class
Chapter 11 Exercise 3
Chapter 11 Exercise 6
Chapter 11 Exercise 10
Chapter 11 Exercise 11
Chapter 11 Exercise 17
Mouse Click Task
Ch8 Ex 8
#include
#include
#include
int find(int startIndex, const String &word, char &str)
/*Searches the string word, starting from start index, looking for the
substring str, and returns the position of the 1st occurrence of str
Pre: substring must appear in the word
Post: returns the value position of the substring within the word*/ {
int pos = -1; int len; String temp; len = ((word.length()) -
startIndex); temp = word.substr(startIndex, len); pos = temp.find(str);
return pos;
}
int main()
{ vector String guess(5); String word; String answer; String nword; int
len; char letter; int pos = 0, pos2 = 0; int counter = 0;
cout<<"Enter word to be guessed: "; cin>>answer; len =
answer.length(); cout< cout<<"word is "; for (int x = 0; x
< answer.length();x++) { cout<<"-"; word +="-"; } nword =
word; do { counter++; cout<<"Enter letter guess($ to guess the
word): "; cin>>letter; if (letter != '$') { do { pos =
find(pos+1,answer,letter); nword = nword.substr(0, pos)+
answer.operator[](pos) + nword.substr(pos+1, len); }while(pos >=0);
cout<<"Word is "; } else { cout<<"Enter word guess: ";
cin>>word; if (word == answer) cout<<"CORRECT! You took
"<
#include
#include
#include
void displayBoard(const matrix &board)
{
for(int Row = 0; Row< board.numrows();Row++)
{
for(int Col = 0; Col tttBoard(5,5," ");
tttBoard[0][0]="PUZZLE";
tttBoard[0][1] = " BALL ";
tttBoard[4][3] = " DOLL ";
tttBoard[2][2] = " BALL ";
tttBoard[1][1] = " BALL ";
tttBoard[3][2] = " DOLL ";
tttBoard[4][4] =" DOLL ";
tttBoard[4][0] = "POSTER";
tttBoard[1][4] = "PUZZLE";
tttBoard[2][3] = "PUZZLE";
tttBoard[0][4] ="POSTER";
tttBoard[3][3] = "POSTER";
tttBoard[2][0] = " GAME ";
tttBoard[1][2] = " GAME ";
tttBoard[3][0] = " GAME ";
displayBoard(tttBoard);
cout<<"You won: ";
for(int i = 1; i<=10; i ++)
{
prize =tttBoard[random(5)][random(5)];
cout<<"Toss number "<
#include
void display(const matrix &cell)
{
for(int Row = 0; Row< cell.numrows();Row++)
{
for(int Col = 0; Col &cell,int row,int col)
{
if(cell[row][col] == 'X')
return true;
else
return false;
}
void getInput(matrix &cell)
{
int arow, acol;
do
{
cout<<"Enter coordinates of living cell (-99 to exit)"<>arow;
cout<<"Column: ";
cin>>acol;
if(arow>=0 && acol>=0 && arow< cell.numrows() && acol<=cell.numcols())
cell[arow][acol] = 'X';
}while((arow != -99) || (acol != -99));
}
void neighbors(const matrix &cell,const int row,const int col, matrix &neigh)
{
int rowT= row, colT = col, nbs = 0;
if(rowT < cell.numrows() -1)
if(cell[rowT +1][colT] == 'X')//bottom middle
nbs++;
if(colT < cell.numcols() -1)
if(cell[rowT][colT + 1] == 'X')//right middle
nbs++;
if(colT < cell.numcols() - 1 && rowT > cell.numrows() -1)
if(cell[rowT +1][colT +1] == 'X')//bottom right
nbs++;
if(colT > 0 && colT > 0)
if(cell[rowT-1][colT -1] == 'X') //top left
nbs++;
if(rowT > 0)
if(cell[rowT -1][colT] == 'X') //top middle
nbs++;
if(colT > 0)
if(cell[rowT][colT - 1] == 'X')//middle row right collumn
nbs++;
if(rowT >0 && colT < cell.numcols() -1)
if(cell[rowT - 1][colT+1] == 'X')//top right
nbs++;
if(rowT < cell.numrows() - 1 && colT > 0)
if(cell[rowT + 1][colT -1] =='X') // bottom left
nbs++;
neigh[row][col] = nbs;
cout< cell(20,20, 'O');
matrix neigh(20, 20, 0);
bool aliveDead;
char nDay;
int row=0, col=0, loops=0;
getInput(cell);
display(cell);
cout<>nDay;
}while(nDay == 'Y');
return 0; //<--
}
/*--------------------Configuration: Ch8EX13 - Win32 Debug--------------------
Compiling...
Ch8EX13.cpp
K:\C++\4th Quarter\Ch8EX13.cpp(98) : error C2061: syntax error : identifier 'aliveDead'
K:\C++\4th Quarter\Ch8EX13.cpp(119) : warning C4508: 'main' : function should return a value; 'void' return type assumed
K:\C++\4th Quarter\Ch8EX13.cpp(119) : error C2143: syntax error : missing ';' before 'while'
K:\C++\4th Quarter\Ch8EX13.cpp(120) : error C2143: syntax error : missing ';' before 'return'
K:\C++\4th Quarter\Ch8EX13.cpp(121) : error C2143: syntax error : missing ';' before '}'
K:\C++\4th Quarter\Ch8EX13.cpp(121) : error C2143: syntax error : missing ';' before '}'
K:\C++\4th Quarter\Ch8EX13.cpp(121) : error C2143: syntax error : missing ';' before '}'
Error executing cl.exe.
Ch8EX13.obj - 6 error(s), 1 warning(s)
*/
• Chapter 8 Exercise 17
#include
#include
void display(const vector &board, int player1, int player2)
{
cout<<" ";
for(int i = 0; i <=5; i++)
cout<<" "<5; x--)
cout<<" "< &board, int &player1, int &player2, bool &player, int col, int &endNum)
{
int numberInPot, tempCol;
if(player == true)
{
numberInPot = board[col];
board[col] = 0;
tempCol = col;
for (int i = numberInPot;i>0; i--)
{
tempCol --;
if(tempCol != -1)
{
board[tempCol] += 1;
endNum = tempCol;
}
else if(tempCol == -1)
{
player1 ++;
tempCol=12;
endNum = -9;
}
}
}
else if(player == false)
{
int loop=0;
numberInPot = board[col];
board[col] = 0;
tempCol = col;
for(int i = numberInPot; i>0; i--)
{
tempCol--;
if(tempCol != 5 || loop == 1)
{
board[tempCol] += 1;
endNum = tempCol;
}
else if(tempCol == 5)
{
player2 ++;
tempCol ++;;
endNum = -9;
loop =1;
}
}
}
}
int main()
{
int player1=0, player2=0, col, endNum = 0;
char letter;
bool player = true;
vector board(12, 3);
display(board, player1, player2);
cout<>letter;
if(player == true)
{
if(letter == 'a' || letter == 'A')
col =0;
else if(letter == 'b' || letter == 'B')
col =1;
else if(letter == 'c' || letter == 'C')
col =2;
else if(letter == 'd' || letter == 'D')
col =3;
else if(letter == 'e' || letter == 'E')
col =4;
else if(letter == 'f' || letter == 'F')
col =5;
}
else if(player == false)
{
if(letter == 'a' || letter == 'A')
col =11;
else if(letter == 'b' || letter == 'B')
col =10;
else if(letter == 'c' || letter == 'C')
col =9;
else if(letter == 'd' || letter == 'D')
col =8;
else if(letter == 'e' || letter == 'E')
col =7;
else if(letter == 'f' || letter == 'F')
col =6;
}
move(board, player1, player2, player, col, endNum);
cout<=0 && board[endNum]== 1)
{
if(player == true)
{
if(endNum == 0)
{
player1 += board[endNum +11];
board[endNum +11] = 0;
}
else if(endNum == 1)
{
player1 += board[endNum +9];
board[endNum +9] = 0;
}
else if(endNum ==2)
{
player1 += board[endNum +7];
board[endNum +7] = 0;
}
else if(endNum ==3)
{
player1 += board[endNum +5];
board[endNum +5] = 0;
}
else if(endNum ==4)
{
player1 += board[endNum +3];
board[endNum +3] = 0;
}
else if(endNum ==5)
{
player1 += board[endNum +1];
board[endNum +1] = 0;
}
}
else if(player == false)
{
if(endNum ==11)
{
player2 += board[endNum -11];
board[endNum -11] = 0;
}
else if(endNum ==10)
{
player2 += board[endNum -9];
board[endNum -9] = 0;
}
else if(endNum ==9)
{
player2 += board[endNum -7];
board[endNum -7] = 0;
}
else if(endNum ==8)
{
player2 += board[endNum -5];
board[endNum -5] = 0;
}
else if(endNum ==7)
{
player2 += board[endNum -3];
board[endNum -3] = 0;
}
else if(endNum ==6)
{
player2 += board[endNum -1];
board[endNum -1] = 0;
}
}
if(endNum == -9)
{
if(player == true)
player = true;
else if(player == false)
player = false;
}
else
{
if(player == true)
player = false;
else if(player == false)
player = true;
}
}
display(board, player1, player2);
cout<
#include
#include
int search(const vector &list, String key)
{
int len = list.length();
for (int i = 0; i &number, int newValue)
{
number.resize(1+number.length());
number[number.length()-1] = newValue;
}
void removeAndResize(vector &id, String key)
{
int position = search(id, key);
if (position >= 0)
{
for(int i = position; i &grocery)
{
for (int i = 0; i < grocery.length(); i++)
cout< grocery(14);
grocery[0] = "bacon";
grocery[1] = "ice pops";
grocery[2] = "soap";
grocery[3] = "paper towels";
grocery[4] = "captain crunch";
grocery[5] = "coffee";
grocery[6] = "chicken";
grocery[7] = "liverwurst";
grocery[8] = "pickled herring";
grocery[9] = "eggs";
grocery[10] = "artichokes";
grocery[11] = "milk";
grocery[12] = "cookies";
grocery[13] = "water";
cout<<"Grocery list"<=0; i--)
cout<
#include
#include
struct videoGame
{ videoGame(String aName, int aRating, int aMinAge, double
aEstCompletion, vector aSimilarGames); videoGame();
String name; int rating; int minAge; double estCompletion; vector
similarGames;
};
videoGame::videoGame(String aName, int aRating, int aMinAge, double
aEstCompletion, vector aSimilarGames) :name(aName),
rating(aRating), minAge(aMinAge), estCompletion(aEstCompletion),
similarGames(aSimilarGames)
{
}
videoGame::videoGame() :name("None"), rating(0), minAge(0),
estCompletion(0), similarGames(0)
{
}
void searchByAge(const vector &games, int age,
vector &nameOfGame)
{ int arraySize = 0; for(int i= 0; i &games)
{ for(int i = 0; i< games.length(); i++)
cout< &games)
{ double sum=0; for(int i = 0; i &name)
{ for(int i = 0; i < name.length(); i++)
cout< &games,
String gameName, vector &nameOfSimilarGames)
{ for(int i = 0; i games(5); double sum; int age; String
similarGame; vector nameOfGames(0); vector
nameOfSimilarGames(3); for(int i = 0; i>games[i].name;
cout<<"Enter the rating: "; cin>>games[i].rating;
cout<<"Enter the minimum age: "; cin>>games[i].minAge;
cout<<"Enter the estimated completion time: ";
cin>>games[i].estCompletion; for(int x = 0; x<
games[i].similarGames.length(); x++) { cout<<"Enter similar
games: "; cin>>games[i].similarGames[x]; } } cout<>age; searchByAge(games, age,
nameOfGames); cout<<"The games found for that age group are:
"<> similarGame; searchBySimilarGame(games, similarGame,
nameOfSimilarGames); display(nameOfSimilarGames); return 0;
}
/*
Enter the name of a game: Ab
Enter the rating: 2
Enter the minimum age: 12
Enter the estimated completion time: 5
Enter Similar Games: F
Enter Similar Games: Dm
Enter Similar Games: Kr
Enter the name of a game: XM
Enter the rating: 12
Enter the minimum age: 12
Enter the estimated completion time: 2
Enter Similar Games: Dmv
Enter Similar Games: Xme
Enter Similar Games: Drm
Enter the name of a game: K
Enter the rating: 6
Enter the minimum age: 9
Enter the estimated completion time: 12
Enter Similar Games: yen
Enter Similar Games: hep
Enter Similar Games: ABR
Enter the name of a game: F
Enter the rating: 2
Enter the minimum age: 14
Enter the estimated completion time: 15
Enter Similar Games: ay
Enter Similar Games: tem
Enter Similar Games: red
Enter the name of a game: j
Enter the rating: 10
Enter the minimum age: 13
Enter the estimated completion time: 2
Enter Similar Games: qem
Enter Similar Games: pen
Enter Similar Games: ir
Games Entered:
Ab
XM
K
F
j
The sum of the estimated hours to finish the games is: 36
Enter an age to search for: 13
The games found for that age group are:
j
Enter name of game to find similar matches of: F
ay
tem
red
Press any key to continue
/*
• Student Class
Main Data File:
#include "studentclass.h"
#include
#include
#include
void enterData(vector &students)
{
String name, classPeriod,couns;
double gpa;
int grade;
for(int i = 0; i < 5; i ++)
{
cout<<"Enter Student name: ";
cin>>name;
students[i].setName(name);
cout<<"Enter GPA of student: ";
cin>>gpa;
students[i].setGpa(gpa);
for(int x = 1; x<=8; x++)
{
cout<<"Enter class for period "<>classPeriod;
students[i].addCourse(classPeriod, x);
}
cout<<"Enter counselor name: ";
cin>>couns;
students[i].setCounselor(couns);
cout<<"Enter student grade: ";
cin>>grade;
students[i].setGrade(grade);
cout< &students)
{
double sum;
for(int i = 0; i<5; i ++)
{
sum += students[i].getGpa();
}
return (sum / 5);
}
void displayByGuidence(vector &students, String guidence)
{
for(int i = 0; i <5; i ++)
{
if(students[i].getCounselorName() == guidence)
students[i].display();
}
}
void displayLowest(vector &students)
{
double lowest = students[0].getGpa();
int index=0;
for(int i = 0;i<5; i++)
{
if(students[i].getGpa() < lowest)
{
lowest = students[i].getGpa();
index = i;
}
}
cout<<"The student with the lowest GPA("< students(5);
enterData(students);
cout<<"The average of all GPA's is: "<>counselor;
displayByGuidence(students, counselor);
displayLowest(students);
cout<<"Displaying all info for all students: "><
#include
class studentClass
{
public:
studentClass();
studentClass(String aName, double aGpa, int aGrade, vector courselist, String counselor);
void display();
double getGpa();
vector getCourseList();
String getCounselorName();
void setGpa(double aGpa);
void setName(String aName);
void setCounselor(String counselor);
void addCourse(String course, int peroid);
void setGrade(int aGrade);
private:
String name;
double gpa;
int grade;
vector enrolledCourses;
String counselorName;
};
#include "studentclass.cpp"
• Employee Class
Main Data File:
#include
#include
#include
#include "employeeclass.h"
void enterData(vector &employees)
{
String name, title;
long salary;
int vacationDays, yearsEmployed;
for(int i = 0; i < 5; i ++)
{
cout<<"Enter Employee name: ";
cin>>name;
employees[i].setName(name);
cout<<"Enter Employee Title: ";
cin>>title;
employees[i].setJobTitle(title);
cout<<"Enter salary: ";
cin>>salary;
employees[i].setSalary(salary);
cout<<"Enter years employed: ";
cin>>yearsEmployed;
employees[i].setYearsEmployed(yearsEmployed);
cout<<"Enter vacation days: ";
cin>>vacationDays;
employees[i].setVacationDays(vacationDays);
cout< &employees)
{
int index;
int senior = employees[0].getYearsEmployed();
for(int i = 0; i < 10; i ++){
if(senior < employees[i].getYearsEmployed()){
senior=employees[i].getYearsEmployed();
index = i;
}
}
employees[index].display();
}
long sumOfSalaries(vector &employees)
{
long sum=0;
for(int i = 0; i<10; i++)
{
sum+=employees[i].getSalary();
}
return sum;
}
long sumOfVacationDays(vector &employees)
{
long sum=0;
for(int i = 0; i<10; i++)
{
sum+=employees[i].getVacationDays();
}
return sum;
}
vector newEmployees(vector &employees)
{
vector newWorkers;
int elements=0;
for(int i = 0; i<10; i++)
{
if(employees[i].getYearsEmployed()<5)
{
elements ++;
newWorkers.resize(elements);
newWorkers[elements-1] = employees[i];
}
}
return newWorkers;
}
int main()
{
vector employees(10);
vector newWorkers;
enterData(employees);
mostSenior(employees);
cout<<"The sum of all the salaries is: "><>sumOfVacationDays(employees)<
.h Data File:
#include
#include
class employeeClass
{
public:
employeeClass();
employeeClass(String aName, String aJobTitle, long aSalary, int aVacationDays, int aYearsEmployed);
employeeClass(String aName, String aJobTitle, long aSalary, int aVacationDays);
void display();
void setName(String aName);
void setSalary(long aSalary);
void setVacationDays(int aVacationDays);
void setYearsEmployed(int aYearsEmployed);
void setJobTitle(String aJobTitle);
String getJobTitle();
long getSalary();
int getVacationDays();
void takeVacation(int numDays);
int getYearsEmployed();
void increaseYear();
private:
String name;
String jobTitle;
long salary;
int vacationDays;
int yearsEmployed;
};
#include "employeeClass.cpp"
• TV Show Class
Main Data File:
#include
#include
#include
tvClass::tvClass()
:name("None"), duration(0), firstAirDate("None"), timeSlot(0),
channel(0)
{ actors.resize(0);
}
tvClass::display()
{ cout<<"\nName: "< aActors)
{ actors = aActors;
}
tvClass::setTimeSlot(double aTimeSlot)
{ timeSlot = aTimeSlot;
}
tvClass::setChannel(int aChannel)
{ channel = aChannel;
}
tvClass::setDuration(int aDuration)
{ duration = aDuration;
}
Header File:
#include
#include
#include
class tvClass
{
public:
tvClass();
tvClass();
tvClass();
tvClass();
display();
getName();
getAirDate();
getActorArray();
getTimeSlot();
getChannel();
getDuration();
setName(String aName);
setAirDate(String aAirDate);
setActors(vector aActors);
setTimeSlot(double aTimeSlot);
setChannel(int aChannel);
setDuration(int aDuration);
private:
String name;
int duration;
String firstAirDate;
vector actors;
double timeSlot;
int channel;
}
#include "tvshowclass.cpp"
• Chapter 11 Exercise 3
#include
int main()
{
const double PI = 3.141593;
cout.setf(10)
cout<
#include
#include
#include
#include
//--------------------------------------------------------------------------------
class ButtonClass {
public: ButtonClass(String Text, int X1,int Y1, int X2, int Y2); /*
Post: A button created with upper-left corner at X1,Y1 and lower-right
corner at X2,Y2 with Text centered in box */ void Paint(); bool
IsHit(int x, int y); /* Post: true returned if and only if (x,y) is on
the button */
private: int MyX1, MyY1, MyX2, MyY2; String MyText;
};
//--------------------------------------------------------------------------------
ButtonClass::ButtonClass(String Text, int X1, int Y1, int X2, int Y2) :
MyText(Text), MyX1(X1), MyY1(Y1), MyX2(X2), MyY2(Y2)
/* Post: Button created with upper-left corner at X1, Y1 and lower
right corner at X2,Y2 with Text centered in box */
{
}
//--------------------------------------------------------------------------------
void ButtonClass::Paint()
{ SetColor(BLACK); Rectangle(MyX1, MyY1, MyX2, MyY2);
gotoxy((MyX1+MyX2)/2, 5+(MyY1+MyY2)/2); DrawCenteredText(MyText);
}
//--------------------------------------------------------------------------------
bool ButtonClass::IsHit(int x, int y)
/* Post: true returned if and only if point (x, y) is on the button */
{ return (x >= MyX1 && x <= MyX2 && y >= MyY1
&& y <= MyY2);
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
class GridClass {
public: GridClass(); void Paint(); void MouseClick(int x, int y); void
InitGrid(); void winner();
private: const int GridDimension; // # of Rows/columns in grid //
Constants for board; must all differ const int Empty, EmptyPicked,
xPicked, oPicked; matrix Board; // Uses above constants bool
GameOver; int NumClicks; int BoxSize; // Pixels per box int LeftMargin;
// Pixels from left int TopMargin; // Pixels from top void
XYToRowCol(int x, int y, int &Row, int &Col); void MarkBox(int
Row, int Col, int BoxContents); ButtonClass QuitButton;
};
//--------------------------------------------------------------------------------
GridClass::GridClass() : GridDimension(3), Empty(0), EmptyPicked(-1),
xPicked(1), oPicked(2), Board(GridDimension,GridDimension,0),
NumClicks(0), GameOver(false),BoxSize(GetMaxY()/2/GridDimension), //
Fill half of y-dimension
LeftMargin((GetMaxX()-BoxSize*GridDimension)/2),TopMargin(GetMaxY()/4),
QuitButton("I give up!",10,10,100,40)
{
}
//--------------------------------------------------------------------------------
void GridClass::InitGrid()
/* Post: Grid initialized for a new game */
{ NumClicks=0; GameOver=false; for (int Row=0; Row < GridDimension;
Row++) for (int Col=0; Col < GridDimension; Col++) Board[Row][Col] =
Empty;
}
//--------------------------------------------------------------------------------
void GridClass::XYToRowCol(int x, int y, int &Row, int &Col)
/* Post: Row and Column corresponding to x, y returned, or -1 for if x,
y is not on the board*/
{ int DistFromLeft = x - LeftMargin; Col=(DistFromLeft+BoxSize)/BoxSize
-1; int DistFromTop = y - TopMargin; Row=(DistFromTop+BoxSize)/BoxSize
-1; if (Col < 0 || Col >= GridDimension || Row < 0 || Row
>= GridDimension) { Row = -1; Col = -1; }
}
//--------------------------------------------------------------------------------
void GridClass::MarkBox(int Row, int Col, int BoxContents)
/* Post: Row, Col box in appropriate color */
{ SetColor(BLACK); // For outline SetFillColor(WHITE); if
(BoxContents==Empty) SetFillColor(WHITE); else if
(BoxContents==xPicked) SetFillColor(RED); else if (BoxContents ==
oPicked) SetFillColor(BLUE); FilledRectangle(Col*BoxSize+LeftMargin,
Row*BoxSize+TopMargin,(Col+1)*BoxSize+LeftMargin,
(Row+1)*BoxSize+TopMargin);
}
//--------------------------------------------------------------------------------
void GridClass::winner()
{ for(int i = 0; i<3; i++) { if(Board[i][0] %2== 1 &&
Board[i][1]%2==1 && Board[i][2]%2==1) { MessageBox("X Wins", "X
Wins"); PostQuitMessage(0); } else if(Board[i][0] %2== 0 &&
Board[i][1]%2==0 && Board[i][2]%2==0) { MessageBox("O Wins", "O
Wins"); PostQuitMessage(0); } }
}
//--------------------------------------------------------------------------------
void GridClass::MouseClick(int x, int y)
{ int Row=0, Col=0; XYToRowCol(x, y, Row, Col); if
(QuitButton.IsHit(x,y)) { GameOver = true; Paint(); // To show the
treasure square MessageBox("Come back again!", "Quit button clicked");
PostQuitMessage(0); } else if(Board[Row][Col] ==Empty) { XYToRowCol(x,
y, Row, Col); if (Board[Row][Col] == Empty) { if (NumClicks% 2 == 1) {
Board[Row][Col] = xPicked; GameOver = false; MarkBox(x, y,
Board[Row][Col]); Paint(); // To show treasure square winner(); /*if
(MessageBoxYN("X Wins! Play again?", "Game over")==1) InitGrid(); else
PostQuitMessage(0);*/ } else if(NumClicks%2 ==0) { Board[Row][Col] =
oPicked; GameOver = false; MarkBox(x, y, Board[Row][Col]); Paint();
winner(); /*if(MessageBoxYN("O Wins! Play again?", "Game over") ==1)
InitGrid(); else PostQuitMessage(0);*/ } NumClicks++; } } else
MessageBeep(-1);
}
//--------------------------------------------------------------------------------
void GridClass::Paint()
{ QuitButton.Paint(); SetColor(BLACK); int Row, Col; // Draw lines for
(Col = 0; Col <= GridDimension; Col++) Line(LeftMargin+Col*BoxSize,
TopMargin, LeftMargin+Col*BoxSize, TopMargin+GridDimension*BoxSize);
for (Row = 0; Row <= GridDimension; Row++) Line(LeftMargin,
TopMargin+Row*BoxSize, LeftMargin+GridDimension*BoxSize,
TopMargin+Row*BoxSize); // Color in boxes for (Row=0; Row <
GridDimension; Row++) for (Col=0; Col < GridDimension; Col++)
MarkBox(Row,Col,Board[Row][Col]); // Display results if
(GameOver==true) { gotoxy(20,GetMaxY()-60); DrawText("Game over! Score
= "); DrawText(NumClicks); }
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
class GuiClass {
public: GuiClass(); void GuiMouseClick(int x, int y); //Action if mouse
click void GuiPaint(); // Repaint the entire window String Title(); //
Title to display
private: GridClass Game;
};
//--------------------------------------------------------------------------------
GuiClass::GuiClass()
{
}
//--------------------------------------------------------------------------------
String GuiClass::Title()
{ return ("Tic-Tac-Toe Game");
}
//--------------------------------------------------------------------------------
void GuiClass::GuiMouseClick(int x, int y)
{ Game.MouseClick(x, y);
}
//--------------------------------------------------------------------------------
void GuiClass::GuiPaint()
{ Game.Paint();
}
//--------------------------------------------------------------------------------
#include
• Chapter 11 Exercise 10
or(RED); else if (BoxContents == Blue) SetFillColor(BLUE);
FilledRectangle(Col*BoxSize+LeftMargin,
Row*BoxSize+TopMargin,(Col+1)*BoxSize+LeftMargin,
(Row+1)*BoxSize+TopMargin);
}
//-------------------------------------------------------------------
int GridClass::winner()
{ numEmpty=0; /* for (int Row=0; Row < GridDimension; Row++) { for
(int Col=0; Col < GridDimension2-5; Col++) { if(Board[Row][Col] ==
Blue &&Board[Row][Col+1]==Blue&&Board[Row][Col+2]==Blue
&& Board[Row][Col+3]==Blue) return Blue; else
if(Board[Row][Col] == Red &&Board[Row][Col+1]==Red
&&Board[Row][Col+2]==Red &&Board[Row][Col+3]==Red)
return Red; } } for (int Row1=0; Row1 < GridDimension-5; Row1++){
for (int Col1=0; Col1 < GridDimension2; Col1++){
if(Board[Row1][Col1] == Blue
&&Board[Row1+1][Col1]==Blue&&Board[Row1+2][Col1]==Blue
&& Board[Row1+3][Col1]==Blue) { return Blue; } else
if(Board[Row1][Col1] == Red &&Board[Row1+1][Col1]==Red
&&Board[Row1+2][Col1]==Red &&Board[Row1+3][Col1]==Red){
return Red; } } } for (int Row3=0; Row3 < GridDimension-5; Row3++){
for (int Col3=0; Col3 < GridDimension2-5; Col3++){
if(Board[Row3][Col3] == Blue
&&Board[Row3+1][Col3+1]==Blue&&Board[Row3+2][Col3+2]==Blue
&& Board[Row3+3][Col3+3]==Blue){ return Blue; } else
if(Board[Row3][Col3] == Red &&Board[Row3+1][Col3+1]==Red
&&Board[Row3+2][Col3+2]==Red
&&Board[Row3+3][Col3+3]==Red){ return Red; } } } for(int Row4 =
GridDimension; Row4>3; Row4--) { for(int Col4 = GridDimension2;
Col4>3; Col4--) { if(Board[Row4][Col4] == Blue
&&Board[Row4-1][Col4-1]==Blue&&Board[Row4-2][Col4-2]==Blue
&& Board[Row4-3][Col4-3]==Blue){ return Blue; } else
if(Board[Row4][Col4] == Red &&Board[Row4-1][Col4-1]==Red
&&Board[Row4-2][Col4-2]==Red
&&Board[Row4-3][Col4-3]==Red){ return Red; } } } */ for (int
Row2=0; Row2 < GridDimension; Row2++){ for (int Col2=0; Col2 <
GridDimension2; Col2++) { if(Board[Row2][Col2] == Empty) { numEmpty++;
} } } return(-2);
}
//--------------------------------------------------------------------------------
void GridClass::MouseClick(int x, int y)
{ int Row, Col; if (QuitButton.IsHit(x,y)) { GameOver = true; Paint();
// To show the treasure square MessageBox("Come back again!", "Quit
button clicked"); PostQuitMessage(0); } else { XYToRowCol(x, y, Row,
Col); if (Row != -1 && Col != -1 && Board[Row][Col] !=
Red && Board[Row][Col] != Blue) { if (Board[Row][Col] == Empty)
{ for(int i = 4; i >= 0; i--) { if(Board[i][Col]==Empty) {
if(NumClicks%2 ==1) { Board[i][Col] = Red; MarkBox(i, Col, Red); break;
} else if(NumClicks%2 == 0) { Board[i][Col] = Blue; MarkBox(i, Col,
Blue); break; } } } } NumClicks++; if(winner() == Red) { GameOver =
true; MessageBox("Red Wins!", "Winner"); PostQuitMessage(0); } else
if(winner()==Blue) { GameOver =true; MessageBox("Blue Wins!",
"Winner"); PostQuitMessage(0); } else if(winner()==-2&&numEmpty
== 0) { GameOver = true; MessageBox("Tie!", "Winner");
PostQuitMessage(0); } } else MessageBeep(-1); }
}
//--------------------------------------------------------------------------------
void GridClass::Paint()
{ QuitButton.Paint(); SetColor(BLACK); int Row, Col; // Draw lines for
(Col = 0; Col <= GridDimension2; Col++) Line(LeftMargin+Col*BoxSize,
TopMargin, LeftMargin+Col*BoxSize, TopMargin+GridDimension*BoxSize);
for (Row = 0; Row <= GridDimension; Row++) Line(LeftMargin,
TopMargin+Row*BoxSize, LeftMargin+GridDimension2*BoxSize,
TopMargin+Row*BoxSize); // Color in boxes for (Row=0; Row <
GridDimension; Row++) for (Col=0; Col < GridDimension2; Col++)
MarkBox(Row,Col,Board[Row][Col]); // Display results if
(GameOver==true) { gotoxy(20,GetMaxY()-60); DrawText("Game over! Score
= "); DrawText(NumClicks); }
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
class GuiClass {
public: GuiClass(); void GuiMouseClick(int x, int y); //Action if mouse
click void GuiPaint(); // Repaint the entire window String Title(); //
Title to display
private: GridClass Game;
};
//--------------------------------------------------------------------------------
GuiClass::GuiClass()
{
}
//--------------------------------------------------------------------------------
String GuiClass::Title()
{ return ("Connect Four");
}
//--------------------------------------------------------------------------------
void GuiClass::GuiMouseClick(int x, int y)
{ Game.MouseClick(x, y);
}
//--------------------------------------------------------------------------------
void GuiClass::GuiPaint()
{ Game.Paint();
}
//--------------------------------------------------------------------------------
#include
• Chapter 11 Exercise 11
#include
#include
#include
#include
#include
//--------------------------------------------------------------------------------
class ButtonClass {
public: ButtonClass(String Text, int X1,int Y1, int X2, int Y2); /*
Post: A button created with upper-left corner at X1,Y1 and lower-right
corner at X2,Y2 with Text centered in box */ void Paint(); bool
IsHit(int x, int y); /* Post: true returned if and only if (x,y) is on
the button */
private: int MyX1, MyY1, MyX2, MyY2; String MyText;
};
//--------------------------------------------------------------------------------
ButtonClass::ButtonClass(String Text, int X1, int Y1, int X2, int Y2) :
MyText(Text), MyX1(X1), MyY1(Y1), MyX2(X2), MyY2(Y2)
/* Post: Button created with upper-left corner at X1, Y1 and lower
right corner at X2,Y2 with Text centered in box */
{
}
//--------------------------------------------------------------------------------
void ButtonClass::Paint()
{ SetColor(BLACK); Rectangle(MyX1, MyY1, MyX2, MyY2);
gotoxy((MyX1+MyX2)/2, 5+(MyY1+MyY2)/2); DrawCenteredText(MyText);
}
//--------------------------------------------------------------------------------
bool ButtonClass::IsHit(int x, int y)
/* Post: true returned if and only if point (x, y) is on the button */
{ return (x >= MyX1 && x <= MyX2 && y >= MyY1
&& y <= MyY2);
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
class GridClass {
public: GridClass(); void Paint(); void MouseClick(int x, int y); void
InitGrid();
private: const int GridDimension; // # of Rows/columns in grid //
Constants for board; must all differ const int Empty, EmptyPicked,
Treasure, TreasurePicked; matrix Board; // Uses above
constants int TreasureRow, TreasureCol; bool GameOver; int NumClicks;
int BoxSize; // Pixels per box int LeftMargin; // Pixels from left int
TopMargin; // Pixels from top void XYToRowCol(int x, int y, int
&Row, int &Col); void MarkBox(int Row, int Col, int
BoxContents); ButtonClass QuitButton;
};
//--------------------------------------------------------------------------------
GridClass::GridClass() : GridDimension(10), Empty(0), EmptyPicked(-1),
Treasure(1), TreasurePicked(2), Board(GridDimension,GridDimension,0),
NumClicks(0), GameOver(false),BoxSize(GetMaxY()/2/GridDimension), //
Fill half of y-dimension
LeftMargin((GetMaxX()-BoxSize*GridDimension)/2),TopMargin(GetMaxY()/4),
QuitButton("I give up!",10,10,100,40)
{ randomize(); for(int i =2; i<=5; i++) { do{ TreasureRow =
random(GridDimension-i-1); TreasureCol = random(GridDimension-i-1);
}while(Board[TreasureRow][TreasureCol] != Treasure); for(int x=0;
x= GridDimension || Row < 0 || Row
>= GridDimension) { Row = -1; Col = -1; }
}
//--------------------------------------------------------------------------------
void GridClass::MarkBox(int Row, int Col, int BoxContents)
/* Post: Row, Col box in appropriate color */
{ SetColor(BLACK); // For outline SetFillColor(WHITE); if
(BoxContents==EmptyPicked) SetFillColor(GRAY); else if
(BoxContents==TreasurePicked) SetFillColor(RED);
FilledRectangle(Col*BoxSize+LeftMargin,
Row*BoxSize+TopMargin,(Col+1)*BoxSize+LeftMargin,
(Row+1)*BoxSize+TopMargin);
}
//--------------------------------------------------------------------------------
void GridClass::MouseClick(int x, int y)
{ int Row, Col; if (QuitButton.IsHit(x,y)) { GameOver = true;
Board[TreasureRow][TreasureCol] = TreasurePicked; Paint(); // To show
the treasure square MessageBox("Come back again!", "Quit button
clicked"); PostQuitMessage(0); } else { XYToRowCol(x, y, Row, Col); if
(Row != -1 && Col != -1 && Board[Row][Col] !=
EmptyPicked) { if (Board[Row][Col] == Empty) Board[Row][Col] =
EmptyPicked; else if (Board[Row][Col] == Treasure) { Board[Row][Col] =
TreasurePicked; GameOver = true; MarkBox(TreasureRow, TreasureCol,
Board[TreasureCol][TreasureRow]); Paint(); // To show treasure square
if (MessageBoxYN("You Win! Play again?", "Game over")==1) InitGrid();
else PostQuitMessage(0); } NumClicks++; } else MessageBeep(-1); }
}
//--------------------------------------------------------------------------------
void GridClass::Paint()
{ QuitButton.Paint(); SetColor(BLACK); int Row, Col; // Draw lines for
(Col = 0; Col <= GridDimension; Col++) Line(LeftMargin+Col*BoxSize,
TopMargin, LeftMargin+Col*BoxSize, TopMargin+GridDimension*BoxSize);
for (Row = 0; Row <= GridDimension; Row++) Line(LeftMargin,
TopMargin+Row*BoxSize, LeftMargin+GridDimension*BoxSize,
TopMargin+Row*BoxSize); // Color in boxes for (Row=0; Row <
GridDimension; Row++) for (Col=0; Col < GridDimension; Col++)
MarkBox(Row,Col,Board[Row][Col]); // Display results if
(GameOver==true) { gotoxy(20,GetMaxY()-60); DrawText("Game over! Score
= "); DrawText(NumClicks); }
}
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
class GuiClass {
public: GuiClass(); void GuiMouseClick(int x, int y); //Action if mouse
click void GuiPaint(); // Repaint the entire window String Title(); //
Title to display
private: GridClass Game;
};
//--------------------------------------------------------------------------------
GuiClass::GuiClass()
{
}
//--------------------------------------------------------------------------------
String GuiClass::Title()
{ return ("Battleship");
}
//--------------------------------------------------------------------------------
void GuiClass::GuiMouseClick(int x, int y)
{ Game.MouseClick(x, y);
}
//--------------------------------------------------------------------------------
void GuiClass::GuiPaint()
{ Game.Paint();
}
//--------------------------------------------------------------------------------
#include
• Chapter 11 Exercise 17
#include
#include
#include
#include
#include
class RadioClass
{
public:
RadioClass(int xLoc, int yLoc);
void AddButton(String Text);
void Paint();
bool MouseClick(int x, int y);
String NowSelected();
private:
int MyxLoc, MyyLoc;
vector Names;
int ButtonSelected;
const int Height, Width;
};
RadioClass::RadioClass(int xLoc, int yLoc):
MyxLoc(xLoc), MyyLoc(yLoc), ButtonSelected(0), Height(20), Width(80)
{};
void RadioClass::AddButton(String Text)
{
Names.resize(Names.length+1);
Names[Names.length-1} = Text;
};
void RadioClass::Paint()
{
SetColor(BLACK);
for(int i = 0; i < names.length(); i++)
{
Circle(+i*20, 20, 30);
if(i == ButtonSelected)
{
};
bool RadioClass::MouseClick(int x, int y)
{
}
String RadioClass::NowSelected()
{
return Names[ButtonSelected];
};
class GuiClass
{
public:
GuiClass();
void GuiMouseClick(int x, int y); // Action if mouse click
void GuiPaint(); // Repaint the entire window
String Title(); // Return the title for the Window
private:
};
//--------------------------------------------------------------------------------
GuiClass::GuiClass()
{
}
//--------------------------------------------------------------------------------
String GuiClass::Title()
{
return "Radio Buttons";
}
//--------------------------------------------------------------------------------
void GuiClass::GuiMouseClick(int x, int y)
{
}
//--------------------------------------------------------------------------------
void GuiClass::GuiPaint()
{
}
//--------------------------------------------------------------------------------
#include
• Mouse Click Task
/* GUI main class Must create a Win 32 Application */ #include
#include
/* Implements a button which can be clicked on Modified to add default
constructor! */ class ButtonClass { public: ButtonClass(String Text,
int X1,int Y1, int X2, int Y2); /* Creates a button with upper left
corner at X1,Y1 and lower right corner at X2,Y2 with Text centered in
box */ ButtonClass(); void SetButton(String Text, int X1,int Y1, int
X2, int Y2); void Paint(); bool IsHit(int x, int y); /* Returns true if
and only if (x,y) is on the button */ private: int MyX1, MyY1, MyX2,
MyY2; String MyText; };
//-------------------------------------------------------------------
ButtonClass::ButtonClass()
{}
//-------------------------------------------------------------------
ButtonClass::ButtonClass(String Text, int X1,int Y1, int X2, int Y2):
MyText(Text), MyX1(X1), MyY1(Y1), MyX2(X2), MyY2(Y2)
/* Creates a button with upper left corner at X1,Y1 and lower right
corner at X2,Y2 with Text centered in box */
{}
//-------------------------------------------------------------------
void ButtonClass::SetButton(String Text, int X1,int Y1, int X2, int Y2)
/* Sets button with upper left corner at X1,Y1 and lower right corner
at X2,Y2 with Text centered in box */
{ MyText = Text; MyX1 = X1; MyY1 = Y1; MyX2 = X2; MyY2 = Y2;
}
//-------------------------------------------------------------------
void ButtonClass::Paint()
{ SetColor(BLACK); SetThickness(2); Rectangle(MyX1,MyY1,MyX2,MyY2);
gotoxy((MyX1+MyX2)/2, 5+(MyY1+MyY2)/2); DrawCenteredText(MyText);
}
//-------------------------------------------------------------------
bool ButtonClass::IsHit(int x, int y)
/* Returns true if and only if point (x,y) is on the button */
{ return (x >= MyX1 && x <= MyX2 && y >= MyY1
&& y <= MyY2);
}
//-------------------------------------------------------------------
class GuiClass { public: GuiClass(); void GuiMouseClick(int x, int y);
// Action if mouse click void GuiPaint(); // Repaint the entire window
String Title(); // Return the title for the Window void GuiDrawCar(int
x, int y); //Draws a car on the window void GuiRandom(); private: int
lastX; int lastY; ButtonClass button1; ButtonClass button2; ButtonClass
button3; ButtonClass button4;
};
//--------------------------------------------------------------------------------
GuiClass::GuiClass()
:button1("Green Circle", 20, 20, 120, 50), button2("Bull's Eye", 140,
20, 240, 50), button3("Car", 260, 20, 360,50), button4("Random",
380,20,480,50)
{
}
//--------------------------------------------------------------------------------
String GuiClass::Title()
{ return "Anthony";
}
//--------------------------------------------------------------------------------
void GuiClass::GuiMouseClick(int x, int y)
{ lastX = x; lastY = y;
}
//--------------------------------------------------------------------------------
void GuiClass::GuiDrawCar(int x, int y )
{ SetFillColor(BLUE); FilledRectangle(x-20, y, x+40, y+40);
FilledRectangle(x-40, y+40, x+60, y +80); SetFillColor(BLACK);
FilledCircle(x-20,y+85, 20); FilledCircle(x+40, y+85, 20);
}
//--------------------------------------------------------------------------------
void GuiClass::GuiRandom()
{ int rX, rY; rX=random(GetMaxX()); rY = random(GetMaxY());
FilledRectangle(rX, rY, rX+1,rY+1);
}
void GuiClass::GuiPaint()
{ button1.Paint(); button2.Paint(); button3.Paint(); button4.Paint();
if(button1.IsHit(lastX, lastY)) { SetFillColor(GREEN);
FilledCircle(GetMaxX()/2,GetMaxY()/2, 100); } if(button2.IsHit(lastX,
lastY)) { SetFillColor(RED); FilledCircle(GetMaxX()/2,GetMaxY()/2,
150); SetFillColor(WHITE); FilledCircle(GetMaxX()/2,GetMaxY()/2, 100);
SetFillColor(RED); FilledCircle(GetMaxX()/2,GetMaxY()/2, 50); }
if(button3.IsHit(lastX, lastY)) { GuiDrawCar(GetMaxX()/2, GetMaxY()/2);
} if(button4.IsHit(lastX, lastY)) { for(int i= 0; i <750; i++)
GuiRandom(); }
}
//--------------------------------------------------------------------------------
#include