more game gui and methods. this is where we left off

56
More Game GUI and methods

Post on 21-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

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

More Game GUIand methods

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

This is where we left off

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

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;

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

This is how it looks in the code

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

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

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

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; }

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

This is how it looks in the code

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

So now the cannon will spin

• And we really should lock down the rotationcannon.rotation = MathHelper.Clamp(cannon.rotation, -MathHelper.PiOver2, 0);

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

This is how it looks in the code.

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

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

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

Here it is in the code

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

And then initialize them in the constructor

velocity = Vector2.Zero;alive = false;

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

Here it is in the code

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

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

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

A closer look at Attributes (also called fields)

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

Declaring Attributes(or fields) Reviewpublic 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.

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

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.

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

Scope: Limiting AccessibilityThe 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

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

A Closer look at Constructors

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

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 );

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

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( );......

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

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);......

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

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

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

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)

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

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.

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

What a class looks like

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

Structure of a Class// A Bank Account with deposit/withdrawpublic class BankAccount {

private long balance;private String accountNumber;private String accountName;private int homeBranch;

//create a new bank account objectpublic 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

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

Class Diagram for a BankAccount Class

BankAccount

nameaccountIDbalance

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

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

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

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

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

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

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

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

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;}

}

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

Invoking a MethodTo 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 datastring s = this.txtDepositAmount.Text;decimal money = Convert.ToDecimal(s);

// method: deposit the money in my accountmyAcct.deposit( money );

call "deposit" method of a BankAccount object

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

Writing a Method (1)A method consists of these parts.

// return the maximum of 2 double valuespublic 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

ParametersMethod

Body, with returned

value.

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

Scope of Methods• All methods (functions) must be

part of a class. • This avoids name conflicts.

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

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)

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

Visibility (Accessibility) of MethodsYou 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 */ }

visibility type of returned value. "void" if method doesn't return any value.

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

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 <expression>".

void means this method does not return a value.

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

So lets make a method

• I think we would like to shoot cannonballs

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

First add the cannon balls; add these 2 fields

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

Load the cannon balls

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

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; } } }}

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

This is what it looks like in your code

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

Now we need to fire the cannonballsnote: 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

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; } } }

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

Here it is in the code

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

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

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

2 more fields at the top

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

Check the A button in the Update method

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

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

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

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

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

Update the gamepad and keyboard states

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

Don’t forget to draw the cannon balls

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

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.

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

Now run it and see if it works

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

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