It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf ·...

26
CIS264 Penn P. Wu, Ph.D. 56 Lecture #3 Rock-Scissor-Paper Game Introduction Designing a computer program requires an engineer mindset. There are three basic steps a software engineer needs to perform: 1. Defining the objective: You should have a clear understanding about the objective of the program you are about to create. What is the program all about? What does it do? How does it function? What will it produce? 2. List the procedures: In order to reach the goal, there are many things you need to do. Each of the “things” is one of the procedures. Think about what you need to do to reach the goal and create a logical list of them is a part of the software design. 3. Arrange the sequence: Computers are very procedural and often very linear (sequential). It reads statement line by line and usually executes them line by line unless you tell them to jump off the sequence. After you figure out all the necessary procedures, you will have to arrange them in the logical sequence. To design a simple Rock-Scissor-Paper game, for example, requires you to exercise these three steps. The objective of this game is to determine which of any two players is the winner. Typically, in such game, the combinations of players are: human player vs. computer human player 1 vs. human player 2 computer vs. computer It is the program designer’s call to decide the combination. However, it is also the designer’s responsibility to clearly define it. In this lecture, the instructor will use the first option (human player vs. computer) to illustrate the design process. Once the combination is defined, it is time to design the game rules. The basic rules to determine who the winner is are: When a scissor meets a paper, the scissor wins because scissors can cut papers. When a scissor meets a rock, the rock wins because rocks can crack scissors. When a paper meets a rock, the paper wins because papers can wrap rocks. When two objects of a kind appear, such as a rock meets another rock, it is a tie. The procedures needed to make this game possible are: Design a data structure that can be used to represent the three options: rock, paper, and scissor. Declare a variable to represent the computer, and then another variable to represent the player. Let the game program randomly choose one of the three options. Assign the randomly picked option to the dedicated variable. Ask the player’s input. What will the player choose, rock, paper , or scissor? Take the player’s input and assign it to the dedicated variable. Compare the values of players input with the random number to determine who the winner is. Display the winner information. Declaring a class is the simplest way in object-oriented programming to build a custom data structure. You can start with a code snippet similar to the following: class MyGame // declare the class members { // attributes public: int x; // hold the player’s input

Transcript of It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf ·...

Page 1: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 56

Lecture #3

Rock-Scissor-Paper Game

Introduction Designing a computer program requires an engineer mindset. There are three basic steps a software

engineer needs to perform:

1. Defining the objective: You should have a clear understanding about the objective of the

program you are about to create. What is the program all about? What does it do? How does it

function? What will it produce?

2. List the procedures: In order to reach the goal, there are many things you need to do. Each of

the “things” is one of the procedures. Think about what you need to do to reach the goal and

create a logical list of them is a part of the software design.

3. Arrange the sequence: Computers are very procedural and often very linear (sequential). It

reads statement line by line and usually executes them line by line unless you tell them to jump

off the sequence. After you figure out all the necessary procedures, you will have to arrange

them in the logical sequence.

To design a simple Rock-Scissor-Paper game, for example, requires you to exercise these three

steps. The objective of this game is to determine which of any two players is the winner. Typically,

in such game, the combinations of players are:

human player vs. computer

human player 1 vs. human player 2

computer vs. computer

It is the program designer’s call to decide the combination. However, it is also the designer’s

responsibility to clearly define it. In this lecture, the instructor will use the first option (human

player vs. computer) to illustrate the design process. Once the combination is defined, it is time to

design the game rules.

The basic rules to determine who the winner is are:

When a scissor meets a paper, the scissor wins because scissors can cut papers.

When a scissor meets a rock, the rock wins because rocks can crack scissors.

When a paper meets a rock, the paper wins because papers can wrap rocks.

When two objects of a kind appear, such as a rock meets another rock, it is a tie.

The procedures needed to make this game possible are:

Design a data structure that can be used to represent the three options: rock, paper, and scissor.

Declare a variable to represent the computer, and then another variable to represent the player.

Let the game program randomly choose one of the three options.

Assign the randomly picked option to the dedicated variable.

Ask the player’s input. What will the player choose, rock, paper, or scissor?

Take the player’s input and assign it to the dedicated variable.

Compare the values of players input with the random number to determine who the winner is.

Display the winner information.

Declaring a class is the simplest way in object-oriented programming to build a custom data

structure. You can start with a code snippet similar to the following:

class MyGame // declare the class members

{

// attributes

public:

int x; // hold the player’s input

Page 2: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 57

int rn; // hold the random number

};

In the MyGame class, the instructor declared two variable to represent the human player’s and the

computer’s selection of options in C++ (where x is for holding the player’s selection, and rn is a

random number that will represent the computer’s selection).

Modularization is a good practice, and its concept fit in object-oriented programming; therefore,

you should also consider modularizing your program during the design process. You can then

declare some member functions and let each of the function handle one behavior (such as

“randomly choose one of the three options” as specified in the program design). class MyGame // declare the class members

{

// attributes

public:

int x;

int rn;

// behaviors

public:

int getRandomNumber(); // to generate random number

int getPlayerInput(); // to take player’s input

string showOption(int n);

void findWinner(int x, int rn); // to decide who the winner is

MyGame() // default constructor

{

getRandomNumber();

getPlayerInput();

findWinner(x, rn);

}

~MyGame() {} //destructor

};

