Skip to content

Commit d15324a

Browse files
committed
Update for rework
1 parent c7e65c4 commit d15324a

File tree

5 files changed

+72
-86
lines changed

5 files changed

+72
-86
lines changed

articles/tutorials/building_2d_games/15_working_with_spritefonts/index.md

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -201,23 +201,27 @@ Next, open the *gameFont.spritefont* file and make the following changes:
201201
The key changes here are:
202202

203203
1. The `<FontName>` element was updated to `04B_11.ttf`, the exact filename with extension of the TTF font we just downloaded.
204-
2. The `<Size>` element was updated to be `16`.
204+
2. The `<Size>` element was updated to be `32`.
205205

206206
### Updating the Game
207207

208208
Finally, open the *Game1.cs* file and make the following changes:
209209

210-
[!code-csharp[](./snippets/game1.cs?highlight=41-45,105-106,234-235,378-379)]
210+
[!code-csharp[](./snippets/game1.cs?highlight=39-43,54-61,90-91,220-221,360-361)]
211211

212212
The key changes made are:
213213

214214
1. The `_font` field was added to store the SpriteFont Description when loaded.
215-
1. The `_score` field was added to track the player's score.
216-
1. In [**LoadContent**](xref:Microsoft.Xna.Framework.Game.LoadContent), the font is loaded using the content manager.
217-
1. In [**Update**](xref:Microsoft.Xna.Framework.Game.Update(Microsoft.Xna.Framework.GameTime)), the player's score is increased by `100` each time the slime eats the bat.
218-
1. In [**Draw**](xref:Microsoft.Xna.Framework.Game.Draw(Microsoft.Xna.Framework.GameTime)), the score is drawn to the top-left of the screen using the sprite batch.
219-
220-
| ![Figure 15-2: The game with score displayed in the top-left corner](./videos/score.webm) |
215+
2. The `_score` field was added to track the player's score.
216+
3. In [**Initialize**](xref:Microsoft.Xna.Framework.Game.Initialize)
217+
1. The height of the rendered font is measured
218+
2. The initial slime position is placed 10px below where the score text will be rendered.
219+
3. The initial bat position is updated to be 10px below where the score text will be rendered.
220+
4. In [**LoadContent**](xref:Microsoft.Xna.Framework.Game.LoadContent), the font is loaded using the content manager.
221+
5. In [**Update**](xref:Microsoft.Xna.Framework.Game.Update(Microsoft.Xna.Framework.GameTime)), the player's score is increased by `100` each time the slime eats the bat.
222+
6. In [**Draw**](xref:Microsoft.Xna.Framework.Game.Draw(Microsoft.Xna.Framework.GameTime)), the score is drawn to the top-left of the screen using the sprite batch.
223+
224+
| ![Figure 15-2: The game with score displayed in the top-left corner](./videos/gameplay.webm) |
221225
|:----------------------------------------------------------------------------------------:|
222226
| **Figure 15-2: The game with score displayed in the top-left corner** |
223227

articles/tutorials/building_2d_games/15_working_with_spritefonts/snippets/game1.cs

Lines changed: 59 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,17 @@
11
using System;
22
using Microsoft.Xna.Framework;
3+
using Microsoft.Xna.Framework.Audio;
34
using Microsoft.Xna.Framework.Graphics;
45
using Microsoft.Xna.Framework.Input;
6+
using Microsoft.Xna.Framework.Media;
57
using MonoGameLibrary;
6-
using MonoGameLibrary.Audio;
78
using MonoGameLibrary.Graphics;
89
using MonoGameLibrary.Input;
910

1011
namespace DungeonSlime;
1112

