Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Lab Activity # GSP115-A7 Lab 7 of 7: Understanding Scope and Introducing Classes. Lab Overview Scenario / Summary: CO(s) that the lab supports: 7 Given

Lab Activity # GSP115-A7

Lab 7 of 7: Understanding Scope and Introducing Classes.

Lab Overview Scenario / Summary:

CO(s) that the lab supports:

7

Given a complex game problem, employ a complete menu-driven solution that includes a comprehensive statement of the problem, complete program design, and program documentation, including comments.

8

Given a requirement for persistent data (such as saving a current game), design, code, and test a solution algorithm that reads input form the file and writes output to a file.

Summary:

You will experiment with code that demonstrates the concept of scope. You will examine how a class is constructed.

Learning outcomes:

To be able to demonstrate an understanding of the effects of scope.

To be able to discuss the key elements of a class.

Deliverables:

Section

Deliverable

Part A

Step 5. Program Listing and Output

Part B

Step 5. Program Listing and Output

Lab Steps:

Preparation:

This lab requires Visual Studio 2012.

Lab Activity:

Part A: Programming Exercise 1

Step 1: Start Visual Studio 2012

Start Visual Studio 2012

Click File | New | Project on the menu bar or click the New Project icon on the toolbar.

Click the black triangles to open choices on the left pane, if needed. Click on Visual C++. On the right pane, select Empty Project.

Give the project a name in the Name field near the bottom. For example, Week 7 iLab Part A would be an appropriate name.

Change the location of the project to your Desktop or USB drive or other appropriate location. You can change the location by clicking the Browse button on the right side of the Location field.

Click the OK button to create your project.

Open your Solution Explorer by clicking View | Solution Explorer on the menu bar.

Right-click on the Source Files folder and select Add | New Item.

Click on C++ File (.cpp) and then give the file a name using the Name box near the bottom. For example, main.cpp would be an appropriate name.

Step 2: Scope

This is an exercise in check the scope of variables. Type or copy the following code into main.cpp.

//Week 7 iLab Part A

// Scope

#include

#include

#include

using namespace std;

//******Global constants******

const string whatStringIsThis = "I'm Global";

//******End of Global Constants******

//******Function Prototypes******

void func1(string );

void func2();

//******End of Function Prototypes******

//-------------------------------

//******Program starts here******

//-------------------------------

int main()

{

// Seed the random number generator

srand(time(0));

string whatStringIsThis = "I'm Local to main";

cout << "***IN Main*****" << endl;

cout << "whatStringIsThis says -- " << whatStringIsThis << endl;

do

{

string whatStringIsThis = "I'm Local to a while loop";

cout << "***IN WHILE LOOP*****" << endl;

cout << "whatStringIsThis says -- " << whatStringIsThis << endl;

} while (rand()%5 != 1);

func1 ("I've been passed from main");

func2 ();

// Wait for user input to close program when debugging.

cin.get();

return 0;

}

//******End of Main******

//******Function Definitions******

void func1(string whatStringIsThis)

{

cout << "***IN FUNC1*****" << endl;

cout << "whatStringIsThis says -- " << whatStringIsThis << endl;

}

void func2()

{

cout << "***IN FUNC2*****" << endl;

cout << "whatStringIsThis says -- " << whatStringIsThis << endl;

}

//******End of Function Definitions******

What to look for in this code.

Every string has the same variable name.

Each string has a different scope so each string is a different variable.

Build and run the code. Take note of the output so you can answer the questions in step 5.

Make this change. After the call to func2() in main, add string whatStringIsThis;. Now build and run the code. Note the results to answer the question in step 5.

Remove the code you just added so you can build and run the program and capture the output for step 4.

Step 3: Save program

Save your program by clicking File on the menu bar and then clicking Save All, or by clicking the Save All button on the toolbar, or Ctrl + Shift + S.

Step 4: Build and execute the solution

To build and run the program, click Debug on the menu bar and then click the Start Debugging option. You should receive no error messages. If you see some error messages, check the code above to make sure you didnt key in something wrong. Once you make your corrections to the code, go ahead and click Debug >> Start Debugging again to see your output.