You can create another function to take inputs from the human players. For example, int MyGame::getPlayerInput()

{

cout << "Select your option [0-2]: ";

cin >> x;

return x;

}

It is necessary to know that functions in C++ must be properly declared before defining its

contents. Every function declaration and definition must specify a return type, whether or not it

actually returns a value. There are two main types:

Void function: When a function does not return a value, void is the type specifier in the

function declaration and definition.

Value-returning functions: A function may be defined to return any type of value, except an

array type or a function type.

If a function is defined as having a return type of void, it should not return a value. In C++, a

function which is defined as having a return type of void, or is a constructor or destructor, must not

return a value. For example, void findWinner(int x, int rn);

If a function is defined as having a return type other than void, it should return a value. A function

Page 3: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 58

defined with a return type must include an expression containing the value to be returned. For

example, int MyGame::getPlayerInput()

{

cout << "Select your option [0-2]: ";

cin >> x;

return x;

}

When a function returns a value, the value is returned via a return statement to the caller of the

function, after being implicitly converted to the return type of the function in which it is defined.

Most of the programming language support pseudo-random generator. You just have to do some

research to find out how standard C++ and Visual C++ handle random numbers. For example, #include <ctime> // For time()

#include <cstdlib> // For srand() and rand()

....................

int MyGame::getRandomNumber()

{

srand(time(0)); // Initialize random number generator.

rn = rand() % 3; // limit option to 0-2

return rn;

}

To make sense to the computer, the above basic rules require a good design of data structure. In

this case, the design of data structure will be very simple. You can use three integers to represent

the three options. For example,

0 - rock

1 - scissor

2 - paper

Consequently you can define how the showOption() function can convert the numbers, 0, 1, and 2

to their string meanings “Rock”, “Scissor”, and “Paper” accordingly.

string MyGame::showOption(int n)

{

switch (n)

{

case 0: return "Rock"; break;

case 1: return "Scissor"; break;

case 2: return "Paper"; break;

}

}

To determine who the winner is, you can design your code based on the following matrix. As you

can see, the probability for both the player and computer to win is 33.33% (3/9 or 1/3).

x rn Winner/Tie

0 0 Tie

0 1 Player

0 2 Computer

1 0 Computer

1 1 Tie

1 2 Player

2 0 Player

2 1 Computer

Page 4: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 59

2 2 Tie

The above matrix leads to the design of the following code in C++. In C++, the logical OR operator

is denoted as ||, and the logical operator AND is denoted as &&. In each of the following three if

statements, three individual expressions (such as x==0 && rn==0) are combined to form a

compound expression (such as (x==0 && rn==0) || (x==1 && rn==1) || (x==2 && rn==2)). Again,

you can organize the codes in a function. For example, void MyGame::findWinner(int x, int rn)

{

if ((x==0 && rn==0) || (x==1 && rn==1) || (x==2 && rn==2))

{

cout << "It is a tie." << endl;

}

if ((x==0 && rn==1) || (x==1 && rn==2) || (x==2 && rn==0))

{

cout << "You win." << endl;

}

if ((x==0 && rn==2) || (x==1 && rn==0) || (x==2 && rn==1))

{

cout << "Computer wins." << endl;

}

}

In practice, you may be required to visualize your program design. While pseudocode is one way,

and flowchart is another, building an UML model has becoming a popular way to visualize your

program design.

UML (Unified Modeling Language) is an object-oriented analysis and design language from the

Object Management Group (OMG). Many design methodologies for describing object-oriented

systems were developed in the late 1980s. UML standardizes several diagramming methods and

now the universal model language adopted by most programmers.

MyGame

Attributes:

-x: int

-rn: int

Methods:

+getRandomNumber(): int

+getPlayerInput(): int

+showOption(int n): string

+findWinner(int x, int rn): void

To create an instance of this MyGame class, use:

// entry point

int main()

{

MyGame* start = new MyGame();

}

GUI-based

design

While text-based games can be used to illustrate the game design concept. Most games are now

GUI-based. GUI is a program interface that takes advantage of the computer's graphics capabilities

to make the program easier to use. Well-designed graphical user interfaces can free the user from

learning complex command languages. On the other hand, many users find that they work more

effectively with a command-driven interface, especially if they already know the command

Page 5: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 60

language.

Since a simple Rock-Scissor-Paper game only needs to types of user interfaces: one that takes input

from the player and one that displays the output. Although a game program is also designed based

on the IPO (input-processing-output) model, the players only have to touch the “I” part to give

input and wait for the “O” part to display the output. The “processing” part usually does not get the

player involved. In order to properly handle the “I” part, you often need some preparation. The

following table illustrates how the game design comply with the “IPO” model with respect to

“preparation”.

Preparation Design a data structure that can be used to represent the three options: rock,

paper, and scissor.

Declare a variable to represent the computer, and then another variable to

represent the player.

Let the game program randomly choose one of the three options.

Assign the randomly picked option to the dedicated variable.

Input Ask the player’s input. What will the player choose, rock, paper, or scissor?

Processing Take the player’s input and assign it to the dedicated variable.

Compare the values of players input with the random number to determine

who the winner is.