12-
public class Game1 : Game
13+
public class Game1 : Core
1314
{
14-
private GraphicsDeviceManager _graphics;
15-
private SpriteBatch _spriteBatch;
16-
1715
// Defines the slime animated sprite.
1816
private AnimatedSprite _slime;
1917

@@ -26,64 +24,48 @@ public class Game1 : Game
2624
// Speed multiplier when moving.
2725
private const float MOVEMENT_SPEED = 5.0f;
2826

29-
// Tracks the input manager
30-
private InputManager _input;
31-
3227
// Tracks the position of the bat.
3328
private Vector2 _batPosition;
3429

3530
// Tracks the velocity of the bat.
3631
private Vector2 _batVelocity;
3732

38-
// Tracks the audio manager
39-
private AudioManager _audio;
33+
// The sound effect to play when the bat bounces off the edge of the screen.
34+
private SoundEffect _bounceSoundEffect;
35+
36+
// The sound effect to play when the slime eats a bat.
37+
private SoundEffect _collectSoundEffect;
4038

4139
// The SpriteFont Description used to draw text
4240
private SpriteFont _font;
4341

4442
// Tracks the players score.
4543
private int _score;
4644

47-
public Game1()
45+
public Game1() : base("Dungeon Slime", 1280, 720, false)
4846
{
49-
_graphics = new GraphicsDeviceManager(this);
50-
Content.RootDirectory = "Content";
51-
IsMouseVisible = true;
52-
53-
// Create the instance of the input manager.
54-
_input = new InputManager(this);
55-
56-
// Add it to the game's component collection
57-
Components.Add(_input);
58-
59-
// Create the instance of the audio manager.
60-
_audio = new AudioManager(this);
6147

62-
// Add it to the game's component collection
63-
Components.Add(_audio);
6448
}
6549

6650
protected override void Initialize()
6751
{
68-
// TODO: Add your initialization logic here
69-
7052
base.Initialize();
7153

72-
// Set the initial position of the bat to be 10px
73-
// to the right of the slime.
74-
_batPosition = new Vector2(_slime.Width + 10, 0);
54+
// Determine the height of the font
55+
float textHeight = _font.MeasureString("A").Y;
56+
57+
// Place the slime at a position below where the score will be displayed
58+
_slimePosition = new Vector2(0, textHeight + 10);
59+
60+
// Set the initial position of the bat to be 10px to the right of the slime.
61+
_batPosition = _slimePosition + new Vector2(_slime.Width + 10.0f, 0.0f);
7562

7663
// Assign the initial random velocity to the bat.
7764
AssignRandomBatVelocity();
78-
79-
// Start playing the background music
80-
_audio.PlaySong("audio/theme");
8165
}
8266

8367
protected override void LoadContent()
8468
{
85-
_spriteBatch = new SpriteBatch(GraphicsDevice);
86-
8769
// Create the texture atlas from the XML configuration file
8870
TextureAtlas atlas = TextureAtlas.FromFile(Content, "images/atlas-definition.xml");
8971

@@ -94,23 +76,27 @@ protected override void LoadContent()
9476
_bat = atlas.CreateAnimatedSprite("bat-animation");
9577

9678
// Load the bounce sound effect
97-
_audio.AddSoundEffect("audio/bounce");
79+
_bounceSoundEffect = Content.Load<SoundEffect>("audio/bounce");
9880

9981
// Load the collect sound effect
100-
_audio.AddSoundEffect("audio/collect");
82+
_collectSoundEffect = Content.Load<SoundEffect>("audio/collect");
10183

102-
// Load the theme song
103-
_audio.AddSong("audio/theme");
84+
// Load the background theme music
85+
Song theme = Content.Load<Song>("audio/theme");
86+
87+
// Start playing the background music
88+
Audio.PlaySong(theme);
10489

10590
// Load the font
10691
_font = Content.Load<SpriteFont>("fonts/gameFont");
92+
93+
base.LoadContent();
10794
}
10895

10996
protected override void Update(GameTime gameTime)
11097
{
111-
// base.Update first so that components are updated before we perform
112-
// additional game logic
113-
base.Update(gameTime);
98+
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
99+
Exit();
114100

115101
// Update the slime animated sprite.
116102
_slime.Update(gameTime);
@@ -204,8 +190,8 @@ protected override void Update(GameTime gameTime)
204190
{
205191
_batVelocity = Vector2.Reflect(_batVelocity, normal);
206192

207-
// Play bounce sound
208-
_audio.PlaySoundEffect("audio/bounce");
193+
// Play the bounce sound effect
194+
Audio.PlaySoundEffect(_bounceSoundEffect);
209195
}
210196

211197
_batPosition = newBatPosition;
@@ -228,12 +214,14 @@ protected override void Update(GameTime gameTime)
228214
// Assign a new random velocity to the bat
229215
AssignRandomBatVelocity();
230216

231-
// Play collect sound
232-
_audio.PlaySoundEffect("audio/collect");
217+
// Play the collect sound effect
218+
Audio.PlaySoundEffect(_collectSoundEffect);
233219

234-
// Increase the player's score.
220+
// Increase the player's score.
235221
_score += 100;
236222
}
223+
224+
base.Update(gameTime);
237225
}
238226

239227
private void AssignRandomBatVelocity()
@@ -252,78 +240,71 @@ private void AssignRandomBatVelocity()
252240

