chapter 14

68
CHAPTER 14 Classes, Objects, and Games XNA Game Studio 4.0

Upload: walter

Post on 23-Feb-2016

38 views

Category:

Documents


0 download

DESCRIPTION

Chapter 14. Classes, Objects, and Games. XNA Game Studio 4.0. Lecture 3. Objectives. Find out about making programs using software objects. Learn some software engineering terms and what they mean when we write programs. Use objects to add some new elements to our game easily. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 14

CHAPTER 14Classes, Objects, and Games

XNA Game Studio 4.0

Page 2: Chapter 14

LECTURE 3

Page 3: Chapter 14

Objectives• Find out about making programs using software objects.

• Learn some software engineering terms and what they mean when we write programs.

• Use objects to add some new elements to our game easily.

Page 4: Chapter 14

METHODS IN CLASSES5.03 Apply procedures to create methods and instantiate an object from a class. (5%)

Page 5: Chapter 14

Methods• Methods are also known as subs, sub-routines, and

functions.• There are several types of methods.

• Accessors• Gets information about your object’s properties.

• Mutators/Modifiers• Change or set your object’s properties or state.

• Helper• A method only used within the class – not really used by the object.

• Immutable• Special classes that have NO mutator methods• String Class is an immutable class.

Page 6: Chapter 14

Using Methods in Classes• Method Signatures

• The method signature is the header of the method.

• It specifies

• Access level• Return type, if any• Name of the method• Parameters, if any

Page 7: Chapter 14

Method Syntax• Every method is written in basically the same form.

access_modifier return_type name (parameters)

• Access Modifier• Public – accessible outside the class• Private – accessible only within the class

• Return Type• If a value is to be returned, the Return_type is the data type of that value.• If there is no value to be returned, the return_type is void.

• Name• You should name the method appropriately to identify its function

• Parameters• These are the values that are to be passed in the “call” to the method.

Page 8: Chapter 14

Methods that Return a Value• When you specify a return type you will add a return

statement.

• Method Header Example:

public string Signature(){

return “Created by J Smith”;}

• Return data type and what is returned MUST match.

Return Type

Page 9: Chapter 14

Methods that Return a Value• When a method returns a value, the method call must be

part of an assignment statement.

• Method Call Example:

lblResult.Text = Signature();

Page 10: Chapter 14

METHODS WITH PARAMETERS5.04 Apply procedures to create class methods with value, reference and default parameters. (5%)

Page 11: Chapter 14

Parameters• Parameters define the values you wish to pass to the

method.

• There are two ways to pass parameters• By Value

• The value is sent to the method.• The method can manipulate that value however the value stays in the

method. It cannot be passed back.

• By Reference• The values is sent to the method• The method can manipulate that value AND send that value back.

Page 12: Chapter 14

Value vs. Reference Parameters• Think of a value parameter as a one-way street.

• The value can only move one way.

• Think of a reference parameter as a two-way street.• The value can pass over, then pass back.

• Java has call by value

Page 13: Chapter 14

Example• public class Dog

