55
Building Games for Windows Phone 7 009 R ob Miles University of Hull [email protected] twitter.com/RobMiles robmiles.com

Building Games for Windows Phone 7

Embed Size (px)

DESCRIPTION

009. Rob Miles. University of Hull [email protected] twitter.com/RobMiles robmiles.com. Building Games for Windows Phone 7. Agenda. Introducing the Windows Phone The platform and the development tools Writing games for Windows Phone Game Development Options Useful code samples - PowerPoint PPT Presentation

Citation preview

Page 1: Building Games for Windows Phone 7

Building Games for Windows Phone 7

009

Rob MilesUniversity of Hull

[email protected]

twitter.com/RobMiles

robmiles.com

Page 2: Building Games for Windows Phone 7

• Introducing the Windows Phone• The platform and the development tools

• Writing games for Windows Phone• Game Development Options• Useful code samples

• What to do now• How to Get Started

Agenda

Page 3: Building Games for Windows Phone 7

• Windows Phone 7 series is a significant advance on previous generations

• It provides a whole new way of interacting with mobile devices

• You will find out more about this tomorrow at the keynote• For us it provides a compelling new

platform to make great new applications and games

Windows Phone 7 series

Page 4: Building Games for Windows Phone 7

• You write in C# using managed code

• You create your programs using Visual Studio 2010• You can write Silverlight

and XNA Apps

• There is also an emulator you can use for testing

Development Options

Page 5: Building Games for Windows Phone 7

• The phone is a very capable application platform

• It is very easy to create quick line of business applications

• Silverlight provides some very useful features for game Developers

Windows Phone for Applications

Page 6: Building Games for Windows Phone 7

DemoDamage Calc Application

Page 7: Building Games for Windows Phone 7

• We can use Silverlight data binding to connect the Price and Damage elements to the underlying code

• You can also use this to manage the position and content of game objects

Databinding inDamageCalc

Page 8: Building Games for Windows Phone 7