Output Display the winner information.

Most of the text-based game code, with just minor modification, can directly apply to “Preparation”

and “Processing” parts. “Input” and “Output”, on the other hand, are completely different because

they need of GUI-supports.

The simplest GUI-based tool provided by .NET Framework for output is the “MessageBox” class

which support Visual C++, Visual C# and Visual Basic programming. For example,

Similarly, Visual Basic provide a “InputBox” function as simple GUI tool to display a prompt in a

dialog box, waits for the user to input text or click a button, and then returns a string containing the

contents of the text box.

Interestingly, the .NET Framework does not provide an “InputBox” class for Visual C++ and

Visual C#. As a game programmer, you can manually create such “InputBox” class for Visual C++.

For example,

//FileName: InputBox.h

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

Page 6: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 61

public ref class InputBox: public Form {

public:

Label^ label1;

TextBox^ textBox1;

String^ Text;

public: InputBox(String^ input) {

label1 = gcnew Label;

label1->AutoSize = true;

label1->Location = Point(10, 10);

label1->Text = input;

Controls->Add(label1);

textBox1 = gcnew TextBox;

textBox1->Location = Point(200, 50);

textBox1->Width = 60;

Controls->Add(textBox1);

Button^ button1 = gcnew Button;

button1->Text = "OK";

button1->Width = 70;

button1->Location = Point(200, 80);

button1->Click += gcnew EventHandler(this,

&InputBox::button1_Click);

Controls->Add(button1);

this->Height = 150;

this->ShowDialog();

}

private: void button1_Click(Object^ sender, EventArgs^ e)

{

Text = textBox1->Text;

if (Text == "")

{

MessageBox::Show("No data entry found!");

}

else

{

this->Close();

}

}

};

The design of this “InputBox” class is very simple. According to the above code, the “InputBox”

class inherits the “Form” class of the .NET Framework. Therefore, it can use the Label, TextBox,

and Button controls of the “Form” class. In this “InputBox” class, there is a InputBox() function,

declared as public member of the “InputBox” class, to be called to create a Windows form similar

to the following:

The Label control is used to display a sentence defined by the game programmer through a

statement similar to the following example,

Label

TextBox

Button

Page 7: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 62

InputBox^ ib = gcnew InputBox("What year were your born?");

“InputBox^ ib” is the instantiation, which means “ib” is an instance (or an object) of the

“InputBox” class. The part, “InputBox("What year were your born?")”, is to call the “InputBox(String^

input)” function of the “InputBox” class. “What year were you born?” is the string literal specified

for displaying in the Label control.

The TextBox can take the player’s input and pass the value to the “Text” variable when the Button

is clicked:

Text = textBox1->Text;

The Button control is tied to the following code, so it can process the input.

private: void button1_Click(Object^ sender, EventArgs^ e)

{

Text = textBox1->Text;

if (Text == "")

{

MessageBox::Show("No data entry found!");

}

else

{

this->Close();

}

}

With this custom-made “InputBox” class, you can modify the getPlayerInput() function to the

following:

int MyGame::getPlayerInput()

{

str += "----Options------" + "\n";

str += "| 0. Rock |" + "\n";

str += "| 1. Scissor |" + "\n";

str += "| 2. Paper |" + "\n";

str += "-----------------" + "\n";

str += "Select your option [0-2]: ";

InputBox^ ib = gcnew InputBox(str);

int x = Convert::ToInt32(ib->Text);

return x;

}

The string literal to be display in the InputBox is assigned to the “str” variable with the use of “+=”

and “+” concatenation operators. Concatenation operators (+) can join multiple strings into a single

string. For example, the following combine two strings “apple” and “tree” into one single string

“appletree”.

str = "apple" + "tree"

The “+=” is a variation of the “+” concatenation operator. It can append new strings to existing

strings without over-writing the existing strings.

Concatenation Overwrite Append

Example str = "apple" + "tree"

str = "orange"

str = "apple" + "tree"

str += "orange"

Page 8: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 63

Result Orange appletreeorange

This modified getPlayerInput() function will create an InputBox similar to the following:

It also creates an instance of the InputBox class due to the following statement.

InputBox^ ib = gcnew InputBox(str);

When the player enters a character (such as “1”), the following line will convert the input from a

string type to the 32-bit integer type, and then assigned the converted integral value to the variable

x. This step is necessary because any character entered through keyboard are assumed to be string

type by Visual C++ (although they look a number to you).

int x = Convert::ToInt32(ib->Text);

The following is the modified findWinner() function. What have been modified are the output

methods. The outputs are no longer handled by “cout”. They are first appended to the “str”

variable, and display as a message box at the end by the “MessgaBox” class of .NET Framework.

void MyGame::findWinner(int x, int rn)

{

str = "";

if (x > 2)

{

str += "Invalid option." + "\n";

}

else

{

str += "Computer picked " + showOption(rn) + "\n";

str += "You picked " + showOption(x) + "\n";

if ((x==0 && rn==0) || (x==1 && rn==1) || (x==2 && rn==2))

{

str += "It is a tie." + "\n";

}

if ((x==0 && rn==1) || (x==1 && rn==2) || (x==2 && rn==0))

{

str += "You win." + "\n";

}

if ((x==0 && rn==2) || (x==1 && rn==0) || (x==2 && rn==1))

{

str += "Computer wins." + "\n";

}

}

MessageBox::Show(str);

}

