Upload
sonya-stephenson
View
37
Download
0
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
Building Games for Windows Phone 7
009
Rob MilesUniversity of Hull
twitter.com/RobMiles
robmiles.com
• 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
• 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
• 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
• 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
DemoDamage Calc Application
• 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
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
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
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
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
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
• 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
DemoPattern Match Silverlight Game
• 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
• 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);
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
• The Draw method implements my game state machine
• It has a case for each game state
The Draw method
• 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
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
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
• 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
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
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
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
• 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
• 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
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);
• 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
• 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
DemoAccelerometer Simulation
• 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
• 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);}
• 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]); }}
• 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
• 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
DemoWindows Phone Piano
• 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; } }}
• 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; } }}
• 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; } }}
• 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
• XNA supports 3D• Windows phones
contain hardware acceleration
• There is shader support, but you can’t write your own shader code
XNA in 3D
DemoDrawing Triangles in 3D
• 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
• 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
DemoMeasuring Performance
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
• 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;
• 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
DemoZune HD Album Shaker
• 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
Q & A
A sua opinião é importante!Complete o questionário de avaliação e devolva-o à saida.