set{ if (priceChangeActive) return; priceChangeActive = true; latestPrice = value; Damage = twoDecimalPlaces((value / exchangeRate) * taxRate); if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Damage")); } priceChangeActive = false;}

Databound Price Property

• This event is fired when the user changes the price

Page 9: Building Games for Windows Phone 7

set{ if (priceChangeActive) return; priceChangeActive = true; latestPrice = value; Damage = twoDecimalPlaces((value / exchangeRate) * taxRate); if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Damage")); } priceChangeActive = false;}

Databound Price Property

• It calculates the new value of the Damage property

Page 10: Building Games for Windows Phone 7

set{ if (priceChangeActive) return; priceChangeActive = true; latestPrice = value; Damage = twoDecimalPlaces((value / exchangeRate) * taxRate); if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Damage")); } priceChangeActive = false;}

Databound Price Property

• It fires a property changed event to update the Damage display

Page 11: Building Games for Windows Phone 7

set{ if (priceChangeActive) return; priceChangeActive = true; latestPrice = value; Damage = twoDecimalPlaces((value / exchangeRate) * taxRate); if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Damage")); } priceChangeActive = false;}

Databound Price Property

• I use an interlock to stop updates from repeating

Page 12: Building Games for Windows Phone 7

Damage Calc Extensions

• It would be easy to make the program automatically update the exchange rates

• It could also use location based services to determine the local tax rate

Page 13: Building Games for Windows Phone 7

• XNA is a great place to write games

• But some kinds of games are a bit hard to write in XNA• Sometimes you end up writing

your own user interface

• Silverlight makes “form based” games really easy to create

Writing Games in Silverlight

Page 14: Building Games for Windows Phone 7

DemoPattern Match Silverlight Game

Page 15: Building Games for Windows Phone 7

• An XNA game has Draw and Update methods which are called regularly by the game framework

• Silverlight does not provide game events• You need to create your own game clock• The CompositionTarget.Rendering event can

be used for this

Getting Game Events

Page 16: Building Games for Windows Phone 7

• The Rendering event fires each time the form is rendered

• This can be used as our game “tick”

Catching the Rendering Event

CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);

Page 17: Building Games for Windows Phone 7

void CompositionTarget_Rendering(object sender, EventArgs e){ gameTick();}

private DateTime lastTick;

private void gameTick(){ DateTime now = DateTime.Now; TimeSpan interVal = now - lastTick; lastTick = now;

Update(interVal);}

Creating an Update behaviour

Page 18: Building Games for Windows Phone 7

• The Draw method implements my game state machine

• It has a case for each game state

The Draw method

Page 19: Building Games for Windows Phone 7

• Unlike an XNA game, the Update method will not be called at fixed intervals

• Instead the game will need to use the TimeSpan value provided to the Update call to perform game timing

Updating Gameplay in Silverlight

Page 20: Building Games for Windows Phone 7

private int currentWait = 0;

private bool testUpdateTime(TimeSpan timeStamp, int updateDelay){ currentWait += timeStamp.Milliseconds;

if (currentWait < updateDelay) { return false; } currentWait -= updateDelay; return true;}

Using the timestamps

• The method returns true if the delay time has passed

Page 21: Building Games for Windows Phone 7

private int flashInterval = 800;

...

if (testUpdateTime(interval, flashInterval)){ // Update randomly flashing buttons int oldLitButton = litButtonNo; while (oldLitButton == litButtonNo) { litButtonNo = attractRand.Next(gameButtons.Length); }}

Flashing the Buttons

• This update code changes the lit button every 800 ms

Page 22: Building Games for Windows Phone 7

• Your games must automatically persist state information so that they resume where they left off

• Windows Phone provides local storage to make this possible

• Each application has its own area of isolated storage

Persisting State

Page 23: Building Games for Windows Phone 7

private void saveHighScore(){ IsolatedStorageFile myStorage =

IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream outputStream =

myStorage.OpenFile("HiScore",FileMode.CreateNew); StreamWriter output = new StreamWriter(outputStream); output.WriteLine(highScore.ToString()); output.Close(); myStorage.Dispose();}

Storing a High Score

• Each application has its own storage area

Page 24: Building Games for Windows Phone 7

private void saveHighScore(){ IsolatedStorageFile myStorage =

IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream outputStream =

myStorage.OpenFile("HiScore",FileMode.CreateNew); StreamWriter output = new StreamWriter(outputStream); output.WriteLine(highScore.ToString()); output.Close(); myStorage.Dispose();}

Storing a High Score

• The game can create files and store values in them

Page 25: Building Games for Windows Phone 7

IsolatedStorageFile myStorage = IsolatedStorageFile.GetUserStoreForApplication();IsolatedStorageFileStream inputStream =

myStorage.OpenFile("HiScore", FileMode.Open);StreamReader input = new StreamReader(inputStream);

string highScoreText = input.ReadLine();highScore = int.Parse(highScoreText);highscorTextBlock.Text = "Score: " + highScore.ToString();

input.Close();myStorage.Dispose();

Loading a High Score

• The storage can be read when the game starts

Page 26: Building Games for Windows Phone 7

• The user never stops a program:• The back button takes you “up” a

level in an application or back to the previous application

• The Start button takes you to the Start Screen

• As far as our game is concerned, in either of these situations the program ends

Windows Phone Navigation

Page 27: Building Games for Windows Phone 7

• Your program can bind to the BackKeyPress event and respond appropriately

• It can absorb the back key event if it is sensible to do this

Handling the Back Button

Page 28: Building Games for Windows Phone 7

Handling the Exit Event

• You can also bind an event handler to the Exit event to detect when your program is being stopped• this doesn’t seem to work quite right

in the present emulator though..

Application.Current.Exit += new EventHandler(Current_Exit);

Page 29: Building Games for Windows Phone 7

• XNA games will run very well on Windows Phone

• Support is provided for 2D and 3D games

• Games can use multi-touch and the accelerometer

Moving into XNA

Page 30: Building Games for Windows Phone 7

• Unlike the Zune HD, the accelerometer input for XNA games is presently via the Sensor library

• However, it is easy to create an emulation of the AccellerometerState class for XNA games

Accelerometer Input

Page 31: Building Games for Windows Phone 7

DemoAccelerometer Simulation

Page 32: Building Games for Windows Phone 7

• Windows Phone programs can consume web services and read web pages

• This is a very powerful feature• I connect the Windows Phone

program to an XNA program that serves out X, Y and Z values read from the Gamepad

An Accelerometer Server

Page 33: Building Games for Windows Phone 7

• The Update method requests a page from the Accelerometer server

Reading a Web Pagepublic void Update(){ Uri uri = new Uri("http://127.0.0.1:8080/Accelerometer"); WebClient client = new WebClient(); client.DownloadStringCompleted +=

new DownloadStringCompletedEventHandler(client_DownloadCompleted); client.DownloadStringAsync(uri);}

Page 34: Building Games for Windows Phone 7

• Get the response and build the acceleration data

Reading a Web Pagestatic void client_DownloadCompleted (object sender,

DownloadStringCompletedEventArgs e){ if (e.Error == null) { string[] numbers = e.Result.Split(new char[] { ',' }); state.Acceleration.X = float.Parse(numbers[0]); state.Acceleration.Y = float.Parse(numbers[1]); state.Acceleration.Z = float.Parse(numbers[2]); }}

Page 35: Building Games for Windows Phone 7

• There is no emulation support• Although you can fake it as

shown above• There are also emulations that

use the Nintendo Wii remote

Working with the Accelerometer

Page 36: Building Games for Windows Phone 7

• XNA provides support for multi-touch input• Up to four touch events

can be tracked at once• Each event is uniquely

identified• You get touch down, up

and moved events

Multi-Touch

Page 37: Building Games for Windows Phone 7

DemoWindows Phone Piano

Page 38: Building Games for Windows Phone 7

• This gets a the current touch events

Processing Touch EventsTouchCollection touchState = TouchPanel.GetState();

foreach (TouchLocation touch in touchState) { Point touchPoint = new Point((int)touch.Position.X, (int)touch.Position.Y); foreach (keyDetails key in noteKeys) { if (key.keyRectangle.Contains(touchPoint) && touch.State == TouchLocationState.Pressed) { key.keySound.Play(); break; } }}

Page 39: Building Games for Windows Phone 7

• We then work through each event in turn

Processing Touch EventsTouchCollection touchState = TouchPanel.GetState();

foreach (TouchLocation touch in touchState) { Point touchPoint = new Point((int)touch.Position.X, (int)touch.Position.Y); foreach (keyDetails key in noteKeys) { if (key.keyRectangle.Contains(touchPoint) && touch.State == TouchLocationState.Pressed) { key.keySound.Play(); break; } }}

Page 40: Building Games for Windows Phone 7

• I use a keyDetails class which holds the key position as a Rectangle and the soundeffect to play when the key is pressed

Processing Touch EventsTouchCollection touchState = TouchPanel.GetState();

foreach (TouchLocation touch in touchState) { Point touchPoint = new Point((int)touch.Position.X, (int)touch.Position.Y); foreach (keyDetails key in noteKeys) { if (key.keyRectangle.Contains(touchPoint) && touch.State == TouchLocationState.Pressed) { key.keySound.Play(); break; } }}

Page 41: Building Games for Windows Phone 7

• If you want to emulate multi-touch you can get a multi-touch monitor • Windows 7 multi-touch is used

directly the emulator

• There are some multi-touch emulators that use multiple mice

Working with Multi-Touch

Page 42: Building Games for Windows Phone 7

• XNA supports 3D• Windows phones

contain hardware acceleration

• There is shader support, but you can’t write your own shader code

XNA in 3D

Page 43: Building Games for Windows Phone 7

DemoDrawing Triangles in 3D

Page 44: Building Games for Windows Phone 7

• The way that you specify Vertices has changed in XNA 4.0

• Do not be surprised if sample code for earlier versions of XNA fail to work

• The new design is much easier to understand though

• Samples are now available on the web

XNA 4.0 Changes

Page 45: Building Games for Windows Phone 7

• The Windows Phone update rate is set to 30Hz

• This is sensible given the type of display in use

• You can use a frame counter to measure the actual update rate

Measuring Performance

Page 46: Building Games for Windows Phone 7

DemoMeasuring Performance

Page 47: Building Games for Windows Phone 7

public override void Update(GameTime gameTime){ elapsedTime += gameTime.ElapsedGameTime;

if (elapsedTime > TimeSpan.FromSeconds(1)) { elapsedTime -= TimeSpan.FromSeconds(1); frameRate = frameCounter; frameCounter = 0; }}

XNA Performance Counter

• This Update method clears the frame counter every second• The counter is increased each time Draw is called

Page 48: Building Games for Windows Phone 7

• It is easy to get a frame rate counter in Silverlight

• Setting the above property in your program will display one

Sliverlight Performance

Application.Current.Host.Settings.EnableFrameRateCounter = true;

Page 49: Building Games for Windows Phone 7

• One way to get experience of Windows Phone XNA development is to get hold of a Zune HD

• You can write XNA 3.1 games in 2D for this platform

• It provides multi-touch and accelerometer support

Using the Zune HD

Page 50: Building Games for Windows Phone 7

DemoZune HD Album Shaker

Page 51: Building Games for Windows Phone 7

• Download the development environment and other cool stuff:

developer.windowsphone.com/ • Read the sample chapters from the free ebook

by Charles Petzold• Get writing code!• All samples, resources and links are on my

blog:www.robmiles.com

What To Do Now

Page 52: Building Games for Windows Phone 7

Q & A

Page 54: Building Games for Windows Phone 7
Page 55: Building Games for Windows Phone 7