Chapter 14
This presentation is the property of its rightful owner.
Sponsored Links
1 / 68

Chapter 14 PowerPoint PPT Presentation

  • Uploaded on
  • Presentation posted in: General

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.

Download Presentation

Chapter 14

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

Lecture 3

Lecture 3



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


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

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


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


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

Value vs. Reference Parameters


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


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


public void Signature(string Name)

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




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

Methods with Parameters

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.


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.


Pass by reference1

  • To pass a variable by reference use the keywordref.

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


Using methods in classes1

Using Methods in Classes

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.

Using a Method in Classes

Value reference parameter example

Value & Reference Parameter Example

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.

Default Parameters in Classes

Overloading methods

Overloading methods

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

Overloading methods1

  • 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

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

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 xna classes

Creating a sprite class hierarchy

Creating a Sprite Class Hierarchy

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

The basesprite class

The BaseSpriteClass

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


Accessor: public

Return: void

Name: LoadTexture

Parameters: Texture2D inSpriteTexture

The basesprite class1

The 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 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 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 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

  • 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

6.05 Understand Overriding and Shadowing. (3%)

What is overriding

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.

Using overriding

Using Overriding

  • 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

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

Shadowing example

Shadowing Example

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

  • 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

  • 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

  • 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

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

  • 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

  • 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

  • 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

  • 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

  • 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

  • Write the Update behavior for the DeadlySpriteclass.

  • Movement code

Updating the deadly pepper sprite1

Updating the Deadly Pepper Sprite

  • Collision Code

Updating the deadly pepper sprite2

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

Updating the deadly pepper sprite3

Updating the Deadly Pepper Sprite

  • Update modification



6.02 Understand Polymorphism

What is polymorphism

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.

What is polymorphism1

What is Polymorphism?

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

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

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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

  • Login