Tag Archives: games

The Making of Mouse Dreams Part 2 – In One Level

In this article, I examine Mouse Dreams’ evolution of by following a single level from its initial design through to the final game.

1: Sketch

Sketch

“Block light switch w/crate to open exit” says my awful handwriting.

That sketch is from the very first time I sat down to create what became the final design for Mouse Dreams (if you don’t count the discarded game from whose ashes Mouse Dreams arose). When I had arrived at the core game design (see Part 1 for the full story), I quickly sketched out the first 8 or so levels in a notebook.

In the sketch, the larger ‘square’ in the lower-left is the player. Next to the player is a box the player must carry onto the ledge on the right side to block the light (the thing near the top of the screen with two diagonal lines beaming from it) from hitting a light-sensitive switch that controls the moving wall (the rectangle with the downwards arrow near the bottom centre of the image), which is blocking the way to  the exit in the lower-right. If that’s confusing, it should become clearer when you see the level as it looks in the game further down.

This early level aims to teach the player about light-sensitive switches, and while the sketch is messy, it’s enough to encapsulate the ideas to transfer into the game.

My hints for sketching out levels:

  • Expect to forget what you were thinking when you drew it…write notes and draw arrows.
  • Use colour for different things.
  • Use a key for objects – e.g. the player is a square, a collectable is a pink triangle.
  • Don’t worry about scale – sketches are guides, and the final level will change numerous times anyway.

Another sketch – now in COLOUR

2: Prototype

Once I had my first bunch of levels, my enthusiasm was high. I had my game idea, and I had some content to get started with. I put my levels into the game with the rudimentary graphics I had at the time:

The first prototype of this level

This matches up closely with the original sketch. A collectable (the pink thing) has been added, and a more complex layout forces the player to jump around a bit.

With the sketch as a starting point, the level evolved as I built it. It felt too simplistic, hence the extra jumping required. I added the collectable because I decided that every level should have a collectable rather than just a few here and there.

3: Fleshing out the Prototype

I liked the idea of patterned wallpaper for some reason, and this led to turning the player into a Victorian-era man’s head with a hat and moustache. He rotated in mid-air when jumping.

Working out the aesthetic

In this version of the level you can see some changes that reflect the progression of the game design and the development of the game’s look.

I had decided that the game was set in houses, so I started replacing the abstract level geometry with chairs, shelves, and so on. While this looks quite different to the previous image, the actual layout is hardly changed – it just looks different.

The other major change here is that the crate has been moved. It is now closer to the light sensor it must be used to block. This is because I decided the player could not jump while carrying a crate.

Here is Level 1 from the same build that I think better gets across the game’s aesthetics at that stage:

Another example from the same build

4: Mouse

As is my tendency, I decided to make the game’s look more cartoony and fun. This was partly informed by the relative simplicity of the game – it was not the serious puzzle game I had first envisioned, but was more accessible with moderate difficulty, suitable for players of all ages.

I decided on a mouse theme to go with the cartoon aesthetic:

Putting the mouse (and cheese) in Mouse Dreams

5: Fleshing Out

As the game progressed, the visuals started to take shape after buying some assets. It took me weeks and lots of experimentation to get those bricks how I wanted. A subtle addition is the skirting along the bottom of the floor.

Getting better

6: Maturation

As the game matured, I released a beta version, and continually tweaked the look and feel to get closer to a final product. Much of this time period had been spent fixing bugs and implementing the game functionality, with the visual changes being mostly swapping out temporary assets for proper ones.

Here is the level as of that first beta:

Approaching the final look.

A few changes here:

  • Polish – the bricks now cover all of the main terrain, the wallpaper is more fitting to the cartoony theme, and the cheese is improved.
  • I have added a wire system to show the player which objects are powered by switches. You can see the red wire linking the light-activated switch to a place in the ground (where the moving wall is).
  • The box now starts in front of the light-activated switch. The trick here is that the player needs to move the box in order to climb on it and get the cheese, but doing so will close the moving wall that is currently open. This teaches the player to think less linearly, which will be required when the game gets more difficult.
  • The cheese is moved to increase the challenge. The player cannot reach the cheese without doing something else first. By this time, collecting the cheese is required before the player can exit the level.

