This chapter teaches how to program two games using if and else logic.
The equivalence operator defines equivalence and cannot be the same symbol as the assignment operator. So what do we do? The assignment operator is = , so we make the equivalence operator ==. This can become very confusing.
The if statement.
The syntax for the if statement is:
if (condition)
{
do this code;
}
The else
statement can be used in conjunction with the if statement.
The else statement must be the first code directly after the
closing brace of the if statement. The syntax is as
follows:
if (condition)
{
do this code;
}
else
{
do this code;
}
The else if
statement can be used about the same way as the else statement.
The difference is that you can only have one else statement per
if statement, but you can have as many else if statements as you
want. Else if statements can be follower by an else statement.
Here is a syntax example:
if (condition)
{
do this code;
}
else if (condition)
{
do this code;
}
else if (condition)
{
do this code;
}
else
{
do this code;
}
Here is a real working example:
int Answer;
cin>>Answer;
if (Answer == 1)
{
cout<<"You said 1.";
}
else if (Answer > 1)
{
cout<<"That number is greater
than 1.";
}
else if (Answer < 1)
{
cout<<"That number is less than
1.";
}
else
{
cout<<"That wasn't a
number.";
}
When a variable is
declared we often want to give it a starting value.
Variables that are not assigned a value upon declaration
automatically have a value. The value is what ever value
was previously stored in the Random Access Memory that the
variable is assigned. Consider the following code:
int Stuff;
cout<<Stuff;
The value can be any int value. Try it for yourself.
When we decide to loop
using a variable in the condition, the loop will not be executed
EVER if the condition isn't true. Consider this code:
int
Value;
while
(Value > 2)
{
do this code
}
The
above loop has a 50 percent chance of not being executed.
To prevent this we should do the following:
int
Value = 3;
while
(Value > 2)
{
do this code
}
The difference between a null terminated string and a character is that a null terminated string is a string that ends with the null ascii value which in C++ is represented as \0. If you type "N" the compiler interprets the value as N\0 . "Hi" would be Hi\0 . A character would be written as 'n' . 'n' is not equal to "n" because "n" is a null terminated string.
The modulus operator is the % symbol. Remember elementary school division? Remember remainders? The modulus of two numbers is the remainder. So 6 % 7 would give the value of 1 because 7 / 6 = 1 remainder 1.
Now
let's look at how to create random numbers. We need to use
the stdlib.h header for random numbers. We will also use
time.h to help give us a random value. We will use the time
as a seed because every time the number is seeded the time should
be different. srand() is the function that seeds the random
number generator so we can grow a tasty number. To use time
we must type convert time to be unsigned. This
basically takes the absolute value of time. We want to pass
NULL to time. After seeding the generator we can call the
rand() function. After that we will take the modulus of the
number we want to be the highest possible value. The
following code will assign a number between 0 and 99 to Number:
srand((unsigned)time(
NULL ));
Number
= rand() % 99;
To get a
random number between 2 and 100 we would do the following:
srand((unsigned)time(
NULL ));
Number
= (rand() % 98) + 2;
The break
statement is used to end a loop as follows:
while(condition)
{
cout<<"Hello"<<endl;
break;
cout<<"Good Bye"<<endl;
}
cout<<"We
are out!";
output:
Hello
We
are out!
You will immediately exit the most inner loop if a break statement is called.
The or
operator is || . Here is a truth table for the or operator:
true or true | true |
true or false | true |
false or true | true |
false or false | false |
The and
operator is && . Here is a truth table for the and
operator:
true and true | true |
true and false | false |
false and true | false |
false and false | false |
The toupper()
and tolower() functions from ctype.h . Given
a character string the toupper function will return a string that
as all upper case and yes you guessed it tolower will return a
string as all lower case. Consider the following:
char
Answer;
cin>>Answer;
if
(toupper(Answer) == 'Y')
{
cout<<"The answer is Y."
}
If a user types several characters before hitting <enter> the input will be shortened according to the size of the declared variable. So we could say the above and if the user typed yes the value in Answer would be 'y' . |
We
now have enough information for our first game, the number
game! Here it is:
//
main3b.cpp
//
This holds a number game
//
Copyright (c) 1998
///////////////////////////
#include
<stdlib.h> // For rand and srand
#include
<time.h> // For time
#include
<iostream.h> // For cin and cout
#include
<ctype.h> // For tolower
//
The main function of our number game
void
main()
{
char
Exit='N'; //Take a Y or N
//
Print a welcome
cout<<"Welcome
to the number game!"<<endl;
//
loop till user wants to exit
while(toupper(Exit)
!= 'Y')
{
int Number; // Will hold a number between 1 and 100
int Answer; // holds answer
int Count=1;// Count wrong answers
// Seed and create a random number
srand((unsigned)time( NULL )); // use time as a seed
Number = (rand() % 99) + 1; // avoid 0
//Ask for input
cout<<"I'm thinking of a number between 1 and
100."<<endl
<<"what is my number? ";
cin>>Answer; // Get an answer
// infinite loop!!
while(9>0)
{
// Check for bad input
if((Answer > 100) || (Answer< 1))
{
cout<<"I said between 1 and 100!"<<endl;
Count = Count + 1; // Add 1 to Count
}
// use the equivalence operator
else if(Answer == Number)
{
cout<<"Good Job!"<<endl
<<"You won in "<<Count<<"
tries!"<<endl;
break; //This exits the most inner loop
}
// Too high
else if(Answer > Number)
{
cout<<"Too High!"<<endl;
Count = Count + 1; // Add 1 to Count
}
// Too Low
else if(Answer < Number)
{
cout<<"Too Low!"<<endl;
Count = Count + 1; // Add 1 to Count
}
// Ask again
cout<<"What is my number? ";
cin>>Answer;
}
//See if the user wants to leave
cout<<"Would you like to exit (Yes or No)? ";
cin>>Exit;
}
}
Now we have a few more things to go over before we get to roulette. First let's deal with functions. As we have discussed main is a function. main has always been void, which means that it doesn't return a value. If we declared it with int we would expect it to return an int value.
The return
statement. Consider the following code:
char
YorN()
{
char Answer; // This will hold the users answer
cout<<"Yes or No? ";
cin>>Answer;
return Answer;
}
The above function will return the first letter of the user's input. A function ends immediately after the return statement is called in the same fashion as the break statement for a loop. If the function is void we could just say return; .
Function
prototypes are necessary for functions that following the
code that is executed. Here is an example with a function
prototype:
char
YorN(); //YorN 's prototype
void
main()
{
char Answer = YorN;
if( YorN = Y)
{
cout<<"You answered Yes.";
}
}
char
YorN() //YorN's function
{
char Answer; // This will hold the users answer
cout<<"Yes or No? ";
cin>>Answer;
return Answer;
}
Although
we can only return one value for every function, we can pass
several values to a function. This is necessary because
every function has it's own symbol table and can only access
globals and variables within the function. Here is an
example where we pass a value:
int
X2(int Value); //X2's prototype
void main()
{
int Value;
cin>>Value;
cout<<X2(Value);
}
int
X2(int Value)
{
return Value * 2;
}
The output will be the input times 2 for the above example.
With roulette we need to deal with complicated strings. cin>>CharArray will stop at a new line character or a space character. So we will try to keep the user from using spaces.
The strlen() function returns the length of the string that you pass to it. strlen() is defined in the string.h header.
A
character string in C++ is an array. That means we can
access characters in it as follows:
char
Answer = "Hello"; // A six char
array.
cout<<Answer[0];
// This outputs the first character which is H
To create an array the
syntax is:
type name[2];
An example is:
char String[2];
Arrays in C++
unfortunately must be declared using constants. Consider
the following code:
#define MAX_SIZE 20
char String[MAX_SIZE - 9];
Because MAX_SIZE - 9
always evaluates to the same number it is a valid constant.
Many times people will use MAX_SIZE - 1 because there is a 0 cell
in C++. Consider the following:
#define MAX_SIZE 20
char String[MAX_SIZE ] = "Hello";
The memory for the array
will be as follows:
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
H | e | l | l | o | \0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
When using the bit shift operator, strlen, strcmp and strcpy the
program ignores and stops at the null value in a string.
When designing a program that needs an array you must plan for the largest array you would need. You can use an int value to keep track of how much of the array you are using. |
We
unfortunately cannot use the equivalence operator with strings in
C++. Instead we can use strcmp() to compare
strings. The syntax is as follows:
strcmp(String1,String2)
If the above strings are equal the function returns 0. strcmp() is defined in string.h .
The isdigit() function is true if the string it is passed is all digits. isalpha() is true if the string is alphanumeric.
Now we are ready for Roulette! Yeah, don't lose all your money!
// main3a.cpp
//
This is a roulette game for the C++ Game Programming Tutorial
//
Written by Forest J. Handford
//
Copyright (c) 1998
//////////////////////////////////////////////////////////////
//
These are all standard C++ header files
#include
<iostream.h> // For cin and cout
#include
<stdlib.h> // For rand and srand
#include
<ctype.h> // For isdigit
#include
<time.h> // For time to seed randomization
#include
<string.h> // For strcmp and strlen
//
The prototype or the function must be declared before it is
called
int
Bet(); // Function Prototype
//
This is the main function of our game
void
main()
{
//
We'll use doubles in case of decimal values.
double
Money; // Amount that player will lose!
double
Wager; // The amount the player is betting
char
Exit = 'Y'; //This will hold Y or N.
//Print
Welcome message
cout<<"
Welcome to Roullette"<<endl<<endl
<<"How much money did you bring to our casino? $
";
cin>>Money;
// Prompt for money
cout<<endl<<endl;
// This is for formatting
//
Loop until the player wants to exit
while(toupper(Exit)
!= 'N')
{
cout<<"Place your bets, Place your
bets!"<<endl<<endl
<<"You have: "<<Money<<endl
<<"How much would you like to bet? $ ";
cin>>Wager;
cout<<endl<<endl;
Money = Money - Wager; // Take the wager out of their total
Money = Money + (Wager * Bet()); // Add their winning to the
total
// If they run out of money kick them out of the casino
if (Money < 1)
{
cout<<endl<<endl<<"You Sir must get more
money! Good Bye!"
<<endl<<endl;
break;
}
// See if they want to lose more money
cout<<endl<<endl<<"Would you like to play
again (Yes or No)? ";
cin>>Exit; // We only need the first char
cout<<endl<<endl<<endl;
}
//
Say Good Bye
cout<<"Thanks
for playing, Come back soon!"<<endl<<endl;
}
//
This function will display the board and take the guess.
//
If they win it will return the odds else 0. It takes
int
Bet()
{
char Answer[15]=""; // This will hold a character
answer
int
Wheel; // This will hold the wheels final resting
stop
//
Print the choices
cout<<"0
|1 4 7 10 13 16 19 22 25 28 31
34|1stColumn"<<endl
<<"--|2 5 8 11 14 17 20 23 26 29 32
35|2ndColumn"<<endl
<<"00|3 6 9 12 15 18 21 24 27 30 33
36|3rdColumn"<<endl
<<"--| 1st12
| 2nd12 | 3rd12
|--- "<<endl
<<" | 1stHalf | Even | ODD |
2ndHalf |
"<<endl<<endl;
//
Print the profit margin
cout<<"
The Profit Margin"<<endl
<<"
+-------------+"<<endl
<<"
|EVEN | 2X |"<<endl
<<"
|ODD | 2X |"<<endl
<<"
|Halves | 2X |"<<endl
<<"
|Columns | 3X |"<<endl
<<"
|12ths | 3X |"<<endl
<<"
|Numbers | 35X|"<<endl
<<"
+-------------+"<<endl<<endl;
//
Prompt the user
cout<<endl<<"What
would you like to bet your money on? ";
cin>>Answer;
// Recieve input
//cout<<endl<<Answer<<endl;
This had been used for debugging
//to
see what the input looked like internally
//
Seed and create a random number
srand((unsigned)time(
NULL ));
Wheel = rand() % 37;
//
First output where the wheel stops.
if
(Wheel == 37) // 37 will be 00
{
cout<<"The wheel has stopped at 00!"<<endl;
}
else
{
cout<<"The lucky number is
"<<Wheel<<" !"<<endl;
}
//
Check for 00 and 0 first to prevent 37 being odd
if(strcmp(Answer,"00")
== 0)
{
if (Wheel == 35)
{
cout<<"You are a winner!"<<endl;
return 36;
}
else
{
cout<<"Oops,Try Again!"<<endl;
return 0;
}
}
//
Check for 0
else
if(strcmp(Answer,"0")==0)
{
if (Wheel == 0)
{
cout<<"You are the winner!"<<endl;
return 35;
}
else
{
cout<<"Oops, Try Again!"<<endl;
return 0;
}
}
//
0 and 00 cannot be in a combo so check for it here
else
if((Wheel == 0) || (Wheel == 37))
{
cout<<"You Sir, have
lost!"<<endl<<endl;
}
//The
following will work for 2 digit answers
else
if(isdigit(Answer[0]) && isdigit(Answer[1]) &&
(strlen(Answer) == 2))
{
if ((int (Answer)) == Wheel)
{
cout<<"You won!"<<endl<<endl;
return 36;
}
else
{
cout<<"Sorry Sport, Try Again!"<<endl;
return 0;
}
}
//
The following is for 1 digit answers
else
if(isdigit(Answer[0]) && (strlen(Answer) == 1))
{
if ((int (Answer)) == Wheel)
{
cout<<"You won!"<<endl<<endl;
return 36;
}
else
{
cout<<"Sorry Sport, Try Again!"<<endl;
return 0;
}
}
//
We only need the first character for even, and odd
else
{
if(tolower(Answer[0]) == 'e')
{
if (Wheel % 2 == 0)
{
cout<<"You are a
winner!"<<endl<<endl;
return 2;
}
else
{
cout<<"Sorry, you were
wrong!"<<endl<<endl;
return 0;
}
}
else if(tolower(Answer[0]) == 'o')
{
if (Wheel % 2 == 1)
{
cout<<"You are a winner
today!"<<endl<<endl;
return 2;
}
else
{
cout<<"Sorry, you guessed
poorly."<<endl<<endl;
return 0;
}
}
// Check for 1st12
else if(strcmp(Answer,"1st12")==0)
{
if (Wheel < 13)
{
cout<<"You have won!"<<endl<<endl;
return 3;
}
else
{
cout<<"Sorry, you gave an incorrect answer
Sir."<<endl<<endl;
return 0;
}
}
//Check for 2nd12
else if(strcmp(Answer,"2nd12") == 0)
{
if ((Wheel > 13) && (Wheel < 25))
{
cout<<"Hooray, You won!"<<endl<<endl;
return 3;
}
else
{
cout<<"You are incorrect
Sir."<<endl<<endl;
return 0;
}
}
// Check for 3rd12
else if(strcmp(Answer,"3rd12") == 0)
{
if (Wheel > 24)
{
cout<<"You won!"<<endl<<endl;
return 3;
}
else
{
cout<<"Sorry, you are incorrect
Sir."<<endl<<endl;
return 0;
}
}
//Check for 1stHalf
else if(strcmp(Answer,"1stHalf") == 0)
{
if (Wheel < 19)
{
cout<<"You won!"<<endl<<endl;
return 3;
}
else
{
cout<<"Sorry, you are incorrect
Sir."<<endl<<endl;
return 0;
}
}
//Check for 2ndHalf
else if(strcmp(Answer,"2ndHalf") == 0)
{
if (Wheel > 18)
{
cout<<"You won!"<<endl<<endl;
return 2;
}
else
{
cout<<"Sorry, you are incorrect
Sir."<<endl<<endl;
return 0;
}
}
// Check for columns
else if(strcmp(Answer,"3rdColumn") == 0)
{
if (Wheel % 3 == 0)
{
cout<<"You have won!"<<endl<<endl;
return 3;
}
else
{
cout<<"Sorry, you are not correct
Sir."<<endl<<endl;
return 0;
}
}
else if(strcmp(Answer,"1stColumn") == 0)
{
if (Wheel % 3 == 1)
{
cout<<"You have won,
Yippee!"<<endl<<endl;
return 3;
}
else
{
cout<<"Sorry, you have lost
Sir."<<endl<<endl;
return 0;
}
}
else if(strcmp(Answer,"2ndColumn") == 0)
{
if (Wheel % 3 == 2)
{
cout<<"You have won,
Hooray!"<<endl<<endl;
return 3;
}
else
{
cout<<"Sorry, you have lost
Sir."<<endl<<endl;
return 0;
}
}
}
//
If we get this far the input was rejected.
cout<<"The
dealer is drunk so we can't tell if you won, but you"
<<" get your money back! "
<<endl<<"Please correct your
input."<<endl
<<"This game is case sensitive and does not accept
spaces!"<<endl;
return
1; // Let them have their money back!
}
Roulette - I think that we have done enough for this chapter. In the next chapter you'll learn how to access files to make a hangman game.