The “Show” method is the one that displays the message box with specified text.

Page 9: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 64

Windows

Forms

Application

More and more GUI applications created for Windows operating systems are designed as Windows

Forms applications (WFAs). You can consider the following a template code which can create a

generic Windows Forms application.

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

public:

Form1() { }

~Form1() { } // destructor

};

[STAThread]

int main()

{

Application::Run(gcnew Form1);

}

Windows Forms applications in Visual C++ use the .NET Framework classes and other .NET

features with the new Visual C++ syntax. Therefore, you can directly apply all Form components

such as Label, Button, TextBox, ComboBox, and so on to it. Although you can use Visual Studio to

create a Windows Forms application using several standard controls from the Toolbox. It is

recommended that you learn to program the WFAs and components through hand-coding.

Without much modification, the above game codes can be converted to a WFA format, so the game

interface looks similar to:

The above figure illustrates how the instructor uses different Form components to create the user

interface. To declare and create an instance of a Label, use:

Label^ label1; // declare

......

label1 = gcnew Label; // create

or simply,

Label^ label1 = gcnew Label; // declare and create

Label

Label

Label

Label

ComboBox

Button

Page 10: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 65

To set the border to a three-dimensional border, for example, use: label1->BorderStyle = BorderStyle::Fixed3D;

Sometimes, it is necessary to declare a component as a “public” member of the class (e.g. the

“Form1” class), so all the members of the class can access it. In the following example, the label1

object is declared as a public member; therefore, one of the class member “changeIt” function can

access the label1 object and modified it. public ref class Form1: public Form

{

public:

Label^ label1; // declare as a global member

Form1() // Create a new instance of the form.

{

label1 = gcnew Label; // create by the default constructor

label1->Text = "Original message" // assign a default value

}

public: Void changeIt()

{

label1->Text = "new message" // assign new value to replace old

}

};

Many of the Form components, such as the Label control, support images. For example, Image^ m1; // declare an Image object

m1 = Image::FromFile("0.png"); // load the image file to the m1

object

label1->Image = m1; // assign m1 to the Label

You can take advantages to this and use images to enhance the game.

Design is an art, so you will find many different ways to design a game program. The .NET

Framework supports GDI+, which is a class-based API for C/C++ programmers. It enables

applications to use graphics and formatted text on both the video display and the printer.

The DrawImage() method draws the specified Image at the specified location and with the original

size. The syntax is: DrawImage(image, x, y, width, height);

where,

image: the Image object to draw.

x: The x-coordinate of the upper-left corner of the drawn image.

Page 11: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 66

y: The y-coordinate of the upper-left corner of the drawn image.

width: Width of the drawn image.

height: Height of the drawn image.

The following is an example. private: Void Form1_Paint(Object^ sender, PaintEventArgs^ e)

{

Drawing::Font^ font1 = gcnew Drawing::Font("Arial", 11);

g->DrawString("Player", font1, sB, 10, 10);

g->DrawString("Computer", font1, sB, 150, 10);

g->DrawImage(m1, 10, 40, w, h);

g->DrawImage(m2, 150, 40, w, h);

g->DrawString(str, font1, sB, 10, 160);

}

When you perform custom drawing, you can draw text in a single horizontal line starting at a

specified point. You can draw text in this manner by using the DrawString overloaded method of

the Graphics class that takes a Point or PointF parameter. The DrawString method also requires a

Brush and Font. The DrawString method of GDI+ draws the specified text string at the specified

location with the specified Brush and Font objects. The syntax is: DrawString(string, font, brush, x, y);

Review

Questions

1. Which is not one of three basic steps a software engineer needs to perform?

A. Defining the objective

B. Study existing coding model

C. List the procedures

D. Arrange the sequence

2. Which is one of the basic rules to determine who the winner is?

A. When a scissor meets a paper, the scissor wins because scissors can cut papers.

B. When a scissor meets a rock, the rock wins because rocks can crack scissors.

C. When a paper meets a rock, the paper wins because papers can wrap rocks.

D. All of the above.

3. Which is the correct way to declare a game class named "sudoku" in Visual C++?

A. gcnew class sudoku { }

B. new class sudoku { }

C. class sudoku { }

D. class new sudoku { }

4. Given a Visual C++ class named "sudoku", which can be its default constructor?

A. ^sudoku() {}

B. sudoku() {}

C. #sudoku() {}

D. ~sudoku() {}

5. Given the following code, what should be displayed if n equals 7?

string MyGame::showOption(int n)

{

switch (n%3) {

case 0: return "Rock"; break;

case 1: return "Scissor"; break;

case 2: return "Paper"; break;

}

}

Page 12: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 67

A. Scissor

B. Rock

C. Paper

D. None of the above

6. Which method should return an integer value to its caller?

A. void showIt(int x) {}

B. int showIt() {}

C. showIt() {}

D. return showIt(int x) {}

7. Given the following code, what should be displayed if x equals 2 and rn equals 0?

if ((x==0 && rn==0) || (x==1 && rn==1) || (x==2 && rn==2)) {

cout << "It is a tie." << endl;

}

