CS161 Topic #15 1 Today in CS161 Lecture #15 Practicing! Writing Programs to Practice Write a game program (1 player) of Mad Math Reuse the functions to.

Slides:



Advertisements
Similar presentations
Pointers Typedef Pointer Arithmetic Pointers and Arrays.
Advertisements

Overview Reference parameters Documenting functions A game of craps. Design, code, test and document.
CS161 Topic #11 1 Today in CS161 Lecture #11 More Functions Write Programs using Functions Black Jack (add the dealer and make corrections) Arguments Now.
True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Functions. Given a number n, the factorial of n, written n!, is computed as follows: note: 0! = 1 examples: n! = n x (n-1) x (n-2)
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 CS 105 Lecture 3 Constants & Expressions Wed, Jan 26, 2011, 4:15 pm.
Computer Science 1620 Programming & Problem Solving.
What is the out put #include using namespace std; void main() { int i; for(i=1;i
Introduction To C++ Programming 1.0 Basic C++ Program Structure 2.0 Program Control 3.0 Array And Structures 4.0 Function 5.0 Pointer 6.0 Secure Programming.
CS161 Topic #14 1 Today in CS161 Lecture #14 Practicing! Writing Programs to Practice Write a program that counts the number of vowels in a sentence, ended.
Today in CS161 Lecture #4 Solving Problems with Computers Walk through the Tic Tac Toe Algorithm Getting ready for Creating Programs Turn the Inches to.
1 Copyright (C) 2008 by Dennis A. Fairclough all rights reserved.
HANGMAN Created By: Will Matthau & Christian Stumpf.
Lecture 2 Arrays, Pointers, and Structures. Objective In this chapter, we will discuss several concepts: Arrays (first-class arrays, using vector) Strings.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
Introduction to C++ Functions Topic #2 1CS162 Topic #2.
Today in CS161 Lecture #9**go to Blackboard ** Practicing… Review from Shackelford Reading If statements Loops Begin writing Programs Using if statements.
Palindromes revisited Here's a simpler program for checking palindromes: int nums[100]; int i = 0, a; cin >> a; while(a > 0) { nums[i++] = a; cin >> a;
Semester Review. As we have discussed, Friday we will have in class time for you to work on a program, this program will come with instructions and you.
1 INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING.
CS161 Week #8 1 Today in CS161 Week #8 Practicing! Writing Programs to Practice Write a program that counts the number of vowels in a sentence, ended by.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 CS161 Introduction to Computer Science Topic #3.
1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
1 CS161 Introduction to Computer Science Topic #10.
# ACS 168 Structured Programming Using the Computer Chapter 2 Spring 2002 Prepared by Shirley White.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
CSC 107 – Programming For Science. The Week’s Goal.
GAME102 - INTRO WHILE LOOPS G. MacKay. Fundamental Control Structures  STRAIGHT LINE  CONDITIONAL  LOOPS.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
1 CS161 Introduction to Computer Science Topic #9.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Lecture 7: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Objective: Students will be able to: Declare and use variables Input integers.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
1 CS161 Introduction to Computer Science Topic #8.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
1 CS161 Introduction to Computer Science Topic #16.
CS1201: PROGRAMMING LANGUAGE 2 FUNCTIONS. OVERVIEW What is a Function? Function Prototype Vs Decleration Highlight Some Errors in Function Code Parameters.
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Today in CS161 Lecture #5 Learn about… Data types (char, int, float) Input and Output (cin, cout) Writing our First Program Write the Inches to MM Program.
CS Class 15 Today  More practice with arrays  Introduction to Multi-dimensional arrays Announcements  Programming project #4 due 10/23 by midnight.
Fundamental Programming Fundamental Programming More Expressions and Data Types.
12/14/2016CS150 Introduction to Computer Science 1 Announcements  Website is up!   All lecture slides, assignments,
1 CS161 Introduction to Computer Science Topic #15.
Variables  A piece of memory set aside to store data  When declared, the memory is given a name  by using the name, we can access the data that sits.
Fundamental Programming Fundamental Programming Introduction to Functions.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
CS161 Topic #10 1 Today in CS161 Lecture #10 Introduction to Functions What is a function? Why would you want to use a function? How do you define functions?
Bill Tucker Austin Community College COSC 1315
User-Written Functions
Introduction to C++ October 2, 2017.
Multi-dimensional Array
Introduction to C++ Programming
Today in CS161 Week #3 Learn about… Writing our First Program
Value returning Functions
Programs written in C and C++ can run on many different computers
Today in CS161 Week #6 Introduction to Functions
Programming Fundamental
Presentation transcript:

