Monday, May 23, 2016

Video Game Design: Education in Games

Since the early times of video games, education has been an important focus.  In 1983, President Ronald Reagan expressed his hope and expectation that video games would prepare the youth of that day for challenges they would face as technology continues to advance, and in a large part, he was right.  Outside of traditional education, video games have been proven to provide dramatic cognitive and coordination benefits for a wide range of problem solving skills.  These are just natural benefits of challenging real-time video games though.  On a parallel track, we have games designed expressly for the purpose of education in traditional subjects.  Since the '80s, and possibly earlier, we have had video games trying to teach math, science, spelling, history, and many other subjects.  Evidence is mounting that well designed video games can be used for learning that is far more motivating and effective than anything we have done in public schools.

There is a problem in the educational game industry.  The problem is that the industry does not actually know how to make effective educational games.  Yes, we have seen games like Math Blaster teach a good portion of a generation basic math.  A few years ago though, we had a blockbuster game come out that turns out to be more effective at educating than any "educational game," and that game was not designed with education in mind at all.  I am talking about Minecraft.  Parents and schools buy games like Math Blaster to teach children, and those children enjoy playing these games mostly because it is a break from schoolwork.  Minecraft, however, is different.  Children beg their parents to buy it for them, and then they spend hours on end playing it, because they want to!  My parents often had to bribe us to play Math Blaster, but no one has to bribe their children to play Minecraft.  If Mojang can make a game that is both educational and extremely motivating, without even trying, then why can't educational game companies deliberately make educational games that are also motivating?

This is a problem that is starting to get more attention, but no solution has been found.  The first problem is that Minecraft was a bit of an anomaly.  It was wildly successful, because it managed to tap into a huge market that no one knew existed.  It is unreasonable to expect this to happen with every new game.  There are companies, like Blizzard, that consistently make very successful games without getting lucky like this though.  Blizzard makes successful games because it knows what its customers want, and it knows how to make games motivating.  The important factor here is the business model.  Blizzard makes fun and motivating games.  Yes, World of Warcraft actually has significant educational value, but it is incidental.  For example, Wow has a nice auction house mechanic that allows players to buy and sell in-game stuff for in-game currency.  Blizzard did this because people like to trade, and it gives the game a wider market.  In other words, it makes the game more fun for more people.  The fact that the auction house can teach economics and accounting is great, but it was not the reason Blizzard put it there.  Minecraft is similar in that it was made to be fun, and it just happened to be educational.  In other words, the games that are most successful in being educational are games that were designed to be fun and motivating but also happen to have educational value.

The problem with educational games is that motivation is a secondary factor, and it is often ignored.  I believe we need significantly more research into what makes games motivating.  Until that happens though, all we have to go on is observation.  Following is what I have learned from my observations.

Gamifying Education

Gamifying education is what early educational games tried to do.  They start by creating a purely educational activity.  Then, they add game elements to it.  Rarely do the game elements integrate well with the education, but the goal was just to make the education more like a game.  New Math Blaster Plus! offers several great examples of this.

New Math Blaster Plus! has four mini-games designed to teach math.  In one game, you have a practice mode and a solve mode.  The game is nothing more than a simple math quiz.  In practice mode, the solution is displayed before you are required to solve the problem.  In the solve mode, you are quizzed without first seeing the solution.  The quiz is 25 problems long.  The game element is trivial.  Each 5 questions answered correctly adds a component to a rocket ship on the left side of the screen.  Once all 5 components are complete, an astronaut enters the ship and it blasts off into space.

The second game is also a quiz.  Each correctly answered question adds to a meter on the left.  When the meter is full, the player gets a break from the math to shoot garbage floating in space.  Each shot reduces the meter.  Once the meter is empty or all of the garbage has floated past, the quiz continues.

The third game is a simple, one screen platformer.  The player controls a small green astronaut.  The character can walk around and jump.  A jetpack allows the character to sort of fly.  On the left side of the screen an alien slowly descends on the astronout's space pet.  This is a simple gamified timer mechanism.  The character has 5 life (if I recall correctly), and he loses a life if the alien gets to the pet or if he misses a question.  At the top of the screen, there are four...things.  Each displays a number.  Above that a math problem is displayed.  The player's job is to fly the astronaut into the appropriate...thing, before his pet is eaten.  This game is still just a quiz.  This time, it is a timed quiz, and it is more heavily gamified than the other mini-games, but it is still just a thinly veiled math quiz.

We will discuss the fourth mini-game later.  Right now, I want to look at the flaws in the first three.  All three are just math quizzes.  The first provides a mode that shows the player the problem with the answer, so the player can memorize it, but honestly, this is more like homework than actual teaching.  The first game is nothing more than a quiz with a progress indicator.  Calling it a game is actually rather presumptive.  The second one does provide actual game play periodically, but this may actually make it worse.  The game play is interrupting the learning.  It does not do anything to improve the learning, and it is only motivating in that it encourages the player to do math to collect ammo.  A better way of putting is that it makes math a chore.  Welcome to the main problem with U.S. education system: It makes children hate learning.  It turns out that poorly designed educational games can actually hurt education more than they help it.  The third activity, with platformer jet pack flying is probably the best of the first three.  It is straight up a game where you answer math problems.  The math and game elements are not exactly well integrated, but the math does not get in the way of the game play and the game play does not get in the way of the math.

The problem with older educational games is generally that the game play interrupts the learning.  Another educational title from Davison (the maker of Math Blaster), Spell It Plus, has a racing activity where the racer jumps hurdles in response to correctly spelled words.  When the player misspells a word, a hurdle is knocked over, taking attention away from the educational element.  These interruptions also interrupt the brain, and from a learning psychology perspective, the game play, which is the fun part, ends up taking a higher priority than the learning, which interferes with retention.  All of that aside, the games were never that fun.  A game that is not motivating cannot effectively teach, because it becomes a chore.  Yes, students might memorize answers to get it over with, but they won't remember them for any longer than they have to.

Adding Education to Games

At some point, educational game designers realized that their games were just not motivating enough to be effective.  They decided to fix this by creating fun games and then inserting the educational elements.  There is a vast collections of games like this, and some turned out fairly good, but others turned out worse than earlier games.

We will turn to Math Blaster for a case study again.  Many years after the early New Math Blaster Plus!, came Math Blaster Episode I: In Search of Spot.  This new game was a game, not a bunch of thinly veiled quizzed.  I don't recall all of the details, but I distinctly recall one of the mini-games.  It was a platformer.  The player would run around collecting things and trying to get through levels without dying.  Each area had a locked door, and the only way to open it was the answer a math problem.  What they had done was make a game that was probably pretty fun, and they inserted math problems here and there as obstacles.  There are three problems with this.  The first is that the educational element is less dense.  A player spending 30 minutes on the old game would probably complete 60 to 100 math problems.  A player spending 30 minutes on this new game would probably complete 15 to 30 math problems.  The game lost a lot of its educational value, by replacing math time with game time.  Second, this ruined the motivation of the game.  Without the math, the game would have been pretty fun, but the constant interruptions made it get old quite fast (I watched several siblings get bored of it far faster than they did with similar non-educational games).  By inserting the math, they ruined a perfectly good non-educational video game.  Third, interrupting something fun with boring learning makes kids hate learning.  I am not saying that all education is boring, but frequent one problem math quizzes with no practical applications certainly is, and it turns math into an annoyance and a chore.  This game is teaching kids that math is a necessary evil, when it should be teaching that math is a useful tool that can even be fun to learn and use.

This is a common current trend with educational games.  Educational game designers have realized that motivation is important, but they still have not figured out that throwing boring education in the face of students when they are trying to do something fun only makes the problem worse.

Turning Educational Activities into Games