7: Ramping up the Colour

During the beta period, I subjected my game for feedback, and among the comments, I received one particularly valuable suggestion: make the game more colourful. At first, I thought the advice was awful. My game had a fun, cartoony look! Didn’t it?

Stepping back, I realised the advice was perfect. I needed to push the brightness and saturation to an extreme. I also started commissioning what art I could afford, most notably a new main player character.

Bolder colours and a new mouse!

Due to some level shuffling, in this build the level was moved to the game’s second house, where it was House 2, Level 1.

The most obvious graphical change is the stylised, brightly coloured bricks (each house has different coloured bricks). The mouse’s night cap represents the game’s central conceit – that the protagonist is a sleeping mouse running around the crazy houses of his dreams. There are a lot more graphical improvements in the game by this point (along with new mechanics, new levels, and plenty of polish), though the early levels, such as this one, were not affected as much due to their simplicity.

8: Near Complete

And finally…

With the level moved back into the first house, the bricks have changed to that house’s colour – red. You can also see a trick I found to cheaply improve the looks – adding corner pieces to the ceiling for a less boxy shape.

As well as the bricks and wallpaper, you’ll notice some subtle changes to the chair, skirting, and shelf colours as well. I went through the game looking for anywhere I could ramp up the colour, and I tried to ensure each level had a good balance of colours – which is why the red wall is paired with a bright yellow wallpaper pattern in this level. With the orange chair and green shelf, most of the rainbow is represented here!

Here’s a different level with a few more details:

Another near-final screenshot.

Spot the Difference

 

Now that you’ve seen the final level, take another look at the original sketch back at the start. You’ll see the core level idea is still intact! The visuals developed over time, and some gameplay details changed. This level is a little more complex than it was originally because I made the cheese collection mandatory, and because I now require the player to undo their action in order to complete the level. But this level is still about teaching the player to use the light-detector switch mechanic.

The evolution of this level is a microcosm of the game itself. As development progressed, the style and theme gradually fell into place with lots of iteration and experimentation…and playing the levels over and over again…

Coming Soon

Mouse Dreams is coming soon. If you want to see more about the game (including a trailer and a Windows 10 Store Beta), please visit the game’s page at http://grogansoft.com/mouse-dreams/ .

Artificial Intelligence in Game Opponents

I needed a CPU AI opponent for a simple game, so I decided to build one, and this article details my process. There’s no specific Unity content or project for this article – it’s all theory.

What is Game Artificial Intelligence?

Game artificial intelligence (AI) provides opponents for a human player. Those opponents need to simulate human (or robot, or animal) behaviour to provide a challenge.

A player wants opponents that act and react as a human opponent would. This is difficult because humans are organic, and computers are digital. And of course, computers don’t think for themselves like people can.

Game AI therefore needs to use purely logical algorithms to simulate the problem solving that a human player does organically. You need to make those algorithms feel natural.

A Simple Multiplayer Game

The game I’m creating AI for is a very simple card memory game, the kind where you have a grid of face-down cards, and you try to turn over two matching cards to win a point:

matching_cardsThis game hardly requires a super-intelligent robot mind, but I found it was a great way to teach myself the fundamentals of game AI.

Define the Rules

To start with you need to know your game’s rules. Memory card games have very simple gameplay:

Players take turns to:

  • Turn over two cards, one at a time (making them face-up and visible to both players)
    • If the cards match, they are removed from play and the player gets a point and another turn
    • If the cards don’t match, they are turned back face down and the other player has their turn.

The player with the most points when all the cards are gone wins.

Implementing AI

