Presentation is loading. Please wait.

Presentation is loading. Please wait.

More Game GUI and methods. This is where we left off.

Similar presentations


Presentation on theme: "More Game GUI and methods. This is where we left off."— Presentation transcript:

1 More Game GUI and methods

2 This is where we left off

3 Input from the GUI We need to detect what the input is from the user: This is the Xbox controller code (it goes in the Update method of Game1.cs) GamePadState gamePadState = GamePad.GetState(PlayerIndex.One); cannon.rotation += gamePadState.ThumbSticks.Left.X * 0.1f;

4 This is how it looks in the code

5 What is the thumbstick is sending the game program? Answer: Numbers – If you push the thumbstick left it will send a negative number – If you push it right it will send a positive number We multiply it by 0.1f (a very small number that is a float) to make it a very small increment so that it looks like the cannon is moving smoothly. – Extra credit: do a one page report on floats – http://msdn.microsoft.com/en- us/library/b1e65aza%28VS.71%29.aspx

6 And we need input from the keyboard (if not Xbox) KeyboardState newState = Keyboard.GetState(); if(newState.IsKeyDown(Keys.Left)) { cannon.rotation -= 0.1f; } if(newState.IsKeyDown(Keys.Right)) { cannon.rotation += 0.1f; }

7 This is how it looks in the code

8 So now the cannon will spin And we really should lock down the rotation cannon.rotation = MathHelper.Clamp(cannon.rotation, -MathHelper.PiOver2, 0);

9 This is how it looks in the code.

10 Now run your game again and see what happens Does it spin? Here is more info on the MathHelper class – http://msdn.microsoft.com/en- us/library/microsoft.xna.framework.mathhelper.aspx http://msdn.microsoft.com/en- us/library/microsoft.xna.framework.mathhelper.aspx – http://msdn.microsoft.com/en- us/library/microsoft.xna.framework.mathhelper_members.aspx http://msdn.microsoft.com/en- us/library/microsoft.xna.framework.mathhelper_members.aspx – http://msdn.microsoft.com/en- us/library/microsoft.xna.framework.mathhelper.clamp.asp x http://msdn.microsoft.com/en- us/library/microsoft.xna.framework.mathhelper.clamp.asp x – http://msdn.microsoft.com/en- us/library/microsoft.xna.framework.mathhelper.piover2.as px http://msdn.microsoft.com/en- us/library/microsoft.xna.framework.mathhelper.piover2.as px

11 Lets make the cannon shoot stuff We are going to use the GameObject.cs for the cannonballs – First we need to add 2 new fields for velocity and whether or not the ball is alive or dead

12 Here it is in the code

13 And then initialize them in the constructor velocity = Vector2.Zero; alive = false;

14 Here it is in the code

15 What does this do to the cannon? This question comes up because the cannon uses the same GameObject Answer: Nothing really – Since we are not using these new fields in the cannon; it will not appear to be any different

16 A closer look at Attributes (also called fields)