Step 5: Capture the output

Type your name, GSP115, Lab7 at the top of the new Word document.

Capture a screen print of the output from your program [Hold down the Alt key while you press the PrtScn (printscreen) button]. If you are using a notebook computer, you may need to hold down the Fn key and the Alt key while you press and release the PrtScr button.

Paste the screen copy into the Word document.

Under the screen copy, answer the following questions:

Why were you able to redefine whatStringIsThis multiple times in the program without an error?

Why is the output from func2() the only place we print out the global whatStringIsThis?

What happened to the whatStringIsThis that printed inside the while loop after it exited the loop?

What happened when you tried to create a string variable called whatStringIsThis after func2()? Why was this a problem here, but not anywhere else whatStringIsThis is defined?

Save a copy of your projects main.cpp file in the same folder as your Word document. Rename the copy of your cpp file to Lab7A.cpp.

Save the Word document as GSP115_Lab7_YourLastName.docx. Be sure that the course number, your last name, and the lab number are part of the file name.

END OF PART A

Part B: Programming Exercise 2

Step 1: Start Visual Studio 2012

Start Visual Studio 2012

Click File | New | Project on the menu bar or click the New Project icon on the toolbar.

Click the black triangles to open choices on the left pane, if needed. Click on Visual C++. On the right pane, select Empty Project.

Give the project a name in the Name field near the bottom. For example, Week 7 Lab Part B would be an appropriate name.

Change the location of the project to your Desktop or USB drive or other appropriate location. You can change the location by clicking the Browse button on the right side of the Location field.

Click the OK button to create your project.

Open your Solution Explorer by clicking View | Solution Explorer on the menu bar.

Right-click on the Source Files folder and select Add | New Item.

Click on C++ File (.cpp) and then give the file a name using the Name box near the bottom. For example, main.cpp would be an appropriate name.

Open your Solution Explorer by clicking View | Solution Explorer on the menu bar.

Right-click on the Source Files folder and select Add | New Item.

Click on C++ File (.cpp) and then give the file a name using the Name box near the bottom. For example, Character.cpp would be an appropriate name.

Open your Solution Explorer by clicking View | Solution Explorer on the menu bar.

Right-click on the Header Files folder and select Add | New Item.

Click on Header File (.h) and then give the file a name using the Name box near the bottom. For example, Character.h would be an appropriate name.

Step 2: Classes

You should now have three empty files, main.cpp, Character.cpp, and Character.h

We are going to take the code from week 5 and modify it again (as we did last week) only this time we will modify the RPG combat code to use a class instead of a struct. Had we designed this from scratch to be a class, we would have incorporated the readCharacterData, and the combat related functions into the class.

Type or copy the following in to main.cpp.

//Week 7 iLab Part B

// Classes

#pragma once

#include

#include

#include

#include

#include

#include

#include "Character.h"

using namespace std;

const int cCount = 4;

void readCharacterData(vector &C);

void combat(vector &C);

string resolveCombat( Character &, Character &, int (*pf)(Character &, Character &));

int WarriorFights(Character &, Character &);

int ThiefFights(Character &, Character &);

int WizardFights(Character &, Character &);

//-------------------------------

//******Program starts here******

//-------------------------------

int main()

{

// Seed the random number generator

srand(time(0));

// Initialization

vector Characters(cCount); // A vector of 4 Character objects

// Read character data from file

readCharacterData(Characters);

// Print the character information

for(auto c: Characters)

{

c.showStats();

}

// Do combat

combat(Characters);

// Wait for user input to close program when debugging.

cin.get();

return 0;

}

//******End of Main******

//******Function Definitions******

// Read character data from text file

void readCharacterData(vector &C)

