code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

//#define MEASURE_FPS //Uncomment this line if you want to measure the performance

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using MotoTrialRacer.UI;

namespace MotoTrialRacer
{
    /// <summary>
    /// The main class for the game. Handles the game mechanics, like timing,
    /// statring the game, failing and winning. Updates and draws all of the
     /// other components.
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        //public static Rectangle screen = new Rectangle(0, 0, 800, 480);

		public static GraphicsDeviceManager Graphics { get; private set; }
        private SpriteBatch spriteBatch;
        private Level level;
        private Texture2D background;
        private View view;
        private Button optionsButton;
        private Button exitButton;
        private Button leftButton;
        private Button rightButton;
        private Matrix transform = Matrix.Identity;
        private AudioPlayer audioPlayer;
        public TimeSpan finishTime;
        private Stopwatch stopwatch = new Stopwatch();
        private String clockTime = "00:00";
        private Vector2 clockPos;
        private SpriteFont font;
        public float scale = 1;
        public bool paused = false;
        private bool failed = false;
        public bool won = false;
        private bool editorOpen = false;
        public String currentLevelName = "";

#if MEASURE_FPS
        private TimeSpan elapsedTime = TimeSpan.Zero;
        private int frameRate = 0;
        private int frameCounter = 0;
#endif

        public int getWidth()
        {
            return GraphicsDevice.Viewport.Width;
        }

        public int getHeight()
        {
            return GraphicsDevice.Viewport.Height;
        }

        public float relativeX( float xin )
        {
            return xin / 800.0f * (float)getWidth();
        }

        public float relativeY(float yin)
        {
            return yin / 480.0f * (float)getHeight();
        }

        /// <summary>
        /// The constuctor for the game. Called by the XNA framework
        /// </summary>
        public Game1()
        {
			Graphics = new GraphicsDeviceManager(this);
			Graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft;
			Graphics.IsFullScreen = true;
            Content.RootDirectory = "Content";

            // Frame rate is 30 fps by default for Windows Phone but that is
            // too slow for Box2D so the target frame rate is set to 60 fps.
            TargetElapsedTime = TimeSpan.FromTicks(166666);
        }

        /// <summary>
        /// Closes views on top the game world
        /// </summary>
        public void CloseView()
        {
            view = null;
        }

        /// <summary>
        /// Resumes to the game if it has been paused
        /// </summary>
        public void Resume()
        {
            paused = false;
            audioPlayer.StopMusic();
            audioPlayer.PlayMotor();
            view = null;
            stopwatch.Start();
        }

        /// <summary>
        /// Starts a new game using a predefined level
        /// </summary>
        /// <param name="levelNumber">the number of the predefiner level (1, 2 or 3)</param>
        public void NewGame(int levelNumber)
        {
            level = new Level(levelNumber, audioPlayer, Content);
            currentLevelName = "level" + levelNumber;
            NewGame();
        }

        /// <summary>
        /// Starts a new game using a user defined custom level
        /// </summary>
        /// <param name="levelName">the name of the level </param>
        public void NewGame(String levelName)
        {
            level = new Level(levelName.Replace(' ', '_') + ".lvl", audioPlayer, Content);
            currentLevelName = levelName;
            NewGame();
        }

        /// <summary>
        /// Starts a new game after the level has been loaded.
        /// For internl use.
        /// </summary>
        private void NewGame()
        {
            level.HeadFail += new Action<Level>(HeadFail);
			level.TireFail += new Action<Level>(TireFail);
			level.Win += new Action<Level>(Win);
            level.EnableControl();
            level.StopBikeMotor();
            failed = false;
            level.ResetBike();
            paused = false;
            won = false;
            audioPlayer.StopMusic();
            audioPlayer.PlayMotor();
            view = null;
            stopwatch.Reset();
            stopwatch.Start();
        }

        /// <summary>
        /// A callback function for LevelEditor to notify that the editor should be closed
        /// </summary>
        /// <param name="sender">the caller of this function</param>
        /// <param name="args">for telling if the created level is wanted to be saved or
        ///                    not</param>
        public void LevelCreated(bool save)
        {
            editorOpen = false;
            editorOpen = false;
            if (save)
                view = new LevelSaver(this);
            else
            {
                level = new Level(1, audioPlayer, this.Content);
                view = new Menu(this);
            }
        }

        /// <summary>
        /// Saves the user defined custom level
        /// </summary>
        /// <param name="levelName">the name of the level</param>
        /// <returns>true if the saving succeeded, false otherwise</returns>
        public bool SaveLevel(String levelName)
        {
            if (level is LevelEditor)
                if (((LevelEditor)level).SaveToFile(levelName))
                    return true;
            return false;
        }

        /// <summary>
        /// Opens the level editor
        /// </summary>
        public void StartLevelEditor()
        {
            audioPlayer.StopMusic();
            view = null;
            stopwatch.Reset();
            paused = false;
            editorOpen = true;
            level = new LevelEditor(audioPlayer, this.Content);
            ((LevelEditor)level).Ready += LevelCreated;
        }

        /// <summary>
        /// Shows LevelSelector on users custom level page
        /// </summary>
        /// <param name="newGame">for telling if we want to select the level for
        /// starting a new game or showing the high scores</param>
        public void ShowMyLevelsSelector(bool newGame)
        {
            view = new LevelSelector(this, newGame, true);
        }

        /// <summary>
        /// Shows LevelSelector on predefined level page
        /// </summary>
        /// <param name="newGame">for telling if we want to select the level bacause of
        /// starting a new game or showing the high scores</param>
        public void ShowLevelSelector(bool newGame)
        {
            view = new LevelSelector(this, newGame, false);
        }

		/// <summary>
		/// A callback function for Level to notify that the driver has hit his head
		/// </summary>
		/// <param name="level">the caller of this function</param>
		public void HeadFail(Level level)
		{
			Failed(false);
		}

        /// <summary>
        /// A callback function for Level to notify that the bike has contacted with a spike mat
        /// </summary>
		/// <param name="level">the caller of this function</param>
		public void TireFail(Level level)
        {
			Failed(true);
        }

		private void Failed(bool tireFailed)
		{
			if (view == null)
			{
				if (!failed)
				{
					failed = true;

					if (tireFailed)
						audioPlayer.PlayBlast();
					else
						audioPlayer.PlayOuch(); // head failed

					audioPlayer.StopMotor();
					view = new Menu(this);
					audioPlayer.PlayMusic();
				}
			}
		}

        /// <summary>
        /// A callback function for Level to notify that the player has got to the finish
        /// </summary>
		/// <param name="level">the caller of this function</param>
        public void Win(Level level)
        {
            if (view == null)
            {
                paused = true;
                stopwatch.Stop();
                finishTime = stopwatch.Elapsed;
                audioPlayer.PlayFanfare();
                audioPlayer.StopMotor();
                view = new WinView(this);
                won = true;
            }
        }

        /// <summary>
        /// Open the main menu
        /// </summary>
        public void OpenMenu()
        {
            view = new Menu(this);
            audioPlayer.StopMotor();
            audioPlayer.StopFanfare();
            audioPlayer.PlayMusic();
        }

        /// <summary>
        /// Pauses the game
        /// </summary>
        public void Pause()
        {
            stopwatch.Stop();
            paused = true;
			OpenMenu();
        }

        /// <summary>
        /// Shows the high scores for the selected level
        /// </summary>
        /// <param name="levelName">the name of the level which high scores we want to show</param>
        public void ShowHighScores(String levelName)
        {
            view = new HighScores(this, levelName);
        }

        /// <summary>
        /// Shows InfoView
        /// </summary>
        public void ShowInfo()
        {
            view = new InfoView(this);
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            audioPlayer = new AudioPlayer(Content);
            level = new Level(1, audioPlayer, this.Content);
			level.HeadFail += new Action<Level>(HeadFail);
			level.TireFail += new Action<Level>(TireFail);
			level.Win += new Action<Level>(Win);
            background = this.Content.Load<Texture2D>("Images/sky");
            font = this.Content.Load<SpriteFont>("SpriteFont3");
            view = new SplashScreen(this);
            optionsButton = new Button("options",
                                        new Vector2(getWidth() * 0.015f, getHeight() * 0.89f),
                                                    this.Content);
			optionsButton.ButtonPressed += (sender => Pause());

            float aspect = (float)optionsButton.Width / (float)optionsButton.Height;
            optionsButton.Height = (int)(0.1f * getHeight());
            optionsButton.Width = (int)(aspect * optionsButton.Height);
            exitButton = new Button("exit",
                                    new Vector2(getWidth() * 0.89f, getHeight() * 0.88f),
                                    this.Content);
			exitButton.ButtonPressed += (sender => Exit());

            aspect = (float)exitButton.Width / (float)exitButton.Height;
            exitButton.Height = (int)(0.1f * (float)getHeight());
            exitButton.Width = (int)(aspect * (float)exitButton.Height);
            leftButton = new Button("left", new Vector2(10, 20),
                                    this.Content, true);
			leftButton.ButtonPressed += (sender => level.leanBikeBackwards());
            leftButton.Height = 70;

			rightButton = new Button("right", new Vector2(relativeX(735), relativeY(20)),
                                     this.Content, true);
            rightButton.Height = 70;
			rightButton.ButtonPressed += (sender => level.leanBikeForwards());

            clockPos = new Vector2(0.45f * getWidth(), 0.89f * getHeight());
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
            this.Content.Unload();
        }

        /// <summary>
        /// The main update method for the game loop. Calls all the lower level update methods
        /// </summary>
        /// <param name="gameTime">snapshot of the game timing state</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

#if MEASURE_FPS
            elapsedTime += gameTime.ElapsedGameTime;