This is where the secret is.  Why are games like Minecraft so successful?  What about history oriented games, like the Age of Empires series?  The reason Minecraft is so successful is that it manages to be motivating and educational at the same time.  The reason the education does not ruin the motivation is because it is part of it.  The trick is to take an activity that is already educational, and focus on the educational aspect.  Minecraft makes people want to learn math, because math can improve their performance in the game, making it more fun.  Age of Empires was ingenious, because it did this intentionally.  History makes an obvious and easy target for this sort of thing, because it takes historical activities and turns them into games, where learning the history is part of the fun.  It turns out that there are a lot of games that do this kind of thing.  None of them really focus on the educational aspect though (not even Age of Empires).  The secret is motivating the player to want to be educated, and then make the game teach the player.  Once the player is motivating, the learning will be much easier, and being able to apply the knowledge gained within the game will help the player to retain it.  It is a simple trick, but everyone seems to be so focused on forcing people to learn that they don't even think about trying to make the learning itself fun and motivating.

So, why does this work?  There are several reasons.  The first is integration.  If the game and learning are well integrated, the player will never feel like the game and educational element are interrupting or interfering with each other.  The second is basic learning psychology.  People learn better when they want to learn, and people retain learning better when they immediately apply it.  So, give someone a game that is motivating, well integrated, makes the person want to learn, teaches the person, and motivates the person to immediately apply what he or she has learned, and you have a truly successful educational game.  And if you can do that, it will probably also sell well.


I said I would discuss the forth mini-game in New Math Blaster Plus!  This mini-game is the only one in the game that is not a quiz.  It is actually more of a puzzle game, and the puzzle is the math.  The player is give 5 columns of symbols.  The first, third, and fifth are numbers, while the second is math operators, and the fourth is equal signs.  Below the columns there are three spaces.  The first is the solution space.  If the symbols in the solution space compose a correct math problem, then pressing Enter will remove the numbers, and the player will be awarded points.  The second space is a recycle space that can contain symbols, and when Enter is pressed, if the solution space has a correct problem, those numbers will be recycled by putting them on the top of their respective columns.  The third space is the zapper.  Anything that gets to the zapper will eventually be destroyed, removing the chance for the player to use them to earn points.  On top of the columns is the green astronaut.  The player can move the astronaut left and right, and when standing on a column, pressing the space bar will cause the astronaut to push the symbols in the column down once (pushing symbols from the solution space into the recycle space and symbols in the recycle space into the zapper).  The ultimate objective of this game is to use all of the symbols provided to create solutions, without zapping any.  It is fun and challenging, and it is an effective application of math skills.  It is also well integrated, because the math is the game.  It may not be motivating to everyone, but for those whom it does motivate, it is actually a good learning tool.  This is the one activity New Math Blaster Plus! did right.  The game still does not teach math (the practice mode on the first quiz activity hardly qualifies as actually learning math), and it really does not strongly motivate people who have already been conditioned to hate math, but does offer an application of knowledge, and it is motivating to some people.



Designing good educational games has proven to be a very elusive goal, but I think it is much simpler than it is made out to be.  I think the biggest problem is an industry that is stuck on a traditional model of education, and I think we can all see how that is working out for the U.S. education system.  I believe a mix of learning psychology and game psychology are the first step on the road to successfully integrate computer games into our education system, and games like Minecraft seem to support this.

Video Game Design: Design Patterns

Design Patterns are common abstract patterns or methodologies used in programming, that tend to be useful for a large range of problems.  If you are not familiar with the concept, let me recommend spending a few minutes learning about the general idea of design patterns.

In video game development, there is a large collection of design patterns that are commonly used.  Many are used only in very large games, where problems can arise without careful management and organization of code.  There are a few that are used almost everywhere though.  This article is going to discuss the three most commonly used video game design patterns, and we will also briefly discuss one design pattern that is widely used in nearly every domain of software development.  Knowing these design patterns can make video game development much faster.

Before we start, there is one other thing to keep in mind: It is very rare when a design pattern will work for a specific problem in its pure state.  Design patterns are not careful recipes that must be followed perfectly for satisfactory results.  They almost always need to be tweaked and adjusted to fit any specific application.  Think of a design pattern as a template or starting position, and then customize it to fit your needs.

Game Loop

This is an essential design pattern in video game design.  It is so important that a vast majority of games end up using it, whether the developers know about the design pattern or not.  It may even seem so obvious that it does not need to be stated.  Understanding this design pattern can allow you much more flexibility in customizing it to your needs though, so there is significant value in discussing it.

In a nutshell, the Game Loop design pattern is implemented by making an infinite loop (with some means of escape) that executes all of the game operations within it.  This includes handling user input, updating the game state, and drawing graphics.  It may include other output, like playing audio, and it may include things like networking.  Once the game has started, nothing happens outside of the game loop, unless the user produces input telling the game to terminate.

The game loop has several responsibilities that may not be initially obvious.  The most important one is to decouple time from input.  By default, operating systems only support text input and they buffer program input.  This means that all input takes the form of text, and when the program requests input, it stalls and waits until the os provides it.  The os presents the user with a prompt, and it buffers the input until the user presses Return or Enter.  In most video games, this is unacceptable.  If the game is real-time, it needs to be updating the game state regularly, even when it is waiting for user input.  It also needs to be redrawing the graphics to the screen regularly, whether it is real-time or not.  If the program is waiting for the os to return with user input, the game cannot do this.  Decoupling time from input allows the game to keep running even when the user is not providing input.  The game loop must process input when it comes, but it should not wait for it to become available.

The second responsibility of the game loop is to decouple time from processor speed.  This can be more difficult, and it may be outright impossible with a high performance game on a very slow system.  Long ago, most games relied on processor speed for time regulation.  The game loop would do enough stuff that the processor could just keep up at a reasonable pace.  This lead to a serious problem as processor technology improved.  Games that ran at an acceptable pace on an old processor would run so fast that they were unplayable on newer, faster processors.  The initial solution was the addition of a "turbo button" to new machines.  This button could be used to reduce the clock speed of the processor to make it equivalent to the older machines, thus allowing the games to run at the right speed.  This worked, but it was a poor solution.  As machines improved and as new games were made for each new processor speed, turbo buttons would have to offer more and more clock speeds, and the processors would have to support those speeds.  This was an untenable long term solution, so game developers had to find a better solution.  Their solution was to explicitly regulate game speed in the game loop.  This is part of the responsibility of the game loop.

In a video game, the game loop is the most important part of the code.  It is the main bottleneck.  If it runs slowly, the whole game will suffer.  If it does its job well, the game will be able to run smoothly on any system fast enough to handle the game.  This design pattern is used in nearly every video game, but it is practically non-existent outside of video games.  There are some non-game applications that could benefit from it though.

 The typical outline for a game loop has several elements.  The first is a while loop.  This is the game loop, and it must run indefinitely.  It can either use true for its condition, or it can use a condition variable that the input processing can change if the user wants to exit the game.  The game loop should be expected to run for as long as the user wants it to run.  Inside the game loop, three are three more elements.  The first is input processing.  The second is updating the game state.  The third is redrawing the screen or rendering.  If these are the only thing in the game loop, order is not important, however, if there is also a network handler and an audio player, order can affect how the player perceives the responsiveness of the game.  If too much stuff happens between input processing and updating the game state, it will introduce input lag, which can be very frustrating.  If too much stuff happens between updating game state and rendering graphics, it can make it appear like there is input lag, which is generally just as bad.  The most important thing, though, is making sure the entire game loop runs at an acceptable speed.

Speed is essential for a game loop.  The speed of the game loop dramatically affects how the user perceives the game.  A slow game loop will result in choppy graphics and laggy input, both of which can make a game unplayable.  It is generally a good idea to know how fast your game runs on the systems you expect it to be played on.  With the default game loop configuration, the most common way of measuring performance is in frames per second (FPS).  Technically FPS refers exclusively to graphics frames rendered each second, but when the frame rate is tied to the game speed, it is an accurate measuring device.