if ((x==0 && rn==1) || (x==1 && rn==2) || (x==2 && rn==0))

{

cout << "You win." << endl;

}

if ((x==0 && rn==2) || (x==1 && rn==0) || (x==2 && rn==1))

{

cout << "Computer wins." << endl;

}

A. It is a tie.

B. You win.

C. Computer wins.

D. None of the above

8. Which indicates that the getNumber() method is a member of "sudoku" class in Visual C++?

A. void sudoku::getNumber() { }

B. void sudoku.getNumber() { }

C. void sudoku->getNumber() { }

D. void sudoku=getNumber() { }

9. Given the following TextBox control, which can convert two characters "23" to integer type in

Visual C++?

TextBOx^ textBox1 = gcnew TextBox;

A. ToInt32(textBox1->Text)

B. ToInt32::Convert(textBox1->Text)

C. Convert::ToInt32(textBox1->Text)

D. Convert->ToInt32(textBox1->Text)

10. Given the following code, which will load an image named "1.jpg" to "pacman"?

Image^ pacman;

A. pacman = Image::FromFile("1.jpg");

B. pacman = Image::File("1.jpg");

C. pacman = Image:->FromFile("1.jpg");

D. pacman = Image->File("1.jpg");

Page 13: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 68

Lab #3 Designing Using Objects

Learning Activity #1: Text-based

1. Launch the Developer Command Prompt. Do not use regular Windows Command Prompt.

2. Under the C:\ drive, type md c:\cis264 and press [Enter] to create a directory named C:\cis264 if it does not

exist.

C:\Program Files\Microsoft Visual Studio 14.0>md c:\cis264

3. In the DeVeloper Command Prompt, type cd c:\cis264 and press [Enter] to change to the C:\cis264

directory. C:\Program Files\Microsoft Visual Studio 14.0>cd c:\cis264

C:\cis264>

4. In the C:\cis264 directory, type notepad lab3_1.cpp and press [Enter] to use Notepad to create a new text

file named lab3_1.cpp.

C:\cis264>notepad lab3_1.cpp

5. In the Notepad editor, type the following contents:

#include <iostream>

#include <string>

#include <ctime> // For time()

#include <cstdlib> // For srand() and rand()

using namespace std;

class MyGame // declare the class members

{

// attributes

public:

int x;

int rn;

// behaviors

public:

int getRandomNumber();

int getPlayerInput();

string showOption(int n);

void findWinner(int x, int rn);

MyGame() // default constructor

{

getRandomNumber();

getPlayerInput();

findWinner(x, rn);

}

~MyGame() {} //destructor

};

// Define member functions

int MyGame::getRandomNumber()

Page 14: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 69

{

srand(time(0)); // Initialize random number generator.

rn = rand() % 3; // limit option to 0-2

return rn;

}

int MyGame::getPlayerInput()

{

cout << "----Options------" << endl;

cout << "| 0. Rock |" << endl;

cout << "| 1. Scissor |" << endl;

cout << "| 2. Paper |" << endl;

cout << "-----------------" << endl;

cout << "Select your option [0-2]: ";

cin >> x;

return x;

}

string MyGame::showOption(int n)

{

switch (n) {

case 0: return "Rock"; break;

case 1: return "Scissor"; break;

case 2: return "Paper"; break;

}

}

void MyGame::findWinner(int x, int rn) {

if (x > 2)

{

cout << "Invalid option." << endl;

}

else

{

cout << "Computer picked " << showOption(rn) << endl;

cout << "You picked " << showOption(x) << endl;

if ((x==0 && rn==0) || (x==1 && rn==1) || (x==2 && rn==2))

{

cout << "It is a tie." << endl;

}

if ((x==0 && rn==1) || (x==1 && rn==2) || (x==2 && rn==0))

{

cout << "You win." << endl;

}

if ((x==0 && rn==2) || (x==1 && rn==0) || (x==2 && rn==1))

{

cout << "Computer wins." << endl;

}

}

}

// entry point

int main() {

MyGame* start = new MyGame();

}

6. Open the Developer Command Prompt.

7. Type cd c:\cis264 and press [Enter] to change to c:\cis264 directory.

8. Compile the code using:

Page 15: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 70

cl lab3_1.cpp

9. Type lab3_1.exe and press [Enter] to test the program. A sample output looks:

10. Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or .docx).

Learning Activity #2: Simple GUI

1. In the C:\cis264 directory, type notepad InputBox.h and press [Enter] to create a custom-made header file

with the following contents: #using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class InputBox: public Form

{

public:

Label^ label1;

TextBox^ textBox1;

String^ Text;

public: InputBox(String^ input)

{

label1 = gcnew Label;

label1->AutoSize = true;

label1->Location = Point(10, 10);

label1->Text = input;

Controls->Add(label1);

textBox1 = gcnew TextBox;

textBox1->Location = Point(200, 50);

textBox1->Width = 60;

Controls->Add(textBox1);

Button^ button1 = gcnew Button;

button1->Text = "OK";

button1->Width = 70;

button1->Location = Point(200, 80);

button1->Click += gcnew EventHandler(this, &InputBox::button1_Click);

Controls->Add(button1);

this->Height = 150;

this->ShowDialog();

}

private: void button1_Click(Object^ sender, EventArgs^ e)

{

Page 16: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 71

Text = textBox1->Text;

if (Text == "")

{

MessageBox::Show("No data entry found!");

}

else

{

this->Close();

}

}

};