17 Declaring Attributes(or fields) Review public class BankAccount { private long accountID; private String name; private double balance;  Attributes are properties of objects, not local variables. (we will talk about types of variables later)  You should declare attributes near the top of the class.  It is OK to declare attributes anywhere in the class (except inside a method), but it makes them hard to find. Attributes should normally be private or protected.

18 Declaring Attributes (2) public class BankAccount { /** the account ID, a 10-digit number */ private long accountID; /** the account name */ private string name; /** the account balance, in Baht */ private double balance;  Attributes are important! So, you should include some comments describing them.

19 Scope: Limiting Accessibility The attributes and methods of a class can be designated as: public - can be used from any code. A public method can be called from any code that references an object. A public attribute can be assessed (or changed) from any code than references an object. protected - can only be used from inside the class or inside a derived (child) class. private - can only be used from inside the class. Guidelines:  Allow the outside program access only to the methods/data it needs to perform its job. This is the "public interface" to the class.  Methods that are part of the external interface are public; everything else is private or protected.  Attributes (state) should be private or protected. Although we did deviate from this to keep our GameObject code lighter

20 A Closer look at Constructors

21 What the constructor does To set attributes when an object is created, you define a constructor. A constructor is called when an object is created, examples: BankAccount ku = new BankAccount( ); BankAccount ku = new BankAccount( "KU", 1234567890 );

22 Constructor A constructor is a method that is called when a new object is created. A constructor has the same name as the class. The constructor usually initializes the attributes (state) of the object. public class BankAccount { private long accountID; private String name; private double balance; /** constructor */ public BankAccount( ) { accountID = "unknown"; balance = 0; } public double myMethod( ) { BankAccount acct;... acct = new BankAccount( );...

23 Constructor (2) A class can have several constructors. The code will use the one that matches the arguments in the "new" command. If a matching constructor is not found, it is an error! public class BankAccount { private long accountID; private String name; private double balance; /** constructor */ public BankAccount( String aName, long id ) { name = aName; accountID = id; balance = 0; } public double myMethod( ) { BankAccount acct;... acct = new BankAccount( "T. Shinawat", 12345678);...

24 Writing Constructors (1) public class BankAccount { private long accountID; private String name; private double balance; /* default constructor */ public BankAccount( ) { accountID = 0; name = "unknown"; balance = 0; } /* parameterized constructor */ public BankAccount(String aname, long id) { name = aname; accountID = id; balance = 0; } No return value -- not even "void" ! The default constructor doesn't have any parameters

25 Writing Constructors (2) public class BankAccount { private long accountID; private String name; private double balance; /* default constructor */ public BankAccount( ) { accountID = 0; name = "unknown"; balance = 0; } /* a parameterized constructor */ public BankAccount(String aname, long id) { name = aname; accountID = id; balance = 0; } Initialize the attributes using parameter values Parameterized Constructors: A class can have many constructors, each with different parameters. This is called overloading a constructor (over loading is good)

26 Writing Constructors (3) /** default constructor */ public BankAccount( ) { this("unknown“, 0); } /* a parameterized constructor */ public BankAccount(String aname, long id) { name = aname; accountID = id; balance = 0; } Constructor can call another constructor. A constructor can call another constructor using “this( … )”.  “this(…)” must be the first statement in the constructor.  This is useful for eliminating duplicate code.

27 What a class looks like

28 Structure of a Class // A Bank Account with deposit/withdraw public class BankAccount { private long balance; private String accountNumber; private String accountName; private int homeBranch; //create a new bank account object public BankAccount( String number, String name ) { } /* deposit to account */ public void deposit( long amount ) { if(amount>=0) "Error: negative deposit"; balance += amount; } comment describes the class Beginning of class definition, including accessibility Attributes (fields) of the class A constructor A method with a parameter

29 Class Diagram for a BankAccount Class BankAccount name accountID balance getBalance( ) credit( double amount ) debit( double amount ) getName( ) A UML class diagram The methods = what it DOES The Class Name The attributes or state = what it KNOWS

30 Specifying Visibility/Accessibility BankAccount - name - accountID - balance + getBalance( ) + credit(double amount) + debit(double amount) + getName( ) Public methods The Class Name Private attributes Indicate accessibility in UML class diagrams using a prefix: + public # protected - private

31 Generate the class diagram for the GameObject class Right click on the class and go to View Class Diagram on the flyout menu This is what it produces; this is what our GameObject class looks like

32 Ok so there seem to be objects and methods everywhere For example: – We used the Draw method of the SpriteBatch class – We used the Clamp method of the MathHelper class

33 What is a Method? Programming view: a method is a function. It can return a value or not. Design view: methods define the behavior of objects. Methods are the way by which objects communicate // define a "deposit" behavior for a bank account. public class BankAccount { private long balance; // acct balance attribute public void deposit( long amount ) { balance = balance + amount; }

34 Invoking a Method To invoke the deposit method, you must use is as a behavior of a particular BankAccount object. Example: // define a "deposit" behavior for a bank account. BankAccount myAcct = new BankAccount(“1111111"); // read some deposit data string s = this.txtDepositAmount.Text; decimal money = Convert.ToDecimal(s); // method: deposit the money in my account myAcct.deposit( money ); call "deposit" method of a BankAccount object

35 Writing a Method (1) A method consists of these parts. / / return the maximum of 2 double values public double Max ( double a, double b ) { if ( a > b ) return a; else return b; } Access Control: who can use this method? Type of value returned by this method. "void" if nothing is returned. Method Name Parameters Method Body, with returned value.

36 Scope of Methods All methods (functions) must be part of a class. This avoids name conflicts.

37 Scope of Methods (2) From inside of the class, you can refer to a method using just its name. From outside of the class, you must use a class name (static methods) or object name (instance method) to call a method. – (We will go over the difference between static and instance methods later)

38 Visibility (Accessibility) of Methods You determine what objects or parts of the program can access an object's methods. private: method can only be invoked by objects of this class. protected: method can be invoked by other code in the same package, and by objects of this class and its subclasses. public: method can be invoked by any program. public void deposit( long amount ) { /* body of the method */ } visibilitytype of returned value. "void" if method doesn't return any value.

39 Returned Value of a Method class BankAccount { public void deposit(long amount) { balance += amount; } public long getBalance( ) { return balance; } }  A method may return a value. The type of returned value must be declared in the method header.  A method which doesn't return any value should have a return type of "void".  In the method body, use "return ". void means this method does not return a value.

40 So lets make a method I think we would like to shoot cannonballs

41 First add the cannon balls; add these 2 fields

42 Load the cannon balls

43 Now we need a method to update the cannon balls; change the position etc so that it looks like the cannon is shooting Collapse the Update method so that you have more screen space Here is the code: public void UpdateCannonBalls() { foreach (GameObject ball in cannonBalls) { if (ball.alive) { ball.position += ball.velocity; if (!viewportRect.Contains(new Point( (int)ball.position.X, (int)ball.position.Y))) { ball.alive = false; continue; }

44 This is what it looks like in your code

45 Now we need to fire the cannonballs note: this is the link to the reference of the Math class http://msdn.microsoft.com/en-us/library/system.math_members%28VS.71%29.aspx http://msdn.microsoft.com/en-us/library/system.math_members%28VS.71%29.aspx public void FireCannonBall() { foreach (GameObject ball in cannonBalls) { if (!ball.alive) { ball.alive = true; ball.position = cannon.position - ball.center; ball.velocity = new Vector2( (float)Math.Cos(cannon.rotation), (float)Math.Sin(cannon.rotation)) * 5.0f; return; }

46 Here it is in the code

47 It is time to use them We need to grab the current state of the game We do that by comparing it with the previous state

48 2 more fields at the top

49 Check the A button in the Update method

50 Check the space key (this also goes in the Update method)

51 Add the call to update the cannon balls; also in the Update method

52 Update the gamepad and keyboard states

53 Don’t forget to draw the cannon balls

54 Compile and see if you have errors You will probably have 2 (I did that on purpose) – Double click on the error and fix what is wrong.

55 Now run it and see if it works

56 Homework If you haven't already decided what your “enemies” are – then figure it out. – What are you going to shoot and why? Change out the cannon ball image


Download ppt "More Game GUI and methods. This is where we left off."

Similar presentations


Ads by Google