The speed of your game loop will be affected by a number of things.  Input handling generally does not take much time.  Updating game state, however, can take a significant amount of time.  This is largely dependent on the complexity of the game physics and the number of objects that need to be updated.  Rendering graphics often takes even more time.  This depends mostly on the number of objects that must be rendered, though with 3D graphics, the complexity of the objects as well as things like shaders can play a big part.  In addition to all of this, there is also hardware.  The processor, memory, video card, sound card, and operating system all play a role in how fast your code runs.  Understanding these things can help you to determine the system requirements for your game, and it can also allow you to optimize your game to run on less powerful systems, by reducing or limiting complexity.

In games, it is common for the number and complexity of game elements to vary.  One area might have tons of objects, while another might be barren.  This will affect the speed of the game loop.  The game play needs to maintain a consistent speed, despite this.  The game play should not be faster when there are fewer game elements on the screen and slower when there are more.  It should appear to the player to have a consistent speed at all times.  Likewise, the game speed should be consistent across different hardware.  The game should not run at different speeds on different hardware.  This is especially important when it comes to networked games.  There are several ways to maintain consistent game speed, though they all have cases where they will fail.

Managing timing in a game loop is called scheduling.  There are many ways to handle scheduling, but three of them are most common.  The first is merely adding delay.  To add delay, you begin the game loop by getting the current system time.  At the end of the loop, you calculate the time elapsed, and then you subtract that from the amount of time you want each game loop to take, and you have the program sleep for that amount of time.  This will force the game loop to run at a specific rate, and it will allow the operating system to do other things while the program is sleeping.  The problem with merely adding a delay is that it only helps if the hardware is fast.  If the hardware is so slow that the processing in the game loop takes longer than the time you want each loop to take, the game will run slow.  If you never expect your game to run on hardware this slow though, just having a delay is fairly simple and efficient.

The second common scheduling method is called variable or fluid time.  Essentially, it scales game state updates to the time elapsed.  All updating functions in this method take the time elapsed as an argument, and this time is calculated at the beginning of each game loop.  All movement or progression calculations are scaled based on the time passed.  For example, if a character should move 5 pixels per second, then the movement distance each frame is 5 pixels divided by the time elapsed in that frame.  The benefit with fluid time is that the game play speed will never deviate.  Even if the game is running at only 5 frames per second, the speed of game play will be consistent (though, the game will not really be playable).  This can also allow for very accurate physics on very fast system.  There are two problems with this scheduling method.  The first is that it requires a lot more math, and all time dependent update math must be floating point math, which is generally slower than integer math.  This will likely make your game run at least slightly slower.  In most cases, the fact that the game uses fluid time will make up for this problem though.  The second problem is that fluid time makes keeping games synchronized over a network very difficult.  A fast system is likely to accumulate more floating point error over time than a slow one.  In most cases this won't make a noticeable difference, however when two players are playing over a network, it will.  Adjusting for the differences in floating point error will require significantly more network communication, which could result in unexpected behavior, lag, or other problems.  Fluid time is generally a bad idea for a game that is going to be networked, and it may have performance problems on slower systems due to the extra math.

The third common scheduling method is frame skip.  Since rendering is typically the bottleneck in a single threaded game, skipping a frame when the game is behind can quickly allow the game state to catch up.  This scheduling method starts with the delay method.  The delay method caps the frame rate, but it cannot help if the speed is too slow.  The frame skip method keeps track of total time elapsed minus the time that should be taken by the game loop.  If this number ever exceeds the time expected for two frames, rendering is skipped until the game catches up.  There are a few ways to do this.  Either the rendering can be in an if statement that only runs the renderer if the accumulated time is not too large, or the game state update code can be put in a while loop that keeps running it and decrementing the counter until it is caught up.  Because this is more complex than the other two, I will provide some pseudocode:
elapsed = 0
t = time.time()
while:
    elapsed = elapsed + time.time() - t
    t = time.time()
    processInput()
    while (elapsed > 16):
        update()
        elapsed -= 16
    render()
The important thing with this is that we are not recalculating the elapsed time each loop.  We are adding the currently elapsed time to the leftover elapsed time from the last update.  You may also notice that this does not have a delay.  Ideally, there should be a delay for 16 - elapsed at the end, however, without it, the renderer and input handling are allowed to use extra time, which will make the game more responsive on a fast system.  It is a trade off.  With the delay, the game consumed less power and gives its extra time to the operating system.  Without the delay, it consumes more power, but it also is more responsive.

Frame skip comes with its own problems.  First, if the game state update takes longer than the expected time, each game loop will take longer than the last, because more and more time will be spent trying to catch up.  This effectively results in infinite lag.  If the update time is too long, we can get stutter in the graphics, because the game is not being updated frequently enough.  Multithreading can be used to put the renderer and input handling in a separate loop that runs concurrently with the game update, and this can mitigate a lot of the problems, even on a single core system.

There is a fourth option for scheduling.  Many game libraries and frameworks include scheduling mechanics that you can use.  Writing your own game loop gives you a lot of flexibility and the ability to customize the scheduling to your game, but it can be more work than using an existing system.  Using an existing system is generally easier, but it is also far less flexible.  That said, in some cases, there is no other option.  For example, JavaScript in browsers does not allow scripts to run indefinitely.  Instead, you use a callback system that handles the scheduling for you.  You can tell it to run your functions on a given schedule, but you are forced to rely on the browser to keep that schedule, and it is rarely accurate.  Generally you will get better results by writing your own scheduling system, but sometimes it is undesirable to spend the time on it, and in some cases it is even impossible.

The game loop pattern is probably the most essential design pattern for any video game.  It is the root of the game, where everything starts from.  It is also where scheduling will need to take place.  Getting your game loop right is often the most important step in making sure your game runs smoothly.

Update Method

The Update Method design pattern is commonly used in object oriented games.  Heavy object orientation is not always good for video games, because it comes with performance costs, but this design pattern is not very difficult to adapt.  The Update Method Design pattern makes handling a heterogenous mixture of game entities much easier.

In an object oriented game, game entities, including characters, in-game objects, and other parts of the game (like the map) are represented as objects (class instances).  Typically all of these objects need to be updated every game loop.  There are many ways to do this, but the Update Method design pattern is one of the most common.  Somewhere a list of game objects that need to be updated regularly is kept.  In the game loop, when the function is called that updates the game state, that function iterates through the list of game objects calling the update method on each of those objects.  Most commonly, this method is just called "update".  Every object that might end up in the list of updateable objects needs this update method.

Implementation of this is language specific.  In Java, it is common to use an interface.  In C++, inheritance will probably be used.  In Python, object type is not important, so long as all of them have an update function with the same name.  What is important is that anything that will need regular updates has this function.

This design pattern can even be adapted to non-OOP languages or games, with a bit of work.  Even in the worst case, and update function can be made for each entity type, and then the different entity types can have their own lists.  The main update function can then iterate through the lists, passing each element to the appropriate updater function.

The implementation of the update method will depend largely on your scheduling method.  If you are using any kind of fixed frame scheduling (the game loop is run at specific intervals), then the update methods can assume that the amount of time passed is always the same.  If you are using a variable time scheduling method, then the time elapsed since the last update will need to be passed into each update method, and the update methods will have to use that for scaling.

Update Method is a very useful design pattern for keeping your game organized and easy to maintain.  It makes adding new game entities much easier, and it helps to keep your code understandable.  It does come at the cost of a lot of function calls (a simpler system might loop through game entities, operating on them directly), but often it is worth the small performance cost.

Component