            if (elapsedTime > TimeSpan.FromSeconds(1))
            {
                elapsedTime -= TimeSpan.FromSeconds(1);
                frameRate = frameCounter;
                frameCounter = 0;
            }
#endif
            if (view != null)
            {
                level.disableBikeControls();
                view.Update();
            }
            else if (!editorOpen)
            {
                TouchCollection touchCollection = TouchPanel.GetState();
                if (touchCollection.Count() > 0)
                {
                    optionsButton.Update(touchCollection[0]);
                    exitButton.Update(touchCollection[0]);
                    leftButton.Update(touchCollection[0]);
                    rightButton.Update(touchCollection[0]);
                }
            }
            if (!paused)
            {
                level.Update();
            }

			clockTime = String.Format("{0:d2}:{1:d2}", stopwatch.Elapsed.Minutes, stopwatch.Elapsed.Seconds);
        }

        /// <summary>
        /// The main draw method for the game loop. Calls all the lower level draw methods
        /// </summary>
        /// <param name="gameTime">snapshot of the game timing state</param>
        protected override void Draw(GameTime gameTime)
        {
#if MEASURE_FPS
            frameCounter++;
#endif
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();
            Rectangle screen = new Rectangle(0, 0, getWidth(), getHeight());
            spriteBatch.Draw(background, screen, Color.White);

            level.Draw(spriteBatch);

			if (view != null)
				view.Draw(spriteBatch);
            else if (!editorOpen)
            {
                spriteBatch.DrawString(font, clockTime, clockPos, Color.Yellow);
				optionsButton.Draw(spriteBatch);
				exitButton.Draw(spriteBatch);
				leftButton.Draw(spriteBatch);
				rightButton.Draw(spriteBatch);
            }
            spriteBatch.End();
        }
    }
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using Microsoft.Xna.Framework.Graphics;

namespace MotoTrialRacer
{
	interface IDrawable
	{
		void Draw(SpriteBatch spriteBatch);
	}
}

repo_name: snapshot/xnamototrialracer

license: unknown


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Box2D.XNA;
using System.IO;
using System.IO.IsolatedStorage;
using System.Globalization;
using MotoTrialRacer.Components;

namespace MotoTrialRacer
{

    /// <summary>
    /// The class for different levels of the game.
    /// Implements the IContactListener class and handles the contacts between Box2D Shapes.
    /// </summary>
    public class Level : IContactListener, IDrawable
    {
        // For converting Box2D meters to screen pixels and vice versa
        public const float FACTOR = 85.33f;
		public const float DEG_TO_RAD = 0.0174533f;
		public const float RAD_TO_DEG = 57.295780f;

		public event Action<Level> TireFail;
		public event Action<Level> HeadFail;
		public event Action<Level> Win;

		protected Matrix transform = Matrix.Identity;
		protected RotationData rotationData;
        protected World world;
        protected List<LevelComponent> components = new List<LevelComponent>();
        protected Bike bike;
        protected ContentManager content;
        protected AudioPlayer audioPlayer;
        protected float[] camPos = { 0, 0 };
        protected float zoom = 1;

		private NumberFormatInfo provider = new NumberFormatInfo();
        private bool bikeShouldBeReleased = false;
		private float[] bikeSpeed = new float[2];

        /// <summary>
        /// Creates a new predefined level
        /// </summary>
        /// <param name="number">The number of the level (1, 2 or 3)</param>
        /// <param name="pAudioPlayer">The AudioPlayer intance that playes all the sound
        ///                            effects</param>
        /// <param name="pContent">Used ContentManager</param>
        /// <param name="pSpriteBatch">Used SpriteBatch</param>
        public Level(int number, AudioPlayer pAudioPlayer, ContentManager pContent)
        {
            content = pContent;
            audioPlayer = pAudioPlayer;
            world = new World(new Vector2(0.0f, 5.0f), true);
            world.ContactListener = this;
            rotationData = new RotationData();
            bike = new Bike(bikeSpeed, rotationData, world, camPos, content);
            provider.NumberDecimalSeparator = ".";

            try
            {
				using (Stream stream = TitleContainer.OpenStream("Content/Levels/Level_" + number + ".lvl"))
				{
					LoadLevel(stream);
				}
            }
            catch (FileNotFoundException)
            {
            }
        }

        /// <summary>
        /// Creates a new user defined custom level
        /// </summary>
        /// <param name="fileName">The name of the file that defines the level</param>
        /// <param name="pAudioPlayer">The AudioPlayer intance that playes all the sound
        ///                            effects</param>
        /// <param name="pContent">Used ContentManager</param>
        public Level(String fileName, AudioPlayer pAudioPlayer, ContentManager pContent)
        {
            content = pContent;
            audioPlayer = pAudioPlayer;
            world = new World(new Vector2(0.0f, 5.0f), true);
            world.ContactListener = this;
            rotationData = new RotationData();
            bike = new Bike(bikeSpeed, rotationData, world, camPos, content);
            provider.NumberDecimalSeparator = ".";

            IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();

            // open isolated storage, and read the savefile.
            if (savegameStorage.FileExists(fileName))
            {
                using (IsolatedStorageFileStream fs = savegameStorage.OpenFile(fileName, System.IO.FileMode.Open))
				{
					LoadLevel(fs);
                }
            }
        }

        /// <summary>
        /// Enables user control
        /// </summary>
        public void EnableControl()
        {
            rotationData.EnableRotation();
        }

		private void LoadLevel(Stream stream)
		{
			using (StreamReader reader = new StreamReader(stream))
			{
				while (!reader.EndOfStream)
				{
					string line = reader.ReadLine();
					string[] pieces = line.Split(':');

					if (pieces.Length >= 3)
					{
						float x = (float)Convert.ToDouble(pieces[1], provider);
						float y = (float)Convert.ToDouble(pieces[2], provider);
						float angle = 0;

						if (pieces.Length > 3)
							angle = (float)Convert.ToDouble(pieces[3], provider);

						switch (pieces[0])
						{
							case "start":
								bike.SetInitPos(x, y);
								break;
							case "grass":
								Add(LevelComponentType.grass, x, y, angle / Level.DEG_TO_RAD);
								break;
							case "jump":
								Add(LevelComponentType.jump, x, y, angle / Level.DEG_TO_RAD);
								break;
							case "nail":
								Add(LevelComponentType.nail, x, y, angle / Level.DEG_TO_RAD);
								break;
							case "finish":
								Add(LevelComponentType.finish, x, y, angle / Level.DEG_TO_RAD);
								break;
						}
					}
				}
			}
		}

        /// <summary>
        /// Create a new empty level with no components in it
        /// </summary>
        /// <param name="pAudioPlayer">The AudioPlayer intance that playes all the sound
        ///                            effects</param>
        /// <param name="pContent">Used ContentManager</param>
        public Level(AudioPlayer pAudioPlayer, ContentManager pContent)
        {
            content = pContent;
            audioPlayer = pAudioPlayer;
            world = new World(new Vector2(0.0f, 5.0f), true);
            world.ContactListener = this;
            rotationData = new RotationData();
            bike = new Bike(bikeSpeed, rotationData, world, camPos, content);
        }

        /// <summary>
        /// A callback function for Box2D to inform that two shapes are beginning to contact with
        /// each other. Collects the information of the contacts and that information will be
        /// handled after the physics simulation iterations are completed.
        /// </summary>
        /// <param name="contact">Box2D Contact</param>
        public virtual void BeginContact(Contact contact)
        {
            if (!bike.OffTheBike)
            {
                UserData data = (UserData)contact.GetFixtureA().GetBody().GetUserData();
                if (data != null)
                {
					if (data.Name == "finish")
					{
						if (Win != null)
							Win(this);
					}
					else if (data.Name == "nail")
					{
						if (TireFail != null)
							TireFail(this);
					}
					else if ( (data.Name == "head" && contact.GetFixtureB().GetBody().GetType() == BodyType.Static) ||
					          (data.Name == null && ((UserData)contact.GetFixtureB().GetBody().GetUserData()).Name == "head") )
					{
						bikeShouldBeReleased = true;

						if (HeadFail != null)
							HeadFail(this);
					}
                }
            }
        }

        /// <summary>
        /// This is one the methods of the IContactListener interface.
        /// No implementation.
        /// </summary>
        /// <param name="contact">Box2D Contact</param>
        public virtual void EndContact(Contact contact)
        {
        }

        /// <summary>
        /// This is one the methods of the IContactListener interface.
        /// No implementation.
        /// </summary>
        /// <param name="contact">Box2D Contact</param>
        /// <param name="oldManifold">Box2D Manifold</param>
        public void PreSolve(Contact contact, ref Manifold oldManifold)
        {
        }

        /// <summary>
        /// This is one the methods of the IContactListener interface.
        /// No implementation.
        /// </summary>
        /// <param name="contact">Box2D Contact</param>
        /// <param name="impulse">Box2D ContactImpulse</param>
        public void PostSolve(Contact contact, ref ContactImpulse impulse)
        {
        }

        /// <summary>
        /// Rotates the motorcycle counterclockwise
        /// </summary>
        public void leanBikeBackwards()
        {
            bike.leanBackwards();
        }

        /// <summary>
        /// Rotates the motorcycle clockwise
        /// </summary>
        public void leanBikeForwards()
        {
            bike.leanForwards();
        }

        /// <summary>
        /// Stops the rotation of the rear wheel
        /// </summary>
        public virtual void StopBikeMotor()
        {
            bike.StopMotor();
        }

        /// <summary>
        /// Stops the rotation of the rear wheel
        /// </summary>
        public virtual void ResetBike()
        {
            bike.Reset();
        }

        /// <summary>
        /// Makes the motorcycle to ignore the user inputs
        /// </summary>
        public virtual void disableBikeControls()
        {
            bike.disableControls();
        }