CS161 Topic #15 1 Today in CS161 Lecture #15 Practicing! Writing Programs to Practice Write a game program (1 player) of Mad Math Reuse the functions to provide for multiple players Rewrite the same program using “structures” to group together related topics Greatly simplifying the ability to have multiple players!

CS161 Topic #15 2 Mad Math – One Player A game that displays an equation and the player must come up with the correct answer. As their score increases, so does their level First, write the algorithm: Describe the rules Get the users name and capitalize each word Play the game Display an equation Get the answer Check to see if the answer is correct Increase/decrease the points Display the points Continue until the user is done

CS161 Topic #15 3 Welcome…and Explain the Rules //describe this game to the user void welcome() { cout <<"Welcome to the Mad about Math program\n\n"; cout <<"The goal is to get as many equations correct\n"; cout <<"You get 1 point for each correct answer and -2 for each wrong!" <<endl <<endl; cout <<endl <<endl <<"Let's begin " <<endl <<endl; srand(time(0)); }

CS161 Topic #15 4 Get the Name of the Player void get_name(char name[]) { cout <<"What is your name? "; cin.get(name,MAX); cin.ignore(100,'\n'); capitalize(name); //make sure each word is capitalized }

CS161 Topic #15 5 Capitalize each word of the name //Capitalize the first letter of each word in the name void capitalize(char name[]) { int length = strlen(name); name[0] = toupper(name[0]); //capitalize the first character of the name //Find the blanks in a name for (int i=0; i< length; ++i) if (name[i] == ' ') //the next character needs to be capitalized name[i+1] = toupper(name[i+1]); }

CS161 Topic #15 6 Show an equation //Play the game! The argument indicates the complexity of the numbers int equate(int max) { int first; //first number int second; //second number int operation; //type of operation int answer ; //answer supplied by user int correct; //correct answer first = rand() % max; second = rand() % max; operation = rand() % 4;

CS161 Topic #15 7 Show an equation if (operation == 0) //additiom { cout <<"SOLVE: " <<first <<" + " <<second <<" Equals: "; correct = first + second; } else if (operation == 1) //subtraction { cout <<"SOLVE: " <<first <<" - " <<second <<" Equals: "; correct = first - second; } else if (operation == 2) //multiplication { cout <<"SOLVE: " <<first <<" x " <<second <<" Equals: "; correct = first * second; } else //division { cout <<"SOLVE: " <<first <<" / " <<second <<" Equals: "; correct = first / second; } cin >>answer; if (answer == correct) return 1; return -2; }

CS161 Topic #15 8 Show an equation…continued cin >>answer; if (answer == correct) return 1;//correct answer return -2;//incorrect answer } //Does the user want to play again? bool play_again() { char answer; cout <<"Do you want to play again? "; cin >>answer; cin.get(); return (answer == 'y' || answer == 'Y'); }

CS161 Topic #15 9 Main… int main() { int level = 10; //simplest level char player[MAX]; int points = 0; //player's points welcome(); get_name(player); do { //show the equation points += equate(level); show_score(player,points); progress(level,points); //should they progress a level? } while (play_again()); ending_message(player, points); cin.get(); return 0; }

CS161 Topic #15 10 Running the program

CS161 Topic #15 11 Mad Math Game…Adding another player If we have written the functions for the single player problem well enough, we can simply reuse them for the next player…let’s see: int play_game(char player[], int & points, int & level) { cout <<player <<"'s turn: "; points += equate(level); show_score(player,points); progress(level,points); //should they progress a level? }