The Component design pattern is not as general purpose as the previous two, but it mitigates a major problem in game development.  That problem is coupling.  A program with high coupling has a lot of interdependent code, which means two things.  First, high levels of interdependent code means that if one piece of code breaks, it is likely to have wide reaching effects.  This can result in a lot of time spent finding and adjusting code scattered throughout the program, just to fix or modify something small.  Second, high levels of interdependent code also makes maintenance very difficult.  Unfortunately, in video games, this is very difficult to avoid.  A single character might need to interact with the input system, the graphics system, the physics system, and the sound system.  The menu system also needs to interact with all of those except the physics system.  The map system probably needs to interact with the graphics system, the physics system, and the sound system.  A small change to the sound API will require all three of these to be adjusted, and if the game has 20 or 30 different characters, this may require changes to 32 different pieces of code.  In a large video game, with characters, items, terrain, destructable and non-destructable terrain features, a menu system, and so on might end up having hundreds of places in code where a simple API change requires adjustments.  Further, a tightly coupled game can become a development nightmare, because a character designer might end up having to poke around in sound system code, and the sound system coder may end up having to figure out exactly who an API change affects, which can result in a lot of people working on the same pieces of code.  This can end very badly.  The Component design pattern helps to separate concerns by centralizing API usage and packaging components.

The Component design pattern also helps with one other thing.  While OOP tends to extol the virtues of class hierarchies, complex inheritance trees can cause all sorts of problems, including maintenance issues and performance issues.  The biggest problem though, is that inheritance tress are not a very good model for the kinds of objects often found in video games.  The Component design pattern generally uses only one class type for a given entity type (for example, all characters, including player character, NPCs, and so on, use the same object type).  Instead of an inheritance hierarchy, it composes entities out of components.  This results in a trivial inheritance hierarchy, it minimizes performance issues, and it allows for a much wider range of options.

The Component design pattern uses an object as a template.  That object has a collection of component containers, generally one for each component type.  These typically include an input component, a physics component, a graphics component, an audio component, and an AI component.  For a player controllable character, the input component might take input directly from the keyboard and mouse.  For an NPC, the input component will dynamically generate input for the object, probably based on the AI component.  The specific collection of components define the behavior, look, and sound of the object.

Components should not interact directly.  Sometimes this is unavoidable, but it should be avoided where possible.  To facilitate this, components should also contain their own data, except when sharing is necessary.  For example, the input, AI, and physics components might all need to access the location of a character.  If all of that type of component object need location data, the object might be a good place to store it.  Otherwise, it might be better to store it in physics, and either allow some direct interaction, or create a place for interaction to take place indirectly.  In some cases it may even be a good idea to create a special component specifically for communication between other components, though this can increase complexity.

The Component design pattern is generally used when high flexibility is necessary due to having a large number of necessary entities.  A database of hundreds of classes for different types of monsters can be very difficult to manage.  Often there are many different graphics, but there are 20 or fewer behaviors, and the other differences are trivial (max HP and such).  Instead of classes, you can create a collection of component classes, and then create factory functions that will compose the appropriate monsters from the different components.  Not only does this make things more manageable, it can also allow for combinations that would not have been possible otherwise without creating new classes for them.  For very small projects, the Component design pattern may be overkill, and because it requires OOP for easy implementation (there are non-OOP ways to implement it), it will affect performance, but when organization and manageability are serious concerns, it can be very valuable.

Observer

This is the bonus design pattern.  Unlike the previous ones, which are primarily limited to games, the Observer design pattern is very commonly used in nearly all domains of software development.  It is incredibly useful for handling communication between different parts of a program.  It is not as efficient as some other methods, but its centralization of communication can make development and maintenance much easier.

The Observer design pattern allows objects to registers as Listeners.  A Listener generally wants to know about a specific type of event.  The event handler keeps a dynamic list of registered Listeners for each type of event.  When an event occurs, all Listeners registered for that event are notified.

A Listener is generally an object that cares about an event.  In OOP languages, Listeners are implemented through interfaces or inheritance.  Each event type has its own Listener class or interface, and anything that cares about that event type inherits.  The Listener class or interface has a single virtual method that is the event handler for the appropriate event, and the child is expected to implement the listener.

The event handler has collections of Listener objects that care about various events.  It has a functions for registering Listeners and it has functions for unregistering.  When a Listener needs to start responding to events, it is registered.  When it needs to stop it is unregistered.  This allows any number of any type of object to listen for specific types of events.

The Listener objects are responsible for handling the events themselves.  Generally, they execute some kind of behavior in their event handling code, though in games this may not always be ideal.  In general, state updates should take place in the update methods, not in the event handling methods.  State updates in the event handling methods can interfere with proper scheduling, by making the event handler take longer than it should.  The Listener objects need to manage their event handling time wisely, otherwise it can interfere with performance.

There are a few options for event handling.  The first is to just do everything in the event handler.  As mentioned, this can cause problems, but if none of the event handling is especially intensive, it may be the best option.  For example, in a platformer, pressing a button might trigger an effect. If that effect just moves an object from one location to another by changing its coordinates, without any other effect, then doing it in the event handler is probably the most efficient way to do it.  On the other hand, if pressing the button starts the character moving in a specific direction, it would probably be better to just set a flag or a velocity variable and handle the actual movement in the update method.  In some cases, a Listener might even need its own internal event queue, and the event handler just adds events to the queue to be handled during updates.  This uses more memory, but it also minimizes the work done by the event handler.  In general though, if the event handler can just make small state changes that will affect the update behavior, that is all you need.

The Observer design pattern is not just useful for user input.  A well designed event handler can also be given internal events.  A great example is messaging the sound system from the physics system.  In an ideal system, the physics system should never play a sound directly.  If it did, it would be susceptible to problems from API changes to the sound system.  Instead, the physics system would send a message to the sound system saying what event happened, and the sound system would play the appropriate sound.  The problem is, if the physics system is calling a messaging function of the sound system, the API problem still exists.  Instead, the physics system can create a new event and send it to the event handler.  If the sound system is listening for physics events, it will be notified of things like the character hitting the ground, and it can play the appropriate sound.  This way, the sound system does not have to know about the physics system, and the physics system does not have to know about the sound system, but they can still communicate effectively.  The communication won't be quite as fast, but in most cases, it won't make any difference.

The Observer pattern can also be implemented in non-OOP languages, but it is much more difficult.  In languages that allow passing and storing functions like variables (Python, Haskell...), you can store listener functions instead of objects.  This is usually no more difficult than passing objects, and it may even allow for more targeted event handlers, since the name of the function is irrelevant.  In languages like C though, the only option is to pass function pointers, which requires function pointer arrays, and even arrays of function pointer arrays.  This is possible, and it works very well (I have done it), but it requires impressive pointer skills, and debugging it can be awful.

The Observer pattern is very useful in many applications.  In games it can make event handling much more organized, and more importantly, it can reduce coupling, making code much more manageable and maintainable.


These are just four design patterns commonly used in video games.  By themselves, these four can really make game development easier, but there are many more that can also be very useful.  This book is a great source of information about design patterns used in video games, and it even discusses the ones discussed here in more depth, including examples.  Anyone who is serious about learning game design and development would benefit greatly from reading this book: http://gameprogrammingpatterns.com/contents.html

Tuesday, May 10, 2016

Video Game Development: Movement Along a Path

I nearly any kind of real-time video game, it is necessary to move game entities along a path from one point to another, one step at a time.  When thinking about this, it seems like a trivial problem, but implementation is not so simple.  We are going to look at some ways of doing this.

Technically, there are three ways to do this.  The first one I learned was based on trig.  You have to determine the angle of movement, use a polar coordinate system with the origin at the current position of the entity to represent the movement, and then convert back to Cartesian coordinates.  This is the worst solution.  Computers don't do trig well.  The trig functions, which are used for the  conversions, require a lot of processing power.  It also turns out that it requires more memory than non-trig solutions.  It is almost always best to avoid using trig whenever possible, so we will not be discussing this solution any further.

Triangle Scaling

The second solution is geometric triangle scaling.  Really, what we are working with here is a vector.  The vector is represented as the line from the current position to the desired position.  Most vectors can be represented as triangles, and geometric scaling of triangles is easy.






