Lab 3 Functions and Types Pre-requisites Read Chapter Chapter 3 and Chapter 4 Vocabulary Function Scope Global Local return value Array Multidimensional array Type Field Instance Post-lab Questions Write your answers after completing the lab, but read them carefully now and keep them in mind during the lab. 1) Why do some functions have a return statement while others do not? 2) Suppose you have two variables of the same name, one is local scope and the other is global. How does the computer distinguish between the two? 3) Types are very useful for modeling real things in a computer. Suppose you wanted to represent an animal at a zoo. Come up with a type that would represent an animal. The type should contain all the necessary information the zoo needs to keep a particular animal healthy. For example, the food it eats, how often it eats, and its sleep cycle— nocturnal or diurnal, plus whatever else comes to your mind. Then declare two instances, one for a lion, the other for a monkey. 1 Discussion and Procedure A FUNCTION is defined using the 'Function' keyword: Function {funcname}{typetag}( {params} ) {statements} End Function {funcname} is any valid identifier. {typetag} is the type of value returned by the function. If {typetag} is omitted, the function returns an integer value by default. {params} is a comma separated list of variables which is passed to the function when it is called, each parameter may be given an optional type tag. Parameters are always local. A function may use the 'Return' statement to return a result. Return may optionally be followed by an expression. If there is no Return statement, or a Return without any expression is used, the function returns a default value of 0 for numeric functions, an empty string ("") for string functions, or a 'Null' object for custom type functions. Part 1. Built in Functions abstraction: make larger units of code to do things we often need accomplished help>command reference list of various built in functions and what they do labels $, #, % are used to indicate return values, (% or integer is default) Some Functions Input$(prompt$) Print MilliSecs( ) Mouse Functions GetMouse( ) MouseX( ) MouseY( ) Math Functions Sqr#(float) Rnd (start#,end#) SeedRnd seed Get input from the user. prompt$ = any valid string (optional) Print a string to the screen. Return the system's timer value in milliseconds. Checks to see if a mouse button has been clicked - returns the number of the button or 0 if no button is clicked. Returns the mouse's X screen coordinate. Returns the mouse's Y screen coordinate. Returns the square root of a given value. start# = Lowest value to generate end# = Highest value to generate Start the random number generator off at seed (seed usually is Millisecs( ) ) 2 Floor#(float) Abs(number) Rounds a decimal floating variable down to the nearest whole number. float=floating point number Returns the absolute (positive) value of a number. number = any valid number or numeric variable ; GetMouse Example While Not KeyHit(1) button=GetMouse() If button <> 0 Then Print "You pressed mouse button #" + button End If Wend Notes A) Experiment with mouseX and mouseY to display mouse coordinates B) Modify to display "GOT ME!" if the mouse X value is the larger than 300 C) Modify to display "Ticklish!" if the mouse X value is the less than 30 AND the mouse Y value is <30 D) modify to display a random number between 50 and 75 whenever the mouse is clicked E) add the SeedRnd command to properly seed the random number generator (before looping) Part 2. User Defined Functions that return a value ;demo03-06.bb - Converts Fahrenheit to Celsius ;MAIN PROGRAM Print "Welcome to our FtoC converter" ;get fahrenheit and put it in fvalue fvalue = Input$("What Fahrenheit value do you wish to convert?") ;Convert fvalue to Celcius cvalue = ConvertFtoC(fvalue) ;print results Print fvalue + " Fahrenheit = " + cvalue + " Celsius." ;Wait for user to press a key WaitKey ;END OF MAIN PROGRAM Function ConvertFtoC(fvalue) ;convert value and return it Return 5.0/9.0 * (fvalue - 32) End Function 3 Notes A) change parameter fvalue to f B) make a C to F converter using the formula F = 9/5 C + 32 C) make a distance function: takes 2 points (x1,y1,x2,y2) and uses the formula d = square root of ( (x2-x1)2 + (y2-y1)2 ) Test: distance(100, 150, 103, 154) should give answer 5 D) make a collision detection function: takes 2 points (x1,y1,x2,y2) , returns 1 (true) if distance is smaller than 10 pixels (use distance function from B), returns 0 otherwise Test: collision (100, 150, 103, 154) should give answer 1 Test: collision (10, 15, 103, 154) should give answer 0 Part 3. User Defined Functions that don't return a value ;demo03-07.bb - CallMe() Global x ;call CallMe() function CallMe() ;concatenate "x is equal to" and the variable x Print "x is equal to " + x WaitKey ;FUNCTION CALLME() ;sets x to 314 Function CallMe() x = 314 End Function Notes A) change "Global x" to "Global x=5" and see what happens. Then just "x=5" – Global vs local variables ;demo StarWars0 Const TIE$="<-o->" Const XWING$=">o<" ;call Text function Text 100, 200, TIE$ Text 200, 150, XWING$ WaitKey Notes A) draw another TIE fighter at 190, 155 B) keeping track of x, y and hitpoints for each ship can be tedious. Solution: 4 Part 4. Types ;StarWars1 using TYPES Ship is now a multi-field variable Type Ship Field x,y ;the position of the ship Field hitpoints ;how many hits left Field shipstring$ ;what the ship looks like End Type Const TIE$="<-o->" Const XWING$=">o<" Global player.ship = New ship player\x = 100 player\y = 200 player\hitpoints = 3 player\shipstring = XWING$ ;call Text function Text player\x, player\y, player\shipstring$ ; X WaitKey Notes A) Make another ship variable "enemy", use TIE$ for it's image, and make it appear at 200, 150, as in the last example B) Add a function to display a ship at bottom of StarWars1.bb file: Function Display(aShip.ship) Text aShip\x, aShip\y, aShip\shipstring$ End Function C) Use the function by adding a function call, replace line ; X with Display(player) D) Now modify the Text command that shows the enemy by using another function call to Display(enemy) Part 5. Crude Animation In this section, we will make our spaceship start to move. Make sure you save your program as StarWars2 first. Notes A) Save your program as StarWars2.bb B) Add the game loop shown below to your program. The spaceships will move! ---already existing lines that initialize player and enemy----While Not KeyHit(1) Add after initializing player and enemy 5 Display(player) Display(enemy) Delay 100 Cls ; erase the screen player\x=player\x+1 Wend end of added code Waitkey C) Add the following if statement after the line player\x=player\x+1 ;If player presses up, move him up. If KeyHit(UPKEY) player\y = player\y - 3 If player\y <= 0 player\y = 10 EndIf EndIf D) Add a new function at the bottom of your program called DrawHUD( ), containing these lines: Function DrawHUD() Text 200, 10, "mouseX " Text 200, 20, "player\x Text 300, 10, "mouseY " Text 300, 20, "player\y End Function + " + " MouseX() + player\x MouseY() + player\y E) Add a function call to DrawHUD( ) right before the Wend statement, you should see the position of your mouse and spaceship F) Make the game stop if you hit the ship with the mouse. Put this if statement in the while loop. Then see if you can get it to stop the game by moving the mouse over ship: If MouseX()=player\x And MouseY()=player\y Then Print "crash" Exit EndIf G) CHALLENGE: Use your collision and distance functions from part 2 to make it easier to hit the ship. H) CHALLENGE: Add other arrow handlers: Copy the TestInput( ) function from Demo03-11 to bottom of your program, and put a function call to it in place of your use it in place of your If KeyHit(UPKEY) …etc… code I) CHALLENGE: modify the program to check if the player hits the enemy 6