I chose to implement a very rough AI to start with. AI version 1.0 picks cards completely at random. As you can guess, this is not challenging, and it doesn’t fit any definition of AI. But it did let me set up the programming infrastructure in my game.

My standard approach to adding functionality is to add in the skeleton first – typically the way the new functionality interacts with the rest of the code. Doing this lets me work on the new feature in isolation knowing that changes to it won’t affect the rest of my game (so long as I keep a simple interface between the main game and the new functionality).

I created a class called AiOpponent containing a single public method ‘ChooseCard()’. ChooseCard() returns a randomly selected card from the current game board. The core game knows that the player is AI and therefore must be asked to select a card rather than wait for a human player to tap the screen. The rest of the game continues as normal.

Once this was working I could encapsulate all my AI code into the AiOpponent class, but never have to change any other code in the game. The game manager doesn’t care how a card is selected, just that one is.

From Zero to Hero

I played the game a few times to figure out the main strategy. The core strategy is to remember the cards that are turned face-up and then returned face-down. The perfect strategy was to remember every card and then use that information to improve the chance of making pairs.

I decided that version 2.0 of my AI would play a ‘perfect game’ and remember every single card with 100% accuracy (this is actually simpler than implementing an imperfect strategy), and always make a pair when possible (i.e. when it knows where two matching cards are or when it knows where a card matching its first selection is). I broke this down into the following flowchart:

ai_flow

Considerations for v2.0

As you can probably guess, this AI is almost unbeatable. It doesn’t make mistakes, and it has a perfect memory. Unless you get lucky and also have a perfect memory you will usually lose. Like a random opponent, a perfect opponent isn’t any fun.

AI v2.0 doesn’t forget a card they saw several turns ago; it doesn’t accidentally pick up the card next to the one it intended. AI v2.0 is too machine-like; too perfect.

AI Overkill

I’m the first to admit that the AI for my card memory game is overkill. It’s a simple kids’ game, and having a purely random opponent would work just fine. But I wanted to teach myself how to create an AI opponent so I can apply that knowledge to a more complex game I plan to make later.

So I set out to make the most human card memory AI I could.

v3.0

The next step was to make the AI adaptable to different difficulty levels by blending the random card selection from v1.0 and the perfect matching skills of v2.0. Based on the difficulty level my AI would choose randomly or perfectly in different proportions.

  • Easy AI – totally random
  • Medium AI – half random, half perfect
  • Hard AI – totally perfect.

v3.0 is probably the most complex AI you could possibly need for this kind of game. In fact, it’s probably already overkill. But once I’d started deconstructing the game I realised even this simple game has more potential for AI, so in a future post I will go into the nuances of a more human card memory opponent (even though it’s overkill).

 

 

 

 

Beginner’s Guide: Create a Pong Clone in Unity: Part 10

Polishing it Off

We’re now at the end of our fun, enlightening, and probably exhausting journey to recreate Pong. In this final part we will add polish to the game and learn a few more titbits of Unity wisdom before signing off on Pong (or whatever you’ve called your version). Then we’ll build a standalone version of the game that can run on any computer without needing Unity. If you have access to a mobile device, I’ll touch a little bit on building and deploying to those, but with so many platforms and other variables, it’s outside of our scope to go into detail about that.

Snazzy Effects

We’ll add a few cool effects to our game to really up the fun factor. The best games have a lot of ‘juice’ – extra touches that make every frame addictive fun. Think of the Candy Crush clunk sounds or Angry Birds’ crashing, tumbling blocks. Granted, our Pong clone is not the height of fun or sophistication, but with these extra touches we’ll prove that even the simplest of games can be improved a lot by a few flourishes.

Shake the Camera

A simple, effective drop of juice is the camera shake. You see it in lots of games, and it gives a sense of kinetic energy, augmenting sound and vision to create something physical on a flat screen.