        /// <summary>
        /// Adds a new component to this level
        /// </summary>
        /// <param name="type">The type of the component</param>
        /// <param name="x">The x position of the component</param>
		/// <param name="y">The y position of the component</param>
        /// <param name="angle">The rotation angle of the component</param>
        /// <returns></returns>
        public LevelComponent Add(LevelComponentType type, float x, float y, float angle)
        {
			Vector2 pos = new Vector2(x, y);
			LevelComponent component = null;

			switch (type)
            {
                case LevelComponentType.grass:
                    component = new Ground(world, content, pos, angle, 400, 60);
                    break;
                case LevelComponentType.jump:
                    component = new Jump(world, content, pos, angle, 150, 85);
					break;
                case LevelComponentType.nail:
                    component = new SpikeMat(world, content, pos, angle, 250, 70);
					break;
                case LevelComponentType.finish:
                    component = new Finish(world, content, pos, angle, 100, 200);
					break;
            }

			if (component != null)
				components.Add(component);

			return component;
        }

        /// <summary>
        /// Updates the whole game world and components in it. Tells Box2D to simulate the physics
        /// one step forward. Updates the graphics tranformation matrix correspongin to the speed
        /// and position of the motorcycle.
        /// </summary>
        public virtual void Update()
        {
            world.Step(0.016666f, 10, 10);
            if (bikeShouldBeReleased)
            {
                bike.Release();
                bikeShouldBeReleased = false;
            }
            world.ClearForces();

            zoom = 0.96f * zoom - bikeSpeed[0] * 0.003333f + 0.056f;
            transform.M11 = zoom;
            transform.M22 = zoom;
            transform.M41 = -camPos[0] * zoom + 300;
            transform.M42 = -camPos[1] * zoom + 350;

            audioPlayer.SetMotorPitch(bikeSpeed[1] * 0.05f - 1);
            bike.Update();
        }

		public virtual void Draw(SpriteBatch spriteBatch)
		{
			spriteBatch.End();
			spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null,
							  null, transform);

			for (int i = 0; i < components.Count; i++)
				components[i].Draw(spriteBatch);

			spriteBatch.End();
			spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, transform);
			bike.Draw(spriteBatch);
			spriteBatch.End();
			spriteBatch.Begin();
		}
	}
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using System.IO.IsolatedStorage;
using Box2D.XNA;
using MotoTrialRacer.UI;
using MotoTrialRacer.Components;
using System.IO;

namespace MotoTrialRacer
{
    /// <summary>
    /// The class that defines the level editor.
    /// Derives from Level.
    /// Implement the ButtonListener interface.
    /// </summary>
    class LevelEditor : Level
    {
		public event Action<bool> Ready;

        private Button grassButton;
        private Vector2 grassButtonPos = new Vector2(190, 10);
        private Button jumpButton;
        private Vector2 jumpButtonPos = new Vector2(350, 10);
        private Button nailButton;
        private Vector2 nailButtonPos = new Vector2(530, 10);
        private Button finishButton;
        private Vector2 finishButtonPos = new Vector2(650, 10);
        private Button testButton;
        private Vector2 testButtonPos = new Vector2(350, 430);
        private Button saveButton;
        private Vector2 saveButtonPos = new Vector2(685, 430);
        private Button closeButton;
        private Vector2 closeButtonPos = new Vector2(310, 400);
        private Button backButton;
        private Vector2 backButtonPos = new Vector2(10, 430);
        private Button zoomButton;
        private Vector2 zoomButtonPos = new Vector2(10, 220);
        private Button unZoomButton;
        private Button activeZoomButton;
        private Vector2 lastPos = Vector2.Zero;
        private Vector2 zoomStartPos;
        private Texture2D bikePosTexture;
        private Rectangle bikePosDestination;
        private Rectangle bikePosActiveDestination = new Rectangle(58, 23, 70, 70);
        private Rectangle bikePosUnActiveDestination = new Rectangle(58, 23, 64, 64);
        private bool testing = false;
        private bool isReady = false;

        /// <summary>
        /// Creates a new level editor.
        /// </summary>
        /// <param name="audioPlayer">The AudioPlayer intance
        ///                           that playes all the sound effects</param>
        /// <param name="content">Used ContentManager</param>
        /// <param name="pSpriteBatch">Used SpriteBatch</param>
        public LevelEditor(AudioPlayer audioPlayer, ContentManager content)
            : base(audioPlayer, content)
        {
            bikePosTexture = content.Load<Texture2D>("Images/bikePos");
            bikePosDestination = bikePosUnActiveDestination;
            bike.SetInitPos(bikePosDestination.X, bikePosDestination.Y);

			CreateUI(content);

			activeZoomButton = unZoomButton;
            TireFail += new Action<Level>(CloseTesting);
			HeadFail += new Action<Level>(CloseTesting);
			Win += new Action<Level>(CloseTesting);
        }

		private void CreateUI(ContentManager content)
		{
			grassButton = new Button("grass", grassButtonPos, content, true);
			grassButton.Width = 100;
			grassButton.Height = 80;
			grassButton.ButtonPressed += new Action<Button>(grassButton_ButtonPressed);

			jumpButton = new Button("jump", jumpButtonPos, content, true);
			jumpButton.Width = 100;
			jumpButton.Height = 80;
			jumpButton.ButtonPressed += new Action<Button>(jumpButton_ButtonPressed);

			nailButton = new Button("nail", nailButtonPos, content, true);
			nailButton.Width = 50;
			nailButton.Height = 80;
			nailButton.ButtonPressed += new Action<Button>(nailButton_ButtonPressed);

			finishButton = new Button("finish", finishButtonPos, content, true);
			finishButton.Width = 100;
			finishButton.Height = 80;
			finishButton.ButtonPressed += new Action<Button>(finishButton_ButtonPressed);

			saveButton = new Button("save", saveButtonPos, content, true);
			saveButton.Width = 100;
			saveButton.Height = 43;
			saveButton.ButtonPressed += new Action<Button>(saveButton_ButtonPressed);

			backButton = new Button("back", backButtonPos, content, true);
			backButton.Width = 70;
			backButton.Height = 43;
			backButton.ButtonPressed += new Action<Button>(backButton_ButtonPressed);

			closeButton = new Button("ok", closeButtonPos, content);
			closeButton.Width = 200;
			closeButton.Height = 100;
			closeButton.ButtonPressed += new Action<Button>(closeButton_ButtonPressed);

			testButton = new Button("test", testButtonPos, content, true);
			testButton.Width = 88;
			testButton.Height = 43;
			testButton.ButtonPressed += new Action<Button>(testButton_ButtonPressed);

			zoomButton = new Button("zoom", zoomButtonPos, content, true);
			zoomButton.ButtonPressed += new Action<Button>(zoomButton_ButtonPressed);

			unZoomButton = new Button("unZoom", zoomButtonPos, content, true);
			unZoomButton.ButtonPressed += new Action<Button>(unZoomButton_ButtonPressed);
		}

		void unZoomButton_ButtonPressed(Button obj)
		{
			zoomStartPos.X = camPos[0];
			zoomStartPos.Y = camPos[1];
			zoom = 0.5f;
			camPos[0] -= zoom * 840;
			camPos[1] -= zoom * 400;
			activeZoomButton = zoomButton;
		}

		void zoomButton_ButtonPressed(Button obj)
		{
			activeZoomButton = unZoomButton;
			zoom = 1.0f;
			camPos[0] = zoomStartPos.X;
			camPos[1] = zoomStartPos.Y;
		}

		void testButton_ButtonPressed(Button obj)
		{
			bike.Reset();
			zoomStartPos.X = camPos[0];
			zoomStartPos.Y = camPos[1];
			testing = true;
            EnableControl();
			audioPlayer.PlayMotor();
		}

		void closeButton_ButtonPressed(Button obj)
		{
			camPos[0] = zoomStartPos.X;
			camPos[1] = zoomStartPos.Y;
			zoom = 1;
			testing = false;
			audioPlayer.StopMotor();
		}

		void backButton_ButtonPressed(Button obj)
		{
			if (Ready != null)
				Ready(false);
		}

		void saveButton_ButtonPressed(Button obj)
		{
			if (Ready != null)
				Ready(true);

			bike.Reset();
			testing = true;
			isReady = true;
		}

		void finishButton_ButtonPressed(Button obj)
		{
			float x = finishButtonPos.X + finishButton.Width * 0.5f + camPos[0];
			float y = finishButtonPos.Y + finishButton.Height * 1.5f + camPos[1];

			Add(LevelComponentType.finish, x, y, 0).SetCamPos(camPos);
		}

		void nailButton_ButtonPressed(Button obj)
		{
			float x = nailButtonPos.X + nailButton.Width * 0.5f + camPos[0];
			float y = nailButtonPos.Y + nailButton.Height * 1.5f + camPos[1];

			Add(LevelComponentType.nail, x, y, 0).SetCamPos(camPos);
		}

		void jumpButton_ButtonPressed(Button obj)
		{
			float x = jumpButtonPos.X + camPos[0];
			float y = jumpButtonPos.Y + jumpButton.Height * 1.0f + camPos[1];

			Add(LevelComponentType.jump, x, y, 0).SetCamPos(camPos);
		}

		void grassButton_ButtonPressed(Button obj)
		{
			float x = grassButtonPos.X + grassButton.Width * 0.5f + camPos[0];
			float y = grassButtonPos.Y + grassButton.Height * 1.5f + camPos[1];

			Add(LevelComponentType.grass, x, y, 0).SetCamPos(camPos);
		}

