Chapter 14
Download
1 / 68

Chapter 14 - PowerPoint PPT Presentation


  • 123 Views
  • Uploaded on

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.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' Chapter 14' - walter


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Chapter 14

Chapter 14

Classes, Objects, and Games

XNA Game Studio 4.0



Objectives
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.


Methods in classes
Methods in Classes

5.03 Apply procedures to create methods and instantiate an object from a class. (5%)


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.

Methods


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

Using Methods in Classes


Method syntax

  • Every method is written in basically the same form.access_modifierreturn_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.

Method Syntax


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.

Methods that Return a Value

Return Type


Methods that return a value1

When a method returns a value, the method call must be part of an assignment statement.

Method Call Example:lblResult.Text = Signature();

Methods that Return a Value


Methods with parameters
Methods with Parameters of an assignment statement.

5.04 Apply procedures to create class methods with value, reference and default parameters. (5%)


Parameters

  • Parameters define the values you wish to pass to the method. of an assignment statement.

  • 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.

Parameters


Value vs reference parameters

Value vs. Reference Parameters


Example

public class Dog of an assignment statement.{ private string name; public void setName(string nm) { name = nm; } public string getName () {return name; }

Example


Methods with parameters1

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 )

Methods with Parameters


Methods with parameters2

Method: to do its job.

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.

Methods with Parameters


Pass by value

Pass-By-Value


Pass by reference

Pass-By-Reference


Pass by reference1

  • To pass a variable by reference use the keyword variable from the call.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.

Pass-By-Reference


Using methods in classes1
Using Methods in Classes variable from the call.


Using a method in classes

Using a Method in Classes


Value reference parameter example
Value & Reference Parameter Example methods that allow you to change those properties.


Default parameters in classes

Default parameters are optional. methods that allow you to change those properties.

The method can be called with or without that parameter defined.

Always default parameters should be placed to the right.

Default Parameters in Classes


Overloading methods
Overloading methods methods that allow you to change those properties.

5.05 Apply procedures to overload class methods. (3%)


Overloading methods1

Overloading Methods


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.

Overloading Methods Examples


Game example

//Overloaded Method following methods:

public void setRatingLevel (string l)

{

level = l;

}

//Overloaded Method

public void setRatingLevel (int r)

{

rating = r;

}

Game Example


Applying methods in xna classes
Applying methods in following methods:xna classes


Creating a sprite class hierarchy
Creating a Sprite Class Hierarchy following methods:

6.01 Apply inheritance and composition to create derived classes. (5%)


The basesprite class
The following methods:BaseSpriteClass

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

Method

Accessor: public

Return: void

Name: LoadTexture

Parameters: Texture2D inSpriteTexture


The basesprite class1
The following methods:BaseSpriteClass

  • 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.


The basesprite class2
The following methods:BaseSpriteClass

  • Use the BaseSpriteto 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.


Extending the basesprite to produce a titlesprite
Extending the following methods:BaseSpriteto 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.


Extending the basesprite to produce a titlesprite1
Extending the following methods:BaseSpriteto Produce a TitleSprite

  • Note there is only one method – Update.

  • The rest are inherited from the parent sprite class.

  • Syntax to extend a base classpublic class NewClass:ParentClass

    public class TitleSprite:BaseSprite


Overriding methods from a parent class
Overriding Methods from a Parent Class following methods:

  • 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.


Abstract class interfaces
Abstract Class & Interfaces following methods:

6.05 Understand Overriding and Shadowing. (3%)


What is overriding
What is Overriding? following methods:

  • 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


Using overriding
Using Overriding following methods:

  • In the Base Class

    public virtualvoid Draw(SpriteBatchspriteBatch)

  • 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.


Using overriding1
Using Overriding following methods:

  • In the derived class

    public override void Draw(SpriteBatchspriteBatch)

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


Shadowing
Shadowing following methods:

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

  • Shadowing uses the newkeyword

  • In the derived class

    public new void Draw(SpriteBatchspriteBatch)

  • 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


Shadowing example
Shadowing Example following methods:

public class BaseC

{

public int x;

public void Invoke() { }

}

public class DerivedC : BaseC

{

newpublic void Invoke() { }

}


Overriding methods from a parent class1
Overriding Methods from a Parent Class following methods:

  • 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


Building a class hierarchy
Building a Class Hierarchy following methods:

  • 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 BatSpriteand the BallSprite

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

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

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


Using protected members from a parent class
Using Protected Members from a Parent Class following methods:

  • 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.


Adding a deadly pepper
Adding a Deadly Pepper following methods:

  • 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.


Creating a deadlysprite class
Creating a following methods:DeadlySpriteClass

  • There is a class called MovingSpritethat 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 MovingSpriteclass 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 boolisDeadly;


Drawing the deadly pepper sprite
Drawing the Deadly Pepper Sprite following methods:

  • 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.


Setting up the deadly pepper sprite
Setting Up the Deadly Pepper Sprite following methods:

  • Next, provide the method that sets up the pepper at the beginning of the game.

  • The MovingSpriteclass provides a method called StartGameto set up a moving sprite.

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

  • Override the StartGamemethod in MovingSpriteand replace it with one that does everything the parent method does, plus the action of setting isDeadlyto false.


Setting up the deadly pepper sprite1
Setting Up the Deadly Pepper Sprite following methods:

  • 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.


Setting up the deadly pepper sprite2
Setting Up the Deadly Pepper Sprite following methods:

  • Select that from the list and press Enter.

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

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


Setting up the deadly pepper sprite3
Setting Up the Deadly Pepper Sprite following methods:

  • You don’t want to have to replace the entire StartGamemethod; you just want to add something to set the isDeadlyvalue.

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


Updating the deadly pepper sprite
Updating the Deadly Pepper Sprite following methods:

  • Write the Update behavior for the DeadlySpriteclass.

  • Movement code


Updating the deadly pepper sprite1
Updating the Deadly Pepper Sprite following methods:

  • Collision Code


Updating the deadly pepper sprite2
Updating the Deadly Pepper Sprite following methods:

  • 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


Updating the deadly pepper sprite3
Updating the Deadly Pepper Sprite following methods:

  • Update modification


Polymorphism
Polymorphism following methods:

6.02 Understand Polymorphism


What is polymorphism
What is Polymorphism? following methods:

  • 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.


What is polymorphism1
What is Polymorphism? following methods:

  • Inheritance in a derived class represents the “Is-A” relationship.

  • Examples

    A BatSprite IS A MovingSprite

    A BallSprite IS A MovingSprite


What is polymorphism2
What is Polymorphism? following methods:

  • 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.


Polymophism example
Polymophism following methods: 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();


Polymophism example1
Polymophism following methods: 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.


Polymorphic calls
Polymorphic Calls following methods:

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


Polymorphism example
Polymorphism Example following methods:

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

  • AnsweraVillain.Move();


Polymorphism example1
Polymorphism Example following methods:

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

  • AnsweraVillain.Run();aHero.Fly();

  • Why?

    • To be a polymorphic call, the derived object must call an implementation of the base method.


Polymorphism example2
Polymorphism Example following methods:

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

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


Check your understanding
Check Your Understanding following methods:

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


Check your understanding1
Check Your Understanding following methods:

  • If the HealthItem class is derived from the BagObject class and the BagObjectclass has a method called use(), which of the following method calls is written appropriately for the HealthItemobject called myHlthItem to call the use() method?

    • myHlthItem.use();


Check your understanding2
Check Your Understanding following methods:

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


Check your understanding3
Check Your Understanding following methods:

  • 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


ad