If you recall all the way back to Part 1 you may remember that our scene (and all scenes) has a default camera. You’ll also recall that all GameObjects (the camera is a GameObject) have a transform component, which determines its placement, rotation, and size. Therefore, if you move the camera’s transform you are effectively moving the view of the scene, or – from the perspective of the player – you’re moving the game area. If you quickly move the camera in small, random jolts, the screen will shake!

We will add a script to our MainCamera GameObject with a simple Shake() method, and we’ll call this method from GameManagerScript.

Create a new C# script called CameraShakeScript (remember to place it in the Scripts folder). Paste the following code into the script:

using UnityEngine;
using System.Collections;

public class CameraShakeScript : MonoBehaviour {
    // remember the correct starting camera position so we can revert back once shaking is complete
    private Vector3 originPosition;
    private Quaternion originRotation;

   public float originalDecay = 0.006f;
   public float originalIntensity = 0.04f;
   float shake_decay;
   float shake_intensity;
   private bool shaking; // is the camera supposed to be shaking at the moment
   Transform cameraTransform;

   void Start() {        
       cameraTransform =  Camera.main.transform;        
   }

   void Update (){
       if(!shaking)            
           return;        

       if (shake_intensity > 0f)
       {
            cameraTransform.localPosition = originPosition + Random.insideUnitSphere * shake_intensity;
            cameraTransform.localRotation = new Quaternion(                
            originRotation.x + Random.Range (-shake_intensity,shake_intensity) * .2f,                
            originRotation.y + Random.Range (-shake_intensity,shake_intensity) * .2f,                
            originRotation.z + Random.Range (-shake_intensity,shake_intensity) * .2f,                
            originRotation.w + Random.Range (-shake_intensity,shake_intensity) * .2f);
            shake_intensity -= shake_decay;
       }

      else
      {        
            shaking = false;
            // reset the camera to its original state
            cameraTransform.localPosition = originPosition;            
            cameraTransform.localRotation = originRotation;            
      }
   }

   public void Shake(){

      if(!shaking) {            
        originPosition = cameraTransform.localPosition;            
        originRotation = cameraTransform.localRotation;
      }

      shaking = true;        
      shake_intensity = originalIntensity;        
      shake_decay = originalDecay;
  }
}

I won’t go into detail about this code, but here’s what it does:

When Shake() is called, the camera is moved around randomly based on the intensity and decay variables (the decay determines how long the shake lasts and the intensity determines how much movement there is). Every frame the camera will shake if the shaking boolean variable is set to true. Once the shake is finished that value reverts to false.

  • Save that script and attach it to the GameManager GameObject.

Open GameManagerScript. We’ll use Unity’s find method to get a reference to the camera to demonstrate the syntax a bit more, but you could just as easily use [SerializeField] and drag CameraShakeScript into the empty field in the Inspector.

Add this variable to the script:

CameraShakeScript camShake;