In this case, the unit is starting at (0, 0), and the destination is (10, 6).  To find the movement vector, we subtract the starting point from the ending point: (10, 6) - (0, 0) = (10 - 0, 6 - 0) = (10, 6).  The triangle representation has a base of 10, and a height of 6.  Scaling this is easy.  Just multiply the height and width of the triangle by some scalar value.  In this case, we want to scale it down, so that value will be between 0 and 1, depending on the speed of the movement we want.  Now, this is where we are going to come up against the limitation of this method, but it may not be initially obvious.

Before we can determine the scaling value, we have to decide how fast we want the entity to move.  We could scale by time passed, but this is more complicated, so we are going to assume that the time value is static (the game is bound to a set frame rate).  So we will say that in one time increment (one game frame), the unit can travel 3 grid units in either dimension.  We want to keep the unit on that line, so we have to make sure both dimensions are scaled by the same value.  The x movement is bigger, so that will be the limiting dimension.  So, we divide the speed (3) by 10 to get the scaling value, which will be 0.3.  Now we multiply both sides of the triangle by that value, which gives us 3 on the x axis and 1.8 on the y axis (position should be stored as a float in most cases).  Now we add this to our current position, giving us the new position of (3, 1.8).  This is where we start at the next game loop, and we have to do all of the math over again.

This is the function, written in Python, for this algorithm:

def move(src, dest, speed):
    '''Move entity using geometric triangle scaling

    src - Tuple with x and y coordinates of current location
    dest - Tuple with coordinates for destination
    speed - Maximum distance moved on either axis
    '''

    # Find the triangle
    diff = (dest[0] - src[0], dest[1] - src[1])

    # If we can get to the dest at this speed, do it
    if diff[0] < speed and diff[1] < speed:
        return dest

    # Figure out the scaling value
    scalar = 0
    if diff[0] > diff[1]:
        scalar = float(speed) / diff[0]
    else:
        scalar = float(speed) / diff[1]

    return (src[0] + (diff[0] * scalar),
            src[1] + (diff[1] * scalar))

