Compartir a través de


Crear la clase Game1

Como sucede con todos los proyectos de Microsoft XNA, la clase Game1 deriva de la clase Microsoft.Xna.Framework.Game, que proporciona inicialización básica de dispositivo gráfico, lógica de juego, y código de representación para juegos de XNA. La clase Game1 es bastante simple porque la mayoría del trabajo se realiza en las clases GamePiece y GamePieceCollection.

Crear el código

Los miembros privados para la clase constan de un objeto GamePieceCollection para mantener las piezas de juego, un objeto GraphicsDeviceManager y un objeto SpriteBatch que se utilizan para representar las piezas de juego.

#region PrivateMembers
// Number of game pieces.
private const int GamePieceCount = 6;
// The collection of game pieces.
private GamePieceCollection faces;
// Graphics device manager.
private GraphicsDeviceManager graphics;
// The sprite batch used for rendering game pieces.
private SpriteBatch spriteBatch;
#endregion

Durante la inicialización del juego se crean instancias de estos objetos.

#region ConstructorInitialize
public Game1()
{
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";
    // This is the default but assigning here explicitly
    // to show that resizing is not supported. The view port
    // boundaries used to bounce a game piece would not be
    // updated if the window was resized.
    Window.AllowUserResizing = false;
}

/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// </summary>
protected override void Initialize()
{
    IsMouseVisible = true;
    faces = new GamePieceCollection();
    // base.Initialize calls the LoadContent method.
    base.Initialize();
}
#endregion

Cuando se llama al método LoadContent, se crean las piezas de juego y se asignan al objeto GamePieceCollection. Hay dos tipos de piezas de juego. El factor de escala de las piezas se cambia ligeramente, de modo que hay piezas algo más pequeñas y piezas algo más grandes.

#region LoadContent
/// <summary>
/// LoadContent will be called once per game. Load all content here.
/// </summary>
protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);

    string filename = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
    string path = System.IO.Path.GetDirectoryName(filename) + @"\Content";

    // Scale pieces from 100% to 160%
    float scale = 1.0f;
    float scaleFactor = 0.60f / ((GamePieceCount/2)-1);
    for (int k = 0; k < GamePieceCount / 2; k++)
    {
        GamePiece face1 = new GamePiece(spriteBatch, path + @"\Face1.png");
        GamePiece face2 = new GamePiece(spriteBatch, path + @"\Face2.png");

        face1.Scale = face2.Scale = scale;
        face1.PieceColor = Color.Green;
        face2.PieceColor = Color.LightSalmon;
        faces.Add(face1);
        faces.Add(face2);
        scale += scaleFactor;
    }
}
#endregion

El marco de XNA llama repetidamente al método UPDATE mientras se ejecuta el juego. El método Update llama a los métodos UpdateFromMouse y ProcessInertia en la colección de piezas de juego. Estos métodos se describen en Crear la clase GamePieceCollection.

#region UpdateGame
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
    faces.ProcessInertia();
    faces.UpdateFromMouse();
    base.Update(gameTime);
}
#endregion

El marco de XNA también llama repetidamente al método Draw mientras se ejecuta el juego. El método Draw realiza la representación de las piezas de juego llamando al método Draw del objeto GamePieceCollection. Este método se describe enCrear la clase GamePieceCollection.

#region DrawGame
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    spriteBatch.Begin();
    faces.Draw();
    spriteBatch.End();
    base.Draw(gameTime);
}
#endregion

Vea también

Conceptos

Usar manipulaciones e inercia en una aplicación XNA

Crear la clase GamePiece

Crear la clase GamePieceCollection

Listas de código completas

Otros recursos

Manipulaciones e inercia