520 likes | 538 Views
Chapter 3 Variables, Calculations, and Colors. Starting Out with Games & Graphics in C++ Tony Gaddis. 3.1 Introduction. Programs almost always work with data of some type. For example, we have seen programs that use: XY coordinate data to draw shapes on the screen
E N D
Chapter 3Variables, Calculations, and Colors Starting Out with Games & Graphics in C++ Tony Gaddis
3.1 Introduction • Programs almost always work with data of some type. • For example, we have seen programs that use: • XY coordinate data to draw shapes on the screen • Strings of characters to display text on the screen • In this chapter, we will: • Take a closer look at how numerical data can be used in a program • Discuss how a program can: • Store data in memory • Perform calculations • Retrieve data from functions in the Dark GDK library • Go beyond the simple world of black and white and discuss how to draw in color
3.2 Literal Data Concept: A literal is an item of data that is typed into a program’s code.
3.2 Literal Data • Literal Data • Simplest form of data • Typed into the program’s code • Used to represent known values • Numeric Literals • For example: • dbCircle(319, 239, 150); • String Literals • For example: • dbPrint(“Hello World!”);
3.3 Variables Concept: A variable is a storage location in memory that is represented by a name.
3.3 Variables • Variable • Storage location in memory • Represented by a name • For example: • Variable named score used to hold a player’s score in memory • In C++, variable must be declared with • Data type • name
3.3 Variables • Data Types • int • Whole numbers • For example, 6, -56, 9, and 45 • float • Floating-point numbers • For example, 8.9, 96.948, and 3.0 • double • Twice the precision of float • DWORD • Unsigned, 32 bits, used for Dark GDK colors
3.3 Variables • Variable Names • Must be • One word • No spaces • First character must be • Letter a – z, A – Z, or underscore (_) • After first character • Letters a – z, A – Z, numbers 0 – 9, or underscore(_) • Uppercase and lowercase characters are distinct • LineLength is not the same as linelength
3.3 Variables • Declaring a Variable • Specify data type and name • For example: • intcenterX; • float distance; • Assigning Values • For example: • centerX = 319; • distance = 159.9; • 319 = centerX; // ERROR! • Initializing • For example • intcenterX = 319; • intcenterX = 319, centerY = 239, radius = 150;
3.3 Variables • Uninitialized Variables • A variable that has been declared but not assigned a value • If the variable is used without initializing first, unpredictable results occur, because “garbage” is stored in this variable (whatever was previously stored in that memory location)
3.3 Variables • Floating-Point Truncation • If you store a floating-point variable into an integer variable, the decimal places will be dropped • For example: • int size; • size = 12.2; • However, it is safe to store an integer into a floating-point or double variable • For example: • float grade; • grade = 90;
3.4 Calculations Concept: You can use math operators to perform simple calculations. Math expressions can be written using math operators and parentheses as grouping symbols. The result of a math expression can be assigned to a variable.
3.4 Calculations • Math Operators • Addition • Adds two numbers • (+) • Subtraction • Subtracts one number from another • (-) • Multiplication • Multiplies one number by another • (*) • Division • Divides one number by another and give the quotient • (/) • Modulus • Divides on integer by another and gives the remainder • (%)
3.4 Calculations • Order of Operations • Parentheses (always first) • From left to right • Multiplications, divisions, or modulus operations(1st) • Additions or subtractions(2nd)
3.4 Calculations Integer Division • When you divide an integer by an integer in C++ • The result is always given as an integer • If the result has a fractional part, it will be truncated
3.4 Calculations Integer Division • The last statement divides the value of length by 2 and assigns the result to half • The result of the division will be truncated, giving the value 37
3.4 Calculations Combined Assignment Operators • Do not require the programmer to type the variable name twice • Give a clear indication of what is happing in the statement
3.5 Getting Values from Functions Concept: A value-returning function returns a value back to the statement that called it.
3.5 Getting Values from Functions Figure 3-15 The dbScreenWidth function returns a value • Value-returning functions • Performs some operation • Returns a value • Can be: • Assigned to a variable • Used in mathematical expressions
3.5 Getting Values from Functions Getting a Random Number • The Dark GDK library provides a function named dbRND that generates random numbers • Random numbers are • Commonly used in games • For example • To represent the values of dice • To represent the face values of cards • Useful in simulation programs to determine various actions and events that take place in the program • Useful in statistical programs that must randomly select data for analysis • Commonly used in computer security to encrypt sensitive data
3.5 Getting Values from Functions Getting a Random Number • int number = dbRND(100); • The dbRND function • Returns a random integer number • From 0 to an upper limit that you specify as an argument • For example, the following statement stores a random number from 0 to 100 in the integer variable number
3.5 Getting Values from Functions Seeding the Random Number Generator Numbers returned from the dbRND function are not truly random, but pseudorandom numbers Pseudorandom numbers are generated by a formula that must be initialized with a starting value, called a seed value The same seed value will always produce the same sequence of random numbers
3.5 Getting Values from Functions Seeding the Random Number Generator Providing a different seed value will change the sequence of random numbers You can call the dbRandomize function to change the seed value that is used by the dbRND function The dbRandomize function accepts an integer argument which is used as the new seed value for dbRND
3.5 Getting Values from Functions Seeding the Random Number Generator • A common practice for getting unique seed values is to call the dbTimer function • The dbTimer function returns the computer’s internal system time in milliseconds • You can pass the value of the dbTimer function as an argument to the dbRandomize function
3.5 Getting Values from Functions Nesting Function Calls • This code performs two steps • (1) it gets the internal system time • (2) it sends that value to the dbRandomize function • A seasoned programmer would look at this code and realize it could all be done in one step • Take a look at the following code:
3.5 Getting Values from Functions Nesting Function Calls • This is known as a nested function call • The statement above • Calls the dbRandomize function • Passes the return value of the dbTimer function as an argument • Eliminates the seed variable • Accomplishes in one line what previously took two lines • Take a look at the following code:
3.5 Getting Values from Functions Math Functions C++ and the Dark GDK provide numerous functions for performing mathematical operations For example, C++ provides a function named pow that raises a number to a power
3.5 Getting Values from Functions Math Functions pow(Base, Exponent); • When this function executes • It returns the value of Base raised to the power of Exponent Here is the pow function’s general format:
3.5 Getting Values from Functions Math Functions • The function returns the value of base raised to the power of exponent • The value that is returned from the function is stored in the result variable Here is an example of how the pow function works:
3.5 Getting Values from Functions Math Functions
3.6 Reading Numeric Input from the Keyboard Concept: Programs commonly need the user to enter data at the keyboard. We will use the Dark GDK library’s dbInput function to do this.
3.6 Reading Numeric Input from the Keyboard • The Dark GDK library provides a function named dbInput that: • Waits for the user to type something on the keyboard and press the Enter key • Returns the data that the user types as a string • We can convert the string returned by the dbInput function • to an intwith the atoi function • to a doublewith the atof function
3.6 Reading Numeric Input from the Keyboard • Example of converting user input to a floating-point number: Example of converting user input to an integer:
3.6 Reading Numeric Input from the Keyboard • A complete program that gets data from the user and uses that data to draw a circle:
3.6 Reading Numeric Input from the Keyboard Figure 3-19 Example output of Program 3-12
3.6 Reading Numeric Input from the Keyboard How atoi and atof Handle Invalid Characters • The atoi and atof functions • Ignore any spaces that might appear at the beginning of the string • Perform the conversion process until an invalid character is encountered • Return 0, if the string • Is empty • Cannot be converted to a number
3.6 Reading Numeric Input from the Keyboard Converting Numeric Values to Strings • Numeric values need to be converted to strings before they can be displayed with • dbPrint • dbText • dbCenterText • The dbStr function can be used to convert numeric values to strings • For example: • int score = 550; • dbPrint( dbStr(score) );
3.7 Colors Concept: The Dark GDK uses the RGB color system to generate colors. In the RGB system, you define a color by specifying values for its red, green, and blue components.
3.7 Colors Figure 3-21 Red, green, and blue channels Figure 3-22 Memory format for storing an RGB color • RGB Color System • 3 color channels: • Red • Green • Blue • value from 0 to 255 • 0 is minimum brightness • 255 is maximum brightness • Stored as DWORD
3.7 Colors dbClear(red, green, blue); • For example • dbClear(255, 0, 127); • Clears the screen to purple • dbClear(255, 0, 0); • Clears the screen to red • dbClear(255, 255, 255); • Clears the screen to white The dbClear function clears the Dark GDK window and fills it with a specified color Here is the general format of how you call the dbClear function:
3.7 Colors Storing RGB Colors in Memory dbRGB(red, green, blue); The DWORD data type is typically used to store RGB colors The Dark GDK library provides a function named dbRGB that returns the DWORD value of an RGB color. Here is the general format of how you call the dbRGB function:
3.7 Colors Storing RGB Colors in Memory • The dbRGB function can be used to store an RGB color value in a DWORD variable • For example, the following code sample shows how to use the dbRGB function to store an RGB color in a DWORD variable:
3.7 Colors Drawing in Color dbInk(foreground, background); The Dark GDK library provides a function named dbInk, which changes the current drawing colors Here is the general format of how you call the dbInk function:
3.7 Colors Drawing in Color • The foreground argument is a DWORD value specifying the foreground color • All subsequent shapes and text will be drawn in the foreground color • The background argument is a DWORD value specifying the background color • Only applies to text • after calling the dbSetTextOpaque function • Has no effect on shapes • For drawing shapes, you can pass any color you like for the background
3.7 Colors Drawing in Color The following code segment shows how to draw a blue circle:
3.7 Colors More About Clearing the Window • The Dark GDK library provides two functions for clearing the window • dbClear • Clears the window to a specific background color • Accepts arguments for the background color’s red, green, and blue components • dbCLS • Clears the window to black if called without an argument • Clears the window to a specific color when you pass a DWORD argument
3.7 Colors More About Clearing the Window • The dbCLS function can be called with a DWORD argument to clear the screen to a specific color, as shown here: The dbCLS function can be called without arguments to clear the screen to black, as shown here:
3.8 Named Constants Concept: A named constant represents a value that cannot change while the program is running. You can use the C++ key word const in a variable declaration to create a named constant.
3.8 Named Constants • Named Constant • Value cannot change • While program is running • Declare with keyword const • For example: • const DWORD myBlue = dbRGB(0, 0, 75); • const int UPPER_LEFT; // ERROR! • const int UPPER_LEFT = 0; // Must initialize
3.9 Changing the Size of the Program Window Concept: You can use the dbSetDisplayMode function to set the size of the program’s window.