        /// <summary>
        /// Updates all the buttons and level components in the level editor.
        /// If a button or a level component reacts somehow to the touch this
        /// function returns immediately and rest of the buttons/level components
        /// doesn't get updated.
        /// </summary>
        public override void Update()
        {
            transform.M11 = zoom;
            transform.M22 = zoom;
            transform.M41 = -camPos[0] * zoom;
            transform.M42 = -camPos[1] * zoom;
            if (testing)
            {
                base.Update();
                if (!testing)
					closeButton_ButtonPressed(null);

                if (!isReady)
                {
                    TouchCollection touchCollection = TouchPanel.GetState();
                    if (touchCollection.Count > 0)
                    {
                        closeButton.Update(touchCollection[0]);
                    }
                }
            }
            else
            {
                TouchCollection touchCollection = TouchPanel.GetState();
                if (touchCollection.Count > 0)
                {
                    if (backButton.Update(touchCollection[0]))
                        return;
                    if (saveButton.Update(touchCollection[0]))
                        return;
                    if (testButton.Update(touchCollection[0]))
                        return;
                    if (activeZoomButton.Update(touchCollection[0]))
                        return;
                    if (zoom == 1)
                    {
                        if (grassButton.Update(touchCollection[0]))
                            return;
                        if (jumpButton.Update(touchCollection[0]))
                            return;
                        if (nailButton.Update(touchCollection[0]))
                            return;
                        if (finishButton.Update(touchCollection[0]))
                            return;
                        for (int i = components.Count - 1; i >= 0; i--)
                            if (components[i].Update(touchCollection[0]))
                            {
                                if (touchCollection.Count > 1)
                                {
                                    float dY = touchCollection[1].Position.Y -
                                               touchCollection[0].Position.Y;
                                    float dX = touchCollection[1].Position.X -
                                               touchCollection[0].Position.X;
                                    float angle = (float)Math.Atan2(dY, dX);
                                    float width = (float)Math.Sqrt(dX * dX + dY * dY);
                                    components[i].SetAngle(angle);
                                }
                                if (!bike.RotationData.device)
                                {
                                    KeyboardState keyboardState = Keyboard.GetState();
                                    if (keyboardState.IsKeyDown(Keys.A))
                                        components[i].SetAngle(components[i].Angle -
                                                               1*Level.DEG_TO_RAD);
                                    if (keyboardState.IsKeyDown(Keys.D))
                                        components[i].SetAngle(components[i].Angle +
                                                               1*Level.DEG_TO_RAD);
                                }
                                return;
                            }
                        if (touchCollection[0].State == TouchLocationState.Pressed &&
                            bikePosDestination.Contains(new Point((int)(
                                                        touchCollection[0].Position.X + camPos[0]),
                            (int)(touchCollection[0].Position.Y + camPos[1]))))
                        {
                            bikePosDestination = bikePosActiveDestination;
                        }
                        else if (touchCollection[0].State == TouchLocationState.Released)
                        {
                            bikePosDestination = bikePosUnActiveDestination;
                            bike.SetInitPos(bikePosDestination.X, bikePosDestination.Y);
                        }
                        if (bikePosDestination == bikePosActiveDestination)
                        {
                            int x = (int)(touchCollection[0].Position.X -
                                          0.5*bikePosTexture.Width + camPos[0]);
                            int y = (int)(touchCollection[0].Position.Y -
                                          0.5*bikePosTexture.Height + camPos[1]);
                            bikePosDestination.X = x;
                            bikePosDestination.Y = y;
                            bikePosActiveDestination.X = x;
                            bikePosActiveDestination.Y = y;
                            bikePosUnActiveDestination.X = x;
                            bikePosUnActiveDestination.Y = y;
                            return;
                        }
                    }
                    if (lastPos.Equals(Vector2.Zero))
                        lastPos = touchCollection[0].Position;
                    camPos[0] -= touchCollection[0].Position.X - lastPos.X;
                    camPos[1] -= touchCollection[0].Position.Y - lastPos.Y;
                    lastPos = touchCollection[0].Position;
                }
                else
                    lastPos = Vector2.Zero;
            }
        }

        /// <summary>
        /// A callback funtion to stop the testing of the level and return to the modifying view
        /// </summary>
		/// <param name="level">The caller of this function</param>
        public void CloseTesting(Level level)
        {
            if (!isReady)
			{
                testing = false;
                audioPlayer.StopMotor();
            }
        }

        /// <summary>
        /// Saves the definitions of the created level to a file
        /// </summary>
        /// <param name="name">The name of the level</param>
        /// <returns>Return true if the saving succeeded, false otherwise</returns>
        public bool SaveToFile(String name)
        {
            String fileName = name.Replace(' ', '_') + ".lvl";
            IsolatedStorageFile recordsStorage = IsolatedStorageFile.GetUserStoreForApplication();
            if (recordsStorage.FileExists(fileName) || name == "level1" ||
                                          name == "level2" || name == "level3")
                return false;

            using (IsolatedStorageFileStream fileStream = recordsStorage.OpenFile(fileName, System.IO.FileMode.Create))
			{
				using (StreamWriter writer = new StreamWriter(fileStream))
				{
					writer.WriteLine(string.Format("start:{0}:{1}", bikePosDestination.X, bikePosDestination.Y));

					foreach (var c in components)
					{
						string s = string.Format("{0}:{1}:{2}:{3}", c.Name, c.Pos.X, c.Pos.Y, c.Angle);
						writer.WriteLine(s);
					}
				}
            }
            return true;
        }

        /// <summary>
        /// An empty implementation because the motorcycle is wanted
        /// to behave differently in level editor than in other levels
        /// </summary>
        public override void StopBikeMotor()
        {
        }

        /// <summary>
        /// An empty implementation because the motorcycle is wanted to
        /// behave differently in level editor than in other levels
        /// </summary>
        public override void ResetBike()
        {
        }

        /// <summary>
        /// Draws all the buttons and level components in the level editor
        /// </summary>
        public override void Draw(SpriteBatch spriteBatch)
        {
            if (testing)
            {
				base.Draw(spriteBatch);
                if (!isReady)
					closeButton.Draw(spriteBatch);
            }
            else
            {
                spriteBatch.End();
                spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap,
                                  null, null, null, transform);
                for (int i = 0; i < components.Count; i++)
                    components[i].Draw(spriteBatch);
                spriteBatch.Draw(bikePosTexture, bikePosDestination, Color.White);
                spriteBatch.End();
                spriteBatch.Begin();
				grassButton.Draw(spriteBatch);
				jumpButton.Draw(spriteBatch);
				nailButton.Draw(spriteBatch);
				finishButton.Draw(spriteBatch);
				saveButton.Draw(spriteBatch);
				testButton.Draw(spriteBatch);
				backButton.Draw(spriteBatch);
				activeZoomButton.Draw(spriteBatch);
            }
        }
    }
}


code:
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <ProjectGuid>{AA22069A-4109-4E67-BFA1-473BECB8C98F}</ProjectGuid>
    <ProjectTypeGuids>{6D335F3A-9D43-41b4-9D22-F6F17C4BE596};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">Windows Phone</Platform>
    <OutputType>Library</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>MotoTrialRacer</RootNamespace>
    <AssemblyName>MotoTrialRacer</AssemblyName>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
	<XnaRefreshLevel>1</XnaRefreshLevel>
    <TargetFrameworkProfile>Client</TargetFrameworkProfile>
    <XnaFrameworkVersion>v4.0</XnaFrameworkVersion>
    <XnaPlatform>Windows Phone</XnaPlatform>
    <XnaProfile>Reach</XnaProfile>
    <XnaCrossPlatformGroupID>255ce0c4-7c16-4d26-8681-2b5f40d46814</XnaCrossPlatformGroupID>
    <XnaOutputType>Game</XnaOutputType>
    <XapFilename>$(AssemblyName).xap</XapFilename>
    <SilverlightManifestTemplate>Properties\AppManifest.xml</SilverlightManifestTemplate>
    <XnaWindowsPhoneManifestTemplate>Properties\WMAppManifest.xml</XnaWindowsPhoneManifestTemplate>
    <TileImage>MotoTrial.png</TileImage>
    <TileTitle>MotoTrialRacer</TileTitle>
    <SupportedCultures>
    </SupportedCultures>
    <ApplicationIcon>Game.ico</ApplicationIcon>
    <Thumbnail>MotoTrial.png</Thumbnail>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|Windows Phone' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Windows Phone\Debug</OutputPath>
    <DefineConstants>DEBUG;TRACE;WINDOWS_PHONE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <NoStdLib>true</NoStdLib>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <XnaCompressContent>false</XnaCompressContent>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|Windows Phone' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Windows Phone\Release</OutputPath>
    <DefineConstants>TRACE;WINDOWS_PHONE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <NoStdLib>true</NoStdLib>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <XnaCompressContent>false</XnaCompressContent>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Microsoft.Devices.Sensors, Version=7.0.0.0, Culture=neutral, PublicKeyToken=24eec0d8c86cda1e, processorArchitecture=MSIL" />
    <Reference Include="Microsoft.Phone, Version=7.0.0.0, Culture=neutral, PublicKeyToken=24eec0d8c86cda1e, processorArchitecture=MSIL" />
    <Reference Include="Microsoft.Xna.Framework">
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.Xna.Framework.Game">
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.Xna.Framework.Graphics">
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.Xna.Framework.GamerServices">
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.Xna.Framework.Input.Touch">
      <Private>False</Private>
    </Reference>
    <Reference Include="mscorlib">
      <Private>False</Private>
    </Reference>
    <Reference Include="System">
      <Private>False</Private>
    </Reference>
    <Reference Include="System.Xml">
      <Private>False</Private>
    </Reference>
    <Reference Include="System.Core">
      <Private>False</Private>
    </Reference>
    <Reference Include="System.Xml.Linq">
      <Private>False</Private>
    </Reference>
    <Reference Include="System.Net">
      <Private>False</Private>
    </Reference>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="AudioPlayer.cs" />
    <Compile Include="Bike.cs" />
    <Compile Include="IDrawable.cs" />
    <Compile Include="UI\Button.cs" />
    <Compile Include="LevelEditor.cs" />
    <Compile Include="Components\Finish.cs" />
    <Compile Include="Components\Ground.cs" />
    <Compile Include="UserData.cs" />
    <Compile Include="Views\HighScores.cs" />
    <Compile Include="Views\InfoView.cs" />
    <Compile Include="Components\Jump.cs" />
    <Compile Include="Level.cs" />
    <Compile Include="Components\LevelComponent.cs" />
    <Compile Include="Views\LevelSaver.cs" />
    <Compile Include="Views\LevelSelector.cs" />
    <Compile Include="Views\Menu.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="RotationData.cs" />
    <Compile Include="RecordHandler.cs" />
    <Compile Include="Components\SpikeMat.cs" />
    <Compile Include="Views\SplashScreen.cs" />
    <Compile Include="UI\TextInput.cs" />
    <Compile Include="Views\View.cs" />
    <Compile Include="Views\WinView.cs" />
    <None Include="Properties\AppManifest.xml">
      <XnaPlatformSpecific>true</XnaPlatformSpecific>
    </None>
    <None Include="Properties\WMAppManifest.xml">
      <XnaPlatformSpecific>true</XnaPlatformSpecific>
    </None>
    <Compile Include="Program.cs" />
    <Compile Include="Game1.cs" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="Game.ico" />
    <Content Include="GameThumbnail.png" />
    <Content Include="Background.png">
      <XnaPlatformSpecific>true</XnaPlatformSpecific>
    </Content>
    <Content Include="MotoTrial.png" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\..\Box2D.XNA\Box2D.XNA - wp7.csproj">
      <Project>{066846BE-AAEA-4EB6-BAA8-2D6B60B3BDB3}</Project>
      <Name>Box2D.XNA - wp7</Name>
    </ProjectReference>
    <ProjectReference Include="..\MotoTrialRacerContent\MotoTrialRacerContent.contentproj">
      <Name>MotoTrialRacerContent</Name>
      <XnaReferenceType>Content</XnaReferenceType>
    </ProjectReference>
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="$(MSBuildExtensionsPath)\Microsoft\XNA Game Studio\Microsoft.Xna.GameStudio.targets" />
  <PropertyGroup>
    <PreBuildEvent>
    </PreBuildEvent>
  </PropertyGroup>
  <PropertyGroup>
    <PostBuildEvent>
    </PostBuildEvent>
  </PropertyGroup>
  <!--
      To modify your build process, add your task inside one of the targets below and uncomment it.
      Other similar extension points exist, see Microsoft.Common.targets.
      <Target Name="BeforeBuild">
      </Target>
      <Target Name="AfterBuild">
      </Target>
    -->