Now, in Start(), populate the variable so it can be used in the script (place this line before the StartNewGame() call:

camShake = GetComponent<CameraShakeScript>();

Now we can make the camera shake by calling the Shake() method on cameraShake like this, which you need to add to the GoalScored() method at the start, so the camera will shake whenever a goal is scored:

camShake.Shake();

Test the Shakes

Run the game and see the shake effects. Nice. The shaking really ‘sells’ the action…

You can experiment with the shake by adjusting the Original Decay and Original Intensity variables via the Inspector. Can you modify the script to shake the camera every time the ball hits a wall?

Particles

A common technique used to create effects is the particle system. A particle system is a graphical effect created by an algorithm. Smoke is usually a particle effect. Particle effects let you create attractive effects with relatively little work (and, incidentally, low processing power).

Our particle effect is going to be rudimentary, but it will give you an idea of how particle systems work. We will display an ‘explosion’ of debris when a goal is scored.

Like everything else, a particle system is a component. We will attach our particle system to the goals, and to do this we will add it to the goal prefab.

Create a new ParticleSystem in the Hierarchy:

  • GameObject | Particle System
If you don’t see the particle system, double-click the new GameObject in the Hierarchy to centre the scene view on it. You may need to zoom in.

It should look like this:

We’ll change this to make a few bits of white debris to fly off the goal when a goal is scored.

With the particle system selected in the Hierarchy you’ll notice it has a lot of settings in the Inspector:

Make the following modifications:

  • Change Duration to 0.25 (how long the particle system shoots out particles)
  • Change Start Lifetime to 0.5 (how long a particle sticks around for)
  • Untick Play On Awake (we don’t want the particle system to automatically start)
  • Change Emission Rate to 40 (click the Emission heading to expand it first)
  • Make the particle system a child of Player1Goal.
  • Reset the particle system’s transform (i.e. set its position to 0, 0, 0 or click the cog in the Transform component and choose Reset).
  • Make the Particle System GameObject a child of Player1Goal (drag-and-drop it in the Hierarchy).
  • Reset the particle system’s transform by clicking the cog and selecting Reset in the Inspector with the Particle System GameObject selected. This sets the particle system’s transform to match the goal it’s attached to.
  • Change the Particle System‘s transform’s rotation values to X = 0, Y=90, and Z = 0. This makes the particles shoot out from the goal.

 

  • Lastly, untick the Looping property of the particle system. This will turn off the particle simulation.

Now we’re going to do something new. We’re going to ‘re-prefab’ our GoalPrefab. This means we are going to update GoalPrefab with changes we’ve made to one of its instances. To do this, drag-and-drop Player1Goal from the Hierarchy onto GoalPrefab in the Prefabs folder (you’ll need the Prefabs folder to be open in the Project window). Once you’ve done this the particle system will become part of the prefab, and Player2Goal will automatically get a matching particle system! That’s the power of prefabs, sir or madam!

Because Player2Goal is a carbon copy of Player1Goal the particle on Player2Goal will face in the same direction – but it needs to be facing the opposite direction, away from its own wall. To fix this, simply change Player2Goal’s Particle System Transform Rotation X value to 180 in the Inspector. This flips it on its X axis.

Script the Particle System

Before we can see our particles in action we need to fire it off at the appropriate time. Open GoalScript.

Insert this new variable:

[SerializeField]
ParticleSystem partSys;

Then change the OnCollisionEnter2D() method to this:

void OnCollisionEnter2D(Collision2D other)
{
    if(other.transform.name == "Ball")
    {
        gameMan.GoalScored(attackingPlayer);
        partSys.transform.position = new Vector2(partSys.transform.position.x, other.transform.position.y);
        partSys.Play();
    }
}

Here we move the particle system to the same position as the ball at the moment it hits the goal, then play the particle emission at that location so it looks like some debris is being chipped off the goal by the ball. Snazzy.

  • Save the script then head back into Unity.

For each of the player goal GameObjects:

  • Select the object, then drag its particle system child into the Part Sys field in the Goal Script Inspector entry. This populates the partSys variable with the particle system so the script has something to play.

Play the game…

Game Over

We’re done! We’ve completed our Pong clone. It’s no masterpiece, but hopefully it has taught you the main building blocks of creating a game in Unity. If you look back through these ten lessons you’ll see that you’ve learned a lot, and hopefully some of it has stuck! You should have a pretty solid grasp of GameObjects, MonoBehaviour scripts, components, the Inspector, and so on, perhaps enough to embark on your own game.

There are also lots of ways to improve on our Pong clone. Here are some suggestions:

  • Improve the UI.
  • Animate something in the main menu screen (a bouncing ball perhaps).
  • Stop the ball after every goal and have a 3…2…1…GO timer before play resumes.
  • Add some extra effects:
    • A bounce sound when the ball hits a wall
    • Flashing when a goal is scored
  • Implement an AI opponent for single-player action
  • Show the score on the End Game screen.

I hope you’ve learned a lot from these tutorials and – more importantly – I hope you’ve had fun!