CS161 Topic #15 12 Main…with two players int main() { int player1_level = 10; //simplest level int player2_level = 10; char player1[MAX]; //player1 char player2[MAX]; //player2 int player1_points = 0; int player2_points = 0; welcome(); cout <<"First player: "; get_name(player1); //get the names of the two players cout <<"Next player: "; get_name(player2);

CS161 Topic #15 13 Main…with two players do { //let each player do an equation... play_game(player1, player1_points, player1_level); play_game(player2, player2_points, player2_level); } while (play_again()); if (player1_level == player2_level && player1_points == player2_points) cout <<"GREAT JOB! You are BOTH winners today " <<"with " <<player1_points <<" points" <<endl <<endl; else if (player1_level > player2_level || player1_points > player2_points) cout <<"THE WINNER IS: " <<player1 <<"with " <<player1_points <<" points" <<endl <<endl; else cout <<"THE WINNER IS: " <<player2 <<" with " <<player2_points <<" points" <<endl <<endl;

CS161 Topic #15 14 Running the program

CS161 Topic #15 15 What is a Structure Using structures ( a new concept we will use in CS162), we can simplify this further and easily allow additional players Think about what a player is…a player has a name, a score, and a level A structure is a way for us to group different types of data together under a common name With an array, we are limited to having only a single type of data for each element... We’d need an array of players names Another for the players scores Another for the players levels. Too complicated!

CS161 Topic #15 16 What is a Structure With a structure, on the other hand, we can group each of these under a common heading So, each player can now have a name, score, and level tied to it And, we can then generalize this to allow for an array of players…and add as many as we want!

CS161 Topic #15 17 Why would we use a Structure Some people argue that with C++ we no longer need to use the concept of structures And, yes, you can do everything that we will be doing with structures, with a “class” (which we learn about next term!) My suggestion is to use structures whenever you want to group different types of data together, to help organize your data

CS161 Topic #15 18 How do you define a Structure? We typically define structures “globally” this means they are placed outside of the main We do this because structures are like a “specification” or a new “data type” which means that we would want all of our functions to have access to this way to group data, and not just limit it to some function by defining it to be local

CS161 Topic #15 19 How do you define a Structure? Each component of a structure is called a member and is referenced by a member name (identifier). Structures differ from arrays in that members of a structure do not have to be of the same type. And, structure members are not referenced using an index.

CS161 Topic #15 20 How do you define members of a Structure? A structure might look like: struct storeitem { char item[20]; float cost; float price; int barcode; }; In this example, item, price, cost and barcode are member names. storeitem is the name of a new derived data type consisting of a character array, two real numbers, and an integer.

CS161 Topic #15 21 How do you define members of a Structure? A structure might look like: struct player //a player is: name, a score, and a level { char name[MAX]; int points; int level; }; //<---- notice the semicolon!

CS161 Topic #15 22 How do you define instances of a Structure? Once your have declared this new derived data type, you can create instances -- variables (or “objects”) which are of this type (just like we are used to): player player1; Or, create an array: player all_players[100];

CS161 Topic #15 23 How do you define instances of a Structure? By saying: player player1; From this statement, player1 is the variable (or object) It has a name, score (#points) and level. Just think of player as being a type of data which consists of an array of characters, two integers in this case.

CS161 Topic #15 24 How do you access members of a Structure? By saying: player player1; To access a member of a structure variable, we use a dot (the “direct member access” operator) after the structure variable’s identifier: player1.nameis the array of characters player1.pointsis the integer player1.levelis the level

CS161 Topic #15 25 How do you access members of a Structure? We can work with these members in just the same way that we work with variables of a fundamental type: To read in a name, we can say: cin >>player1.name Or, cin.get(player1.name, 21); To display the score, we say: cout <<player1.points

CS161 Topic #15 26 What operations can be performed? Just like with arrays, there are very few operations that can be performed on a complete structure We can’t read in an entire structure at one time, or write an entire structure, or use any of the arithmetic operations... We can use assignment, to do a “memberwise copy” copying each member from one struct variable to another