{ private string name;

public void setName(string nm) { name = nm; } public string getName () { return name; }

Page 14: Chapter 14

Methods with Parameters• Parameters provide information to a method that is

necessary to do its job.

• The method call provides the values – called actual arguments.

• You will add the “formal arguments” or “parameters” to the method header.

public void Signature(string Name )

Page 15: Chapter 14

Methods with ParametersMethod:public void Signature(string Name){

lblResult.Text = “Written by: ” + Name;}

Call:Signature(strName);

• The arguments and parameters MUST match in order, data type and number.

Page 16: Chapter 14

Pass-By-Value• This is the default way to pass arguments in C#.

• A copy of the value is made and sent to the method.

• Any changes are not passed back to the call.

• Think of this as a one way street; the value only moves in one direction.

Page 17: Chapter 14

Pass-By-Reference• The method has the ability to access and modify the original

variable from the call.

• Reference-type variables store references to objects.

• Think of it as sending the actual address of the object for the method to access the value. The method can then manipulate that value and send it back.

Page 18: Chapter 14

Pass-By-Reference• To pass a variable by reference use the keyword ref.

• Apply the ref keyword to the parameter declaration allows you to pass that variable by reference.

• The ref keyword is used for variables that already have been initialized in the calling method.

• It must be initialized, otherwise the compiler will generate an error.

Page 19: Chapter 14

USING METHODS IN CLASSES

Page 20: Chapter 14

Using a Method in Classes• Remember, an object is made up of properties/attributes

and methods that allow you to change those properties.

• Syntax

objectName.methodName (arg, arg, …)

• Arguments are listed in the appropriate order that matches the order, number and data type of the parameters in the method signature.

Page 21: Chapter 14

Value & Reference Parameter Example

Page 22: Chapter 14

Default Parameters in Classes• Default parameters are optional. • The method can be called with or without that parameter

defined.• Always default parameters should be placed to the right.

Page 23: Chapter 14

OVERLOADING METHODS5.05 Apply procedures to overload class methods. (3%)

Page 24: Chapter 14

Overloading Methods• You can create a method with the same name as long as

the parameters are different in one of the following ways

• Number of parameters,

• Order of the parameters,

• Data type of parameters

Page 25: Chapter 14

Overloading Methods Examples• For example, in the student class, you could have the

following methods:

public void addGrade(double grade)

public void addGrade(int grade)

• The compiler can tell the difference between the data types when the method is executed.

Page 26: Chapter 14

Game Example//Overloaded Method public void setRatingLevel (string l) { level = l; }//Overloaded Method public void setRatingLevel (int r) { rating = r; }

Page 27: Chapter 14

APPLYING METHODS IN XNA CLASSES

Page 28: Chapter 14

CREATING A SPRITE CLASS HIERARCHY6.01 Apply inheritance and composition to create derived classes. (5%)

Page 29: Chapter 14

The BaseSprite Class• Here is the base class – Note it does not do much.

MethodAccessor: publicReturn: voidName: LoadTextureParameters: Texture2D inSpriteTexture

Page 30: Chapter 14

The BaseSprite Class• The BaseSprite is the simplest type of sprite. It contains

the bare minimum of sprite behaviors.

• It can be given a texture and a destination rectangle and be asked to draw itself.

• It also declares an update behavior, although in this version of the sprite, it doesn’t do anything.

• It serves as the starting point for all the sprite classes.

Page 31: Chapter 14

The BaseSprite Class• Use the BaseSprite to Store the Background.

• The BaseSprite class is perfect for the game’s background.

• This is created, set to the size of the display, and then drawn at the start of each call of the game’s Draw method.

Page 32: Chapter 14

Extending the BaseSprite to Produce a TitleSprite

• Exactly the same as the BaseSprite, except that it has an Update behavior that checks to see if the player has pressed the A button on the gamepad.

Page 33: Chapter 14

Extending the BaseSprite to Produce a TitleSprite

• Note there is only one method – Update.

• The rest are inherited from the parent sprite class.

• Syntax to extend a base class

public class NewClass : ParentClass

public class TitleSprite : BaseSprite

Page 34: Chapter 14

Overriding Methods from a Parent Class• We need provide a replacement Update method that

works for the TitleSprite.

• The empty method in the BaseSprite class has been marked as virtual, as shown here in bold.

• A method that is virtual can be overridden by a method with the same name in a child class.

Page 35: Chapter 14

ABSTRACT CLASS & INTERFACES6.05 Understand Overriding and Shadowing. (3%)

Page 36: Chapter 14

What is Overriding?• The override modifier is required to extend or modify the

abstract or virtual implementation of an inherited method, property, indexer, or event.

• An override method provides a new implementation of a member that is inherited from a base class.

• The method that is overridden by an override declaration is known as the overridden base method.

• The overridden base method must have the same signature as the override method.

http://msdn.microsoft.com/en-us/library/ebca9ah3.aspx

Page 37: Chapter 14

Using Overriding• In the Base Class

public virtual void Draw(SpriteBatch spriteBatch)

• Note the use of the keyword virtual.

• An override declaration cannot change the accessibility of the virtual method.

• Both the override method and the virtual method must have the same access level modifier.

Page 38: Chapter 14

Using Overriding• In the derived class

public override void Draw(SpriteBatch spriteBatch)

• This method will take precedence over the base class Draw method when called by an object constructed from the derived class.

Page 39: Chapter 14

Shadowing• Shadowing is the same as “Hiding” in C#.

• Shadowing uses the new keyword

• In the derived class

public new void Draw(SpriteBatch spriteBatch)

• When used as a modifier, the new keyword explicitly hides a member inherited from a base class.

• When you hide an inherited member, the derived version of the member replaces the base-class version.

http://msdn.microsoft.com/en-us/library/435f1dw2.aspx

Page 40: Chapter 14

Shadowing Examplepublic class BaseC {

public int x; public void Invoke() { }

}

public class DerivedC : BaseC {

new public void Invoke() { } }

Page 41: Chapter 14

Overriding Methods from a Parent Class• When a program calls the Update method on a reference

to a TitleSprite instance, this Update method is used instead of the one in BaseSprite.

• In other words, the TitleSprite class can contain a new version of the Update method that behaves in the way it needs. Note the keyword override

Page 42: Chapter 14

Building a Class Hierarchy• Next in the hierarchy is the child class MovingSprite.

• These are sprites that need to move around the screen.

• They have extra properties and methods that allow them to be set.

• The BatSprite and the BallSprite

• The only method that differs between these classes is Update.

• In the BatSprite class, the Update method reads the gamepad and uses it to control the position of the bread bat.

• In the BallSprite class, the Update method bounces the cheese ball around the screen and checks for collisions between the ball and other game objects.

Page 43: Chapter 14

Using Protected Members from a Parent Class• If the parent class contains private members, they are not visible to code in the child classes.

• Members of a class can be marked as protected, which means that they are visible to code in children of the class, but not to any code in classes outside the hierarchy.

Page 44: Chapter 14

Adding a Deadly Pepper• How the deadly pepper works

• Sometimes the pepper is green, at which point it is harmless, but at other times it is red.

• If the bread bat collides with the pepper when it is red, the player loses a life.

• Shooting the pepper with the cheese when it is red gains 50 points and turns the pepper green again.

Page 45: Chapter 14

Creating a DeadlySprite Class• There is a class called MovingSprite that provides all the

elements required to make a sprite that moves across the screen.

• This includes working out the size of the sprite and how fast it should move.

• Start by extending the MovingSprite class to make a new class called DeadlySprite.

• This needs to contain an extra data field that records whether or not the pepper is deadly.

• This needs to contain an extra data field that records whether or not the pepper is deadly.

private bool isDeadly;

Page 46: Chapter 14

Drawing the Deadly Pepper Sprite• Updated Draw

• Pepper is red if deadly, otherwise green

• The first thing you do is convert your image of the pepper to black and white.

Page 47: Chapter 14

Setting Up the Deadly Pepper Sprite• Next, provide the method that sets up the pepper at the beginning of the game.

• The MovingSprite class provides a method called StartGame to set up a moving sprite.

• It works out the size of the texture to use, and also calculates the speed of movement.

• Override the StartGame method in MovingSprite and replace it with one that does everything the parent method does, plus the action of setting isDeadly to false.

Page 48: Chapter 14

Setting Up the Deadly Pepper Sprite• If you start to override a method, XNA Game Studio provides

Intellisense to help you choose the method to override.

• When you type “public override” into the code inside the DeadlySprite class, XNA Game Studio shows you a menu of methods that can be overridden.

Page 49: Chapter 14

Setting Up the Deadly Pepper Sprite• Select that from the list and press Enter.

• XNA Game Studio makes an empty version of the method to get you started

• The base key word is used to call the method that has been overridden.

Page 50: Chapter 14

Setting Up the Deadly Pepper Sprite• You don’t want to have to replace the entire StartGame method; you just want to add something to set the isDeadly value.

• The base keyword means that you can use the behavior of the parent method and then add something extra.

Page 51: Chapter 14

Updating the Deadly Pepper Sprite• Write the Update behavior for the DeadlySprite class.

• Movement code

Page 52: Chapter 14

Updating the Deadly Pepper Sprite• Collision Code

Page 53: Chapter 14

Updating the Deadly Pepper Sprite• There is now a method in the BreadAndCheese class that

returns the current score of the game.

• The deadly sprite needs to keep track of the next score to trigger its deadly behavior. To do this, it uses two variables

Page 54: Chapter 14

Updating the Deadly Pepper Sprite• Update modification

Page 55: Chapter 14

POLYMORPHISM6.02 Understand Polymorphism

Page 56: Chapter 14

What is Polymorphism?• Remember the inheritance hierarchy below?

• We will look at polymorphism given the hierarchy.

• Polymorphism allows us to “program in the general” instead of the specific.

• We can create programs that use objects that share the same base class that can share base methods.

Page 57: Chapter 14

What is Polymorphism?• Inheritance in a derived class represents the “Is-A”

relationship.

• ExamplesA BatSprite IS A MovingSpriteA BallSprite IS A MovingSprite

Page 58: Chapter 14

What is Polymorphism?• Given the hierarchy below, an object from the BatSprite

class and the BallSprite class can both implement a method called move from the MovingSprite class.

• Depending upon whether an object is a BatSprite object or a BallSprite object will determine which implementation of the method is used.

Page 59: Chapter 14

Polymophism Example• Let’s look at another example.

• The implementation of the Speak() method for Dog returns “Woof” whereas the implementation for the Cat Speak() method returns “Meow”.

• Given the code below, what is returned? Dog myDog = new Dog(); string says = myDog.Speak();

AnimalSpeak()

DogSpeak()

CatSpeak()

Page 60: Chapter 14

Polymophism Example• What is returned? “Woof”

• Why?

• The compiler looks the object that is calling the method.

• A Dog object called the method so the compiler looked to the Dog class first for the method to use.

Page 61: Chapter 14

Polymorphic Calls• A polymorphic call is one where a derived object calls a method that was declared in the base (or parent) class.

Page 62: Chapter 14

Polymorphism Example

CharacterMove()

HeroFly()

VillainRun()

• Given the following code, how would a Villain object access the Move() method from the base class? Hero aHero; Villain aVillain;

• Answer aVillain.Move();

Page 63: Chapter 14

Polymorphism Example

CharacterMove()

HeroFly()

VillainRun()

• Given the following code, which class would NOT be a polymorphic call? Hero aHero; Villain aVillain;

• Answer aVillain.Run(); aHero.Fly();

• Why?• To be a polymorphic call, the derived

object must call an implementation of the base method.

Page 64: Chapter 14

Polymorphism Example

CharacterMove()

HeroFly()

VillainRun()

• Given the following code, which call would be incorrect Hero aHero; Villain aVillain; Character aCharacter;

• Answer aCharacter.Run(); aCharacter.Fly();

Page 65: Chapter 14

Check Your Understanding• Which of the method calls would be considered

polymorphic if HealthItem and TreasureItem are classes derived from the BagObject? All three classes have the Draw() method.

• HealthItem.Draw();

• TreasureItem.Draw();

Page 66: Chapter 14

Check Your Understanding• If the HealthItem class is derived from the BagObject

class and the BagObject class has a method called use(), which of the following method calls is written appropriately for the HealthItem object called myHlthItem to call the use() method?

• myHlthItem.use();

Page 67: Chapter 14

Check Your Understanding• A King and a Queen class was derived from the Character

class. The Character class has the method called Walk() method, the King class has a Strut() method, and the Queen method has a Glide() method. Which of the following would be a polymorphic calls?

• aKing.Strut();• AKing.Walk();• ACharacter.Walk();• aQuen.Glide();

Page 68: Chapter 14

Check Your Understanding• Given that the Asteroid and Star classes were derived

from the Space class, which of the following statements is false?

• A Asteroid object is a Space object• A Star object is a Space object• A Space object is a Space object• A Space object is a Star object