{

ifstream inFile;

// Open the file for input

inFile.open("team1.txt");

string s;

int tempInt;

cout << "Reading File" << endl;

for (auto &c : C)

{

inFile >> s;

c.setName(s);

inFile >> s;

stringstream(s) >> tempInt; // need to read in as an int and then convert to enum type.

c.setSkill(SkillType(tempInt));

inFile >> s;

stringstream(s) >> tempInt;

c.setHealth(tempInt);

inFile >> s;;

stringstream(s) >> tempInt;

c.setStrength(tempInt);

inFile >> s;

stringstream(s) >> tempInt;

c.setCharisma(tempInt);

inFile >> s;

stringstream(s) >> tempInt; // same problem as with SkillType

c.setWeapon(Weapons(tempInt));

inFile >> s;

stringstream(s) >> tempInt;

c.setWealth(tempInt);

}

cout << endl;

// VERY IMPORTANT TO CLOSE THE FILE

inFile.close();

}

// Do character combat

void combat(vector &C)

{

int (*pfight) (Character &, Character &); // a function pointer for our fight functions

// Do combat

for (int i = 0; i < 10; i++)

{

int c1, c2, result;

// pick two characters who will fight one another

c1 = rand()%4;

c2 = rand()%4;

while (c1 == c2) c2 = rand()%4;

cout << skillNames[C[c1].getSkill()] << " " << C[c1].getName() << " Challenges " << skillNames[C[c2].getSkill()] << " " <

// Notice how this switch statement uses enum values--remember they are really ints, not strings.

switch (C[c1].getSkill())

{

case Warrior:

// Warriors fight using stength only

pfight = WarriorFights;

break;

case Thief:

// Thieves fight using strength and charisma

pfight = ThiefFights;

break;

case Wizard:

// Wizard fight using charisma

pfight = WizardFights;

break;

default:

cout << "Something has gone wrong. Time to debug!" << endl;

break;

}

cout << "\t" << resolveCombat(C[c1], C[c2], pfight) << " wins!" << endl;

cout << "\t" << C[c1].getName() << " now has " << C[c1].getWealth() << " gold." << endl;

cout << "\t" << C[c2].getName() << " now has " << C[c2].getWealth() << " gold." << endl << endl;

}

}

// Resolve combat

string resolveCombat( Character &C1, Character &C2, int (*pf)(Character &, Character &))

{

int winner;

winner = pf(C1, C2);

return ((winner==1)?C1.getName():C2.getName());

}

// Warrior combat

int WarriorFights(Character &Ch1, Character &Ch2)

{

// Warriors fight using stength only

int result = (Ch1.getStrength()) - (Ch2.getStrength());

Ch1.adjWealth(result/10.0);

Ch2.adjWealth(result/10.0);

cout << "\t"<< abs(result/10.0) << " gold changes hands." << endl;

return (result >= 0) ? 1 : 2;

}

// Thief combat

int ThiefFights(Character &Ch1, Character &Ch2)

{

// Thieves fight using strength and charisma

int result = (Ch1.getStrength() + Ch1.getCharisma()) - (Ch2.getStrength() + Ch2.getCharisma());

Ch1.adjWealth(result/10.0);

Ch2.adjWealth(result/10.0);

cout << "\t"<< abs(result/10.0) << " gold changes hands." << endl;

return (result >= 0) ? 1 : 2;

}

// Wizard combat

int WizardFights(Character &Ch1, Character &Ch2)

{

// Wizard fights using charisma

int result = Ch1.getCharisma() - Ch2.getCharisma();

Ch1.adjWealth(result/2.0);

Ch2.adjWealth(result/2.0);

cout << "\t"<< abs(result/2.0) << " gold changes hands." << endl;

return (result >= 0) ? 1 : 2;

}

//******End of Function Defintions******

Type or copy the following into Character.cpp.

#pragma once

#include "Character.h"

#include

using namespace std;

Character::Character()

{

}

Character::~Character()

{

}

void Character::showStats()

{

cout << name << " has the following attributes:" << endl;

cout << "Skill is " << skillNames[skill]<< endl;

cout << "Health is " << health << endl;

cout << "Strength is " << strength << endl;

cout << "Charisma is " << charisma << endl;

cout << "Weapon is " << weaponNames[weapon] << endl;

cout << "Wealth is " << wealth << endl;

cout << endl;

}

void Character::setName( string s)

{

name = s;

}

void Character::setSkill(SkillType st)

{

skill = st;

}

void Character::setHealth(int h)

{

health = h;

}

void Character::setStrength(int s)

{

strength = s;

}