</Project>


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;

namespace MotoTrialRacer
{
#if WINDOWS || XBOX
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            using (Game1 game = new Game1())
            {
                game.Run();
            }
        }
    }
#endif
}


code:
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
    <Deployment.Parts>
    </Deployment.Parts>
</Deployment>


code:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MotoTrialRacer")]
[assembly: AssemblyProduct("MotoTrialRacer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyCopyright("Copyright © 2011 Nokia Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]

// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("77160c64-1360-47c4-9638-04813e595fce")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
[assembly: AssemblyVersion("1.0.0.0")]


code:
<?xml version="1.0" encoding="utf-8" ?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2009/deployment" AppPlatformVersion="7.0">
  <App xmlns="" ProductID="{77160c64-1360-47c4-9638-04813e595fce}" Title="MotoTrialRacer" RuntimeType="XNA" Version="1.0.0.0" Genre="Apps.Normal" Author="" Description="" Publisher="">
    <IconPath IsRelative="true" IsResource="false"></IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_NETWORKING" />
      <Capability Name="ID_CAP_LOCATION" />
      <Capability Name="ID_CAP_SENSORS" />
      <Capability Name="ID_CAP_MICROPHONE" />
      <Capability Name="ID_CAP_MEDIALIB" />
      <Capability Name="ID_CAP_GAMERSERVICES" />
      <Capability Name="ID_CAP_PHONEDIALER" />
      <Capability Name="ID_CAP_PUSH_NOTIFICATION" />
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
      <Capability Name="ID_CAP_IDENTITY_USER" />
      <Capability Name="ID_CAP_IDENTITY_DEVICE" />
    </Capabilities>
    <Tasks>
      <DefaultTask Name="_default"/>
    </Tasks>
    <Tokens>
      <PrimaryToken TokenID="MotoTrialRacerToken" TaskName="_default">
        <TemplateType5>
          <BackgroundImageURI IsRelative="true" IsResource="false"></BackgroundImageURI>
          <Count>0</Count>
          <Title></Title>
        </TemplateType5>
      </PrimaryToken>
    </Tokens>
  </App>
</Deployment>


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework;
using System.IO;

namespace MotoTrialRacer
{
    /// <summary>
    /// The stucture of the high score records
    /// </summary>
    struct Record
    {
        public string Name;
        public int Time;
    }

    /// <summary>
    /// This class handles all the high scores
    /// </summary>
    class RecordHandler
    {
		public List<Record> Records { get; private set; }

		private string fileName;
		private const char dataSeparator = ':';

        /// <summary>
        /// Creates a new record handler
        /// </summary>
        /// <param name="levelName">The name of the level
        ///                         which records this instance handles</param>
        public RecordHandler(String levelName)
        {
            fileName = levelName + ".scr";
			Records = new List<Record>();
        }

        /// <summary>
        /// Loads the records to memory.
        /// If there isn't any records yet, this method will create them.
        /// </summary>
        public void LoadRecords()
        {
            Load();

			if (Records.Count == 0)
			{
				CreateRecords();
				SaveRecords();
			}
        }

        /// <summary>
        /// Gets the placement of the player with specific level completion time
        /// </summary>
        /// <param name="time">The time in which the player has completed the level</param>
        /// <returns>The placement of the player</returns>
        public int GetPlacement(int time)
        {
            if (time < Records[0].Time)
                return 1;

            for (int i = 0; i < Records.Count-1; i++)
            {
                if (Records[i].Time < time && time < Records[i + 1].Time)
                    return i+2;
            }
            return -1;
        }

        /// <summary>
        /// Saves the records to IsolatedStorage
        /// </summary>
        public void SaveRecords()
        {
            IsolatedStorageFile recordsStorage = IsolatedStorageFile.GetUserStoreForApplication();

            using (IsolatedStorageFileStream fileStream = recordsStorage.OpenFile(fileName, System.IO.FileMode.Create))
			{
				using (StreamWriter writer = new StreamWriter(fileStream))
				{
					foreach (Record r in Records)
						writer.WriteLine(r.Name + dataSeparator + r.Time);
				}
            }
        }

        /// <summary>
        /// Sets a new record
        /// </summary>
        /// <param name="placement">The placement of the record</param>
        /// <param name="name">The name of the player</param>
        /// <param name="time">The level completion time of the player</param>
        public void SetRecord(int placement, string name, int time)
        {
            for (int i = Records.Count-1; i > placement-1; i--)
            {
                Records[i] = Records[i - 1];
            }
            Records[placement - 1] = new Record {Name = name, Time = time};
        }

        /// <summary>
        /// Loads the records from IsolatedStorage
        /// </summary>
        private void Load()
        {
            IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();

            // open isolated storage, and write the savefile.
            if (savegameStorage.FileExists(fileName))
            {
                using (IsolatedStorageFileStream fs = savegameStorage.OpenFile(fileName, System.IO.FileMode.Open))
				{
					using (StreamReader r = new StreamReader(fs))
					{
						string text = r.ReadToEnd();
						string[] rows = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

						foreach (string row in rows)
						{
							string[] pieces = row.Split(dataSeparator);

							Records.Add(new Record	{
														Name = pieces[0],
														Time = Convert.ToInt32(pieces[1])
													});
						}
					}
                }
            }
        }

        /// <summary>
        /// Creates new records and initializes them with player
        /// name "Racer" and level completion time one minute
        /// </summary>
        private void CreateRecords()
        {
			for (int i = 0; i < 10; i++)
				Records.Add(new Record() { Name = "Racer" + (i + 1), Time = 60000 });
        }
    }
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Devices;
using Microsoft.Devices.Sensors;

namespace MotoTrialRacer
{
    /// <summary>
    /// This class handles the acceleration sensor data of the device
    /// </summary>
    public class RotationData
    {
#if WINDOWS_PHONE
        private Accelerometer accelerometer = new Accelerometer();
#endif
        private static object threadLock = new object();
        public bool device = (Microsoft.Devices.Environment.DeviceType == DeviceType.Device);
        public float xRot, yRot;

        /// <summary>
        /// Enables handling rotation data. Creates a new acceleration sensor data handler.
        /// If called using an emulator, won't do anything.
        /// </summary>
        public void EnableRotation()
        {
#if WINDOWS_PHONE
            if (device)
            {
                try
                {
                    accelerometer.ReadingChanged +=
                        new EventHandler<AccelerometerReadingEventArgs>(sensor_ReadingChanged);
                    accelerometer.Start();
                }
                catch (Microsoft.Devices.Sensors.AccelerometerFailedException)
                {
                }
            }
#endif
        }

#if WINDOWS_PHONE
        /// <summary>
        /// A callback function for Accelerometer to notify that the sensor reading has changed.
        /// This method reads the acceleration along the x axis, then scales and clamp it between
        /// 0 and -30.
        /// </summary>
        /// <param name="sender">The caller of this function</param>
        /// <param name="e">the parameter wich holds the data of the sensor</param>
        private void sensor_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            lock (threadLock)
            {
                if (e.X < -0.6)
                {
                    xRot = -30.0f;
                    return;
                }
                if (e.X > 0)
                {
                    xRot = 0;
                    return;
                }
                xRot = (float)e.X / 0.6f * 30.0f;
            }
        }
#endif
    }
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;

namespace MotoTrialRacer.UI
{
    /// <summary>
    /// The class that defines a button UI component
    /// </summary>
    class Button : IDrawable
    {
		public event Action<Button> ButtonPressed;
		public event Action<Button> ButtonLongPressed;

		public String Name { get; private set; }

        private int width;
        private int height;
        private Rectangle destination;
        private Rectangle pressedDestination;
        private Rectangle currentDestination;
        private Texture2D currentTexture;
        private Texture2D texture;
        private Texture2D pressedTexture;
        private Vector2 position;
        private SpriteFont font;
        private int pressedTime = 0;

        /// <summary>
        /// Creates a new button that has an image in Content for up and pressed states
        /// If the images name is for example "image.png" the pressed state image has to be
        /// "image_selected.png"
        /// </summary>
        /// <param name="pName">The name of the image in Content</param>
        /// <param name="pListener">The listener for this button</param>
        /// <param name="pos">The position of this button</param>
        /// <param name="contentManager">Used ContentManager</param>
        /// <param name="pSpriteBatch">Used SpriteBatch</param>
        public Button(String pName, Vector2 pos,
                      ContentManager contentManager)
        {
            position = pos;
            Name = pName;
            texture = contentManager.Load<Texture2D>("Images/" + Name);
            currentTexture = texture;
            pressedTexture = contentManager.Load<Texture2D>("Images/" + Name + "_select");
            width = texture.Width;
            height = texture.Height;
            destination = new Rectangle((int)position.X, (int)position.Y, width, height);
            currentDestination = destination;
            pressedDestination = new Rectangle((int)(position.X + 0.05f * width),
                                               (int)(position.Y + 0.05f * height),
                                               (int)(width * 0.9f), (int)(height * 0.9f));
        }

        /// <summary>
        /// Creates a new button that has an image in Content for up state only of doesn't an
        /// image at all
        /// </summary>
        /// <param name="pName">The name of the image in Content if there is one. Otherwise the
        ///                     text on the button</param>
        /// <param name="pListener">The listener for this button</param>
        /// <param name="pos">The position of this button</param>
        /// <param name="contentManager">Used ContentManager</param>
        /// <param name="pSpriteBatch">Used SpriteBatch</param>
        /// <param name="isTexture">To tell if there is an image for the button or not. True if
        ///                         there is, false otherwise</param>
        public Button(String pName, Vector2 pos,
                      ContentManager contentManager, bool isTexture)
        {
            position = pos;
            Name = pName;
            if (isTexture)
            {
                texture = contentManager.Load<Texture2D>("Images/" + Name);
                currentTexture = texture;
                pressedTexture = null;
                width = texture.Width;
                height = texture.Height;
                destination = new Rectangle((int)position.X, (int)position.Y, width, height);
                currentDestination = destination;
                pressedDestination = new Rectangle((int)(position.X + 0.05f * width),
                                                   (int)(position.Y + 0.05f * height),
                                                   (int)(width * 0.9f), (int)(height * 0.9f));
            }
            else
            {
                font = contentManager.Load<SpriteFont>("SpriteFont2");
                Vector2 dims = font.MeasureString(Name);
                width = (int)(dims.X*1.1f);
                height = (int)(dims.Y*1.05f);

				RenderTarget2D renderTarget = new RenderTarget2D(Game1.Graphics.GraphicsDevice, width, height);
				SpriteBatch spriteBatch = new SpriteBatch(Game1.Graphics.GraphicsDevice);
                spriteBatch.GraphicsDevice.SetRenderTarget(renderTarget);

                Texture2D bgTexture = new Texture2D(spriteBatch.GraphicsDevice, width, height);
                Color[] colors = new Color[width * height];
                for (int i = 0; i < colors.Length; i++)
                {
                    if (i < 2 * width || colors.Length - 2 * width < i ||
                        i % width < 2 || width - 3 < i % width)
                        colors[i] = Color.Yellow;
                    else
                        colors[i] = Color.Transparent;
                }
                destination = new Rectangle((int)pos.X, (int)pos.Y, width, height);
                bgTexture.SetData<Color>(colors);
                spriteBatch.Begin();
                spriteBatch.Draw(bgTexture, Vector2.Zero, Color.White);
                spriteBatch.DrawString(font, Name, new Vector2(width*0.5f - dims.X*0.5f,
                                                               height*0.5f - dims.Y*0.5f),
                                       Color.Yellow);
                spriteBatch.End();

                spriteBatch.GraphicsDevice.SetRenderTarget(null);
                texture = (Texture2D)renderTarget;

                texture.GetData<Color>(colors);

                for (int i = 0; i < colors.Length; i++)
                {
                    if (!colors[i].Equals(Color.Yellow))
                      colors[i] = Color.Transparent;
                }

                texture.SetData<Color>(colors);

                currentTexture = texture;
                pressedTexture = null;
                destination = new Rectangle((int)position.X, (int)position.Y, width, height);
                currentDestination = destination;
                pressedDestination = new Rectangle((int)(position.X + 0.05f * width),
                                                   (int)(position.Y + 0.05f * height),
                                                   (int)(width * 0.9f), (int)(height * 0.9f));
            }
        }

        public int Width
        {
            get
            {
                return width;
            }
            set
            {
                width = value;
                destination = new Rectangle((int)position.X, (int)position.Y, width, height);
                currentDestination = destination;
                pressedDestination = new Rectangle((int)(position.X + 0.05f * width),
                                                   (int)(position.Y + 0.05f * height),
                                                   (int)(width * 0.9f), (int)(height * 0.9f));
            }
        }

        public int Height
        {
            get
            {
                return height;
            }
            set
            {
                height = value;
                destination = new Rectangle((int)position.X, (int)position.Y, width, height);
                currentDestination = destination;
                pressedDestination = new Rectangle((int)(position.X + 0.05f * width),
                                                   (int)(position.Y + 0.05f * height),
                                                   (int)(width * 0.9f), (int)(height * 0.9f));
            }
        }

        public Vector2 Position
        {
            get
            {
                return position;
            }
            set
            {
                bool pressed = (currentDestination == pressedDestination);
                position = value;
                destination = new Rectangle((int)position.X, (int)position.Y, width, height);
                pressedDestination = new Rectangle((int)(position.X + 0.05f * width),
                                                   (int)(position.Y + 0.05f * height),
                                                   (int)(width * 0.9f), (int)(height * 0.9f));
                if (pressed)
                    currentDestination = pressedDestination;
                else
                    currentDestination = destination;
            }
        }

        public int X
        {
            get
            {
                return destination.X;
            }
            set
            {
                bool pressed = (currentDestination == pressedDestination);
                position.X = value;
                destination.X = value;
                pressedDestination.X = (int)(position.X + 0.05f * width);
                if (pressed)
                    currentDestination = pressedDestination;
                else
                    currentDestination = destination;
            }
        }

        public int Y
        {
            get
            {
                return destination.Y;
            }
            set
            {
                bool pressed = (currentDestination == pressedDestination);
                position.Y = value;
                destination.Y = value;
                pressedDestination.Y = (int)(position.Y + 0.05f * height);
                if (pressed)
                    currentDestination = pressedDestination;
                else
                    currentDestination = destination;
            }
        }

        /// <summary>
        /// Updates the button state.
        /// </summary>
        /// <param name="touchLocation">The location of the users touch</param>
        /// <returns>Returns true if the button asumes that the touch was dedicated to it,
        ///          false otherwise</returns>
        public bool Update(TouchLocation touchLocation)
        {
            if (currentDestination == pressedDestination)
            {
                pressedTime++;
                if (pressedTime > 120)
                {
					if (ButtonLongPressed != null)
						ButtonLongPressed(this);

					currentDestination = destination;
                    currentTexture = texture;
                    pressedTime = 0;
                    return true;
                }
            }
            if (destination.Contains(new Point((int)touchLocation.Position.X,
                                               (int)touchLocation.Position.Y)))
            {
                if (touchLocation.State == TouchLocationState.Pressed)
                {
                    if (pressedTexture != null)
                        currentTexture = pressedTexture;
                    currentDestination = pressedDestination;
                    return true;
                }
                if (touchLocation.State == TouchLocationState.Released &&
                    currentDestination == pressedDestination)
                {
                    currentDestination = destination;
                    currentTexture = texture;

					if (ButtonPressed != null)
						ButtonPressed(this);

                    pressedTime = 0;
                    return true;
                }
                return false;
            }
            if (touchLocation.State == TouchLocationState.Released)
            {
                currentDestination = destination;
                currentTexture = texture;
                pressedTime = 0;
                return false;
            }
            return false;
        }

		public virtual void Draw(SpriteBatch spriteBatch)
		{
			spriteBatch.Draw(currentTexture, currentDestination, Color.White);
		}
	}
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Input.Touch;

namespace MotoTrialRacer.UI
{
    /// <summary>
    /// This class defines the text input UI component
    /// </summary>
    class TextInput	: IDrawable
    {
		public String Text { get; set; }
		public String HintText { get; private set; }

        private SpriteFont font;
        private Color hintColor = new Color(1.0f, 1.0f, 0.0f, 0.0f);
        private Vector2 textPos;
        private Texture2D texture;
        private Rectangle destination;
        private int width;
        private int height;

        /// <summary>
        /// Creates a new text input UI component
        /// </summary>
        /// <param name="hint">The hint text that is shown when the text input is empty</param>
        /// <param name="pos">The position of the component</param>
        /// <param name="contentManager">Used ContentManager</param>
        /// <param name="spriteBatch">Used SpriteBatch</param>
        /// <param name="pWidth">The width of the component</param>
        /// <param name="pHeight">The height of the component</param>
        public TextInput(String hint, Vector2 pos, ContentManager contentManager, int pWidth, int pHeight)
        {
            HintText = hint;
            Text = HintText;
            width = pWidth;
            height = pHeight;
            texture = new Texture2D(Game1.Graphics.GraphicsDevice, width, height);
            Color[] colors = new Color[width * height];
            for (int i = 0; i < colors.Length; i++)
            {
                if (i < 2 * width || colors.Length - 2 * width < i ||
                    i % width < 2 || width - 3 < i % width)
                    colors[i] = new Color(1.0f, 1.0f, 0.0f, 1.0f);
                else
                    colors[i] = new Color(0.0f, 0.0f, 0.0f, 0.0f);
            }
            destination = new Rectangle((int)pos.X, (int)pos.Y, width, height);
            texture.SetData<Color>(colors);
            font = contentManager.Load<SpriteFont>("SpriteFont1");
            textPos = new Vector2(pos.X + width*0.1f,
                                  pos.Y + height*0.5f - font.MeasureString(HintText).Y*0.5f);
        }

        /// <summary>
        /// Checks if the text input is touched and if it is, then opens the virtual keyboard
        /// </summary>
        /// <param name="touchLocation">The touch location</param>
        public void Update(TouchLocation touchLocation)
        {
            if (destination.Contains(new Point((int)touchLocation.Position.X,
                                               (int)touchLocation.Position.Y)))
            {
                if (touchLocation.State == TouchLocationState.Pressed)
                {
                    if (!Guide.IsVisible)
                    {
                        if (Text == HintText)
                        {
                            Guide.BeginShowKeyboardInput(PlayerIndex.One, "Moto Trial Racer",
                                                         HintText, "",
                                                         delegate(IAsyncResult result)
                            {
                                String tempText = Guide.EndShowKeyboardInput(result);
                                if (tempText != null)
                                {
                                    if (tempText == "")
                                        Text = HintText;
                                    else
                                        Text = tempText;
                                }
                            }, null);
                        }
                        else
                        {
                            Guide.BeginShowKeyboardInput(PlayerIndex.One, "Moto Trial Racer",
                                                         HintText, Text,
                                                         delegate(IAsyncResult result)
                            {
                                String tempText = Guide.EndShowKeyboardInput(result);
                                if (tempText != null)
                                {
                                    if (tempText == "")
                                        Text = HintText;
                                    else
                                        Text = tempText;
                                }
                            }, null);
                        }
                    }
                }
            }
        }

		public virtual void Draw(SpriteBatch spriteBatch)
		{
			spriteBatch.Draw(texture, destination, Color.White);
			spriteBatch.DrawString(font, Text, textPos, hintColor);
		}
	}
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Box2D.XNA;
using System.IO;
using System.IO.IsolatedStorage;
using System.Globalization;
using MotoTrialRacer.Components;

namespace MotoTrialRacer
{
	/// <summary>
	/// The class for holding the information of LevelComponent bodies.
	/// </summary>
	class UserData
	{
		public String Name;
		public Texture2D Texture;
		public float Width;
		public float Height;

		public UserData(String pName, Texture2D pTexture)
		{
			Name = pName;
			Texture = pTexture;
		}
	}
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Graphics;
using MotoTrialRacer.UI;

namespace MotoTrialRacer
{
    /// <summary>
    /// This class defines the HighScores view.
    /// Derives from View.
    /// </summary>
    class HighScores : View
    {
        private Texture2D topic;
        private Vector2 topicPos;
        private Vector2 namePos;
        private String level;
        private Vector2 listPos = new Vector2(280, 130);
        private Button closeButton;
        private Button backButton;
        private RecordHandler recordHandler;
        private SpriteFont font;
        private String scoresList = "";

        /// <summary>
        /// Creates a new HighScores view
        /// </summary>
        /// <param name="game">The Game instance that will show this view</param>
        /// <param name="levelName">The name of the level which high scores this view will
        ///                         show</param>
        public HighScores(Game1 game, String levelName) : base(game)
        {
            level = levelName.Replace('_', ' ');
            recordHandler = new RecordHandler(level);
            recordHandler.LoadRecords();
            for (int i = 0; i < recordHandler.Records.Count; i++)
            {
                TimeSpan time = TimeSpan.FromMilliseconds(recordHandler.Records[i].Time);

                scoresList += (i + 1) + "  " + recordHandler.Records[i].Name + "  " +
                              String.Format("{0:d2}:{1:d2}:{2:d3}",
                                            time.Minutes, time.Seconds, time.Milliseconds) + "\n";
            }
            font = game.Content.Load<SpriteFont>("SpriteFont1");
            topic = game.Content.Load<Texture2D>("Images/highScores");
            topicPos = new Vector2(game.getWidth() * 0.5f - topic.Width * 0.5f, 0);
            namePos = new Vector2(game.getWidth() * 0.5f - font.MeasureString(level).X * 0.5f,
                                  topic.Height);

            closeButton = new Button("ok", new Vector2(game.getWidth() * 0.7f,
                                           game.getHeight() * 0.75f),
                                           game.Content);

            closeButton.Position = new Vector2(game.getWidth() * 0.5f - closeButton.Width * 0.5f,
                                               game.getHeight() * 0.78f);

			closeButton.ButtonPressed += new Action<Button>(closeButton_ButtonPressed);

            backButton = new Button("back", new Vector2(game.relativeX(10), game.relativeY(430)),
											game.Content,
											true);
            backButton.Width = 70; backButton.Height = 43;
			backButton.ButtonPressed += new Action<Button>(backButton_ButtonPressed);

        }

		void backButton_ButtonPressed(Button sender)
		{
			if (level != "level1" && level != "level2" && level != "level3")
				game.ShowMyLevelsSelector(false);
			else
				game.ShowLevelSelector(false);
		}

		void closeButton_ButtonPressed(Button sender)
		{
			game.OpenMenu();
		}

        /// <summary>
        /// Updates the buttons in this view
        /// </summary>
        public override void Update()
        {
            base.Update();
            closeButton.Update(touchLocation);
            backButton.Update(touchLocation);
        }

        /// <summary>
        /// Draws all the components in this view
        /// </summary>
        public override void Draw(SpriteBatch spriteBatch)
        {
			base.Draw(spriteBatch);
            spriteBatch.Draw(topic, topicPos, Color.White);
            spriteBatch.DrawString(font, level, namePos, Color.Yellow);
            spriteBatch.DrawString(font, scoresList, listPos, Color.Yellow);
			closeButton.Draw(spriteBatch);
			backButton.Draw(spriteBatch);
        }
    }
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using MotoTrialRacer.UI;

namespace MotoTrialRacer
{
    /// <summary>
    /// A view that shows the information about this application.
    /// Derives from View.
    /// </summary>
    class InfoView : View
    {
        private String infoText;
        private float textHeight;
        private Button closeButton;
        private Vector2 buttonPos = new Vector2(0, 0);
        private SpriteFont font;
        private Vector2 textPos;
        private float lastY = 0;
        private float speed = 0;
        private int minY = -700;
        private int maxY = 0;
        private bool dragging = false;

        /// <summary>
        /// Creates a new info view
        /// </summary>
        /// <param name="game">The Game instance that will show this view</param>
        public InfoView(Game1 game) : base(game)
        {
            maxY = (int)(game.getHeight() * 0.1f);
            infoText = game.Content.Load<String>(@"infotexts");
            font = game.Content.Load<SpriteFont>("SpriteFont1");
            textHeight = font.MeasureString(infoText).Y;
            textPos = new Vector2(game.getWidth() * 0.25f, game.getHeight() * 0.1f);
            closeButton = new Button("ok", buttonPos, game.Content);
			closeButton.ButtonPressed += new Action<Button>(closeButton_ButtonPressed);

            buttonPos = new Vector2(game.getWidth() * 0.5f - closeButton.Width * 0.5f,
                                    textPos.Y + textHeight);
            closeButton.Position = buttonPos;
        }

		void closeButton_ButtonPressed(Button sender)
		{
			game.OpenMenu();
		}

        /// <summary>
        /// Updates the position of the info text corresponding to the touch inputs of the user.
        /// This implements the "flickable" feature. Also updates the buttons in this view.
        /// </summary>
        public override void Update()
        {
            base.Update();
            if (touchChanged)
            {
                if (touchLocation.State == TouchLocationState.Pressed)
                {
                    dragging = true;
                    lastY = touchLocation.Position.Y;
                }
                else if (touchLocation.State == TouchLocationState.Released)
                {
                    dragging = false;
                }
                closeButton.Update(touchLocation);
            }
            if (dragging)
            {
                speed = lastY - touchLocation.Position.Y;
                lastY = touchLocation.Position.Y;
            }
            else
            {
                if (textPos.Y < minY)
                    if (speed > 0)
                        speed -= (minY - textPos.Y) * 0.02f;
                    else
                        speed = (textPos.Y - minY) * 0.1f;
                else if (maxY < textPos.Y)
                    if (speed < 0)
                        speed -= (maxY - textPos.Y) * 0.02f;
                    else
                        speed = (textPos.Y - maxY) * 0.1f;
            }
            textPos.Y -= speed;
            buttonPos.Y = textPos.Y + textHeight;
            closeButton.Y = (int)buttonPos.Y;
            speed *= 0.98f;
        }

        /// <summary>
        /// Draws all the components in this view
        /// </summary>
        public override void Draw(SpriteBatch spriteBatch)
        {
			base.Draw(spriteBatch);
            spriteBatch.DrawString(font, infoText, textPos, Color.Yellow);
			closeButton.Draw(spriteBatch);
        }
    }
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using MotoTrialRacer.UI;
using Microsoft.Xna.Framework.Graphics;

namespace MotoTrialRacer
{
    /// <summary>
    /// This class defines the view which is used for the saving of the user created custom levels
    /// Derives from View.
    /// </summary>
    class LevelSaver : View
    {
        private TextInput nameInput;
        private Button closeButton;

        /// <summary>
        /// Creates a new level saving view
        /// </summary>
        /// <param name="game">The Game instance that will show this view</param>
        public LevelSaver(Game1 game)
            : base(game)
        {
            nameInput = new TextInput("Enter the name of you level", new Vector2(200, 200),
                                      game.Content, 400, 50);
            closeButton = new Button("ok", new Vector2(300, 350), game.Content);
			closeButton.ButtonPressed += new Action<Button>(closeButton_ButtonPressed);
        }

		void closeButton_ButtonPressed(Button sender)
		{
			if (game.SaveLevel(nameInput.Text))
				game.OpenMenu();
			else
				nameInput.Text += " allready exists.";
		}

        /// <summary>
        /// Updates the name input and button UI components
        /// </summary>
        public override void Update()
        {
            base.Update();
            if (touchChanged)
            {
                nameInput.Update(touchLocation);
                closeButton.Update(touchLocation);
            }
        }

        /// <summary>
        /// Draws the name input and button UI components
        /// </summary>
		public override void Draw(SpriteBatch spriteBatch)
        {
			base.Draw(spriteBatch);
			nameInput.Draw(spriteBatch);
			closeButton.Draw(spriteBatch);
        }
    }
}


code:
/**
 * Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using MotoTrialRacer.UI;

namespace MotoTrialRacer
{
    /// <summary>
    /// This class defines the view which is used for selecting a level.
    /// Derives from View.
    /// </summary>
    class LevelSelector : View
    {
        private List<Button> buttons = new List<Button>();
        private List<Button> preDefinedButtons = new List<Button>();
        private List<Button> myButtons = new List<Button>();
        private String deleteQuestion = "";
        private String deleteCandidate = "";
        private SpriteFont font;
        private Button backButton;
        private Button yesButton;
        private Button noButton;
        private bool newGame = true;
        private bool dragging = false;
        private float lastY = 0;
        private float speed = 0;
        private int minY = 0;
        private int maxY = 0;
        private float listPos = 0;

        /// <summary>
        /// Creates a new level selecting view
        /// </summary>
        /// <param name="game">The Game instance that will show this view</param>
        /// <param name="pNewGame">true if the level is going to be
        ///                        selected for the new game, false otherwise</param>
        /// <param name="myLevelsPage">true if the view is wanted to
        ///                            be opened on the custom level page</param>
        public LevelSelector(Game1 game, bool pNewGame, bool myLevelsPage)
            : base(game)
        {
            maxY = (int)(game.getHeight() * 0.1f);
            newGame = pNewGame;
            float screenXMiddle = game.getWidth() / 2;
            int spacing = 90;
            int top = 70;
            Button button = new Button("level1", Vector2.Zero, game.Content);
			button.ButtonPressed += new Action<Button>(tmpButton_ButtonPressed);

            preDefinedButtons.Add(button);
            button.Position = new Vector2(screenXMiddle - button.Width * 0.5f,
                                          spacing * (preDefinedButtons.Count-1) + top);
            button = new Button("level2", Vector2.Zero, game.Content);
			button.ButtonPressed += new Action<Button>(tmpButton_ButtonPressed);

            preDefinedButtons.Add(button);
            button.Position = new Vector2(screenXMiddle - button.Width * 0.5f,
                                          spacing * (preDefinedButtons.Count-1) + top);
            button = new Button("level3", Vector2.Zero, game.Content);
			button.ButtonPressed += new Action<Button>(tmpButton_ButtonPressed);

            preDefinedButtons.Add(button);
            button.Position = new Vector2(screenXMiddle - button.Width * 0.5f,
                                          spacing * (preDefinedButtons.Count-1) + top);
            button = new Button("myLevels", Vector2.Zero,
                                game.Content);
			button.ButtonPressed += new Action<Button>(button_ButtonPressed);

            preDefinedButtons.Add(button);
            button.Position = new Vector2(screenXMiddle - button.Width * 0.5f,
                                          spacing * (preDefinedButtons.Count-1) + top);

            IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();
            String[] fileNames = savegameStorage.GetFileNames();
            for (int i = 0; i < fileNames.Length; i++)
            {
                String[] pieces = fileNames[i].Split('.');
                if (pieces.Length > 1 && pieces[1] == "lvl")
                {
                    var tmpButton = new Button(pieces[0].Replace('_', ' '), Vector2.Zero,
                                        game.Content, false);
					tmpButton.ButtonPressed += new Action<Button>(tmpButton_ButtonPressed);
					tmpButton.ButtonLongPressed += new Action<Button>(tmpButton_ButtonLongPressed);
					myButtons.Add(tmpButton);
					tmpButton.Position = new Vector2(screenXMiddle - tmpButton.Width * 0.5f,
                                                  60 * (myButtons.Count));
                }
            }
            minY = -myButtons.Count * 60 + (int)(0.5f * game.getHeight());
            yesButton = new Button("Yes", new Vector2(game.relativeX(290), game.relativeY(280)), game.Content, false);
			yesButton.ButtonPressed += new Action<Button>(yesButton_ButtonPressed);

            noButton = new Button("No", new Vector2(game.relativeX(490), game.relativeY(280)), game.Content, false);
			noButton.ButtonPressed += new Action<Button>(noButton_ButtonPressed);

            backButton = new Button("back", new Vector2(game.relativeX(10), game.relativeY(430)), game.Content, true);
			backButton.ButtonPressed += new Action<Button>(backButton_ButtonPressed);
            backButton.Width = 70;
			backButton.Height = 43;

			if (myLevelsPage)
                buttons = myButtons;
            else
                buttons = preDefinedButtons;

            font = game.Content.Load<SpriteFont>("SpriteFont1");
        }

		void tmpButton_ButtonLongPressed(Button sender)
		{
			deleteCandidate = sender.Name.Replace(' ', '_');
			if (buttons == myButtons)
				deleteQuestion = "Do you want to delete " + sender.Name + "?";
		}

		void tmpButton_ButtonPressed(Button sender)
		{
			if (newGame)
			{
				if (buttons == preDefinedButtons)
					game.NewGame(Convert.ToInt32(sender.Name.Substring(sender.Name.Length - 1)));
				else if (Math.Abs(speed) < 1)
					game.NewGame(sender.Name);
			}
			else
			{
				if (Math.Abs(speed) < 1)
					game.ShowHighScores(sender.Name);
			}
		}

		void button_ButtonPressed(Button sender)
		{
			buttons = myButtons;
		}

		void yesButton_ButtonPressed(Button sender)
		{
			DeleteLevel(sender.Name);
		}

		void noButton_ButtonPressed(Button sender)
		{
			deleteCandidate = "";
			deleteQuestion = "";
		}

		void backButton_ButtonPressed(Button sender)
		{
			if (buttons == preDefinedButtons)
				game.OpenMenu();
			else
			{
				speed = 0;
				buttons = preDefinedButtons;
			}
		}

        /// <summary>
        /// Deletes a custom level and all its high scores
        /// </summary>
        /// <param name="name">The name of the level</param>
        private void DeleteLevel(String name)
        {
            IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();
            savegameStorage.DeleteFile(deleteCandidate + ".lvl");
            savegameStorage.DeleteFile(deleteCandidate + ".scr");
            game.ShowMyLevelsSelector(false);
        }

		/// <summary>
        /// Updates the position of the info text corresponding to the touch inputs of the user.
        /// This implements the "flickable" feature. Also updates the buttons in this view.
        /// </summary>
        public override void Update()
        {
            base.Update();
            if (touchChanged)
            {
                if (deleteQuestion != "")
                {
                    yesButton.Update(touchLocation);
                    noButton.Update(touchLocation);
                }
                else
                {
                    if (buttons == myButtons)
                    {
                        if (touchLocation.State == TouchLocationState.Pressed)
                        {
                            dragging = true;
                            lastY = touchLocation.Position.Y;
                        }
                        else if (touchLocation.State == TouchLocationState.Released)
                        {
                            dragging = false;
                        }
                    }
                    List<Button> curButs = buttons;
                    for (int i = 0; i < curButs.Count; i++)
                    {
                        curButs[i].Update(touchLocation);
                    }
                    backButton.Update(touchLocation);
                }
            }
            if (buttons == myButtons)
            {
                if (dragging)
                {
                    speed = lastY - touchLocation.Position.Y;
                    lastY = touchLocation.Position.Y;
                }
                else
                {
                    if (listPos < minY)
                        if (speed > 0)
                            speed -= (minY - listPos) * 0.02f;
                        else
                            speed = (listPos - minY) * 0.1f;
                    else if (maxY < listPos)
                        if (speed < 0)
                            speed -= (maxY - listPos) * 0.02f;
                        else
                            speed = (listPos - maxY) * 0.1f;
                }
                listPos -= speed;
                for (int i = 0; i < buttons.Count; i++)
                    buttons[i].Y = (int)(listPos + 60 * (i + 1));
                speed *= 0.98f;
            }
        }

        /// <summary>
        /// Draws all the buttons in this view
        /// </summary>
        public override void Draw(SpriteBatch spriteBatch)
        {
			base.Draw(spriteBatch);
            if (deleteQuestion == "")
            {
                for (int i = 0; i < buttons.Count; i++)
					buttons[i].Draw(spriteBatch);
				backButton.Draw(spriteBatch);
            }
            else
            {
                spriteBatch.DrawString(font, deleteQuestion, new Vector2(240, 200), Color.Yellow);
				yesButton.Draw(spriteBatch);
				noButton.Draw(spriteBatch);
            }
        }
    }
}