Quantcast
Channel: GameDev.net
Viewing all 17825 articles
Browse latest View live

Social Media Handbook Policy

$
0
0

Introduction


So, you are an indie game developer getting close to releasing your first game. Or maybe you are a large company that is ready to launch your next triple-A title. Perhaps your employees have already started talking about your games on Facebook, Twitter, or on their personal blogs. And maybe you are starting to wonder if your employees' online actions can impact your game's success.

Now you are thinking about whether you should revise (or have?) a social media handbook policy. In the game industry, most employees are very tech savvy, so you want to have some sort of policy regulating their social media usage, right? If so, read on for guidance on how to draft your policy with federal labor law and the Federal Trade Commission's guidelines in mind.

Federal Labor Law


Federal labor law applies to both unionized and non-unionized workplaces. This impacts all companies regardless of company size, with limited exceptions. Federal labor law gives employees the right to engage in activities, such as discussing their wages and criticizing their company, which could lead them to improve their working conditions or form a union.

The National Labor Relations Board (NLRB), the federal agency that safeguards employees' rights to unionize, says that social media is a viable method of forming a union. Therefore, if a company's social media policy is too broad (for example, "do not disparage or damage the company online"), then the company risks violating federal labor law because its social media policy might inadvertently restrict its employees' rights to unionize.

The FTC's Endorsement Guidelines


Companies should also keep the FTC's endorsement guidelines in mind -- specifically, the requirement for the disclosure of "material connections" between companies and advertisers/endorsers. Being an employee of a company counts as a material connection (an "endorser") that has to be disclosed.

An employee may not directly receive payment or benefits for writing about the company and its products like an advertiser would; nevertheless, the employee's job security may depend on the company's success. Therefore, a violation of these guidelines would include an employee who tweets that your game is "the best game ever" without disclosing that she works for your company.

Potential Conflict?


Companies cannot have policies that completely forbid their employees from posting "endorsements" of their products and services online because this could conflict with federal labor law. For example, a policy stating, "Do not use social media to discuss anything related to the company and its products/services" is too broad and may signal to employees that they cannot engage in unionization activities.

At first, the NLRB rule and the FTC's guidelines seem like they conflict with each other. On one hand, the NLRB says that a company cannot have a policy that is too restrictive of its employees' social media usage, but then the FTC says that a company should regulate its employees' social media activities. So, what should a company's handbook policy regarding social media usage be? And how can an employee safely talk about their company's upcoming game or hardware via social media?

Luckily, there is a way to comply with both rules: have a policy stating that employees are advised to (or must) disclose their relationship to the company when promoting and endorsing its games/hardware via social media. Such a policy is narrow enough that employees will not think that the policy intends to restrict their unionization activities, yet the policy still encourages compliance with the FTC's guidelines.

How can an employee properly disclose their employment relationship? The good news is that the FTC's guidelines do not require employees to use any special language when disclosing their employment relationship as long as the disclosure is clear and conspicuous. A simple statement such as "I work for Company X and we just released [insert name of awesome new game] and it's awesome" is sufficient. And for Twitter, which limits users to just 140 characters, even a simple hashtag is sufficient (e.g., #microsoftemployee or #ad).

Just make sure that the audience is aware of the employment relationship! It is probably not enough for an employee to have a general disclosure on their "about me" page (or list the company as their place of employment on Facebook/Twitter) or assume that their social media followers know whom they work for and what games/hardware their company and its affiliates produce. To be completely safe, an employee should directly disclose their employment relationship within each separate post that endorses their company's products.

Additional Suggestions Based on Federal Labor Law


In addition to recent NLRB cases, the NLRB has also offered extensive guidance through its Acting General Counsel's reports, which explain the NLRB's current position on social media. Unlike a regular NLRB case, not everything in these reports is the law yet. However, the reports are still very useful because they offer companies cautionary guidance and are very likely to become the law in the near future. Foremost, the reports reiterate that handbook policies must not be too broad; otherwise, employees will think that their right to engage in unionization activities is also being restricted. The reports contain additional useful advice, which I have summarized below.

Give the policy some context: A policy can restrict certain social media activities if the policy provides enough context that employees know that the policy is not meant to restrict their unionization activities. Therefore, a company should try to explain the business purpose behind their policy. The examples below give their respective policies the appropriate context and are therefore lawful.

"Employees may not use social media to post or display comments about coworkers or supervisors or the employer that are vulgar, obscene, threatening, intimidating, harassing, or a violation of workplace policies against discrimination, harassment, or hostility on the account of age, race, religion, sex, ethnicity, nationality, disability, or other protected class, status, or characteristic."

"Employees may not use or disclose confidential/proprietary information that is necessary to ensure compliance with securities regulations and other laws."

"Employees must maintain the confidentiality of company trade secrets and private or confidential information. Trades secrets may include information regarding the development of systems, processes, products, and technology. Do not post internal reports, policies, procedures or other internal business-related confidential communications online."

"Promotional Content: Employees may not refer to the employer by name or publish promotional content. Promotional content is defined as content that is designed to endorse, promote, sell, advertise, or otherwise support the employer and its products and services." (Yes, this company policy was meant to comply with the FTC's endorsement guidelines, too.)

Provide definitions: Be sure to define ambiguous words that employees could mistakenly believe are restricting their unionization activities. For example, the term "inappropriate communication" could refer to sexual harassment, but it could also refer to communications about wages (which the NLRB explicitly protects) if the term is not properly defined.

There are many other words that also require definitions: misleading, untrue, inaccurate, sensitive, confidential, proprietary, non-public, private, personal, inflammatory, disrespectful, unprofessional, dishonest, unreasonable, objectionable, offensive, demeaning, abusive, damaging, embarrassment, harassment, and defamation. This is not an exhaustive list. When in doubt, define the word clearly.

Use examples: In addition to defining ambiguous words, provide examples. For instance, explain that the term "inappropriate communications" refers to activities such as "displaying sexually-oriented material" or "revealing trade secrets."

Do not require employees to be courteous and avoid conflict when using social media. Employees could interpret such "courtesy policies" as restricting their unionization activities because discussions about unionization are often heated and cause conflict. Instead, be sure to clarify what kind of conduct is not appropriate (e.g., using profanity) through proper definitions and context.

Do not restrict employees from posting about certain topics that federal labor law normally allows them to discuss, such as wages and other terms and conditions of their employment.

Do not restrict employees from using social media at work. Federal labor law allows employees to engage in unionization activities while on company premises as long as employees do it during non-work time (e.g., lunch) and in non-work areas (e.g., outdoor picnic area).

Do not restrict employees from using the company's name, address, or other information on their online profiles (e.g., Facebook) because such profiles serve as a way for employees to find one another online and possibly communicate about unionization activities.

Do not restrict employees from posting pictures of your company's logo, uniforms, etc. because this also restricts employees from posting about their union activity (e.g., posting pictures of coworkers at a union rally wearing pro-union T-shirts that depict the company's logo).

Do not restrict employees' communication with the public and press via social media because federal labor law protects these kinds of communications.

Do not require employees to explicitly state that whatever they post is their personal opinion every time that they post anything about the company (e.g., "Company XYZ doesn't provide us proper benefits. This is my personal opinion, not that of the company").

Do not require an employee to get approval before they can identify themselves as an employee online.

But you may require employees to get the company's permission before they post something on behalf of the company or post something that people could think came from the company directly.

Do not restrict employees from becoming Facebook friends with one another or communicating with one another via social media.

But you may have a policy that prevents employees from pressuring their coworkers into connecting or communicating with them via social media. Just be sure that the policy clearly applies only to harassing conduct and does not restrict employees from contacting one another for the purpose of engaging in unionization activities.

Do not require employees to discuss work-related concerns with their supervisors or managers before they air their frustrations online.

But you may suggest that employees should first try to resolve their work-related concerns using internal company procedures.

Do not rely on a disclaimer to fix an overly broad social media policy that lacks appropriate definitions and context. For example, one company had a disclaimer in their policy stating, "This policy will not be interpreted or applied so as to interfere with employee rights to self-organize, form, join, or assist labor organizations, to bargain collectively through representatives of their choosing, or to engage in other concerted activities for the purpose of collective bargaining or other mutual aid or protection." The NLRB says that this may still conflict with federal labor law because employees may not understand what this statement means and will nonetheless think that they are not allowed to engage in unionization activities. In other words, err on the side of being more specific.

That is a lot to take in, so how do you begin? The NLRB has graciously included a full sample of a social media policy in its third report ("It's dangerous to go alone! Take this!"), which is available here. Search for the Operations Memorandum 12-59 published on May 30, 2012; the sample is on pages 22-24. Use this sample as a starting point and remember to also keep in mind the FTC's guidelines that I mentioned earlier. Happy drafting!

100-Percenting It: Video Game Play Through the Eyes of Devoted Gamers

$
0
0

Introduction


100-Percenting It: Videogame Play Through the Eyes of Devoted Gamers examines video gaming from a cultural sociological standpoint. The paper is based on my undergraduate honors thesis, which I wrote during my senior year at Rutgers University in 2006-2007.

Back then, gaming research was not as prevalent as it is today (and most of the studies I encountered involved violence in games). When I decided that I wanted to study gaming, many people told me that it was immature, stupid or that there was nothing worthwhile that anyone could learn from gaming (not surprisingly, my first chapter was a strong, 26-page defense of why one should study gaming).

However, I was fortunate to find two extremely supportive advisors who were willing to indulge my interests and guide me. Neither of them were gamers, but they saw the value of studying gaming and encouraged me to produce something that would make me proud. The end result was a 260+ page thesis that received the distinction of highest honors and several awards, including the award for best thesis in the department.

The publication, which appears in the December 2012 issue of Sociological Forum, is considerably shorter and significantly more polished than my original thesis. Below, I have provided a brief overview of several of the publication's topics. The full text of the article is available on the journal's website.


Research Methods


I relied primarily on three forms of data: one-on-one interviews, participant observation (you guessed it: watching people play video games), and a questionnaire. I interviewed 20 "devoted gamers," 17 male and 3 female, ages 18 to 27. These people were a mix of core and hardcore gamers, but they were unwilling to attach such labels to their gaming. I spent over 12 hours observing my gaming participants, four 21-year-old males, play video games.

All of the quotations in this article are either from the interviews or the participant observation sessions. The 50-question questionnaire was administered to a random sample of undergraduate students at Rutgers University: 101 female and 69 male, ages 18 to 25.

Defining the "Devoted" or "Hardcore" Gamer


Attached Image: hardcore_gamer.jpg

Earlier, I used the term "devoted" to describe my interviewees' gaming habits because no interviewee wanted to identify as a "hardcore gamer," fearing that it carried a negative connotation of playing too many video games or being obsessed with them. In fact, interviewees went to great lengths to distinguish themselves from the stereotypical "hardcore gamer," though they did not attempt to downplay their own dedication to video games. Thus, the interviewees did not personally think that they were too invested in gaming but believed that others could be.

Because no interviewee was willing to accept the term "hardcore gamer," I relied on the term "devoted gamer," which I elicited and defined through my questionnaire data. The definition of "devoted gamer" is just as imprecise as "hardcore gamer," the former being a person who has a passion for games, plays them more often than the average casual gamer, and for whom games are meaningful.

Gaming as an Immersive Experience: Atmosphere


Interviewees described gaming as an immersive experience both because of the gameplay itself and through other absorbing aspects of the game. For example, many interviewees appreciated in-game music, defending it as real music, and the artistic quality of games, including the art found in game manuals.

One interviewee referred to a game's immersive quality as its "atmosphere," which he explained is "something that when you play the game and when you hear the music from the game afterwards [it] sends chills down your spine" and makes each game "feel different." He described Metal Gear Solid as a game with such atmosphere -- a "masterpiece" that "works on so many levels."

Gaming as a Social Activity


Almost every interviewee agreed that gaming is a social activity, both online or offline and whether multiplayer or single-player. Indeed, gaming facilitates gamers in forming and solidifying their friendships, leading to a rich social experience. Gamers play games alongside one another, often discussing subjects unrelated to the game itself. And gamers discuss and reminisce over games even when they are not playing them, adding a social dimension to single-player games. One interviewee described how he became better friends with an acquaintance because they both used Xiaoyu in Tekken 4. Another interviewee explained how gamers met and played games together at her college's gaming society.

Ironically, many interviewees believed that gaming made people less sociable, but every interviewee (except for one) felt that games had personally made them more sociable. Thus, the interviewees subscribed to the image of the stereotypical socially-isolated gamer -- "guy with glasses, greasy hair, Cheetos stains on his shirt . . . sitting in his mom's basement" -- but did not believe that they fit that image. If such a stereotype exists but does not apply to most gamers, then how accurate is the stereotype?

While watching gamers play multiplayer games (specifically, two-on-two Super Smash Bros. Melee timed games on the Final Destination stage), I noticed that the players simultaneously, but separately, interacted with each other and with each other's characters. When a player spoke to his teammate in-game, he referred to his teammate by his teammate's first name. However, when a player referred to his opponents in-game, he referred to them by their characters' names (e.g., "Greg, way to just look at Yoshi!" and "Aw, fucking Bowser!").

In fact, when a player picked a female player, the other team referred to the player as a "she." Thus, allies were players but enemies were characters. Interestingly, the players referred to the opposing team by their characters' names only in-game but did not do so in between matches, i.e., while on the character selection screen ("Peter, keep Greg off of me as much as you can"). I observed the same phenomenon when the players switched teams.

Gaming Status


An important social dimension of gaming is a gamer's status: how good they are at a game. Getting a high score or unlocking certain in-game features are just some of the many ways that one can flaunt one's gaming ability. Several interviewees described how, as children, they would taunt their siblings by outscoring them in certain games, like Tetris.

Being good at a game is not just about bragging rights, however: pro-gamers base their careers on competing in tournaments, maintaining fanbases, and signing endorsements. Thus, being good at a game commands some respect and awe. One interviewee respected a player who beat him in a tournament because it was the first time in a long time that he was so excited and nervous. Likewise, another interviewee described his admiration for the winners of a Street Fighter tournament that he attended, stating that "the admiration that I have for someone that is good at a game is usually because I also play the game [...] so that admiration is borne out of my own desire to improve and [...] knowing what it takes to be so good."

In contrast, one interviewee characterized a tournament winner he watched as "precise," but noted that the player's skillfulness detracted from the game's fun because he played too mechanically. In that sense, being too good at a game can sometimes be a bad thing.

Indeed, a game is more immersive and meaningful when players are competing against well-matched opponents. Obliterating your opponent (or being obliterated) can get boring; it is the back-and-forth edge-of-your-seat closeness in ability that keeps players engaged. An interviewee described this as recognizing his opponent's "play style," which allows him to adapt and learn from each encounter he has with his opponent. He explained that a truly great match is between equals who constantly keep changing the way they play, making the match uncomfortably close until the very end.

For this reason, he (and many other interviewees) expressed a strong preference for playing against human, rather than computer-controlled, opponents. Of course, a human opponent provides an opportunity for social interaction that a computer cannot, but human opponents also make the gameplay more dynamic and challenging. You never really know your true skill level until you have played against other people who have invested time in mastering the game.

Thoroughness and 100-Percenting It


Games are not just about having fun; they also give us a sense of accomplishment. Many interviewees described a sort of duty they had towards their games, which went well beyond just playing the game for its entertainment value. Interviewees best described this as a need to "100-percent" games by playing them thoroughly and to their fullest: exploring every cave, assisting every NPC, collecting every golden coin, defeating every boss and mini-boss, beating every mini-game, and so forth.

One interviewee found it "extremely satisfying" to look at the catalogue of games he had 100-percented, thereby reminding himself of what he had achieved. Another interviewee drew a distinction between his gaming habits, making sure that he had "gotten every little thing you can get," and the habits of "some people who . . . will just go on and beat it in a few hours." His comment suggested that playing a game without 100-percenting it is a less honorable method of gaming.

Similarly, several interviewees touched on a common struggle that "haunts" them -- choosing between playing every game that interests them versus wanting to play every game thoroughly. The need to 100-percent games was not limited to just a desire for completeness but also extended to an obligation or way to pay homage to the game's designers. Specifically, one interviewee felt that it was important to "take the most out of the games, everything that the creators intended [...] [like] feedback or a way of showing respect for the creators of the game." If a game's designers put in the effort to include quests beyond those required to beat a game, how can you justify not completing them?

The Etiquette of Gaming: Spoilsports, Cheaters, and Being Cheap


What irritates a gamer more: the spoilsport (i.e., the person who does not take the game seriously) or the cheater? Interviewees generally found spoilsports to be more aggravating, which is the same kind of attitude you would probably find in competitive sports. No one wants to watch a sports game in which the other team is goofing off or losing on purpose because such behavior destroys the game's importance (and its balanced, competitive aspect, which I discussed earlier).

The same goes for video games; spoilsports break the delicate illusion of reality, that the game is meaningful and that winning is important. There are very few things more irritating than beating someone in a game and then having him or her respond, "Who cares? It's just a stupid game." We care; that's why we played it!

Interviewees found spoilsports to be annoying because such behaviors made them feel as though their opponent was not taking them seriously. In contrast, the cheater was taking the game seriously, which is why they were cheating in the first place. With the cheater, winning was so important that it was worth going through the effort of cheating.

One interviewee explained that dealing with a cheater is easier than dealing with a spoilsport because at least he could still try to beat the cheater or stoop to their level and "cheat back." Another interviewee used the term "bad cheating" to describe extreme cheating that could not be overcome. Other cheating, like screen cheating in FPS games, was acceptable because the opportunity was "right there in front of you."

Cheating was not just limited to multiplayer games, however. Other than following the explicit rules that limit how players can play a game, gamers also imbue games with their own set of rules and norms. One common theme among interviewees was the notion that relying on walkthroughs and online guides is a form of quasi-cheating or is at least a bit shameful. Interestingly, one interviewee who looked down on the use of walkthroughs also qualified that he would instead ask a friend for help whenever he was stuck in a game.

Similar to cheating, many interviewees used the term "cheap" to describe gaming that was not quite cheating, because it was still within the game's parameters, but was nonetheless unfair. Two examples of being cheap were abusing unfair tactics (e.g., "snaking" in Mario Kart DS) and using overpowered characters (e.g., "burn characters," like Cable and Iron Man in Marvel vs. Capcom 2).

The Etiquette of Gaming: Trash Talking


Not surprisingly, trash talking is widespread and accepted as part of what makes multiplayer gaming fun, even if the trash talk is directed at you. Most interviewees generally saw trash talking as something to do among friends, rather than when playing with strangers. However, trash talking was thought to be easiest in online settings, where one was least likely to fear reactions from other players due to the geographical distance between them.

Trash talking is also a tool, which can be used to put a cheater or braggart in place or just to be funny. One interviewee explained that he even trash-talks when he is losing because it is "so ridiculous that you know I'm joking." Trash talk is also another way for players to express that they are engaged in the game -- taking it seriously -- so it is important for solidifying the competitive and cooperative nature of gaming.

"The computer" can also be trash-talked or talk its own trash. During my gaming observation sessions, I observed one player trash-talk the computer when it outscored all of the human players in Donkey Konga ("Seventy-six? Kiss my ass, computer!"). One interviewee described Chipp Zanuff of Guilty Gear as engaging in "a ridiculous amont of trash talk."

Trash talking can also involve sexist, racist, homophobic, and otherwise obscene language. It is important to stress that this is not unique to video gaming or gamer culture as a whole. Indeed, the analytical framework for this topic came from a 1987 study of Little League baseball players, who used homosexual epithets to taunt one another and express domination. And we observe the same type of obscene language emerge in other competitive activities, like sports (playing and watching), board games, and cards, to name a few.

Like the language that emerges during these other competitive activities, the language that I observed players (unconsciously) use during their gameplay did not necessarily reflect their personal beliefs and does not mean that such language is essential to gaming. As with violence, which I discuss below, I do not think that my findings lead to the conclusion that playing video games encourages people to use obscene language or that such behavior is unique to those who play video games.

Contextualizing Violence


Unlike much of the early research on gaming, the causal relationship between games and violent behavior was beyond the scope of my research. Instead, I was interested in two things: how gamers rationalized and talked about the violence they encountered in games, and how gamers felt about non-gamers' attitudes towards violent games.

As an initial matter, I found that whether or not a game is judged to be violent depended on the context in which the interviewee viewed the activity. One of my interviewees put it best when he described his interest in fencing and martial arts; both are non-violent activities within the context of sport but would certainly be violent if performed on innocent victims. Similarly, even non-violent game series, like Pokémon, Mario, and The Legend of Zelda, could be (albeit wrongly) viewed as violent depending on the audience's sensitivities. And some may even view a series like Grand Theft Auto to be non-violent because the animation, such as heads popping off victims' bodies, is unrealistic and almost cartoon-like.

No matter how hard each interviewee tried, no interviewee could successfully argue that games were categorically non-violent. (One interviewee even went so far as to argue that she could play a Grand Theft Auto game non-violently, but by the end she admitted, "it's human nature to like violence, I guess. I find it funny to run someone over, too.'') The argument is as useless as arguing that all movies are non-violent. Like movies, there are both violent and non-violent games, but that does not necessarily mean that games (or even violent, M-rated games) cause people to commit actual violence.

Attached Image: blackops2.jpg
Source: Call of Duty: Black Ops 2

Identifying with Characters: Good Guys, Badassness, and Morality


Every interviewee identified with at least one specific game character. This sometimes involved imbuing these otherwise one-dimensional characters with certain anthropomorphic characteristics. For example, Ky Kiske from Gulity Gear was described as "a totally good person" who was "a little naïve in his ideals." Two interviewees admired Ryu from the Street Fighter series, separately stating "you never get a bad vibe from him" and "what [he] embodies forms a lot of the philosophy that I consider very much close to my heart."

One interviewee, in particular, spoke fondly of his affection for Kirby, who he said was "so humble and courageous and funny. [...] He never is like King Dedede where he's always showing off or something. [...] Kirby's so cool."

Villains also fascinated interviewees, with many describing them as "badass" and appreciating them for their multi-dimensional qualities. For example, one interviewee spoke fondly of Pyron, a demon lord in the Darkstalkers series, stating that Pyron's goal of eliminating evil was "admirable" even though "he was obviously going about it in a bad way." Similarly, another interviewee described Big Boss in Metal Gear Solid as someone whose "intentions were good" but whose "methodology was questionable."

Being a badass bad guy was almost a redeeming quality because, as one interviewee explained, it is "it is something that separates them from just [a] cardboard bad guy" and makes him or her fun to fight. Some protagonists were also described as badass, though not nearly as often as villains.

Similar to identifying with video game characters, some interviewees explained that games had influenced their morals. One interviewee altered his religious beliefs after playing certain games, and another believed that playing games with others made her a more patient and persevering person. Link from the Legend of Zelda series was also cited as possible inspiration for "standing[ing] up for a kid that was getting picked on one day." For a classically silent character, that is a lot of personality!

Conclusion


The purpose of this study was to analyze the culture of gaming through a sociological framework, thereby exploring how gaming is meaningful to gamers. The study, of course, has its limits: a small sample size of participants drawn from limited backgrounds. Moreover, this study did not explore online and social gaming, which is much more prevalent now than it was when I conducted my research approximately six years ago. Back then, the term "gamer" was also much more limited -- and applied only to core and hardcore gamers -- than it is today thanks to the proliferation of mobile and casual games. Nonetheless, the study still offers a look at the more "devoted" gaming audience that persists.

Mechanics, Dynamics, Aesthetics

$
0
0

Introduction

Back in the early 2000s, there was a paper published by Robin Hunicke, Marc LeBlanc, and Robert Zubek, introducing the concept of  'Mechanics, Dynamics, Aesthetics'.  It was one of the earliest attempts to formalize game design.  It's fundamental to how we look at game genres, and it teaches some very helpful lessons to new game designers.

This article will help you to begin looking at games differently; not by the rules they use or the things you do while playing them, but by the underlying reasons one might find the game interesting or appealing.

For designers, deciding those reasons early when designing your game will help to focus you on the things that you find truly important for your game, which will result in an altogether more organized and powerful game experience.

For game players, knowledge about these reasons will help to tighten your grip on what you truly enjoy in your games, which can help you better decide which games to buy in the future.

Note:  This article draws from, and at times may quote or paraphrase, the information presented in this video:
Extra Credits - Aesthetics of Play (on YouTube).



Mechanics, Dynamics, Aesthetics

The Mechanics, Dynamics, Aesthetics (MDA) approach provides a new way of looking at games that categorizes their individual aspects.
As well as this, it points out some glaring flaws in the way we categorize our games by genre - but before I get to that, here's what the Mechanics, Dynamics, and Aesthetics actually mean:

Mechanics - rules and mathematics behind the game, like the physics, damage and health systems, etc.
Dynamics - the experience and actions the player takes when playing the game, like running around, doing parkour, battling monsters, controlling an army, etc.
Aesthetics - underlying reasons we go to the game; what it offers that we find interesting and fun; e.g. the fantasy of being a monster-slayer/marine/soldier, the challenge of beating the game, etc.  Games often only focus on 2-4 aesthetics, though elements of other aesthetics might be included here and there.

The mechanics come together to make the game's dynamics, which form the game's aesthetics of play.
Game designers and players approach this from the opposite ends: players most directly experience the aesthetics, and designers start with the mechanics and build their way up.

Unfortunately, this sometimes leaves designers so focused on mechanics that they're not actually thinking about the aesthetics of play they're trying to deliver, which can result in hackneyed games that don't seem to have any focus.
Or worse, they mistakenly think that specific mechanics will always deliver specific aesthetics.

Genres

Now, back to genres.  Let's look at the names of movie genres and game genres.
Movies have comedy, drama, action/adventure, and documentary (among others).
Games have first person shooter, real-time strategy, roleplaying game.

Movies label their genres by the underlying reason you go to the movie: what you're looking to experience while watching the film.
Games label their genres by silly things like first-person shooter: you view the game through a first-person camera and you...shoot things.  Or real-time strategy: it's not turn-based and there's strategy involved in some way.  Role-playing game: you play a role.
These labels are general and indescriptive, as well as shallow: they don't portray much of what's truly important about the game: the aesthetics of play, not the dynamics.

For example, let's take Portal and Fallout 3.  Both of these games have a first person camera and involve shooting, but they just don't fit the 'first-person shooter' category.  They are fundamentally different from other first-person shooter games, like Call of Duty and Team Fortress 2, because they deliver on different aesthetics of play.  You go to Portal for a much different game experience than you would go to Call of Duty for, because, though both games are first-person and involve shooting, they differ in aesthetics of play.

Fallout 3 and Portal have an emphasis on narrative, and Portal is more of a puzzle game than a shooter.  Call of Duty games emphasis competition and online play, and focus heavily on shooting and killing.

Aesthetics of Play

Before we get into the specific aesthetics, note that many games contain elements of many different aesthetics, but they usually only focus on 2-4 of them.  It's more important to get to these 'core' aesthetics that more strongly define the game.  For example, early Mario games included narrative, but the narrative isn't really a reason people would play the game, because it didn't focus strongly on narrative; it was more of a challenge game.

OK, here are the aesthetics:

  • Sense Pleasure:  Enjoyable to the senses; good graphics/sound and music/stimulation of feelings.  Video games usually don't stimulate physical feelings very much, though some Kinect or Wii games, like a dancing game or a Rock Band game, may deliver here.
  • Fantasy:  Playing as something you aren't able to be in real life; a soldier in war, a hunter, etc.  Generally, RPGs deliver this kind of experience: you become an adventurer on a journey.
  • Narrative:  Intriguing and well-designed game narrative.
  • Challenge:  Overcoming arbitrary obstacles.  Platformer-type games often use this aesthetic (this was a core aesthetic of early Mario games).  However, challenge is not difficulty; making something really hard isn't essentially making it a good challenge.  Difficulty is certainly useful when defining challenge, but don't take it too far.  Sometimes, challenge can include just trying to beat your high score by playing better.
  • Fellowship:  Cooperation and working as a team; MOBA-type games often feature a lot of fellowship (required to win, that is).
  • Competition:  The urge to express your superiority and dominance over your peers by crushing them in competition.  Usually, this is through multiplayer online games like Call of Duty, Halo, Warcraft, and so on, but minor elements of competition can be found in simple Flash-based games with online high-scores.
  • Discovery/Exploration:  Finding new things.  This isn't just related to exploring the terrain of your world: it can include many things, including unlocking hidden spells, crafting new items, and so on.  Minecraft uses discovery in a few ways, one being exploring the randomly-generated terrain, and two being crafting new items.  Games with a lot of choice in them often have a focus on discovery, because it makes you want to find out what happens based on what you choose to do; this kind of focus on discovery often gives a good boost in replayability.
  • Expression:  People like expressing themselves, whether it be through their equipment choices or their play-style.  Games that cater to this aesthetic will often provide lots of customization and try to push the capability of being unique and standing out amongst other players; lots of online RPGs cater (sometimes only minorly) to expression by introducing lots of different pieces of armor and weapons, classes, skills, etc. that players can customize their characters with.
  • Abnegation:  This is kind of like "zoning out" by playing a game.  Sometimes, you don't want to play a game that makes you think very much or try very hard; you just want to turn yourself off for a while.Grinding in games often offers a form of abnegation (whether intentional or not) because you don't really do that much while grinding, other than the same (often simple) tasks over and over again.  Sometimes, these games don't even have ultimate goals, like unlimited mode in Bejeweled.

New game designers often think that making a good game is as simple as combining all of the coolest features that they've enjoyed most from other games; MDA teaches us that this isn't always the case, because it may very well result in a hackneyed game design that just seems all over the place.

If you understand the aesthetics you're trying to deliver early on into your game design, then you can build your mechanics and dynamics to highlight those aesthetics.

The aesthetics are the thing you should truly be focusing on, not dynamics or mechanics, because the aesthetics are what the player directly experiences.

Conclusion


The MDA (Mechanics, Dynamics, Aesthetics) framework helps to teach game designers that specific dynamics and mechanics in a game do not always translate to specific aesthetics.

Focusing on the aesthetics of play you want to deliver and trying to make sure your mechanics and dynamics highlight the aesthetics will help you create sophisticated, focused game designs.

As well as this, MDA can help game consumers better decide which games they most enjoy by categorizing games by their core aesthetics of play rather than genres.

Further Reading

If you're looking to delve deeper into the subject of Mechanics, Dynamics, Aesthetics, read the full paper here.
Also, you may be interested in checking out the video that I mentioned at the start of the article, which is what provided me with most of this information (and the paper provided the video with the information).

Article Update Log


22 March 2013: Added link to video in Further Reading; added a paragraph to the Conclusion; added more information to the Introduction; added more information after the aesthetics list.
21 March 2013: Initial release

State Machines in Games

$
0
0
Source code can be found here:  Attached File  StateMachineTutorialsV5.zip   64.24K   54 downloads


Introduction


Many of the beginners on the site are pre-college students.  Often beginners will learn by reading tutorials on the Internet, copying code from books, and trying out things that they find interesting.

Sometimes the basic computer science theory topics are ignored or viewed lightly.  

This article will cover one frequently overlooked topic and hopefully underscore its importance to beginners.

This article is based on a series of entries from my developer journal.


tl;dr --  This used to be a bunch of small pieces.  It starts out with boring theory.  Keep reading because ends up with something fun.


The Computer Science Aspect


Finite state machines, also called finite state automata, FSMs, or simply state machines, are important in computer theory.

Computer theory covers several types of abstract machines, including FSMs.  The most famous is probably the Turing Machine, which can represent the logic of any computer algorithm.  

The FSM is a 'weak' abstract machine.  It can only solve a few types of problems and it is easy to make problems that it cannot solve.  Even though it is weak we still see them in our daily lives all the time.  They exist in everything from elevators to traffic lights; from vending machines to combination locks; from credit card number validation to complex artificial intelligence  systems.

There are several categories of FSMs that game programmers use all the time.  These include Acceptors, Transducers, and Sequencers.

Acceptor machines are useful in creating simple grammars.  If you can build an FSM to represent a grammar  it is called a regular language.  A single acceptor statement in a regular language is called a regular expression.  There are many books devoted to using regular expressions to handle user input. You might have noticed that many programmer tools for search and replace contain options to search and replace using regular expressions.

Transducer machines are often found in game tools.  They read some input file and generate a corresponding output file.  A tool that consolidates all your files into a single large data file is a transducer.  A tool that converts from generic data into a game's final memory format for faster loading time is a transducer.

Sequencer machines are often found in code and data.  They control a sequence of events or actions.   This is the type of FSM I'll be covering.

What does a State Machine Look Like?


A finite state machine really only has two key components.  First, it contains states, which can also be called a node or a vertex.  Second, it contains transitions, which are also called edges.  One of the states is marked as the starting state.  States may also be marked as an exit state.  When run, the FSM begins at a starting state.  There is an event or trigger or condition that causes it to transition to the next state.

There are many ways to picture it.  Here is a state machine in table format:

Attached Image: FSM_Table.PNG

This machine has four states.  (Two entries are for state 2.)

The same state machine in a graphical format:

Attached Image: FSM_NumberedStates.PNG

Pretty simple.

We don't need to stick with numbers for state names, just like we don't need to stick with i and j or x and y for variable names.

Here is the same graph with better names:

Attached Image: FSM_Named.png

Suddenly this state machine looks less like a boring theory topic and much more like a game topic.  This type of simple state machine is frequently used for simple NPC game logic.

Implementing a Simple State Machine


For a quick-and-dirty simple state machine that will never change, programmers will often just hard code something simple.  The most common way to implement that kind of state machine is with a simple switch statement.

The full code (including the state machine runner) is attached at the bottom of the article.

In this code we have the four different states from the example above.  

    public class StateMachine
    {
        public enum State
        {
            Routing,
            Sentrying,
            Attacking,
            Ending
        }
        State mState = State.Routing;
        Random rng = new Random();        

        public string GetStateName()
        {
            return mState.ToString();
        }
        public string UpdateState()
        {
            return "Running state " + GetStateName() +". Your game logic goes here.";
        }
        public void NextState()
        {
            switch (mState)
            {
                case State.Routing:
                    mState = State.Sentrying;
                    break;
                case State.Sentrying:
                    mState = State.Attacking;
                    break;
                case State.Attacking:
                    // TODO: Make this based on game logic instead of random number generator
                    if (rng.NextDouble() < 0.75)
                    {
                        Console.WriteLine("Random generator says NPC has survived.");
                        mState = State.Routing;
                    }
                    else
                    {
                        Console.WriteLine("Random generator says NPC did not survive.");
                        mState = State.Ending;
                    }
                    break;
                case State.Ending:
                    // Nothing to do.
                    break;
            }            
        }
        public bool IsDone()
        {
            return mState == State.Ending;
        }
    }

This isn't the same as a fancy graph, but it does implement the same logic.  Remember that a state machine is just a concept --- the actual implementation details can vary greatly.

A State Machine Interface


When building large programs it is a good practice to program against an interface or an abstract base class.  This is often called the  Dependency Inversion Principle.  It allows us to write generic code that can be applied to many different concrete classes.

For the next few examples I'm going to use a simple interface for the states and for the state machines.

Here is the interface:

public abstract class IStateMachine
{
    // Accessor to look at the current state.
    public abstract IState CurrentState { get; }

    // List of all possible transitions we can make from this current state.
    public abstract string[] PossibleTransitions();

    // Advance to a named state, returning true on success.
    public abstract bool Advance(string nextState);

    // Is this state a "completion" state. Are we there yet?
    public abstract bool IsComplete();
}
public abstract class IState
{
    // Utility function to help us display useful things
    public abstract string GetName();
    // Do something
    public abstract void Run();

    // This isn't really needed, but it helps in debugging and other tasks.
    // It allows hover-tips and debug info to show me the name of the state
    // rather than the default of the type of the object
    public override string ToString()
    {
        return GetName();
    }
}

To go along with that interface we need a simple state machine runner that uses it.

Here's the state machine runner I need for these examples:

static void Main(string[] args)
{
    // First we need to create the state machine.
    // Note that I'm using the abstract IStateMachine instead of a concrete class.
    IStateMachine machine = GetMachine();

    // We have a machine, now run it.
    while(!machine.IsComplete())
    {
        // Print out our current state
        Console.WriteLine("Currently in " + machine.CurrentState);
        machine.CurrentState.Run();

        // Print out our possible transitions
        Console.WriteLine("&#092;nAvailable choices are:");
        string[] transitions = machine.PossibleTransitions();
        foreach (string item in transitions)
        {
            Console.WriteLine(" " + item);
        }

        // Request a transition from the user
        Console.WriteLine("&#092;nWhat do you want to do?");
        string nextState = Console.ReadLine();
        machine.Advance(nextState);
    }

    // And we're done!
    // Run our final node as a special case since the above loop won't do it.
    Console.WriteLine("Currently in " + machine.CurrentState);
    machine.CurrentState.Run();

    // Finish off.
    Console.WriteLine("&#092;n&#092;nPress any key to continue.");
    Console.ReadKey(true);
}

That is all we need, and we've got the framework for a text-based dungeon explorer game.

A Boring State Machine


Just to prove out the above code I created a simple machine.  Because it doesn't do anything fun or exciting I called it the BoringMachine.

Note:  Remember that a state machine is a CONCEPT.  There are many ways to implement it.  You can have a machine that points to a collection of objects.  You can have a single variable that changes to represent the state.  You can use a series of conditional statements.  You can use an inheritance tree.  The implementation details are up to you.



In this machine I chose to make a single state and then caused the state to modify itself as the machine moves around it.

This state machine implements the interface I described above, but that interface requires you to state the transition name.  In this case I just ignore the name of the state and advance along a fixed route.

Remember that this is just a proof of concept of the state machine runner, it doesn't do anything fancy.  It is like the state machine above with states labeled 0, 1, 2, and 3 --- it doesn't look like much yet.

class BoringMachine : IStateMachine
{
    BoringMachineState mState = new BoringMachineState();

    public override IState CurrentState
    {
        get { return mState; }
    }
    public override string[] PossibleTransitions()
    {
        // For this simple example, forward it on to the state
        return mState.ListTransitions();
    }
    public override bool Advance(string nextState)
    {
        Console.WriteLine("I'm a boring state machine. I don't care what you entered. Advancing state.");
        return mState.Advance();
    }
    public override bool IsComplete()
    {
        // For the simple example, forward it on to the state
        return mState.IsComplete();
    }
}

class BoringMachineState : IState
{
    #region Members
    internal enum SameOldStates
    {
        Enter,
        DoStuff,
        Exiting,
        Done
    }
    SameOldStates mState = SameOldStates.Enter;
    #endregion
    #region IState overrides
    public override string GetName()
    {
        return mState.ToString();
    }
    public override void Run()
    {
         // Do nothing. This is the game logic.
    }
    #endregion
    #region Helper functions
    public bool IsComplete()
    {
        return mState == SameOldStates.Done;
    }
    public string[] ListTransitions()
    {
        List<string> result = new List<string>();
        switch (mState)
        {
        case SameOldStates.Enter:
            result.Add("DoStuff");
            break;
        case SameOldStates.DoStuff:
            result.Add("Exiting");
            break;
        case SameOldStates.Exiting:
            result.Add("Done");
            break;
        case SameOldStates.Done:
            result.Add("Done");
            break;
        }
        return result.ToArray();
    }
    public bool Advance()
    {
        switch (mState)
        {
        case SameOldStates.Enter:
            mState = SameOldStates.DoStuff;
            break;
        case SameOldStates.DoStuff:
            mState = SameOldStates.Exiting;
            break;
        case SameOldStates.Exiting:
            mState = SameOldStates.Done;
            break;
        case SameOldStates.Done:
            // Do nothing.
            break;
        }
        return true;
    }
    #endregion
}

At this point I can feed that machine into the runner and it works.

Sometimes that is the biggest accomplishment.

Let's Make a Game


Now that I have proved that the state machine runner is up to the task, I create another state machine implementation.  This is one of the nice things about writing to an interface: I can create many variations easily.

I'll call this one FunMachine.  It derives from IState and implements that simple interface.

The state machine will represent a map to explore.  Each state will represent the room.  Here's that code:

class FunMachineState : IState
    {
        string mName;
        string mDescription;
        List<FunMachineState> mNeighbors = new List<FunMachineState>();
        public List<FunMachineState> Neighbors { get { return mNeighbors; } }


        /// <summary>
        /// Initializes a new instance of the FunnerState class.
        /// </summary>
        /// <param name="mName">Name to display for this state</param>
        /// <param name="mDescription">Text to display for this state</param>
        public FunMachineState(string mName, string mDescription)
        {
            this.mName = mName;
            this.mDescription = mDescription;
        }

        #region IState Overrides
        public override string GetName()
        {
            return mName;
        }

        public override void Run()
        {
            // We don't do any fancy stuff, just print out where we are
            Console.WriteLine();
            Console.WriteLine(mDescription);
        }
        #endregion
    }

Most of the State Machine


Remember that we can implement a state machine in many ways.  In this example the machine will point to the current state, and during transitions will move to the next state.

This source listing is going to include everything EXCEPT the state machine constructor.  I'll go over that in more detail in the next section.

The machine implements the same IStateMachine interface.  It also adds three machine-specific values: A list of states, a link to the current state, and a link to the exit state (which we will eventually remove).  

Two things to note are how it gets the list of possible transitions and how it advances.  We look at the names of the current node's neighbors --- in this case the name of a room on the map.  We advance by making sure we can only travel to neighboring rooms.  That avoids the exploit of typing "move Exit" and winning the game in the first step.

class FunMachine : IStateMachine
    {
        List<FunMachineState> mStates;
        FunMachineState mCurrent;
        FunMachineState mExit;

        /// CONSTRUCTOR NOT SHOWN

        #region IStateMachine Overrides
        public override IState CurrentState
        {
            get { return mCurrent; }
        }
        public override string[] PossibleTransitions()
        {
            List<string> result = new List<string>();
            foreach (FunMachineState state in mCurrent.Neighbors)
            {
                result.Add(state.GetName());
            }
            return result.ToArray();
        }
        public override bool Advance(string nextState)
        {
            foreach (FunMachineState state in mCurrent.Neighbors)
            {
                if (nextState == state.GetName())
                {
                    mCurrent = state;
                    return true;
                }
            }
            System.Console.WriteLine("Invalid state.");
            return false;
        }
        public override bool IsComplete()
        {
            return mCurrent == mExit;
        }
        #endregion
    }

Again, this should seem straightforward if you've been following along.  We've got the state machine in just a few lines of code.

On to the Constructor


This state machine is still hard-coded.  In order to generate the maze we need to manually construct each room (aka FSM state, or vertex, or node).  We also need to construct each transition (aka edge) of the state machine.

        public FunMachine()
        {
            // Create all the fun states in our mini-world
            FunMachineState entryHall = new FunMachineState("Grand Entrance", "You are standing in a grand entrance of a castle.&#092;nThere are tables and chairs, but nothing you can interact with.");
            FunMachineState staircase = new FunMachineState("Grand Staircase", "The staircase is made from beautiful granite.");
            FunMachineState eastWing = new FunMachineState("East Wing", "This wing is devoted to bedrooms.");
            FunMachineState westWing = new FunMachineState("West Wing", "This wing is devoted to business.");
            FunMachineState bedroomA = new FunMachineState("Master Suite", "This is the master suite.  What a fancy room.");
            FunMachineState bedroomB = new FunMachineState("Prince Bob's Room", "The prince has an extensive library on his wall.&#092;nHe also has more clothes than most males know what to do with.");
            FunMachineState bedroomC = new FunMachineState("Princess Alice's Room", "The princess has filled her room with a small compur lab.&#092;nShe spends her days playing games and writing code.");
            FunMachineState workroomA = new FunMachineState("Study", "This is the study.  It has many books.");
            FunMachineState workroomB = new FunMachineState("Bathroom", "Every home needs one");
            FunMachineState workroomC = new FunMachineState("Do Not Enter", "I warned you not to enter.&#092;nYou are in a maze of twisty little passages, all alike.");
            FunMachineState passage = new FunMachineState("Twisty Passage", "You are in a maze of twisty little passages, all alike");

            mExit = new FunMachineState("Outside", "You have successfully exited the castle.");

            // Hook up doors.
            entryHall.Neighbors.Add(staircase);
            entryHall.Neighbors.Add(mExit);

            staircase.Neighbors.Add(eastWing);
            staircase.Neighbors.Add(westWing);
            staircase.Neighbors.Add(entryHall);

            eastWing.Neighbors.Add(bedroomA);
            eastWing.Neighbors.Add(bedroomB);
            eastWing.Neighbors.Add(bedroomC);
            eastWing.Neighbors.Add(staircase);

            bedroomA.Neighbors.Add(eastWing);
            bedroomB.Neighbors.Add(eastWing);
            bedroomC.Neighbors.Add(eastWing);

            westWing.Neighbors.Add(workroomA);
            westWing.Neighbors.Add(workroomB);
            westWing.Neighbors.Add(workroomC);

            workroomA.Neighbors.Add(westWing);
            workroomB.Neighbors.Add(westWing);

            // Trap of doom.
            workroomC.Neighbors.Add(passage);
            passage.Neighbors.Add(passage);

            // Add them to the collection
            mStates = new List<FunMachineState>();
            mStates.Add(entryHall);
            mStates.Add(staircase);
            mStates.Add(eastWing);
            mStates.Add(westWing);
            mStates.Add(bedroomA);
            mStates.Add(bedroomB);
            mStates.Add(bedroomC);
            mStates.Add(workroomA);
            mStates.Add(workroomB);
            mStates.Add(workroomC);
            mStates.Add(passage);
            mStates.Add(mExit);

            // Finally set my starting point
            mCurrent = entryHall;
        }

This creates a fun little graph.

In case you're having trouble visualizing it, the picture version looks like this:

Attached Image: FSM_SimpleMap.PNG

It has rooms.  It has a text adventure with a death trap room and a route to victory.

It is starting to look like a real game.

Run the Example Code


If you haven't gone through the executable yet, now would be a great time to do it.

You can explore this little text-based world.  It doesn't have a plot, it doesn't have inventory items or any action other than moving, but it demonstrates a part of the game.

Making it Data Driven


That term shows up a lot in games: Data Driven.

What does it mean?

So far if I wanted to make changes I needed to modify the source code, recompile, and test the app.  For a small castle map and a single developer this is not a hard thing.

But what happens when the app grows?

Let's imagine I hire someone to design my levels.  That person is not a programmer.  I don't want them touching my C# files, and I don't want to teach them to read and write C#.  So what should I do?

Simple:  I create a save file that contains all the information describing the level.

I can allow non-programmers to work on my game by loading data at runtime.  Data driven means level designers can modify rooms, put different things in different locations, and otherwise improve the game without touching the code.  It means another programmer can implement game objects like ropes and bottles and water without touching the game code.  It means that if we were making a graphical game, artists could create new art, modelers could create new models, and animators could modify animations, all without touching the code.

Data driven means that only programmers need to touch the code.  Everyone else uses data to modify the game.

Fancy engines will implement ways to reload data while the game is running.  Designers and artists and animators and modelers can iterate on their work much faster, potentially saving months of development time.

Making My Dungeon Data Driven


The states are only slightly modified from last time.

Last time I stored the state's name, description, and neighbors.  This time I add a unique name key and a set of flags.  The flags indicate if the node is the Enter node (there is only one) or if the node is an exit node.

Next I added the functions ReadXml and WriteXml.  These two functions save and load my five elements (unique name, flags, visible name, description, and neighbors) into an XML file.  Because it is basically free I chose to implement them using the IXmlSerializable interface.  Someday when I'm feeling ambitious I can extend future components to also use the C# serialization routines to automatically handle my data.

Since the state machine will need to create these objects from XML, I create a second constructor that takes an XmlReader and pass that on to the ReadXml function.

Finally I added some accessors and mutators (get and set functions) to help out the state machine.

    public class SavedMachineState : IState, IXmlSerializable
    {
        #region Members
        [Flags]
        public enum StateFlags
        {
            None = 0,
            Enter = 1,
            Exit = 2,
        }

        public string mKey;
        StateFlags mFlags;
        string mName;
        string mDescription;
        List<string> mNeighbors = new List<string>();
        public List<string> Neighbors { get { return mNeighbors; } }
        #endregion
        #region Constructors
        /// <summary>
        /// Manual constructor for default maze
        /// </summary>
        /// <param name="uniqueKey">unique name for the stateFlags</param>
        /// <param name="flags">flags to indicate enter nodes and exit nodes</param>
        /// <param name="name">name to show to the user</param>
        /// <param name="description">text to show for the description</param>
        /// <param name="neighbors">unique keys for neighboring rooms, seperated by commas and not spaces</param>
        public SavedMachineState(string uniqueKey, StateFlags flags, string name, string description, string neighbors)
        {
            mKey = uniqueKey;
            mFlags = flags;
            mName = name;
            mDescription = description;
            mNeighbors.AddRange(neighbors.Split(','));
        }
        /// <summary>
        /// Constructor to create an object from a save file
        /// </summary>
        /// <param name="reader">xml stream to read from</param>
        public SavedMachineState(XmlReader reader)
        {
            ReadXml(reader);
        }
        #endregion
        #region Helper Functions
        public bool IsStartState { get { return (mFlags & StateFlags.Enter) != StateFlags.None; } }
        public bool IsExitState { get { return (mFlags & StateFlags.Exit) != StateFlags.None; } }
        public string Key { get { return mKey; } }
        public bool IsMyName(string nameToTest)
        {
            //TODO: Add shortcuts to names.  For example, allow "Great Hall", "Hall", etc.
            if (nameToTest.ToLower() == mName.ToLower())
                return true;
            if (nameToTest.ToLower() == mKey.ToLower())
                return true;
            return false;
        }
        #endregion
        #region IState Overrides
        public override string GetName()
        {
            return mName;
        }

        public override void Run()
        {
            // We don't do any fancy stuff, just print out where we are
            Console.WriteLine();
            Console.WriteLine(mDescription);
        }
        #endregion
        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            reader.ReadStartElement();
            mKey = reader.ReadElementContentAsString("UniqueName","");
            string flagString = reader.ReadElementContentAsString("Flags","");
            mFlags = (StateFlags)Enum.Parse(typeof(StateFlags), flagString);
            mName = reader.ReadElementContentAsString("VisibleName", "");
            mDescription = reader.ReadElementContentAsString("Description", "");
            string neighborsString = reader.ReadElementContentAsString("Neighbors", "");
            mNeighbors.AddRange(neighborsString.Split(','));
            reader.ReadEndElement();
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            writer.WriteElementString("UniqueName", mKey);
            writer.WriteElementString("Flags", mFlags.ToString());
            writer.WriteElementString("VisibleName", mName);
            writer.WriteElementString("Description", mDescription);
            string neighbors = String.Join(",",Neighbors.ToArray());
            writer.WriteElementString("Neighbors",neighbors);
        }

        #endregion
    }
If that was the first exposure to the code it might be a little intimidating.  But since we've been slowly adding to it over time, you should see that it is only a minor incremental change.

State Machine Changes


Changes to the state machine were a little more dramatic.

The exit node information is now contained in the data, so I can drop the mExit state I mentioned earlier.  

For convenience I moved the map construction code from a constructor to its own function: GenerateDefaultMap().  It allows us to generate and save a map when bootstrapping the tool chain.  The constructor calls ImportFromXml() instead.  If that fails we generate the default map, save a copy with ExportToXML(), and then reload our newly created map.

ExportToXML() creates an XML writer, loops through the states, and writes each state out using the WriteXml() function.  ImportFromXML() creates an XML reader and reads the file in through the corresponding ReadXml() function.  

Here's the modified code:

    public class SavedMachine : IStateMachine, IXmlSerializable
    {
        #region Members
        List<SavedMachineState> mStates = new List<SavedMachineState>();
        SavedMachineState mCurrent;
        #endregion
        #region Constructor
        /// <summary>
        /// Initializes a new instance of the FunnerMachine class.
        /// </summary>
        public SavedMachine()
        {
            try
            {
                ImportFromXML();
            }
            catch (Exception ex)
            {
                mStates.Clear();
            }

            if (mStates.Count == 0)
            {
                GenerateDefaultMap();
                ImportFromXML();
            }

            // Find the entry state
            for (int i = 0; i < mStates.Count; i++)
            {
                if (mStates[i].IsStartState)
                {
                    mCurrent = mStates[i];
                    break;
                }
            }
            if (mCurrent == null)
            {
                Console.WriteLine("&#092;n&#092;nERROR! NO ENTRY STATE DEFINED.");
                throw new Exception("No entry state defined in this state machine.  Cannot continue.");
            }
        }
        #endregion
        #region Helper Functions
        private void GenerateDefaultMap()
        {
            mStates.Clear();

            // Create all the fun states in our mini-world
            mStates.Add(new SavedMachineState("entryHall", SavedMachineState.StateFlags.Enter, "Grand Entrance", "You are standing in a grand enterance of a castle.&#092;nThere are tables and chairs, but nothing you can interact with.", "staircase,outside"));
            mStates.Add(new SavedMachineState("staircase", SavedMachineState.StateFlags.None, "Grand Staircase", "The staircase is made from beautiful granite.", "eastWing,westWing,entryHall"));
            mStates.Add(new SavedMachineState("eastWing", SavedMachineState.StateFlags.None, "East Wing", "This wing is devoted to bedrooms.", "bedroomA,bedroomB,bedroomC,staircase"));
            mStates.Add(new SavedMachineState("westWing", SavedMachineState.StateFlags.None, "West Wing", "This wing is devoted to business.", "workroomA,workroomB,workroomC"));
            mStates.Add(new SavedMachineState("bedroomA", SavedMachineState.StateFlags.None, "Master Suite", "This is the master suite.  What a fancy room.", "eastWing"));
            mStates.Add(new SavedMachineState("bedroomB", SavedMachineState.StateFlags.None, "Prince Bob's Room", "The prince has an extensive library on his wall.&#092;nHe also has more clothes than most males know what to do with.", "eastWing"));
            mStates.Add(new SavedMachineState("bedroomC", SavedMachineState.StateFlags.None, "Princess Alice's Room", "The princess has filled her room with a small compur lab.&#092;nShe spends her days playing games and writing code.", "eastWing"));
            mStates.Add(new SavedMachineState("workroomA", SavedMachineState.StateFlags.None, "Study", "This is the study.  It has many books.", "westWing"));
            mStates.Add(new SavedMachineState("workroomB", SavedMachineState.StateFlags.None, "Bathroom", "Every home needs one", "westWing"));
            mStates.Add(new SavedMachineState("workroomC", SavedMachineState.StateFlags.None, "Do Not Enter", "I warned you not to enter.&#092;nYou are in a maze of twisty little passages, all alike.", "passage"));
            mStates.Add(new SavedMachineState("passage", SavedMachineState.StateFlags.None, "Twisty Passage", "You are in a maze of twisty little passages, all alike", "passage"));
            mStates.Add(new SavedMachineState("outside", SavedMachineState.StateFlags.Exit, "Outside", "You have successfully exited the castle.", ""));

            ExportToXML();
        }
        public void ExportToXML()
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.OmitXmlDeclaration = true;
            settings.NewLineHandling = NewLineHandling.Entitize;

            using (XmlWriter writer = XmlWriter.Create("GameRooms.xml",settings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("SavedMachine");
                WriteXml(writer);
                writer.WriteEndElement();
                writer.WriteEndDocument();
            }           
        }
        public void ImportFromXML()
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreWhitespace = true;
            XmlReader reader = XmlReader.Create("GameRooms.xml", settings);
            ReadXml(reader);
        }
        #endregion
        #region IStateMachine Overrides
        public override IState CurrentState
        {
            get { return mCurrent; }
        }
        public override string[] PossibleTransitions()
        {
            List<string> result = new List<string>();
            foreach (string state in mCurrent.Neighbors)
            {
                result.Add(state);
            }
            return result.ToArray();
        }
        public override bool Advance(string nextState)
        {
            foreach (SavedMachineState state in mStates)
            {
                if(state.IsMyName(nextState)
                    && mCurrent.Neighbors.Contains(state.Key))
                {
                    mCurrent = state;
                    return true;
                }
            }
            System.Console.WriteLine("Cannot do that.");
            return false;
        }
        public override bool IsComplete()
        {
            return mCurrent.IsExitState;
        }
        #endregion
        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }


        public void ReadXml(XmlReader reader)
        {
            bool isEmpty = reader.IsEmptyElement;
            reader.ReadStartElement();
            if (isEmpty) return;
            while (reader.NodeType == XmlNodeType.Element)
            {
                if (reader.Name == "Room")
                {
                    mStates.Add(new SavedMachineState(reader));
                }
                else
                    throw new XmlException("Unexpected node: " + reader.Name);
            }
            reader.ReadEndElement();
        }

        public void WriteXml(XmlWriter writer)
        {
            foreach (SavedMachineState state in mStates)
            {
                writer.WriteStartElement("Room");
                state.WriteXml(writer);
                writer.WriteEndElement();
            }
        }

        #endregion
    }

Not too bad for an incremental change.

Run the Game and Generate Bootstrap Data


Now when I run the game it attempts to load the save file.  It cannot find one so it generates a new GameRooms.xml data file.  Then it plays the same dungeon explorer code as before.

Since I am bootstrapping my tools, I need to jump straight into the generated xml:

<SavedMachine>
  <Room>
    <UniqueName>entryHall</UniqueName>
    <Flags>Enter</Flags>
    <VisibleName>Grand Entrance</VisibleName>
    <Description>You are standing in a grand enterance of a castle.
There are tables and chairs, but nothing you can interact with.</Description>
    <Neighbors>staircase,outside</Neighbors>
  </Room>
  <Room>
    <UniqueName>staircase</UniqueName>
    <Flags>None</Flags>
    <VisibleName>Grand Staircase</VisibleName>
    <Description>The staircase is made from beautiful granite.</Description>
    <Neighbors>eastWing,westWing,entryHall</Neighbors>
  </Room>
  <Room>
    <UniqueName>eastWing</UniqueName>
    <Flags>None</Flags>
    <VisibleName>East Wing</VisibleName>
    <Description>This wing is devoted to bedrooms.</Description>
    <Neighbors>bedroomA,bedroomB,bedroomC,staircase</Neighbors>
  </Room>
  <Room>
    <UniqueName>westWing</UniqueName>
    <Flags>None</Flags>
    <VisibleName>West Wing</VisibleName>
    <Description>This wing is devoted to business.</Description>
    <Neighbors>workroomA,workroomB,workroomC</Neighbors>
  </Room>
  <Room>
    <UniqueName>bedroomA</UniqueName>
    <Flags>None</Flags>
    <VisibleName>Master Suite</VisibleName>
    <Description>This is the master suite.  What a fancy room.</Description>
    <Neighbors>eastWing</Neighbors>
  </Room>
  <Room>
    <UniqueName>bedroomB</UniqueName>
    <Flags>None</Flags>
    <VisibleName>Prince Bob's Room</VisibleName>
    <Description>The prince has an extensive library on his wall.
He also has more clothes than most males know what to do with.</Description>
    <Neighbors>eastWing</Neighbors>
  </Room>
  <Room>
    <UniqueName>bedroomC</UniqueName>
    <Flags>None</Flags>
    <VisibleName>Princess Alice's Room</VisibleName>
    <Description>The princess has filled her room with a small compur lab.
She spends her days playing games and writing code.</Description>
    <Neighbors>eastWing</Neighbors>
  </Room>
  <Room>
    <UniqueName>workroomA</UniqueName>
    <Flags>None</Flags>
    <VisibleName>Study</VisibleName>
    <Description>This is the study.  It has many books.</Description>
    <Neighbors>westWing</Neighbors>
  </Room>
  <Room>
    <UniqueName>workroomB</UniqueName>
    <Flags>None</Flags>
    <VisibleName>Bathroom</VisibleName>
    <Description>Every home needs one</Description>
    <Neighbors>westWing</Neighbors>
  </Room>
  <Room>
    <UniqueName>workroomC</UniqueName>
    <Flags>None</Flags>
    <VisibleName>Do Not Enter</VisibleName>
    <Description>I warned you not to enter.
You are in a maze of twisty little passages, all alike.</Description>
    <Neighbors>passage</Neighbors>
  </Room>
  <Room>
    <UniqueName>passage</UniqueName>
    <Flags>None</Flags>
    <VisibleName>Twisty Passage</VisibleName>
    <Description>You are in a maze of twisty little passages, all alike</Description>
    <Neighbors>passage</Neighbors>
  </Room>
  <Room>
    <UniqueName>outside</UniqueName>
    <Flags>Exit</Flags>
    <VisibleName>Outside</VisibleName>
    <Description>You have successfully exited the castle.</Description>
    <Neighbors />
  </Room>
</SavedMachine>

I can look it over and verify that it is our original map, saved out in XML format.

To prove that the system actually works, we can make some minor modifications to the map:

Attached Image: FSM_BiggerMap.png

This requires a tiny modification to the entrance hall (pointing the neighbor to 'courtyard') and making three new rooms.

A few seconds in a text editor, copy/paste, a little wordsmithing, and I get this addition to the save file:

  <Room>
    <UniqueName>courtyard</UniqueName>
    <Flags>None</Flags>
    <VisibleName>Courtyard</VisibleName>
    <Description>The courtyard is decorated with many large trees and several marble benches.</Description>
    <Neighbors>entryHall,townGate</Neighbors>
  </Room>
  <Room>
    <UniqueName>townGate</UniqueName>
    <Flags>None</Flags>
    <VisibleName>Town Gate</VisibleName>
    <Description>You arrive at the gate of the town.  Ahh, to be home again.&#092;n&#092;nNOTICE: The guards will not let you return to the castle if you leave.</Description>
    <Neighbors>courtyard,village</Neighbors>
  </Room>
  <Room>
    <UniqueName>village</UniqueName>
    <Flags>Exit</Flags>
    <VisibleName>Quaint Village</VisibleName>
    <Description>You return to your village.  You won't soon forget your experiences in the castle.</Description>
    <Neighbors />
  </Room>

I fire up the game, and can quickly verify that I have altered the map just by changing data.

Someone could now write a simple tool that allows a map designer to visualize dungeons.  Or they could just let the map designer work with the raw XML files.  Either way, the map is now data driven --- it can be modified entirely by data without any work from the programmer.

Always Room for Improvement


There are many more things we could do with this simple example.  The first thing I would do is create objects that can be placed in rooms.  These are simple state machines in themselves.  For example I could have a bucket object that has several states: Empty, Water, WaterAndFish.  Events could be added (again with a simple state machine) that tracks your progress through a quest and grants points as you complete objectives.

Those are nice things to have in a game, but in this case they don't add anything beyond what was just demonstrated.  That can be left as an exercise to the reader.


A More Complex Set of Machines


Let's move on to a more complex topic.

Every game I've worked on has used an AI system of some form.  There are actors and objects, and the actors do something.  Often the actors use objects.

For this demo I created the following structure:

Attached Image: FSM_BehaviorTree.png

The game container is a playing field.  It contains a collection of GameObject instances. The playing field gets regular updates at about 30 frames per second, and each update gets passed along to the individual objects.

There are two types of game objects: Pets and Toys.  These to objects work together using activities.

Now to go over each of these in detail.

The Base GameObject Class


A game object fits in with the state machines.  They serve as both state machines AND as state nodes.  Remember from earlier that a state machine is a concept.  The implementation details don't matter when the concept is intact.  

It has an Update(), which means to run the current state, and also to advance the current state if necessary.  We’ll expand on this a little later.

The GameObject represents any object we can place on our game board.  They have an owner (in this case, the playing field).  They have a location.  They have an image.

For convenience they have a ToString() override that makes things look nicer when I view them in a property grid.

Also over development, they have evolved to have a PushToward() and a MaxSpeed() method.  These would probably be integrated into a physics system or a collision system, but for now this is their best natural fit.

    public abstract class GameObject
    {
        public PlayingField Owner { get; set; }

        /// <summary>
        /// Initializes a new instance of the GameObject class.
        /// </summary>
        public GameObject(PlayingField owner)
        {
            Owner = owner;
        }

        /// <summary>
        /// Update the object
        /// </summary>
        /// <param name="seconds">seconds since last update.</param>
        /// <remarks>seconds is the easiest scale for the individual settings</remarks>
        public abstract void Update(float seconds);

        /// <summary>
        /// Location on the playing field to draw the actor
        /// </summary>
        public PointF Location { get; set; }

        /// <summary>
        /// What to draw on the playing field
        /// </summary>
        public abstract Image Image { get; }

        /// <summary>
        /// Push the game object toward a location.  Default behavior is to not move.
        /// </summary>
        /// <param name="destination">Location to push toward</param>
        /// <param name="seconds">Seconds that have passed in this movement</param>
        public virtual void PushToward(PointF destination, float seconds) { return; }

        /// <summary>
        /// Get the maximim speed of this game object. Default behavior is not to move.
        /// </summary>
        /// <returns></returns>
        public virtual float MaxSpeed() { return 0; }

        /// <summary>
        /// Simplified name for the object to display in the property browser
        /// </summary>
        /// <returns>Shorter name</returns>
        public override string ToString()
        {
            string classname = base.ToString();

            int index = classname.LastIndexOf('.');
            string shortname = classname.Substring(index+1);
            return shortname;
        }
    }

All game objects need to implement the interface.

Pets and Motives


The basic pet class is pretty simple.

A pet is a game object (so it gets everything above), plus it also gets an activity and a collection of motives.

The motives are nothing more than a wrapper for the pet’s status.  In this case we are only tracking fun and energy.  (Note for comparison in The Sims3 there are 8 visible motives – hunger, social, bladder, hygiene, energy, and fun.)

When a pet is created we default them to the Idle activity, and initialize their Motives.

We have a default update behavior to run whatever activity we are currently doing, or if we aren’t doing anything to create a new idle activity and do that instead.

We’ll also implement what it means to push a pet.

    public class MotiveBase
    {
        public float Fun { get; set; }
        public float Energy { get; set; }
    }
    public abstract class Pet : GameObject
    {
        public MotiveBase Motives { get; set; }

        public Activities.Activity Activity { get; set; }
        /// <summary>
        /// Initializes a new instance of the Pet class.
        /// </summary>
        public Pet(PlayingField owner)
            : base(owner)
        {
            Activity = new Activities.Idle(this, null);
            Motives = new MotiveBase();
        }

        /// <summary>
        /// Allow a pet to do something custom on their update
        /// </summary>
        /// <param name="seconds"></param>
        protected virtual void OnUpdate(float seconds) { return; }

        public override void Update(float seconds)
        {
            if (Activity == null)
            {
                Activity = new Activities.Idle(this, null);
            }
            Activity.Update(seconds);
        }

        public override void PushToward(System.Drawing.PointF destination, float seconds)
        {
            base.PushToward(destination, seconds);

            // TODO: Someday accumulate force and make a physics system.  Just bump it the correct direction.
            // TODO: Create a vector class someday
            float xDiff = destination.X - Location.X;
            float yDiff = destination.Y - Location.Y;
            float magnitude = (float)Math.Sqrt(xDiff * xDiff) + (float)Math.Sqrt(yDiff * yDiff);
            if (magnitude > (MaxSpeed() * seconds))
            {
                float scale = (MaxSpeed() * seconds) / magnitude;
                xDiff *= scale;
                yDiff *= scale;
            }
            Location = new PointF(xDiff + Location.X, yDiff + Location.Y);
        }
    }

There are a few TODO: markers in the code, but the interface work.

Remember the Dependency Inversion Principle mentioned before: Program against an interface or abstract base class, don't program against the individual concrete classes.  

Puppies!


Finally we get to create a concrete class.  A puppy.

Note that we're just pulling the values from saved resources so a designer and artist can modify them later.

    class Puppy : Pet
    {
        /// <summary>
        /// Initializes a new instance of the GameObject class.
        /// </summary>
        public Puppy(PlayingField owner)
            : base(owner)
        {
            
        }

        public override System.Drawing.Image Image
        {
            get { return FSM_Puppies.Properties.Resources.Puppy; }
        }

        public override float MaxSpeed()
        {
            return FSM_Puppies.Properties.Settings.Default.Pet_Puppy_MaxSpeed;   
        }
    }

Yup, all that work and we only get a tiny little concrete class.

That is actually a very good thing.  It means that when we want to extend it later for different kinds of puppies, kitties, horses, and other pets, we only need to add a tiny bit of code to hook up the new actors with their new data.

Toys


A toy is also a game object, so it can behave as a state machine and as a state node, as appropriate.

A toy has a default activity associated with it.  When a pet attempts to use a toy they will get this default activity (aka behavior tree) and start running it.

A toy is also responsible for computing the interest level in the object.  For now these will just be hard-coded formulas inside each toy object.  Later on these could be a more complex series of interactions but for this system it is adequate.

Here’s the Toy abstract class:
    public abstract class Toy : GameObject
    {
        /// <summary>
        /// Initializes a new instance of the Toy class.
        /// </summary>
        public Toy(PlayingField owner)
            : base(owner)
        {
            
        }

        public abstract Activities.Activity DefaultActivity(Pets.Pet actor, GameObject target);
        public abstract float Interest(Pets.Pet pet);

        public override void Update(float seconds)
        {
            // Note that most toys do nothing of themselves.  They are driven by their activities.
            return;
        }

    }

Two Toys


Now we’ll create two concrete classes for toys.

First, a sleeping mat.  The interest of the sleeping mat is only based on energy.  It has an image to draw.  The default activity is to sleep on the mat.

    class SleepingMat : Toy
    {
        /// <summary>
        /// Initializes a new instance of the SleepingMat class.
        /// </summary>
        public SleepingMat(PlayingField owner)
            : base(owner)
        {
            
        }
        public override FSM_Puppies.Game.Activities.Activity DefaultActivity(Pets.Pet actor, GameObject target)
        {
            return new Activities.SleepOnMat(actor, this);
        }

        public override System.Drawing.Image Image
        {
            get { return FSM_Puppies.Properties.Resources.SleepingMat; }
        }

        public override float Interest(FSM_Puppies.Game.Pets.Pet pet)
        {
            return MaxEnergy() - pet.Motives.Energy;
        }
    }
Second, a ball to kick around.  The interest is only based on fun, although it probably should include an energy component.  It has an image to draw, and the default activity is to chase the ball.
    class Ball : Toy
    {
        /// <summary>
        /// Initializes a new instance of the Ball class.
        /// </summary>
        public Ball(PlayingField owner)
            : base(owner)
        {
        }

        public override Image Image
        {
            get { return FSM_Puppies.Properties.Resources.Ball; }
        }

        public override Activities.Activity DefaultActivity(Pets.Pet actor, GameObject target)
        {
            return new Activities.ChaseBall(actor, target);
        }

        public override float Interest(FSM_Puppies.Game.Pets.Pet pet)
        {
            return MaxFun() - pet.Motives.Fun;
        }
    }

Now we move on to the activities that drive the system.

Activities Are Both Glue and Oil


Activities serve as glue to the system.  They are the interactions between actors and objects.  Without them there wouldn’t be much of a connection between the two.

Activities also serve as the oil that keeps the parts moving smoothly.  They are constantly moving.  They change themselves, and they change the actors they work with, and they can change the objects they work with.  A more complex example of a food bowl could change the actor by modifying hunger, and also change the target by reducing the amount of food in the bowl.

So here is our activity base class.

An activity has an Actor and a Target.  I intentionally limited Actors to be pets.  I could have allowed any object to interact with any object, but that doesn’t quite make sense in practice.  We don’t really want a food bowl to interact with a chew toy, or a ball to interact with a sleeping mat.  We DO want to allow a pet to be a target allowing default activities to play social events.  For example, pets could dance together or sniff each other or do whatever groups of pets do together.

We allow an Update event on the activity base.  This update is run by the pet earlier.  We pass that on through the OnUpdate callback in each activity.  If the activity returns true then we know it is complete and the pet needs to find something new to do.

Finally we have a magical function, FindBestActivity() that needs to live somewhere in the code.  I could have created another class for it, but for now this is the best spot.

This FindBestActivity is the magic that makes the AI do fun things.  In this example it is only 35 lines.  We loop over all the toys in the game world and see how interesting they are.  Then we take the best interaction and return a new instance of it.  If we fail we just return the idle activity.

For a game like The Sims there are potentially tens of thousands of objects to choose from, and each object can have many activities associated with it.  Finding the best activity among them all is a complex job.  The theory behind it is no different:  Find the best activity, and create an instance of it.

        public abstract class Activity
    {
        public Pets.Pet Actor { get; set; }
        public GameObject Target { get; set; }

        /// <summary>
        /// Initializes a new instance of the Activity class.
        /// </summary>
        public Activity(Pets.Pet actor, GameObject target)
        {
            Actor = actor;
            Target = target;
        }

        /// <summary>
        /// Update this activity state
        /// </summary>
        /// <param name="seconds">elapsed time</param>
        /// <returns>true if the activity is complete</returns>
        public abstract bool OnUpdate( float seconds );
        
        /// <summary>
        /// Update this activity state
        /// </summary>
        /// <param name="seconds">elapsed time</param>
        public void Update(float seconds)
        {
            if(OnUpdate(seconds))
            {
                Actor.Activity = new Idle(Actor, null);
            }
        }

        /// <summary>
        /// Utility function to locate the best next activity for the actor.
        /// </summary>
        /// <returns></returns>
        public static Activity FindBestActivity(Pets.Pet actor)
        {
            // Look for a toy to play with...
            if (actor.Owner != null
                && actor.Owner.GameObjects != null)
            {
                List<Toys.Toy> candidates = new List<Toys.Toy>();
                foreach (GameObject obj in actor.Owner.GameObjects)
                {
                    Toys.Toy t = obj as Toys.Toy;
                    if (t != null)
                    {
                        candidates.Add(t);
                    }
                }
                if (candidates.Count > 0)
                {
                    float bestScore = float.MinValue;
                    Toys.Toy bestToy = null;

                    foreach (Toys.Toy t in candidates)
                    {
                        float myscore = t.Interest(actor);
                        if(myscore>bestScore)
                        {
                            bestScore = myscore;
                            bestToy = t;
                        }
                    }
                    return bestToy.DefaultActivity(actor, bestToy);
                }
            }

            return new Idle(actor, null);
        }

        public override string ToString()
        {
            string classname = base.ToString();

            int index = classname.LastIndexOf('.');
            string shortname = classname.Substring(index + 1);
            return shortname;
        }
    }

Now we know what an activity is.  Basically just another state machine.

Idle Activity


We’ll start with the idle activity.

It has an idle time.  After enough time has passed we look for something new to do.  This new activity will replace our current idle activity.
If we don’t find anything interesting to do we can just sit there, slowly dropping our fun and our energy.

Since this is C# we don’t need to schedule cleanup and deletion of our own idle activity which simplifies our code quite a lot.

    class Idle : Activity
    {
        float mTimeInIdle = 0;

        public Idle(Pets.Pet actor, GameObject target)
            : base(actor, target)
        {
        }
        
        public override bool OnUpdate(float seconds)
        {
            mTimeInIdle += seconds;
            if (mTimeInIdle >= FSM_Puppies.Properties.Settings.Default.Activity_Idle_WaitingTime)
            {
                Actor.Activity = FindBestActivity(Actor);
            }

            // Sitting there idle isn't much fun and slowly decays energy.  This encourages us to pick up other activiites.
            Actor.Motives.Fun += FSM_Puppies.Properties.Settings.Default.Activity_Idle_Fun * seconds;
            Actor.Motives.Energy += FSM_Puppies.Properties.Settings.Default.Activity_Idle_Energy * seconds;

            // Always return false because idle is never finished.  It auto-replaces if it can find something.
            return false;
        }
    }

ChaseBall Activity


This is actually TWO activities.  It is a miniature state machine within itself.  Chasing a ball has one component "RunToObject", and then a second component where they actually kick the ball.  It isn't a difficult state machine, just two states, and can be represented directly with a simple if statement.  That is a good time for this reminder:

Note:  REMINDER: A state machine is a CONCEPT.  It can be implemented many different ways.  Even a simple if statement can implement the concept of a state machine.



So every update we attempt to run to the ball object.  If we succeeded to running to the object, we kick the ball a random distance.  We also bump fun a little bit whenever they kick the ball.

An activity’s return result indicates when it is complete.  We’ll return true only when our fun is maxed out.  We might want to have a second exit condition when energy runs low, but that is for later.

    class ChaseBall : Activity
    {
        RunToObject mRto;

        /// <summary>
        /// Initializes a new instance of the ChaseBall class.
        /// </summary>
        public ChaseBall(Pets.Pet actor, GameObject target)
            : base(actor, target)
        {
            mRto = new RunToObject(actor, target);
        }

        public override bool OnUpdate(float seconds)
        {
            // When they kick the ball, move it to a new location and continue our activity.
            if( mRto.OnUpdate(seconds))
            {
                float kickDistance = FSM_Puppies.Properties.Settings.Default.Activity_ChaseBall_KickDistance;
                // Get a random number with +/- kick distance
                float newX = Target.Location.X + (((float)Target.Owner.Rng.NextDouble()*(2*kickDistance))-kickDistance);
                float newY = Target.Location.Y + (((float)Target.Owner.Rng.NextDouble()*(2*kickDistance))-kickDistance);
                PointF randomLocation = new PointF(newX,newY);
                Target.Location = randomLocation;
                Actor.Motives.Fun += FSM_Puppies.Properties.Settings.Default.Toy_Ball_Fun;
                if(Actor.Motives.Fun > 100)
                    return true;
            }
            return false;
        }
    }

RunToObject Activity


Next we’ll look at how they run to an object.

It is pretty simple.  If we are close enough (another designer-adjustable value) then they have made it to the object and we return true.  If they are not there yet we push them toward the object, drop their energy, and return false (we aren’t done with the activity yet).

    class RunToObject : Activity
    {
        /// <summary>
        /// Initializes a new instance of the RunToObject class.
        /// </summary>
        public RunToObject(Pets.Pet actor, GameObject target)
            : base(actor, target)
        {
            
        }
        public override bool OnUpdate(float seconds)
        {
            // Are we there yet?
            // And why didn't PointF implement operator-() ?
            PointF offset = new PointF( Target.Location.X - Actor.Location.X, Target.Location.Y - Actor.Location.Y);
            float distanceSquared = offset.X * offset.X + offset.Y * offset.Y;
            float closeEnough = FSM_Puppies.Properties.Settings.Default.Activity_RunToObject_CloseEnough;
            float closeEnoughSquared = closeEnough * closeEnough;
            if (distanceSquared < closeEnoughSquared)
                return true;

            Actor.PushToward(Target.Location, seconds);
            Actor.Motives.Energy += FSM_Puppies.Properties.Settings.Default.Activity_RunToObject_Energy * seconds;
            return false;
        }
    }

Sleeping On the Mat


Just like chasing a ball, we start out by running to the object.  So first we call RunToObject.

If it succeeds (meaning we finally got there), then we start resting. We bump the motives, return true or false based on our energy status.

    class SleepOnMat : Activity
    {
        RunToObject mRto;

        /// <summary>
        /// Initializes a new instance of the SleepOnMat class.
        /// </summary>
        public SleepOnMat(Pets.Pet actor, GameObject target)
            : base(actor, target)
        {
            mRto = new RunToObject(actor, target);
        }
        public override bool OnUpdate(float seconds)
        {
            // Route to the sleeping mat
            if(mRto.OnUpdate(seconds))
            {
                // Now that we are on the mat, just sit here and increase our motives.
                Actor.Motives.Energy += FSM_Puppies.Properties.Settings.Default.Toy_SleepingMat_Energy;
                Actor.Motives.Fun += FSM_Puppies.Properties.Settings.Default.Toy_SleepingMat_Fun;

                if (Actor.Motives.Energy > 100)
                    return true;
            }
            return false;
        }
    }

Proof of Concept is Complete


And... we're done.

Go ahead and play with the sample now.

Drop multiple play mats, multiple balls, and multiple puppies.  Watch them run around chasing balls, and when they get tired watch them run over and sleep on the mat.  Pick them from the list on the left-hand pane to view details in the little property grid.  

It is not much, but it is enough to see a sandbox game starting to grow.  I showed my children and they immediately made a list of new objects to add.  Add a kitty!  Add a teeter-totter!  Add a tetherball! (Really?)

Repeat this around thirty times with new objects, add a few motives, and you can have your own self-running simulated pet world.

Focus on a few of them to create minigames, and drop some spawn points in the world.  Repeat until the game is complete.

But I Wanted a First Person Shooter


That is solved very easily:

Rename "Pets" to "Monsters", and "Puppy" to "Grunt".

Rename "Toys" to "WayPoint", "Ball" to "Flamethrower", and "SleepingMat" to "SpawnPoint".

Finally, rename activities as appropriate.

Wrapping It Up


So we learned that state machines are the least powerful of the automata in computer science.  We also learned that they are used everywhere in our daily lives, and can do incredible things for games.

We can use state machines to run different code based on state.

We can use state machines to represent arbitrary meshes.  These meshes can include things like maps and connectivity grids.

We don't need to hard code the state machines.  When you load them from data you can get substantially more use out of them.  Designers and artists and modelers and animators and producers can all modify the game without touching the code.

We can build complex systems such as AI behavior trees out of a nested tree of very simple state machines.

How Else Can I Apply This


Most games apply these concepts all over the place.

One of the most common jobs in the industry is Gameplay Engineer, or GPE. All they do is create the exact types of items we have made in this series of tutorials.

For example, in Littlest PetShop I spent months adding new behaviors and actions. They ranged from 'in the world' behaviors like those above to minigames such as hide and seek where pets would run behind bushes to hide, then run up to the camera and celebrate with the player when they were found.

In The Sims every one of the tens of thousands of objects in the game required scripting. You need a pile of clothes, then you need some of these scripts: Behaviors and interactions to create the piles of clothes; interactions to drop the piles of clothes and pick them up again; interactions for a washing machine; interactions for a dryer; interactions for the maid to come clean up; and on and on and on.

Or if you are into faced paced games, you need behaviors and actions for your main characters to know to attack or run away, or decide if they should attack towers or players or minions. You need to create objects to pick up, weapons, inventories, and more. All of these behave the same way that we demonstrated above.  It uses a common interface for objects, and the programmer fills out the details.


These little activities and behaviors grow into complex ecosystems powering most games.



So there you go.  A text-based dungeon crawler prototype and a sandbox world prototype, both filled with state machines and written in just a few hours.

Creating objects and behaviors like this describes the daily life of a gameplay engineer.  Chances are good that if you get a programming career in the industry you will spend a few years of your life writing code much like that above.  Remembering that it is a simple state machine can help avoid many nasty bugs and can simplify your life greatly.

Thanks for reading.

Source code can be found here:  Attached File  StateMachineTutorialsV5.zip   64.24K   54 downloads

Getting Started : Introduction to Game Development for Beginners

$
0
0

Introduction


This article aims to teach you the basics about how games are made, and what they're made of.  The individual fields of game development will be introduced and explained briefly in a simple way, without getting too technical or confusing.  For those who want to jump in and start learning, resources (tutorials, software, stuff like that) will be linked as well.

Note:  Please keep this article "Under Review" while it is being completed with help from the community!  This article still needs a lot of work and is meant to serve as a starting point for beginners. Specifically, the Music and Sound section and the Resources section are in need of some love.  Expect to see many changes in the coming days. If you're not part of the GameDev 'Crossbones+' group, but can offer materials you'd like to see added to the Resources section, please PM me about it.



The Fields of Game Development


It takes a set of rather unique skills to create a full game; they're made of a lot of parts.  This is why game studios often have teams dedicated to making games, with employees from all the necessary fields.  It's hard to make even a simple game all by yourself, though it's getting easier with the advance of technology.

Let me introduce you to these fields individually.  Once you're introduced, there will be resources to see you on your way to learning whichever field you choose.

Programming

Programming makes the gameplay itself, and all of the 'gameplay logic'. Jumping, moving, picking up new weapons, and saving/loading your game wouldn't be possible without a programmer.
Essentially, programmers tell the computer what they want it to do. Computers don't speak regular, human languages, though. They aren't that smart. You have to use a programming language to communicate with them, and instead of just using sentences, you use code.

This is essentially what programming is, but in order to really decide if you like it or not, you should just look at some beginner tutorials and get the basic hang of actually writing code and how the code works, because that kind of stuff is hard to explain in a few sentences.

Art

Games must have some form of art (conventionally). The kind of art you need depends on whether you're making a 2D game or a 3D game.

2D games use 2D images, made in Photoshop, Microsoft Paint, GraphicsGale, GIMP, and other such programs. The programmer deals with drawing the images to the screen and moving them based on the game mechanics. These images are usually animated, such as to make a character jump, or swing a weapon.  This is done by drawing multiple instances of the image, all in different poses as the image does whatever you're animating it to do.

3D games use a mixture of 2D images and 3D 'models'. Models are made of vertices, which are just "places" or "points". Those vertices (also knows as vertexes, or verts) are connected to each other to form triangles (tris), made of 3 vertices, and/or polygons (polys), made of 4 vertices. Some programs allow you to make polygons out of more than 4 vertices. Models are made with programs like Blender, 3DS Max, and Maya.

3D games also have to animate some of their models, like the player and the enemies, otherwise your game would be made of a bunch of still objects sliding around on the floor instead of walking or running (and that would probably be lame).  Animations are commonly done by binding a set of vertices to a "bone", and moving all of those vertices at the same time just by moving that bone.
So you'd have a bone for the upper left arm, a bone for the lower left arm, a bone for the upper body, a few bones for each leg, and so on.  You can move those bones into 'poses', like placing a foot forward.  You make a lot of these poses and the software you're using to model and animate will move from one pose to the next when you play the animation.  So you could have one pose with the character standing, the next with the right leg lifted, then the right leg set down, then the left leg lifted, set down, and so on.

3D games also have to put textures on their models. Textures are made like 2D images, and then they're "put on" the model. Modeling programs often provide you with the ability to "UV map" your model. This is how you decide where your textures are placed. It's hard to explain in text, but essentially, you tell your program how the texture should be laid out across all of the tris and/or polys that make up your model.
Textures can be the actual colors that draw the character, like their black-and-white suit and tie, their actual face, like their eyes and eyeballs and their lips, and so on.  Those kinds of textures are sometimes called 'skins'.
Other times, your textures are like tree bark that you wrap around your tree models, or rocky textures that you put on all your stones and mountains.

Music and Sound

Note:  Unfinished.  I don't know enough about music and sound to make this section!  Other members will have to fill in for me.



Writing

Game writers deal with the characters, dialog, the lore of the world, and so on.
But you can't just drag a novel writer in and tell them to write up your game.  Games are much different than novels or movies.  You have a lot of other means of communicating your narrative to players.  The art style, the mechanics themselves, the music and sound, they all have an effect on the mood and environment of the story.  Game writers, or "game narrative designers" as some people call them (I think it's more fitting, too), aren't just going to be writing text.  There's a lot more to game narrative than text!

Note:  Unfinished.  I've heard that game companies often don't actually seek out writers, and you kind of have to work your way up if you ever want to be a game writer (like it is with game designers).  However, I'm not in the industry, so I need someone to clarify here.



Resources


Programming

The most important thing is to pick something and stick to it until you're good enough to comfortably switch to other things that expand your abilities.  It's more important that you know general programming fundamentals rather than lots of languages.  Get really good at one language, not mediocre at three different ones!

If you're going to write your code, you'll want a program dedicated to writing code, preferably one that supports debugging (telling you where you've made errors to help you fix them) in the language you're using.  A program like this is usually called an 'IDE', which stands for Integrated Development Environment.

It's suggested that, before you go and get into developing games, you learn the fundamentals of programming.  This will help to establish a firm ground for the rest of your learning because it will be the kind of stuff that applies to programming in general, not a specific language.

Once you're ready, a lot of people will suggest you start with 2D games, because they're often much simpler than 3D games.  They cut out some of the things you'd have to worry about that may overwhelm you.  3D games also involve more math than 2D games.
It's suggested that you start by programming small games, like clones of Tetris, Pac-Man, Pong, Breakout, etc.
This will make sure you aren't delving too deep before you're ready, and will help to keep you motivated with quick results.

Generic Programming and Fundamentals:
Before trying

Note:  Unfinished.  My original route to learning how to program was hackneyed and disorganized, so unfortunately, I'm not the one who would have any resources like this lying around.



C# as a language, XNA as an 'engine':
You can hop into making 2D games with C# as your programming language, using Microsoft Visual Studio C# Express, a free IDE for writing C# code.
Here is the Microsoft official tutorial on making a simple game with C# and XNA.
The tutorial tells you to get Visual Studio to write your code and to make sure you have XNA installed.
Get Visual Studio C# 2010 Express (click on "Visual C# 2010 Express")
Get Microsoft XNA 4.0: specifically here, though you might want to poke around here as well.

Art


(3D) Blender
Blender is a great, totally free and open-source program that can be used to model, animate, rig, and UV map (among other things).

Here is the official website, where you can find a link to download Blender.

The user 'cgboorman' on YouTube has a very helpful beginner's tutorial series for Blender.  If you're just getting started with Blender and/or 3D modeling, I highly recommend his videos.  Here is a link to the entire playlist on YouTube, with all the tutorial videos in it.

Blender Cookie is a website with lots of tutorials for using Blender.

The official Blender website tutorial page has a large collection of tutorials in various categories, from modeling to animation to lighting.  It also has beginner tutorials to teach you the interface, if you don't want to use the videos I linked above.

Music and Sound

Note:  Unfinished.



Writing

Note:  Unfinished.



Article Update Log


27 March 2013: Cleaned up the Resources/Programming introduction
26 March 2013: Added a link to Resources/Art/Blender
22 March 2013: Initial release

A Cross Platform Test Driven Development Environment (Part 1)

$
0
0

Introduction

Making a small cross platform project is pretty easy, you write some code and create makefiles or IDE projects for each platform and away you go.  Unfortunately as soon as the project goes from a couple files to even a dozen, maintaining different build solutions for each platform becomes difficult if you want to maintain an agile working environment.  The simple act of renaming or moving a file in such an environment can be difficult and as such, something people will tend to avoid.  For this reason, there are a number of cross platform "makefile" replacement systems such as BJam/Jam, Scons and others.

Unfortunately makefile replacement systems don't make a lot of people happy because they can't use a favored IDE or whatever they are used to.  Catering to peoples comfort zones is something I believe is important in any development environment.  I've worked with people who swear by Vi and makefiles, fine by me, just please don't make me use Vi.  As such there are other tools which are makefile replacements but don't actually perform the build process, instead they output makefiles, projects and/or solutions appropriate to the given platform and targeted IDE's.  Among these tools is CMake, the solution I will be covering here.

A basic understanding of CMake will be presented over a series of articles.  This article will cover the very basics of getting up and running and setting up a hierarchical project.  Later articles will cover per-compiler and environment options and eventually incorporate the Test Driven Development portions of the title.  Additions after that point will show methods of working within the environment effectively with some very nice tricks not generally available without using something like CMake as a fundamental portion of your build environment.

CMake

CMake is a description and generator system, it takes a description of a project and generates whatever output you desire.  So, if you desire to work with a text editor and makefiles, an IDE or some other variation, CMake allows you to work that way without forcing others to follow suit.  It imposes only one thing, all definition is done in the CMake description files and as such you can't rename/add/move/etc a file in the IDE, or in the makefile, you need to use the CMake definition files for that.  Once you get used to this though, it's not a horrible item to deal with, especially given the alternatives of maintaining multiple build solutions.

Preparations

For this article it is expected you have at least one of the initial target platforms setup for development work and of course that you have CMake installed.  It is best to see things working in two different environments as such I would suggest setting up a virtual machine of Linux or Windows depending on your primary Os.  VirtualBox is a free and reasonably usable VM which can be used for this purpose, of course OsX expects real Apple hardware so it has to be a primary Os if you happen to have a Mac.  Setting such things up is beyond the scope of this article though, there are plenty of tutorials you can Google for if you need help in this area.

The basic expectations per platform are:

  • Windows: Visual Studio 2012 and CMake installed.
  • OsX: Xcode and CMake installed.
  • Linux: Basic development tools and CMake installed.

Again, install as appropriate to the system.  Your CMake should be version 2.8 or higher if possible.


Hello World! CMake Style

Starting with the old standby "Hello World!" project, it is time to get an idea of how CMake fits into the workflow.  Create a new directory called 'HelloWorld' and add two files with the following names and content:

main.c
/* Hello World program */
#include <stdio.h>

main()
{
    printf( "Hello World" );
}

CMakeLists.txt
CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 )
PROJECT( HelloWorld )
ADD_EXECUTABLE( HelloWorld main.c )

Attached File  helloworld.zip   638bytes   6 downloads


For the first usage of CMake, I'll cover the basics of the command line but in the future I'll be using the CMake GUI since it is considerably easier to use as options and configuration items are added to the project.  Additionally, you probably want to download the zip file and keep it around as we will be examining some of the workings of CMake and needing a clean version of this project for each of the variations.

Open a terminal or command prompt and change your directory to be in the new 'helloworld' directory.  Type the command 'cmake' and take a look at the information it outputs.  It's a pretty big wall of text but the only portion you need to look at right now is at the end; the list of 'generators' available on your platform.  I will be assuming you will use the following generators on the given platforms:

  • Windows : "Visual Studio 11" (AKA Visual Studio 2012)
  • OsX : "Xcode"
  • Linux : "Unix Makefiles"

So, in the terminal, type the following command, replacing '<generator>' with one of the above strings.
cmake -G "<generator>"

For Windows, you would have typed in 'cmake -G "Visual Studio 11"'.

During the first run CMake can take a while to complete.  It is evaluating your system looking for the compiler and making sure it functions.  It is also doing some items similar to what autoconf does in determining what header files are available, location of libraries and other items you can use in making your code compile cross platform. Don't worry though, after the initial run, CMake will only evaluate your project description since it will have saved out the detection data, as such it is very fast after the initial scan. Once CMake completes, list the content of your directory in order to see what has been done.

CMake has written out some data it will use in the future and the appropriate output file for your platform.  I.e. on Windows a sln/proj pair of files.  At this point load the solution into Visual Studio or Xcode as appropriate, build and run the result.  For Linux, simply type make and then ./HelloWorld.

Assuming everything worked correctly, head back to the terminal and list the content of the directory again.  I don't know about you but I really don't like how everything has been placed in a single directory and made a mess in and around the two files.  It's actually worse under Linux since the '.o' intermediate files are placed in this same directory so you have a 'main.c' and a 'main.o'. In order to fix this, we use what CMake calls "out of source builds".

Remove all the CMake and build generated files such that you are back to having only the 'main.c' and 'CMakeLists.txt' files in your directory. (Or, just delete the directory and unpack the supplied zip again.) Go back to the terminal within the 'helloworld' directory and make a directory called "build" then change directory into the build directory.  This new directory is where we want CMake to do all it's work from now on such that it won't dirty up the directory with our source files.  Calling CMake is basically the same with a single additional parameter:
cmake -G "'generator name'" ../

Again, on Windows, this would be: 'cmake -G "Visual Studio 11" ../'.

Now, if you look at what CMake has done, it put all of it's cache files and the generator output in this new directory.  This is perfect and keeps the separation between code and intermediate data.  Load up Visual Studio or Xcode and build again, or type make for Linux, and you will see that the intermediate files are also stored under the new directory and kept out of the source directory.  So, this cleans up the primary directory but still leaves another problem when you start working cross platform.  Try using CMake with a different generator under your existing build directory:
cmake -G "CodeBlocks - Unix Makefiles" ../

CMake should complain that you can't change from one output generator to another.  This can be annoying in a cross platform environment where you may want to test multiple compilers and IDE's, even on the single platform.  This is very simple to correct, 'cd' out of the build directory and 'mkdir codeblocks', 'cd' into the new directory and type the above command again.  CMake will generate the new output and leave the old one alone.  In this way you can keep both IDE's open, recompile without intermediate files overwriting each other and work problem free switching back and forth as you want.

CMake: The Beast

CMake is a very large project and has been around for a number of years.  It started out with a fairly humble beginning and has grown from there.  Unfortunately, due to the organic nature of the growth it has what most people consider a pretty harsh "language" which grew from the simple beginnings.  The language is a mutant blend of bash scripting and a Basic like syntax with weakness's inherited from both.  For this reason a lot of people, myself included, greatly prefer Premake with the nice Lua based language.  Unfortunately Premake is often very slow to keep up with the IDE's and compiler upgrades and in general has a number of bugs which can end up producing invalid outputs on various platforms.  Unfortunately, having run into the bugs and slow updates in the past, I bit the bullet and switched to CMake since I want to make games and not worry about the generator itself getting in the way.  This is not to say CMake is bug free, just that the bugs are fewer and usually far between due to the much larger community of support and active usage.

Making use of CMake effectively is the goal for the remainder of this article.  Learning CMake features and some things to avoid, are as important basic information as to how to use the commands and the language.  Let's start by breaking down the simple 'CMakeLists.txt' for "Hello World!":

CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 )
PROJECT( HelloWorld )
ADD_EXECUTABLE( helloworld main.c )

First off, CMake is a caseless language and the commands such as "PROJECT" could be written as: "project", "Project" or even l33t style "proJeCt" and CMake won't care.  As a convention, I stick to using all upper case for the commands simply to differentiate them from other text, file names and such.  It doesn't matter in anyway, that's just how I first saw CMake used and I followed it.

The first line in the CMake file is a quick check to tell CMake the minimum version it should allow to build your project.  You should go as far back as possible but due to changes in behavior which have been made, 2.6.4 was the first version with a couple items I tend to use and as such that is as far back as I allow.  It was also a very stable release in the 2.6 series where 2.6.0-5 had a couple bugs in the new behaviors.

The second line of the code, 'PROJECT( HelloWorld )', tells CMake the name of the primary project/solution which is being built.  For Visual Studio this is the name of the solution file, for Xcode this is the name of the xcodeproj and in a makefile it is a general all encompassing (and default) build target.

The third line, 'ADD_EXECUTABLE( helloworld main.c )', defines an actual build item, in this case an executable.  The name of the executable is the first item passed into the command and the remaining items are the file names which are part of the build for that executable.  The Visual Studio generator will output a project file to be contained within the solution, the Xcode generator will add this as a target in the Xcode project and of course it is a named target within generated makefiles.

Examples of the output:
  • Visual Studio:

    Attached Image: VCSolution.jpg

  • Xcode:

    Attached Image: XCode_HelloWorld.png

  • Makefiles:

    Attached Image: Makefile_HelloWorld.png


The first thing you may be asking yourself is what are the two extra projects/targets in the IDE's?  CMake attempts to make things as easy as possible on the programmer and the extra projects are how it does this.  The "ALL_BUILD" target is pretty much what the name suggests, if this is the active target it builds everything within the project.  It is a utility which can be useful to make sure everything still builds after making changes or when using a continuous integration backend such as Cruise Control, Hudson, Continuum etc.  The other project 'ZERO_CHECK' is a bit less obvious and unfortunately, as of Visual Studio 2012, not particularly useful for Windows development.

The purpose of 'ZERO_CHECK' is to check if the developer has changed any of the CMakeLists.txt files or files which are directly referenced.  If any changes are detected it automatically calls CMake to update the solution prior to recompilation.  This works pretty well with Makefiles and Xcode but unfortunately as mentioned, the recent version of Visual Studio no longer includes the macro system which the utility required. As such all 'ZERO_CHECK' ends up doing is rebuilding the solution and projects but not stopping the build, only 'after' the compilation process completes (likely with a whole slew of errors) does Visual Studio notice the solution and projects are different and ask you to reload them.  This is unfortunately Microsoft's infinite wisdom that "no one really uses the macro system anyway, so we won't continue supporting it" at fault, not a problem with CMake.  Hopefully CMake will be able to find an answer to make it work nicely with VC again.

Setting Up The Real Environment

At this point, it is time to break out the CMake GUI since the command line becomes unwieldy as you add more detail to the project.  Starting up the CMake GUI should give you something like the following:

Attached Image: BlankCMakeGui.jpg

The CMake GUI is fairly bare bones and not a great upgrade over the command line in general, but when it comes understanding what CMake is doing and controlling build options, it makes life a lot easier.  Even with the simple 'HelloWorld' project it can display a stunning amount of information describing how CMake is generating the outputs:

Attached Image: CMakeAdvancedOptions.jpg

As you can see, CMake uses a lot of variables with many options.  Normally these items are hidden by having the 'Advanced' option unchecked, but they are very useful in explaining what build options are being used.  You can also change the values from the GUI as desired, this is the main reason to use the GUI since otherwise you have to type in a command line with a potentially large set of '-D "value=whatever"' items appended.

Note:  Editing the options in the GUI will not modify the CMakeLists.txt, if you wish to change an option permanently it must be done in CMakeLists.txt manually.  Option changes are stored only in the CMake cache and will be lost if you move to another machine, change generators or otherwise delete the CMake cache.



Starting with another clean copy of the 'HelloWorld.zip' or manually cleaning out the generated items, setting up the GUI is fairly easy, there are only really two things to worry about at this time; filling in the two text boxes. Telling CMake where the root 'CMakeLists.txt" is and where you wish to output the generated project files.  In the text box labeled "Where is the source code:", you want to point this to the location of the CMakeLists.txt.  So for the 'HelloWorld' test, it would be: "'full_path_to_helloworld'/".  In the text box labeled "Where to build the binaries:" you want to put in: "'full_path_to_helloworld'/_vc11" for Windows as an example.

At this point you can click "Configure" or "Generate" to setup the basic CMake caches.  If you select "Generate" it will also output the solutions/projects/makefiles after configuration is complete.  I usually just press "Generate" myself as it is equivalent to the command line version of running CMake.  If running from a clean directory CMake will ask if it should create the output directory, yes of course we want that so accept it.  CMake will then pop up the following:

Attached Image: Generators.jpg

Obviously depending on platform the options will be different, select the generator appropriate to your platform and press "FINISH".  After CMake builds up it's cache of information, if you didn't press "Generate", do so now.  Your solution/projects or makefiles will be output and you can run through the build and run process appropriate to your platform in order to make sure it's the same as when you did things from the command line.

Introducing ADD_SUBDIRECTORY

It is time to make a new starting project for further work.  This will introduce a basic directory structure and some of the advanced features of CMake which make life easier in the long run.  Build the following directory stucture:

CMakeProject
    build
    tests
    	HelloWorld

Copy the 'main.c' and 'CMakeLists.txt' files into the 'HelloWorld' directory under this structure.

As it is, if you point CMake GUI at the 'CMakeProject' directory and the output to 'CMakeProject/build/"generator"', CMake will do nothing since there is no 'CMakeLists.txt' in the root directory.  Don't try going ahead and pointing CMake at the subfolder with the 'CMakeLists.txt' file, this is not the goal. The goal for the real environment is to support an easily maintained and flexible environment to start with.

Next, it is time to start working with C++ so rename 'main.c' to 'main.cpp'.  This of course implies that 'CMakeLists.txt' needs to also be updated since it is the file which describes our project.  Change the line:
ADD_EXECUTABLE( HelloWorld main.c )
to read:
ADD_EXECUTABLE( HelloWorld main.cpp )

Next, we want to start the hierarchical build description for our project so add two empty 'CMakeLists.txt' files into the directory structure, one under 'CMakeProject' and the other under 'CMakeProject/tests'.

In the file 'CMakeProject/CMakeLists.txt', add the following:
CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 )

PROJECT( CMakeProject )

ADD_SUBDIRECTORY( tests )

And finally in 'CMakeProject/tests/CMakeLists.txt', add the following:
ADD_SUBDIRECTORY( HelloWorld )

Now, with CMake pointed to 'CMakeProject' and 'CMakeProject/build/"generatorname"' click on "Generate".  Open the result in your IDE and everything should look identical to how it did before.  Attempt to build though and it gives you errors.  This is simply because we stopped using the forgiving C compiler and switched to the more explicit C++ compiler.  (Or just told the compiler to be more strict in reality.)  Let's fix the C++, in your IDE or favorite editor, edit the code in 'main.cpp' to be:

/* Hello World program */
#include <iostream>

int main( int argc, char** argv )
{
	std::cout << "Hello World!";
	return 0;
}
Attached File  CMakeProject.zip   1.7K   4 downloads


You do not have to update CMake for this change so just recompile via the IDE and everything should be correct.


So, what does this hierarchy and 'ADD_SUBDIRECTORY' do?  ADD_SUBDIRECTORY is similar to bash/shell scripting 'exec' or 'call' functions in terms that it makes a copy of the current environment and passes it to a child, which in the case of CMake, will look in the specified subdirectory for a 'CMakeLists.txt' file to be processed.  So, if we change compile flags in the top level 'CMakeLists.txt' it will propagate down to the 'HelloWorld' build.  But, on the other hand, if we changed flags within 'HelloWorld' it would not propogate back up and affect other items.

This behavior will become very important later on but for the moment just keep in mind that information passing is "one way" down to children by default.  Later there will be cases of needing to pass data back up to parents but it will be done under very strict control.

Breaking Things While Still Safely Committing To Source Control

That's a mouthful but the intention is to show how you can accidentally break a build for one platform, quickly fix things so others don't have a problem working.  Then going back to track down and correct what failed.  Build breakage is a common problem and it scales from a simple oops and fixed to a major day to day time sink as more people work in the codebase.  Even the best programmer is likely to break the build at least monthly no matter how anal they are about testing and catching problems.  If you have 30 developers with commit rights, that means a broken build at least once a day and this quickly gets out of hand.

So, let's start with a simple build breakage.  Make a copy of the "HelloWorld" directory and name it "Hello2" at the same location as the original.  Add the following line to 'CMakeProject/tests/CMakeLists.txt':
ADD_SUBDIRECTORY( Hello2 )

Hit generate on CMake GUI and you should see:
CMake Error at tests/Hello2/CMakeLists.txt:3 (ADD_EXECUTABLE):
  add_executable cannot create target "HelloWorld" because another target
  with the same name already exists.  The existing target is an executable
  created in source directory "'path'/CMakeProject/tests/HelloWorld".
  See documentation for policy CMP0002 for more details."
That's pretty descriptive, we forgot to change the executable name to something unique.  Go into 'CMakeProject/tests/Hello2/CMakeLists.txt' and rename the executable to 'Hello2' to match our new directory name.  Now regenerate and all should be well.  In the IDE or makefile you should now see subprojects/targets for "HelloWorld" and "Hello2".

Everything is great and you can commit your code.  Now let's break the build in a non-intuitive but very simple manner.  Change the 'main.cpp' in 'Hello2' to the following as a C++11 test:

/* Hello World program */
#include <iostream>


int main( int argc, char** argv )
{
	auto	helloString	=	[]()	{return "Hello World!";};
	std::cout << helloString();
	return 0;
}
Attached File  CMakeProjectBroken.zip   2.46K   7 downloads


If you are on Windows or Linux and rebuild, everything should be fine. So you commit the changes and if you are using an automated build or someone happens to get your code on OsX they get a failure.  Why, what could be wrong?  Well, for the moment we don't care what is wrong, we just want to fix the build.  So, it only fails on OsX, we'll just fix it by not compiling that particular item on OsX.  Change 'CMakeProject/texts/CMakeLists.txt' to the following:
ADD_SUBDIRECTORY( HelloWorld )
IF( NOT APPLE )
    ADD_SUBDIRECTORY( Hello2 )
ENDIF( NOT APPLE )

Commit that change and the build machine should stop complaining and people on OsX won't hate you.  Unfortunately 'Hello2' is simply removed from the build on OsX until we can figure out what the problem is.  As it turns out, the answer is simple; by default OsX uses Clang 4.2.0 (as of Xcode 4.6.1) which does not automatically enable C++11.  In order to enable C++11 it is required to add some compiler and linker flags, but only for OsX.  That will be covered in the next article as we take the environment further.

Conclusion

In this first part we covered a very simplistic usage of CMake and some basic description of how CMake works.  The next article will show how to correct the intentional cross platform breakage of the project and start digging into the important details of the CMake language and its usage in large projects.

Data Structures for Pre-College Programmers: Arrays, Dynamic Arrays, and Linked Lists

$
0
0

Introduction

Many of the beginners on the site are pre-college students.  Often beginners will learn by reading tutorials on the Internet, copying code from books, and trying out things that they find interesting.

This article is part of a series that focuses on giving pre-college developers the basics they need to understand data structures.

This article is about the first three basic data structures: the array; the dynamic array; and the linked list.

The Array

When you need one object, you create one object.  When you need several objects... well, you have several options.

I have seen many beginners with code like the following:
// High Scores
int score1 = 0;
int score2 = 0;
int score3 = 0;
int score4 = 0;
int score5 = 0;
This gives you five high score values.  This method works just fine until you need fifty or a hundred or a thousand of something.

Rather than creating your objects individually you can use an array.  
// High Scores
const int NUM_HIGH_SCORES = 5;
int highScore[NUM_HIGH_SCORES] = {0};

This will create a buffer of 5 items, like so:

Attached Image: ds_array.PNG

Note that the array index starts at zero.  If you have five items, then they range from zero to four.

Drawbacks of a Simple Array


If all you want is a fixed number of objects an array can work just fine.

Let's say you want to add an item to the array.  You can't do that with a simple array.

Let's say you want to remove an item from the array.  You can't do that with with a simple array.

You are stuck with the same size of items for the duration of the object.

What we need is an array that can change size.  This brings us to...

The Dynamic Array


A dynamic array is an array that can change sizes.

Major languages support dynamic arrays in their standard libraries.  In C++ it is a vector.  In Java it is an ArrayList.  In C# it is a List.  All of these are dynamic arrays.

Under the hood a dynamic array is a simple array, but it also has two extra pieces of data.  It stores how big the simple array actually is, and it stores how much data the simple array can actually store.

A dynamic array might look something like this:

// Internals of a dynamic array class
sometype *internalArray;
unsigned int currentLength;
unsigned int maxCapacity;

The internalArray member points to a dynamically allocated buffer.  That actual size of the buffer is stored in maxCapacity.  The numver of items actually used is represented with currentLength.

Adding to a Dynamic Array


When you add an object to a dynamic array several things happen.

The array class verifies that there is enough space.  If currentLength < maxCapacity then there is room to add to the array.  If there is not enough space then a larger internal array is allocated, and everything is copied over to th new internal array.  The maxCapacity value is increased to the new larger size.

When there is enough space, the new item is added.  Every element after the insertion point must be copied over one space in the internal array, and after the copies are made then the hole is filled with your new object, then the currentLength value is incremented.  

Attached Image: ds_arrayAdd.PNG

Since every object after the insertion point must be moved, the best case is when you add to the end; zero objects must be moved (unless the internal array must be expanded).  A dynamic array works best when you only add to the end rather than adding to the middle.

Note:  When you add an object to a dynamic array it is possible for every object to move in memory.  For languages like C and C++, adding to a dynamic array means ALL pointers to array objects become invalid.



Removing from a Dynamic Array


Removing objects is less work than adding objects.

First, the object itself is destroyed.  Second, every object after that location is moved over one space.  Finally, the currentLength is decreased.

Attached Image: ds_arrayRemove.PNG

Just like adding to the end of the array, removing from the end of the array is the best case because zero objects need to be moved.

Also note that we don't need to resize the internal array to make it smaller.  The space can hang around in case we add objects later.

Note:  Removing an object to a dynamic array causes everything after the removed item to move in memory.  For languages like C and C++, removing from a dynamic array means pointers to everything after the removed object become invalid.



Drawbacks of Dynamic Arrays


Let's say your array is very large, and you need to add and remove objects frequently.  This can cause objects to be frequently copied to new locations, and it can cause many pointers to be invalidated.

If you need to make frequent changes in the middle of a dynamic array, there is a better type of linear data structure for you...

Linked Lists


An array is a continuous block of memory, each item after the other.  A linked list is a chain of objects.

Again, the major languages have linked lists in their standard libraries.  In C++ it is called a list.  In Java and C# it is called a LinkedList.

A linked list is made of a series of nodes.  Each node is basically made like this:

// Linked list node
sometype data;
Node* next;

That generates this type of structure:

Attached Image: ds_linkedlist.PNG

Each node chains to the next.

Adding to a Linked List


When an object is added to a linked list it starts by creating a new node.  Your data is copied inside the node.

Next, the insertion point is found.  The new node's pointer to the next object is updated to point to the node that will follow it.  

Finally, the node before the new node is modified to point to your new node.

Attached Image: ds_linkedlistAdd.PNG

Removing From a Linked List


When an object is removed from a linked list, the node before the removed node is found.  It is altered to point to the removed object's next node.  Then the removed object can be safely deleted.

Attached Image: ds_linkedlistRemove.PNG

Benefits of a Linked List


The biggest benefit of a linked list comes when adding and removing objects from the list.  Making changes to the middle of the list is very quick.  Remember that a dynamic array potentially caused every item to move, a dynamic array keeps every other object in place.

Drawbacks of a Linked List


Recall that a dynamic array is a continuous block of memory.  If you need to get the 500th item in the array the code can simply look 500 spaces ahead.  In a linked list the memory is chained together.  If you need to find the 500th item, you must start at the beginning of the chain and follow its pointer to the next item.  Then you need to follow the pointer in the next node.  Then you need to follow the pointer in the next node.  Repeat 500 times.  Random access to a linked list is very slow.

The other major drawback of a linked list isn't quite as obvious.  Each node requires a little extra space.  How much space does it require?  You might think it only requires the size of a pointer, but that isn't quite right.

There is a little bit of overhead every time an object is created dynamically.  Some languages, like C++, work with pages of memory.  Typically a page is 4 kilobytes.  When you use the default new and delete operators a full page of memory will be allocated even if you will only use a single byte. Both Java and C# were designed differently and have special rules for small objects.  These languages do not require a full 4kB memory page, but they do have a small amount of overhead.

You don't need to worry about the second drawback if you are using the standard libraries.  They have been written in a way that minimizes the wasted space.

Conclusion


These three types, the array, dynamic array, and linked list, form the basis for nearly all the more complex data containers.  When you get to college some of the first assignments in a data structures class will be to implement a dynamic array and a linked list class on your own.

These structures are fundamental to programming.  It doesn't matter what language you learn, you will be using them to work with your data.

NEXT: Stacks and Queues

A Cross Platform Test Driven Development Environment Using CMake (Part 2)

$
0
0

Introduction


In Part 1, I went through the creation of a basic CMake build environment and ended by breaking the build for one of the three targeted platforms.  Continuing on from this broken example, the intention is to fix the project correctly and begin leveraging CMake abilities in a more fundamental manner.  A utilzation of CMake's language will be presented in the process of fixing the project and additional target types, and ways to use them, will be added.  Primarily everything covered will be focusing on the cross platform nature of the environment and CMake usage.

The CMake Language

Everything in the language supported by CMake is based on text processing and the expansion of macro type text into larger (or smaller) pieces of different text.  This simplicity of design for the language unfortunately also leads to a number of things which seem simple enough from the descriptions but can be confusing and downright painful to use correctly. The key to using CMake is to make sure you don't try to get too fancy.  If you can write a couple extra lines and avoid complexity, just write the extra code.  This is a build system after all and as such being verbose still means you are being verbose in a very minimal portion of the overall project code.

MESSAGE, Learn It and Love It

The first thing to do when learning CMake is to get an understanding of the command 'MESSAGE'.  This command is your bread and butter method of debugging.  From the online documentation:

message([STATUS|WARNING|AUTHOR_WARNING|FATAL_ERROR|SEND_ERROR]
          "message to display" ...)

For most usage only two variations are needed:

MESSAGE( "This is a message." )
and
MESSAGE( FATAL_ERROR "Why this failed." )

Everytime I describe a command or feature of CMake, I will include a 'MESSAGE' based example so you can see the item in action and what it does.  You should be able to add these snippets to any CMake file without causing problems for the file you add them to.  As such, using the previous articles very simple hello world starter project is a good place to insert the snippets and see the results.


Revisting the Basics

Remember that CMake is a caseless language, well that's only partially true and the details need to be cleared up.  A command named 'PROJECT' can be written as 'Project' or 'project' and CMake will execute it the same way no matter what case it is.  The important item here is that the description is specific to commands, the variables covered next are case sensitive such that 'a' and 'A' are different variables.  In fact most items beyond the commands are case sensitive so be careful about your usage of case.

The CMake Variable Type

As with any language, CMake has the concept of a variable.  In the case of CMake the variable is very limited in terms that it is nothing more than a dynamic form of text replacement.  There are no integer, boolean or other types of variable in CMake though integer and boolean are supported by being represented as strings.  Also of note, if you misstype a variable via incorrect case or simply a typo there is no concept of "undefined" variable except that you get an empty string back.  This lack of error result can be a large source of bugs and they can be very difficult to track down.  There are only two direct operations performed on variables in CMake:

  1. Setting a variable:
    SET( MyVariable ToThis )
  2. Expanding a variable:
    ${MyVariable}

The first rule to keep in mind, CMake treats everything as text until explicitly told not to and as such using variables can be error prone.  Take the following CMake snippet:
SET( MyVariable AValue )
SET( AnotherVariable MyVariable )

MESSAGE( "MyVariable" )
MESSAGE( "${AnotherVariable}" )

The output will be:
MyVariable
MyVariable

If you are scratching your head going "huh", you are not alone.  The expansion of a variable to its replacement has to be triggered manually by the user.  In order to trigger expansion you must surround the variable name with '${' and '}'.  So, rewriting the example to do what you may have expected:

SET( MyVariable AValue )
SET( AnotherVariable ${MyVariable} )

MESSAGE( "${MyVariable}" )
MESSAGE( "${AnotherVariable}" )

The output of which will be:
AValue
AValue

Note that in the two uses of 'MyVariable' I told CMake to explicitly expand it.  Also note that expansion within quotes takes place, so using '$' as part of a message needs to be done carefully.

Nesting Expansion

Revisting the first version of the example of variables, there is something important to consider.  Given the original example:
SET( MyVariable AValue )
SET( AnotherVariable MyVariable )

MESSAGE( "MyVariable" )
MESSAGE( "${AnotherVariable}" )

Let's modify it a bit:
SET( MyVariable AValue )
SET( AnotherVariable MyVariable )

MESSAGE( "${MyVariable}" )
MESSAGE( "${${AnotherVariable}}" )

You might be surprised to see the output as:
AValue
AValue

What the code in the second 'SET' and 'MESSAGE' lines means now is something quite a bit different.  The 'SET' portion has not changed but the way we expand the variable within the 'MESSAGE' text string has.  Basically we are saying to expand the variable 'AnotherVariable' and then expand the result of that expansion again.  In other words, it is a pointer to another variable in a C like language.

Another variation would be:
SET( Target Something )
SET( ${Target}_Name MyLibrary )
SET( ${Target}_Type SharedLibrary )

If you guessed that the last two 'SET' commands will make variables named: 'Something_Name' and 'Something_Type', you get a gold star.  This makes it possible to create the equivelant of structures within CMake.

As much as these are clever ways to use the expansion system, I try to avoid them as overly complicated for what should be a simple secondary portion of your project.  There are times and places to use them, hence the description, but try to avoid them for your personal sanity and that of others that have to figure out what the expansions mean.

Appending To Variables

A common pattern required in make files is to concatenate and append various things together.  The set command is used for this with a slightly modified syntax:

SET( Target Part1 )
SET( Target "${Target} Part2" )
MESSAGE( "${Target}" )

Which outputs:
Part1 Part2

Make sure to use the quotes unless you want CMake to eat white space and turn the item in a list.

Lists In CMake

Lists are supported in CMake but in a somewhat clunky manner which imposes some limitations on what they can be used for.  Remember that everything in CMake is text based, as such CMake can support lists but it does so by simply making a string with semi-colon delimited sections of text in them.  So, if I want a list of x, y and z, it is really just a string: "x;y;z".  This is normally fine and you can do a lot with this, but if you ever have something which requires a semi-colon you can't use CMake lists since it will break the item at the semi-colon into two pieces.

Even with the limitations, lists are an important part of CMake day to day usage.  Take the following:
SET( MyList a b c )
MESSAGE( "${MyList}" )

Outputs:
a;b;c

In larger lists, it is possible to write the same code as:
SET( MyList
    a
    b
    c
   )
MESSAGE( "${MyList}" )

With the same output. CMake automatically removes the whitespace and replaces it with a semi-colon.

Now, what if you really wanted the string "a b c" instead of conversion to a list?  Simple, double quote the right hand side of the 'SET' command:
SET( NotAList "a b c" )
MESSAGE( "${NotAList}" )

Outputs:
a b c


Again, things get more complicated mixing and matching variables in different manners.  So for instance what about the following:
SET( NotAList "a b c" )
SET( NotAList2 "d e f" )
SET( ItsAListNow ${NotAList} ${NotAList2} )
MESSAGE( "${ItsAListNow}" )

Outputs:
a b c;d e f

To fix it to be a non-list of the two given items, you again have to double quote the 'SET' contents:
SET( NotAList "a b c" )
SET( NotAList2 "d e f" )
SET( ItsStillNotAList "${NotAList} ${NotAList2}" )
MESSAGE( "${ItsStillNotAList}" )

While the examples are simple, the complexity of what is and what is not a list or compiled into a list gets a bit tricky on occasion.  Once again, the best solution is not to mix and match and be very explicit about how you work with lists.

Booleans, Really?

In any language which supports flow control it is neccessary to have a concept of true and false.  CMake supports this concept but it can be a tricky subject due to the way the support is implemented.  In many (most?) languages true means "non-zero" without further expansion, i.e. only 0 means false, anything else is true.  CMake unfortunately enforces the false premise and assumes everything else is true which really turns things around on most programmers.  What is considered false in CMake is the following: an empty string, "FALSE", "OFF", "NO" or any string ending with "-NOTFOUND".

So, when writing flow control, it is important to remember the list of things which actually will be considered false.  A notable item missing from the list is "0" so math can't be used to actually end up with a false value unless you then compare the resulting string to a zero string explicitly.

Integral Variables

They don't exist except by side effect of extensions added to the language.  Again, everything is text in CMake, so 1, 2, 3 are all stored as text strings.  In general, there is rarely much reason to use numeric values in a build system so integer processing will not be covered.

Flow Control In CMake

CMake supports a full language, you could sit down and write a CMake game if you were perverse enough to have the desire to do so.  Instead I'll stick to writing a game using C++ and avoid CMake as much as possible.  CMake supports the basic 'foreach', 'while' and 'if/else' types of flow control.  While it seems limited, each command has multiple variations which allow for common usage patterns you may require.

90+% of the time, the only flow control you should really need in a build system is the 'if/else' variation.  As such, the syntax is important to cover but also a second warning to read the section on "Booleans, Really?" as these items go hand in hand.  A real understanding of the oddities of CMake's concept of true/false is critical moving forward.  (Or to repeat it here, what constitutes a false must be known as everything else is considered true.)

If/Else In a Linear Text Processor

CMake is not much of a parser and primarily is just a lexer, it simply processes text in a linear fashion looking for keywords and what are effectively 'escape' sequences.  The keywords are fairly obvious such as "PROJECT" or "ADD_SUBDIRECTORY".  The escape sequences are generally caused by something like '${' where the system waits till it finds a matching '}' and then looks in a map for the text between '${' and '}' which it then inserts into the the text stream CMake is reading.  Given such a system, if/else require specific terminators.  As such, CMake supplies the following commands: 'IF', "ELSEIF" and "ENDIF".

An example of using 'IF'/'ENDIF' to test for primary platforms:
IF( WIN32 )
ENDIF( WIN32 )

IF( APPLE )
ENDIF( APPLE )

IF( UNIX )
ENDIF( UNIX )

Note:  
It is no longer required to put in the same start and end tags for 'IF'/'ENDIF', i.e. the 'ENDIF( UNIX )'.  You can simply write 'ENDIF()' and it will implicitly match the nearest scope of 'IF'.  I started when CMake expected the matching tags and as such it is a habit to use the matching tags.  The benefit to continuing to do so is that CMake will print out warnings about non-matching tags such that if you goofed up the structure you know where to start backtracking from.




Fixing The Intentional Build Break: The Correct Method

In the prior article I ended up intentionally adding something which seemed like a safe change but broke the build on the OsX platform.  The fix at the time was intended to be something you might do in a panic in order to let others get back to work.  It was a quick patch, it is now time to fix the problem in the proper manner.

The problem introduced is very simple.  As of the latest Xcode (4.6.1) and the recent transition to LLVM (CLANG) as the compiler instead of GCC, C++11 support is not enabled by default.  So, using lambda's is illegal without some changes to the build environment.  CMake makes this easy, but there are some gotcha's to be noted.

In order to start this, download the following simple environment: Attached File  CMakeProjectBroken.zip   2.46K   2 downloads
.  Unzip that somewhere.

If you have a Mac, you get to follow along and see the errors go away, otherwise you still learn a key bit about CMake in this process.  The reason I used the OsX break in the example is that it was easy to trigger and Windows and/or Linux specific folks would be mostly clueless as to how to fix it.  If you don't have a Mac available don't fret, the intention is to teach about CMake and cross platform work, not specifically about the Mac environment no matter how specific the fixes are to Mac at this point.

The CMake Variables Of Interest

Using the simple project, the CMake GUI displays the following when advanced is turned on
Attached Image: OsXAdvancedOptions.png

That's a lot of variables, thankfully we don't need to modify very many of them.  The items we are looking to change are the "xxx_CXX_FLAGS_xxx" variations to start with.  But first, we need to put the broken project back into the build. Open up 'CMakeProject/tests/CMakeLists.txt' and remove the 'IF( NOT APPLE )' and related 'ENDIF' lines and then regenerate the project with CMake.  When you go back to Xcode it should update automatically and show the 'Hello2' target once again.  Obviously if you attempt to build it will fail on the lambda line.

Since we need to make the new flags global, we are going to put the modifications of the compilation flags into the base most 'CMakeLists.txt'.  Instead of having to hunt for the file via the open file dialog, CMake has done us a favor and added the file into the project for us.  The base most 'CMakeLists.txt' can be found under the 'ALL_BUILD' target, so just click on that and it shows up in the Xcode editor area.  (Most IDE's have this same feature where the most related CMakeLists.txt is included in the targets and/or projects.)

The flag we want to add is going to be global and included in all build variations.  So the variable we want to modify is 'CMAKE_CXX_FLAGS' by adding the '-std=c++11' flag to the variable.  Change the root CMake file as follows:

CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 )

SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11" )

PROJECT( CMakeProject )

ADD_SUBDIRECTORY( tests )

Regenerate the project and build in Xcode.  If you were to check this in as is, the OsX folks would be happy but everyone else would likely be very mad because this will apply to all builds regardless of platform.  Since Visual Studio's compiler doesn't know this flag, the build would either be broken or generate a whole bunch of warnings about the unknown flag.  So, how do you figure out what is the current platform and limit the changes to only one of them.  CMake defines several variables based on the current platform: UNIX, WIN32, APPLE and others.  These variables are fairly generic and don't specifically indicate a particular platform, for instance on OsX both UNIX and APPLE will be set.  For the time being, we don't need to be very specific, we just care if this is a Mac and we assume it is running OsX, so just checking 'APPLE' is good enough.

CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 )

IF( APPLE )
	SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11" )
ENDIF( APPLE )

PROJECT( CMakeProject )

ADD_SUBDIRECTORY( tests )

This fixes the code for Mac and will work on other platforms.  You can commit and be confident that all platforms will work with the new project added.

Let's have some fun and make our C++11 test a bit more complicated.  Open 'Hello2/main.cpp' and modify it to be the following:

/* Hello World program */
#include <iostream>
#include <functional>


int main( int argc, char** argv )
{
	typedef std::function< const char* const ( void ) >	StringFunction_t;
	StringFunction_t	helloString	=	[]()	{return "Hello World!";};

	std::cout << helloString();
	return 0;
}

If you are on Windows or Linux everything looks good and you commit.  Within the next couple minutes a furious OsX programmer walks over and smacks you upside the head and asks why you keep breaking the build!!!!  So, you disable your C++11 test again, and go back to figuring out what the heck is wrong now.  Deciding to fix the thing once and for all, you change the root CMake file to be the following:

CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 )

IF( APPLE )
	SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++" )
	SET( CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -stdlib=libc++" )
	SET( CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -stdlib=libc++" )
	SET( CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -stdlib=libc++" )
ENDIF( APPLE )

PROJECT( CMakeProject )

ADD_SUBDIRECTORY( tests )

Once again, the C++11 testbed compiles under all three environments and the OsX programmers stop making Voodoo dolls which look like you.  In addition to telling the compiler to allow C++11 syntax in the core language, we also need to point it at the Clang project standard libraries, otherwise it only allows the language changes but none of the library features.  We also tell the linker for the three forms of targets about the change.

Libraries

Eventually almost every project is going to want to break up code into libraries.  There are of course two variations of libraries: static and shared.  To start with, we'll add the most simple version which happens to be a static library.  Add the following directories to the 'CMakeProject' hierarchy:

CMakeProject
    libraries
    	Hello
    		Include
    		Source

Note:  
A fair number of people do not like separating the include and source folders and prefer to simply put everything in a single location.  This is purely personal preference and as such, once you have gone through the articles, merge the directories if you desire.  The reason I perform the division is for later, when I want to distribute a pre-built library and the headers, it simply makes it easier if the headers and source are not mixed together.



Add the following files, we'll discuss the contents a bit later:

CMakeProject/libraries/CMakeLists.txt
ADD_SUBDIRECTORY( Hello )

CMakeProject/libraries/Hello/CMakeLists.txt
INCLUDE_DIRECTORIES( Include )

SET( INCLUDE_FILES
	Include/Hello.hpp
)

SET( SOURCE_FILES
	Source/Hello.cpp
)

ADD_LIBRARY( Hello
	STATIC
	${INCLUDE_FILES}
	${SOURCE_FILES}
)

CMakeProject/libraries/Hello/Include/Hello.hpp
#pragma once

const char* const HelloString();


CMakeProject/libraries/Hello/Include/Hello.cpp
#include <Hello.hpp>
    
const char* const HelloString()
{
    return "Hello Library!";
}

And finally, modify the root CMake file to contain the additional line to add this to the build:
CMakeProject/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 )

PROJECT( CMakeProject )

ADD_SUBDIRECTORY( libraries )
ADD_SUBDIRECTORY( tests )

Regenerate the project with CMake and you should see the new library in the project.

INCLUDE_DIRECTORIES

One of the new commands used in CMake is the 'INCLUDE_DIRECTORIES' command.  This command is responsible for telling CMake what include paths your targets require when compiling.  The path you give CMake is relative to the location of the 'CMakeLists.txt' currently being processed.  In this case the file 'CMakeProject/libraries/Hello/CMakeLists.txt' is being processed and as such we can simply type in 'Include' since it is in the same directory as the 'CMakeLists.txt'.

Later, we will need to include multiple directories.  In order to do so, there are two options.  Call 'INCLUDE_DIRECTORIES' multiple times with each directory or add multiple directories in a single call.

GET_PROPERTY( directories DIRECTORY INCLUDE_DIRECTORIES )
MESSAGE( "${directories}" )
INCLUDE_DIRECTORIES( Include )
GET_PROPERTY( directories DIRECTORY INCLUDE_DIRECTORIES )
MESSAGE( "${directories}" )
INCLUDE_DIRECTORIES( A )
GET_PROPERTY( directories DIRECTORY INCLUDE_DIRECTORIES )
MESSAGE( "${directories}" )
INCLUDE_DIRECTORIES( B C D )
GET_PROPERTY( directories DIRECTORY INCLUDE_DIRECTORIES )
MESSAGE( "${directories}" )

Which outputs:

CMakeProject/Include
CMakeProject/Include;CMakeProject/A
CMakeProject/Include;CMakeProject/A;CMakeProject/B;CMakeProject/C;CMakeProject/D

Note:  
All directories and paths output by CMake are absolute rooted paths.  For this reason, do not try to distribute the outputs of CMake since they are machine specific.  Anyone compiling the code will need to use CMake on their machine.



ADD_LIBRARY

The command 'ADD_LIBRARY' is similar to 'ADD_EXECUTABLE' in that it defines an output for your project.  There is an additional parameter which tells CMake what type of library is to be made.  The new parameter can be 'STATIC', such as we used, or 'SHARED', which will be dealt with later.  Something which may seem a little strange is that you give this command both the headers and the source files.  The reason for this is that 'ADD_LIBRARY' is effectively the project generator, if it did not have the header files they would not show up in an IDE.

Using Libraries

So far we can build the library but nothing is trying to call the functionality or link against it.  In order to use the library we need to expose some extra data to the other projects.  The data exposed needs to be the include directory location and the name and location of the library to be linked against. The link library can be solved fairly easilly, add the following:

CMakeProject/tests/Hello2/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 )

PROJECT( HelloWorld )

ADD_EXECUTABLE( Hello2 main.cpp )

TARGET_LINK_LIBRARIES( Hello2 Hello )

CMake will take care of figuring out where the library is and link it to 'Hello2' from now on. Things get a bit more difficult at this point since CMake does not track the include directories.  We need to somehow pass the location of the include directories back to the root CMake file.  If you remember from the first article though, CMake propagates data only into files called by 'ADD_SUBDIRECTORY', it doesn't get the changes made in those files back though.  In steps a modification of the 'SET' command:

SET( OutVariable Values PARENT_SCOPE )

Using this variation of the 'SET' command we can push values back up to the calling CMake command.  So, let's add a couple items to the 'CMakeLists.txt' files:

CMakeProject/tests/Hello2/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 )

INCLUDE_DIRECTORIES( ${HELLO_INCLUDE_DIRS} )

PROJECT( HelloWorld )
ADD_EXECUTABLE( Hello2 main.cpp )
TARGET_LINK_LIBRARIES( Hello2 Hello )

CMakeProject/libraries/Hello/CMakeLists.txt
INCLUDE_DIRECTORIES( Include )

SET( INCLUDE_FILES
	Include/Hello.hpp
)

SET( SOURCE_FILES
	Source/Hello.cpp
)

ADD_LIBRARY( Hello
	STATIC
	${INCLUDE_FILES}
	${SOURCE_FILES}
)

# Export the include directory.
SET( HELLO_INCLUDE_DIRS Include PARENT_SCOPE )

CMakeProject/tests/Hello/main.cpp
/* Hello World program */
#include <iostream>
#include <functional>
#include <Hello.hpp>


int main( int argc, char** argv )
{
	std::cout << HelloString();
	return 0;
}

If you regenerate the project and compile again, it doesn't compile.  There are three basic problems with the approach which have to be fixed.  First off, the propagation of the include directory only goes up one level and there are actually two levels involved.  I.e. CMakeProject/CMakeLists.txt calls CMakeProject/libraries/CMakeLists.txt which in turn calls CMakeProject/libraries/Hello/CMakeLists.txt.  The propagation of the variable only gets to the CMakeProject/libraries/CMakeLists.txt scope.  We have several choices to fix this, one would be to call 'SET' in the second level to push the variable all the way to the root CMake context but this is error prone since then you have to duplicate the 'SET' calls at both levels.

Another possible approach would be to remove the intermediate file and add libraries directly via the root CMake file.  This is possible but defeats the purpose of breaking things up for easier maintanence.  So, the solution is another new CMake command: 'INCLUDE'.  The 'INCLUDE' command works similar to the 'ADD_SUBDIRECTORY' except that instead of starting a new context of CMake, it processes the file in the existing context. As such, we effectively do include the libraries directly in the root CMake file but we leave the division of files alone.

Unfortunately, 'INCLUDE' is not a perfect solution since it runs within the scope, and effectively the directory, of the parent CMake file.  So the calls to 'ADD_SUBDIRECTORY' need to be modified.

CMakeProject/libraries/CMakeLists.txt
ADD_SUBDIRECTORY( libraries/Hello )

With this change, regenerate the projects and attempt to build.  Once again, it fails.  The last bit to fix is the include path itself, let's do a little debugging.  Add the following line to 'CMakeProject/tests/Hello2/CMakeLists.txt':

MESSAGE( "${HELLO_INCLUDE_DIRS}" )

Regenerate the projects and the output will be:
Include

This is not correct, we need the full path to the include directory. In order to correct this, open up the 'CMakeProject/libraries/Hello/CMakeLists.txt' and modify it as follows:

SET( INCLUDE_DIRS
	${CMAKE_CURRENT_LIST_DIR}/Include
)
INCLUDE_DIRECTORIES( ${INCLUDE_DIRS} )

SET( INCLUDE_FILES
	Include/Hello.hpp
)

SET( SOURCE_FILES
	Source/Hello.cpp
)

ADD_LIBRARY( Hello
	STATIC
	${INCLUDE_FILES}
	${SOURCE_FILES}
)

# Export the include directory.
SET( HELLO_INCLUDE_DIRS ${INCLUDE_DIRS} PARENT_SCOPE )

Regenerate the project and the output will be the full path to the library include directory.  Build and everything should work this time.  CMake keeps some useful variables which can be used to solve a number of problems in setting up the build, among them is the variable 'CMAKE_CURRENT_LIST_DIR' which contains the full path to the location of the 'CMakeLists.txt' file currently being processed. By combining that variable with the include directory name we form the full path required in projects intending to use this library.

If you have not followed along step by step, here is the new project: Attached File  CMakeProject.zip   4.45K   6 downloads


Conclusion

In this part we have covered some of the basic commands available in CMake files, how to fix per OS issues and finally how to start building modular projects using static libraries.  In the next part we will cover shared libraries and finally begin including the open source unit testing libraries.

Data Structures for Pre-College Programmers: Trees and Heaps

$
0
0

Introduction


Many of the beginners on the site are pre-college students.  Often beginners will learn by reading tutorials on the Internet, copying code from books, and trying out things that they find interesting.

This article is part of a series that focuses on giving pre-college developers the basics they need to understand data structures.

The previous article was on Stacks and Queues.

This article is about tree data structures.

Tree Data Structures


Trees of data are very useful for many things.  Since we are a game development site, one of the most common uses of tree data structures is to subdivide space, allowing the developer to quickly find objects that are nearby without having to check every object in the game world.

Even though tree data structures are fundamental to computer science, in practice most standard libraries do not directly include tree-based containers.  I'll cover the reasons for that in the details.

The Basic Tree


A tree is, well, a tree.

A real life tree has a root.  It has branches.  And at the end of the branches it has leaves.

Attached Image: IMG_7060.png

A data structure tree starts at a root node.  Each node can branch off into child nodes.  If a node has no children, it is called a leaf node.  When you have more than one tree, it is called a forest.  

Here is an example of a tree.  They are generally drawn upside down from real life trees; the root node is usually drawn at the top, and the leaves are usually drawn at the bottom.

Attached Image: ds_tree.PNG

One of the first questions to ask is: How many children should a node have?

Many trees have up to two child nodes.  These are called binary trees.  The example above is a binary tree.  Usually the children are called the left and right child nodes.

Another common type of tree in games has four child nodes.  A quadtree, which is a tree that can be used to cover a grid, will usually call the child nodes by the direction they cover: NorthWest or NW, NorthEast or NE, SouthWest or SW, and SouthEast or SE.

Trees are used in many algorithms.  You have already heard about binary trees.  There are balanced trees and unbalanced trees.  There are red-black trees, AVL trees, and many more.  

While the theory of a tree is nice, it suffers from some major flaws:  Storage space and access speed.

What is the best way to store a tree?

The most basic route, simply building a linked list, is also one of the worst cases you can construct.

Let's assume you want to build a balanced binary tree.  You start out with this data structure:

// Tree node
Node* left;
Node* right;
sometype data;

Fair enough.

Now let's assume you want to store 1024 items in it.  

So for 1024 nodes you will need to store 2048 pointers.  That's fine, pointers are small and you can live with the tiny space.

You may recall that every time you allocate an object it consumes a small amount of additional resources.  The exact amount of extra resources depends on the libraries your languge is using.  Many popular compilers and tools can use the wide range from just a few bytes to store the data on the small end up to using several kilobytes of padding to help with debugging on the large end.  I have worked with systems where even the smallest allocation required 4KB of memory; in this case the 1024 items would require about 4MB of memory.  

It usually isn't that bad, but the overhead of lots of tiny objects allocated individually will add up quickly.

Next, the speed issue.

Processors like it when things are right next to each other in memory.  Modern processors have a piece of very fast memory --- the cache --- that usually works really well for most data.  Whenever a program needs one piece of data the cache will load up that item and also all the items next to it.  When something isn't loaded in the very fast memory --- called a cache miss --- it will pause the program until the data is loaded.

The most direct format where every tree item is stored in its own little bucket of memory means that nothing is next to each other.  Every time you travel across the tree you end up stalling your program.

So if making a tree directly has these problems, we should consider a data structure that acts like a tree but doesn't have the problems.

Which brings us to...

The Heap


Just to be confusing, there are two kinds of heap.

One is the memory heap.  It is a huge block of memory where objects live. That is not the kind of heap I am writing about.

A heap data structure in concept is the same as a tree.  It has a root node, each node has child nodes, and so on.

A heap adds constraints that it must always be sorted in a special way.  You will need to provide a sorting function --- usually the less than operator.  When objects are added or removed from a heap the structure shuffles itself to be a "complete" tree, where every level in the tree is full, except for possibly the last row where everything must be pushed on one side.  This makes storage space and searches on a heap very efficient.

Heaps can be stored in an array or a dynamic array so there is little space wasted per allocation.

C++ provides functions such as push_heap() and pop_heap() to help you implement heaps on your own containers.  Java and C# do not provide similar functionality in their standard libraries.

Here are a tree and a heap with the same information:

Attached Image: ds_heap.PNG

Why They Are Not In Standard Libraries


These are basic, fundamental, very useful data structures.  Many people believe they should be included in standard libraries.  A few seconds on your favorite search engine will find thousands of implementations of trees.

It turns out that while trees are very useful and fundamental, there are better containers out there. There are more complex data structures that have the benefits of a tree (stability and shape) and the benefits of a heap (space and speed).

The more advanced data structures are generally a combination of data tables coupled with lookup tables.  The two tables combined will allow fast access, fast modification, and will perform well in both dense and sparse situations. They don’t require shuffling items around when items are added or removed, and they don’t consume excess memory or fragment memory after extended use.


Conclusion


It is important to know about the tree data structures since you will rely on them many times in your career.

Also important is that using these data structures directly has a few drawbacks.  You can implement your own tree structures, just be aware that more compact representations exist.

So why did I cover these if they aren't really used in standard libraries?  They are used as the internals to the next topic:

NEXT: Non-Linear Data Structures

Data Structures for Pre-College Programmers: Stacks and Queues

$
0
0

Introduction


Many of the beginners on the site are pre-college students.  Often beginners will learn by reading tutorials on the Internet, copying code from books, and trying out things that they find interesting.

This article is part of a series that focuses on giving pre-college developers the basics they need to understand data structures.

The previous article was Arrays, Dynamic Arrays, and Linked Lists.

This article is about stacks and queues.

The Stack


Imagine you have a bunch of papers.  You push one paper onto the stack.  Now you can only easily access the top paper.  You push another paper onto the stack.  The earlier paper is now covered and inaccessible, and the new paper is available for use.  When you are done with the top paper you can remove it from the stack, exposing the one beneath.

That is the idea of a stack.

A stack is a LIFO structure.  That stands for Last In First Out.  When you add and remove from a stack, the last one that you put in will be the first one you get out.

There are really only three operations needed for a stack:  Push, Pop, and Top.  Push will add an object to the stack.  Pop will remove an object from the stack.  Top will give you the last-most object on the stack.

These containers are part of the standard libraries of most languages.  In C++ it is called a stack.  In Java and C# it is a Stack.  (Yes, the only differnce is the capitalization of the first letter.)

Under the hood, a stack often implemented as a dynamic array.  If you recall from that data structure, the fastest operations on a dynamic array are to add and remove elements from the end.  Since a stack is always adding and removing from the end, it is usually extremely fast to push and pop objects onto a stack.

The Queue


Imagine you are waiting in line for something.  The first person in the line gets served, then leaves.  The second person in line gets served, then leaves.  More people walk over to the line and stand at the end of it.

That is the idea of a queue.

Attached Image: queue.PNG

A queue is a FIFO structure.  That stands for First In First Out.  When you add and remove from a queue, the first one you put in will be the first one you get out.

A queue only needs a few operations:  Push_Back, Pop_Front, Front, and Back.  Push_Back will add to the end of the queue.  Pop_Front will remove from the front of the queue.  Front and Back will let you examine the two ends of a queue.

Programmers will frequently need to add and remove from both ends of a queue.  This is called a double ended queue, or deque.  In this case they add two other operations, Push_Front and Pop_Back.  

Again, these containers are included in most major languages.  In C++ it is a queue and a deque.  Java specifies interfaces for both queue and deque, then relies on a LinkedList for the implementation.  C# provides a Queue class, but not a Deque class.

Internally, a queue and a double-ended queue can be somewhat complex.  Since objects can come and go at either end, the internal container needs to be able to grow and shrink at the beginning and at the end.

Many implementations will rely on multiple pages of memory.  When either end grows beyond the current page, an extra page is added.  Similarly a page is removed when it is no longer needed.  Java follows a different route; it requires a little additional memory using a linked list rather than pages of memory, but it works for the language.

Priority Queue


There is a very common variation on the queue.  A priority queue is very similar to a basic queue.  You push things on to the end, and you pop things off from the front.

The difference is that you can give priority to certain items in the queue.  All of the most important items are processed in a FIFO order.  Then the next priority items are processed in a FIFO order.  Repeat until the lowest priority items are handled in FIFO order.  If you add a new item that is higher priority than the rest of the queue, it will immediately jump to the head of the line.

In C++ this is called a prioirty_queue.  In Java it is a PriorityQueue.  C# does not include a priority queue in the standard library.

Priority queues are not just useful in getting yourself to the front of the line on the corporate printer.  Priority queues can be used to easily implement algorithms like the A-star searching routine.  The most likely results can be given a higher priority over the less likely results.  You could choose to build your own system for sorting and organizing your A-star search, but it will be much easier to just use the built-in priority queue.

Conclusion


Stacks and queues and deques and priority queues can be implemented in terms of other data structures.  They are not fundamental data structures, but they are frequently used.

They are very efficient when you need to work only with the endpoints of your data, and don’t really care what is in the middle.

NEXT: Trees and Heaps

What does a Game Designer do? An Introduction to Role

$
0
0

The Introduction to an Introduction


If you think of a small indie developmer team, many people imagine an Artist, a Programmer and a Game Designer. The Artists draws nice shapes with a pen, the Programmer punches his keyboard until the nice shapes show up and the Game Designer? What in the world does he do, a sacred design ritual?
It is a bit hard to grasp for anybody new to Game Development, it is also not an easy job to explain. That's why I hope to shed some light the role of the Game Designer and what he actually does and maybe even give a starting point for aspiring Game Designers. I also want to touch upon Game Design, it obviously has to do something with this role and what a good design is. So without further ado, let's get right to business.


The Role of a Game Designer


Let's make a comparison, a game Designer and Level Designer have a lot in common. As a Level Designer, you are responsible to put the assets of an Artist into a nice level for a player. But that is nearly not enough, the player has to like the level he is playing, it has to fulfill a certain goal, for example introduce a new tool to the player. This sounds like intiuitive to the max, and it is. But if you are doing this subconciously is bound to fail at some point. Your job is not to dream up nice levels, you are making levels for a specific purpose to the player. As a Level Designer, you are making a prediction, what obstacles the player has to overcome and how he or she is able to do so. Then you HAVE TO TEST your prediction, you have to playtest.
With your new experience, you can make more accurate predictions, make a better level, playtest, rinse and repeat. That is basically what a Game Designer does, but in a bigger scheme of things.

Note:  As a Game Designer, you are constantly testing predictions about how a mechanic or subpart affects the player. Even an experienced designer gets surprises on a regular basis. You should analyse the results and figure out why your predictions were inaccurate and how you can fix it.
This is how you improve on your game design!



As a Game Designer, you don't design one level, you design the level progression, how difficult the level is, when to introduce new mechanics, pacing, story development, basically everything. From the attack animation of one character to the balancing of whole systems, everything is part of what the player experiences, which makes it partly your job to make it fit in the game and to ensure it has the effect on the player you thought it would.
And everything influences your design. The artstyle is part of the game design as the button layout. Unless you are doing every single job yourself, you are working with many different people with many different expertises, if you like it or not they will influence the game design in some way or another.

The Team and the Game Designer

In a nutshell, there is a good and a bad side of being a game designer in a team.
The bad side of your role is that the job you are responsible for is influenced by everyone. But this is also part of the job description (see reference 1). You have to inform the team members about the game visions. Maybe the most important task of a game designer is communicate, to talk to the different experts and understand their different "languages"(it is hard to understand a programmer for a layman), make sure that all differet worlds share the same goal, the same vision of what the game should become.   The good side of it is that the job you are responsible for is influenced by everyone. Because you have so many different expertises in your team, because they sometimes don't even seem to talk the same language, they bring in ideas you would never even dreamed about. They help you with some parts of your job.

It actually isn't your main task coming up with new ideas, or even deciding if a mechanic gets put into a game or not. Your job is to make the mechanics work, balance them and test their impact on the players. But when have you done a good job? Unlike computer programs, you hardly have a way to compare game designs, when is your design good?


"Good" and "Bad" Game Design


Those two terms get thrown around a lot without asking the question, what actually is "good" or "bad" design?

What is a good game?

Take your favorite game for example, if you can't play it in your head, play it again for five to ten minutes. Why do you like it? Why is it your favorite game?

I guess the most frequent answer would be: "Because it is fun!".

You probably picked a favorite game where this is partially true, but I argue it is not the reason why this game stands out. Many things are fun, many games have been fun but vanished from the face of the earth.
I would say the same thing is true about movies, many movies are entertaining, but the Batman reboot isn't that good because they have been more entertaining than the old movies(well, not counting Batman the dark knight rises, my heart is still bleeding Christopher Nolan!). I say it is because of the story that we cared about. We could see the pain Batman went through, we could see him as a human we relate to, how he overcame his inner fears, how and why he chose to do the right thing. Batman Begins is one of the few movies I really cared about the protagonist. One of the few movies where the antagonist, the evil guy, wasn't far more interesting and actually made the film stand out.  I argue the same thing is true for games.

Let's take Ben "Yahtzee" Croshaw's favorite game and analyse what he says about it: Watch his Silent Hill 2 review I selected him because he is simply the hardest reviewer to please and does not shy away from pointing out flaws in the best game ever.
To use Yahtzee's words: "the strangest thing about Silent Hill 2 is, from a cold critical non gushy standpoint, the actual gameplay of it is kinda shitty",in other words not fun, sometimes even outright bad.   The reason you play Silent Hill 2 is for the story, but why should tell it in the game and not in a movie? Because Silent Hill 2 managed to tell a deep story without using words, it did it by solely through the Level Design, Enemies and the mechanics of the game. Everything is a symbol for the Protagonist's psyche, everything comes together to tell a story in a way that hardly works in any different medium.

There seems to be this doctrine in the industry that only "fun" games are good (see reference 2) and every game needs to be fun. This is like saying every movie needs to be entertaining. How would Schindler's List have looked like if the directors said: "We need to make it more entertaining". That luckily doesn't happen for movies, but it sadly does for games.  To end this section on a positive note, it seeems like times are changing. If you haven't already, look at ExtraCreditz's explanation on Spec ops: The Line and why it is so important.


Conclusion


Your job as a Game Designer is not to make an entertaining piece of software, your job is to create experiences. It can tell a story, leave a question inside the players head, provide a way to relax the mind, or scare the living hell out of people. If you have done a good job, the player dives right into a world, the gamer can walk in the shoes of somebody else.  Basically, a Game Designer is a scientific communicator, observing the players. You are constantly exploring, testing new methods and heuristics. No matter how much you think you know about your audience, no matter how experienced you think you are, you get surprises on a regular basis.  If you do your job right, you get your whole team going in the same direction, to make a greater game you ever could ever come up with alone.


Further Reading


  • Very important for any aspiring game designers is the concept of Mechanics Dynamics and Aestetics. Have a look!

References

  1. So you want to be a Game Designer
  2. Beyond fun

Article Update Log


26 Mar 2013: Article Created

Data Structures for Pre-College Programmers: Non-linear Data Structures

$
0
0

Introduction


Many of the beginners on the site are pre-college students.  Often beginners will learn by reading tutorials on the Internet, copying code from books, and trying out things that they find interesting.

This article is part of a series that focuses on giving pre-college developers the basics they need to understand data structures.

This article is about the non-sequential container types

Overview


These data structures are different from arrays and lists.  Arrays and lists are sequential containers.  Things have an order.  When you add a bunch of items in a specific order, they will remain in that order.

Non-linear data structures do not necessarily remain in the order you add them.  When you add or remove something it can cause other items to shuffle around.

Internally these are made from trees and heaps, which were covered in the previous article.

There are many variations of these data structures.  The most basic are the data dictionary and the ordered and unordered set.

The Data Dictionary


A regular dictionary contains a bunch of words (the key) and a definition (the value). Since the keys are in alphabetical order you can find any item very quickly.  Imagine if the dictionary were not sorted, looking up words would be extremely difficult.

There are two common ways to sort the items in the dictionary: a comparison, or a hash.

A traditional comparison ordering is usually the most intuitive.  This is like the real-world dictionary where everything is sorted alphabetically, or they could be sorted numerically.  When storing items this way you need to provide a comparison function.  

Usually this function defaults to the less than operator, such as a < b

The second way to sort items is with using a hash.  A hash is just a way to convert a block of data into a single number.  For example, the string ‘blue’ might have a hash of 0xa66b370d, and the string ‘red’ might have a hash of 0x3a72d292.  When a data dictionary uses a hash it is usually considered unsorted.  In reality it is still sorted, just sorted by hash rather than by something that is human usable.

A data dictionary works the same way.  There are slight performance differences between using a traditionally-sorted dictionary or a hash-sorted dictionary.  The differences are minor enough that you generally don't need care about them.

In C++ the family of containers are a map or a mutimap, or an unordered_map or unordered_multimap.  In Java the family is a HashMap, TreeMap, or LinkedHashMap.  In C# it is a Dictionary or SortedDictionary.  Each one has its own implementation details such as if they use a hash or a comparison and if they allow duplicates, but the overall concept is the same.  

Note that in each of the standard libraries they provide an ordered version (where you specify the comparison) and an unordered version (where they use a hash function).

Once you have added items to a data dictionary you can change the values but you cannot change the key.  Back to the real-world word dictionary analogy, you can modify the word’s definition without moving the word in the book; if you change the spelling of the word then you need to remove the first spelling and re-insert the word with the new spelling.  

The details for how they work is best left to a college level.  It is enough to know that they are very fast for looking up data, and they can be pretty slow when adding or deleting values.

The Ordered and Unordered Set


An ordered set is almost exactly the same as a dictionary.  Instead of having a key and a value, it only has a key.

Instead of a traditional dictionary with words and definitions, it is just the words.

These are useful when you want to store just store items directly without any additional data.

In C++ the family of structures are called a set or multiset, or an unordered_set or unordered_multiset.  In Java they are HashSet, TreeSet, or LinkedHashSet.  In C# they are the HashSet and SortedSet.

Just like above, there are ordered versions (where you specify the comparison) and an unordered version (where they use a hash function).  You also cannot modify a key when it has been added.  Instead you must remove the old object and insert a new object.

Often times they are implemented exactly the same as a data dictionary above, they simply store nothing for the value.

Since they are implemented the same way they have the same characteristics. They are very quick for searching and looking up values, but they are slow when it comes to adding and removing items.

Conclusion


The data dictionary, ordered set, and unordered set container classes are very useful for fast data lookup.  They are often implemented as trees or hash tables, which are very efficient for that.  Use them when you need to construct the data once and reference it many times.

They are not efficient at adding and removing items.  Change to the container can cause items to shift and shuffle internally.  If you need to follow that use pattern, a sorted linked list may be a better option.

NEXT: Choosing the Right Data Structure

Cross Platform Test Driven Development Environment Using CMake (Part 3)

$
0
0

Introduction

In the last part I showed how to start adding static libraries and setup to share information between the different portions of the CMake build system.  This part will cover the last of the build targets, shared libraries which are a little more difficult than the static libraries.  The difficulty is not on the CMake side but instead due to Windows being a bit of a pain in this area and requiring some additional work.  Once the shared libraries are complete though, the final portion of the environment will be added, the unit test library.

Unit tests are a great benefit to nearly any project.  A set of proper tests can help in many ways, the most obvious being to catch bugs early.  Unfortunately a number of the test libraries end up requiring a lot of boilerplate code and become a pain to write.  As such, when looking for a testing library the number one goal was to find something as minimal and non-intrusive as possible.  At the same time, a mocking system is also useful to have for larger and more complicated testing purposes.  The Google Mock library googlemock supplies both the mocking and unit test libraries and it is very simple to use.

Download Attached File  CMakeProject.zip   4.45K   8 downloads
and uncompress it somewhere if you don't have it from Part 2 of the series.

Parts 1 2 3

Shared Libraries

The final target type which we have not implemented as of yet is the shared library.  At the basic level it is no different than using a static library and in fact, on Linux and OsX it is identical except it is a shared library.  Unfortunately Windows is significantly more complicated due to the requirements of importing and exporting functions.  We'll start by ignoring the problems on Windows for now and getting the basics functioning on Linux and OsX.

The first thing to do is add a new set of directories for the shared library:

Create the following directories under CMakeProject/libraries:
World
    Include
    Source

Now edit the CMakeProject/libraries/CMakeList.txt as follows:
ADD_SUBDIRECTORY( libraries/Hello )
ADD_SUBDIRECTORY( libraries/World )

Finally add the new files:

CMakeProject/libraries/World/CMakeLists.txt:
SET( INCLUDE_DIRS
	${CMAKE_CURRENT_LIST_DIR}/Include
)
INCLUDE_DIRECTORIES( ${INCLUDE_DIRS} )

SET( INCLUDE_FILES
	Include/World.hpp
)

SET( SOURCE_FILES
	Source/World.cpp
)

ADD_LIBRARY( World
	SHARED
	${INCLUDE_FILES}
	${SOURCE_FILES}
)

# Export the include directory.
SET( WORLD_INCLUDE_DIRS ${INCLUDE_DIRS} PARENT_SCOPE )

CMakeProject/libraries/World/Include/World.hpp:
#pragma once

const char* const WorldString();

CMakeProject/libraries/World/Source/World.cpp:
#include <World.hpp>

const char* const WorldString()
{
	return "World!";
}

Regenerate the build and you now have a shared library.  If you are using Linux or OsX, your library is complete and can be used by simply adding it to a target the same way the static library was added.  Let's make a couple minor modifications in order to use this library and link against it.

CMakeProject/libraries/Hello/Source/Hello.cpp:
#include <Hello.hpp>

const char* const HelloString()
{
	return "Hello";
}

CMakeProject/tests/Hello2/main.cpp:
/* Hello World program */
#include <iostream>
#include <functional>
#include <Hello.hpp>
#include <World.hpp>


int main( int argc, char** argv )
{
	std::cout << HelloString() << " " << WorldString();
	return 0;
}

CMakeProject/tests/CMakeLists.txt:
CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 )

INCLUDE_DIRECTORIES( ${HELLO_INCLUDE_DIRS} ${WORLD_INCLUDE_DIRS} )

PROJECT( HelloWorld )
ADD_EXECUTABLE( Hello2 main.cpp )
TARGET_LINK_LIBRARIES( Hello2 Hello World )

With the given changes, Linux and OsX can build and run the modified 'Hello2' project and the string for "Hello" comes from a static library function and the "World!" comes from a shared library function.  Unfortunately Windows is not so lucky and will fail to link.

Attached File  CMakeProjectWindowsBroken.zip   5.8K   8 downloads


The Windows DLL

As with the OsX specific fix, using shared libraries with Windows is something of a black art.  I don't intend to explain all the details, that would take another article.  I will simply explain the basics of the fix and make the code work on all three platforms again.

The basic problem with using shared libraries on Windows requires a little description.  First off they are called dynamic link libraries (aka DLL) on windows.  Second they are split into two pieces, the actual DLL portion which is the shared library where the code lives and a link library which is like a static library.  Confusingly the link library usually has the file extention 'lib' just like an actual static library so don't get them confused.  At this time, we are not telling the compiler to generate this intermediate file.

Note:  
To add more confusion, the lib "is" actually just a static library.  It simply contains meta data to tell Windows the DLL to load and stub functions which are fixed up after load.  Now forget this and continue on with the simple description.



Generating the intermediate file is simple enough but you have to deal with it in a cross platform nature or you break Linux and OsX builds.  Exporting the library symbol and making the link library is as simple as changing the function declaration to be the following:

__declspec( dllexport ) const char* const WorldString();

If you go ahead and make this change, the project compiles on Windows, but it will not run because it can't find the DLL.  This problem is an annoyance with how VC tends to layout the projects when divided up in the manner suggested in this series of articles.  Fixing this digs into the darker recesses of CMake properties which, for the moment we will avoid by cheating.  For the time being, just copy the dll manually:

Copy from CMakeProject/build/vc11/libraries/World/Debug/World.dll
to
CMakeProject/build/vc11/tests/Hello2/Debug/World.dll

At this point Windows is functioning again, though with obvious cheats and actually a glaring error, though the error doesn't cause a problem at the moment.  What's the error?  Well, to be proper you are supposed to use '__declspec( dllexport )' only in the code building the DLL and then '__declspec( dllimport )' in code which uses the library.  While it works as it is, it is best to follow the rules as closely as possible so as not to get strange behaviors/errors at a later time.

So, we'll extend the code to correct the issue of import versus export:
#ifdef BUILDING_WORLD
#	define WORLD_EXPORT		__declspec( dllexport )
#else
#	define WORLD_EXPORT		__declspec( dllimport )
#endif

WORLD_EXPORT const char* const WorldString();

Rebuild and now you get a warning: "warning C4273: 'WorldString' : inconsistent dll linkage"

The reason is, we have not defined 'BUILDING_WORLD'.  Since we want to define this only for the 'World' library, we edit the CMakeProject/libraries/World/CMakeLists.txt as follows:

SET( INCLUDE_DIRS
	${CMAKE_CURRENT_LIST_DIR}/Include
)
INCLUDE_DIRECTORIES( ${INCLUDE_DIRS} )

SET( INCLUDE_FILES
	Include/World.hpp
)

SET( SOURCE_FILES
	Source/World.cpp
)

ADD_DEFINITIONS( -DBUILDING_WORLD )

ADD_LIBRARY( World
	SHARED
	${INCLUDE_FILES}
	${SOURCE_FILES}
)

# Export the include directory.
SET( WORLD_INCLUDE_DIRS ${INCLUDE_DIRS} PARENT_SCOPE )

Notice the new CMake command: 'ADD_DEFINITIONS'.  As the name states, we are adding a definition to the macro preprocessor named 'BUILDING_WORLD' to the 'Hello2' target.

Windows is happy, we are following the rules and other than having to manually copy the DLL for the moment, it functions.  There is one last issue, the macro will be applied to all platforms, something we don't want.  So back in CMakeProject/libraries/World/Include/World.hpp, make the following change:

#ifdef _WINDOWS
#	ifdef BUILDING_WORLD
#		define WORLD_EXPORT		__declspec( dllexport )
#	else
#		define WORLD_EXPORT		__declspec( dllimport )
#	endif
#else
#	define WORLD_EXPORT
#endif

WORLD_EXPORT const char* const WorldString();

CMake inserts per OS specific definitions based on the platform being targetted.  In this case, as with using Visual Studio without CMake, '_WINDOWS' is defined by default.  So, we can rely on this and now the code is safely cross platform and ready for commit.

Changing Output Directories

In order to finish correcting the Windows build we have to use a bit of CMake voodoo which is not often documented particularly well.  Changing output directories.  What we want is to output the executables and the libraries (shared and static) to a single output directory while leaving intermediate files wherever CMake/VC wants to store them.  This is not required for OsX and Linux as the output generators there follow a more simplified directory structure.  We also want to do this only for Visual Studio and not change the default behavior of nmake, CodeBlocks and other generators.

Modify the CMakeProject/CMakeLists.txt to be the following:
CMAKE_MINIMUM_REQUIRED( VERSION 2.6.4 )

IF( APPLE )
	SET( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -stdlib=libc++" )
	SET( CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -stdlib=libc++" )
	SET( CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -stdlib=libc++" )
	SET( CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -stdlib=libc++" )
ENDIF( APPLE )

PROJECT( CMakeProject )

IF( MSVC )
	SET( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries )
	SET( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries )
	SET( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries )
ENDIF( MSVC )

INCLUDE( libraries/CMakeLists.txt )
ADD_SUBDIRECTORY( tests )

Note that the detection for Visual Studio is performed after the 'PROJECT' command.  There is a reason for this.  CMake does not initialize many variables until after the 'PROJECT' command is issued.  Among the variables not initialized is of course 'MSVC'.  The reason for the delayed definition is that CMake reads the locally catched data at the point where it see's the 'PROJECT' command.  So, while knowing the platform being run on and being able to modify the compile and linker flags can be done before the 'PROJECT' command, the specifics such as the generator in use are not known until the cache data is processed.

The next item to note is: why three directories?  CMake divides the directories into three pieces to match the three target types, runtime for the executables, archive for static libraries and library for shared/dynamic libraries.  While you could just set the executable and shared library paths, I include the static libraries in case something external to this build system wanted to link against the libraries.  It is not required but makes things easier in advanced usages.

Finally, what is the 'PROJECT_BINARY_DIR' variable being used?  Before we define any of the targets, this variable simply points to the directory CMake was launched from as it's out of source build location.  In my case on Windows, I'm using '<root>/CMakeProject/build/Vc11' and as such that is what 'PROJECT_BINARY_DIR' is initialized with.  There are many other variables, some which will also point to this location and could have been used.  I just like this one because it is related to what I'm trying to accomplish, which is put all the final compiled binaries in one place.

Regenerate the project, rebuild all and you will now have a single directory with all the binary outputs within it.  You can run the examples using Visual Studio and it will no longer complain that it can not find the DLL to load.

Note:  
On some installations of Visual Studio when used with CMake, Visual Studio will complain that it can't find a file to debug.  My Win7 desktop has this problem where my Win7 laptop does not.  The easy fix, if you run into this, is to simply switch the dropdown Debug Type from 'Auto' to 'Mixed'.  VC now has no problems.  I do not know the source of this issue or I would fix it.



Attached File  CMakeProjectFullFix.zip   6.08K   6 downloads


Unit Testing

With a title that states "Test Driven Development" in it, you would probably think that adding unit tests would have been done a bit earlier.  The funny thing is that you have had a unit testing framework the entire time, it is built right into CMake itself called CTest.  The downside is that I don't much like the way the built in functionality works and incorporating an external library is a good learning experience.  So, we will start using googlemock in a little bit.

During the course of writing this series I initially thought that I would stick to an 'all lower case' naming convention.  In the process of writing, I mostly added code quickly and as such fell back on my habitual way of doing things without paying much attention.  Other than to say I'm going to use camel case for the names, we'll skip the reasons and simply start with a fresh empty environment based on all the work we have done and also adding the final target divisions, so download the following (Attached File  CMakeEnvironment.zip   69.93K   7 downloads
) and we'll start adding the unit test library.

The New Environment

There is not much changed in the new environment other than applying the mentioned capitalizations and adding a couple new subdirectories along with the removal of 'tests'.  The directories are intended as follows:

  • Build: A placeholder for where you can use CMake to store its cache files and such.  I tend to use subdirectories such as: Vc11, Xcode, Makefiles, etc.
  • External: The location we will be storing external libraries such as googlemock.
  • Libraries: Static and shared libraries used by the projects.
  • Applications: Your game, potentially another game and anything which is not a tool but uses the libraries.
  • Tools: Obviously things which are used in the creation of the game.  Exporters, converters, big level builders, etc.

Go Get GoogleMock

Download the gmock-1.6.0.zip file from googlemock and decompress it into the 'CMakeEnvironment/External' directory.  You should end up with a new folder: 'CMakeEnvironment/External/gmock-1.6.0' which contains the library source.  If you go looking around in the folder you will notice that it uses autoconf and m4 scripting to build on Linux/OsX and supplies a solution and project file for Visual Studio.  This is normally fine for simple things but I want it integrated with the CMake build environment more tightly such that if I change global compiler flags it will rebuild along with the other sections of the project.

As you will see, all the little steps we've gone through in setting up the environment with CMake in a clean manner will start to pay off as we integrate the library. Thankfully, as with many other Google libraries, the source contains a 'fused-src' directory which means we can add two headers and a source file to our project and almost be done with it.  I say almost, since I want to make sure we integrate the library within the environment as cleanly as possible and make no modifications to the unzipped directory.  Start by adding the following (and creating the new directories):

CMakeEnvironment/External/CMake/GMock/CMakeLists.txt:
# Use a variable to point to the root of googlemock within
# the External directory.  This makes it easier to update
# to new releases as desired.
SET( GOOGLEMOCK_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../gmock-1.6.0" )

# Make the file lists.
SET( INCLUDE_FILES
	${GOOGLEMOCK_ROOT}/fused-src/gtest/gtest.h
    ${GOOGLEMOCK_ROOT}/fused-src/gmock/gmock.h
)

SET( SOURCE_FILES
    ${GOOGLEMOCK_ROOT}/fused-src/gmock-gtest-all.cc
)

# Setup some build definitions for VC2012.
IF( MSVC )
	ADD_DEFINITIONS( -D_VARIADIC_MAX=10 )
ENDIF( MSVC )

# Add as a static library target.
ADD_LIBRARY( GMock
	STATIC
	${INCLUDE_FILES}
	${SOURCE_FILES}
)

This will allow GMock and GTest to compile on Windows and Linux.  Unfortunately nothing ever seems to work without problems.  The library refuses to compile on OsX due to Clang being detected as GCC and making a bad assumption about the availability of tr1 files.  After arguing with it and even hacking the source I decided that for the time being, the easiest and most time effective method was to cheat.  The benefit of cheating is under rated when you need to get things done and don't want to hack on external code.  So, what exactly is this cheat?  We'll add a directory for tr1 and a file for tuple, the file will simply alias the to C++11 tuple in order to meet the requirements.  (I won't detail the changes, check out the various CMakeLists.txt if you are curious.)

Additionally, we have a link problem with the Linux environments to fix.  If you tried to link against the GMock library and build you will get link errors, given the output it becomes pretty apparent that we've missed the threading libraries.  In order to fix this, we get to learn a new command in CMake: FIND_PACKAGE.  Anytime you need a set of specific includes and/or libraries to link against, there is usually a module which CMake supplies (or the community supplies) for the item.  In this case we need to find the 'Threads' package.  Once we do this, we add a new target link library to our binaries: '${CMAKE_THREAD_LIBS_INIT}'.  This will take care of the linking on Linux and also because it is a variable, it will be empty on other platforms which don't need explicit linkage to an additional library.

As with static libraries in general, we know it is easy to link against the library but a bit more of a challenge to get the include paths setup.  Additionally, the variadic work around for VC needs to be pushed out as a global item for all projects, otherwise they will fail to compile.  This is all stuff we've dealt with before so it becomes easy.  In the root CMake file move the 'ADD_DEFINITIONS' command to be just under the output path changes we made and also insert the FIND_PACKAGE command for all builds:

CMakeEnvironment/CMakeLists.txt:
# ###############################################
# Make VC happy and group all the binary outputs,
# also make sure GMock headers will compile in
# all targets.
IF( MSVC )
	SET( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries )
	SET( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries )
	SET( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/Binaries )

	ADD_DEFINITIONS( -D_VARIADIC_MAX=10 )
ENDIF( MSVC )


# ###############################################
# Find the threading package for this machine.
FIND_PACKAGE( Threads )

Remove the definition line from the GMock/CMakeLists.txt and add the following to the bottom of the file:
SET( GMOCK_INCLUDE_DIRS ${GOOGLEMOCK_ROOT}/fused-src PARENT_SCOPE )

Controlling Tests

The last thing to be done is to control if unit tests are compiled and built.  When you start working this is not a big deal of course as you will likely only have a couple libraries and tests.  After a while though, you may end up with more little "test" targets than actual libraries and applications.  So, it is a good idea to go ahead and add the ability to disable tests from day one.  Add the following item:

CMakeEnvironment/CMakeLists.txt:
# ###############################################
# Allow unit tests to be disabled via command
# line or the CMake GUI.
OPTION( BUILD_UNIT_TESTS "Build unit tests." ON )

Add this just under the 'PROJECT' command and it will show up in the CMake GUI as something you can turn on and off.

Putting The Results To Use

Two and a half articles later, we are finally ready to put our work to good use.  I'm going to start by writing a 3D vector class since it is a common item and easily unit tested.  The first thing to do is of course get the completed environment: Attached File  CMakeEnvironmentComplete.zip   1.93MB   7 downloads
.  This file includes the googlemock library so it's quite a bit larger than the prior items.

The Math Library

I'm going to keep this very simple for the purposes of this article.  I will not be implementing the actual class, just enough to show a unit test in action.  Future articles will likely build off this work but this is going to close out the CMake work for the time being so we want to keep things simple.  Let's start by adding the directories for the new 'Math' library:

CMakeEnvironment
	Libraries
		Math
			Include
				Math
			Source
			Tests

Ok, so the first question is likely to be why did I duplicate the directory 'Math' under the 'Include' directory?  This is simply a polution prevention item.  Let's say you have a custom 'Collections' library and within that there is a 'Vector.hpp' file and of course the math library could have a 'Vector.hpp' file.  If you include without the prefix of 'Collections' or 'Math', which file are you including?  With the way we will setup the libraries, this problem is solved by forcing the users of the libraries to qualify the includes as follows:

#include <Math/Vector.hpp>
#include <Collections/Vector.hpp>

This is another one of the personal preference items but I prefer avoiding problems from day one and not simply assuming they won't happen.  If you don't like this, once we get done feel free to remove the nested directory. But be warned that in future articles you'll see some good reasons to use this pattern which can greatly simplify normally difficult processes.

Let's fill in the hierarchy with files now, add the following:

CMakeEnvironment/Libraries/Math/CMakeLists.txt:
SET( INCLUDE_DIRS
	${CMAKE_CURRENT_LIST_DIR}/Include
)
INCLUDE_DIRECTORIES( ${INCLUDE_DIRS} )

SET( INCLUDE_FILES
	Include/Math/Math.hpp
	Include/Math/Vector3.hpp
)

SET( SOURCE_FILES
	Source/Vector3.cpp
)

ADD_DEFINITIONS( -DBUILDING_WORLD )

ADD_LIBRARY( Math
	STATIC
	${INCLUDE_FILES}
	${SOURCE_FILES}
)

# Export the include directory.
SET( MATH_INCLUDE_DIRS ${INCLUDE_DIRS} PARENT_SCOPE )

Add empty files for:
Include/Math/Math.hpp
Include/Math/Vector3.hpp
Source/Vector3.cpp
Tests/Main.cpp

Regenerate the environment and you should have your new Math library.

The First Unit Test

The first thing we want to do is add a unit test holder before we add any code to the library.  What we need is a simple executable which can include the files from the library.  Since this is part of the math library, we can simply add the test within 'CMakeEnvironment/Libraries/Math/CMakeLists.txt'.  Additionally, we want the test to honor the flag we setup such that the test is not included when tests are disabled.  Add the following to the end of the Math libraries CMake file:

# Make a unit test holder for the Math library.
IF( BUILD_UNIT_TESTS )
	# Add the gmock include directories.
	INCLUDE_DIRECTORIES( ${GMOCK_INCLUDE_DIRS} )

	ADD_EXECUTABLE( _TestMath
		Tests/Main.cpp
	)
	TARGET_LINK_LIBRARIES( _TestMath
		Math
		GMock
		${CMAKE_THREAD_LIBS_INIT}
	)

	ADD_TEST( NAME
		_TestMath
		COMMAND
		_TestMath
	)
ENDIF( BUILD_UNIT_TESTS )

Regenerate and you get a new target '_TestMath'.  In the CMake GUI if you set 'BUILD_UNIT_TESTS' to 'FALSE' and regenerate, the new target goes away as we desired.  But, there is actually one more thing we want to do to make this even better in the future.  In the root CMake file with the 'OPTION' command defining the 'BUILD_UNIT_TESTS' variable, add the following bit right afterward:

# ###############################################
# Enable the CMake built in CTest system if unit
# tests are enabled.
IF( BUILD_UNIT_TESTS )
	ENABLE_TESTING()
ENDIF( BUILD_UNIT_TESTS )

Make sure to set 'BUILD_UNIT_TESTS' back to 'TRUE' and regenerate.  A new target shows up in the build: "RUN_TESTS".  This is a nice little target when you have many more tests then we will have here.  Basically if you attempt to build this target is runs all the executables you add with 'ADD_TEST'.  It is also great for automated build/continuous integration environments since running the target is easy compared to finding all the individual tests.

Now, lets add the actual unit test code:
CMakeEnvironment/Libraries/Math/Tests/Main.cpp
#include <gmock/gmock.h>

int main( int argc, char** argv )
{
	::testing::InitGoogleTest( &argc, argv );
	return RUN_ALL_TESTS();
}

This is a do nothing bit of code right now until we add some code to the Math library and of course add some tests.  So, let's fill in the vector class real quick:

CMakeEnvironment/Libraries/Math/Include/Math/Vector3.hpp:
#pragma once

#include <Math/Math.hpp>


namespace Math
{
	class Vector3f
	{
	public:
		Vector3f()									{}
		Vector3f( float x, float y, float z );

        float			X() const					{return mX;}
        float			Y() const					{return mY;}
        float			Z() const					{return mZ;}
        
	private:
		float			mX;
		float			mY;
		float			mZ;
	};
}

CMakeEnvironment/Libraries/Math/Source/Vector3.cpp:
#include <Math/Vector3.hpp>

using namespace Math;

Vector3f::Vector3f( float x, float y, float z )
:	mX( x )
,	mY( y )
,	mZ( z )
{
}

Note:  
Yes, the default constructor does not initialize to zero's.  That is a topic for another article.



Rebuild and the library should build, the test case should build and even run with the following output:
[==========] Running 0 tests from 0 test cases.
[==========] 0 tests from 0 test cases ran. (1 ms total)
[  PASSED  ] 0 tests.

So it is time to add our first tests.  Add the following files:

CMakeEnvironment/Libraries/Math/Tests/TestAll.hpp:
#include <Math/Vector3.hpp>
    
#include "TestConstruction.hpp"

CMakeEnvironment/Libraries/Math/Tests/TestConstruction.hpp:
TEST( Math, Vector3f )
{
    Math::Vector3f	test0( 0.0f, 0.0f, 0.0f );
    
    EXPECT_EQ( 0.0f, test0.X() );
    EXPECT_EQ( 0.0f, test0.Y() );
    EXPECT_EQ( 0.0f, test0.Z() );

    Math::Vector3f  test1x( 1.0f, 0.0f, 0.0f );

    EXPECT_EQ( 1.0f, test0.X() );
    EXPECT_EQ( 0.0f, test0.Y() );
    EXPECT_EQ( 0.0f, test0.Z() );

    Math::Vector3f  test1y( 0.0f, 1.0f, 0.0f );

    EXPECT_EQ( 0.0f, test0.X() );
    EXPECT_EQ( 1.0f, test0.Y() );
    EXPECT_EQ( 0.0f, test0.Z() );

    Math::Vector3f  test1z( 0.0f, 0.0f, 1.0f );

    EXPECT_EQ( 0.0f, test0.X() );
    EXPECT_EQ( 0.0f, test0.Y() );
    EXPECT_EQ( 1.0f, test0.Z() );
}

Modify CMakeEnvironment/Libraries/Math/CMakeLists.txt by adding the test headers:
	ADD_EXECUTABLE( _TestMath
		Tests/Main.cpp
		Tests/TestAll.hpp
		Tests/TestConstruction.hpp
	)

And include the 'TestAll.hpp' from the file CMakeEnvironment/Libraries/Math/Tests/Main.cpp:
#include <gmock/gmock.h>
#include "TestAll.hpp"


int main( int argc, char** argv )
{
	::testing::InitGoogleTest( &argc, argv );
	return RUN_ALL_TESTS();
}

Regenerate, build and run.  The test should output the following:
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from Math
[ RUN      ] Math.Vector3f
[       OK ] Math.Vector3f (0 ms)
[----------] 1 test from Math (1 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (5 ms total)
[  PASSED  ] 1 test.

Congratulations, you have a unit test for your new Vector3 class.

The completed environment and example unit test can be downloaded here Attached File  CMakeEnvironmentWithTest.zip   1.93MB   10 downloads
.  Please provide feedback on any build problems you might have and I'll attempt to get things fixed.

Conclusion

In this article we covered dealing with OS specific difficulties involving Windows and a couple more OsX issues.  It has been a long haul to get to this point dealing with nitpicky items and a lot of explanation.  The final result is a fairly easy to use and maintain environment which you can use to build unit tests and apply test driven development features to your coding.  In a future article I intend to expand on the Math library and show some of the big utilities of using an environment such as this day to day.  For now, my fingers are tired and my own code calls to me.

Developing Your Game Concept By Making A Design Document

$
0
0
This article is intended for beginning and intermediate game designers.  It will walk you through the process of creating a design document, including making a features list, identifying your genre(s), brainstorming each feature, doing research, and using your design document in the game development process.  This assumes the reader wants to make a pet-themed game and all the examples are pet-related, but it should be easy for the reader to apply the instructions to their preferred game theme.  This article was originally posted at the Virtual Pet List forums, and also in my developer journal Designing: The Game And Its Content as Guide To Designing A Pet Game, Parts 0-15.  I was asked to reformat it as an article, so here it is.

Original Author's Note


This document, created by Mare Kuntz (sunandshadow) in 2012, is a free, public guide to making a design document for a pet-themed game, including example pet game design document sections intended for reuse in readers' own game design documents. A design document is not the only way to develop a game; some people favor the alternate method called agile development. But, this document is aimed mainly at people who have little design and development experience, and IMO agile development works better for more experienced people, or for people who are more interested in learning than in making a specific game. I am providing this document as a community service and releasing it to the public domain. It is freely usable by anyone for both noncommercial and commercial purposes. For example, an indie game developer could use this as the basis for a design document for their own pet game. Or anyone doing a school project or teaching a class where they needed an example design document could use this. I would enjoy hearing from people who find this document useful (sunandshadow@excite.com), but you are not required to notify me if you make use of it. I am available as a consultant for game-design-related projects, but I do charge for that kind of service.

Table Of Contents


0. Introduction: What is a game design document, why should you make one, and how do you use this guide to make one?
1. Genres: What kind of pet games are there, how are they different from each other?
2. Theme: Story, Setting, Playable Character(s), And How These Should Interrelate With Gameplay.
3. Distribution and Monetization: Getting the game to the player and the player's money to you.
4. Player Registration and Account Creation, Data Storage Within The Game
5. Avatar Creation: Human vs. Pet, Clothing Systems, The Avatar's Role(s) Within The Game, Avatar Equipment Slots, Stats, and Abilities.
6. Inventory Systems: Types Of Items And How Each Type Functions Within The Game, How The User Interacts With Storage, Storage Limitations And Expansion As Gameplay.
7. Gathering and Crafting: Climbing the Tech Tree, Recipes, Skills, Building Up Infrastructure, and Crafting Gameplay.
8. Trading, Shops and the Marketplace
9. Forums, Messaging, Chatting
10. Pets In More Detail: Functionality Within The Game, Capturing, Breeding and Genetic Systems
11. Tutorials, Quests, Reputation, and Levels
12. Combat
13. Minigames, Puzzles, And Other Combat Alternatives
14. GUIs and Controls, Game Modes and Context-Sensitive Behavior
X. Finale: An overview of the game development process and how the design document is used during this process.


0. Introduction: Game Design Document – What? Why? How?


A game design document is a written description of proposed game. In this guide I am assuming you, the reader, want to create a game. This makes you the game designer. (Or a co-designer if you want to team up with someone who will also contribute ideas.) Design is just another word for plan: a game designer plans out a game.  In order to create a game you must decide what kind of game you want to create. I am also assuming you are going to outsource some or all of the programming and art of your game to other people. The main purpose of a game design document is to paint a clear picture of a proposed game. The document describes what game parts (otherwise known as features) will be in the game, and how they will fit together. The process of creating a document helps a designer clarify their creative vision for a game and make sure there aren't any inconsistent or missing pieces. The finished document is a record of all the design decisions that have been made. It can be given to others, in whole or in part, as a quick clear way of communicating the designer's vision. It can also be used as a checklist to track which pieces of code, art, and other assets have been created, until everything is checked off and the game is done!

What? So, what is actually in a game design document? A game design document usually includes:

1. A statement of the designer (you) or design team's purpose that they want the game to accomplish. You can write this as a serious statement of philosophy if you really want to, but it doesn't have to be anything complicated; instead you can just say "This game will be awesomely fun to play because..." Optionally you can mention a favorite game that you want yours to be similar to, or what genre it will be, or what type of player will really like it. Typically this part will be 1-3 paragraphs long.


2. A list of features you want the game to have (this does double duty as your table of contents).


3. A description of each feature (these are the sections listed in the table of contents, the "meat" of your design document).


4. Appendixes listing all the characters, location, items, puzzles, monsters, etc. needed to complete the game. (These lists are often added later, after the main design document is done. So really there are only 3 main parts – nice and simple. But, if, in the middle of making your design document, you happen to decide something like: "There are going to be six classes of pets in my game: Sun, Moon, Star, Shadow, Plaid, and Rutabaga." then an appendix is where you file that kind of information so you know where to find it later.)


Why? What good is a game design document? How do you use it to help develop your game? As soon as you write a feature description it becomes useful because you can refer back to it when designing a related feature, so you don't forget what you decided. An in-progress design document is like a journal, but more organized because you will be showing it to other people as well as referring back to it yourself. If you are in a team, the design document serves as a record of what has been firmly decided and should not be squabbled over or changed without an important reason. The design document can also be a fast way to orient a new team member to what is going on.

Most importantly, when you have finished writing your design document the feature descriptions you have written are used as a guideline in the development process when programming a feature, creating graphics or sound files for that feature, and playtesting that feature. How? When hiring a programmer or an artist the design document is both a checklist of all the tasks that need to be done to make the game, as well as a source of bite-size "assignments" that your employee(s) can do one at a time. You can do this by copying and pasting from your design document in to an email or forum post to a team member or employee, or by simply showing them your whole design document. The same applies to tasks you are going to do yourself – if you get around to creating something a month after you initially designed it, re-reading what you wrote reminds you exactly what you decided to do and why.

A game design document is also helpful as an organizational tool for your whole development process; it can be used as a plan you can then follow step-by-step to develop your game. You can even check off within the game design document which tasks have already been completed by you and others. As these parts of the game are created, they form the alpha version of your game! And finally, material from a design document's statement of purpose and story section are often reused when creating promotional materials or a webpage for a game project or completed game, while material from the appendixes is often reused in item flavor text, NPC dialogue, and other places throughout the game.

How? Okay, so how do you make a game design document? You follow this guide! I will describe the various genres of pet game so you can identify which one you want to make. I will describe the various features commonly found in each genre so you will have a starting list of features your game should have. Because this document is public domain (copyright-free) you are welcome to copy and paste as much of it as you can use directly into your own design document. You can also modify it however you want if you want features different than described here. When there are two or three alternative versions of a feature I will try to describe the differences between them and which is better in what context, so you can pick which version you want to use, or you can use this as background knowledge when designing your own version of a feature. You will still need to create some of the material yourself, such as your statement of purpose, your story, names of characters and places, and all the parts where your own creativity is the essential ingredient. But following this guide should be much faster and easier than creating your own design document from scratch, and hopefully the list of example features I'll describe here will make the guide flexible enough to help people design a wide variety of games.

1. Pet Game Genres: What Is Your Game's Primary Activity And Overall Goal?


The first thing to realize is that there are different genres (kinds) of pet games, which have different feature sets. It's very helpful to any game designer to have played a variety of games so they remember experiencing a variety of features and can pick from that “mental toolbox” which features they want their own game to have. If you have only ever played one kind of pet game, you would have difficulty trying to make anything other than that same type of pet game. If you want to make that kind of game, that's fine, though background knowledge of a variety of games would help you avoid designing a game that's just a rehash of something that already exists. So, I encourage all designers to play a variety of games, the same way writers should read a variety of fiction and artists should look at a variety of art. But it's ok if you already have a specific type of pet game in mind because you want to make a game similar to your favorite, or combining features of two or three of your favorites. It's also ok if you just know that you want to make a pet game, but not know exactly what kind yet. Figuring out which kind you want your game to be is the first step in creating your own game design document!

There are different kinds of genres. “Pet Game” is itself a genre, specifically a theme or motif genre. Fantasy, science-fiction, and sports are also theme genres. There are art genres, like 2D vs. 3D and anime style vs. western comic style. There are story genres, like horror games and romance games. Then there are gameplay genres, which is what people usually mean when they talk about genre: RPGs (role playing games), sims (simulations), MMOs (massively multiplayer online games), and others less commonly seen in the realm of pet games, such as adventure games, FPSes (first person shooters), and RTSes (real-time strategy games). The overall point of this section is for you to start writing your design document by listing what genres of different kinds apply to your game. The idea is that a person can pick up your game design document and in the first few sentences you will give them a concise and clear description of your proposed game.

Specifically you are going to fill in the blanks in this sentence: “[NameOfGame] will be a [2D or 3D or ?D] [optionally name the art style, e.g. anime] [singleplayer or multiplayer] [VPS/RPG/SIM/etc.] game where the player has [a small number or a large number] of [type of pet if you know it already] which which they do [combat or other main activity of the game].” Sorry if that looks confusing. Once you plug all the information in it will look like something sane, e.g. “Sunandshadow's Fish Game will be a 2D realistic-art singleplayer RPG/sim where the player has many fish which they use to battle and capture more fish, breed in a fishtank, and craft into fishscale armor, weapons, and potions.” Or, “Sunandshadow's Dragonrider Game will be a 2D anime singleplayer interactive story game where the player has 6 dragons they can attempt to befriend and partner with in dragonrider training class until one of the dragons agrees to permanently bond with the player and accept him/her as their rider.” Or “Sunandshadow's Virtual Pet Site will be a 3D Spore-style multiplayer VPS where the player starts with one pet of the most basic type and, using it to explore and breed, collects all possible pet variants.”

The Name Of The Game

You might happen to have a name in mind already; if so, cool. If you don't have an idea for your game's name yet, that's also fine. This section is not about brainstorming an awesome title which elegantly expresses the project's identity and grabs the attention of the project's target audience. Actually, names are often changed as a creative project develops, and are often one of the last things to be decided. It's almost impossible to think of a great name at the beginning, when you don't fully know yet what the project will be. No, what we want here is a functional working title. Something simple and handy you can use to name the file, discuss the project with others, and later use a search and replace to automatically put the game's real name in all the right places. I recommend something like Jane's Pet Game or Dragon Breeder Game or Pokemon Clone. So just pick something and fill in that first blank. Also, create a new document, name it Jane's Pet Game Design Document or whatever, then copy and paste that bolded sentence into it so you can fill in the blanks there. Unless you prefer to use a pen and paper, that's fine too.

What Are You Doing With Those Pets?

Pet games (or pet monster games, monster capturing games, monster breeding games, livestock ranching games, horse riding games, etc.) are characterized by the player's enthusiasm for some kind of creature. They don't have to be literally animals, but instead anything that can be presented as animal-like, including plants, robots, alien creatures, magical beings, or virtual creatures. Pet games could be divided into those where the player interacts a lot with one or a small number of creatures vs. where the player collects or breeds a large number of creatures, selling unneeded ones, or even slaughtering livestock to harvest crafting resources. Which of those are you more interested in creating? Approaching the question from a different angle, pet games could be divided into games where the pets' main role in the game is combat-related vs. those where it is something other than combat. Does one of these two types sound more like what you want to make? When you combine these you get four of the most common kinds of pet games:

1. A game where you own one or a few companion pets (or you are an animal or small group of animals) and you fight alongside or through them.
2. A game where you fight to build up a collection of pets which become your army or workforce (units in your combat squad, cards in a deck, or part of your home base producing stuff for you).
3. A game where you care for one or a few pets and compete with them.
4. A game where you have a farm or ranch where you raise many pets to sell, compete with, or build up to a complete collection.


Is one of those what you want to make? If not, here are a few less common options, and of course it is possible to mix and match:

5. An interactive story game where you talk to creature-characters, trying to befriend them or solve problems related to them.
6. A game where each pet is a challenge because they need to be healed or tamed before they can be passed on to a permanent owner.
7. A babysitting game where you must take care of the needs of several pets as fast as you can to keep them happy.
8. A world simulation where you experimentally create creatures and see how they survive in the wild.
9. Add your own!


2D vs. 3D

Art type is a challenging topic in game development because it is 1/3 personal preference, 1/3 dependent on what resources you have available because artists and game engines alike tend to only be good with one kind of art of the other, and 1/3 functionality because while some gameplay works fine with both approaches, a few kinds of gameplay work much better with one or the other. Since those thirds are like apples, oranges, and, plums, it's quite difficult to balance them against each other if they conflict. All you can do is try to figure out if some factors are more relevant than others. For example if you, the designer, really hate one of the two styles and don't want to put time and effort into developing a game that will have that type of art, that probably overrules any other issues. Or if you intend to be the primary artist and are only good at one of the two types, or you intend to be the primary programmer and already own a license for a game engine that is focused on one of the two types, that's also a strong argument for which you should go with. Or, if you have a strong idea of some gameplay you want your game to have which is incompatible with one of the two types, that's another strong argument. It's convenient to the development process to decide early which type of art a game will use, but if you really are stuck between the two options it can be postponed until more data is available to reevaluate the choice. There are also a few less common options like 2 ½ D that you might want to research if the two straightforward options aren't working for you. Fortunately the question of art style (as in things like realism, anime, western comic, gothic...) is a simpler issue because it has basically no functional difference, just personal taste and what your available artists have experience with.

Singleplayer vs. Multiplayer

Two main categories of computer games are online multiplayer games, and offline singleplayer games. The big difference between these two types is that in singleplayer games the game's primary activity is always something the player does against computer-generated opponents, whether these are monsters or something more abstract like a time limit. In multiplayer games, on the other hand, competition against other players or cooperation with other players is a significant part of the game (even though the majority of the player's time within the game may still be spent of single-player activities). A few games have a limited online component, such as phone and Facebook apps where the only things the player can do online are buy cash shop items and send presents to neighbors; these have mainly singleplayer gameplay so I will include them in the singleplayer category. Do you know whether you want to make a multiplayer or singleplayer game?

Multiplayer Game Genres:


Virtual Pet Sites – Pet Sites are characterized by having their primary multiplayer activities include forum posting and trading items or pets with other players. Some VPS games include a breeding system, and if they do it is commonly possible to use other players' pets as breeding stock. Some games encourage the player to collect pets or other collectibles. Some VPS games include a minigame arcade; if they do this is typically the main source of player income within the game, and players may compete for high scores at the games. Some VPSes include a clothing system, either for pets or human avatars. VPSes are the pet-themed version of social gaming sites, which are usually built around a forum with a customizable avatar and clothing system. This system is intended to facilitate player socialization by allowing players to present a carefully-chosen visual representation of themselves to others, and regularly update this visual representation to reflect holidays and other social events.

Minigame Arcades – Minigames are games which take a short time to play. They consist mainly of speedpuzzle games (Tetris, Frozenbubble, Pouyopouyo), solitaires (cards, Mahjongg, Minesweeper, Hangman, boardgames against a computer opponent), and arcade games (beat-'em-ups, shoot-'em-ups, bullet hells, pinball). In many some cases it is possible but rare to win; in other cases it is impossible to win, instead the player is scored on how long they survived or how many targets they shot or bonuses they collected before losing. A minigame does not have to have a forum or other social component; sometimes they are purely ad-supported and have no cash shop or membership. If a minigame arcade is combined with a social forum such as VPS the arcade is usually the method by which players can earn a daily income of game currency to spend on pets, clothing, or similar items. Minigames may not be terribly memorable or artistic, but they are convenient from a site maintainer's perspective because if one breaks or is disliked by player it is not related to the others and doesn't spoil the players' enjoyment of them. Arcades are also easy to expand by adding new minigames, as opposed to larger games where new content must be integrated and balanced with existing content.

PvP Pet Competition Games – PvP (player vs. player) games are those where the main multiplayer activity is dueling other players; possibly in combat but non-violent activities like racing, show jumping, agility, dressage, or beauty contests are also popular. One of the main goals is to earn a high rank in the competitive league of all players. Another goal may be to have the highest personal score on a particular course compared to your friends or other players who attempted that course during the current week or month. These games come in two flavors, fast-paced for those who crave adrenaline, and slow-paced for those who prefer strategy and patient persistence. The fast-paced kind has a main activity of driving the pet at high speeds while avoiding obstacles with quick reflexes (Or more rarely, fast-paced RTS combat between the armies belonging to two players.) The slow-paced kind is a sim or RPG where the main activity is increasing pet stats through training, breeding, or interacting repeatedly with an individual pet; in these slower-paced PvP games the competitive activity is either automated or turn-based instead of real-time. Both flavors of PvP game may have a singleplayer campaign or series of quests which teach the player how to play and may allow the player to earn higher levels and increased stats for individual pets or for the player's infrastructure. (Infrastructure is the property, tools, and abilities the player uses to produce competing animals: their ranch or other property, appliances and outbuildings for storing and breeding pets, training pets, or crafting useful items, their ability to breed higher-potential or rare baby pets, and their ability to modify pets.)

MMORPGs – MMOs are games where hundreds or thousands of people interact within an explorable virtual world. Whether the game uses 2D or 3D graphics the key element is that friends can, in realtime, see each other doing stuff within the world. RPGs are fighting-focused games where the fighting is strongly effected by stats; the main activity of the game is increasing these stats through leveling up and getting better gear. Progress through the game is typically guided by NPCs (non-player characters) offering quests, but the player is usually free to wander anywhere they don't immediately get killed by higher-level monsters. The most common type of combat is realtime involving spellbars and cooldowns, but many other types of combat are compatible with this type of game, from simple turn-based to turn-based tactical to realtime 3/4 overhead to realtime sidescroller/arcade/platformer, and even racing combat where racers can attack each other during the race. Please see the combat section for more details. Some MMOs are almost completely focused on PvE (player vs. Environment, where environment usually = monsters) combat. Normal difficulty monsters are found by single players or pairs of players in the main game world, while instanced dungeons are populated with elite (high-difficulty) monsters and bosses that require teams players to work together. Other MMOs have a focus on PvP, whether between individuals or in teams of 5 or more. Singleplayer PvP involves dueling other players for personal gain; group PvP can be simple team duels where the last player alive determines which team wins, or can be a more complicated activity of territorial capture by either NPC factions that players join or player-created clans/guilds. However PvP is structured, each player earns a PvP rank by their performance, and improving this rank is a goal and a source of pride. Both PvE and PvP are the main source of player income in games featuring them.

FPSes – I have not actually seen a pet-themed FPS, so I'll speculate on what one might be like. One possibility is that different pets might correspond to different types of guns, or perhaps biological armored suits that happen to include guns, or animal forms the player could shapeshift into which would happen to include distance attacks. The player would have the ability to bond with (or equip) one animal at a time, and which animal was equipped could affect range, firing speed, power, special effects like poison or freeze rays, and maybe things not directly related to shooting like the player's size, running speed, armor, healing speed, max health, jumping ability, etc. There are single-player FPSes, usually those are very similar to either an RPG or a fast-paced PvE racing game. Multiplayer FPS games are more different from MMOs and fast-paced PvP competition games because of the emphasis on short, intense interactions between 4-12 people and their environment (because the environment typically contains weapons, ammo, and healing items that the players have to scrabble for while avoiding being shot). Some FPS games have battle royale rules, meaning all players are against each other and the last one alive wins. Other FPS games have team play, often inspired by capture the flag, with death being a temporary setback from which players respawn until other one team or the other captures the flag (or destroys the other team's base, or whatever the specific goal is).

RTSes – Real-time Strategy Games typically have BOTH a singleplayer campaign and a multiplayer system for allowing 2-4 players to duel. The closest an RTS gets to a pet game is probably where the units are all creatures, and the buildings are either also creatures or are designed to feed or breed creatures. SimAnt is a fairly clear example, while the Zerg race in Starcraft may require a bit of squinting to see as an army of the player's pets. RTSes are all about building up infrastructure and climbing a tech tree, as described in the entry on sims. But in an RTS the play has to do it as fast as possible while being attacked by enemies, and the goal of PvP duels and most singleplayer missions is to exterminate the enemy from the map. Sims on the other hand are generally slower-paced, and instead of extermination sims are usually about becoming the best pet-breeder or similar profession, and earning a lot of money this way.

Singleplayer Game Genres:


RPGs – Single-player RPGs typically lack the focus on character appearance customization that MMORPGs often have. Instead single-player RPGs come in two flavors: J and W. J stands for Japanese and W for Western, but that was a historical division that is no longer accurate. These days both types of RPG can be made anywhere. Instead it's best to think of jRPGs as those which have a strong story and pre-created characters and quests, while wRPGs are those in which the player creates the playable characters and the game can generate semi-randomized quests, maps, and/or NPCs to make the game extensible and replayable. In jRPGs the player's progress through the game's story and world is regulated mainly by quests and puzzles which must be solved to unlock the player's ability to move to a new physical are of the game. In wRPGs the game is usually less linear, with the player free to wander anywhere they can stay alive. Both games have a focus on 1-10 playable characters and their use in combat, which can come in all the varieties listed under MMORPG. Singleplayer RPGs by definition cannot have PvP, so all play is PvE, unless the game has limited multiplayer functionality which allows dueling outside the main context of the game. But the main activity of the game is fighting monsters and bosses. The overall goal of this activity is to become the best fighter in the world and beat the biggest bad guy in the world.

PvE Pet Competition Games – These are singleplayer versions of PvP Pet Competition Games. As with singleplayer versions of strategy games, singleplayer competition games are often organized in the form of a campaign, a sequence of increasingly complex and difficult competitions which will eventually result in becoming the world-wide winner of whatever the particular competitive activity is. Like the PvP version the PvE version is split into fast-paced activities like racing and flying games and slow-paced activities like pet shows of the beauty contest variety. This genre is the one that most commonly tends to be confused about whether it is a game or a toy, though VPSes and sims may also suffer from this confusion. This causes problems both during development and for players of the finished game. See the entry below about Virtual Toys for info about avoiding this mistake.

Babysitting Game or Time Management Game – Other pet games often include a babysitting segment for raising young pets or breeding pets. Babysitting games can also be minigames. Technically they are a hybrid between a speedpuzzle game and a sim. A time management game is the non-combat version of an RTS, though in most time management games you control one unit rather than an army of units. What happens in a babysitting game is that the pets have happiness, health, cleanliness, sleepiness, or similar gauges. And these meters will get lower until the pet is very unhappy or dies, if the player does not intervene. Either the player can select the pet to see all of its gauges, or the pet will emote any need that crosses into the danger zone, or both. Emoting can be done by an emoticon symbolizing the pet's need appearing above their head in a thought or speech bubble, or it can be done by the pet's facial expression and/or body language changing to express their need, along with other visual effects like “stink lines” rising off a dirty pet. In some cases pets do not have health gauges; Lemmings is a classic example. The pets move of their own volition and often encounter fatal obstacles. The player must use some pets to solve the level's puzzle while keeping enough pets alive to lead them through the final gate to safety and satisfy the level's victory condition. When babysitting is the main activity of a standalone game the game is typically organized into a campaign, and each level of mission has a time limit. Time management games have a similar dynamic where the player runs around as fast as they can trying to fulfill a variety of needs. These goal of the game is not to maintain happiness though, it's probably to grow, breed, or craft something which can be sold for money, as in a Tycoon game.

Sims and Tycoons – Some Pet Competition games and RPGs overlap with sims, in that they can all include breeding, collecting, and training pets, and amassing wealth, levels, and/or stats and special abilities tied to level. Sims and RPGs may also both include crafting and building up an infrastructure by climbing a tech tree. Where RPGs have an overall goal of becoming the best fighter in the world, sims and tycoons usually replace this with a goal of becoming the best farmer or breeder or collector or crafter in the world. As the player gains experience they usually unlock new resources and special abilities related to this profession. Tycoons are a subgenre of sims; there's no real difference between the two except that tycoons have more of an emphasis on making money via selling the results of your sim-labor, while non-tycoon sims sometimes don't even have a currency system. Sim games usually have tech trees. A tech tree is a structure where the player puts effort into unlocking or mastering low level abilities, which are prerequisites to unlocking or mastering higher level abilities. For more details see the crafting section below.

Adventure Games and Interactive Story Games – Adventure and interactive story are actually two different genres, I'm just combining them here because they are so often seen together. Both of them typically lack combat, though they can be hybridized with a kind of game that has combat (for example the Zelda series are action-adventure hybrids). Both of them are typically singleplayer because, like sim gameplay, puzzle-solving gameplay is very difficult to make multiplayer without interfering with what makes it fun. The difference between these two genres is: Adventure games have physical puzzles that the player solves by flipping switches, turning knobs, sliding things along tracks, using pipes to move fluids around, igniting fires, and that sort of thing. Interactive story games mostly involve talking to other NPCs in a form of interaction called a dialogue puzzle, where the player can choose from a list of options what to say or do, and the choice made affects how the NPC decides to act, which in turn sends the plot of the game in one of a few different directions. In fact an interactive story game as a whole can be seen as one big puzzle where the player tries to carry out the right steps in the right order to get the best possible ending; many interactive story games expect the player to play through the game more than once the same way adventure games expect the player to need to restart puzzles if their first attempt at solving the puzzle turns out to be the wrong strategy. So both genres are about solving puzzles, the difference is just whether the puzzle pieces are physical objects or people. And it's common for games to have puzzle pieces of both types, thus making the game a combination of the two genres. Where do pets come in? Well, pets can be puzzle pieces, such as in a game about herding sheep through mazes. Animal-forms or summons can be puzzle solving techniques, such as a game where the player changes into a spider or summons a spider to weave a giant spiderweb that acts as a net to solve a puzzle, or the player changes into a bull or summons a bull to push a heavy object that they otherwise couldn't move. Or the player could be responsible for a space ark full of animal characters and have to matchmake between the animals so they are ready to produce lots of baby animals when they land on their target alien planet. There are all sorts of ways a game could be about solving complex puzzles involving animals.

Virtual Toys – Virtual Toys resemble games, but they generally have no goals or victory conditions. “Pet games” which are actually toys include the software portions of Tamagotchis, Furbys, and HexBugs, as well as various desktop pets and virtual fishtanks/fishponds. In the realm of non-pet games, Minecraft is the most notable example of a virtual toy in the past few years, though it has grown more game-like features (such as deadly monsters) since it was first created as a virtual lego-like toy. As a designer it's important to be aware of whether you want to make a game or a toy, since players who expect one will be disappointed if they get the other. Games and toys are both fun but not really in the same way, and software which has half game features and half toy features can be confusing and frustrating to the player – in other words, they can fail to be either kind of fun.

2. Theme: Story, Setting, Playable Character(s), And How These Should Interrelate With Gameplay.


A game is a piece of multimedia entertainment where the writing has to work as a partner with the gameplay (which is programming underneath) and the art. Well, not all games have stories, and virtual toys may have story but don't have goals. But this section is aimed at games that have a medium or high amount of story.

The word in the section heading that it's most likely readers will be confused by is theme. So let's talk about theme first. Above, we've talked about games which are focused on combat or competition, exploring at a relaxed pace or being super-efficient, solving puzzles or building up a small empire. I've mentioned that games also come in flavors like funny, cute, scary, magical, high-tech, and many others. All of these are theme, though they don't get at the heart of theme. Theme is the statement your game makes about what the (game) world is like and what the player's role is within that world. Who the player should be and what they should do to be declared the winner of (virtual) life. All forms of fiction, including games, are interpreted by the player's or reader's brain as life experience from which they may learn something about the real world and real life. This is why fiction is referred to as “the lie which tells a truth”.

The details are all made up, but characters act in ways that express truths of human nature, because they are based on the author's experience of themselves and others. The characters must behave in ways the audience finds psychologically and sociologically plausible, otherwise the characters will feel fake and the audience won't be able to suspend their disbelief and get immersed in that piece of fiction. Similarly, fictional worlds, though they can have magic or gameplay conventions that don't match the real world, are based on the creator's experience of the world. They must behave like something in the real world, though it's common to substitute something simpler for something too complicated, random, or slow to be quick fun. For example growing plants in a game is usually much faster and less prone to random disasters than growing plants in real life. And a difficult skill like picking a lock with several tumblers may be substituted for with a simpler locking mechanism like a sliding block puzzle. Fictional worlds must be internally consistent so that players feel satisfied because they are learning to master an interesting new environment, and don't feel like the game is “cheating” or “AI stupid”.

(AI stupid refers to a game being unable to recognize what the player is trying to do or refusing to accept a solution that seems logical and realistic from the player's point of view but the game has not been programmed to understand. For example, say a player must combine a string and a stick in their inventory to make a bow. If using the string on the stick works correctly but using the stick on the string results in an error, that's a classic example of AI stupidity.)

What kinds of themes do games commonly express? A game where the player spends all their time fighting, for example, can't help but promote the idea that the way one wins at life is by being the best warrior. Most of us aren't fighters in real life but the message still comes across that traits which are important to winning fights, like toughness, are important to cultivate in oneself. Also that the problems we encounter in life can be thought of as battles, with enemies we ought to attack and vanquish. An adventure game which has puzzles instead of combat has totally different messages: awareness of one's surroundings, creativity in using tools, and manipulative finesse when dealing with other people are connected with success, while straightforwardly attacking an enemy with a weapon as unsophisticated as a sword seems unlikely to work and unwise. Strategy games are about using one's intelligence and awareness of surroundings to directly and forcefully overwhelm an opponent. A time management game where you have to be efficient and fast to survive can make you reflect that you should be acting more industrious and efficient in your real life, and avoid activities that are inefficient or not obviously productive.

Now, games and stories are not about preaching or brainwashing and don't have a strong effect on most people's beliefs. Usually audiences already have their own beliefs about what kind of role they want to play in what kind of world, and will seek out games that deliver a message they are already familiar with because everyone likes some positive reinforcement, and wants to hear more stories of kinds they already know they enjoy hearing. So as a designer the idea isn't really to say what you think people ought to hear, but instead to analyze the games whose stories you love, and why you love them, and how you can create a game world and cast of characters who will be as much fun for your players. As an added bonus you and your team members will be more motivated on writing bits of story and creating pieces of art to illustrate fun ideas.

So, a simple way to get started brainstorming story ideas for your game is to make a list of game stories you have really enjoyed. Novels, anime, movies, and folktales are all good source material too. Who would you want to be in a game, that your players might enjoy being in your game? What kind of game world would you like to spend time in, that your players might also enjoy spending time in? Since this is a pet game, and you've already decided whether you want one or many pets to be used in a combat or non-combat situation, let's get more specific about that! What should they look like and how would you enjoy interacting with these creatures? No need to limit yourself to story ideas if any gameplay ideas are occurring to you too. Scribble all your ideas down, because it's much easier to work with ideas you can see in front of you than ones floating nebulously around in your head.

If you already have a strong idea of what kind of experience you want your game to be for your players, you can cross out things you like but aren't compatible with this particular project. You can always use them in another project in the future! For example, I think breeding systems are awesome, but a breeding system doesn't fit very well with a game where you want the player to only own and use one or a few pets. So if I wanted to make a game which was about a player bonding with one pet, I'd save my elaborate breeding system ideas for a different game design. Or, if I wanted to make a game about the player as an individual becoming the best warrior ever, I would consider making the player a shapeshifter or animal who fights opponents alone, instead of a human who fights with pet companions. And if there are any other player-controlled animals in the game they could be the civilians who make up the player's home base, the pack/herd/flock the player fights to protect and helps to grow by bringing home the spoils of victory.

I can't talk about every possible case here, or even go into detail about different brainstorming techniques. You can use whatever techniques work for you. I personally like starting with a list of everything that occurs to me, then crossing off irrelevant things, adding new relevant ones, grouping these things into compatible clumps, ordering those clumps in order from ones I like most to ones I like least, then trying to the best or second-best and combine the best parts of the others into it, so that I end up with one big clump of compatible ideas that contains most of my favorites. But some people love mind-mapping/webbing/bubble diagrams, and some people like to analyze 1-3 examples of similar games in detail rather than pull ideas from many sources, and some people prefer to do their brainstorming in a conversation with one or more other people... there are lots of ways to brainstorm that work for different people, or the same person at different times. But the end goal here is to add a description of your game's playable character, world, and thematic appeal to your statement of purpose.

Here's another fill-in-the-blank for you: “The player will control/be [number and type of playable character(s)] who will be [profession] who [game's main activity such as fighting, questing, solving puzzles, or crafting] in the [description of game world] world of [world's name]. [Other important activities] will also allow the player to satisfy their urges to [explore/become wealthy and famous/play mad scientist/help someone/be clever/build something/investigate a mystery/save the world/etc.].” And some examples: “The player will be a witch or wizard who learns the craft of brewing complex potions to create unique pet monsters in the dark fantasy world of Monsturbia. Exploring the world to find ingredients provides a peaceful break between frantic potions-brewing sessions where the player must exhibit the speed and efficiency that will enable him/her to become the world's master monster-brewer, showered with wealth and fame.” Or, “The player, represented by an alpha wolf, will control him/herself and up to 7 subordinate wolves at a time in tactical combat, fighting his/her way from the humble beginning of the darkest forest of Wulfmoon to its capital city populated with the other most ambitious wolfpacks of the world. Combat alone can't get the player to the throne; only solving the puzzles in the ancient ruins of Paw's Mark, Broken Fang, and other such locations(dungeons) will allow the alpha to gain the wisdom and spiritual strength necessary to carry out the hero's true task: saving the world of Wulfmoon from itself.” Or, “The player will control the team of Wordy the Parrot and Arch the Cat as they bumble their way through a series of zany adventures, not-so-willingly helping the other animal denizens of Abcedaria solve their problems. Wordy and Arch must help each other navigate over obstacles and through mazes, as well as maze-like arguments with their stubborn neighbors. Even if this odd pair succeeds at bringing peace to their village, will they ever be able to stop arguing with each other?”

3. Distribution and Monetization: Getting the game to the player and the player's money to you.


Thinking about selling a game before any of it has been programmed may feel like getting ahead of yourself. However, the intended sales method affects the design, and plans for earning and dividing income affect recruitment of other team members. Non-profit and/or opensource games also have legal differences with regard to what resources you can use to make the game or how large of a fee you have to pay to use them.

Distribution used to be more of an issue, but these days most indie games are sold entirely online and there's no need to worry about printing CDs, packaging them, and getting them to brick-and-mortar stores. If physical sales happen for an indie game at all they usually happen through a distributor who is already selling the game online, or instead of the game itself the distributor may sell cash cards and you may sign an agreement to add your game to the stable of games that the cash card works with. If you want to sell physical spin-off items like keychains, t-shirts, stuffed animals, etc. you can either do that yourself or you can do it through an online merchant that prints these items on demand and sells similar items for many games, comics, and other fandoms; they probably get cheaper bulk shipping rates than would be available to you.

Online distribution involves either providing downloads of the game, providing a server for the player to play the game on, or both. These services are available through different kinds of distributors, such as appstores and other online game distributors, social networking sites, and server farms; it's also possible to build a server room full of machines yourself, provided you can get a location with access to professional quality internet.

There are three main ways of getting payment from players: selling a game outright (optionally after giving the player a free trial), charging a monthly subscription fee (again there is often a free trial first), or making the whole game f2p (free to play) and instead earning income through a cash shop and/or ad revenue. For a singleplayer game, the one-time sale is the standard model, except for apps. Apps are applications for smartphones or devices like ipads, where the game is sold through an appstore which can be assumed to already have a billing account set up for the device owner. (Account set-up is a traditional hurdle for all online sales because people may decide they don't want a game badly enough to fill out a form and give their credit-card number to a company they aren't familiar with. Thus, avoiding the need to create an account can result in more sales.) Apps can use a traditional one-time sales model, or they can be freemium (free or ad-supported except for premium content) and can use a cash shop to sell the premium content (including the ability to remove in-game ads) even though the game otherwise has few or no online features. Ad-removal can also be sold as a subscription, often this is an annual subscription instead of a monthly one.

For an online multiplayer game the choice is usually whether to go with a cash shop or a subscription. Cash shops are generally more popular with younger (i.e. credit-card-less) and casual players (don't spend enough hours per week playing to feel that they could make full use of a subscription), while subscriptions are more popular with hardcore players (subscriptions can limit beggars and spammers, and more importantly ensure that the game is fair to all players, not pay-to-win).

So, how is the sales method relevant to design? For starters, if your game is going to have a free trial, you need to figure out what the limiting factor(s) of that trial will be, and how to notify the player when they are encountering one of these limits so they aren't confused by why they can't do something, without spamming them silly with constant notifications.

If you intend to have a cash shop you need to design items to sell in it. Items that won't be available within the game for normal currency, items that everyone playing the game wants, but that don't make the game so obnoxious for those who don't buy them that they quit. Cash shop item sales come from three overlapping categories: Consumables, Conveniences, and Customizations.

Consumables include things like energy refills, timer accelerators, and buff scrolls, especially ones of double XP or death penalty prevention. Many of these are also conveniences. Some MMOs also require a consumable “megaphone” to be spent to speak in the world chat channel. Conveniences include anything that spares the player time, deaths and other losses, or annoyance: a permanent inventory expansion, a version of an item that usually requires 30 or more levels to equip that is instead equippable by a level 1, packs of crafting ingredients, and mounts or mount upgrades that increase traveling speed. Mounts (and limited or premium pets) are also a major category of customization, along with clothing, dye, special haircuts, and other visual effects from fireworks and petal showers to neon username frames. And again, many of those are consumables.

So the point is, if you intend to have a cash shop you have to create lacks in your game, which the player can remedy with time and/or work, or can immediately fix with a cash item, and you also have to consider how cash shop pets fit into your breeding system, and what percent of your cool hair and clothing designs should be cash vs. what percent should be quest rewards or cost game currency. It's also ideal to get players used to using the cash shop by giving them a small amount of cash currency and a few quests to buy or use cash items.

If you have a subscription system you need to have some kind of scheduler to remind people to renew before their subscription runs out. Longer subscriptions often come with bonus items, and a method to transfer these to the player's account and, if the account has more than one character, a method to let the player choose what character to receive the item on.

And on top of all that, you need to know how much money you are willing to spend on developing your game, and you need to keep track of money you spend toward developing the game so you can know later when (if) the game breaks even by earning that money back. If you are promising team members future revenues from the game, you need to have a plan for how that will work, and if that payment will end after a certain amount of money or time. If you are paying team members up front you are probably going to need a paypal account. And if you are selling your game, cash items, or any spin-off merchandise up front you are going to need a merchant account to accept credit card transactions.

You should now add a sentence about how your game will be sold and distributed to your statement of purpose. If you intend to recruit a volunteer team you may want to specify whether the game will be for profit but wait and get their input on which specific sales method to use. If you plan to make a kickstarter or similar crowd-sourcing call for funds there are extensive how-tos on that topic by people who have a lot more experience with that than me. “I, [YourName], am putting up [X$] as a budget for developing this game. [If you plan to ask other people to donate money, who and how?] The priority for what to spend this budget on will be [1st, 2nd, if any is left]. [If you are planning to offer shares or royalties, how will that work or when will you decide how that will work? Will some go to monthly webhosting bills or other game maintenance? Will some go to paying back investors, including you?] The game will earn money through [cash shop, subscription, flat sale, ad revenue, and/or spin-off merchandise sale].” If you have any ideas for specific cash-shop items or a kickstarter plan, put them in an appendix for later.

4. Player Registration and Account Creation, Data Storage Within The Game


For a singleplayer game it has recently become standard to allow the player to enter their name or name the location they own within the game (ranch/farm/zoo/store/house/estate/tribe/country). This is a simple input and storage of a text string. This name may be used when the game or an NPC speaks to the player or about the player. It may also be incorporated into the save game file's name. Many singleplayer games do not bother with a password system, but such a system can be used if it seems likely that multiple people will have their own game accounts on the same computer, and players might want to protect their own account from meddling siblings or friends. Passwords in general need to be stored using some kind of encryption. Some singleplayer games are in a free trial mode by default, unless and until the player purchases the game online, receiving an activation code or script. Entering this code or running this script is part of the process of registering the player as an official owner of the game, but it may take place after the player has already been playing the game for an hour or more.

So, where are you storing all this data? A completely singleplayer game typically uses a saved game file stored on the player's own computer. This is possible because with a singleplayer game it does not harm other players if anyone hacks game files on their own computers. Some games even encourage user-modifications, and may offer an online system for distributing these to other players. The Creatures series, Sims series, and Spore are some examples. Multiplayer games on the other hand do not want to put any important data on the players' computers where it is vulnerable to being altered. It's common to have the player's computer store a client, which is more or less an engine for displaying the game's data to the player, and also remembering the player's customized settings and patch history. They also may cache on the player's computer sound files, graphics files, and other data used only by the player's computer to display the game to the player. This can reduce constantly re-downloading the same files from the server, which is annoying to the player and costs bandwith for both the player and the server. For a while people were experimenting with putting hackable data on players' computers and just checking it against the server to make sure it hadn't been tampered with, but players kept finding ways to get around this checking so this method is basically extinct.

Some games, especially those with minimal graphics, store all their data online and don't put anything on the player's computer except possibly a browser cookie. Most browser-based games are in this category. This method can be advantageous because it removes the need for players to wait for a possibly long download before they can start playing, a traditional hurdle to getting potential new players into the game. But on the other hand the game may have a fairly long load time for every play session, which could have been shorter if some of the things being loaded had been cached on the player's computer.

On the server-side of multiplayer games, because the server has data for many, many players, in addition to data for various monsters and items which have many instances within the game, it makes a lot more sense to store all that data in a database rather than a file for every player, every monster, and every item. A database is a system that structures and indexes information so it's fast and retrieve the data you want from it. For example, a common thing a game needs to do is to generate the loot a player gets after winning a combat. Each monster has a standardized set of database entries associated with it, one of which is a loot table. When generating the loot, the game only needs the loot table, not the monster's other data like hp or appearance, so it would be inefficient if they were in the same database entry. And the game needs to quickly grab the loot tables for every monster that was killed in the combat if more than one was. Well-known databases include all those variants of SQL, along with Oracle and Access. Anyway, although someone has to design the particular way a game's information will be stored in a chosen database or saved game file, that's getting more into programming issues and is off-topic for this guide.

Online games typically have a more complex registration system than single-player games. (The major exception is ad-supported minigame archives, which typically have optional registration or no registration, since they do not need billing information for users.) Usually the player will have to state their birthday or that they are over the minimum age your game or a specific server of your game allows. Many games also require an email address. Optionally a game may allow one player to create several characters or locations, each of which needs their own name; in this case the player's name may either be used only by the forum and billing system, or may not be used within the game at all. Online games typically store most of the game's data in database entries. A player's true identity within the game may be their account number, with the player's username being only one of several pieces of data in the database entry for that account number. In some cases a game may be part of a larger network where the player already has an account, from which the game will import some of the player's data, and possibly share the player's achievements within the game back to that network. Typically a player is required to read the game's terms of service during the registration phase if they were not already required to do so during an installation phase. Many people don't actually read those things, so it can be helpful to also present the few major rules of the game in big red letters as part of the registration process.

If your game has servers or realms, helping the player select one and recording that selection is also part of the registration process. Typically the player will want to know the server's age and how full it is. In some cases you will want serves to be functionally different: PvP vs. PvE, or normal vs. heroic (larger rewards and harsher penalties possibly including permadeath), under-18 vs. over-18, or f2p vs. subscriber-only. So you will need to tell the player which servers are which, and also check the player's age or subscriber status to see if they are allowed into a restricted server.

Another standard part of many registration processes is to test the validity of the email address that has been entered by sending a test mail with an activation code, which the player must click on or copy and paste to activate their account. Un-confirmed players may be able to play with some features disabled – usually multiplayer ones like trading and chatting or posting to forums. This is because the email-validity check is designed to help filter out previously-banned people, spammers, and goldfarmers, all of whom cause problems by interacting with other players but aren't really a problem when playing solo.

Hey look, we've gotten to the end of the statement of purpose! For the last sentence you should write something along the lines of “Gameplay will take place [on the player's computer or phone/in a client communicating with an online server/entirely online via a browser.]

Then let's strike while the iron is hot and start the features list! This is the list that will develop into the main part of your design document (and a non-detailed version of it will be your table of contents). But right now let's just make a list, you will need to look back at what you decided in the first 3 parts:

- Game Data Storage

- [Offline saved game file/Online database/Mainly offline with minimal online friends network or cash shop or ad serving]

- Account Creation and Registration

- [If online, are you handling account creation yourself or is a store or stable handling it for you?]

- [What data do you want to collect from each player?]

- [If you have a free trial, how do you tell whether a player is in that mode or fully activated mode? Some distributors, such as Big Fish, have a standardized free trial system that they apply to all games sold through them.]

- [Do you require email confirmation, credit card confirmation, or age verification? What can't the player do before they are confirmed?]

- [If you intend to have multiple servers, what differentiates them?]

- [Graphics Type]
- [Gameplay Genre(s)]

- [Looking at the description of your genre, what major features does this genre have that you want your game to have? E.g. Combat, racing, crafting, puzzles... Give each of these its own entry here.]

- Story (unless your game has none)

- [Linear or Interactive]

- [Story Genres(s) E.g. Horror, Fantasy, Humor, Romance, Adventure, Mystery]

- [Theme(s)]

- Story is shown to the player through [NPC dialogue, written pages or books, cut-scenes between play segments, comic/manga pages between play segments, direct narration to the player, item flavor texts, graffiti/murals/stained glass images on level walls, etc.]

- Notes: [Any story ideas you have had so far]

- [Number and Type of Playable Characters]

- [Continue to section 5 for the rest! :) ]


5. Avatar Creation: Human vs. Pet, Clothing Systems, The Avatar's Role(s) Within The Game, Avatar Equipment Slots, Stats, and Abilities.


Probably most of you are familiar with the concept of an avatar as a 2D image which you choose to represent yourself on a forum, IM network, or social networking site. Some games use that kind of avatar, notably Facebook games where the players already have such avatars as part of their Facebook account. This kind of image can either be provided by the player or chosen from a list provided by the game. That's fine, and if that fills your game's need to visually identify players to each other, well and good. But that's not actually the kind of avatar I'm going to talk about here.

Some games do not have avatars. These include 1st person games where you cannot see the main character because you are looking out through their eyes, and also large-scale strategy or sim games where your role is that of a general or business manager, and there is no point showing the player's body because the player doesn't do any gameplay through an individual body. In 1st person games sometimes the mouse pointer is characterized as the player's hand, or a gun the player is holding is visible in the bottom center of the screen. In strategy and sim games the player's identity is more that of their whole army or company, often combined with a color, insignia, or faction. Think of board games – it's common to say, “I'm red” or “I'm the blue army”. Or for an insignia example, “I'm the shoe” in Monopoly, and for a faction example, “I'm the Orcs” in Starcraft. This can be a standalone system or included alongside more complex avatars. Games that allow the player to create a guild or corporations generally also let the player create an insignia for it, and games that allow building a castle or fortress often let the player design a flag. If you want this kind of system in your game it needs to be designed like any other graphical system – make a note in an appendix. But it's still not what I really mean by avatars.

What I actually wanted to talk about is the concept of the avatar as a playable character through which the player acts out gameplay actions and the main role in the game's story. An avatar is the player's primary worker, explorer, fighter, and problem-solver, and also a way of showing the player's physical and emotional involvement in the story. In a pet game these avatars may be humanoids or non-human creatures, depending on the player's role in the story.

Multiplayer games often have highly customizable avatars, and make avatar customization its own kind of gameplay. Singleplayer games often don't have much customization because it's not as interesting to players to customize their appearance when there are no other players to see that appearance. On the other hand singleplayer games have the option to pre-create a character with a distinctive appearance, name, and story like that of a novel or movie, and get the player to play as that character. This is less tolerated by players of multiplayer games. Some games equate one player with one playable character, while others allow the player to start a new parallel journey through the game with each new character, while still others give the player simultaneous control of a team or small army of characters. Is your player a pet owner or other person who works with (NPC) animals, or is your player an animal themselves? Some virtual pet sites avoid having a human avatar by giving the player a minimal role as a pet owner but delegate much or all of the gameplay to the player's active pet; the player thus acts through the avatar of this pet. This limits the possibilities for telling any kind of personal story about the player, so it's only an appropriate choice of you don't want your game story to be about the player's own heroic adventures, but instead about the pet's adventures. Some pet games have both humanoid and pet avatars; either their roles in the game are split, with the humanoid doing the interaction with NPCs and the pets doing the combat/competition, or the player controls a mixed team of humanoid(s) and pet(s) in combat/competition.

Some specific uses of avatars: Avatars are appropriate to tactical games where the player controls ten or fewer units in combat. (A unit is each humanoid or pet which participates in combat; real-time and turn-based RPG-style combat usually has 1-3 units while tactical games often have 4-10.) Avatars are also appropriate to time-management and energy-management games where the player can only act through their avatar and that avatar is what the player uses to run around trying to get all their tasks done in an efficient order. Avatars are appropriate to games where one of the game's activities is solving the problems of NPCs, since it is difficult to tell this kind of story about inter-personal interaction without giving the player a person with which to carry out their half of the interactions. (Though, dating sims are commonly 1st person, and they are very personal and emotional stories. This is because they are single-player games and the lack of avatar customization is extra-likely to alienate players in a game where the player is supposed to imagine themselves in a romantic relationship with one or more NPCs.) And finally avatars are appropriate to RPGs and action adventure games which typically have stories of personal growth (bildungsroman), adventuring, and exploration; again, it's difficult to tell a story about a character's adventures and progress without a visual representation of that character.

So in conclusion, the type of avatar system you choose for your game, if any, should be appropriate to the kind of actions you intend the player to perform within the game and the kind of story you want to tell about the playable character(s). If you want to tell a personal story where the player is equated with the main character, you need to either give the player an avatar or make the game be in 1st person POV. Avatars are appropriate to games where the main activities are those carried out by one or a few characters within an interactive world. (Or games which are primarily forums, where people want to present an image of themselves for social communication purposes.) On the other hand, games where the player's main activities are detail tasks like solving puzzles or large-scale tasks like acting as the general of an army can work quite well without an avatar, beyond the possible characterization of the mouse pointer as the player's hand or use of a faction color or symbol. And games which have neither a social element nor a story probably don't require avatars.

Avatar creation is often considered part of the pre-play or setup portion of a game; if all or most gameplay must be done through the avatar, the player pretty much can't play until they have created an avatar. However, avatar customization can be much more than a setup-type activity. Customization can be a major type of gameplay within the game. Avatar customizations make good quest rewards and thing the player can enjoy shopping for. Some games even include a ticker or progress bar where the player can set a goal item they want to buy and its price, and the game will display the player's current money as progress toward this shopping goal. Avatar appearance plays an important role in socialization between players, and changes of costume associated with holidays contribute to making a multiplayer game world feel alive to players. In class-based RPGs character appearance (especially weapon type) is commonly tied to class and can tell other players at a glance what the character's fighting style is, or if they are a healer or other support class.

In games where there is one avatar per player, the data for the avatar may be stored directly in the database entry for the player's account (or saved game file for a singleplayer game). If multiple characters are possible, the player's account database entry should contain links to the database entries for each character. In singleplayer games instead of allowing multiple avatars per player the game may allow multiple players, which may be equated to saved games, or may be allowed multiple saved games. In this case, if a player wants a new avatar and a new journey through the game they can simply create a second player account (because it's free, unlike in many online games, and it's easy to create a player account and switch between them).

In some games a human avatar's appearance is its only relevant property. Appearance traits typically include: gender, species/race if the game has multiple kinds of playable humanoids, body build if there are multiple options per gender, skin color, hair color, hair shape, and face (sometimes the shapes, sizes, and positions of individual facial features can be chosen). In more highly customizable games eye color, makeup, tattoos, height, and animalistic accessories such as horns, ears, tails, and wings are all possible avatar traits. In some games where a pet is necessary for combat the player may need both a human avatar and a first pet which is also created like an avatar.

Pet avatar systems depend on whether the pets in the game have predetermined appearances, with or without animations, or whether the pets' appearances are genetically generated from either layers of 2D images or body part models and textures. Even when pets are highly customizable via a genetic system, most of this system will be closed off to a starting player, as unlocking the branches of this genetic tech tree is usually a major part of the gameplay. So the player's creation of a first pet will be limited by that. Some systems do not allow the player to create a pet, but instead limit the player to choosing from a small selection of standard starter pets, adopting a pet another player has abandoned (or the game has randomly generated). Or the player may be required to start with a specific type of pet. For example, in a system where all newborn pets are amoebas which evolve into different animals through gameplay, it would be logical that all players must start with an amoeba. Some systems require the player to start with an egg or egg-equivalent, whether the pet type is choosable or not. That egg might appear as the player's avatar until the player manages to hatch it. Some pet systems do not have gendered pets, or do not visually distinguish between male and female pets. Some pet systems allow the player to choose the color and/or markings of a pet, some do not.

Avatar Clothing And Other Equipment

Then of course there is the clothing. Newly-created humanoid characters are usually given default clothing. This could be a universal default or a default for their gender or class. Occasionally the player is allowed to choose the colors of this default clothing, or chose between a small number of clothing styles. Some games allow pets to wear clothing, but even when they do newly-created pets often have no clothing at all, or only a collar. But once the player begins playing the game, many more clothing choices can become available. Clothing in games can come in a wide range of customizability, from a non-customizable whole outfit, to different colors of that outfit, to 3-piece mix-n-match gear (waist-up, waist-to-knees, and knees-down), to separate hats/masks, cloaks, shields, weapons, and gloves, to a highly layerable wardrobe and a wide assortment of jewelry, and even to objects which are not clothing but instead visual effects such as glows, sparkles, or falls of petals or feathers, backgrounds that appear behind the avatar, decorative borders or symbols near the avatar's name, or accessory objects either attached to the character or following nearby.

A character's mount may also be considered part of the character's equipped items, and that mount itself may be customizable with different saddles, barding or body armor, headgear, leg armor, and/or mane and tail styles.) The same goes for a character's currently equipped pet (or pets if the game allows more than one to be equipped at once). Current buffs and debuffs (aka status ailments) applied to a character may also be considered part of that character's equipment; they may have visual effects such as causing the character to appear transformed into a monster, causing the character to glow red with berserk rage, white with healing power, green with sickness, etc.

In some games, especially RPGs and RPG hybrids, the avatar may have dozens statistics which describe its abilities. Many of these are only relevant in combat, and those will be discussed in the combat section, along with whether classes and races are actually a good idea. But some may affect the character's behavior outside of combat: level, class(es), race/species, faction alignment, reputation with various individual NPCs, running speed, jumping height, ability to lift and/or carry various items, resistance to damage from falling, resistance to harsh temperatures and poison, swimming ability, flying ability, ability to sit or meditate to heal, available emotes and gestures, ability to identify and gather different kinds of resources, and learned non-combat spells and skills. The actions a character is able to perform can further be enabled, disabled, or altered by a spell, skill, tool, consumable item, equipped pet or mount, or currently applied buff or debuff.

Now you should be able to add the following to your features list:

- [Number and Type of Playable Characters]

- [What role does the avatar serve within the game? Exploration, combat, sim-play, picture next to forum posts and messages...?]
- [Describe a default avatar's stats and abilities]
- [Describe a default avatar's appearance. Is it Customizable? Is it tied to class? Is it genetic? Can characters be customized before play begins, during play, or both?]
- [Describe the equipment part of the customization system. Is there a clothing system, and if so how does it work. Weapons, tattoos, and jewelry are included, as well as backgrounds and special effects. Does equipment affect the character's stats, and if so, how?]
- [Are there mounts? If do, are they customizable or all of one type or of a few specific types?]
- [If the pet has both humanoid and creature characters which have different customization systems, repeat the above entries for the second type of characters.]


6. Inventory Systems: Types Of Items and How Each Type Functions Within the Game, How the User Interacts With Storage, Storage Limitations and Expansion As Gameplay.


Almost all pet games have an inventory of some sort. In games where the player is expected to collect many pets they usually have their own inventory system, separate from equippable and consumable items. Tycoon games have one of the most minimal kinds of inventories, so let's start there. A pet breeding tycoon game generally has one playing field functioning as a visual inventory of currently owned pets, optionally a secondary playing field with pets being sold in your shop, an inventory category for eggs or frozen animals, optionally a secondary inventory category which is a book recording all pets you have bred so far and which sets you've completed and earned an achievement and rewards for, one inventory category for upgradeable tools, an inventory category for consumable items like medicine, vitamins, food, and insta-grow, and the basic one for money and optionally the other basic ones for XP and/or energy/magic. It may not be immediately obvious that the playing field is an inventory, but there is often a limited number of pet slots, whether those are stalls, nests, pots for plants, or simply a capacity limit. It's also often possible to buy additional space, either within the playing field, as additional copies of the playing field, or in the other inventory categories such as the shop and egg storage. Upgradeable tools are technically "key items" or "plot items" which are generally items the player can't sell and which don't get consumed when used. Sometimes these items have their own XP bars and level up with use.

Equippable gear with combat stats (armor, weapons, accessories) is another standard inventory category. Typically the clothing inventory interface include some sort of paperdoll or wireframe representation of what items are currently equipped on the character, as well as the character's stats as modified by the gear. Some clothing systems have a double clothing inventory; in one set of slots go the stat-bearing gear, but there is a second set of slots where more attractive gear or statless clothing can be placed to cover up the not-necessarily-matched-or-attractive gear.

Consumable items in an RPG-type game can include all the breeding and pet food sort of items from tycoon games, as well as scrolls that teach a skill, armor-repair kits and bandages, various sorts of buffs in pill, potion, or human food form, and gatherables/monster drops which are consumed through crafting. Gatherables include things you pick from plants, dig from the ground, or otherwise find while exploring. Drops include things you can get from tending tame animals (wool, milk, eggs, beeswax, possibly leather and meat if the game allows players to slaughter tame animals) as well as things you can get from fighting monsters and also fishing and similar minigames. The consumable items category can also include crafted items which are used to craft more complex items. (Things like string, fabric, boards, bricks, metal ingots, dye, glue, etc.)

Key items in RPG-type games may include quest-related items in addition to tools and even emotes in online games. Like character customizations, special emotes make nice quest rewards.

Most genres have only one or two inventory locations, though a location may be divided into categories. An inventory location may be an abstract place reachable by a menu, a backpack or similar portable container, a bank which can only be accessed from specific locations within the game and probably has usage fees, or a chest/safe/warehouse built or bought by the player at a specific location within the game (commonly in the player's house). In some systems items can be manipulated within the inventory, either by using a tool on an item, or by using one item on another, or by selecting multiple items and attempting to use a “combine” function. In some cases there may be multiple copies of the same kind of inventory; for example each avatar may have their own backpack or the player may have 3 fish tanks.

So, how is the storage internally structured, and how does the user rearrange it or get things in and out? If a player cannot have duplicates of an item, that's pretty simple: they have it or they don't. Let's call this a binary inventory, because the number of each item is either 0 or 1. Tools and upgrades often follow this paradigm. Also, checklists of achievements, such as areas of the map that have been discovered, types of pet that have been captured or bred (often recorded in a book), and many 1-time quest objectives. These may not be physical objects in an interactive inventory, but the way in which the game keeps track of them is like a read-only inventory. In some cases the player may have an inventory size limited by slots. For example if the inventory has 20 slots the player can carry 20 items, but if they try to pick up a 21st they will either be unable to or will be prompted to discard something.

Another type of inventory would be the stack inventory. In this case, whenever a player gets a new type of item it starts a new stack, then all additional items of the same type are added to that stack, up to a predetermined maximum number the stack can hold. 10, 20, and 100 (or 9 and 99) are common stack sizes. In some systems stack size varies to create the impression that some items are larger or heavier. For example 100 feathers might fit in a stack, while only 10 iron bars do. If a game has this type of information it is stored as part of the data for each specific item, though there is usually a default stack size for a generic item. This is related to the programming concept of inheritance, which... is getting off topic. The player may or may not be allowed to have a second stack of that type of item after the first is full; usually this rule applies to the whole system, not individual item types. As with a binary inventory the player may have a limited number of slots; in this case each slot can only hold one stack of same-type items, regardless of whether it is a stack of 1 or a stack of 100.

Inventory type #3 is the weight inventory. Every item has a weight (or in some cases separate weight and volume numbers). The character's stats determine how much weight and volume they can carry. The two numbers might be affected by different stats, for example the character's strength might determine weight while the backpack they have equipped might directly give a volume. The character can then carry as many of each type of item as they want, but if they try to carry too much weight or too much volume they are overloaded (or pinned) and cannot walk until they discard something. Some games don't allow an overloaded character to pick up more items, others do as long as the character can do it without moving. Some games don't actually allow the character to become overloaded, instead giving the player an error message when they try to pick up an item that will put them over the limit. Those usually still need the functionality of being pinned when overloaded, though, because a character carrying a legal weight may get debuffed so that they are now unable to carry what they were already holding. Some games block the trading function on overloaded characters; I've never quite understood the goal of this rule.

Inventory type #4 is the puzzle inventory. In this case the player's storage is a 2D grid and each item has a 2D shape; the player can carry whatever they can fit into the grid. This is intended to simulate the experience that real backpacks and suitcases can hold more when they are packed efficiently than when you just throw things in.

Finally, there is the rummage inventory. This type of inventory displays each item or stack as a 2D image, and each of these images is on a transparent layer. The player can only access items which don't have other items on top of them. This is intended to simulate the experience of rummaging around in a purse or rucksack and occasionally needing to dig out items from the bottom. Also the visual image of all one's possessions lying in a pile may seem more realistic then having them neatly organized in a grid, especially in a low-tech game world.

Oh, a bit more about the playing field as a visual inventory, especially of pets (or plants). This varies hugely based on the individual game. In some games you have a piece of property, usually with a square grid, on which you place all your buildings, appliances, crops, and/or animals. You're usually not intended to be able to fill up all this space, so the limit on number of animals you are allowed to have on your property may be much lower than the number of grid squares you could hypothetically park animals on. But still, your property functions as an inventory, similar to the puzzle inventory described above. In other games there is no such grid. Fish tanks are a nice example. A fish does not generally stay parked in one square of the tank, it wanders all around and can pass in front of or behind other fish and decorations, through the use of image layers. But the tank does have a limit on the number of fish it can hold. In this case the tank is probably programmed as a binary inventory where the tank holds a set number of binary items, each one being a fish. This is likely because each fish typically has individual data, like age and health, so they couldn't be effectively treated as a stack of a single type of fish.

Time to add to your features list again:

- [Inventories]

- [For the first inventory, describe its location, the kinds of things it can contain, and starting size]

- [For each inventory, describe how it can be upgraded if this is possible.]

- [Repeat for each additional inventory]

- [Ditto]

- [Item types]

- [For each item type, describe how it functions and some example objects of that type. If you have listed pets as avatars, but the game has a different mode where pets function more like items, you may have to list them here too. Or if pets function as different types of items in two game modes, make an entry here for each mode.]

- [What properties or statistics, if any, do items of this type have?]

- [Repeat for each additional item type]

- [Ditto]


7. Gathering and Crafting: Climbing the Tech Tree, Recipes, Skills, Building Up Infrastructure, and Crafting Gameplay.


Crafting is any act of processing a resource to alter it or combining two resources into something new. The resources upon which crafting is performed are usually gatherables or drops. Gatherables are items the player can pick up from their environment. Some items are gatherable by default: berries, mushrooms, and fallen branches are common examples. Some items require tools to enable gathering them: for example a pick may be needed to mine ore, while a bucket or bottle is needed to gather water. Some items require a skill to gather them, and perhaps even to detect them in the first place: ectoplasm might be gatherable from ghosts, but you might need to learn spirit-version before you can see ghosts, much less interact with them. Drops on the other hand are items received after winning a combat or playing a minigame. Combat drops commonly include body parts of the monster killed: horns, feathers, scales, bones, teeth. If a humanoid opponent is killed drops might logically include bits of broken armor, fabric, potions, and anything else the humanoid might have been wearing or carrying. In some games combat drops are the major source of player gear, but droppable gear combines badly with a deep or extensive crafting system; I personally suggest that anyone who wants crafting to be a major part of their game should not make gear droppable. Minigame drops should have some thematic relevance to the game; they often include collectibles and consumables, since it's logical to assume that minigames are created by NPCs within the game, and would have prizes those NPCs could manufacture or buy in bulk.

A game's path of advancement in crafting ability is called a tech tree. The roots of the tree are the abilities the player begins the game with. The tree grows upward and branches out every time the player masters a current ability or builds a new piece of infrastructure which unlocks new abilities and/or crafting recipes. For example, a player may begin with the ability to pick up two rocks and bang them together. Initially there is a low chance of creating a stone blade, or the blade produced will be of low quality. But after banging rocks together 20 times the player masters the ability, meaning it permanently has the highest possible chance of success, whether this is 100% or slightly lower, and the blades produced are either of the highest possible quality or usually very good. More importantly, mastering the ability to make stone blades may unlock the player's ability to start practicing a more advanced skill, like making stone knives with handles. In turn, stone knives with handles may allow the player to skin killed monsters to obtain raw leather. Then the player may get to practice curing leather until they master that, which unlocks their ability to make leather armor.

Just as a tool may be needed to enable gathering, tools or larger-scale appliances or buildings may enable various crafting techniques. These tools, appliances, and buildings taken together are termed infrastructure. They are typically the result of crafting themselves, such as the knives just described – perhaps two knives can be crafted into a pair of scissors, and this tool is needed to unlock the crafting technique “fabric cutting” which is required for a whole range of clothing crafting recipes. For a building example, domesticated animals commonly require building an enclosure to keep them in, such as a pen for sheep or a barn for cows. In the rare event that a piece of infrastructure is not craftable by the player it is probably obtained from an NPC; it might be purchased or might be a quest reward.

NPCs are also a source of skills. Basic skills are often given away free, because the purpose of the player's interaction with the NPC is more to teach the player how crafting works in the game and where to find the relevant NPC than to pose a challenge. But basic skills don't have to be free, and non-basic skills rarely are. Just talking to an NPC isn't gameplay, the fun is in tackling a challenge. The NPC may name a test or price, in exchange for which they will teach the player a new skill. Or it can happen the other way around, with the character teaching the player the skill but keeping the first few results of that skill.

So, a tech tree is the map of all these skills within a game, and which needs to be learned to enable the player to learn the next. Designing a game's crafting system consists largely of creating this tech tree: both the recipes for crafting every item, and the conditions for unlocking each branch. In a pet game sometimes all of these skills are directly related to breeding or training pets. Other times pets are just one branch of a much larger tree, or may be broken up into multiple branches, like combat-companion pets vs. non-combat mounts which increase traveling speed vs. beetles which are bred to be ground up to make colorful paint from their shells. Sometimes the skills gained become part of the player of their avatar, sometimes they may exist within a pet, or sometimes they may exist within a piece of infrastructure.

Crafting gameplay can be as simple as selecting ingredients and then an action to be performed upon them, then possibly waiting for the task to be carried out. This is easy to implement and requires no skills from players; it's kind of boring as gameplay, though. Another option is that each crafting (or gathering) activity can be its own minigame. Any kind of minigame can be plugged in as a crafting step, though of course some will be a better thematic fit than others. Minigames aren't as appropriate for an activity where the results are binary (success vs. failure) or worse activities which are always successful. A minigame is much better-suited to an activity where the results are a range (minimal success, average success, perfect success; failure may or may not be included in the range). For example, it might require twenty units of ore to start a game of “smelting”, which might be a tetris-clone. Surviving level one would yield a minimum amount of metal from the batch of ore, while surviving many levels would yield more metal and maybe a bonus item, like one unit of a different metal or a piece of charcoal or a refund of some of the ore.

Get at least a general outline of the crafting system written down, but it's ok if you don't know all possible gathering and crafting processes yet. Specific minigame designs should go in the mini-game section, but we won't get to that for a while yet, so if you currently have ideas for minigames write them down and stick them into an appendix for later. Similarly, put any specific ideas for crafting items, tools, appliances, buildings, quests, etc. in an appendix. I haven't talked about prioritizing core features yet either; the basic concept is that the fewer features you need to create at first, the more likely you are to actually get to a point where the first (alpha) version of you game is playable. This is often a big boost for morale and recruitment, as well as a playtesting opportunity that can result in big redesigns. I mention it here because while you may want your main crafting system in the alpha feature set, you may want to postpone some portions of it and/or any secondary crafting systems to a beta or later version of the game. It's convenient if you have separate bullet points for anything you want to postpone, so it's easy to color-code them or move them into another section when you do your prioritization step.

- Crafting system(s) [Skip this section if your game does not have crafting of any kind, or note if you intend to postpone all crafting until post-alpha.]

- [Describe your game's (primary) crafting system: what are you crafting out of what, by what sort of gameplay?]

- [Describe the most common process by which gathering is carried out.]
- [Describe each additional process by which gathering is carried out.]
- [Describe the most common process by which crafting is carried out.]
- [Describe each additional process by which crafting is carried out.]

- [Describe each additional crafting system (it is additional if it has a separate tech tree). For example cooking is often separate from crafting gear. Note if you intend to postpone any of these until post-alpha.]

- [List the types of things which may be required to unlock a recipe or skill. Is the avatar's combat level a prerequisite (if your game has combat levels)? The avatar's property ownership level, if any? Is the avatar's gender, class, race, etc. a prerequisite? Do you want to have consumable items that teach skills? NPC quests? Tools which must be equipped (to what kind of slot?) or tools which must be carried in the avatar's inventory but don't need to be equipped?]


8. Trading, Shops and the Marketplace


This section is about the exchange of money and/or items between the player and the game or between two players. “Money” can be any kind of currency, not just bills or coins. Gems, tokens, tickets, pretty much anything can be used as a game currency. Many games have multiple currency systems with some kind of restriction or difficulty preventing the two from being directly exchanged. Or sometimes they can be directly exchanged but the exchange tax/fee is high enough to discourage doing this except in special cases. Secondary currencies are used to regulate the player's time within the game; for example if the player needs 1000 casino tickets for an item they can't buy with the main currency, this encourages the player to spend enough time playing the casino minigame(s) to earn that many tickets. If the casino did not have unique rewards some players would spend little or no time playing the games there; not necessarily because the games weren't fun, but because min/max calculations told the player it wasn't the most efficient way to earn money. The players would then get bored with the game as a whole faster because they aren't experiencing the full breadth of its content. Another common example of this is PvP reward tokens which can be spent in a PvP rewards shop. Cash shop currency is a special case of a secondary currency, with the purpose of encouraging the player to contribute real money to the game in order to immediately get things that would otherwise be impossible or a lot of work for them to get within the game.

The most basic use of currency in a game is the NPC shop, which allows the player to purchase items within the game. Most literally, this is a storefront presided over by an NPC, who is ostensibly the one receiving the player's money, and adding new stock to the store as the game progresses. Functionally, NPC shops can include vending machines or automatic stores which have no NPC, and can also include NPCs which sell or exchange items or tickets but have no physical store. A simple NPC shop works like so: There is a button showing a picture of an item, and it's price. The player clicks the button to buy the item, or drags the item onto their inventory. The game checks if the player has enough money, and if they don't, an error message says so. The game checks if the player has enough room in their inventory, and again an error message will warn the player if they don't. If the player has enough money and space the item is added to the player's inventory and the money is subtracted from their wallet/money pouch/whatever the game calls the player's stock of money. Optionally you can add a step in there asking the player if they are sure they want to buy the item, or would prefer to cancel the transaction. Another option is to allow the player to buy multiple of the same item at once, by selecting or entering the quantity they want to buy. The game does multiplication to find the total price, then the rest of the transaction proceeds as usual.

An NPC shop can also allow the player to sell unwanted items back to the game. Sell-back prices are typically half or less of the shop's prices if it sells the same item. In a marketplace system sell-back prices effectively set the minimum price for which a player will sell an item to another player. Selling is just like buying in reverse – either items in the players inventory need to have sell buttons and prices, or dragging an item from the inventory onto the store should give the option to sell it. Optionally some games keep track of the last six or so things the player has sold, in case the player wants to buy them back. Some items may not have sell-back prices. They may be discardable, either by dropping it on the ground or by using a trashcan option in the inventory, but the player can't get money out of them unless they are able to trade the item to another player.

Trading is any exchange of money or items between players. As such it is not relevant to games which have no multiplayer features. (Buying from or selling to an NPC doesn't count.) Some multiplayer games do not allow this kind of exchange between players. The purpose of this may be to avoid complaints about accounts being hacked and trade-scamming, or simply because trading is off-topic to some kinds game, like those where the player has no permanent inventory or equipment; they may own items during minigames or duels, but they don't retain those items after the minigame or duel ends.

If you do want to have some kind of trading mechanism, there are two ways to make this kind of exchange relatively scam-resistant. The two methods are direct exchange (with double approval) and exchange through a shop or market, (with two-step single approval). Approval is simply when the game asks a player, “Are you sure you're okay with this?” and shows them the details of the trade they are agreeing to.

Direct exchange requires one player to click on the other's avatar or name. Some games limit direct exchange to those in the player's friends list, though I don't personally see the point of this. I suspect the idea is to discourage trade-scamming, but I don't think it actually works. Double approval is when both players add money and/or items to their side of the trade, commit to what they have put, then once both players have committed to their side, both must give their approval to finalize the trade. It's common for players to use their side of a trade to display a range of items they have available for sale, and even to show off items they have no intention of trading. For these uses it's important that they player not accidentally give away the items they are just showing. It's also common for players to add items and money to their sides in stages as they continue to chat and negotiate the trade, so it's good to allow this, and not make the trade window auto-close if the players are taking a while or the money portion be unable to handle simple addition and subtraction. Some trading interfaces include a mini 4-function calculator. The disadvantage of this type of trade is that it requires both people to be online, and some versions require the players to be standing next to each other. Also there is no way to automate offering the same trade to multiple people.

Exchange through a shop or marketplace solves the problem of players wanting to trade offline or in batches. But it is less flexible than a direct trade, because most systems don't allow mixed batches of items to be sold, nor items to be sold for anything but money. A few games have a barter system which does allow trade lots and allows the player to describe the general kinds of things they want in exchange. Barter systems are interesting but I think they are ultimately a dead end in economic evolution, which is why no one uses them in real life any more. I don't recommend adding one to a game unless it seems to fit extremely well with the flavor of the game (such as a game which chooses not to have money at all to create the feel of an ancient economy). Shops and marketplaces both use 2-step single approval: the first step is when the seller player specifies what and how many of the item they want to sell. For a flat sale they also specify the price and how long the item should be listed for sale before being delisted and returned to the player (unless the game lets sales last forever unless the player cancels them). Or for an auction they specify the minimum bid, the bid increment, and possibly an autobuy or reserve if the system has those. The seller player looks at all the information and approves it, though they may still have the option to cancel a listing if no one has bought it yet, or bid on it if the item is being auctioned. Then the buyer player looks at the item for sale and the price asked or the price they can bid, and approves that.

So what is the difference between shops and marketplaces? Personally I hate player shops, but I'll try not to be biased here. A player shop gives the player a personalized area in which they can sell multiple items for prices they specify. Some games require the player to be offline, or worse, online but idle, in order to be in shop mode. Most games don't allow prospective buyers to ask the game where they can get the cheapest currently-available one of an item they want; instead they have to look at one shop after another, hoping to find the item they are looking for at a reasonable price. So player shops are inconvenient for both buyers and sellers. The main argument in favor of player shops is that they are a realistic exchange system for a low-tech culture. An additional factor is that some players look at a player shop system and would prefer to use it like a display case instead of actually selling anything, which results in items being listed for sale at ridiculously high prices because no one is intended to buy them. That's just messy and can frustrate buyers. This can be worked around by offering players a display-case or collection gallery system which is better-suited to the purpose than a shop system. If you want some kind of player display system, I'll talk about those in the Player Property and Housing section.

Marketplaces, by contrast, have all sorts of convenience features like searching by keyword, browsing by category, sorting by price or item quantity, and the ability to choose an auction sale type in addition to a flat price sale type. In some games players must visit a physical location or NPC auctioneer to access the marketplace, while in other games it is accessible from anywhere through a menu or GUI icon. Marketplaces enable some interesting economic gameplay, like attempting to buy up all of an item to create an artificial shortage and inflate prices, then sell the hoarded items at a profit. This is illegal to do in reality, but that's no different from attacking other people with bladed weapons, stealing cars, and other things that are fun in games even though they aren't allowed in the real world. Some games try to discourage this sort of market manipulation with auction fees or other sales taxes; I'm not personally in favor of taxing marketplace use, but it's a legitimate design strategy and realistic place to put a gold sink, so it works well in some games.

Trading cash-shop currency. Many games do not allow players to trade cash shop currency, possibly because they think they will sell less cash-shop currency this way. I think it's actually the opposite; it's very difficult to convince a player to make their first purchase of cash-shop currency, but someone who is already inclined to buy cash-shop currency for their own uses can be easily convinced to buy more by the opportunity to exchange it with other players for items or in-game currency, or use it to gift other players with cash-shop currency or cash-shop items. Trading cash-shop currency is especially useful in games where many items purchased from the cash shop are soulbound to the purchaser and can't be traded at all. (The purpose of this is to ensure that players buy new ones instead of passing the same ones around from player to player within the game for years, and the same applies to games where all crafted gear is bind-on-equip).

Mail. Some games allow sending money or items through the mail (otherwise known as the private message system). This is not a trade, since nothing is received in return. This is useful if a player needs to send items from one character on his account to another, since it's (usually) impossible for the two to be online at the same time. It's also a convenient way for the game to send an item to the player, such as returning an item that failed to sell on the marketplace, or giving the player a holiday gift or subscription reward.

- Money System [This is applicable to both singleplayer and multiplayer games; only skip it if your game has no currency whatsoever.]

- [Describe the primary money system: What is the currency called? What denominations does is come in? How does the player earn this money? What is the player intended to spend this money on? Is there any special story explanation behind this currency?]

- [Describe each additional money system, if any]

- NPC-Owned Shops [This does not include quest-givers which give or take something from the player in a one-time exchange.]

- [Describe the shop use method and GUI.]

- [If possible, list each specific NPC owned shop and describe the range of items it sells. But if there are a large number, just describe an example one and put the rest in an appendix.]

- Trading System [Skip this if your game has no trading system. This is only trades between two players].

- [Describe the trading method and GUI, any restrictions on trading certain types of items, and any fees or taxes on trading.]

- Player-Owned Shops [Skip this if your game has no player shops].

- [Describe how they work.]

- Marketplace(s) [Skip this if your game has no marketplaces where players sell items to other players. Simulated markets where all items are supplied by the game go under the NPC-Owned Shops category.]

- Flat Sale Method [If your game has this, describe how it works. What parameters can the player set, such as sale duration, lot size (quantity of items), price per item or price per all items. Are there any fees or taxes on flat sales?]

- Auction Method [If your game has this, describe how it works. What parameters can the player set, such as minimum bid, bid increment, auction duration, lot size (quantity of items), reserve, autobuy, etc. Are there any fees or taxes on auctions?]

- Browsing Structure [This should be based on your description in part 6 of what item types there are in the game. Cash shop currency may be an additional item type.]

- Sorting and Filters [How can the player narrow down to only the sales they are interested in and prioritize them for convenience? Lowest price per unit and ending soon are probably the two most popular ways to filter sales. Gear by level equippable is also popular.]

- Search Feature [The player might like to search for all gear of a type, all gear for a class, all clothing that is a particular color, or an item that they only remember part of the name. It's common to want to combine two search criteria.]

- Delivering items to buyers and returning unsold items to sellers. [How does it work?]

- [If there are multiple marketplaces that actually sell different stuff or work differently, describe each.]


9. Forums, Messaging, Chatting


Purely singleplayer games, of course, have no need for a forum or messaging system. Games with minimal multiplayer may have the messaging system without the forum; usually in this kind of game the purpose of the messaging system is to send gifts and friend invites or PvP challenges to other players, and optionally the player can type a message to go with this. If your game is part of an existing social network or game stable, they may already have a system in place for this kind of thing. Similarly game stables often have a forum in place outside any of the games where they will create a new subforum for any new game in the stable. And of course there are many free services that will let you make a forum if you are trying to get your game going on the smallest possible budget, though it's not extremely professional looking for a finished game to be using one of these free boards. If you are recruiting a team of volunteers one of these free forums can be helpful to have as a place where team members can talk about developing the game with all conversations being preserved for future reference and there's no need to schedule everyone to be online at the same time. For some purposes or some types of people a voice chat or text chat room may be preferable, and the benefit of real-time communication may outweigh the scheduling difficulty.

One of the few areas of game design where pet games have actually been pioneers is in the incorporation of forum-posting physically into the main game and functionally into gameplay. VPSes and the closely related genre of social gaming sites are some of the only places where game avatars are automatically used as forum avatars and forum posting is rewarded with game currency, as well as a way for players to negotiate trades and other cooperative activities within the game. Some of these sites also make chatrooms available to their players; this part is a traditional feature of MMOs, existing in even text-based MUDs and MUCKs before they evolved into MMOs. (Chat has also long been a feature of networked PvP board games and strategy games.) There may be a chatroom for the whole game, a chatroom for a physical area within the game, a chatroom for people waiting for PvP matchups or trying to recruit a dungeon party, a chat room for each guild or faction, a server for private voice chats within the game, etc.

Private Messaging (aka mail) is usually handled by using the forum system. A private message (note, mail, etc.) is no different from a private forum post that can only be viewed by the sender and receiver. I'm particularly fond of approaches where replies to and from the same pair of people are displayed as a thread, rather than a list of separate mails. Some share a copy between these two people, such that if the sender edits the message after sending, the copy in the receiver’s inbox will also be changed. Other systems do not allow messages to be edited after being sent, and may generate a second copy of the message for the receiver (while the original copy goes in the sender's sent box). Some systems have various storage limitations, such as automatically deleting stored messages that are a month old, not having sent boxes, or not saving sent messages unless the sender checks a check box on each individual mail. These economizations are mildly annoying to players, but players may also indirectly benefit from the system not having to deal with storing as much data, so it's pretty much a judgment call.

Some private message systems incorporate the ability to send one or a few items attached to a message. If you want a private message system but not a forum, then you might instead take the approach of starting with the trading system and adding the functionality to comment on an offered trade. An invite or similar request is like sending a trade where instead of an item a clickable link is displayed, which runs a little script to carry out the friend list addition or other request. It's also possible to have private chat messages sent through a chat system as a main private message system instead of anything more like a forum post or email.

There are various commercial forum softwares available, most of which come with a private message system included but may or may not have good chat functionality. Vbulletin is a widely-used example, and one of several that use the UBB standard. I haven't looked into free opensource forum softwares but there probably are some. It's possible to create your own forum system, but you are re-inventing the wheel; I don't recommend attempting it unless you really need your forum to have some features that you can't adapt a commercial software to have. GaiaOnline is an example of a social site that made their own forum software and has integrated several custom features into it over the years, starting with the way players earn money by using the forums and their avatars are displayed by their posts, and then adding signature image automation and regulation, adding the capability to display a car or fishtank, making the banner across the top of the forum interactive, and various temporary forum modifications for events. But the core of their forum software isn't very good, which is most easily visible in the fact that some of their subforums are almost impossible to use due to not handling high traffic well and not supporting thumbnail images beside thread titles. DeviantArt is another example-of a well-known website which made their own forum software and ended up with featureless, user-unfriendly forums. Chat clients are somewhat easier to implement yourself, but again there are an assortment of commercial and free ones available, both closed-source and opensource, and some of them will be more featureful and user-friendly than anything you could make without a lot of time and effort.

So, as a designer you mostly need to plan which of these communications systems you want and how you want to integrate them into the game. Do you want your forum to be usable when your game itself is having server maintenance? If so then you have to plan for them to not be hosted in the exact same place, and probably for user log-ins and money earned from forum use to be hosted separately from the main game.

- Forum(s) [skip if you don't want one]

- [Describe what you want the main game's forum to be like – is there any kind of censoring system, can players block themselves from seeing posts from specific other players, do players earn money for forum use, can players include links and images in their posts, are signature images or text allowed, are forum avatars the player's avatar or something else, does the information below the avatar contain links to a player's collections, property, guild, a view of what items are equipped on the avatar, etc.]

- [If you want to have private forums, such as for guilds or private roleplaying, describe how those should work, such as whether players can have moderator abilities over private forums or threads they create, whether the visual themes of private forums are customizable by players, whether rules about images or signatures are different from those of the main forum, etc.]

- Private Message System [skip if you don't want one]

- [Is this done using the forum software, trade interface, an external network, or something else?]

- [Describe how you want it to work – can items be sent, are sent messages stored, are they editable, can messages be sent to more than one recipient, is there a length limit, do you want to have some automatic message types such as requests, etc.]

- Chat [skip if you don't want one]

- Text Chat [What channels or rooms are there, is there censoring, can emotes be used, are urls automatically made clickable, can clicking an item in your inventory create a link to that item's info in chat, are there different rules for private chats, etc.]

- Voice Chat [If you are providing this, describe what you want to provide.]


10. Pets In More Detail: Functionality Within The Game, Capturing, Breeding and Genetic Systems


As you may have noticed, I've been using a very loose definition of the term “pet”. Basically, I think any interactive animate being the player owns or controls can be considered a pet. That vague definition includes humans, which wouldn't normally be considered pets, but in games like the Sims they certainly function like pets. Pets function so differently across the spectrum of games that any more narrow definition would exclude some pet games. But, if you would prefer to define pets a bit more narrowly, that's fine, because this section is all about narrowing down which type(s) of pet you want in your game!

Some common kinds of pets:


Avatars As Pets – The most minimal element that might justify calling something a pet game is when the playable character looks like an animal or monster. This would include all games where the player is a puppy, horse, dragon, etc. The playable character does not act like a pet

Vanity Pets and Transformations – Vanity pets are the simplest kind of pet because they have no gameplay functions aside from character customization. In other words they are just there to look pretty following the player's avatar around or living on the player's property, thus the term 'vanity'. In some cases they may have minimal interactivity, such as needing to be fed or occasionally saying randomized dialogue. They typically wander around a bit, though anchored to the player's avatar or to a placement point on the player's property. Or they may wander around inside a tank or pasture. Transformations are when a normally human avatar is shapeshifted to look like a pet, but this does not affect the way the avatar functions (emoticons or chatting might be affected, but those are also 'vanity' elements). Sometimes vanity transformations are the lowest level of something upgradable into a functional traveling form or combat form.

Mascots – This is any kind of companion character that gives the player feedback on their actions. Clippy from Microsoft Office, Navi from the Zelda series, and Issun from the Okami series are some examples of this 'helpy' type of pet. By 'companion character' I mean an NPC which follows the player around, is a part of the game's GUI or always available via menu, or pops up regularly to deliver tutorials, tips, and/or narration. A mascot may function as a tool, such as a compass, radar, grappling hook, digger, or backpack-carrier. Perhaps the most developed case of a mascot-type pet ever is the blob from game A Boy and His Blob – this was originally an NES game but a new version is currently available as a wii game. This is a puzzle game where the pet blob functions as a swiss army knife of tools used to help the avatar travel through the level.

Mounts and Traveling Forms – This is any pet used as a vehicle in a way which is more than just looks – the creature must actually increase the avatar's speed or be capable of movements the avatar is not, such as jumping, swimming, or flying. In some games (many racing games for example) the avatar is not capable of moving at all without their vehicle. A mount is a pet the player sits on or is otherwise carried by; a traveling form is a shapeshift which transforms the player into the pet. An interesting classic example of pets as vehicles is the NES game Little Nemo the Dream Master; this game is a platformer with many puzzles that must be navigated by using different pets as vehicles, each of which have different abilities. Mascots are sometimes usable as mounts or transformations

Infrastructure Pets – These are pets which produce or process resources. Cows produce milk, sheep produce wool, hens produce eggs, and various animals produce manure, feathers, pearls, or fantasy resources like gems and mana orbs. Beavers might process trees into logs or boards, fire-breathing dragons might process ore into ingots or wood into charcoal, hens might incubate dinosaur eggs to hatch them into dinosaurs; the possibilities are infinite. Infrastructure pets can even include alien or fantasy creatures which function as buildings or furniture. Typically infrastructure pets are found in sim and RTS games, though they would work in any game where the player has a “home base” which they upgrade between missions.

Combat Pets and Combat Forms – This is any pet which which increases or alters the player's abilities in combat. The creature may fight alongside the avatar, fight under the direction of a non-fighting avatar, be equipped onto the avatar as a weapon or armor, or be a transformation of the avatar. This includes all Pokemon, all Monster Rancher monsters, all creature units in tactical combat games, all pets of the Hunter and Warlock Classes in WoW, all non-vehicle transformations of the Druid Class in WoW, and vehicle pets which also have combat abilities. The most common kind of pet in games which have combat.

Capturable Pets – The flip side of combat pets, these are creatures that fight against you. (They often turn into combat pets after you capture them, though they can also turn into infrastructure pets or become available as shapeshifts.) There are two main dynamics of capturing pets – either you fight them to weaken them then must capture them before they are quite dead or run away, or you must NOT fight them, instead distracting them with bait or getting them to chase you into a trap or enduring their attacks while you wait for your capture spell to be cast or a tameness meter to fill. It's also possible to have capturable pets in a game with no combat – they might be randomly encountered while exploring and captured by paying money, using a consumable item such as a net or collar, or playing a minigame where a sufficiently high score is needed to capture the pet. Capturable pets occur mainly in RPGs.

Collectible Pets – Games with collectible pets are also called “Gotta Catch 'Em All” games. They typically give the player quests or achievements for accumulating numbers or sets of pets, and keep track of the first time the player collects a pet of each type in a book or list. Pets can be obtained either by capturing or by breeding, and this kind of pet occurs mainly in RPG and sim games. Pocket Frogs and Fish Tycoon are two examples of collection by breeding instead of capturing. (Plant Tycoon is a similar game with somewhat different/improved features, if you consider plants to be pets). But unfortunately, neither of these games are good examples of a collection quest/achievement system. Monster Rancher is slightly better – it keeps track of your discovered pets in a book and notified you when you have found a new one. Still no quests or rewards for breeding though.

Breedable Pets – Breeding pets can be a large portion of the gameplay in some pet games. In some games the player may be breeding pets of specific appearances to sell to customers, either by filling an NPC's order or in a pet shop where each type of pet has a set price. In other games the player may be breeding for stats, related to combat or competition. The game does not actually have to contain competitions; Celebrity Pedigree is a game where pet quality is measured in stars, and the overall goal is to have a certain number of 5-star (maximum quality) pets. The game's theme implies that the pets are competing as celebrities in the entertainment industry, but they presumably are entered into this competition by their new owners after you sell them.

Craftable Pets – Aside from breeding or capturing, pets can also be produced by crafting. For example an artificer might build clockwork and golem pets, or a mage might gather spell ingredients to summon a mythological pet with a magic potion or ritual, or a sci-fi toy factory might assemble pets on an assembly line. Less literally, an NPC might give a pet to the player in exchange for a batch of ingredients or crafted items. Craftable pets would be especially suited to time-management games, where the player would run their avatar around at top speed to efficiently gather the crafting ingredients to fulfill pet recipes. But craftable pets could occur in a sim, RPG, etc. Craftable pets can be combined with capturable or breedable pets if the pet captured or bred is a basic type which can be developed into a more advanced type.

Consumable Pets – These are creatures which, once captured, bred, or crafted, can be used once or a set number of times to give some particular stat bonus, work, or other assistance to the player. The fairies in the Zelda series which can be captured in bottles and stored until the player needs to be healed are consumable pets. In a game where the character is a summoner, summoning a pet into combat might consume it or wear it down.

More About Genetic Systems:


Any type of pet which is breedable needs to have some type of genetic system. This may, but does not have to, bear any resemblance to real genetics (which IMO don't make for great gameplay). Sometimes it bears a resemblance to the discredited concept of Lamarckian inheritance instead – this is a system where offspring inherit a stat bonus based on their parents' training and accomplishments, instead of their parents' genetics. This is nice, gameplay-wise, because it means that successive generations of the same type of pet can reach slightly higher ranks of competition (or whatever) before they must be retired (assuming the game has pet aging). It's like a “new game plus” for individual pets. Many pet breeding systems do not have pet gender, because it simplifies things for the player if any pet can be bred to any other pet (sometimes including itself) and if there are no sex-linked genes or non-genetic appearance variation by gender.

Genetic systems can be about appearance only, stats only, or both. The stats part is pretty simple – a type of pet may have a basic set of stats with possible bonuses from inheritance, or an individual pet's stats may be entirely determined by its parents' stats, with minor randomization. Often the genetic process is slightly biased in favor of offspring getting good stats. So, for example, if HP is one of the pet's variable stats, the genetic algorithm could average the HP stat of the two parents, the randomly choose a value in the range from (average – 20%) to (average + 35%). Or if that type of pet had a base HP stat, you would subtract that base from the average, randomize as above, then add that back to the base. That's just one really basic example – there are all sorts of ways to design the math behind inheritance in your game.

Appearance inheritance systems can be done in three ways:

The first way is that there are set pet shapes, but each shape can come in different colors. So a red pet of type A and a blue pet of type B could be bred to result in a blue pet of type A, among other combinations. In some cases purple pets might also result from breeding a red pet with a blue pet. In a 2D bitmap/raster system the pet shape would consist of a lineart layer (unless it's a lineless art style), coloring layers, and shading layers (each layer would also have a layer mask, with the possible exception of the lineart layer. The pet's color would be changed by bucket-filling or mathematically rotating the color layers. The final sprite is flattened and saved as a PNG file with transparency. In a 2D vector system there are no masks and each color-area is its own object on its own layer. But the basic principle is the same, an image built up from color fills and areas of shadow and highlight. The color can be changed by bucket-filling but it's more efficient to do it mathematically, with the search-and-replace function. For example you can tell the vector graphics program, “Replace all areas of color #FF0033 with color #AA00FF.” The final image can be an SVG file or can be flattened and exported as a PNG. In a 3D system the pet shape is a model and the color is a texture or procedural color applied to it. For the final version the model and textures can be stored separately in any of several file types and combined by the game engine, or the model and texture(s) can be bound together, or the textured model can be rendered to a 2D sprite.

A second way of doing appearance inheritance is having body parts with set colors which can be mixed and matched. The 2D version of this system, whether bitmap/raster or vector, is called a paper doll, and is the same kind of thing as a 2D avatar clothing system. Each body part is an image file and the game assembles them in a predetermined layering order. (For clothing the game might let the player choose the layering order, but this is unlikely to be useful for pets.) The 3D version of this system divides the model into smaller models, each of which has its own texture.

The third way combines the first two – the pets have both mix-n-match body parts and a genetically determined color scheme. Some systems have one or two colors (main and accent) for each body part, but the results may look nicer if the color genetics determine a scheme of 2-4 colors for the whole pet and this scheme is applied to the body part shapes selected. Really sophisticated 3D systems like that in Spore can have the body part models be adjustable and the connectors between them generated procedurally, instead of both the body parts and connectors being of predetermined size and position.

Appearance inheritance is a bit less math-friendly; in some cases you might need something more like a spreadsheet or some rules expressed through if/else programming loops (or whatever your programming language of choice calls them). I mean, you can convert colors into hex values and then do math on those, but that can be ugly, in more ways than one. And converting body parts into numbers is also dubious, unless you are talking about numbers for dominance and recessiveness, which only apply to polyploid systems (systems where each creature has two or more sets of chromosomes). Many pet systems are monoploid for simplicity, because in a monoploid system genotype is always the same as phenotype. If you did not understand that sentence you would have to go study genetics before you would be able to design a realistic genetic system. Having a set color palette of somewhere between 10 and 40 colors that pets can come in, and/or a list of shapes each body part can come in, is my personal favorite approach.

Example color palette spreadsheet:

WhiteL. BrownL. OrangeL. RedL. PurpleL. BlueL. GreenL. Yellow
GrayBrownOrangeRedPurpleBlueGreenYellow
BlackDk. BrownDk. OrangeDk. RedDk. PurpleDk. BlueDk. GreenDk. Yellow

The top, middle, or bottom row is determined by a brightness gene which can be A, B, or C. Assuming the system does not have dominance and recessiveness, the inheritance algorithm could look like this:

A + B = 50% A, 50% B
B + C = 50% B, 50% C
A + C = 25% A, 50% B, 25% C

The color inheritance rules would be a bit more complex:

Orange + Red = 50% Orange, 50% Red
OR 25% Orange, 50% Brown, 25% Red
Orange + Purple = 25% Orange, 50% Red, 25% Purple
OR 25% Orange, 25% Red, 25% Brown, 25% Purple
OR 100% Brown
Orange + Blue = 30% Orange, 30% Blue, 10% each other color excluding brown and gray
OR 25% Orange, 50% Gray, 25% Blue
OR 100% Gray
Brown + Brown = 40% Brown, 10% Each other color excluding gray
OR 100% Brown

There are many, many other ways this could be done. For an utterly different but still monoploid genetic system you could google a walkthrough of Plant Tycoon, and there are other walkthroughs and wikis which explain the breeding systems in various games. I just wanted to give an example of what genetic algorithms might look like. Now lets finish up with your features' list entry for this section:

- [For the primary type of pet in your game, which category(ies) do they belong to?]

- [Describe how the pet's functions within game fit primary category.]

- [Describe how the pet's functions within game fit each additional category.]

- [For each additional type of pet, which category(ies) do they belong to?]

- [Describe how the pet's functions within game fit primary category.]

- [Describe how the pet's functions within game fit each additional category.]

- Pets inherit [appearance, stats, both, or skip this section if there is no inheritance]

- [If there is stat inheritance, how does it work?]

- [If there is appearance inheritance, how does it work?]

- [2D bitmap/raster, vector, or 3D]

- [set forms or mix-and-match body parts]

- [set colors per form or body part, standard palette of colors, numerical]


11. Tutorials, Quests, Reputation, and Levels


Playing a game is all about having interesting stuff to do within the game. So what exactly do you intend your player to be doing within your game? Game design philosophy is divided into two camps, those who favor sandbox play and those who favor structured play. I prefer structured play, myself, because I like the experience of being given assignments with rewards attached. In my experience structured games do a better job at being fun in the same way a novel or movie is. In a story the main character's goals are what drive the character to strive against their opponents, make progress through the plot, and better themself as a person. Goals create dramatic tension and also help give the player a sense of their role within the social and philosophical context of the story. Not that all structured games have story, but in games without story a structured sequence of goals first helps teach the player how to play and after that continues to guide the player through all of the game's content in a sequence that makes it feel intuitive to tackle each new challenge; sequence also regulates the pacing of the player's experience, helping avoid either long stretches where nothing is new or overwhelming floods of too many new things at once.

Though they are not my personal cup of tea, I'll try to give a fair description of why sandbox fans like that kind of game. Sandbox games are more toy-like than structured games, and their design often takes inspiration from toys like building blocks and Legos, doll houses, train sets, science experiment kits, and the namesake of this kind of game, sandboxes with their associated sand-shaping tools. They are fun in the same way that playing with blocks and dolls is. This type of game is supposed to support the players in choosing goals for themselves and telling stories to themselves. (Whether most existing sandbox games are actually any good at asking the player what goals they choose or giving positive feedback to the player for accomplishing those goals, well...) Sandbox games are compatible with player-created content, which in turn can be a strong part of participating in a game's community. One goal of sandbox game design is enabling emergent gameplay, where the players can use the pieces provided by the game to build more things than the designers ever dreamed of. Sandbox games can potentially provide a more free and realistic experience than the scripted dramatic experience of more structured games.

Tutorials, quests (or achievements), reputation, and levels, while more characteristic of structured games, are all allowed in sandbox games too; it's more about how you use them. Sandbox games pretty much should not have required content and should have limited amounts of sequential content. In a sandbox game tutorial and quests, if present, should not get in the player's face but instead be available as optional activities that can be done whenever the player wants help or feels bored and is looking for an idea for want to do next. Reputation and levels, if present, should also be like optional quests – the player can decide they want to work specifically to earn these because of associated benefits, but it shouldn't prevent the player from playing the game if they are not interested in pursuing these.

In a more structured game, tutorials aren't just about explaining how the game works to the player – they are also the first impression the game makes on the player, and everyone knows how important first impressions are. In the realm of fiction-writing people always talk about hooks and contracts with the reader; these things apply just as much if you substitute 'player' for 'reader'. A reader will start reading a book or a player playing a game because something external to the book/game has caught their attention – it may be that an acquaintance is playing the game, or a reviewer has reviewed the game, or the book/game has attractive cover art and a title that suggests the content is something the reader/player would enjoy. Once the audience gives the book/game that first minute of their attention, that's where the hook comes into play. The book/game needs to give the reader/player a feel for why its world is an interesting one to spend time in, give the reader/player a glimpse at some impressive things they could accomplish if they play a while, and then immediately give the player a task that gives them a taste of the gameplay and how that gameplay is interesting and satisfying. This taste of the gameplay is the contract with the reader(player). The rest of the game should be relatively consistent with this sample so the player doesn't feel like they've been the victim of a bait-and-switch.

In a sandbox game glimpses of impressive future possibilities and initial educational tasks might be presented in a more exploratory manner. If the game has NPCs, it's common to have low level NPCs standing around playing with some of the in-game elements, and high-level NPCs with fancy armor and architecture serving as living examples of what the player might choose to strive for. Talking to them might give the player an option to listen to that NPC explain what they are doing. Of course players of a sandbox game come into the game expecting to explore and experiment; they look at the mouse pointer and GUI options for clues and poke anything that looks interesting in a way other gamers aren't conditioned to do or aren't interested in doing (adventure gamers might be an exception). But still, in many games there are objects that it's just not obvious how you use them. Error messages are a pretty good solution to this. For example, say there are large rocks in your game and the player tries to gather one. This action shouldn't fail silently, or worse insult the player without specifying what they are doing wrong. (Humorous insult error messages can give a game character, but they should be helpful too.) Instead it's important to have helpful messages like, “You need to break this into smaller pieces before you can lift it.” or even more directly, “You bang the hammer on the rock but nothing happens. Maybe if you had a chisel...”

What is a quest or achievement? Level requirement and mission objective are more terms for the same thing. Basically this is a task that you assign to the player. You can present the task through an NPC (including a mascot pet), through a building acting as an NPC (schools are commonly implemented this way), through a found or activated object like a scroll, bulletin board, or obelisk, or through a menu-accessed list. Typically the game maintains a list of all quests the player has accepted or been mandatorily assigned, including the dialogue or written text that the player heard or read when first presented with the quest. This quest tracker may contain additional help, like information about where necessary objects can be found on the map, how many necessary items are currently in the player's inventory, or how many specified tasks have already been done.

Common quest types include:

- Kill X of monster Y
- Kill monsters of type P or Q until they drop X of quest item Z
- Go to location A and talk to NPC B
- Obtain X of item C and give them to NPC D
- Craft X of item E
- Grow X of crop F
- Tend a pet of type G X times
- Own X of pet type H
- Get a score above X on mission/competition I
- Win X missions/competitions
- Perform complicated combo J for the first time

What is reputation? This is when an NPC or faction of NPCs want the player to do tasks for them or tasks they approve of, and the game counts the number of these the player does to determine how friendly the NPC or faction is to the player (and sometimes how hostile an opposing faction or enemy NPC is). In a dating sim the reward for having a strong relationship with an NPC is having that NPC requite your love. In a more platonic situation an NPC who is very friendly may sell you rare items or give you discounts if they own a store, or may allow you to recruit them if it's a tactical game or adventuring-party RPG, or may teach you secret crafting recipes and techniques, not to mention that you may unlock more advanced quests from this NPC. A faction is similar – they often sell special items or discounted items, teach advanced recipes and techniques, and offer advanced quests to a player who earns a high rank within that faction. Faction tabards (outfits), tattoos, and mounts are some of the most popular faction rewards in MMOs, as well as ranks or graphics which decorate the avatar's name.

Levels are something everyone has encountered, but should your game have them? What is their purpose and how do they work? Well, levels measure the amount of time a player has put into a game. (This can get fouled up if you have major gameplay types that don't generate XP, unless this is balanced by them generating more money or other benefits than XP-producing activities.) Some games have separate level systems for different types of gameplay, such that a player might be a level 12 crafter, level 10 fighter, or a level 20 PvP-er, level 17 PvE-er. Levels have a secondary function of helping the player select battles and quests of appropriate difficulty, while still allowing them to select easier ones if they find the game difficult or harder ones if they find the game too easy. Leveling-up commonly rewards the player with an energy/health/mana refill, gives them stat or ability points to spend, and unlocks new quests, abilities, purchasable items, and sometimes new areas of the game or new areas of personal property (for the player's garden/ranch/house/town).

It's common for levels to be quick and easy to earn at the beginning and slower as the game progresses; however one of the most common mistakes online games make is stretching the interval between levels so far that players get bored and frustrated with their inability to advance and stop playing. I instead recommend setting a standard amount of time leveling-up should take starting at around level 20; or in terms of time, gaining a level should never take more than 2 days of intense play or 5 days of casual play (about 10 hours). In an RPG with classes, class balancing also needs to take this into account – if one class takes longer to kill the same monster, that class needs to either need less XP per level or receive more XP (and loot) per monster.

There are two functional ways to hybridize structured gameplay with sandbox gameplay: alternation or blend. Alternation would mean that the player gets to spend time in a sandbox area in between missions or levels. This is common for tactical, RTS, tower defense, and speedpuzzle campaign games. Blending is when structured content and sandbox content exist in parallel; for example the player might have to complete the next quest or mission in a linear progression to advance the plot, but the player can take a break whenever they want to do non-linear sim or minigame activities, which might even give rewards that made it easier for the player to get past a difficult quest or mission. Most MMOs are a blend, which is one of their major differences from singleplayer RPGs, which tend to have few or no sandbox elements. When singleplayer RPGs do have sandbox elements they tend to be minigames, and are usually all locked at the beginning of the game; the player must unlock them one at a time by progressing through the main plot. Well known examples include The Gold Saucer in Final Fantasy 7, Triple Triad in Final Fantasy 8, and fishing, snowboarding, battleship, archery, etc. in the Zelda series. Of the pet-themed singleplayer RPGs I've seen, those that have minigames tend to use them in a structured way instead, as required activities to train the pets, or as contests that only occur at certain times in the plot.

- Gameplay Experience: [Structured, Sandbox, Alternating, or Blended?]

- [Describe how the major activities in this game create this type of experience.]

- [Describe your game's tutorials and how they teach basics]

- [Describe how content near the beginning of your game acts as a teaser/contract with the player.]

- [Describe your game's quests & etc. if any]

- [Describe your game's individual NPC reputation system, if any.]

- [Describe your game's factions and their reputation system, of any.]

- [Describe your game's leveling system, if any, and what type of things it rewards.]


12. Combat


Combat is the single broadest area of game design. Some games do not have combat at all, but a large percentage do, and in a large number of varieties. The simplest kind of combat is random combat: flipping a coin, rolling a die, or rock-paper-scissors. This is not satisfying, because even if the player chooses heads or tails (or whatever) that choice doesn't matter. There is no strategy. Even the first generation of primitive games rarely bothered with completely random combat. Instead programmers invented AI, which is programming telling enemies how to react to the player's actions (or changes in their environment). AI is the source of strategic challenge in singleplayer games. That most basic strategy consists of studying enemy AI to be able to predict what you should defend against or how you can manipulate enemies into making themselves vulnerable. (In some cases the player will have one or more AI-controlled ally creatures, which it is also strategically advantageous to be able to predict the behavior of.) Completely predictable AI is also rather boring, because once you solve the initial strategic challenge you don't need to think any more, just repeatedly do what you decided was the most advantageous. So, many AI systems add a moderate amount of randomness to spice things up a bit. This is realistic, because random variation occurs in real life combat (or other activities that AI can direct an NPC unit to participate in) and randomness is certainly easier to add than more complex AI (which wouldn't even have fit in the oldest games due to storage space restrictions on floppy disks and cartridges).

Even today, it is still unknown whether it will ever be possible to create an AI that can simulate realistic human behavior, though some amazing AI programs have been created to accomplish all sorts of goals, from entertaining behavior for robotic toys to word, speech, and face recognition software. Don't be intimidated, though; anyone who knows how to play a game, how to analyze their own behavior, and some basic algebra can design monster AI for a game. It does not require mastery of a programming language to design AI, only to implement that design. The design itself can be done by making a flowchart or a written description of how a unit's decision-making process should work. But, enough about AIs, and back to combat.

The oldest kind of computer game combat is one hit = death (though the player may have multiple lives). This kind of combat originated in text adventure games, but could be seen more recently in many sidescrollers and platformers. The Super Mario series is a well-known example: Mario is traveling toward the right side of the screen, a goomba is traveling left, and whichever one is struck by the other first will die. They don't die simultaneously because they have different vulnerable zones – Mario is vulnerable on his sides, but not beneath him, so he can kill the goomba by landing on top of it. The goomba is vulnerable on its top but not on its sides, so it can kill Mario by walking into him. Of course that's only the most basic situation: Mario may be powered up, and if so the first hit will cause the power-up to fall off instead of instant death. Some monsters are tougher and may need to be hopped on multiple times. A few monsters cannot be killed by hopping on them, but instead must have a turtle shell or other object thrown/slid at them, or a fireball shot at them. The raccoon tail or cape gives him a side attack with a slightly longer range than his vulnerable side area. Etc.

So, as enemies become tougher, it may take several hits to kill them. The monster's toughness is thus called HP (hit points). And then, games where a single mistake kills you tend to be more on the stressful side than the fun side. So we can give the playable avatars and pets HP too, so they won't die from a single hit. It's nice if the player can see how much life they have, so they know when to use health potions or retreat. This is usually shown with a HP meter. There are three standard approaches to visualizing health. The simplest is a bar where the left side represents 0 health and the right side represents maximum health. In some games the maximum health and/or the current health are shown as numbers. The health meter often changes colors from red at low health through yellow or purple at medium health to green or blue at full health. Other color schemes or locations of colors can work too. In some games an injured character has a red nimbus (full-body halo or form-fitting cloud) while a healthy character has a white one, and in other games the whole screen's colors become desaturated (grayed-out) as the character is injured. The second approach is showing health as a clock-shape, where the clock begins filled with color and with a 'hand' pointing upward to 12 o'clock. As the character becomes injured this hand sweeps clockwise, revealing a gray or black of missing health. Again, numbers are optional. The third approach is a heart shape. The heart can either have a vertical meter that shows how full of life the heart is, or can behave like a heart-shaped clock. Horizontal health bars also sometimes include a heart as a graphic indicating that the meter is for health. If numbers are included they are usually written as a fraction: current/max.

Before health meters, landing a direct hit, completely blocking or reflecting a direct hit, and status changes like slowness/quickness, temporary invulnerability, size change, and range decrease/increase were the only things that could happen in combat. The addition of HP enabled DOT (damage over time) attacks and status ailments, such as poison and burn. Not to mention healing (partially or completely refilling an HP meter) and healing over time, commonly known as regen. It also enabled partial blocking and reflecting of damage, and attacks that hurt the user a small amount to hurt the enemy a large amount. Both of these add cost-benefit-analysis strategy to combat, making it more complex and interesting.

Health is far from the only stat playable characters and enemies can have. Magic, energy, and rage are other possible meters that the player might need to manage during combat; in some cases the goal is not to run out, in other cases the goal is not to have too much. Magic, energy, rage, and health are called by a variety of names in different games. There are several other kinds of stats characters and enemies can have which are not typically represented with meters, because they don't go up and down a lot during combat. In turn-based tactical and strategy games these may include action points and movement points, which regenerate at the beginning of each turn and are spent on the character or enemy's actions and movements during that turn. And in RPGs and RPG-influenced genres the character may have long-term stats affected by their equipment, class, stat points that have been spent on that character, and current buffs and debuffs. This group of stats may include defense (armor class), speed (initiative), intelligence, spirit (wisdom), charm (charisma), luck, and stealth.

So from simple platformer combat and turn-based combat the next things that evolved were arcade fighters, which are characterized by the ability of individual moves to add up to combos, and skill cooldowns, which make frequency of use a new factor in combat strategy. Both of these can be found in both turn-based and real-time combat systems. The realtime versions are probably more familiar – cooldowns take the form of a timer, while combos require performing a sequence of actions correctly within a certain time frame without being interrupted by an enemy action or a critical failure. In a turn-based system cooldowns are take the form of a turn number count-down, or more rarely a damage-taken or damage-dealt count-down. Turn-based combos can be executed by two units acting on the same turn (or an enemy and a unit who reflects or counterattacks in response) or they can be executed by one unit taking a set-up action on one turn and then a follow-up action on the next turn.

Another evolution at approximately the same time was the addition of terrain. Technically platformers have terrain, such as spiked ground, slippery surfaces, ground that crumbles when walked on, and underwater areas the playable character must use a different or slower kind of locomotion to travel through. But that's 1D terrain, more or less, and 2D terrain in tactical turn-based combat, strategy combat, FPS, and live-action RPG combat adds more complexity. Distance affects the range of attacks and the speed at which units can pursue or flee each other. In a turn-based game this is usually implemented by giving each unit a number of movement points per turn, while in a real-time game it is usually implemented as a running speed stat. Different kinds of terrain can also give bonuses or penalties to units standing on them or trying to cross. Some terrains types are beneficial to all units or detrimental to all units, while other terrains are sympathetic to some types of units and antagonistic to some types of units (often this is about a unit's elemental affiliation, like fire terrain benefiting fire units and penalizing ice units). Terrains may have obstacles that make them unable to be walked on and may block line-of-sight attacks. Finally, terrain allows for the player to construct fortifications, traps, and other buildings or immobile units, as well as destroy or activate ones which the game has placed there before the beginning of the battle.

So, that's pretty much the whole list of elements that the various modern styles of combat are built out of. Several genres add yet more complexity by blending non-combat elements into combat. RTS games put the infrastructure and workers onto the battlefield where they must be protected from attack. Tactical, RTS, and deck building card game-style combat all may require the player to spend gathered or crafted resources to summon units into play. FPSes and an odd assortment of other games allow avatar(s) to change equipment during combat. Action-adventures may allow adventuring tools to be put to unorthodox use in combat.

What constitutes modern styles of combat? Here is a list. Yes, it's biased. I am deliberately excluding random combat, text-based combat, automated combat, simple turn-based combat as either antiquated or just bad.

- Platformer, Arcade, and Action/Adventure combat: This is a realtime form of combat where the player controls a single unit to perform actions usually bearing some resemblance to martial arts (or things like biting and clawing if the avatar is non-human). Whether armed, unarmed, or able to wield magic in place of/in addition to a weapon, common actions include an upper body attack, a lower body attack, jumping, ducking or rolling, possibly blocking, and possibly a projectile attack or magic attack. Combat takes place in the main/exploring game mode, and the player may end up fighting several enemies at once. During combat the player maneuvers around the screen, trying to place themselves in a position to attack while dodging enemy attacks and also avoiding any holes or other terrain hazards that happen to be present. As with all real-time games, commands must be entered quickly; this limits the avatar's possible actions to a small number of button presses most players can memorize, and limits the amount of strategic thinking the player will have time to do. Some games pause the action to allow the player to select a special action from a menu, but more commonly the player must choose before combat begins which special action(s) to equip to their available button(s) or key(s). Typical features include collision detection, knockback, combos, an obstacle-course-like environment, tool use on both the environment and enemies, and simple status ailments that quickly wear off on their own. Racefighting combat would also go in this category.

- Tactical Turn-based combat: This is a turn-based form of combat where the player controls between one and ten units on a field of terrain. If the player only directly controls one unit they probably can summon AI-controlled allies (e.g. pets) instead. As with all turn-based combat this is slow-paced, and instead of being about adrenaline and resources it is about strategic complexity. Generally the player gets a budget of a set number of movement and action points per unit per turn and each unit has its own stats and set of equipment; in singleplayer versions units may be able to access the player's inventory of consumable items, while in multiplayer games item-use may be unavailable during combat. Combats take place in a limited area with a limited population of enemies, and eliminating all enemies concludes the combat. Common actions include movement across the terrain, ranged attacks which require line of sight, area effect or splash-damage attacks, setting traps, summoning units onto the battlefield, and units healing or buffing team members. Deck building card game combat is a variant of this which usually substitutes some kind of zones and/or creature types for terrain. For example, the player's hand may be one zone and the player's deck another zone, while flying creatures may be assumed to be in a hypothetical sky and non-flying creatures are on the ground.

- Shooter/FPS: This is a realtime form of combat where the player controls only their own avatar, who is generally not visible except as their gun barrel or crosshairs. Common actions consist mainly of sneaking/making use of cover, shooting enemies and picking up found items such as different guns, ammo, and healing items. The emphasis is on reflexes and skill (also luck) rather than stats. Kill combos may be possible (e.g. 3 blue enemies in a row).

- MMORPG: This is a realtime form of combat where the player controls their own avatar, possibly accompanied by 1-3 AI-controlled pets; if there are AI-controlled pets either they or the avatar take a tank role while the other takes a DPS and healing role. Combat takes place in the main world, and it's common for two or more players to fight the same enemy. Enemies are anchored to small territories, which usually prevents more than two enemies from attacking the same player, and enemies will 'leash' back to this territory if the player flees. Enemy AI is usually less complex than in a tactical/strategic system; this is a side effect of class balancing more than a result of the simplicity required of all realtime combat. Typical features include timed skill cooldowns, aggro (enemies preferentially attack whichever unit they are the most mad at), a party system with automatic or configurable loot division, spellbars, a basic attack that repeats automatically, classes with different combat styles and equipment (this is not necessarily a GOOD feature), and player-alterable stats/purchasable skills.

- [Combat Type]

- [Are enemies visible before combat begins, and is combat in the main game mode or its own separate mode? What non-combat activities, such as resource gathering and constructing buildings, can or must be done during combat?]

- [What unit(s) is the player controlling in the fight and what can the player do with them, including movement and types of attacks?]

- [Are there AI allies of some kind?]

- [What attributes do units have? Equipment, an equipped/learned subset of available abilities, what types of stats from HP to AP and Movement/Speed, or elemental attributes, and are these stats player-alterable...?]

- [What is the battlefield like and in what ways can it effect combat?]

- [Can items be used in combat, and if so, how?]

- [What is the typical number of enemies fought at once, as well as the minimum and maximum number?]

- [Are enemies typically different in stats or other capabilities from player-controlled units?]

- [What is typical enemy behavior and common variants on that?]

- [What are the typical rewards of combat?]


13. Minigames, Puzzles, And Other Combat Alternatives


While combat is the main activity of many games, other games do not have combat at all, or alternate combat with some other major activity. Changing-up the player's experience by alternating two major activities is done with the goal that the player doesn't get bored as fast. The entertainment value of any activity will last longer if a player only does it occasionally than if they do it for several hours straight. Non-combat possibilities for a major activity of a game include:

- Gathering and Crafting (Covered in an earlier section)
- Tending and Babysitting (Growing Plants, Raising Pets, Lemmings, Sims)
- Dexterity and Timing Games (Racing, Fishing, Dance Dance Revolution, Guitar Hero)
- Speedpuzzles, Physics Puzzles, Adventure Game Puzzles, and Solitaires (Card Solitaire, Mahjongg, Memory, Tetris, Match-3, Angry Birds, and adventure-game-style puzzles)

Tending and babysitting are relatively simple. Each unit that needs to be tended has either a predetermined schedule of needs, a table of percentages from which randomized needs are generated, or a timer that determines how often a new need is generated. For example, in a turn-based sim where each player action is one turn or one action is allowed per pet/plant per turn, then each pet/plant which has had a need satisfied on one turn will display a new need the next turn. 'Need' is a loose term, it could include a “ready to compete” state or a “ready to be milked/sheared” state where the pet 'needs' to put out effort instead of taking in effort. If pets/plants age, age is typically determined by number of turns; some systems only count turns the pet/plant is interacted with, other systems count all turns, and some only count until the pet/plant reaches adulthood or until it reaches old age. Pets/plants which have age stages typically have different needs per stage.

In a realtime tending and babysitting game pets typically generate needs based on a timer (or they may not generate needs but instead walk across the playing field toward dangers). The pet/plant may have pre-set need requirements, or may have meters (e.g. happiness, hunger, health...) which fall over time until the player raises them by filling a need. If a need falls too low the pet/plant may run away or die. The same thing happens if a wandering pet encounters a hazard, like walking off a cliff or into spikes. The player's actions are scored either when the pet/plant changes age states or when the round of play ends. The pet/plant or round may have specific requirements or simply a required number of points. There may be multiple sets of requirements, which give the player different verdicts: failure/lowest possible stats/worst type into which the pet can mature, normal success/average stats/average type of pet, gold star success (achievement) /high stats/best type of pet.

Dexterity and timing games range from the very simple to the very elaborate. Occasionally they are too simple to actually be fun – one of the most pathetic excuses for a minigame I've seen, and seen more than once, is a cursor that bounces back and forth between two ends of a meter and you have to try to stop it as close to the meter as possible. This kind of dynamic can work fine as part of a larger game, such as pulling the plunger back in a pinball game or casting a fishing rod, but it just doesn't work as a game by itself. Now fishing on the other hand, there's a nice simple example of a minigame. Or at least it can be nice, when done well. There are several timing and dexterity elements involved – the fish's movement in the water (if it's the kind where you can see the fish before you cast), the force and direction of the cast, yanking the rod promptly after the fish strikes, and possibly angling the rod to counteract the fish's sideways pull or alternately reeling the fish in when it's not resisting and letting out more line if it resists a lot and the line tension gets too high.

Arrows-on-tracks games, such as DDR and Guitar Hero, are another simple, popular kind of timing game. They evolved from conveyor-belt speedpuzzle games like the classic arcade puzzle game Klax. You can see the arrows traveling toward you, so you can try to get ready for them, then you have to push the corresponding key or button when they get to you. In some versions all arrows travel at the same speed, in other versions different tracks can travel at different speeds. Sometimes there is an extra, rarely-used button that works differently (space bar or whammy bar) This kind of game typically has combos, like an arcade fighting game or rogue MMO combat. It's also pretty similar to pinball, oddly enough – they are scored in a very similar way, and pinball also requires using the paddles promptly when the ball gets to them, though pinball has physics sim elements that arrows-on-tracks games don't. Breakout is another similar game, it just adds some puzzle-elements to the paddle-and-ball dexterity challenge of a pinball game.

Racing and related games where you do acrobatic flying, show jumping, agility, jousting, skateboarding/snowboarding/stunt biking, slalom, &etc. are at the complex end of the spectrum of timing and dexterity games. Racing can be simple, such as a hurdle race where the avatar runs straight forward at a set pace and the player's only input is when to jump. But the complexities that can be added on top of that are what really bring the magic to this genre. Endurance meters, the ability to raise or lower the basic running/flying speed, a sprint ability that drains the meter extra-fast, curvy tracks which make jockeying for position and controlling speed important, an assortment of obstacles to jump over or duck under, and stars/balloons/bonus items to collect as a goal the player must balance their goal to get to the end as fast as possible, are all typical features of this genre.

Speedpuzzles are kind of a hybrid between timing/dexterity games and puzzles, but I think they fall more on the puzzle side of the line because many of these games have some levels/missions judged on speed but others judged on efficiency or accomplishing a specific goal; some also let you choose whether to play in a timed mode or a zen/relaxed mode. Speedpuzzles are usually about a stream of falling pieces or a screen full of pieces that you move to make patterns (3 or more in a row, 4 in a square, a complete row across the screen). The completed patterns vanish, and new pieces appear to take their place, often rearranging the other pieces in the process so you can get bonus cascades.

A minor variant on the pattern-making speedpuzzle is the shooter speedpuzzle, e.g. Frozen Bubble and Zuma. In this kind of game the patterns are created by shooting additional pieces at the constantly or periodically increasing mass of pieces in the level which will overflow (a loss condition) if the player is not quick enough to trim the back.

A completely different type of speedpuzzle is the time management game. In this kind of game you control a single worker you have to run around the screen as fast and efficiently as possible. The difference between this and a realtime babysitting game is that instead of taking care of emoting units, you are usually doing chores and interacting with machines; you set the schedule instead of simply reacting to the schedules set by the units. Combatless strategy speedpuzzles are related; these games focus on the infrastructure building part of a strategy game, and the goal is to gather resources and build up your infrastructure as quickly and efficiently as possible. Both of these games are crafting-like in that your mission objectives can easily take the form of a recipe, e.g., “Produce 5 tomatoes, 2 jugs of milk, and 1 chicken.” or “Produce 10 gold, 2 emeralds, and 2 diamonds.” It's easy to imagine these being crafted into a meal and a piece of jewelry, whether the game explicitly states that this is what they are intended for or not.

The physics puzzle genre has recently been popularized by Angry Birds and World Of Goo (one casual, one not), but this kind of game has actually been around a long time. These combine shooting or placing objects with the mouse where they will most disrupt the environment with destructible environments where falling pieces can contribute to (or block) completing the level's puzzle objectives. Magnets, mirrors and lasers, ropes and pulleys, weights and balloons, fire and explosives, electricity and lightbulbs, balls and ramps, and all sorts or rotating and revolving things are traditional elements in physics puzzles.

Adventure game puzzles typically consist of a set of objects which can be arranged into various positions or states, or interacted with in various orders. Usually there is only one correct pattern of positions, states, or orders that solves the puzzle. There is usually no time limit, and the puzzle is free and easy to reset/reattempt. This is because the player is intended to take multiple attempts to solve the puzzles, otherwise they are too easy. Adventure game puzzles should be exploratory – the player should toy with the objects and use deductive and inductive reasoning to figure out the rules by which the objects operate. Adventure game puzzles range from simple mazes, jigsaws, sliding block puzzles, and sudokus, through more complex puzzles like hopping games (peg solitaire, towers of hanoi, solitaire mancala), pushing blocks around obstacles and into holes, flipping/rotating pieces to align them, rearranging weights or volumes to balance them, or flipping switches and rotating pieces to complete a circuit. There is some overlap with physics puzzles, but those are more freeform while adventure game puzzles are generally more structured.

Solitaires are probably familiar to everyone; they consist of a standard set of pieces (such as a deck of cards or set of mahjongg tiles) laid out in a randomized order, and the player tries to eliminate or otherwise resolve the whole set by making moves within the rules of the game. The main distinguishing trait of this kind of game is that unlike other puzzles it is not scored only by perfect completion, but instead it can be scored by degree of completion, which makes it more useful for gambling systems than other puzzles.

Finally, there are many games where combat and puzzles are blended together. Puzzle-like combat is especially common in action adventure, tower defense, and strategy games. (Tower defense games are those where enemies advance toward your base, trying to destroy it, while your units can't move once placed because they are either passive defenses like moats, walls, and caltrops, or automatic defenses like sniper towers and other kinds of gun emplacements. Plants vs. Zombies is the closest thing I have seen to a pet tower defense game, because the plants in that game are animalistic and pet-like.) Strategy games commonly have mission objectives which the player must 'puzzle out' how to accomplish, often through multiple attempts. These mission objectives involve defending an area long enough to build or repair a specific building, taking a foozle or civilian to a target, or running a gauntlet without being able to build up your normal infrastructure. Action-adventure games use adventure style puzzles, minigames where play branches internally and you replay the game until you find the right branch to get a treasure, and bosses which aren't vulnerable to normal attacks or are only vulnerable at certain times.

- [Tending and babysitting, if the game includes this type of activity]

- [What is tended/babysat, how does this activity work?]

- [If there are multiple activities of this type within the game, describe each additional one.]

- [Dexterity and timing, if the game includes this type of activity]

- [What kind of dexterity/timing activity is it, how does it work?]

- [If there are multiple activities of this type within the game, describe each additional one.]

- [Puzzles, if the game includes this type of activity]

- [What kind of puzzle is it, how does it work?]

- [If there are multiple activities of this type within the game, describe each additional one.]


14. GUIs and Controls, Game Modes and Context-Sensitive Behavior


GUI stands for graphical user interface. Borders, icons, menu bars, mouse cursors, font(s), the title screen, the credit screen(s), the help/about screen(s), trading and shop interfaces, pop-up menus, tool tips, any backgrounds which are solid colors or gradients rather than artwork, etc. all make up a game's GUI. There are programming toolkits and libraries available to help implement standard GUI elements, but first they need to be designed. This is a tricky type of design because it's half usability and half art. As such, GUI design is a field related to web design and graphic design. Consult your statement of purpose to review what art style and theme/tone you wanted your game to have; the GUI must be consistent with these. For example, you probably don't want to use smiley-faces as indicators of high durability on armor in a horror game.

Controls are the way the player uses an input device to tell the game what they want to do. Each button/key or directional input is a control. The GUI and the control scheme are inevitably related, because if you are making a mouse-driven game then you need to have mouse-friendly controls. If you want the game to be dual mouse/keyboard then it's really helpful to label the mouse-click-able buttons with the keyboard shortcuts that will activate them, or if it's pure keyboard then you need to have a 'cheat sheet' of all the keyboard shortcuts or some other reference the player can consult to learn them. Gamepad controls also require a different GUI – they have fewer buttons than a keyboard, are awkward to use to drive a mouse pointer, but work really well with a cursor that slides or rotates through menu options, and that menu can be completely invisible when the player doesn't need it instead of taking up screen space with a clickable button. Some games even use microphones, cameras, gyroscopes, toys with gamepad buttons built in, and other gamepad-substitutes like dancepads and steering wheels.

Game modes are strongly related to both GUIs and controls. A game mode is situation within the game – account/character creation mode, exploration mode, battle mode, puzzle mode, inventory mode, and a particular minigame's mode(s) are examples of these kind of situations. Each game mode has unique GUI and control needs. Thus each game mode needs a version of the GUI tailored to it, and the controls need to be context sensitive, which means the same button or mouse click can do different things in different situations within the game. It is called remapping the controls when your game assigns different functions to each button/key/whatever when the player enters a different mode within the game.

I haven't really mentioned concept art design in this document yet, so here's a crash course of the steps involved:

1. Make a list of needed features – (Yo dawg, I heard you liked making features lists so I put a features-list-making step in your features list.) Specifically you need to make a list of your different game modes, what information and actions need to be immediately visible to the player in each, what information and actions are necessary but less urgent and should be accessible by a menu, and what controls the player should be using in that mode, including how they access any menus and how they exit that mode.

2. Get source images – Google Image Search is one of the most incredibly useful things on the internet. Make one or more folders on your computer and save copies of anything relevant. You do not own the rights to these images so you can't copy them directly, but looking at them for reference is fair game. That's what a source image is. What are you searching for source images of? GUIs of other games and random art related to your chosen theme and tone. If possible, identify 1-3 example games, animes/cartoons, or similar which have a very similar theme and tone to the one you want your game to have; google those as well as terms for your theme and tone.

3. Make mock-ups (concept art) – You can doodle on paper or use your graphics program of choice, but either way you need to make pictures of what your different game modes, including their GUIs, might look like. If possible, use the proportions you want your game to have on the player's screen. Don't just make one concept; after you make your first attempt try to clear your mind and do something different, then do that again.

4. Revise, Consult, Revise – Look at the different attempts side-by-side, see if there's any way to get something better still by combining part A of attempt 1 with part B of attempt 2. Now, it's almost inevitable that this kind of mock-up is missing something. Many, many, student architects have designed a house with no bathrooms, for example. So even if you are your game's main artist I don't recommend putting your GUI concepts right into development without getting some kind of second opinion. If you have to wait until a later point in your development process to have someone you can ask, then wait. When you make your final revision after getting some input, then your job here is done, unless the required features change or playtesting turns up a problem later. If your document format can include images, add your concept images to an appendix.

- [Input devices you want your game to use, such as mouse, keyboard, and/or gamepad]

- [List game mode(s) with the primary control scheme]

- [Describe the control scheme, both info displayed to the player and input giveable by the player.]

- [List each group of game modes with an additional control scheme]

- [Describe the control scheme, ditto.]


X. End: An overview of the game development process and how the design document is used during this process.


1. Revise – Theoretically you now have the first two parts of a game design document: a statement of purpose and a features list. Look them over for any inconsistencies or missing information and fix that if you can, or mark it (I use bright red text) as something that needs to be fixed when you can figure out how.

2. Prioritize – Look through your features list and separate it into Core features that you absolutely must have, and Non-Core features that you like but will not start to implement until the core features are done. You can also re-arrange topics within the features list if you think they are more logical or useful in a different order. For example, perhaps the GUI and game modes section should be near the beginning instead of near the end.

3. Format – Copy your features list and paste it into your document, so you now have two. Remove all but the headings from one. If any of the headings seem confusing, clarify them. Congrats you just made a table of contents. Depending on what kind of word processor or other program you are using to make your game design document, you can go through and make each table of contents entry hyperlink to the appropriate feature.

4. Revise Appendices – Review your appendices – is there stray stuff in there that should be filed into appropriate places in the features list? Are there any things you know you'll need an appendix for that you don't yet have one for? (E.g. list of locations, list of NPCs, list of weapons, list of armor, list of enemy types, list of crafting resources, list of crafting recipes, list of quests...) Make more appendices for those. Rearrange the appendices until they seem to be in the most logical order.

5. Brainstorm – Go through one feature at a time, then each appendix; for each one, add any other useful and relevant information you can think of. The goal is to get the document as complete as you can make it without outside help, before looking for that outside help.

6. Research – If there is some feature you are interested in but don't have much experience with as a player, research what games have that feature. Read about how the feature works in those games, and consider playing one or a few to experience how the feature works. You may do this part first or multiple times if you like.

7. Copyedit – If you have really long or confusing sentences, improve them. If you have really long paragraphs or no paragraphs, cut up your wall of text into more manageable chunks. Spellcheck. Beware of homophones and use of apostrophes. Have you used consistent formatting for headings and lists? The goal of this step is to make your document as readable and polished as possible before showing it to others.

8. Seek Feedback – The kind of feedback you need will differ depending on what role you intend to play in your game's development, and how complete you've managed to get your design document. You may prefer to recruit a co-designer who will add a lot of their own thoughts to the design document before beginning development. Or you may want to hire a consultant, paying them to sign an NDA and give you all the suggestions they can come up with for your design without becoming a part of your team or having any rights to future income from the game. Or you may want to describe either the general outline of your game or a specific problematic area on a public forum to get volunteer feedback. Or you may want to begin development immediately, either by your own efforts or by recruiting or hiring a skilled programmer or artist.

9. Development – Whoever is the most experienced programmer involved with the project will need to use this design document to make a programming plan: Name the languages, libraries, engine, database, etc. to be used, break the core features into proposed code objects, and plan how those code objects will communicate with each other. Whoever is in charge of the story should make sure enough of it has been created to guide the artist(s) in producing art assets appropriate to the story. Whoever has the most experience with GUI design and/or art will need to set standards for the still images, animated sprites, and/or 3D models and textures the game requires, and use this design document to make checklists of all the art assets that need to be created. As pieces of the game are completed you can mark them as completed within the design document, for example by turning the text relevant to them blue or green.

Now, alas, you have reached the end of the help I can give you. If anyone thinks of a topic I have missed or forgotten here, please let me know in a comment. Otherwise, good luck and happy game designing! ^_^




Article Update Log

28 Mar 2013: First draft; added "Design is just another word for plan: a game designer plans out a game." to section 0.  OMG why are the headings such a horrible shade of orange?!  But eh, it's a passible first draft now.  Wtf, is it in the programming category?  I didn't see a box to choose the category T_T  Somebody put it in design please.
03 April 2013 Yay the category is finally right.  Thank yous to both Michael Tanczos and Gaiiden for sorting this out!

Understanding Component-Entity-Systems

$
0
0

Introduction


The traditional way to implement game entities was to use object-oriented programming. Each entity was an object, which intuitively allowed for an instantiation system based on classes and enabled entities to extend others through polymorphism. This led to large, rigid class hierarchies. As the number of entities grew, it became increasingly difficult to place a new entity in the hierarchy, especially if the entity needed a lot of different types of functionality. Here, you can see a simple class hierarchy. A static enemy does not fit well into the tree.

Attached Image: classdiagram.png

To solve this, game programmers started to build entities through composition instead of inheritance. An entity is simply an aggregation (technically a composition) of components. This has some major benefits over the object-oriented architecture described above:

  1. It's easy to add new, complex entities
  2. It's easy to define new entities in data
  3. It's more efficient

Here's how a few of the entities above would be implemented. Notice that the components are all pure data - no methods. This will be explained in detail below.

Attached Image: compositiondiagram.png

The Component


A component can be likened to a C struct. It has no methods and is only capable of storing data, not acting upon it. In a typical implementation, each different component type will derive from an abstract <Component> class, which provides facilities for getting a component's type and containing entity at runtime. Each component describes a certain aspect of an entity and its parameters. By themselves, components are practically meaningless, but when used in conjunction with entities and systems, they become extremely powerful. Empty components are useful for tagging entities.

Examples

  • Position (x, y)
  • Velocity (x, y)
  • Physics (body)
  • Sprite (images, animations)
  • Health (value)
  • Character (name, level)
  • Player (empty)

The Entity


An entity is something that exists in your game world. Again, an entity is little more than a list of components. Because they are so simple, most implementations won't define an entity as a concrete piece of data. Instead, an entity is a unique ID, and all components that make up an entity will be tagged with that ID. The entity is an implicit aggregation of the components tagged with its ID. If you want, you can allow components to be dynamically added to and removed from entities. This allows you to "mutate" entities on the fly. For example, you could have a spell that makes its target freeze. To do this, you could simply remove the <Velocity> component.

Examples

  • Rock (Position, Sprite)
  • Crate (Position, Sprite, Health)
  • Sign (Position, Sprite, Text)
  • Ball (Position, Velocity, Physics, Sprite)
  • Enemy (Position, Velocity, Sprite, Character, Input, AI)
  • Player (Position, Velocity, Sprite, Character, Input, Player)

The System


Notice that I've neglected to mention any form of game logic. This is the job of the systems. A system operates on related groups of components, i.e. components that belong to the same entity. For example, the character movement system might operate on a <Position>, a <Velocity>, a <Collider>, and an <Input>. Each system will be updated once per frame in a logical order. To make a character jump, first the <keyJump> field of the Input data is checked. If it is true, the system will look through the contacts contained in the <Collider> data and check if there is one with the ground. If so, it will set the <Velocity>'s <y> field to make the character jump.

Because a system only operates on components if the whole group is present, components implicitly define the behaviour an entity will have. For example, an entity with a <Position> component but not a <Velocity> component will be static. Since the <Movement> system uses a <Position> and a <Velocity>, it won't operate on the <Position> contained within that entity. Adding a <Velocity> component will make the <Movement> system work on that entity, thus making the entity dynamic and affected by gravity. This behaviour can be exploited with "tag components" (explained above) to reuse components in different contexts. For example, the <Input> component defines generic flags for jumping, moving, and shooting. Adding an empty <Player> component will tag the entity for the <PlayerControl> system so that the <Input> data will be populated based on controller inputs.

Examples

  • Movement (Position, Velocity) - Adds velocity to position
  • Gravity (Velocity) - Accelerates velocity due to gravity
  • Render (Position, Sprite) - Draws sprites
  • PlayerControl (Input, Player) - Sets the player-controlled entity's input according to a controller
  • BotControl (Input, AI) - Sets a bot-controlled entity's input according to an AI agent

Conclusion


To wrap up, OOP-based entity hierarchies need to be left behind in favour of Component-Entity-Systems.  Entities are your game objects, which are implicitly defined by a collection of components.  These components are pure data and are operated on in functional groups by the systems.

I hope I've managed to help you to understand how Component-Entity-Systems work, and to convince you that they are better than traditional OOP. If you have any questions about the article, I'd appreciate a comment or message.

Article Update Log


1 April 2013 - Initial submission
2 April 2013 - Initial publication; cleaned up formatting

I Have a Game Idea!

$
0
0

Introduction


If you're new to game development and came to GameDev.net with a game idea, hoping to...
  • Sell the idea to game developers that'll make the game and pay you/split profits with you, or
  • Lead a group of developers to make the game under your management
...then I've got some knowledge to impart to you.  This is actually the very reason I first joined GameDev (because I had a game idea), and I was taught the same lessons I'm about to teach you.

Clearing your Delusions


This first part is going to be taken up mostly by me shattering your dreams.  It's tough, but in order to look at your situation realistically and consider how to make your game, you have to first understand what's not going to happen and how things just aren't going to be.

I have an awesome idea for a game! How do I sell my idea so I can get rich off of it?


This isn't how it works. You most likely won't be able to pitch a game idea to someone or some company and have them make it for you. You pretty much definitely won't be able to actually sell the idea for a huge check or a percentage of the profits that the game makes.

This is because games are mixtures of quite a few different fields - to name some of them: programming, art, music, sound effects, and in some cases, writing for the world, story, characters, dialog, etc.

These are all rather extensive fields that require skill and knowledge to implement well.  Games are tough to make.  They're combinations of both artistic and technical fields, each one requiring time and dedication to get skilled with.

The idea for a game, the raw concepts for it, are a tiny fraction of what's involved with making a game.  Not only this, but game ideas are often changed a lot during the process of developing them; the original idea probably won't even be that fun, even if it seems like it would be when you think of it.  That's why people make short demos of their game ideas and play-test those demos to see if their games are fun.  They tweak and iterate on their ideas until they're polished and fun.  Very rarely (if ever) does a game idea just come to someone, perfect and ripe for development, ready to make people rich and entertain on a meaningful, worldwide level.

So...in short, it's very unlikely that you'll sell a game concept/idea, because game studios have lots of these (pretty much anyone who's into game development has their own ideas), and they don't consider them particularly valuable.  What's truly valuable is the implementation of those ideas, and how you turn them into an actual game: that's why the playtesting and tweaking part is considered so important.

If you want your game idea to be developed, then you'll have to do more than throw around concepts and ideas, especially since you're completely new to designing games - and playing lots of games doesn't qualify you, either (though it does help).

OK, in that case, can't I just find game developers and get them to make my game?


Now that you know you won't be directly selling your idea to people, you may consider trying to gather a group of game developers to make your game for you, while you tell them how everything should be.

Game Designers and Idea Guys

Before we go on, I feel it's time to clear something up: the common title for "the idea guy" is called a 'game designer' (even though that kind of sounds like they make graphics or art...it confused me at first).

At least in the GameDev.net forums, people have separated the Idea Guy and the Game Designer into two different kinds of people:
  • The Idea Guy is one who has vague ideas without providing very many useful, specific details.  Like I said, the majority of a game is its implementation and polish, and the actual, high-level ideas, though important, are only a small part of the creation process.
  • The Game Designer is one who provides ideas and concepts as well as digging deeper to fill in a lot of technical details (such as how much damage and health things have, how fast the player moves, and so on).  Game designers understand the importance of iteration and playtesting when creating games, and know that games are very unlikely to come straight out of their heads as pristine magnificence.  For more information on specifically what a game designer does, check out this article.
Okay, now, back to the topic at hand: gathering developers to make your game for you.

This idea is mostly unrealistic unless you can pay those developers.  If your game is as big as Call of Duty or similar, then this entails paying the salaries of a team of developers for at least a year.  I've said it before, and I'll say it again: games aren't easy to make, especially triple-A quality games like Call of Duty, Final Fantasy, World of Warcraft, and so on.  It takes a lot of money and expertise to push out a game like those.

If your game is smaller (and you should start small!), something like a simple mobile game that doesn't have an RPG-like need for content, then you'll be much better off.

If you can't pay developers, and you just expect them to make your game for you "because it's awesome", then you're going to have a rough time.  Specifically, you'll probably end up only attracting people who aren't really that good at what they do, or you'll just be ignored entirely.

The reason behind this is because you, as an idea guy/game designer, aren't really in low supply or high demand.  In fact, when you're on game development sites looking for developers, the chances are they all got into game development to make their own ideas, not to do it for other people...for free.

The gist of it is: you can't expect people to do hard work like making games for you unless you can pay them.  If you can pay them a reasonable rate, then that greatly increases your chances of getting your game made - but you should research and make sure you know what you're doing before you start trying to hire developers.

Okay, so it's impossible to make my game without money?!


Whoa, whoa, calm down there!  Things may be looking a bit negative now, but there are still ways to make your game: you can do so by harvesting the power of "doing things yourself".

That's pretty much the point I've been working towards up until now: your chances of turning your game ideas into reality...er, virtual reality...are going to get higher and higher the more you know about actually making games.

If you learn and get good at some kind of game-development-related skill, like one I mentioned above (programming, art, sound, etc.) then you'll be much more respectable in the eyes of hobbyist/indie game developers.  If you're actually a good game designer (which also takes practice and research!) and team manager, and have at least one skill to contribute other than game design, then gathering a team of hobbyists and making a game is achievable, as long as you have reasonable expectations (i.e., aren't expecting a huge, triple-A game to be the result).

Summing it up

  • Games are hard to make, and big games like Call of Duty and Final Fantasy are created by teams of many paid developers: programmers, 2D and 3D artists, music composers, sound effect designers, etc.
  • Even hobbyist game developers who don't have a job probably aren't going to make your game for you if you don't pay them for it, because they have their own ideas and dreams that they'd rather work on.
  • Fighting the facts won't get you anywhere; the sooner you realize game ideas are a dime a dozen, the better.

Learning a Skill


Now we've learned that if you want to make a game and you can't pay for it, then you'll be a lot better off if you have something to contribute to the development of a game.  Simply being a 'game designer' isn't ordinarily enough to entitle yourself as a true 'developer', because, although design is important, so much more goes into a game than just design.  As well as that, you probably aren't necessarily a good game designer if you're new to game development in general - no offense.

The next step in your journey leads you to the Introduction to Game Development article.

Article Update Log


4 April 2013: Initial release

Getting into Games through Education: "Where do I begin?"

$
0
0
Moving into the Games Industry can be a tricky minefield, especially if it is something you think you might want to do, but are not really sure where to start. This is where education can play a helpful role in focusing attention. You can start doing the stuff you’ve thought about, as well as some you may not have, all whilst being given a guiding hand by tutors. This series of articles aims to provide the best possible tools to ensure a smooth route through the process; from selecting a University establishment, all the way to day one of your course, and beyond.

Note:  It is not my aim within these articles to ‘name and shame’ the best, or worst, Universities in the UK. It would be irresponsible to do so. In these articles, I am looking to provide a set of tools and reference points, which a prospective student can use to research the best University for them. Also, I am writing from the perspective of a UK Graduate and therefore I make reference to policies or organisations (i.e. UCAS; a UK Organisation dealing with student applications to University) that are part of the UK University system. This does not mean that the skills can't be extrapolated and applied elsewhere, I am just unfamiliar with the policies of other education systems.


Choosing your Subject Area


My Experience


You might be asking yourself “Who is this person to give such advice, is it not just his opinion?” and you would be right to do so. Please see the 'About the Author' section at the end of this article where I provide a small background to myself, and the journey I took through University; detailing some of the pitfalls and mistakes I encountered, so that it might benefit the potential path of the reader.

Where to begin?


So you’ve decided that education would be the best way forward, now to select the area you want to go into. The best way to do this is to look at what you already know and enjoy, and ask yourself some questions. Do you like to draw in your spare time and want to get your designs on-screen? Are you technically able when it comes to computers and have a passion to go deeper? Do you sometimes look at the games you play and wonder “how do people come up with these ideas”? These are just examples but, asking the right questions early enough can really help narrow down the area you are going to have the most passion for, and excel at.

Types of Course


There are four major course types that one can take to give themselves a solid foundation to progress into the industry:

  1. Computer Games Programming. Usually awards a BSc.
  2. Computer Games Art. Usually awards a BA.
  3. Computer Games Design. Awards either degree type, depending on specific content weighting.
  4. Computer Science, with modules specifically tailored to Game Development. Usually awards a BSc

Note:  There are also other courses that are concerned with Sound Engineering and the Business of Games that one could look into. I will not be going into these as it might dilute the article, but it is something that can be easily researched, should this be of more interest. I have also listed the types of degree (abbreviated) that these award, please see the Glossary for more details.


The first three are representative of significant areas that can be found in most, if not all, Game production companies. There is enough of a differentiation in the real world, that they can have entire syllabuses devoted to them. The fourth option is one where the aim is to teach Computer Science principles, such as Software Engineering and Application Development, with the option to do Games specific modules in the second/third year of the course.

Computer Games Programming

This type course will focus the majority of its attention on Computer Programming, Mathematics and Software Engineering, among other concepts, using the perspectives of Games Software Development as the focal point. Having previously done Maths or IT would be beneficial to this though, it is not uncommon to be invited for interview if you programme in your spare time and can demonstrate the ability/understanding.

Computer Games Art

This course will push your art skills to the limit. The curriculum for this type of course involves 3D modelling, conceptualising ideas using 2D techniques and software, as well as a lot of drawing (life, still object etc.). You will be highly unlikely to get into a course like this without previous background in some form of Art education, and an accompanying portfolio.

Computer Games Design

This course allows for you to conceptualise all those ideas you may have had when playing games yourself. You would find yourself looking into the design of levels, user-interfaces, characters and story-telling. You might also be exposed to the production processes that help take a game from concept, to final shipment. A background in a design based course would be advisable however, if you have a portfolio showing your capabilities, this might not necessarily be required.

Each of these is a great route and provides your particular interest with a focus in that area, allowing you to build on topics you may have studied at college; Maths -> Programming or Art/Graphical Design -> Games Art.

Note:  It is not necessarily true that each of these courses is specifically isolated to itself and, more likely than not, you will be provided complimentary/optional Modules to delve into various aspects of the other, in a lighter way. For example, a programming course with an art module that allow you to put your own artwork, into what you code.


As I have mentioned, these types of courses might, and in some cases will, require specific A-Levels in that field to have been studied and completed with good pass rates (usually ‘C’ or above), as well as a solid number of UCAS points (points are obtained by achieving certains grades in each college subject you study). You might also be asked to bring along a portfolio of work, usually required by Art/Design courses, to demonstrate your skills. These are used to ensure that the prospective student is able to handle the workload presented to them on day one. In some cases, even if you don't have the necessary A-Level grades, a University can accept you if you present them with a strong body of work you may have done in your spare time. Examples of code or your ability to use a photo-editing suite proficiently are but to name a couple.

Jumping forward to day one; every course will have a period of a couple of weeks at the start to ‘break the ice’. This is where the students get introduced to their tutors, their fellow students and the work they will undertake. After this period the workload quickly ramps up. If a student is unable to show through their college work at interview that they are able to commit their time effectively, they are likely to fall behind and Universities are less likely to select them. It is a business after all and for each student not likely to fail, means one less bad statistic and one more tuition fee in their accounts.

Don't be scared of Rejection


Don’t look at the possibility of rejection before the interview as the be-all end-all... it happened to me! This is why you are required, by UCAS, to make a list of University choices so that you have other choices to fall back on. Even in the worst case scenario, other options become available that introduce new types of courses, different from what I have previously mentioned:

  1. Computer Games (insert general Technology/Development Noun here); a course that usually has low, previous education requirements, covers all 3 of the major areas and is tailored to the beginner.
  2. [Specific Area] Foundation; a pre-cursor to the course at your ideal University. It is usually a catch-up on what may not have been achieved through A-Levels and, as long as it is completed to a reasonable level, can get you doing what you want.

There are a number of Universities that offer the first option and, don't get me wrong, some can be good however, there are those that spread their subject area quite thin. Some try to cover too many areas and potentially brush-over subjects briefly that you may think are important. Some are an amalgamation of modules previously offered by the establishment and re-branded to represent games.

These sorts of courses can be handled in one of two ways. Either they are very good with a lot of industry links to ‘feed’ them, meaning you will get the same sorts of skills and education as in a speciality course or, they will make use of the low points requirement to pick-up the students that might not have been capable enough at their first choice. The main problem with this second is, if you do find yourself on a course like this, you might be completing all your weekly assignments with ease and wanting to learn more. But, more often than not, there will be students in that class who might be struggling with content from 3-4 weeks ago. Whilst this doesn’t affect your learning directly, it does take away the focus of the tutor in order to help them catch-up, and trust me when I say that said time with them is like gold-dust.

Commitment is the Key


An important point along this line of thought is that you will only get out of University what you put in. This is true of any course, Games related or not, and at its most basic level means don’t rely solely on lecture/tutorial time to complete your work or learn new topics. In fact, a core principal that lecturers instil on day one is that it is all about Independent Learning. They will introduce you to advance topics and set you assignments, but they won’t chase you up on late drafts/submissions as tutors in school would have.

If you want a degree you can be proud and be able to say “I absolutely did my best and made the most of my tuition fees”, then you will need to put in many additional hours, outside of the classroom. This links back to what I was saying about being competent to be able to handle the work load.

Conclusion


My aim with this article was to provide you with food for thought on how to approach the education route, for those that have been thinking about it, but don’t know where to start, or for those who didn’t know that this was an option. Either way I have only scratched the surface by providing some of the more popular routes and, with extra research; you can find more ways to go about it.

Thank you for taking the time to read this. In my next article, I will talk about how to make the most out of an Open Day visit. What you need to look for, who you need to speak to, the questions you need to ask to find the correct establishment for your educational needs. After all, you will be there for 3-5 years.

Further Reading


UCAS (Universities & College Admissions Service): http://www.ucas.ac.uk/
The Guardian Profile for Computer Sciences: http://www.guardian.co.uk/education/2008/may/01/universityguide.computerscienceandit
The Guardian League table for Computer Sciences: http://www.guardian.co.uk/education/table/2012/may/22/university-guide-computer-sciences-it
The Guardian League table for Art and Design: http://www.guardian.co.uk/education/table/2012/may/22/university-guide-art-design

Glossary


Qualifications


BSc: Bachelor of Science
BA: Bachelore of Arts

A-Levels: Advanced Level Qualifications, also referred to as GCE's.

Article Update Log


1 April 2013: Initial release
4 April 2013: Added article image; under licence from Ajari: http://www.flickr.com/photos/25766289@N00/3898591046/ , sourced from Wikimedia: http://commons.wikimedia.org/wiki/File:Heiwa_elementary_school_18.jpg

Games have the potential to be infinite, so why are you still working on a throwaway project?

$
0
0

Games have the potential to be infinite, so why are you still working on a throwaway project?


Lets get this straight. Books, images, music and video are a single-use item. Once you've seen them, read them or listened to them, the discoveries has been made and you move on to something else.

Sure, you may revisit them for a second or even a third go, but by that time, they're already old. You know what happens, you know what it looks likes and how it feels. Its done.

A throwaway product.

Before I continue, I do infact recognize that its a throw-away product for a single person. It may have as many uses as there are the amount of people, which are born every day, making its potential lifespan infinite in that sense.

But thats not the point. Lets get a bit selfish here.

This article about you as a consumer, not the whole world.
Picture this the following:

So you've experienced some neat scripted game and its now over. It was fucking awesome.

You want more.

There is none at the moment.

Lets also mention that making games is a hard and slow process.

...

That sucks, doesn't it?

You're back to square one. You experienced something inspiring, but it ended and thats it. You wanted more, but the experience was cut off as soon as the content ended. Now you're left stranded to look for something else to enjoy.

Whats worse, is that it may take a long while before you get something that good again, but if its the same limited design, you'll consume it in a few hours like the last game and be back in this same state of emptiness.


2lrz2b.jpg
Waiting till the next good game comes around.



Its an endless cycle. So what's the point of continuing this?

However, there is another way.


Something a computer program can that a movie can't.


Video games have something that movies, music and books don't. The potential to be infinite.

When I say infinite games, I don't mean those simple highscore-based arcade games, no.
I'm talking about games with the same seriousness and scale as those massive scripted ten plus hour adventures like Mass Effect or Skyrim, but much better and truly infinite.

If you're freaking out and saying this is impossible, then stop. It is. The main difference between those above examples and the infinite game, is that you play as yourself and not forcibly being someone you're really not.

From the perspective of gameplay design, it works much more fluently, is more consistent and doesn't require the artifical constraints you get often get in a scripted game. It just works.

Most of the time, unless your main goal is to specifically teach something or tell a story, which movies, visual novels and books are more fluent at, these games are meant to give you a specific experience. A thrill, an emotion or some particular feeling. An atmosphere.

The trick is to focus on that experience and build around that, rather than stuffing the player into a some arbitrary role, when the real goal of the game is to simply give an experience, like being a pilot, monster, soldier, hunter, spy, hero, adventurer, commander, god... you name it.

The whole aspect of putting a player into a specific character's role only shifts the focus from what is really important, which is about delivering an experience, not being someone you're not.


Were not really making the games we really want, are we now?


But alas, the games industry, both AAA and indies, seem oblivious to all this and keep doing the same thing over and over, despite deep down really wanting that infinite game. Talk about the definition of insanity, eh?

Whats mind boggling, is that developers spend years of their life to create games, only for them to have such a limited - and often rather shoe-horned - design that can be exhausted within a few hours, some times even in just mere minutes.

This is understandable for movies and books, since they're not interactive by nature and cannot generate fresh new content like a computer program is capable of doing, either through multiplayer, user content or procedural random generation.

But come on, whats with the obsession of shoe-horning the scripted movie framework on video games?

This is especially the case when the player is put in the role of a specific character, usually with the hopes that he or she will experience the story from a more closer angle.

There is a huge problem with this design. A big conflict.


Fitting a square peg in a round hole.


You put the player in full or even partial control over a character that has a previously established past, abilities and perhaps a personality of some description.

The problem is that the player can do anything he wants. Any story or personality the character has or the path that he takes will get perverted in one way or another.

Its no mere coincidence players are having fun doing absurd things that the character they play as would never ever do. Like tea-bagging corpses. Or going AFK during a conversation with an NPC in the middle of something important.


256wccp.jpg
Typical player behaviour in a video game universe.



Why? Because you simply can. As the player you're in control, after all.

A game is an interactive system and its natural for this behavior to occur, so your attempt to tell a convincing scripted story and creating strong immersion in this way goes right out the window.

And yes, an obvious thing to do against this is to limit what the player can do, to the point that the pretty much runs on rails, but at that point your game has turned into a glorified movie.

Doing so cripples the game's ability to be infinite and it greatly limits its flexibility in terms of gameplay and what the player can experience within it. Thats just contradictory game design right there.

Trying to force a storytelling approach to a video game while giving the direct control over a character to the player is as shoe-horned as it can get. The more serious a game tries to take itself, the more cringe worthy it becomes.

So you're basically shooting yourself in the foot with a design that adopts the approach of movie and books.


So, back to the point of infinite games.


Like mentioned previously, there are three big things that make the whole infinite game idea possible; multiplayer, procedural random generation and user content. In addition, there are two more; persistency and emergent behaviour.

Using these five concepts, either all of them or even just a few of them, it is possible to create a video game that never gets old or lame unlike a movie, book or those traditional scripted video games do inevitably.

With all that said, I return to my initial question:

Why would you spend years creating something so complex as a video game with the goal to deliver an experience that limits itself with a scripted, finite design?

All that hard work you put in would get used up in mere hours, where instead you could create a game with a design that is infinite?

Not only you could create something that will have virtually infinite longevity for yourself to have fun with endlessly, but also provide a lasting product to your players that offers them same infinite entertainment, with much wider flexibility on how it can be played.


jab194.jpg
To infinity and beyond!



Talk about some seriously huge value for their money. This is what video games were meant for. This is what they're capable of.

Besides that, people are starved for infinite games, you can see signs of this in any hardcore gaming communities when you ask them about it. Theres a huge opportunity to be had here for success and a new form of games to enjoy.

Go out there and design your games with infinite gameplay in mind and a strong focus on the atmosphere and emotion its supposed to evoke in you. Its all a matter of design.

Introduction to Spritesheets

$
0
0

Introduction


This article aims to introduce spritesheets and how to incorporate them into your game. Basic programming knowledge is assumed, however, knowledge of C++ and SFML is not required. The spritesheet concepts apply to other languages and libraries.

Spritesheets


What are spritesheets?


For a nice summary of spritesheets and why they are useful, check out the video on this page that was kindly given to me for this article by Michael Tanczos: What is a sprite sheet?. There is a summary of the video content on the bottom of the same page if you scroll down below the comments.

Essentially, some graphics hardware require images to be of certain dimensions, and sprite images do not always match these dimensions. The result is you either pad an image with unneeded pixel information, wasting space, or you can place multiple sprites together in an image, filling the padded space, and creating a sheet of sprites, more commonly referred to as a spritesheet.

How do I use them?


For this tutorial, let us say this is our spritesheet we wish to work with:
Attached Image: spritesheet.png
It isn't anything special, but a start. Let's call it simple programmer art we made to test the spritesheet system because that is currently our goal.

These sprite images are not all the same size, they have varying widths and, in practice, sprites can have varying heights within a sheet (some spritesheet makers will have an option to included rotated images to try to use up more of the padded space). To handle the issue of designating which part of the spritesheet contains an individual sprite, spritesheets are usually accompanied by a file that tells where each sprite is located, including its width and height, and if the image is rotated, how much the image was rotated (90, 180, or 270 degrees). These files can also include other information about a sprite, if desired, such as a group they belong to, such as "Animation 1" or "Character XYZ". This is helpful when more than one item is included in the sheet, like sprites for bushes and trees.

These green borders show the outline of our sprite area and where our accompanying file should reference our four images.
Attached Image: spritesheet2.png
For this example, these four images are part of one sprite animation, so our accompanying file should group these images together.

Assuming we did not have a program create the spritesheet for us, we also will have to make the information file. Our file will need the following: spritesheet name, transparency color (if needed), sprite groups, and individual sprite regions -- we didn't rotate any sprites. To keep things simple, we will just write each item on it's own line, however you could use whatever format you are provided with or can imagine (XML, JSON, etc).

Our template to go by:

Spritesheet Filename
Transparency Color (3 numbers for RGB)
Item Group Name
    StartX StartY EndX EndY
    StartX StartY EndX EndY
    StartX StartY EndX EndY
    StartX StartY EndX EndY
Item Group Name
    StartX StartY EndX EndY
    StartX StartY EndX EndY
    StartX StartY EndX EndY
    StartX StartY EndX EndY

For this particular example (the image is 256px x 128px), our information file will look like this:

spritesheet.png
255 255 255
Stickman
    9 13 62 114
    71 13 126 114
    135 13 188 114
    193 13 236 114

Once we have both the spritesheet and the information file, we can start incorporating the sprites into our game.

We will need to handle reading the file data and storing the information to use later. Since we are using SFML for this example, we will load the image into an sf::Image and the sprite region information into structs we can easily use to assign to our sf::Sprites.

Our item group struct will look like this:

struct SpriteItemGroup {
	std::string groupName;
    sf::Sprite groupSprite;
	std::vector<sf::IntRect> spriteRegions;
	int currentSprite;
    int animationDirection;
};

The currentSprite variable will be used to keep track of which region we are using, whether it is for an animation, state, or just what image in a set. The animationDirection variable will be used to move forward and backward through our SpriteItemGroup (0, 1, 2, 1, 0, 1, 2, etc.). The sf::IntRect is part of SFML's codebase, and is a rectangle with integer coordinates, taking a top left point (our start X and Y) and a bottom right point (our end X and Y). The sf::Sprite has functions to set a source image, set a sub-rectangle of the source image (which is what we want to pull one sprite from our spritesheet), as well as a few other useful functions, like rotating a sprite (which can help if your sprite image in the spritesheet was rotated).

The process should follow these steps:
  • Open and begin reading the file.
  • Store the filename for the spritesheet.
  • Store the transparency color (if being used, if not you could omit this step).
  • Create a struct to store the item group.
  • Add coordinates to the item group.
  • Continue reading coordinates until you reach the end of the file or you reach another string (meaning another item group and you start back at creating another struct).
  • Close file.
  • Create/load spritesheet file.
  • Set the transparency color for the spritesheet.
  • Create a sprite image for each item group (this tutorial uses an sf::Sprite).
  • Assign the spritesheet file to each sprite as the source image.
  • For each item group's sprite, assign the first sprite region.
  • Draw each sprite to the screen.

The code for the process


String Parsing

This code function is used to pull the integers from a given string (and assumes only spacing and integers are in the string). If you plan to use a different format for your information file, you may have to edit this code. A string is passed in, the first integer that it comes across is returned, and the rest of the string starting just after the integer is assigned back to the string.

int retrieveInt(std::string &stringToParse) {
	std::string legalNumbers = "0123456789";
	size_t startPosition = stringToParse.find_first_of(legalNumbers, 0);
	size_t endPosition = stringToParse.find_first_not_of(legalNumbers, startPosition);
	int returnInt = atoi(stringToParse.substr(startPosition, endPosition).c_str());
	if(endPosition >= stringToParse.length())	{
		stringToParse = "";
	}
	else {
		stringToParse = stringToParse.substr(endPosition);
	}
	return returnInt;
}

The animation function

This function will take one of our structs and move the animation forward or backward depending on which region is current. This may not be the case for every spritesheet; our sample was made to be used forward and then backward to show a constant animation. If you have sprite animations and the final sprite should be followed by the first sprite, then simply keep the animationDirection equal to 1 and when the currentSprite is at the max for the spriteRegions, reset currentSprite to 0.

void nextAnimation(SpriteItemGroup &itemGroup) {
	if((itemGroup.currentSprite >= itemGroup.spriteRegions.size() - 1 && itemGroup.animationDirection == 1) || (itemGroup.currentSprite <= 0 && itemGroup.animationDirection == -1)) {
		itemGroup.animationDirection *= -1;
	}
	if(itemGroup.spriteRegions.size() > 1) {
		itemGroup.currentSprite += itemGroup.animationDirection;
	}
	itemGroup.groupSprite.SetSubRect(itemGroup.spriteRegions.at(itemGroup.currentSprite));
}

The main variables

To show our sprites, we need a window to display them in, as well as a few variables to store our data from the information file, and to open the file for reading.

int main() {
    sf::RenderWindow display(sf::VideoMode(800, 600, 32), "Sprite Display");
    
    std::string spritesheetFilename = "";
    std::string parsingString = "";
    int startX = 0, startY = 0, endX = 0, endY = 0;
    
    int redTransparency = 0, greenTransparency = 0, blueTransparency = 0;
    std::vector<SpriteItemGroup> itemGroups;
    
    std::ifstream spritesheetDatafile;
    spritesheetDatafile.open("spritesheet.txt");

Reading the information file

We need to read in our general spritesheet information (the filename of the image and the transparency color), as well as collecting all of our groups. After we get every region for a group, we store it in our itemGroups std::vector. Since we don't want to do anything if we can't read our file, the reading code as well as the display code will be inside this if block.

if(spritesheetDatafile.is_open() && spritesheetDatafile.good()) {
    // Read in filename and transparency colors
    getline(spritesheetDatafile, spritesheetFilename);
    getline(spritesheetDatafile, parsingString);
    
    redTransparency = retrieveInt(parsingString);
    greenTransparency = retrieveInt(parsingString);
    blueTransparency = retrieveInt(parsingString);
    
    while(spritesheetDatafile.good()) {
        // Still can read groups
        SpriteItemGroup tempGroup;
        getline(spritesheetDatafile, tempGroup.groupName);
        tempGroup.currentSprite = 0;
        tempGroup.animationDirection = 1;
        getline(spritesheetDatafile, parsingString);
        while(parsingString.substr(0, 1) == " " || parsingString.substr(0,1) == "&#092;t") {
            // Still have coordinates
            startX = retrieveInt(parsingString);
            startY = retrieveInt(parsingString);
            endX = retrieveInt(parsingString);
            endY = retrieveInt(parsingString);
            tempGroup.spriteRegions.push_back(sf::IntRect(startX, startY, endX, endY));
            getline(spritesheetDatafile, parsingString);
        }
        itemGroups.push_back(tempGroup);
    }
    
    spritesheetDatafile.close();

Preparing the image and sprites

The spritesheet image needs to be loaded and the transparency color needs to be set. Then the image needs to be assigned to each sf::Sprite, and the first spriteRegion of the group needs to be set. Also, the position of each sf::Sprite should be set. The position will change depending on where you wish for the sf::Sprite to be drawn. Since I only have one sf::Sprite, just that sf::Sprite's position was set.

sf::Image spritesheetImage;
if(!spritesheetImage.LoadFromFile(spritesheetFilename)) {
    return EXIT_FAILURE;
}
// Setting transparency
spritesheetImage.CreateMaskFromColor(sf::Color(redTransparency, greenTransparency, blueTransparency));

for(int i = 0; i < itemGroups.size(); i++) {
    itemGroups.at(0).groupSprite.SetImage(spritesheetImage);
    
    if(itemGroups.at(i).spriteRegions.size() > 0) {
        itemGroups.at(i).groupSprite.SetSubRect(itemGroups.at(i).spriteRegions.at(0));
    }
}

itemGroups.at(0).groupSprite.SetPosition(250.0, 250.0);

Display the window

Finally, we clear the window, draw our sf::Sprites, and start our loop. Events are checked and processed, then, if enough time has elapsed, we draw our sf::Sprites again, as well as progressing our animations. If there are only certain groups that you wish to show, edit both drawing sections (they start with "display.Clear"). The maximum number of frames per second is determined just below the "// 15 FPS" line. Adjust the value in the if check to your game's needs or add the drawing calls to your rendering section of code.

		display.Clear(sf::Color(0, 255, 255));
		for(int i = 0; i < itemGroups.size(); i++) {
			display.Draw(itemGroups.at(i).groupSprite);
			nextAnimation(itemGroups.at(i));
		}
		display.Display();
		
		float elapsedTime = 0.0;
		sf::Clock gameClock;
		
		while(display.IsOpened()) {
			sf::Event event;
			while(display.GetEvent(event)) {
				if(event.Type == sf::Event::Closed) {
					display.Close();
				}
			}
			
			if(display.IsOpened()) {
				elapsedTime = gameClock.GetElapsedTime();
				// 15 FPS
				if(elapsedTime >= 1.0/15.0) {
					display.Clear(sf::Color(0, 255, 255));
					for(int i = 0; i < itemGroups.size(); i++) {
						display.Draw(itemGroups.at(i).groupSprite);
						nextAnimation(itemGroups.at(i));
					}
					display.Display();
					gameClock.Reset();
				}
			}
		}
	}
	
	if(display.IsOpened()) {
		display.Close();
	}
	
	return 0;
}

Conclusion


Summary


Spritesheets are useful game resources. They cut down on wasted filesize by filling the unused padding around individual sprites with more sprites. Games need a way to find all the different sprites in a spritesheet, so the spritesheets are accompanied by an information file that specifies where each sprite is located. Once read, each sprite can be found and assigned to the proper location, referencing the sheet and the rectangle within the sheet that is needed.

Attached


In the attached .zip file, I included both the spritesheet image the program uses and the one with the borders, the required .dll files, a .exe, the information file, and the source code. Feel free to use or modify the code and images. The SFML .dlls are straight from the C++ Full SDK for Windows - MinGW (http://www.sfml-dev.org/download.php).

Things to note


The sample information file and spritesheet does not include any rotated sprites. Adding this functionality is relatively simple. In the information file at the end of the coordinates line for that particular region, just indicate a fifth number that tells how the image was rotated (90, 180, or 270 degrees). You can use 0 degrees for images that were not rotated. Add a way to keep track of this information in the SpriteItemGroup, and then you just apply a rotation to the sf::Sprite after you set the sub-rectangle.

The example used in this article does not use more than one sprite item group, however, the code is flexible enough to handle varying amounts of sprite item groups.

I did not take sprite position relative to other sprites into account, such as when you switch to the next sprite in a spriteItemGroup since all of my sprites' positions are unaffected when I switch. The top left point of the sf::Sprite rectangle always is at the same point, and the sprites all have the same height. To take this into account, you can include an amount of repositioning needed at the end of the coordinates in the information file, using a change in X and Y, and then just move the sf::Sprite by the changes needed. When you move on to the next sub-rectangle in the list, just undo the move and apply the new move for the next sprite.

The information file reading code does not do much in the way of catching errors, so use that exact code with caution.

The SFML code currently uses SFML version 1.6 since version 2.0 has not been fully released at the time of this writing. I will update the code after version 2.0 is fully released.

Article Update Log


04 Apr 2013: Initial release

Evolve Your Hierarchy : Refactoring Game Entities with Components

$
0
0

Introduction


Up until fairly recent years, game programmers have consistently used a deep class hierarchy to represent game entities. The tide is beginning to shift from this use of deep hierarchies to a variety of methods that compose a game entity object as an aggregation of components. This article explains what this means, and explores some of the benefits and practical considerations of such an approach. I will describe my personal experience in implementing this system on a large code base, including how to sell the idea to other programmers and management.

Game Entities


Different games have different requirements as to what is needed in a game entity, but in most games the concept of a game entity is quite similar. A game entity is some object that exists in the game world, usually the object is visible to the player, and usually it can move around.

Some example entities:
  • Missile
  • Car
  • Tank
  • Grenade
  • Gun
  • Hero
  • Pedestrian
  • Alien
  • Jetpack
  • Med-kit
  • Rock

Entities can usually do various things. Here are some of the things you might want the entities to do
  • Run a script
  • Move
  • React as a rigid body
  • Emit Particles
  • Play located audio
  • Be packed up by the player
  • Be worn by the player
  • Explode
  • React to magnets
  • Be targeted by the player
  • Follow a path
  • Animate

Traditional Deep Hierarchies


The traditional way of representing a set of game entities like this is to perform an object-oriented decomposition of the set of entities we want to represent. This usually starts out with good intentions, but is frequently modified as the game development progresses - particularly if a game engine is re-used for a different game. We usually end up with something like figure 1, but with a far greater number of nodes in the class hierarchy.

Attached Image: Fig-1.gif

As development progresses, we usually need to add various points of functionality to the entities. The objects must either encapsulate the functionality themselves, or be derived from an object that includes that functionality. Often, the functionality is added to the class hierarchy at some level near the root, such as the CEntity class. This has the benefit of the functionality being available to all derived classes, but has the downside of the associated overhead also being carried by those classes.

Even fairly simple objects such as rocks or grenades can end up with a large amount of additional functionality (and associated member variables, and possibly unnecessary execution of member functions). Often, the traditional game object hierarchy ends up creating the type of object known as "the blob". The blob is a classic "anti-pattern" which manifests as a huge single class (or a specific branch of a class hierarchy) with a large amount of complex interwoven functionality.

While the blob anti-pattern often shows up near the root of the object hierarchy, it will also show up in leaf nodes. The most likely candidate for this is the class representing the player character. Since the game is usually programmed around a single character, then the object representing that character often has a very large amount of functionality. Frequently this is implemented as a large number of member functions in a class such as CPlayer.

The result of implementing functionality near the root of the hierarchy is an overburdening of the leaf objects with unneeded functionality. However, the opposite method of implementing the functionality in the leaf nodes can also have unfortunate consequence. Functionality now becomes compartmentalized, so that only the objects specifically programmed for that particular functionality can use it. Programmers often duplicate code to mirror functionality already implemented in a different object. Eventually messy re-factoring is required by re-structuring the class hierarchy to move and combine functionality.

Take for example the functionality of having an object react under physics as a rigid body. Not every object needs to be able to do this. As you can see in figure 1, we just have the CRock and the CGrenade classes derived from CRigid. What happens when we want to apply this functionality to the vehicles? You have to move the CRigid class further up the hierarchy, making it more and more like the root-heavy blob pattern we saw before, with all the functionality bunched in a narrow chain of classes from which most other entity classes are derived.

An Aggregation of Components


The component approach, which is gaining more acceptance in current game development, is one of separating the functionality into individual components that are mostly independent of one another. The traditional object hierarchy is dispensed with, and an object is now created as an aggregation (a collection) of independent components.

Each object now only has the functionality that it needs. Any distinct new functionality is implemented by adding a component.

A system of forming an object from aggregating components can be implemented in one of three ways, which may be viewed as separate stages in moving from a blob object hierarchy to a composite object.

Object as Organized Blob


A common way of re-factoring a blob object is to break out the functionality of that object into sub-objects, which are then referenced by the first object. Eventually the parent blob object can mostly be replaced by a series of pointers to other objects, and the blob object's member functions become interface functions for the functions of those sub-objects.

This may actually be a reasonable solution if the amount of functionality in your game objects is reasonably small, or if time is limited. You can implement arbitrary object aggregation simply by allowing some of the sub-objects to be absent (by having a NULL pointer to them). Assuming there are not too many sub-objects, then this still allows you the advantage of having lightweight pseudo-composite objects without having to implement a framework for managing the components of that object.

The downside is that this is still essentially a blob. All the functionality is still encapsulated within one large object. It is unlikely you will fully factor the blob into purely sub-objects, so you will still be left with some significant overhead, which will weight down your lightweight objects. You still have the overhead of constantly checking all the NULL pointers to see if they need updating.

Object as Component Container


The next stage is to factor out each of the components (the "sub-objects" in the previous example) into objects that share a common base class, so we can store a list of components inside of an object.

This is an intermediate solution, as we still have the root "object" that represents the game entity. However, it may be a reasonable solution, or indeed the only practical solution, if a large part of the code base requires this notion of a game object as a concrete object.

Your game object then becomes an interface object that acts as a bridge between the legacy code in your game, and the new system of composite objects. As time permits, you will eventually remove the notion of game entity as being a monolithic object, and instead address the object more and more directly via its components. Eventually you may be able to transition to a pure aggregation.

Object as a Pure Aggregation


Attached Image: Fig-2.gif

In this final arrangement, an object is simply the sum of its parts. Figure 2 shows a scheme where each game entity is comprised of a collection of components. There is no "game entity object" as such. Each column in the diagram represents a list of identical components, each row can be though of as representing an objects. The components themselves can be treated as being independent of the objects they make up.

Practical Experience


I first implemented a system of object composition from components when working at Neversoft, on the Tony Hawk series of games. Our game object system had developed over the course of three successive games until we had a game object hierarchy that resembled the blob anti-pattern I described earlier. It suffered from all the same problems: the objects tended to be heavyweight. Objects had unnecessary data and functionality. Sometimes the unnecessary functionality slowed down the game. Functionality was sometimes duplicated in different branches of the tree.

I had heard about this new-fangled "component based objects" system on the sweng-gamedev mailing list, and decided it sounded like a very good idea. I set to re-organizing the code-base and two years later, it was done.

Why so long? Well, firstly we were churning out Tony Hawk games at the rate of one per year, so there was little time between games to devote to re-factoring. Secondly, I miscalculated the scale of the problem. A three-year old code-base contains a lot of code. A lot of that code became somewhat inflexible over the years. Since the code relied on the game objects being game objects, and very particular game objects at that, it proved to be a lot of work to make everything work as components.

Expect Resistance


The first problem I encountered was in trying to explain the system to other programmers. If you are not particularly familiar with the idea of object composition and aggregation, then it can strike you as pointless, needlessly complex, and unnecessary extra work. Programmers who have worked with the traditional system of object hierarchies for many years become very used to working that way. They even become very good at working that way, and manage to work around the problems as they arise.

Selling the idea to management is also a difficult. You need to be able to explain in plain words exactly how this is going to help get the game done faster. Something along the lines of:

"Whenever we add new stuff to the game now, it takes a long time to do, and there are lots of bugs. If we do this new component object thing, it will let us add new stuff a lot quicker, and have fewer bugs."

My approach was to introduce it in a stealth manner. I first discussed the idea with a couple of programmers individually, and eventually convinced them it was a good idea. I then implemented the basic framework for generic components, and implemented one small aspect of game object functionality as a component.

I then presented this to the rest of the programmers. There was some confusion and resistance, but since it was implemented and working there was not much argument.

Slow Progress


Once the framework was established, the conversion from static hierarchy to object composition happened slowly. It is thankless work, since you spend hours and days re-factoring code into something that seems functionally no different to the code it replaces. In addition, we were doing this while still implementing new features for the next iteration of the game.

At an early point, we hit the problem of re-factoring our largest class, the skater class. Since it contained a vast amount of functionality, it was almost impossible to re-factor a piece at a time. In addition, it could not really be re-factored until the other object systems in the game conformed to the component way of doing things. These in turn could not be cleanly refactored as components unless the skater was also a component.

The solution here was to create a "blob component." This was a single huge component, which encapsulated much of the functionality of the skater class. A few other blob components were required in other places, and we eventually shoehorned the entire object system into a collection of components. Once this was in place, the blob components could gradually be refactored into more atomic components.

Results


The first results of this re-factoring were barely tangible. But over time the code became cleaner and easier to maintain as functionality was encapsulated in discreet components. Programmers began to create new types of object in less time simply by combining a few components and adding a new one.

We created a system of data-driven object creation, so that entirely new types of object could be created by the designers. This proved invaluable in the speedy creation and configuration of new types of objects.

Eventually the programmers came (at different rates) to embrace the component system, and became very adept at adding new functionality via components. The common interface and the strict encapsulation led to a reduction in bugs, and code that that was easier to read, maintain and re-use.

Implementation Details


Giving each component a common interface means deriving from a base class with virtual functions. This introduces some additional overhead. Do not let this turn you against the idea, as the additional overhead is small, compared to the savings due to simplification of objects.

Since each component has a common interface, it is very easy to add additional debug member functions to each component. That made it a relatively simple matter to add an object inspector that could dump the contents of the components of a composite object in a human readable manner. Later this would evolve into a sophisticated remote debugging tool that was always up to date with all possible types of game object. This is something that would have been very tiresome to implement and maintain with the traditional hierarchy.

Ideally, components should not know about each other. However, in a practical world, there are always going to be dependencies between specific components. Performance issues also dictate that components should be able to quickly access other components. Initially we had all component references going through the component manager, however when this started using up over 5% of our CPU time, we allowed the components to store pointers to one another, and call member functions in other components directly.

The order of composition of the components in an object can be important. In our initial system, we stored the components as a list inside a container object. Each component had an update function, which was called as we iterated over the list of components for each object.

Since the object creation was data driven, it could create problems if the list of components is in an unexpected order. If one object updates physics before animation, and the other updates animation before physics, then they might get out of sync with each other. Dependencies such as this need to be identified, and then enforced in code.

Conclusions


Moving from blob style object hierarchies to composite objects made from a collection of components was one of the best decisions I made. The initial results were disappointing as it took a long time to re-factor existing code. However, the end results were well worth it, with lightweight, flexible, robust and re-usable code.

Resources


Scott Bilas: GDC 2002 Presentation: A Data-Driven Game Object System
http://scottbilas.com/files/2002/gdc_san_jose/game_objects_slides.pdf

Bjarne Rene: Component Based Object Management. Game Programming Gems 5, 2005, page 25.

Kyle Wilson: Game Object Structure: Inheritence vs Aggregation, 2002, http://gamearchitect.net/Articles/GameObjects1.html


Note:  This article is reprinted with permission from http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/

Viewing all 17825 articles
Browse latest View live