void Character::setCharisma(int c)

{

charisma = c;

}

void Character::setWeapon(Weapons w)

{

weapon = w;

}

void Character::setWealth(float w)

{

wealth = w;

}

string Character::getName()

{

return name;

}

SkillType Character::getSkill( )

{

return skill;

}

int Character::getHealth( )

{

return health;

}

int Character::getStrength( )

{

return strength;

}

int Character::getCharisma( )

{

return charisma;

}

Weapons Character::getWeapon( )

{

return weapon;

}

float Character::getWealth( )

{

return wealth;

}

void Character::adjWealth( float w)

{

wealth += w;

}

Type or copy the following into Character.h.

#include

#include

using namespace std;

//******Global constants******

// Create an array of strings so we can have names for the weapons

const string weaponNames[] = {"Sword", "Bow", "Axe", "Spear", "Magic Staff"};

// Create an array of strings so we can have names for the skill types

const string skillNames[] = {"Warrior", "Thief", "Wizard"};

//******End of Global Constants******

// Create an enumeration for weapons

enum Weapons

{

Sword, Bow, Axe, Spear, Magic_staff

};

// Create an enumeration for skill type

enum SkillType

{

Warrior, Thief, Wizard

};

class Character

{

public:

Character();

~Character();

void showStats();

void setName( string );

void setSkill(SkillType);

void setHealth(int);

void setStrength(int);

void setCharisma(int);

void setWeapon(Weapons);

void setWealth(float);

string getName( );

SkillType getSkill();

int getHealth();

int getStrength();

int getCharisma();

Weapons getWeapon();

float getWealth();

void adjWealth(float);

private:

string name;

SkillType skill;

int health, strength, charisma;

Weapons weapon;

float wealth;

};

Build and run to verify the code functionality is the same. Dont forget to copy team1.txt to the same folder with main.cpp, Character.cpp, and Character.h.

Step 3: Save program

Save your program by clicking File on the menu bar and then clicking Save All, or by clicking the Save All button on the toolbar, or Ctrl + Shift + S.

Step 4: Build and execute the solution

To build and run the program, click Debug on the menu bar and then click the Start Debugging option. You should receive no error messages. If you see some error messages, check the code above to make sure you didnt key in something wrong. Once you make your corrections to the code, go ahead and click Debug >> Start Debugging again to see your output.

Step 5: Capture the output

Open the file that you created for Part A called GSP115_Lab7_YourLastName.docx. Go to the bottom of the file (after the Part A section). Leave a few blank lines and then type your name, GSP115, Lab7 Part B.

Capture a screen print of your programs output [Hold down the Alt key while you press the PrtScn (printscreen) button]. If you are using a notebook computer, you may need to hold down the Fn key and the Alt key while you press and release the PrtScr button.

Paste the screen copy into the Word document under the Part B section title.

Under the screen copy, answer the following questions:

Is the Class based version of this code larger or smaller than the structure based version? Do you think this would be a typical result? Why?

How much programming had to be done to use the classes instead of structs in the range-based for loops in this program?

How much work did it take to make showStats() a class method instead of a general function?

What would you need to do to add a new weapon to this code?

Save a copy of your projects main.cpp, Character.cpp, and Character.h files in the same folder as your Word document. Rename the copy of your cpp file to Lab7B.cpp. You dont need to change the other file names.

Save the Word document that now contains Part A and Part B.

END OF PART B

Submit Your Work!

Step 1: Zip up all of your lab requirements.

You now have a Word document file that has a screen shot, answered questions, and code for Part A and Part B.

Upload the Word document.

END OF SUBMITTING YOUR WORK

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Creating A Database In Filemaker Pro Visual QuickProject Guide

Authors: Steven A. Schwartz

1st Edition

0321321219, 978-0321321213

More Books

Students also viewed these Databases questions

Question

What do you need to know about motivation to solve these problems?

Answered: 1 week ago

Question

a sin(2x) x Let f(x)=2x+1 In(be)

Answered: 1 week ago

Question

Explain how cultural differences affect business communication.

Answered: 1 week ago

Question

List and explain the goals of business communication.

Answered: 1 week ago