2. In the c:\cis264 directory, use Notepad to create a new text file named lab3_2.cpp with the following contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

#include "InputBox.h" // import the InputBox.h file

using namespace System;

using namespace System::Windows::Forms;

ref class MyGame // declare the class members

{

// attributes

public:

int x;

int rn;

String^ str;

// behaviors

public:

int getRandomNumber();

int getPlayerInput();

String^ showOption(int n);

void findWinner(int x, int rn);

MyGame() // default constructor

{

rn = getRandomNumber();

getPlayerInput();

findWinner(x, rn);

}

~MyGame() {} //destructor

};

// Define member functions

int MyGame::getRandomNumber()

{

Random^ rn = gcnew Random();

return rn->Next(0, 10000000) % 3;

}

int MyGame::getPlayerInput()

{

str += "----Options------" + "\n";

str += "| 0. Rock |" + "\n";

str += "| 1. Scissor |" + "\n";

str += "| 2. Paper |" + "\n";

str += "-----------------" + "\n";

str += "Select your option [0-2]: ";

InputBox^ ib = gcnew InputBox(str);

Page 17: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 72

x = Convert::ToInt32(ib->Text);

return x;

}

String^ MyGame::showOption(int n)

{

switch (n) {

case 0: return "Rock"; break;

case 1: return "Scissor"; break;

case 2: return "Paper"; break;

}

}

void MyGame::findWinner(int x, int rn) {

str = "";

if (x > 2)

{

str += "Invalid option." + "\n";

}

else

{

str += "Computer picked " + showOption(rn) + "\n";

str += "You picked " + showOption(x) + "\n";

if ((x==0 && rn==0) || (x==1 && rn==1) || (x==2 && rn==2))

{

str += "It is a tie." + "\n";

}

if ((x==0 && rn==1) || (x==1 && rn==2) || (x==2 && rn==0))

{

str += "You win." + "\n";

}

if ((x==0 && rn==2) || (x==1 && rn==0) || (x==2 && rn==1))

{

str += "Computer wins." + "\n";

}

}

MessageBox::Show(str);

}

// entry point

int main() {

MyGame^ start = gcnew MyGame();

}

3. Open the Developer Command Prompt.

4. Type cd c:\cis264 and press [Enter] to change to c:\cis264 directory.

5. Compile the code using:

cl /clr lab3_2.cpp /link /subsystem:windows /ENTRY:main

6. Test the program (by typing lab3_2.exe). A sample output looks:

Page 18: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 73

and

7. Download the “assignment template”, and rename it to lab3.doc if necessary. Capture a screen shot similar to

the above figure and paste it to a Word document named lab3.doc (or .docx).

Learning Activity #3: Windows Forms Application

1. In the C:\cis264 directory, use Notepad to create a new text file named lab3_3.cpp with the following contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

public:

Label^ label1;

Label^ label2;

Label^ label3;

Label^ label4;

ComboBox^ comboBox1;

Button^ button1;

String^ str;

int x;

int rn;

Form1() // Create a new instance of the form.

{

label1 = gcnew Label;

label1->Location = Point(10, 10);

label1->Text = "Player";

label2 = gcnew Label;

label2->Location = Point(150, 10);

label2->Text = "Computer";

label3 = gcnew Label;

label3->Location = Point(150, 40);

label3->BorderStyle = BorderStyle::FixedSingle;

label3->Width = 100;

label3->Text = "";

label4 = gcnew Label;

label4->Location = Point(10, 100);

label4->AutoSize = true;

label4->Text = "";

comboBox1 = gcnew ComboBox;

comboBox1->Location = Point(10, 40);

comboBox1->Size = Drawing::Size(120, 30);

comboBox1->Items->Add("Rock");

comboBox1->Items->Add("Scissor");

comboBox1->Items->Add("Paper");

Page 19: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 74

// create a button

this->button1 = gcnew Button;

button1->Text = "Play";

button1->Location = Point(100, 220);

button1->Click += gcnew EventHandler(this, &Form1::button1_Click);

Controls->Add(label1);

Controls->Add(label2);

Controls->Add(label3);

Controls->Add(label4);

Controls->Add(comboBox1);

Controls->Add(button1);

}

~Form1() { } // destructor

private: int getRandomNumber() {

Random^ rand = gcnew Random();

rn = rand->Next(0, 10000000) % 3;

return rn;

}

private: String^ showOption(int n)

{

switch (n) {

case 0: return "Rock"; break;

case 1: return "Scissor"; break;

case 2: return "Paper"; break;

}

}

private: Void button1_Click(Object^ sender, EventArgs^ e)

{

getRandomNumber();

x = comboBox1->SelectedIndex;

label3->Text = showOption(rn);

str = "";

if (x > 2)

{

str += "Invalid option." + "\n";

}

else

{

str += "Computer picked " + showOption(rn) + "\n";

str += "You picked " + showOption(x) + "\n";

if ((x==0 && rn==0) || (x==1 && rn==1) || (x==2 && rn==2))

{

str += "It is a tie." + "\n";

}

if ((x==0 && rn==1) || (x==1 && rn==2) || (x==2 && rn==0))

{

str += "You win." + "\n";

}

if ((x==0 && rn==2) || (x==1 && rn==0) || (x==2 && rn==1))

{

str += "Computer wins." + "\n";

Page 20: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 75

}

}

label4->Text = str;

}

};

