Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Similar documents
C Functions. 5.2 Program Modules in C

Functions and Recursion

EAS230: Programming for Engineers Lab 1 Fall 2004

Chapter 3 - Functions

Function Call Stack and Activation Records

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

6.5 Function Prototypes and Argument Coercion

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Fundamentals of Programming Session 25

Chapter 3 - Functions

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

CSE123. Program Design and Modular Programming Functions 1-1

Chapter Four: Loops II

C Functions Pearson Education, Inc. All rights reserved.

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

ECET 264 C Programming Language with Applications

CS2141 Software Development using C/C++ C++ Basics

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Lab Instructor : Jean Lai

Lecture 04 FUNCTIONS AND ARRAYS

Programming Language. Functions. Eng. Anis Nazer First Semester

12/22/11. } Rolling a Six-Sided Die. } Fig 6.7: Rolling a Six-Sided Die 6,000,000 Times

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

Chapter 3 - Functions

Why Is Repetition Needed?

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

C++ How to Program, 9/e by Pearson Education, Inc. All Rights Reserved.

Programming Assignment #4 Arrays and Pointers

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

Sol. Sol. a. void remove_items_less_than(int arr[], int size, int value) #include <iostream> #include <ctime> using namespace std;

Programming for Engineers Functions

pointers + memory double x; string a; int x; main overhead int y; main overhead

Last Time: Rolling a Weighted Die

The cin Object. cout << "Enter the length and the width of the rectangle? "; cin >> length >> width;

Introduction to C++ Systems Programming

Elements of C in C++ data types if else statement for loops. random numbers rolling a die

Topic 2: C++ Programming fundamentals

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Programming. C++ Basics

(created by professor Marina Tanasyuk) FUNCTIONS

Chapter 3 Function Basics

C++ For C Programmers Week 1 Part 1

Partha Sarathi Mandal

CSci 1113 Lab Exercise 5 (Week 6): Reference Parameters and Basic File I/O

CS 103 Lecture 3 Slides

CSC 126 FINAL EXAMINATION Spring Total Possible TOTAL 100

CS 150 Lab 10 Functions and Random Numbers

Designing Loops and General Debug Pre-Defined Functions in C++ CS 16: Solving Problems with Computers I Lecture #6

Due Date: See Blackboard

Chapter Procedural Abstraction and Functions That Return a Value. Overview. Top-Down Design. Benefits of Top Down Design.

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Chapter 4. Procedural Abstraction and Functions That Return a Value

C++ basics Getting started with, and Data Types.

IT 374 C# and Applications/ IT695 C# Data Structures

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Methods: A Deeper Look Pearson Education, Inc. All rights reserved.

LAB: WHILE LOOPS IN C++

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Due Date: See Blackboard

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Chapter 10 - Notes Applications of Arrays

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

BITG 1233: Introduction to C++

