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

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
The child gets it all..  Factor out common behavior  parent class implements behavior needed by children  guarantee that all subclasses have the characteristics.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Chapter Day 7. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 7 Questions from last Class?? Problem set 1 Corrected  Good results 3.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
Chapter 9: Classes with Instance Variables or Classes=Methods+Variables Asserting Java © Rick Mercer.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
OOP Languages: Java vs C++
Programming Games Computer science big ideas. Computer Science jargon. Show virtual dog Homework: [Catch up: dice game, credit card or other form.] Plan.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
Chapter 5 - Writing a Problem Domain Class Definition1 Chapter 5 Writing a Problem Domain Class Definition.
1.  A method describes the internal mechanisms that actually perform its tasks  A class is used to house (among other things) a method ◦ A class that.
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
Introduction to Object-Oriented Programming
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Creating Simple Classes. Outline of Class Account Class Account Account # Balance Holder name phone# Overdrawn (true/false) Data Members Open Credit Debit.
Classes CS 21a: Introduction to Computing I First Semester,
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Programming in Java CSCI-2220 Object Oriented Programming.
SE-1010 Dr. Mark L. Hornick 1 Java Programming Basics.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Chapter 4 Introduction to Classes, Objects, Methods and strings
CIS Intro to JAVA Lecture Notes Set July-05 GUI Programming – Home and reload buttons for the webbrowser, Applets.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
ACO 101: Intro to Computer Science Anatomy Part 3: The Constructor.
CHAPTER 3 Getting Player Input XNA Game Studio 4.0.
Using Objects. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L7: Objects Slide 2 Java.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Problem 1 Bank.  Manage customers’ bank account using the following operations: Create a new account given a customer’s name and initial account. Deposit.
Bank Account Example public class BankAccount { private double balance; public static int totalAccounts = 0; public BankAccount() { balance = 0; totalAccounts++;
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Monday, Jan 27, 2003Kate Gregory with material from Deitel and Deitel Week 4 Questions from Last Week Hand in Lab 2 Classes.
Topics Instance variables, set and get methods Encapsulation
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
Chapter 3 Implementing Classes
Designing Classes Lab. The object that you brought to class Put it in the basket we will exchange them now.
Georgia Institute of Technology More on Creating Classes Barb Ericson Georgia Institute of Technology June 2006.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
ENCAPSULATION. WHY ENCAPSULATE? So far, the objects we have designed have all of their methods and variables visible to any part of the program that has.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Introduction to Classes and Objects
Implementing Classes Yonglei Tao.
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Creating and Using Classes
Chapter Three - Implementing Classes
The Basics of Class Diagrams for a single class
CSC 113 Tutorial QUIZ I.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Anatomy of a Method.
More on Classes and Objects
Introduction to Objects
Outline Anatomy of a Class Encapsulation Anatomy of a Method
JAVA CLASSES.
Introduction to Object-Oriented Programming
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

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;

This is how it looks in the code

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 – us/library/b1e65aza%28VS.71%29.aspx

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

This is how it looks in the code

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

This is how it looks in the code.

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

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

Here it is in the code

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

Here it is in the code

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

A closer look at Attributes (also called fields)

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.

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.

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

A Closer look at Constructors

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

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

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

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

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)

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.

What a class looks like

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

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

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

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

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

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

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(“ "); // 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

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.

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

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)

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.

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.

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

First add the cannon balls; add these 2 fields

Load the cannon balls

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

This is what it looks like in your code

Now we need to fire the cannonballs note: this is the link to the reference of the Math class 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; }

Here it is in the code

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

2 more fields at the top

Check the A button in the Update method

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

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

Update the gamepad and keyboard states

Don’t forget to draw the cannon balls

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.

Now run it and see if it works

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