[STAThread]

int main()

{

Application::Run(gcnew Form1);

}

2. Open the Developer Command Prompt.

3. Type cd c:\cis264 and press [Enter] to change to c:\cis264 directory.

4. Compile the code using:

cl /clr lab3_3.cpp /link /subsystem:windows /ENTRY:main

5. Test the program (by typing lab3_3.exe). Click Play to find the winner. A sample output looks:

6. Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or .docx).

Learning Activity #4: Windows Forms Application with Image

1. Download the rsp.zip file from DocSharing and extract its contents to the C:\cis264 directory.

2. In the C:\cis264 directory, use Notepad to create a new text file named lab3_4.cpp with the following contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

public:

Label^ label1;

Label^ label2;

Label^ label3;

Label^ label4;

Label^ label5;

Image^ m1;

Image^ m2;

Button^ button1;

String^ str;

Random^ rand;

int x;

int rn;

Page 21: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 76

Form1() // Create a new instance of the form.

{

x=0; // set initial value of x to 0

m1 = Image::FromFile(getRandomNumber() + ".png");

m2 = Image::FromFile(x + ".png");

label1 = gcnew Label;

label1->Location = Point(10, 10);

label1->Text = "Player";

label2 = gcnew Label;

label2->Location = Point(150, 10);

label2->Text = "Computer";

label3 = gcnew Label;

label3->Location = Point(10, 40);

label3->BorderStyle = BorderStyle::FixedSingle;

label3->Size = Drawing::Size(m1->Width, m1->Height);

label3->Image = m1;

label3->Click += gcnew EventHandler(this, &Form1::label3_Click);

label4 = gcnew Label;

label4->Location = Point(150, 40);

label4->BorderStyle = BorderStyle::FixedSingle;

label4->Size = Drawing::Size(m1->Width, m1->Height);

label4->Text = "";

label5 = gcnew Label;

label5->Location = Point(10, 160);

label5->AutoSize = true;

label5->Text = "";

// create a button

this->button1 = gcnew Button;

button1->Text = "Play";

button1->Location = Point(100, 220);

button1->Click += gcnew EventHandler(this, &Form1::button1_Click);

Controls->Add(label1);

Controls->Add(label2);

Controls->Add(label3);

Controls->Add(label4);

Controls->Add(label5);

Controls->Add(button1);

}

~Form1() { } // destructor

private: int getRandomNumber() {

DateTime dt = DateTime::Now;

rand = gcnew Random(dt.Millisecond);

rn = rand->Next(0, 10000000) % 3;

return rn;

}

private: String^ showOption(int n)

{

String^ str = "";

switch (n) {

case 0: str = "Rock"; break;

case 1: str = "Scissor"; break;

case 2: str = "Paper"; break;

Page 22: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 77

}

return str;

}

private: Void label3_Click(Object^ sender, EventArgs^ e)

{

x++;

x = x % 3;

m1 = Image::FromFile(x + ".png");

label3->Image = m1;

label4->Text = "";

label5->Text = "";

}

private: Void button1_Click(Object^ sender, EventArgs^ e)

{

getRandomNumber();

m2=Image::FromFile(rn + ".png");

label4->Image = m2;

str = "";

if (x > 2)

{

str += "Invalid option." + "\n";

}

else

{

str += "Computer picked " + showOption(rn) + "\n";

str += "You picked " + showOption(x) + "\n";

if ((x==0 && rn==0) || (x==1 && rn==1) || (x==2 && rn==2))

{

str += "It is a tie." + "\n";

}

if ((x==0 && rn==1) || (x==1 && rn==2) || (x==2 && rn==0))

{

str += "You win." + "\n";

}

if ((x==0 && rn==2) || (x==1 && rn==0) || (x==2 && rn==1))

{

str += "Computer wins." + "\n";

}

}

label5->Text = str;

}

};

[STAThread]

int main()

{

Application::Run(gcnew Form1);

}

3. Open the Developer Command Prompt.

4. Type cd c:\cis264 and press [Enter] to change to c:\cis264 directory.

5. Compile the code using:

cl /clr lab3_4.cpp /link /subsystem:windows /ENTRY:main

Page 23: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 78

6. Test the program (by typing lab3_4.exe). Click the image under “Player” to select the player’s option. Clikc

Play to find the winner. A sample output looks:

7. Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or .docx).

Learning Activity #5: Windows Forms

7. In the C:\cis264 directory, create a new text file named lab3_5.cpp with the following contents:

#using <System.dll>

#using <System.Windows.Forms.dll>

#using <System.Drawing.dll>

using namespace System;

using namespace System::Drawing;

using namespace System::Windows::Forms;

public ref class Form1: public Form