Introduction to C ++

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 15 - C++ As A "Better C"

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Sample Final Exam. 1) (24 points) Show what is printed by the following segments of code (assume all appropriate header files, etc.

Creating a C++ Program

Classwork 7: Craps. N. Duong & R. Rodriguez, Java Crash Course January 6, 2015

A SHORT COURSE ON C++

Chapter 4. Procedural Abstraction and Functions That Return a Value. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Object oriented programming

Methods: A Deeper Look

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Programming Fundamentals. With C++ Variable Declaration, Evaluation and Assignment 1

Part of the Picture: Simulation

2. Functions I: Passing by Value

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

Input and Expressions Chapter 3 Slides #4

Lab # 02. Basic Elements of C++ _ Part1

CME 112- Programming Languages II. Week 1 Introduction, Scope Rules and Generating Random Numbers

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

ProgrammingAssignment #5: Let s Play Craps!

Name Section: M/W or T/TH. True or False (14 Points)

JAVASCRIPT LESSON 4: FUNCTIONS

In this chapter you will learn:

Transcription:

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Outline 12.1 Test-Driving the Craps Game Application 12.2 Random Number Generation 12.3 Using an enum in the Craps Game Application 12.4 Using Random Numbers in the Craps Game Application 12.5 Wrap-Up

Objectives In this tutorial, you will learn to: Use simulation techniques that employ random-number generation. Use the rand math library function to generate random numbers. Use enumerations to enhance code readability.

12.1 Test Driving the Craps Game Application

12.1 Test Driving the Craps Game Application (Cont.) Figure 12.1 Example of an initial appearance of Craps Game application. Figure 12.2 Player winning on the first roll by rolling an 11.

12.1 Test Driving the Craps Game Application (Cont.) Figure 12.3 Player losing on the first roll by rolling a 3. Figure 12.6 Player losing by rolling a 7 before matching the point value.

12.1 Test Driving the Craps Game Application (Cont.) Figure 12.5 Player winning the game by matching the point value before rolling a 7. Figure 12.6 Player losing by rolling a 7 before matching the point value.

<cstdlib> c standard utility library header file cstdlib is part of the C++ Standard Library. The C++ Standard Library includes 18 header files from the C Standard Library. The cstdlib include/header file contains the function declarations for commonly used library functions which either don't fit somewhere else, or, cannot be declared in the normal place for other reasons. cstdlib includes several general purpose functions, including dynamic memory management, random number generation, communication with the environment, integer arithmetic, searching, sorting and converting. Function prototypes declared in cstdlib are defined within the std namespace.

<cstdlib> c standard utility library header file (Cont.) Each C++ header file has the same name as the C language version but with a "c" prefix and no extension. In this case, the C++ equivalent for the C language header file <stdlib.h> is <cstdlib>. If you look inside the cstlib file you will find the following preprocessor directive. #include <stdlib.h>

<cstdlib> c standard utility library header file (Cont.) Figure 12.9 Including the <cstdlib> and <ctime> standard library header files so that the application can produce random numbers. Including the <ctime> standard library header file Including the <cstdlib> standard library header file

Random Number Generation rand function : Generates a pseudorandom number between 0 and RAND_MAX RAND_MAX is defined in stdlib.h as /* Maximum value that can be returned by the rand function. */ #define RAND_MAX 0x7fff #define directive substitutes token-string for all subsequent occurrences of an identifier in the source file. 0x7fff = 32,767 10

Random Number Generation Seed the rand function with srand The value used to seed rand determines the sequence of pseudorandom numbers it generates Use srand(time(0)) to make rand generate a different sequence of pseudorandom numbers each time the application runs time returns the current calendar time in seconds since 1/1/1970 00:00:00. The function prototype for time is in the <ctime> C++ Standard Library header file Figure 12.15 Using the time and srand functions to seed the rand function. Seeding the rand function

Random Number Generation (Cont.) Exp ression Resulting ra nge rand() 0 to RAND_MAX [0 to at least 32,767] rand() % 30 0 to 29 10 + rand() % 10 10 to 19 Figure 12.7 rand func tion c a ll exp ressions with ranges of rand om numb ers p roduc ed. Using the modulus operator to generate random numbers within a certain range

Random Number Generation rolldice Example Figure 12.10 Declaring the rolldice function prototype. Declaring the rolldice function prototype rolldice function simulates rolling two dice Returns the value of the sum of the two dice

Random Number Generation rolldice Example Figure 12.22 Defining the rolldice function. Defining local variables to store die values Getting two random numbers and storing their sum

Using the rolldice function Random Number Generation rolldice Example rolls two dice, displays their values and returns their sum Figure 12.16 Rolling the dice. Rolling the dice

Using an enum in the Craps Game Application In C and C++, enum types can be used to set up collections of user-defined (or programmer-defined) named integer constants. (The keyword enum is short for ''enumerated''.) Figure 12.13 Using the enum keyword to declare an enumeration. Declaring an enumeration In this example, user-defined type Status can only be one of three values CONTINUE, WON or LOST

Using an enum in the Craps Game Application (Cont.) Enumeration constants start at 0, unless specified otherwise, and increment by 1 enum FooSize {SMALL=10, MEDIUM=100, LARGE=1000}; Attempting to assign another value to an enumeration constant after it has been defined is an error.

Using an enum in the Craps Game Application (Cont.) Figure 12.14 Defining a variable to store values declared in the Status enumeration. Defining a variable of type Status

Using an enum in the Craps Game Application (Cont.) Assigning an enumeration constant to a variable of the enumeration type. Figure 12.18 default case in main. User must match the point Displaying the point A common syntax error is to assign the integer equivalent of an enumeration constant to a variable of the enumeration type.

Using an enum in the Craps Game Application (Cont.) Figure 12.8 Pseudocode for the Craps Game application. Roll the two dice using random numbers Calculate and display the sum of the two dice Switch based on the sum of the two dice: Case where the sum is 7 or 11 Display the winning message Case where the sum is 2, 3 or 12 Display the losing message Default case Set the value of the point to the sum of the dice and display the value While the player has not won or lost Roll the two dice using random numbers Calculate and display the sum of the two dice If the player rolled the point Display the winning message If the player rolls a 7 Display the losing message

Using an enum in the Craps Game Application (Cont.) Figure 12.11 Defining constants in the Craps Game application. Defining constants

Using an enum in the Craps Game Application (Cont.) Figure 12.17 switch statement in main. Winning on the first roll Losing on the first roll

1 // Tutorial 12: CrapsGame.cpp 2 // This application plays a simple craps game. 3 #include <iostream> // required to perform C++ stream I/O 4 #include <string> // required to access string functions 5 #include <ctime> // contains prototype for function time 6 7 // contains function prototypes for srand and rand 8 #include <cstdlib> 9 10 using namespace std; // for accessing C++ Standard Library members 11 12 int rolldice( void ); // function prototype 13 Include the <ctime> standard library header file CrapsGame.cpp (1 of 6) Include the <sdtdlib> standard library header file Declare the rolldice function prototype

14 // function main begins program execution 15 int main() 16 { 17 // constants representing winning dice rolls 18 const int LUCKY_SEVEN = 7; 19 const int YO_LEVEN = 11; 20 21 // constants representing losing dice rolls 22 const int SNAKE_EYES = 2; 23 const int TREY = 3; 24 const int BOX_CARS = 12; 25 const int CRAPS = 7; // loses only after first roll 26 27 // enumeration constants represent game status 28 enum Status { CONTINUE, WON, LOST }; 29 30 int sum; // stores sum of the dice 31 int mypoint; // stores the player's point 32 string input; // stores input after each dice roll 33 34 Status gamestatus; // can contain CONTINUE, WON or LOST 35 CrapsGame.cpp (2 of 6) Define constants Declare an enumeration Define a variable of the Status type

36 // randomize random number generator using current time 37 srand( time( 0 ) ); 38 39 sum = rolldice(); // first roll of the dice 40 41 // determine game status and point based on sum of dice 42 switch ( sum ) 43 { 44 // win on first roll 45 case LUCKY_SEVEN: 46 case YO_LEVEN: 47 gamestatus = WON; 48 break; 49 50 // lose on first roll 51 case SNAKE_EYES: 52 case TREY: 53 case BOX_CARS: 54 gamestatus = LOST; 55 break; 56 Seed the rand function Win on the first roll Lose on the first roll Roll the dice CrapsGame.cpp (3 of 6)

57 // remember point 58 default: 59 gamestatus = CONTINUE; 60 mypoint = sum; 61 cout << "Point is " << mypoint << endl; 62 break; // optional 63 64 } // end switch 65 66 // repeat while the game is not complete 67 while ( gamestatus == CONTINUE ) 68 { 69 cout << "\npress enter to continue..."; 70 getline( cin, input ); // pauses until user presses Enter 71 72 sum = rolldice(); // roll dice again 73 74 // determine game status 75 if ( sum == mypoint ) // win by matching point 76 { 77 gamestatus = WON; 78 } // end if User must match the point Repeat until user has won or lost Roll the dice again Determine if user won CrapsGame.cpp (4 of 6)

79 else if ( sum == CRAPS ) // lose by rolling 7 80 { 81 gamestatus = LOST; 82 } // end else if 83 84 } // end while 85 86 // display won or lost message 87 if ( gamestatus == WON ) 88 { Determine if user lost 89 cout << "Player wins" << endl << endl; 90 } // end if 91 else 92 { 93 cout << "Player loses" << endl << endl; 94 } // end else if 95 96 return 0; // indicates successful termination 97 98 } // end function main 99 Display game outcome CrapsGame.cpp (5 of 6)

100 // roll dice, calculate sum and display results 101 int rolldice( void ) 102 { 103 int die1; // stores the value of the first die 104 int die2; // stores the value of the second die 105 int dicesum; // stores the sum of the dice values 106 107 die1 = 1 + rand() % 6; // pick random die1 value 108 die2 = 1 + rand() % 6; // pick random die2 value 109 dicesum = die1 + die2; // sum die1 and die2 110 111 // display results of this roll 112 cout << "\nplayer rolled " << die1 << " + " << die2 113 << " = " << dicesum << endl 114 115 return dicesum; // return the sum of dice 116 117 } // end function rolldice CrapsGame.cpp (6 of 6) Generate random numbers and calculate their sum Display the die values and their sum