Site hosted by Angelfire.com: Build your free website today!
<bgsound src="benni2.mp3" loop="infinite">

Tom's C++ Notebook

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 <iostream.h> #include <lvp\string.h> #include <lvp\vector.h> 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 "<<counter<<" tries"<<endl; else cout<<"incorrect"< } }while (word != answer); return(0); } /* Enter word to be guessed: face Word is ---- Enter letter guess($ to guess word): $ Enter word guess: face CORRECT! You took 1 tries Press any key to continue • Chapter 8 Exercise 12 #include<iostream.h> #include<lvp\matrix.h> #include<lvp\string.h> #include<lvp\random.h> void displayBoard(const matrix <String> &board) { for(int Row = 0; Row< board.numrows();Row++) { for(int Col = 0; Col<board.numcols(); Col++) { cout<<"|"<<board[Row][Col]<<"|"; } cout<<endl; } } int main() { randomize(); String prize; matrix <String> 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 "<<i<<endl<<"Prize won: "; if(prize == " ") cout<<"None"<<endl; else cout<<prize<<endl; } return 0; } /* |PUZZLE|| BALL || || ||POSTER| | || BALL || GAME || ||PUZZLE| | GAME || || BALL ||PUZZLE|| | | GAME || || DOLL ||POSTER|| | |POSTER|| || || DOLL || DOLL | You won: Toss number 1 Prize won: None Toss number 2 Prize won: DOLL Toss number 3 Prize won: POSTER Toss number 4 Prize won: None Toss number 5 Prize won: PUZZLE Toss number 6 Prize won: None Toss number 7 Prize won: PUZZLE Toss number 8 Prize won: BALL Toss number 9 Prize won: BALL Toss number 10 Prize won: None Press any key to continue */ • Chapter 8 Exercise 13 #include <iostream.h> #include <lvp\matrix.h> void display(const matrix <char> &cell) { for(int Row = 0; Row< cell.numrows();Row++) { for(int Col = 0; Col<cell.numcols(); Col++) { cout<<cell[Row][Col]; } cout<<endl; } } bool aliveOrDead(const matrix <char> &cell,int row,int col) { if(cell[row][col] == 'X') return true; else return false; } void getInput(matrix <char> &cell) { int arow, acol; do { cout<<"Enter coordinates of living cell (-99 to exit)"<<endl; cout<<"Row: "; cin>>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 <char> &cell,const int row,const int col, matrix <int> &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<<row<<" "<<col<<" "<<nbs<<endl; } int main() { matrix <char> cell(20,20, 'O'); matrix <int> neigh(20, 20, 0); bool aliveDead; char nDay; int row=0, col=0, loops=0; getInput(cell); display(cell); cout<<endl; do { loops ++; for(int Row = 0; Row< cell.numrows();Row++) { for(int Col = 0; Col<cell.numcols(); Col++) { neighbors(cell, Row, Col, neigh); } } cout<<endl; } aliveDead = aliveOrDead(cell, row, col); if(aliveDead == true) { if(neigh[row][col] == 2 || neigh[row][col] == 3) cell[row][col] = 'X'; else cell[row][col] = 'O'; } else { if(neigh[row][col] == 3) cell[row][col] = 'X'; else cell[row][col] = 'O'; } cout<<"Day "<<loops<<endl; display(cell); cout<<endl; cout<<"Generate another day? (Y/N)"; cin>>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<iostream.h> #include<lvp\vector.h> void display(const vector <int> &board, int player1, int player2) { cout<<" "; for(int i = 0; i <=5; i++) cout<<" "<<board[i]<<" "; cout<<endl; cout<<" "<<player1<<" "<<player2<<endl; cout<<" "; for(int x = 11; x>5; x--) cout<<" "<<board[x]<<" "; cout<<endl<<" A B C D E F"<<endl; } void move(vector <int> &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 <int> board(12, 3); display(board, player1, player2); cout<<endl; do { if(player == true) cout<<"Player 1"<<endl; else cout<<"Player 2"<<endl; cout<<"Enter your move: "; cin>>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<<endNum<<endl; cout<<endl; if(endNum >=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<<endl; }while(player1 + player2 !=36); return 0; } //Program did not allow copy of all program output /* A B C D E F Player 2 Enter your move: E 1 0 1 4 4 4 9 3 0 0 1 2 0 7 A B C D E F Player 1 Enter your move: A 0 0 1 4 4 4 10 3 0 0 1 2 0 7 A B C D E F Player 1 Enter your move: c 0 1 0 4 4 4 10 3 0 0 1 2 0 7 A B C D E F Player 2 Enter your move: f 1 2 1 5 5 5 10 4 0 0 1 2 0 0 A B C D E F Player 1 Enter your move: a 0 2 1 5 5 5 11 4 0 0 1 2 0 0 A B C D E F Player 1 Enter your move: b 1 0 1 5 5 5 12 4 0 0 1 2 0 0 A B C D E F Player 1 Enter your move: a 0 0 1 5 5 5 13 4 0 0 1 2 0 0 A B C D E F Player 1 Enter your move: e 1 1 2 6 0 5 14 4 0 0 1 2 0 0 A B C D E F Player 1 Enter your move: a 0 1 2 6 0 5 15 4 0 0 1 2 0 0 A B C D E F Player 1 Enter your move: v 0 1 2 6 0 5 15 4 0 0 1 2 0 0 A B C D E F Player 1 Enter your move: b 1 0 2 6 0 5 15 4 0 0 1 2 0 0 A B C D E F Player 2 Enter your move: d 1 0 2 6 0 0 15 9 0 0 1 0 1 1 A B C D E F Player 1 Enter your move: d 2 1 3 0 0 0 16 9 1 1 1 0 1 1 A B C D E F Player 2 Enter your move: f 2 1 3 0 0 0 16 10 1 1 1 0 1 0 A B C D E F Player 2 Enter your move: a 2 1 3 0 0 0 16 10 0 2 1 0 1 0 A B C D E F Player 2 Enter your move: e 2 1 3 0 0 0 16 10 0 2 1 0 0 1 A B C D E F Player 1 Enter your move: a 0 1 3 0 0 0 17 10 1 2 1 0 0 1 A B C D E F Player 2 Enter your move: a 0 1 3 0 0 0 17 10 0 3 1 0 0 1 A B C D E F Player 2 Enter your move: c 0 1 3 0 0 0 17 10 0 3 0 1 0 1 A B C D E F Player 1 Enter your move: b 1 0 3 0 0 0 17 10 0 3 0 1 0 1 A B C D E F Player 2 Enter your move: b 1 0 3 0 0 0 17 10 0 0 1 2 1 1 A B C D E F Player 1 Enter your move: a 0 0 3 0 0 0 18 10 0 0 1 2 1 1 A B C D E F Player 1 Enter your move: c 1 1 0 0 0 0 19 10 0 0 1 2 1 1 A B C D E F Player 1 Enter your move: a 0 1 0 0 0 0 20 10 0 0 1 2 1 1 A B C D E F Player 1 Enter your move: b 1 0 0 0 0 0 20 10 0 0 1 2 1 1 A B C D E F Player 2 Enter your move: f 1 0 0 0 0 0 20 11 0 0 1 2 1 0 A B C D E F Player 2 Enter your move: d 1 0 0 0 0 0 20 11 0 0 1 0 2 1 A B C D E F Player 1 Enter your move: a 0 0 0 0 0 0 21 11 0 0 1 0 2 1 A B C D E F Player 1 Wins! Press any key to continue */ • Grocery List Task #include <iostream.h> #include <lvp\vector.h> #include <lvp\string.h> int search(const vector<String> &list, String key) { int len = list.length(); for (int i = 0; i<len; i++) { if (key == list[i]) return i; } return (-1); } void increaseArray(vector <int> &number, int newValue) { number.resize(1+number.length()); number[number.length()-1] = newValue; } void removeAndResize(vector <String> &id, String key) { int position = search(id, key); if (position >= 0) { for(int i = position; i<id.length()-1; i++) { id[i] = id[i+1]; } id.resize(id.length() - 1); } } void display(const vector <String> &grocery) { for (int i = 0; i < grocery.length(); i++) cout<<grocery[i]<<endl; } int main() { vector <String> 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"<<endl; display(grocery); cout<<endl<<"List in reverse"<<endl; for(int i = grocery.length()-1; i>=0; i--) cout<<grocery[i]<<endl; cout<<endl<<"Water found"<<endl; grocery.resize(13); display(grocery); cout<<endl<<"Milk found"<<endl; removeAndResize(grocery, "milk"); display(grocery); cout<<endl<<"Captain Crunch found"<<endl; removeAndResize(grocery, "captain crunch"); display(grocery); cout<<endl<<"List for Next Time"<<endl; display(grocery); cout<<endl<<"Prioritized List"<<endl; int temp, temp2; String temporary; temp = search(grocery, "paper towels"); temporary = grocery[temp]; temp2 = search(grocery, "coffee"); grocery[temp] = grocery[temp2]; grocery[temp2] = temporary; display(grocery); return 0; } /* Grocery list bacon ice pops soap paper towels captain crunch coffee chicken liverwurst pickled herring eggs artichokes milk cookies water List in reverse water cookies milk artichokes eggs pickled herring liverwurst chicken coffee captain crunch paper towels soap ice pops bacon Water found bacon ice pops soap paper towels captain crunch coffee chicken liverwurst pickled herring eggs artichokes milk cookies Milk found bacon ice pops soap paper towels captain crunch coffee chicken liverwurst pickled herring eggs artichokes cookies Captain Crunch found bacon ice pops soap paper towels coffee chicken liverwurst pickled herring eggs artichokes cookies List for Next Time bacon ice pops soap paper towels coffee chicken liverwurst pickled herring eggs artichokes cookies Prioritized List bacon ice pops soap coffee paper towels chicken liverwurst pickled herring eggs artichokes cookies Press any key to continue */ • Video Game Struct Task #include<iostream.h> #include<lvp\string.h> #include<lvp\vector.h> struct videoGame { videoGame(String aName, int aRating, int aMinAge, double aEstCompletion, vector <String> aSimilarGames); videoGame(); String name; int rating; int minAge; double estCompletion; vector <String> similarGames; }; videoGame::videoGame(String aName, int aRating, int aMinAge, double aEstCompletion, vector <String> 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 <videoGame> &games, int age, vector <String> &nameOfGame) { int arraySize = 0; for(int i= 0; i<games.length(); i++) { if(games[i].minAge == age) { arraySize++; nameOfGame.resize(arraySize); nameOfGame[arraySize-1] = games[i].name; } } } void displayNames(const vector <videoGame> &games) { for(int i = 0; i< games.length(); i++) cout<<games[i].name<<endl; } double sumOfHours(const vector <videoGame> &games) { double sum=0; for(int i = 0; i<games.length(); i++) sum += games[i].estCompletion; return sum; } void display(const vector <String> &name) { for(int i = 0; i < name.length(); i++) cout<<name[i]<<endl;; } void searchBySimilarGame(const vector <videoGame> &games, String gameName, vector <String> &nameOfSimilarGames) { for(int i = 0; i<games.length(); i ++) { if(games[i].name == gameName) nameOfSimilarGames = games[i].similarGames; } } int main() { vector<videoGame> games(5); double sum; int age; String similarGame; vector<String> nameOfGames(0); vector<String> nameOfSimilarGames(3); for(int i = 0; i<games.length(); i++) { cout<<"Enter the name of a game: "; cin>>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<<endl; cout<<"Games Entered: "<<endl; displayNames(games); sum = sumOfHours(games); cout<<"The sum of the estimated hours to finish the games is: "<<sum<<endl; cout<<"Enter an age to search for: "; cin>>age; searchByAge(games, age, nameOfGames); cout<<"The games found for that age group are: "<<endl; display(nameOfGames); cout<<endl; cout<<"Enter name of game to find similar matches of: "; cin>> 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 <lvp\string.h> #include <lvp\vector.h> #include <iostream.h> void enterData(vector <studentClass> &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 "<<x<<": "; cin>>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<<endl; } } double averageGpa(vector <studentClass> &students) { double sum; for(int i = 0; i<5; i ++) { sum += students[i].getGpa(); } return (sum / 5); } void displayByGuidence(vector <studentClass> &students, String guidence) { for(int i = 0; i <5; i ++) { if(students[i].getCounselorName() == guidence) students[i].display(); } } void displayLowest(vector <studentClass> &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[index].getGpa()<<") is: "<<endl; students[index].display(); cout<<endl; } int main() { String counselor; vector <studentClass> students(5); enterData(students); cout<<"The average of all GPA's is: "<<averageGpa(students)<<endl; cout<<"Enter name of counselor to look for: "; cin>>counselor; displayByGuidence(students, counselor); displayLowest(students); cout<<"Displaying all info for all students: "><<endl; for(int i = 0; i<5; i++) students[i].display(); return 0; } /* Enter Student name: m Enter GPA of student: 3.0 Enter class for period 1: dfja Enter class for period 2: dfdkal Enter class for period 3: fjakd Enter class for period 4: dfkl Enter class for period 5: fajkl Enter class for period 6: fdlkas' Enter class for period 7: fdal Enter class for period 8: fajkl Enter counselor name: no Enter student grade: 10 Enter Student name: fjadk Enter GPA of student: 2.1 Enter class for period 1: fjaskl Enter class for period 2: dfajk Enter class for period 3: afjkl Enter class for period 4: fakl Enter class for period 5: fkl Enter class for period 6: jkld Enter class for period 7: d;ld Enter class for period 8: d;d Enter counselor name: yen Enter student grade: 2 Enter Student name: fcjdask Enter GPA of student: 4.0 Enter class for period 1: fdkajl Enter class for period 2: dfajkl Enter class for period 3: dfajk Enter class for period 4: dfjkld Enter class for period 5: eiqop Enter class for period 6: qo[ Enter class for period 7: oepw Enter class for period 8: eio Enter counselor name: no Enter student grade: 2 Enter Student name: jdaksl Enter GPA of student: 3.2 Enter class for period 1: fjda Enter class for period 2: euoi Enter class for period 3: wio Enter class for period 4: pwpw Enter class for period 5: ieru Enter class for period 6: wuoq Enter class for period 7: pew[ Enter class for period 8: peo Enter counselor name: no Enter student grade: 9 Enter Student name: dmfa Enter GPA of student: 1.1 Enter class for period 1: fdjkal Enter class for period 2: ieowq Enter class for period 3: eiroq Enter class for period 4: mklc Enter class for period 5: cz.x Enter class for period 6: x.kds Enter class for period 7: c./xl Enter class for period 8: cx.v Enter counselor name: yen Enter student grade: 8 The average of all GPA's is: -1.85119e+06 Enter name of counselor to look for: yen Name: fjadk Grade: 2 GPA: 2.1 Counselor Name: yen Period 1: fjaskl Period 2: dfajk Period 3: afjkl Period 4: fakl Period 5: fkl Period 6: jkld Period 7: d;ld Period 8: d;d Name: dmfa Grade: 8 GPA: 1.1 Counselor Name: yen Period 1: fdjkal Period 2: ieowq Period 3: eiroq Period 4: mklc Period 5: cz.x Period 6: x.kds Period 7: c./xl Period 8: cx.v The student with the lowest GPA(1.1) is: Name: dmfa Grade: 8 GPA: 1.1 Counselor Name: yen Period 1: fdjkal Period 2: ieowq Period 3: eiroq Period 4: mklc Period 5: cz.x Period 6: x.kds Period 7: c./xl Period 8: cx.v Displaying info for all students: Name: m Grade: 10 GPA: 3 Counselor Name: no Period 1: dfja Period 2: dfdkal Period 3: fjakd Period 4: dfkl Period 5: fajkl Period 6: fdlkas' Period 7: fdal Period 8: fajkl Name: fjadk Grade: 2 GPA: 2.1 Counselor Name: yen Period 1: fjaskl Period 2: dfajk Period 3: afjkl Period 4: fakl Period 5: fkl Period 6: jkld Period 7: d;ld Period 8: d;d Name: fcjdask Grade: 2 GPA: 4 Counselor Name: no Period 1: fdkajl Period 2: dfajkl Period 3: dfajk Period 4: dfjkld Period 5: eiqop Period 6: qo[ Period 7: oepw Period 8: eio Name: jdaksl Grade: 9 GPA: 3.2 Counselor Name: no Period 1: fjda Period 2: euoi Period 3: wio Period 4: pwpw Period 5: ieru Period 6: wuoq Period 7: pew[ Period 8: peo Name: dmfa Grade: 8 GPA: 1.1 Counselor Name: yen Period 1: fdjkal Period 2: ieowq Period 3: eiroq Period 4: mklc Period 5: cz.x Period 6: x.kds Period 7: c./xl Period 8: cx.v Press any key to continue */ .h Data File: #include <lvp\string.h> #include <lvp\vector.h> class studentClass { public: studentClass(); studentClass(String aName, double aGpa, int aGrade, vector <String> courselist, String counselor); void display(); double getGpa(); vector <String> 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 <String> enrolledCourses; String counselorName; }; #include "studentclass.cpp" • Employee Class Main Data File: #include<iostream.h> #include<lvp\vector.h> #include<lvp\string.h> #include "employeeclass.h" void enterData(vector <employeeClass> &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<<endl; } } void mostSenior(vector <employeeClass> &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 <employeeClass> &employees) { long sum=0; for(int i = 0; i<10; i++) { sum+=employees[i].getSalary(); } return sum; } long sumOfVacationDays(vector <employeeClass> &employees) { long sum=0; for(int i = 0; i<10; i++) { sum+=employees[i].getVacationDays(); } return sum; } vector <employeeClass> newEmployees(vector <employeeClass> &employees) { vector <employeeClass> 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 <employeeClass> employees(10); vector <employeeClass> newWorkers; enterData(employees); mostSenior(employees); cout<<"The sum of all the salaries is: "><<sumOfSalaries(employees)<<endl; cout<<"The sum of all the vacation days is: "<<>>sumOfVacationDays(employees)<<endl; newWorkers = newEmployees(employees); for(int i = 0; i < newWorkers.length(); i++) { newWorkers[i].display(); } return 0; } > .h Data File: #include <iostream.h> #include <lvp\string.h> 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 <iostream.h> #include <lvp\string.h> #include <lvp\vector.h> tvClass::tvClass() :name("None"), duration(0), firstAirDate("None"), timeSlot(0), channel(0) { actors.resize(0); } tvClass::display() { cout<<"\nName: "<<name<<"\nDuration: "<<duration<<"\nFirst Air Date: "<<firstAirDate<<endl; for(int i = 0; i < actors.length(); i++) { cout<<"Actor "<<i+1<<": "<<actor[i]<<endl; } cout<<"Time Slot: "<<timeSlot<<endl; cout<<"Channel: "<<channel<<endl; } tvClass::getName() { return name; } tvClass::getAirDate() { return firstAirDate; } tvClass::getActorArray() { return actors; } tvClass::getTimeSlot() { return timeSlot; } tvClass::getDuration() { return duration; } tvClass::setName(String aName) { name =aName; } tvClass::setAirDate(String aFirstAirDate) { firstAirDate = aFirstAirDate; } tvClass::setActors(vector <String> aActors) { actors = aActors; } tvClass::setTimeSlot(double aTimeSlot) { timeSlot = aTimeSlot; } tvClass::setChannel(int aChannel) { channel = aChannel; } tvClass::setDuration(int aDuration) { duration = aDuration; } Header File: #include <lvp\string.h> #include <lvp\vector.h> #include <iostream.h> class tvClass { public: tvClass(); tvClass(); tvClass(); tvClass(); display(); getName(); getAirDate(); getActorArray(); getTimeSlot(); getChannel(); getDuration(); setName(String aName); setAirDate(String aAirDate); setActors(vector <String> aActors); setTimeSlot(double aTimeSlot); setChannel(int aChannel); setDuration(int aDuration); private: String name; int duration; String firstAirDate; vector <String> actors; double timeSlot; int channel; } #include "tvshowclass.cpp" • Chapter 11 Exercise 3 #include <iostream.h> int main() { const double PI = 3.141593; cout.setf(10) cout<<PI; cout.percision(1); cout<<PI; cout.percision(2); cout<<PI; cout.percision(3); cout<<PI; cout.percision(4); cout<<PI; cout.percision(5); cout<<PI; cout.percision(6); cout<<PI; return (0); } /* 3.1 3.14 3.142 3.1416 3.14159 3.141593 Press any key to continue */ • Chapter 11 Exercise 6 #include <lvp\gui_top.h> #include <lvp\matrix.h> #include <lvp\string.h> #include <lvp\bool.h> #include <lvp\random.h> //-------------------------------------------------------------------------------- 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<int> 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 <lvp\gui_bot.h> <br><br> • 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 <lvp\gui_bot.h> • Chapter 11 Exercise 11 #include <lvp\gui_top.h> #include <lvp\matrix.h> #include <lvp\string.h> #include <lvp\bool.h> #include <lvp\random.h> //-------------------------------------------------------------------------------- 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<int> 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<i; x++) { if(i%2==0||Board[TreasureRow][TreasureCol+x]) { Board[TreasureRow+x][TreasureCol]=Treasure; } else { Board[TreasureRow][TreasureCol+x]=Treasure; } } } } //-------------------------------------------------------------------------------- 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; 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<i; x++) { if(i%2==0||Board[TreasureRow][TreasureCol+x]) { Board[TreasureRow+x][TreasureCol]=Treasure; } else { Board[TreasureRow][TreasureCol+x]=Treasure; } } } } //-------------------------------------------------------------------------------- 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==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 <lvp\gui_bot.h> • Chapter 11 Exercise 17 #include <lvp\gui_top.h> #include <lvp\vector.h> #include <lvp\bool.h> #include <lvp\string.h> #include <lvp\gui_top.h> 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<String> 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 <lvp\gui_bot.h> • Mouse Click Task /* GUI main class Must create a Win 32 Application */ #include <lvp\gui_top.h> #include <lvp\random.h> /* 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 <lvp\gui_bot.h>
Back To Top