{

public:

Graphics^ g;

SolidBrush^ sB;

Image^ m1;

Image^ m2;

Button^ button1;

Button^ button2;

String^ str;

Random^ rand;

int x;

int rn;

int w;

int h;

Form1() // Create a new instance of the form.

{

x=0; // set initial value of x to 0

m1 = Image::FromFile(getRandomNumber() + ".png");

m2 = Image::FromFile(x + ".png");

w = m1->Size.Width;

h = m1->Size.Height;

g = this->CreateGraphics();

sB = gcnew SolidBrush(Color::Black);

// create a button

button1 = gcnew Button;

button1->Text = "Select";

button1->Location = Point(70, 220);

Click this image

Page 24: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 79

button1->Click += gcnew EventHandler(this, &Form1::button1_Click);

// create a button

button2 = gcnew Button;

button2->Text = "Play";

button2->Location = Point(150, 220);

button2->Click += gcnew EventHandler(this, &Form1::button2_Click);

Controls->Add(button1);

Controls->Add(button2);

this->Paint += gcnew PaintEventHandler(this, &Form1::Form1_Paint);

}

~Form1() { } // destructor

private: int getRandomNumber() {

DateTime dt = DateTime::Now;

rand = gcnew Random(dt.Millisecond);

rn = rand->Next(0, 10000000) % 3;

return rn;

}

private: String^ showOption(int n)

{

String^ str = "";

switch (n) {

case 0: str = "Rock"; break;

case 1: str = "Scissor"; break;

case 2: str = "Paper"; break;

}

return str;

}

private: Void button1_Click(Object^ sender, EventArgs^ e)

{

x++;

x = x % 3;

m1 = Image::FromFile(x + ".png");

str = "";

this->Refresh();

}

private: Void Form1_Paint(Object^ sender, PaintEventArgs^ e) {

Drawing::Font^ font1 = gcnew Drawing::Font("Arial", 11);

g->DrawString("Player", font1, sB, 10, 10);

g->DrawString("Computer", font1, sB, 150, 10);

g->DrawImage(m1, 10, 40, w, h);

g->DrawImage(m2, 150, 40, w, h);

g->DrawString(str, font1, sB, 10, 160);

}

private: Void button2_Click(Object^ sender, EventArgs^ e)

{

getRandomNumber();

m2=Image::FromFile(rn + ".png");

str = "";

if (x > 2)

{

str += "Invalid option." + "\n";

}

Page 25: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 80

else

{

str += "Computer picked " + showOption(rn) + "\n";

str += "You picked " + showOption(x) + "\n";

if ((x==0 && rn==0) || (x==1 && rn==1) || (x==2 && rn==2))

{

str += "It is a tie." + "\n";

}

if ((x==0 && rn==1) || (x==1 && rn==2) || (x==2 && rn==0))

{

str += "You win." + "\n";

}

if ((x==0 && rn==2) || (x==1 && rn==0) || (x==2 && rn==1))

{

str += "Computer wins." + "\n";

}

}

this->Refresh();

}

};

[STAThread]

int main()

{

Application::Run(gcnew Form1);

}

8. Open the Developer Command Prompt.

9. Type cd c:\cis264 and press [Enter] to change to c:\cis264 directory.

10. Compile the code using:

cl /clr lab3_5.cpp /link /subsystem:windows /ENTRY:main

11. Test the program (by typing lab3_5.exe). A sample output looks:

12. Capture a screen shot similar to the above figure and paste it to a Word document named lab3.doc (or .docx).

Submittal

1. Complete all the 5 learning activities and the programming exercise in this lab.

2. Create a .zip file named lab3.zip containing ONLY the following self-executable files.

lab3_1.exe

lab3_2.exe

lab3_3.exe

lab3_4.exe

lab3_5.exe

Page 26: It is the program designer’s call to decide the ...students.cypresscollege.edu/cis264/lc03.pdf · In practice, you may be required to visualize your program design. While pseudocode

CIS264 – Penn P. Wu, Ph.D. 81

lab3.doc (or lab3.docx) [You may be given zero point if this Word document is missing]

Programming Exercise 03:

1. Launch the Developer Command Prompt.

2. Use Notepad to create a new text file named ex03.cpp.

3. Add the following heading lines (Be sure to use replace [YourFullNameHere] with the correct one).

//File Name: ex03.cpp

//Programmer: [YourFullNameHere]

4. Use all the sample codes in this lecture to create a simple “Rock-Scissor-Paper” game that allows TWO

HUMAN PLAYERS to play against each other. Notice that all the game codes in this lecture are create for

ONE human player to play against the computer. [Hint: You don’t need the getRandomNumber() function any

longer]

5. Compile the source code to produce executable code.

and and

6. Download the “programming exercise template”, and rename it to ex03.doc if necessary. Capture a screen

similar to the above one and paste it to a Word document named “ex01.doc” (or .docx).

7. Upload both the source file and executable code as file response of the Assignment.

8. Compress both the source file (ex03.cpp) and executable code (ex03.exe) to ex03.zip. Upload the .zip file.

Note: You will not receive any credit if you submit file(s) to the wrong question.

Grading criteria:

You will earn credit only when the following requirements are fulfilled. No partial credit is given.

You successfully submit all required files in a .zip file.

Your code must allow two human players to play against each other to earn credit.

Your source code must be fully functional and may not contain syntax errors in order to earn credit.

Your executable file (program) must be executable to earn credit.