This algorithm will work fairly well, but it has the effect of sort of warping the map around the current unit (this is not a visible warping; rather it is a sort of temporal warping; ignore this if you still don't get it).  The problem is that unit move faster at angles than they do parallel to the x or y axes.

Notice on the x and y axes, the entity can move exactly 3 units in either direction.  Now, look at the diagonals.  Using the Pythagorean Theorem, we can calculate the diagonal movement distances as sqrt(3^2 + 3^2) = 4.24, which is much further than 3!  In some games, this is fine.  In fact, most turn based games handle movement this way.  In real-time games though, units will move noticeably faster diagonally, which essentially makes things diagonal to a unit closer than things parallel to an axis (the invisible warping effect).  The benefit is that the math for this is pretty simple.








Linear Algebra

When doing this kind of thing in game programming, the best solution is linear algebra.  Linear algebra can do pretty much everything trig can do, without the need for a polar coordinate system.  This means that you can do most things without the need for trig functions.  The only exception is rotation using an angle, because angles are already polar and must be converted.

The linear algebra solution to this particular problem requires a bit more math, but it also eliminates temporal warping.  In other words, distances are the same regardless of the angle of motion.  The movement range graph would be represented as a circle instead of a square.  For real-time games, this is what you want.  Interestingly, this method is very similar to triangle scaling, with a few important differences.

In any case using a Cartesian coordinate system, vectors can be represented as triangles.  For this though, it is probably easier to treat vectors as vectors. Before we start, there is some important vector math we will need to know.

The first vector math we need to know should already be familiar.  We are going to represent vectors in the following format: <x, y>.  This will help avoid confusion with coordinates: (x, y).  (Technically coordinates are position vectors, but we need to differentiate between position vectors and vectors representing desired movement.)  We will need to know the length of our movement vector.  The length of a vector is found using the Pythagorean Theorem, as if the vector elements were the sides of a triangle.  For a vector <x, y>, sqrt(x^2 + y^2) = length.  This length will always come out positive.  In linear algebra, this is called the "norm" of the vector, and for a vector v it is represented as |v|.

The second important vector math is the unit vector.  The unit vector for any vector points in the same direction as that vector, but it is exactly 1 unit in length.  Unit vectors represent directions (or angles).  This is important, because we will want to move our entity a set distance in a specific direction, without worrying about the distance from the source to the destination.  The unit vector is found by dividing the initial vector by its norm, represented as v/|v| = u.

This should be enough vector math to create the algorithm we need.  We start by finding the difference between the source and destination vectors: m = d - s (bold symbols are 2 element vectors).  Given s = (1, 1) and d = (2, 3), m = (2, 3) - (1, 1) = (2 - 1, 3 - 1) = <1, 2>.  So, the total movement the entity needs to get to the destination is <1, 2>.  We don't actually care about this though, because we are only taking one step in this path.  We need to know where that step lands.

Now that we have m, we can use it to figure out the direction of our movement.  This is the unit vector: u = m/|m|.  Using the m we just calculated, that is u = <1, 2> / sqrt(1^2 + 2^2) = <1, 2> / sqrt(5) = <1, 2> / 2.24 = <1/2.24, 2/2.24> = <0.447, 0.894>.  If you take the norm of u, it should be exactly 1 (slightly less, because I rounded).

We could add the unit vector to s (the source) to move the entity exactly 1 unit closer to d (the destination).  This is rarely what is needed though.  In this case, let's say the entity has a speed of 2 units per game loop.  This means we need to move the unit by the value of u twice.  We can find the vector for this by multiplying u by the speed.  The new vector will be 2u = <0.447 * 2, 0.894 * 2> = <0.894, 1.789>.  We want to add this to s to find the new position: p = s + 2u = (1, 1) + <0.894, 1.789> = (1 + 0.894, 1 + 1.789) = (1.894, 2.789).  So, that is our new position, and it is exactly 2 unit closer to d than the original position, on the line between s and d.

This may still be confusing.  If it is, that is fine for now.  This math has tons of applications in game development, from drawing lines to gradating colors to movement.  It is definitely worth learning, but if all you need to do right now is move entities from one point to another in steps of a specific distance, you can work on that later.  Right now, I am going to give you the function, in Python, for finding the next step along a straight line.

def move(src, dest, speed):
    '''Move toward destination by a set number of units

    src   - The current position of the entity
    dest  - The final destination
    speed - The number of units to move
    '''

    # First we need the difference between dest and src
    # Note that this corresponds with m above
    diff_v = (dest[0] - src[0], dest[1] - src[1])

    # We need the norm to find the unit vector
    # Note that you need to import math for this to work
    norm = math.sqrt(diff_v[0]**2 + diff_v[1]**2)

    # Let's make sure we do not overshoot
    # Since norm is the length of diff_v, if it
    # is less that the speed, we have arrived at
    # the destination.
    if (norm <= speed):
        return dest

    # Now we can extract the direction from diff
    unit_v = (diff_v[0] / norm, diff_v[1] / norm)

    # Now we will calculate the actual movement we need
    move_v = (unit_v[0] * speed, unit_v[1] * speed)

    # Now we just need to add the movement to the
    # current position and return the result
    return (src[0] + move_v[0], src[1] + move_v[1])

Given a source, destination, and speed (movement distance), this function will return the next step.  Note that you can take some shortcuts with this that will save memory and processing power.  For example, you can combine the unit_v and move_v steps into a single step to save memory.  Doing that will allow you to precalculate speed / norm, which will reduce the number of divisions in the function by half.  The following code could replace the unit_v and move_v parts:

scalar = speed / norm
move_v = (diff_v[0] * scalar, diff_v[1] * scalar)

The scalar variable only holds one float, instead of a tuple of two floats, and we trade the two divisions for just one.  This may seem minor, but this function will get called for every moving entity every game loop, so the small difference will add up quickly.

In most cases, this linear algebra solution will be the best way to manage real-time movement.



I hereby release the code presented in this article into the Public Domain.  In jurisdictions that do not allow this, all parties may use this code under a license allowing copying, modification, distribution, commercial use, and non-commercial use freely, with or without attribution.

Tuesday, May 3, 2016

Video Game Design: User Interface

It is fairly easy to find academic information on the topic of video game user interfaces online, and from a totally theoretical perspective, that information is quite interesting.  I am going to ignore all of that in this article though, for several reasons.  The first is that most sources use inconsistent terminology that is not very useful for application of the knowledge.  The second is that the highly theoretical focus ultimately fails to provide much value for actual game design.  On an academic level, if you ignore the terminology problems, it is certainly interesting, but when you are actually making a game, it is not that helpful.  Since there is not a significant body of work on this subject that can be applied to real world game design, I will be using my own, very consistent, terminology.

Before we get into the meat of this subject, there are some terms that are important to understand.  To begin with, every video game consists of two "worlds" or settings.  The one everyone is familiar with is the (generally) fictional world inside the game.  This is where the characters or objects that the player interacts with during game play exist.  There is also the "world" of the game application itself.  This world is not part of the game world.  It contains things like the main menu, various other game menus, as well as indicators that tell something about the character or the game world, but which are not an actual part of the game world.  In this article, we will call any kind of interface that exists within the game world an "internal" interface.  Interfaces that exist in the application outside of the game world are "external" interfaces.  There is a second set of terms we will use to specify exactly what a given interface affects.  A "game" interface affects things inside the game world.  A "meta-game" interface affects the application outside of the game world.  This gives us a total of four interface types, defined by where the interface is and what it affects.


Internal Game Interfaces

Internal game interfaces are interfaces that exist in the game world and affect the game world.  The Myst series is full of examples of internal game interfaces.  In the original Myst game, there is a small room at the dock.  Inside there is a holographic projector.  On one wall, there is a control panel can be used to make the projector play back different projections.  This control panel, as well as the button to activate the projector are internal game interfaces.  The controls are part of the game world, and they affect the projector, which is part of the game world.  The entire point of the Myst games is to solve puzzles in the game by using interfaces that are part of the game world.  These are all internal game interfaces.


External Game Interfaces

External game interfaces exist as part of the application outside of the game world, but they affect things in the game world.  Perhaps the best example is input devices, like keyboards, mice, or controllers, which are actually outside of the application, the operating system, and in many cases, even the computer itself.  Input devices often function in multiple capacities, as they can usually affect the meta-game as well, so it might be better to look at interfaces that are part of the application.

World of Warcraft offers some good examples.  One is the crafting interface.  In WoW, when a player wants to craft an item, the player opens a menu window that displays all of the possible items that can be crafted in a specific category.  The player then selects the desired item and clicks a button to tell the game to craft the item.  This interface is not part of the game world.  It exists to abstract and simplify crafting in the game.  The affect once the player submits the desired item is that materials are removed from the character's inventory and the crafted item is added.  This effect is completely within the game world, which is why the interface is a game interface.

In general, external game interfaces exist to abstract in-game processes.  It would not be very reasonable for WoW players to have to literally forge items in-game.  External game interfaces are also very common in real-time strategy games, in the form of menus of buttons used to command units.  Clicking a button represents sending an order to a unit or a group of units.  Even unit selection uses an external game interface.  This is because it would be unreasonable to expect the player to issue vocal commands to every unit, and even something as trivial as grouping units would require the player to memorize unique identifiers (names) for every unit they control.  For some types of games, external game interfaces are essential for making the game playable.

Interfaces do not have to be directly interactive, and the most common external game interfaces are not.  Thinks like health bars and other status indicators are generally implemented as external game interfaces.  The indicator on your screen is not a literal part of the game world.  It is not something your character can see, but it does represent something about your character or the world.  Note, however, that not all status indicators are external.  In a driving game, a speedometer displayed as part of the dashboard of the car is an internal interface.  In the Halo series, the health, weapon, and ammo status indicators are part of the character's equipment, and as such, they are actually part of the game world.  This also makes them internal game interfaces.  Doing this can make a game more immersive, as long as it does not interfere with game play.


Internal Meta-game Interfaces

Internal meta-game interfaces have never been too common.  They tend to break suspension of disbelief, which can ruin the game for some players.  Internal meta-game interfaces exist within the game world, but they affect the outside application.  The one place this kind of interface is common is older console platformers, where the character could save the game by activating an in-game console or save point.  Note, though, that game narrative can affect whether an interface is game or meta-game.  If the narrative states that the character is using the console to store memory and genetic data which can be used to create a new clone of the character in case of death, then the interface is actually affecting the game world and not the application.  Without such a narrative though, this kind of interface is meta-game.

More rarely, in-game terminals have been used as full meta-game interfaces.  Some console games and even a few PC games do not allow the player to access any meta-game controls except when their character is at an in-game terminal.  This may be intended as an immersion tactic, but it is not a very good one.  In general, mixing internal with meta-game or external with game is a good way to break suspension of disbelief and thus make the game less immersive.  The most immersive games maintain strict separation of the game world from the external application.  Perhaps the best examples are the Myst series and the Halo series.  Internal meta-game interfaces can be a fun gimmick, but they tend to make the game feel more casual.


External Meta-game Interfaces

This is fairly simple.  External meta-game interfaces exist outside of the game world and they affect the outside game application.  These include main menus, menus that affect things like key bindings, graphics resolution and quality, and sound volume, menus for loading and saving games, and even autosave features that are activated at the completion of a level.  Even controls that define how a game world is going to be created (difficulty level, terrain parameters, which map to play on, who is going to play, etc...) are external meta-game interfaces (note, however, that a menu for changing difficulty after the game has started is an external game interface, because it is changing the game world; before it is created, the game world does not yet exist to be changed).  External meta-game interfaces are one of the most common types of interface in modern games.


Understanding the different types of interfaces can you tailor a game to have the feel you want.  Immersive games tend to stick with external meta-game interfaces and internal game interfaces.  When complexity is high, external game interfaces may be necessary as a buffer between the player and some in-game process (or they may be necessary to avoid excessive amounts of coding and design on trivial elements of the game).  Internal meta-game interfaces offer some degree of novelty, and they can make a game feel more casual, but if immersion is important to your game, they will likely interfere.


Controls

The controls used for playing a game also have a strong effect on how the game feels and is played.  The ideal controls for a game leverage natural mapping.

Natural mapping is when the controls for a game mirror how the process in the game works in real life.  For example, a driving game that uses a steering wheel and a set of foot pedals maps naturally to how cars are controlled in real life.  The Nintendo Wii has a lot of games that use natural mapping, including bowling and tennis.  Unfortunately, sometimes attempts at natural mapping can fail.  There are a number of games that use motion control that are actually much harder to play, because the designers picked control schemes that seem to use natural mapping but which are not natural at all.  Natural mapping for controls is a fairly young field, so you can expect to see more research on the subject in the future.

Almost as important as natural mapping is familiarity.  This is why attempts at natural mapping sometimes fail.  If a player is used to using a simple controller for playing platformers, adding motion control, even when it leverages natural mapping very well, can make the game significantly harder to play.  While natural mapping can be very good for inexperienced people, familiarity dominates for people that are already familiar with traditional control schemes.  Familiarity is a major reason why so many games still support the WASD keys for movement, even though typical keyboards have had arrow keys for over two decades (there are some other benefits to the WASD key mapping, but familiarity is the main reason it is still around).  Using a familiar control scheme is very useful in game design, because many players will be able to get into the game much more quickly than they would if they had to deal with learning a new control scheme.

 The most common controller types are console controllers, keyboards, and the combination of keyboard and mouse.  Each of these offers unique benefits as well as challenges.  Controllers tend to fit in the hands well, and they are often very intuitive to experienced players.  They also offer a limited range of options, which can keep the controls simple.  Unfortunately, the lack of options can limit overall richness of the game, and it can also make it hard for game designers to map all of the necessary controls for the game.  Because controllers have limited numbers of inputs, they can impose strict limits on how much the player can do in the game.  Keyboards offer an enormous range of control options, which can allow for a very rich game interface.  It is almost impossible to design a game that gives the player enough options to use an entire keyboard.  Keyboards do not offer analog controls though, and the richness of the keyboard as a controller can tempt game designers to make games far too complicated.  The last common control is the keyboard and mouse combination.  The main benefit of this is that it adds a highly responsive analog control.  In games that need a highly responsive analog control, game controllers and keyboards are not enough.  The keyboard and mouse combination is not always available or feasible, but when it is, it offers the largest range of control options.

I also want to share some examples of poor controller choices.  The first is real-time strategy games using console controllers.  Command and Conquer: Red Alert and Starcraft are two RTS games that were released for console.  Unfortunately, neither were very successful.  I once watched someone try to play Red Alert on a console, and the reason for the lack of success was clear: Game controllers are not responsive enough.  A secondary problem is the lack of hotkeys, but the response time was the main problem.  In RTS games, the most successful players are the ones who can quickly select arbitrary groups of units and give them orders.  It is important to be able to split up groups of units that are close together very quickly.  Waiting for a pointer to move across the screen as you hold the joystick or digital pad on a controller is a problem, and changing the speed of the pointer does not help.  The general process of quickly selecting a group of units with a mouse involves an initial very rapid movement to get the pointer close to the units, then the movement slows down a bit to ensure units are selected precisely.  Even a good analog stick with cursor speed based on how far the stick is pushed cannot get the same precision as a mouse.  This added to the very limited hotkey selection imposed by a controller with only a few buttons makes RTS games very difficult to play using controllers.

The second example was self imposed.  Some guy decided to get good at playing DOTA2 using a PS 3 controller.  He proved that it is possible, but he admits that the controller is so limiting that he could never compete with top players.  The problem is that he has reached a point where the controller limits his skill in the game, where a keyboard and mouse would allow additional improvement.  While it may have been a fun experiment, and he did prove it is possible to get good at the game with a controller, ultimately the complexity of the game makes it impossible to progress past a certain point without a better interface device.


Aesthetics

We have mostly talked about technical parts of user interface.  While having a good user interface is essential to a good game, usability is not the only important factor in user interface design.  Aesthetics is also very important in how players feel about your game, and the user interface is a large part of that.

How your interface elements look and work has a major impact on the look and feel of your game.  A user interface that seems out of place for the style of game can harm the experience for players.  Look and feel is also an element of branding.  Using a consistent user interface style can define your game and your company.  A smooth user interface can make your game feel well designed and very user friendly, while a clunky user interface can make your game feel poorly designed, even if the game itself is the same.  In a game intended to be immersive, a well integrated user interface that blends into the game can make a huge difference.  When designing a user interface for a game, it is important to consider how it will make the game feel for players.

When using a programming language that comes with a GUI library, it can be very tempting to use the various UI elements included in the library.  It is easy to find GUI libraries with stock buttons, menus, check boxes, and so on.  Giving in to the temptation to use these can ruin a perfectly good game idea.  Using stock UI elements imposes the aesthetics of the library on your game.  For extremely casual games, this is not always a bad thing, but this tends to make games look unprofessional.  Whenever possible, it is best to make your own custom UI elements that fit the look and feel of your game.  Some UI libraries offer options for this, but many are not sufficiently customizable for making professional looking games.  Often it is best to create a simple framework for making custom UI elements, and then tweak a copy of it to work for each game you use it in.

Aesthetics can be an important element of brand identity.  You will get a reputation based on how your games look and feel.  If you consistently use old 8-bit style graphics, you will get a reputation as a modern retro game maker.  If you consistently use low quality graphics, you will get a reputation for crummy graphics (this is not necessarily a bad thing, for example if you have a reputation for very engaging stories in your games).  Cartoonish interfaces will make your company feel more casual, and more realistic interfaces and graphics will make your company feel more hardcore.  When selecting graphics and designing UI, it is wise to consider how your game aesthetic will make people feel about your brand.

Video Game Design: Game Psychology

Every successful video game leverages human psychology to keep players engaged and motivated.  Good games can be made without a solid understanding of the psychology, but it is much easier to make a successful game, if you understand how to keep players engaged and motivated.

 Every video game designer endeavors to make a "fun" game.  What is "fun" though?  If we could understand exactly what makes a game fun, then we could make all sorts of game with no fear of failure.  There are a number of common game activities that are considered fun.  One category is exploration.  This includes things like discovering new things, experiencing a story as it unfolds, doing things we cannot do in real life, and wielding extra power.  Another category is playing.  This includes exercising real skills, doing real thinking and problem solving, and accomplishing real achievements.  There is also the meta-game, which includes enjoyment of how the game is implemented and joking about the game.  The problem with all of this is that different people enjoy different categories or different subcategories.  There are a lot of people that find the economics of Eve Online to be great fun, but many other people feel like it is a lot of unnecessary drudgery.  Some people enjoy the constant action of real-time strategy games, while other people prefer games like chess, where players can spend some time thinking about their decisions before they commit.  The fact is, "fun" is far to subjective to be a useful metric in designing games.  Using game psychology to design successful games needs a bit more science.

There are two things a game needs to be successful.  First, it needs to be motivating.  A motivating game will first convince people to play it, then it will make players want to do the work to accomplish tasks that drive progression in the game.  Second, it needs to be engaging.  An engaging game will keep the player playing, even if there are other entertainment options available.  A motivating game will make the player want to play it, and an engaging game will make the player not want to stop.  If you can make a game that is motivating and engaging for a large number of people, your game can be successful.


Scoring

Scoring is an important motivation tool for games.  Scoring is a metric for progress within a game, and video games can have many different scoring metrics.

Points is a generic scoring metric that generally measures the overall success of a player.  The player will gain points for actions that help the player progress.  This encourages the player to progress more, and it offers a metric for comparing the progress of different players.

Prestige is a scoring metric that is reputation based.  In some games, prestige might be represented as reputation with NPCs.  In multiplayer games, it might be something like a titles or achievements.  Prestige in multiplayer games can encourage competition between players.

Levels is a very common scoring metric in RPGs.  Not only is it a metric for comparing how powerful a character is, it is also used to determine how powerful a character is.  Levels can encourage competition, but usually they just motivate players to want to progress more.

Ranks is a scoring metric similar to levels and prestige, but it is generally only of importance to NPCs.  Ranks don't necessarily determine how powerful your character is, but they may affect what your character has access to.  Ranks are a level independent measure of the characters position in an in-game group or organization.  For example, a character may have a rank in an in-game military that affects what technology the character has access to.  The character could also have a level that determine how well he or she can use that technology, but it does not affect access.  Rank can encourage competition, however it is usually sufficiently motivating by itself.

In-game currency can also be a scoring metric.  How much game money a player has can affect what the player has access to, and for some people, amassing a lot of game wealth can be a strong motivator by itself.

In RPGs and similar games, gear or equipment can be a valid scoring metric.  In Diablo 2, level advancement tends to stall around the early 90s.  Once a character has gotten into the 90s, gear makes a much bigger difference than level, so the primary metric of progression is how good a character's gear is.

Collectables, including badges, achievements, items, or even graphics (some modern games have unlockable "skins" that are alternative graphics awarded for accomplishing some task) can also  be strong motivators for many people.  Collectables are especially good for end-game characters, to help avoid the boredom that can be brought on by a sudden halt in progress.

Scoring is generally a motivator.  People want to play a game to progress, and scoring shows them that progression.  Wanting to level up your character, get better gear, or amass more wealth in a game makes people want to play that game.  Scoring can help a game be more engaging, but it is not usually engaging by itself.


Envy and Competition

Competition can be both motivating and engaging.  Playing a game because you want to beat a friend's high score is motivation, but playing with a friend (cooperatively or competitively) is engaging.  If as long as your friend is playing, you want to keep playing, it is engaging.  There are several common things that can encourage competition, generally by causing envy and a desire to do better than someone else.

Leaderboards are perhaps the biggest mechanism for encouraging competition.  A leaderboard is an ordered list of players.  It is ordered by score, with the highest score at the top  Each entry lists the player in that position and that player's score.  The typical leaderboard has a limited number of entries, containing only the highest scoring players.  Leaderboards motivate players in several ways.  First, they give the players a goal.  Since leaderboards show the score of the highest ranking player, other players can see that score and know what they have to beat.  They also know who they need to beat, which may encourage competitors to target that player (depending on whether the game mechanics allow this or not).  Once a player gets on the leaderboard, there is additional motivation and even engagement, as the player can see the progress more clearly.  Leaderboards are not always the best mechanic for all applications, but they are so common because they work.

Badges are virtual rewards given for accomplishing some task.  They are essentially awards for achievements.  Badges give players something to compare.  Badges can be awarded multiple times, each time a difficult task is completed, or each badge can be awarded only once, to signify that some challenge has been overcome.  Perhaps the best example of badges is Khan Academy, a web site devoted to offering free education to anyone with internet access.  Several years ago, the founder of Khan Academy was working with a grade school class, and several of the students using the web site started competing with each other for badges.  Supposedly, they ended up going through elementary, and high school level math, into college level math, just so they could get more badges.  Badges can be extremely strong motivators, and when people start competing, they can encourage intense engagement.

Even bragging rights can be a motivator.  When someone accomplishes an especially difficult task in a game, they may feel justified in making a big deal about it to friends.  Even something as simple as this can be a good motivator.  Bragging rights can also help engagement, if a player is close to accomplishing some difficult task.  Bragging rights might be something as simple as beating a very difficult opponent for the first time, or it could be something as complicated as beating the entire game on an especially high difficulty level.  In general though, people like to share especially notable things they have done, and giving players opportunities to do things worthy of telling can make a game more motivating and engaging.


Peer Pressure

Peer pressure can be good for motivation and engagement.  People like to play games with their peers, and when they peers encourage them to play a game, they are more motivated to do it.  Peer pressure can also make a game more engaging, especially when friends can play the game together.

Peer pressure is such a strong motivator that it can motivate people to play games they don't even like.  A great example is Call of Duty.  It turns out that a significant number of Call of Duty players do not actually consider it a "fun" game.  They don't enjoy the game itself.  They only play it because they have friends who play it.  The motivation in this case is not fun.  It is companionship and human interaction.  When they play with their friends, these people can be very strongly engaged in the game, despite the fact that they do not find the game fun.  This brings up some interesting observations.  A game does not have to be fun to be fulfilling.  A game that is not fun can still have legitimate value.  Admittedly, it would probably be an even better experience if these people played games with their friends that they did find fun, but even a game that is not fun can have value.  This offers some additional insight into why "fun" is not a very good metric for the value of a game.

Another example of peer pressure motivating people to play a game is Farmville, which relies almost exclusively on peer pressure for motivation.  Engagement is handled by having scheduled events (crops need harvested on a regular schedule, or they will wilt and lose value).  The primary marketing strategy, however, is purely peer pressure driven.  As with Call of Duty, Farmville has value whether people find it fun or not.  Many people use social games like Farmville to keep in contact with friends.

Peer pressure tends to be associated with bad behaviors like drug use, but peer pressure does not have to be bad.  It might seem a bit manipulative for games to use peer pressure to motivate players, and it probably is, but not only is it an effective marketing strategy, it can also provide ways for games to be more beneficial.


Cheating and Strategy Guides

This is a psychological thing, because it is about how players feel about and react to certain game strategies.  Cheating in video games is generally looked down on.  This is even true of single player games, where cheating does not give any advantage over anyone else.  It is such a big thing that there are even myths about it.  According to many gamers, using cheat codes to improve your chances of winning will prevent you from improving your skill in a game.  It turns out that this is not true.  Cheat codes can be used in the same way training wheels are used on bicycles.  I have had experience with this effect in several games, where I started out with cheat codes, but eventually I gained enough skill to get by without them.

Cheating is looked down on so much that there is a specific term for playing though a game without cheating.  This term is playing "legit."  Someone who cheats is "not legit."  From a competitive perspective this makes sense, but in single player games where no one cares about score, it makes no difference, but many people are so concerned with cheating that it bothers them when other people do it.

In competitive games, cheating is a lot more serious, and it goes beyond just cheat codes.  If cheating can give one player a competitive over another, then it becomes truly problematic.  This will be discussed more in a future article, but preventing cheating in multiplayer games can be quite challenging, but it is also essential for games that may be treated like e-sports.

Strategy guides are generally not viewed as cheating, but in some circles they are looked down on.  Generally strategy guides provide hints about how to beat or do well in a game.  In non-competitive play, strategy guides are often viewed the same way movie spoilers are viewed.  For many people, discovery is part of the fun of the game, and strategy guides tend to ruin that.  For competitive games, however, strategy guides are starting to see greater acceptance.  For games that have become e-sports, competitive players often spend a lot a time watching videos on strategy to improve their own skills.  This is a lot like how basket ball players sometimes watch videos of themselves or their opponents to learn and improve


Investment

Investment can be a very strong motivator for games.  This includes both money and time spent on the game.  When a person has spent a lot of time or money on a game, they are more likely to spend time playing it, because they don't want to feel like they have wasted anything.  Ironically, this further increases the investment, which also increases the motivation.  There are some business models that capitalize on the connection between investment and motivation.

The subscription model is a very effective investment motivator.  The subscription model requires players to pay a regular fee (generally monthly) for access to the game.  Once a person has spent a few hundred dollars on a game, they are less likely to quit playing it, because quitting would make them feel like they are losing all of the money and time they have already spent on the game.

The paid content model allows people to play the game for free, but it offers special content for some kind of payment.  The paid content may just be something that takes a long time to get normally, or it may be something that cannot be obtained without paying.  Either way though, when a person has paid a lot of money for in-game content, that person is less likely to quit playing the game, because it feels like the money paid would be wasted.

Even just time invested into a free game can be a motivator, if there is some long lasting benefit gained from spending that time.  Things like character levels, items, or even just collectibles can make time spent playing a game feel valuable enough to make a player want to keep playing to avoid losing a valuable investment.


Example

World of Warcraft is a very good example of using psychology to motivate and engage players.  The advancement cycle of WoW early in the game is designed to be very engaging.  The player easily increases in level at quite a fast rate.  The fast rate of progression keeps the player engaged.  This progression gives the player a sense of achievement, and it makes the character feel like an item of great value.  It only takes a few hours to get a new character up to level 20, so the time investment is not that great, but the character itself feels like it has value, and abandoning it would feel like throwing away a valuable item that required several hours of hard work to create.  This connection between the player and the character motivates the player to continue playing the game, even when the progression slows down dramatically.  Once this happens though, the character is even better, with better equipment and more in-game currency, and the player has invested a lot more money and time in the game.  This progression curve hooks new players, and then keeps them through investment based motivation.

WoW also uses a good engagement strategy in its quest system.  Quests are tasks given to the characters by NPCs.  WoW's quest system works by giving characters many small quests, with small rewards, in rapid succession (often with some concurrent quests, so that multiple quests can be worked on at the same time).  This constant stream of small quests always giving players something to do is engaging, but by itself, eventually it will get boring.  So, occasionally, the characters will be given larger quests with much better rewards, to interrupt the stream of small quests, and to motivate the player to continue doing the small quests.  This reward cycle keeps players engaged and motivated, and it also keeps the character constantly gaining experience and better equipment, which makes the character progress.  All together, the steady stream of small rewards, the occasional big rewards, and the constant character progression keeps the player engaged and motivated.  The result is that WoW is one of the most profitable video games ever created, has 5.5 million subscribers (it has been as high as 12 million), and the total cumulative WoW time played by all of humanity totals well over 6 million years.


Psychology is essential to creating a successful game.  Understanding how psychology affects motivation and engagement in games can help you to make games that are much more likely to be successful.