253241
private void CheckKeyboardInput()
254242
{
255-
// Exit the game if the escape key is pressed.
256-
if (_input.Keyboard.IsKeyDown(Keys.Escape))
257-
{
258-
Exit();
259-
}
260-
261243
// If the space key is held down, the movement speed increases by 1.5
262244
float speed = MOVEMENT_SPEED;
263-
if (_input.Keyboard.IsKeyDown(Keys.Space))
245+
if (Input.Keyboard.IsKeyDown(Keys.Space))
264246
{
265247
speed *= 1.5f;
266248
}
267249

268250
// If the W or Up keys are down, move the slime up on the screen.
269-
if (_input.Keyboard.IsKeyDown(Keys.W) || _input.Keyboard.IsKeyDown(Keys.Up))
251+
if (Input.Keyboard.IsKeyDown(Keys.W) || Input.Keyboard.IsKeyDown(Keys.Up))
270252
{
271253
_slimePosition.Y -= speed;
272254
}
273255

274256
// if the S or Down keys are down, move the slime down on the screen.
275-
if (_input.Keyboard.IsKeyDown(Keys.S) || _input.Keyboard.IsKeyDown(Keys.Down))
257+
if (Input.Keyboard.IsKeyDown(Keys.S) || Input.Keyboard.IsKeyDown(Keys.Down))
276258
{
277259
_slimePosition.Y += speed;
278260
}
279261

280262
// If the A or Left keys are down, move the slime left on the screen.
281-
if (_input.Keyboard.IsKeyDown(Keys.A) || _input.Keyboard.IsKeyDown(Keys.Left))
263+
if (Input.Keyboard.IsKeyDown(Keys.A) || Input.Keyboard.IsKeyDown(Keys.Left))
282264
{
283265
_slimePosition.X -= speed;
284266
}
285267

286268
// If the D or Right keys are down, move the slime right on the screen.
287-
if (_input.Keyboard.IsKeyDown(Keys.D) || _input.Keyboard.IsKeyDown(Keys.Right))
269+
if (Input.Keyboard.IsKeyDown(Keys.D) || Input.Keyboard.IsKeyDown(Keys.Right))
288270
{
289271
_slimePosition.X += speed;
290272
}
291273

292-
// If the M key is pressed, toggle mute state for audio
293-
if(_input.Keyboard.WasKeyJustPressed(Keys.M))
274+
// If the M key is pressed, toggle mute state for audio.
275+
if (Input.Keyboard.WasKeyJustPressed(Keys.M))
294276
{
295-
_audio.ToggleMute();
277+
Audio.ToggleMute();
296278
}
297279

298-
// If the + button is pressed, increase the volume
299-
if(_input.Keyboard.WasKeyJustPressed(Keys.OemPlus))
280+
// If the + button is pressed, increase the volume.
281+
if (Input.Keyboard.WasKeyJustPressed(Keys.OemPlus))
300282
{
301-
_audio.IncreaseVolume(0.1f);
283+
Audio.IncreaseVolume(0.1f);
302284
}
303285

304-
// If the - key is pressed, decrease the volume
305-
if(_input.Keyboard.WasKeyJustPressed(Keys.OemMinus))
286+
// If the - button was pressed, decrease the volume.
287+
if (Input.Keyboard.WasKeyJustPressed(Keys.OemMinus))
306288
{
307-
_audio.DecreaseVolume(0.1f);
289+
Audio.DecreaseVolume(0.1f);
308290
}
309291
}
310292

311293
private void CheckGamePadInput()
312294
{
313-
// Get the info for player one's gamepad.
314-
GamePadInfo gamePadOne = _input.GamePads[(int)PlayerIndex.One];
295+
GamePadInfo gamePadOne = Input.GamePads[(int)PlayerIndex.One];
315296

316297
// If the A button is held down, the movement speed increases by 1.5
317298
// and the gamepad vibrates as feedback to the player.
318299
float speed = MOVEMENT_SPEED;
319300
if (gamePadOne.IsButtonDown(Buttons.A))
320301
{
321302
speed *= 1.5f;
322-
gamePadOne.SetVibration(1.0f, TimeSpan.FromSeconds(0.5f));
303+
GamePad.SetVibration(PlayerIndex.One, 1.0f, 1.0f);
323304
}
324305
else
325306
{
326-
gamePadOne.StopVibration();
307+
GamePad.SetVibration(PlayerIndex.One, 0.0f, 0.0f);
327308
}
328309

329310
// Check thumbstick first since it has priority over which gamepad input
@@ -364,23 +345,24 @@ private void CheckGamePadInput()
364345

365346
protected override void Draw(GameTime gameTime)
366347
{
348+
// Clear the back buffer.
367349
GraphicsDevice.Clear(Color.CornflowerBlue);
368350

369351
// Begin the sprite batch to prepare for rendering.
370-
_spriteBatch.Begin(samplerState: SamplerState.PointClamp);
352+
SpriteBatch.Begin(samplerState: SamplerState.PointClamp);
371353

372354
// Draw the slime sprite.
373-
_slime.Draw(_spriteBatch, _slimePosition);
355+
_slime.Draw(SpriteBatch, _slimePosition);
374356

375357
// Draw the bat sprite.
376-
_bat.Draw(_spriteBatch, _batPosition);
358+
_bat.Draw(SpriteBatch, _batPosition);
377359

378360
// Draw the score
379-
_spriteBatch.DrawString(_font, $"Score: {_score}", Vector2.Zero, Color.White);
361+
SpriteBatch.DrawString(_font, $"Score: {_score}", Vector2.Zero, Color.White);
380362

381363
// Always end the sprite batch when finished.
382-
_spriteBatch.End();
364+
SpriteBatch.End();
383365

384366
base.Draw(gameTime);
385367
}
386-
}
368+
}

articles/tutorials/building_2d_games/15_working_with_spritefonts/snippets/gameFont.spritefont

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<XnaContent xmlns:Graphics="Microsoft.Xna.Framework.Content.Pipeline.Graphics">
33
<Asset Type="Graphics:FontDescription">
44
<FontName>04B_11.ttf</FontName>
5-
<Size>16</Size>
5+
<Size>32</Size>
66
<Spacing>0</Spacing>
77
<UseKerning>true</UseKerning>
88
<Style>Regular</Style>
352 KB
Binary file not shown.
-57.3 KB
Binary file not shown.

0 commit comments

Comments
 (0)