CS161 Topic #15 27 How do you define arrays of Structures? But, for structures to be meaningful when representing a deck cards, a store inventory, or a number of players for a game. we may want to use an array of structures where every element represents a different player in the game…

CS161 Topic #15 28 How do you pass Structures to functions? To pass a structure to a function, we must decide whether we want pass by reference or pass by value By reference, we can pass 1 player: return_type function(player & arg); //or an array of players: return_type function(player arg[]);

CS161 Topic #15 29 Mad Math Game…2 players… #include using namespace std; //This program simulates a "mad about math" game //written by Karla Fant for CS161 demonstrations const int MAX = 21; const int NUM = 2; struct player //a player has a name, a score, and a level { char name[MAX]; int points; int level; }; //<---- notice the semicolon! void welcome(char name[]); //displaky the rules void capitalize (char name[]); //capitalize each word in a name

CS161 Topic #15 30 This is the same as before…. void welcome(char name[]); //displaky the rules void capitalize (char name[]); //capitalize each word in a name //capitalize the first character of each word in a name void capitalize(char name[]) { int length = strlen(name); name[0] = toupper(name[0]); //capitalize the first character of the name //Find the blanks in a name for (int i=0; i< length; ++i) if (name[i] == ' ') //the next character needs to be capitalized name[i+1] = toupper(name[i+1]); }

CS161 Topic #15 31 This is the same as before…. void get_name(char name[]) { cout <<"What is your name? "; cin.get(name,MAX); cin.ignore(100,'\n'); capitalize(name); //make sure each word is capitalized } //describe this game to the user void welcome() { cout <<"Welcome to the Mad about Math program\n\n"; cout <<"The goal is to get as many equations correct\n"; cout <<"You get 1 point for each correct answer and -2 for each wrong!" <<endl <<endl; cout <<endl <<endl <<"Let's begin " <<endl <<endl; srand(time(0)); }

CS161 Topic #15 32 New Stuff…using the struct! int play_game(player & a_player) { //Tell which player’s turn it is… cout <<a_player.name <<"'s turn: "; //Give the player an equation to calculate a_player.points += equate(a_player.level); //Show their score show_score(a_player.name,a_player.points); //should they progress a level? progress(a_player.level,a_player.points); }

CS161 Topic #15 33 Main…now using the structure! int main() { player players[NUM]; //we have two players welcome(); //initialize the level and points for (int i = 0; i < NUM; ++i) { players[i].level = 10; players[i].points = 0; cout <<"For player # " <<i+1 <<": "; get_name(players[i].name); }

CS161 Topic #15 34 Main…now using the structure! //Time to play the game! do { for (int i = 0; i < NUM; ++i) //let each player do an equation... play_game(players[i]); } while (play_again()); winning_message(players); cin.get(); return 0; }

CS161 Topic #15 35 Display the winning message… void winning_message(player all[]) { int highest_score = -99; int highest_index = -99; bool found_tie = false; //Find the higihest score for (int i = 0; i < NUM; ++i) { //find the player with the highest score if (all[i].points > highest_score) { highest_score = all[i].points; highest_index = i; }

CS161 Topic #15 36 Display the winning message… //Now see if there is a tie for (int i = 0; i < NUM; ++i) { //find the player with the highest score if (all[i].points == highest_score && i != highest_index) { found_tie = true; cout <<"GREAT JOB! We have a tie today! " <<all[i].name <<" and " <<all[highest_index].name << " have " <<highest_score <<" points" <<endl <<endl; } if (!found_tie) //there was not a tie { cout <<"THE WINNER IS: " <<all[highest_index].name <<"with " <<highest_score <<" points" <<endl <<endl; }

CS161 Topic #15 37 Running the program

CS161 Topic #15 38 Mad Math Game…Many Players! With structures and arrays of structures we can make a slight jump with minimal code modifications to allow for many players! #include using namespace std; //This program simulates a "mad about math" game //written by Karla Fant for CS161 demonstrations const int MAX = 21; const int NUM = 5;***THE ONLY CHANGE ***

CS161 Topic #15 39 Running the program