# Question
Title: How do I protect my rights to my game on the web?
My small games all have different gameplay. I want to showcase them through the internet. However, I'm worried about them and their concepts getting copied. How can I protect them?

Also, if I have to openly display the code to the open source community, how can I make sure I get credit for my work.

# Answer
Don't worry about your concept getting copied wholesale. It's much more work implementing a concept than coming up with one, and anyone who can put together a finished product will either have ideas of their own, or will change the game enough that it becomes different. If your game is awesome, then it'll be really hard to copy it and make a version that's better/more popular, and if it isn't awesome, people are unlikely to copy it.

Art and engineering are built on the shoulders of giants. You're surely copying some concepts from games you've played, and people will (if you're lucky) borrow a few things from your game to make their own. Don't worry about copying at all.
> 14 votes

# Answer
You just don't.

1) try to be able to sell it, and if you really put a lot of effort on it, people will have a hard time re-implementing its "concept".

2) if you release with a license such as GPL, credits will not be usually a problem. Someone could still steal your code, and if they do you could sue if you knew (but you won't know). The EFF might help.

I'm wondering how did you come up with two opposite questions such as these, I guess you're a bit confused. If you release the game open source, and it's any good, derivate games will almost automatically happen.
> 5 votes

# Answer
According to the law you actually cannot do that.

You want to protect the game rules, rules are inherently ideas, and ideas cannot be protected, only your text can be copyrighted (code and GDD), the name trademarked, and that is it.

The patent law says it is illegal to patent ideas, including software and game rules (unfortunately patent offices ignore this, so yes, you CAN try to patent your game, and try to enforce the patent, but it may, or may not work).

But that is for obvious reasons, if your concept is THAT great, then it is good for humanity to it be copied, it is up to you to get money and credit with it (you can for example create a exceptional game, and everyone will call the genre as "yourgame-clone" or you can name the thing after yourself, like Perlin Noise...).

Ever tought of what would happen if id Software could prevent anyone else from making FPS, and EA from anyone making RTS? Or the MUD people preventing anyone from making MMO?
> 5 votes

# Answer
According to US intellectual property law you have 4 options:

* Copyright
Doesn't apply to ideas only rendered works. Game mechanics are an idea, no help here. But your code, artwork, media, and game executable are protected by copyright by default.
* Trademark
Doesn't apply to you, unless you trademarked RTS, MMORPG, or FPS or something like that.
* Tradesecret
Your game will no longer be a secret the moment you share it.
* Patent
You can't patent ideas. You see this all the time with movie scripts. A particularly talented writer brings an awesome idea to one of the big producers. They like the idea but not the price. They rip off the script's ideas with out copying the script (which is protected by copyright). This is how come the movie industry seems to run in waves, eg The Prestige and The Illusionist.
**However**, software patent law is sufficiently fubar'd that you can patent ideas if you *"limit"* you claim to an implementation on particular hardware (eg a computer, any computer). This is **EVIL**.

Two examples of evil patents that are being up held and effecting the game industry.

Direction arrows above cars are patented in racing games. IE you're racing you get knocked off course, the arrow points the way towards the course/goal. Every game that uses this mechanic needs to pay royalties to Sega of America.

A ghost racer is time trials. IE you're trying to beat your best time and you race against a ghost version of the current fastest time. *Every* game that has this mechanic must pay royalties to Midway games.

I repeat software patents are sick and evil.
> 2 votes

# Answer
I dig for some information on the question i asked and got some more info on how to protect the Game Code and Game Assests.

**Copyright** is the best way to protect the code/art assests.It clearly protects the game code and taking even a portion of the game code and using it in some other context is a copyright violation if it is not your material. However, it is more the code as a whole that is protected and not simply the individual pieces. If one line of code is identical in two separate games, there is unlikely to be a violation. If entire chunks are the same throughout, there could be a possible lawsuit.

Read more: Video Game Copyright Laws | eHow.com http://www.ehow.com/list\_6011584\_video-game-copyright-laws.html#ixzz15XlkEYcb

Also, as i wanted to what exactly can be copyrighted, i got clear idea of what and how to copyright: http://www.copyright.in/register\_copyright\_deposit.html
> 1 votes

---
Tags: legal, web, open-source
---


title: OpenGL clipping plane

text:
# Question
Title: OpenGL clipping plane
I need to move clipping plane of OpenGL and **begin the clipping from that position**. The default location of clipping plane is (0,0,0), so if my model is far enough from the center of coordinate system it immediately disappears, as I begin the clipping, cause it appears in the half clipped by the plane that just moved from (0,0,0) point. So what I need is :

1. Create a clipping plane
2. Translate it to the point I want (normally it's near model surface I want to clip)
3. Begin the clipping from **that** point and **not** from (0,0,0).

How can I achieve my goal ?

# Answer
glClipPlane takes 4 coordinates for the plane equation: {Nx, Ny, Nz, d}, where N=\[Nx,Ny,Nz\] is the normal of the plane, and d is the projected distance of any point on that plane along the normal.

The definition of a plane is:

```
dotProduct(P,N) + d = 0
```

(where P is any point on that plane)

So, by simple math,

```
d = -dotProduct(P,N)

```

eg. if you want to place your plane at (0,3,1), you calculate:

```
d = -dotProduct([0,3,1], [Nx,Ny,Nz])

```

then it should just be a matter of sending Nx,Ny,Nz,d to glClipPlane.
> 2 votes

---
Tags: opengl
---


# Question
Title: Obscuring stored info in a flat-text file
I have an idea for an addon for World of Warcraft which would basically be a minigame within the game itself. Eventually, I'd like to have players be able to compete against each other directly. The game would have some RPG-like elements, particularly statistics and abilities, which it would be undesirable for the end users to modify.

So the fact that this is a client-side script, where everything (logic and data storage) are all in flat text files, means that it's impossible for me to truly secure things. But I'd like to at least make it non-trivial to alter things, e.g. so that you can't just open up a file in notepad and type in 'Strength = 256'.

I'm looking for any ideas on how I might obfuscate the data, preferably something which is easy to implement as it's not really what I feel like spending my time on, but probably more sophisticated than ROT-13.

As an example, one idea I had, which I'm not sure if it's feasible (have never made an addon for WoW before) is to serialize the data in base-64.

# Answer
> 2 votes
Your first idea is good: Just put all your settings into a structure, and store is as a binary. Another thing you might want to try is to concatenate all integers and add something inbetween to checksum (i.e. NVVVCC, N is number of bytes that follow, V is the value, C is the checksum.) Use some weird checksumming (xor of all values emitted so far for instance), so people have to pull out a calculator to change the values, after finding them in the super-long digit string. That's usually enough to prevent someone from using notepad to open your file and changing something, but easy enough so your implementation stays simple. And you can inspect the values visually, which might be helpful.

As you said, the goal is to keep people away from randomly tampering with the data, and adding stuff which is easy to do automatic but cumbersome to do manually usually helps there.

# Answer
> 10 votes
Sorry, no matter what kind of encryption on the client side you do, **if you store sensitive stuff on the client, it will be hacked.**

The client has to be able to read the data in the "encrypted" file. So you are giving the lock and the key to the client in a competitive game, and telling them not to edit anything inside your encrypted file.

Your client will be hacked no matter what. The only thing that the encryption will do is slightly increase the time to be hacked.

**Always assume the client is compromised. If you can't work around that assumption, then you are So-Out-of-Luck.**

# Answer
> 1 votes
I don't have specific experience with WoW addons, but if it were me I'd serialize the script to binary, then for each successive byte XOR it by the next element of a linear congruential random number generator. The generator could be seeded by the CRC of some pre-known locations in your script file. If you need to convert back to ascii, you can remap bits\[0..3\] of each byte to 'A'..'P' character and bits \[4..7\] to 'K'..'Z'. NOTE: the pre-known locations would have some other invertible transform applied, and obviously they should not be XOR encrypted (otherwise you can't reconstruct your CRC for decryption).

Not the best or most unique algorithm in the world, but would serve against opportunistic reverse engineering.

# Answer
> -2 votes
An idea I had which is interesting, though way more involved than I'd care to implement, is to use the 'integrity of the crowds'. That is, working under the assumption that most people wouldn't both trying to change things, have each client broadcast all their progress, and when a client logs in it attempts to sync with other clients.

Obviously just the skeleton of an idea with a whole lot of complicated details that would need to be ironed out, which is why I said it's more involved than I'd care to implement. :)

---
Tags: lua
---


title: Arc'd jumping method?

text:
# Question
Title: Arc'd jumping method?
Okay, so I'm making a platformer, and I wanna know how I can make a arc'd jump easily. Like what Mario does in super Mario Bros 1. Any ideas on a simple way to accomplish this?

# Answer
> 6 votes
Interesting question; having taken Physics classes, I take this sort of thing for granted, when really it is an intriguing idea.

The key point is that X and Y movements are distinct from each other. An object in motion will sustain its X motion, and its Y motion will be affected by gravity at a rate which you set.

You should track the sprite's X and Y velocities. When standing still, the sprite has an X velocity of 0; when moving, it has a constant velocity. When touching the ground, the sprite has a Y velocity of 0. When the jump button is pressed, give the sprite a Y velocity.

Now every frame, reduce the Y velocity by some amount; this is your gravity magnitude. But if the sprite is touching ground, set the Y velocity to 0 so that the sprite doesn't move into the ground. And then modify the sprite's position by (velocity\*time).

Here is a decent-looking Physics lesson which demonstrates these separated velocity components: http://www.physicsclassroom.com/class/vectors/u3l2c.cfm

---

If this was not the answer you're looking for, and you actually mean something more complicated by an "arc'd jumping method", then please elaborate!

# Answer
> 5 votes
ExciteMike has some great examinations of the Super Meat Boy and Super Mario 3 jump physics on his blog.

---
Tags: 2d, software-engineering, java, physics
---


# Question
Title: Do I, and how, separate the concerns of input and game objects?
In probably every game a developer has to somehow deal with input, may it be simple keyboard and mouse events, touch events or something as accelerometer input. This input directly of indirectly effects objects in the game. Sometimes the same input can effect diffent objects. Now I've been thinking about how to model this. The way I see it there are two different approaches.

* Let the game object itself handle it, subscribe to the events and call it's own methods. This has the advantage of letting the game-objects themselves decide which inputs cause which action. A disadvantage seems to be that the input code gets mangled with the "core" game object code. Also the game objects are unaware of the state of the rest of the game, and should sometimes maybe not act upon input events. This doesn't seem right.
* Have a general input-controller take care of all the input and make decisions about who gets to handle what event. This seems to separate concerns better, but tighly couples the input-controller class to the game-objects. It somehow need to know who wants to receive which event and in which state. This doesn't seem right either.

What strategies are you using to handle this?

# Answer
> 6 votes
I recommend separating input events from game objects so you can quickly change/upgrade input methodologies without having to edit and debug 10 object classes. Examples being shifting over from keyboard-only controls to mouse+keyboard, or simply reassigning keys.

Instead of tightly coupling input to the individual game objects, call only one method per unique input signal on the game object, and let it decide the way to execute it.

Use an input controller to keep track of input state:

```
Up press event   -> dir = up
Down press event -> dir = down

```

Whenever input state changes, evaluate if game objects are ready to be modified:

```
set dir  ->  if gamestate != paused && battlemode == false
             ->  character.changeDir(dir);

```

Implement general methods on your game objects, that can be called by the input controller, or other game objects, as needed:

```
changeDir (dir)
setSpeed (walk/run)

```

# Answer
> 6 votes
I recommend the MVC approach. In MVC the game objects only have to worry about modeling the game system, and provide a high level interface like move\_left. Then have a controller object that worries about mapping input to model calls. Not only does it allow for easy change of controls, it gives a good interface for AI they are just another controller.

In your second option I would split up the input-controller in to two parts, one that handles the actual device touch, keyboard, accel, whatever else you can throw at it, have it map them into a generic set of inputs. Then have a second part that maps generic inputs to game specific inputs. Say the keyboards up arrow maps to input1 then touching the top of a touch screen also maps to input1 as well now you write a second piece that maps input 1 to jump. You can now map any IO device as well as stored playback or AI inputs to this generic input system and have a small game specific part that loads what input1 one means to the model.

# Answer
> 1 votes
I would suggest to make your game (the *Model*) define a list of possible input events (implemented as enums or objects with a base interface in common). Things such as `MovingRightStarted`, `MovingRightStopped`, `FiredWeapon1`, `Escape`, etc ...

The game defines a data structure (for instance a `queue`) that your input code (the *Controller*) can fill with input events.

Then your game can poll the data structure to get the input events.

This way, you can plug different kind of controllers to feed the model:

* Keyboard only
* Keyboard + Mouse
* Joystick
* Touchscreen
* Artificial Intelligence

You just have them to push input events to the model.

---
Tags: architecture, input, events
---


title: Tile editor for flash based games?

text:
# Question
Title: Tile editor for flash based games?
I am trying to make the age-old version of pacman. And only then that I realized that I need to spend a heck lot of time for making the tile matrix itself. It gets messy more and more.

I've also heard of this thing called level editors; Are there any of these kind for flash based games. If so, do write it down one line at a time. Thank You.

# Answer
First of all there are a bunch of tutorials on Google regarding building Pac-man clones in eg. Flash. Some of these explain the idea pretty well. There is also a site telling the story and ruleset of the original Pacman ghosts AI. Will see if I can find that link again someday.

But regarding your question.

First of all you need to know your "maximum size" of your levels. In PacMan (from now on "PM" only) the maze is of a certain size, but this wouldnt be too hard to change later though - its only for the principles.

A 2D maze can be implemented with ARRAY's 2 dimensional arrays are just large strings of data.

I will try to show it with characters here:

```
XXXXXXXXXX
X...X....X
X.X.X.XX.X
X.X...X..X
X.X.X.XX.X
X...X....X
XXXXXXXXXX

```

Now thats not a pretty reprecentation of the actual PM, but enough for my point. What I can do now is to store these within a simple array/list of strings.

As you havent told us what programming language you will be using, I will just try to use some "pseudo kinda description" (javascript/actionscript/C# kinda )

```
var maze string[10];

maze[0] = "XXXXXXXXXX";
maze[1] = "X...X....X";
maze[2] = "X.X.X.XX.X";
maze[3] = "X.X...X..X";
maze[4] = "X.X.X.XX.X";
maze[5] = "X...X....X";
maze[6] = "XXXXXXXXXX";

```

From this I can find out where the walls are. I can use this for collision detection, I can use it for pathfinding and I can use it to draw the actual map.

You just make a function that will return what kinda "tile" is on a certain coordinate.

```
tiletype GetTile(xcoord:int, ycoord:int)
{
   return substring(maze[ycoord], xcoord,1);    // returns a substring (string, starting at xcoord, length)
}

```

You could also make it more "specific" if you want.

```
boolean isWall(xcoord:int, ycoord:int)
{
   return (substring(maze[ycoord], xcoord,1) == "x")
}

```

Does this make sense?
> 1 votes

# Answer
* Tiled is a cross platform and quite powerful tile-editor.
* Ogmo Editor is implemented in Flash (Adobe AIR), simple but good enough for most tasks.
> 6 votes

# Answer
Mappy is another one. There's a plugin for mappy that exports maps in a format that is ready for flixel (a very well known game engine for Flash)
> 1 votes

# Answer
Dame- Deadly Alien Map Editor. Looks very slick, although I haven't tried it myself yet. It gets high ratings on the flixel boards.
> 0 votes

---
Tags: tiles, flash, level-design
---


title: Deterministic random number sequence

text:
# Question
Title: Deterministic random number sequence
I have an array of lights that I need to sample from randomly, but deterministically so that all the lights are sampled. Currently I use random numbers to pick a light, and then put processed lights into another list, but I'm wondering if there is a way to use something like a hammersly or halton sequence to do this instead. A biased solution would be ok.

# Answer
> 8 votes
If I understand this, the sequence:
1,2,3,4
could end up as:
3,2,4,1 or 1,3,2,4 or whatever?

Fisher-Yates Shuffle, or the Knuth Shuffle came up on wikipedia. It says linear time, which is good.

```
import random

def shuffle(x):
    for i in reversed(range(1, len(x))):
        # pick an element in x[:i+1] with which to exchange x[i]
        j = random.randrange(i+1)
        x[i], x[j] = x[j], x[i]

```

---
Tags: rendering, random
---


# Question
Title: How does a game like Doodlejump generate its "level"?
How does the game Doodlejump for iphone generate its stage? Are the platforms randomized in some way? If so, how do they make sure it doesn't generate impossible combinations?

If it's not randomized, how do they make sure it's different (or varied enough) every time?

# Answer
Well, its generated on the fly, and definitely random.

To make sure there is imposible jumps you need to tune your game to generate only possible yet interesting situations. It a really hard topic because it is totally different for each game. Luckily you can learn about some games by looking at it and analyzing how you would generate interesting levels.

One very very very good resource here is an article about Tuning Canabalt on how the developer decided to make it not only possible but also hard, and interesting.
> 2 votes

---
Tags: level-design, procedural-generation
---


# Question
Title: Spell casting - How to optimize damage per second
Imagine we have a wizard that knows a few spells. Each spell has 3 attributes: Damage, cool down time, and a cast time. Pretty standard RPG stuff.

Cooldown time: the amount of time (t) it takes before being able to cast that spell again. A spell goes on "cooldown" the moment it begins casting.

Cast time: the amount of time (t) it takes to use a spell. While the wizard is casting something another spell cannot be cast and it cannot be canceled.

The question is: **How would you maximize damage given different sets of spells?**

It is easy to calculate the highest damage per cast time. But what about in situations where it is better to wait then to get "stuck" casting a low damage spell when a much higher one is available?

For example,

1. Fireball: 3000 damage, 3 second cast time, 6 second cool down.
2. Frostbolt: 20 damage, 4 second cast time, 4 second cool down.
3. Fireblast: 3 damage, 3 second cast time, 3 second cool down.

In this case your damage per second is higher if you chose to go for the lower DPCT spell (fireblast) instead of the frostbolt. So we must consider consequences of choosing a spell.

In the following example are cases of "over casting" and "waiting".

# Answer
> 23 votes
> All AI is search!

When you get into the guts of AI it's amazing how much of it is really search.

* **state**: the remaining cooldown of all available spells.
* **fitness**: total damage done
* **cost**: total time taken
* **branches**: any known spell. If spell is still in cooldown just add that value to its cast time.
* **goal**: total health of target. The goal has to be a finite amount of damage, so in the case of an unknown target, pick the largest possible health.
Alternatively, the goal could be spend less than 50 seconds and the search would find the maximal damage that could be done in 50 seconds.

Plug these parameters into a Uniform Cost Search (UCS) and presto, guaranteed optimal battle plan. Even better if you can come up with a heuristic, search with A\*, or IDA\* and you'll get the same answer much faster.

Some more advantages to using UCS is it can find optimal cast order for much more complicated situations than the one you provided with only 3 variables. Some other aspects that could easily added:

* damage over time
* refresh spell to reduce cooldown of other spells
* haste spell causing other spells to cast faster.
* damage booster causing other spells to do more damage.

UCS is not omnipotent. It cannot model the benefits of protection spells. For that you'll have to upgrade to alpha-beta search or minimax.
Also it doesn't handle area-of-affect and group fights very well. UCS can be tweaked to give reasonable solutions in these situations, it is not guaranteed to find the optimal solution.

# Answer
> 2 votes
This is a specialized combinatorial optimization problem. As the number of spells increases, the difficulty in finding the optimal combination/pattern of spells increases significantly. Heuristics similar to those used for the knapsack problem would be valuable in solving this problem.

# Answer
> 1 votes
You need to think in terms of 'damage per unit of casting time' (DPCT) - for example, a fireball with a 3 second cast and doing 3000 damage would do 1000 DPCT.

If you had to wait 3 seconds for the cooldown before casting it, that would reduce it to 500 DPCT (3000 damage, divided by 6 seconds total, including the waiting)

So you just need to determine the damage-per-cast-time of each spell, including any remaining wait for the cooldown. Pick the one with the highest DPCT, Wait if necessary, then cast it. Repeat until the boss is dead :)

# Answer
> 1 votes
Using your example, you'd probably want the two spells to be closer in effectiveness, but possibly give you a different advantage. Having a short casting time (or no casting time for that matter) would be very useful, so then it may be worth using even if it does less damage and takes longer to use again.

You could always impose another element into the equation. Mana/Magic Points can serve this purpose, by allowing the player to determine whether the use of those points is worth the benefit.

Overall though, as bluescrn said, the DPCT (or DPS as its called in many games that are highly tuned and discussed by players seeking the best mix) is really the main element you will want to have balanced, especially if you have any sort of tech/skill trees that allow different players to progress with different skills, yet with the ability to do similar amounts of damage at their given position in the game.

# Answer
> 0 votes
Figured out this algorithm which works well for my purposes.

People brought up some great points. Giving it ultimate goal parameters would allow normal search algorithms to do their thing. ie. do optimal damage in t seconds, do x damage in optimal time.

My algorithm simply returns the sequence of spells with the highest DPS. It is a fast algorithm as it cuts down on the size of the set you are traversing, does not require knowledge of other search tree techniques.

The first step is to identify the spell with the highest damage per cast time. This spell becomes the "baseline" spell since it will guarantee the highest damage per second. Meaning, you should always cast this spell if the following 2 conditions are met: 1) The baseline spell is available (not on cooldown). 2) You are not currently casting a spell.

So it then becomes a matter of filling in other spells while the baseline spell is on cooldown. Between (cast time) and (cooldown - cast time). However, some overlapping can occur (rule 2 above is false).

It then becomes a matter of recursing through all non-baseline spells to find all sequences of spells which do not violate the 2 rules.

For spells which DO overlap you must penalize them for potential damage the baseline spell could have done (up to its maximum damage).

Take for example, 2 spells

1: 300 damage, 3s cast time, 10s cooldown

2: 290 damage, 3s cast time, 3s cooldown

The most damage comes from the sequence 1 - 2 - 2 - 2. Which causes an overlap of 2 seconds into a potential #1 cast. However, this is still beneficial since if you dont cast the third spell (ie. 1 - 2 - 2) you will do 880 damage with 1 second to spare. If you cast the extra #2 spell you will do 1170 - 2 second of #1 which is 200. So 970 damage is your relative damage.

# Answer
> -2 votes
You could do a simple "security level" style switch case.

This is just off the top of my head so beware logic errors beyond my tired state's level of thought, but I hope this can get you started.

Assuming your time is done in block integers -

```
// after casting spell
int remainingTime = (coolDown - castTime);
switch(spellJustCast)
{
  // assuming the cast method will have some input validation for whether the spell
  // is off cooldown or not, pass the time as a parameter
  case 3 : castSpell1(remainingTime);
           castSpell2(remainingTime);
           break;
  case 1 : castSpell2(remainingTime);
           castSpell3(remainingTime);
           break;
  case 2 : castSpell1(remainingTime);
           castSpell3(remainingTime);
           break;
  default: System.out.println("Debug!");
           break;
}

```

Some of the method calls are unnecessary due to your spell times, but there's always room for updates this way.

Edit: I just realised, you would need to reset the remaining time after the new spell was cast, probably best to make it a class attribute/field and set it from a call within the castSpell methods.

---
Tags: algorithm, ai, optimization
---


# Question
Title: How to generate random level from a seed?
How would I go about using a random seed to generate a game level? The same seed should always generate the exact same level.

For this example it would be a Worms style level. So each level would have a theme (grasslands, snow etc), base terrain, different objects such as trees.

So where would I start to create this kind of level generator? What would be involved? What concepts does it use?

Bonus points for any any good links (*bonus* bonus points for anything related to how it was done in worms or similar).

Thanks.

# Answer
The key to this is using your own custom pseudo-random number generator that you initialize with the known seed value. The "Mersenne Twister" is a popular algorithm, here is the Wikipedia entry and some sample source. This, and other, PRNG algorithms actually produce a (very long) fixed series of numbers for which the seed value serves as a starting point.

So long as you follow the exact same procedure for generating your world every time, each value will represent a unique reproducible world.
> 8 votes

# Answer
Here's a PRNG (pseudo random number generator) implemented in ActionScript (available in AS2 or AS3). It's lightweight and fast, ideal for games: http://lab.polygonal.de/2007/04/21/a-good-pseudo-random-number-generator-prng/

The above implementation is based on the Park-Miller-Carta PRNG. This site will give you some more insight about the math behind all this.

To build a worms-like level, I would probably use a Perlin-Noise function though. If you generate a perlin noise image with the height of 1px and the width of your game-world, then you basically get a height map, ready to use. Perlin noise functions also always generate the same map with the same seed.

You can then use the PRNG mentioned above to determine where to place random Objects on the map, or where to create a hole in the ground. For holes you could also take advantage of perlin noise again. Just create a perlin-noise image with the size of your map (x, y), and then create a hole in your map where the pixel-value is below a given threshold (eg. 0.2).
> 4 votes

# Answer
Theoretically if you can use a pseudo-random number generator (such as Perlin-Noise or Marsenne Twister) to share maps via

seed numbers then you can also create custom maps and reduce them to seeds, solving the issue of not being able to create

custom maps when using PRNGs. This however is built on a few presumptions. Namely that pseudo-random number generators are

a reversible process and that ANY data fed backwards into a PRNG will produce a valid seed, let alone a seed at all!
> 2 votes

---
Tags: algorithm, procedural-generation, random
---


# Question
Title: What pattern is this, and should I do it?
I'm making a game in as3 using flash develop and flash cs5. Everything is object oriented. I was wondering, should I have one "gateway" class that has a property-reference to all instantiations of other classes, and I just pass this gateway class to new objects, so they have access to every class. Like so:

```
 var block:Block = new Block(gateway);

 //In the block class:
 this.gateway.player.setHealth(100);
 //Or:
 this.gateway.input.lock();

```

Is this like a singleton pattern or something? Should I do this?

# Answer
This is called the context object design pattern, and it is better than the singleton pattern.

* Context objects aid testing, because you can pass mock contexts to functions you want to test. Singletons hinder it, because to mock singletons you need to make them not singletons.
* Context objects makes your "global state" explicit, and therefore easier to reason about. If a function doesn't take a context object, you know it doesn't use any global context state. You have no such guarantee with singletons or global variables.
* Context objects are *very slightly* slower if you don't use them, because you add another parameter to all your function calls. They can be *faster* than globals if you do use them, and are nearly always faster than singletons.
* Context objects are easier to implement; usually they live on the heap or stack in a normal way. Singletons have tricky issues involving threading in many languages.

So no, this is not a singleton, it's way better than a singleton.

***However,*** you're still passing around a crapload of state - the fact you're keeping it all in a single local variable makes it more explicit, but still creates major conflation of concerns. Keep in mind the one responsibility rule. It makes some sense for there to be a context that owns the player and the current level - they're related - but why does the same context own your keyboard input?

Consider different levels of contexts, for example:

* GameplayContext - owns the player, enemies, the level geometry, etc.
* InputContext - owns keyboard and mouse handles, input events, etc.
* GraphicsContext - owns textures, the window handle, etc.
* GlobalContext - owns a GameplayContext, a GraphicsContext, and an InputContext. This is where you want to apply the service locator pattern, to be able to swap out some contexts for others as needed. And maybe, for quick iteration and testing, this should be in a real global variable - just realize that whenever you use it, you're building up tech debt.

These contexts still conflate concerns somewhat - maybe some event handler takes a GameplayContext and really only needs the player - but the responsibilities are clearly laid out. You know that something that takes a GameplayContext won't load a texture; something taking an InputContext can't kill a player.
> 13 votes

# Answer
This doesn't look like the Singleton pattern. The way I understand it, you're passing an object with references to important game-objects to all of your instances.

If this would be the Singleton pattern, you would have:

```
AudioManager.getInstance().playSound(XY);

```

Whereas in your case you might have:

```
this.gateway.getAudioManager().playSound(XY);

```

It looks basically the same, but it really isn't. If you would want to replace `AudioManager` with a new (extended class) like `ExtendedAudioManager`, you would hit a wall using the Singleton pattern. Your gateway approach will handle that just fine though.

The drawback of your approach is that you'll have to pass around the `gateway` everywhere. The service locator pattern (proposed by Joe Wreschnig in this thread), looks like a good replacement for your "gateway pattern".

Sometimes it's better to just run with the simple and straightforward method instead of over-designing things though. Especially when it's a small project or a prototype. Maybe you could make that `gateway` some sort of a global variable.. eg. `Game.gateway` and run with it.
> 0 votes

# Answer
Most solutions to this problem, including the Singleton pattern, involve the use of static variables. If you'll only ever have one player, you can just have Player be a singleton class, which means you could access the Player instance through something like Player.currentPlayer. Many people rage against Singletons, however. You could also have a ResourceManager or similar class that contains static references to various useful global or pretty-darn-global variables. In your code, you might as well make "Gateway's" variables statically accessible instead of inflating your code by passing it around everywhere.
> -2 votes

---
Tags: architecture, flash, actionscript-3, design-patterns
---


# Question
Title: Creating a top-view racing game, do I have the right ideas, any suggestions?
I am creating a top-view, multiplayer, arcade-ish racing game, and I want to know if you guys think that I am on the right track, or not. It will work basically like this:

-There are 3 races, and one demo derby in a round.

-Each race will be a 15 lap circuit (they are very small tracks, the tracks will be visible within the entire screen, tracks will be chosen at random.)

-The winners will be displayed after each race, in leaderboard style. 1st place- 100pts. 2nd place- 75pts. 3rd place 50 pts. 4th and below- 10pts.

-After all 3 races, averaged scores will be displayed; the final top 3 scores will then battle to the death in a demo derby "bonus round" type thing. (This will also serve as a tiebreaker, if that is necessary.)

-The winner of the demo derby will receive 250pts., all others including non-participants get nothing.

-The person with the highest averaged pts. at the end of each round wins, and a new round begins.

-I also plan to include a garage type thing, where you can buy, upgrade, and customize cars.

And that’s about it. Does my basic idea sound correct? Do I have any flaws? Please give me ways I could improve/edit this, thanks!

# Answer
> 3 votes
* The core gameplay is the most important part of the game, making it "fun" should be done as soon as possible. Developing scoring rules should be way down the list of considerations.
* It is almost impossible to tell if the rules "feel right" without actually having experienced them. For instance, 15 laps may be too long or short, and the points for different places may be too unbalanced. Make the game with any set of rules you think might work, test it, get others to try it, and use their feedback to tweak and refine the game rules until they're perfect.
* Also, ideally you should let the player configure the game rules, including setting the number of laps per track and the number of races in a round.

# Answer
> 3 votes
> -After all 3 races, averaged scores will be displayed; the final top 3 scores will then battle to the death in a demo derby "bonus round" type thing. (This will also serve as a tiebreaker, if that is necessary.)

This throws up an immediate red flag. You don't want rounds that don't include all players. If you have 8 total players and 5 of them just have to sit there and watch the last round they will quit.

> The winner of the demo derby will receive 250pts, all others including non-participants get nothing.

Second red flag. A player who places first in the first 3 races only has 300pts a player who places in 3rd for 3 races has 150pts. What this means is that the first three races are only important for getting into the final. But they are effectively thrown out as the winner of the derby effectively wins the whole round.

This is doubly troubling since derby and racing are different skill-sets. So your winners will always be the best derby drivers who have just enough racing skill to get into the final round.

# Answer
> 3 votes
Red flag: your design is missing a "hook" -- what is it about this game that would make someone want to play it? There are only about a zillion racing games, ranging from hyper-realistic NASCAR to powerup-based kart-racing, 2d to 3d, single to multiplayer. There are racing games for arcade, console, and PC, and probably a bunch for Web and smartphone, too. I'm not seeing anything in your design that hasn't been done before many times; where does this game stand out? What does this game give you that you can't get from dozens of other similar games in the genre? Start there, before figuring out details like point scores and number of laps.

# Answer
> 1 votes
This sounds like a great startup project if you don't have much experience with game programming.

I wouldn't necessarily think you need a "Hook" unless you plan to really allow the game to take off. However some considerations I would keep in mind.

You Garage system needs a great deal of emphasis in design and how much customization you allow (the more the better). To me as a gamer, this is what makes games insanely fun.

wkerslake is absolutely correct, you do not want rounds that do not include everyone. Consider changing this in someway, perhaps you can somehow include those players but controlling hazardous obstacles and power-ups during the race. This might introduce a degree of politics in your game! =)

Remember, its YOUR game and YOUR design. If its good or bad you still made a great game!

---
Tags: game-design, multiplayer
---


# Question
Title: Game Scripting Example in any scripting language
If i have to create a Battle System for a game which is like Final Fantasy 10 Turn Based battle system or Shadow Hearts Ring Based Battle System and likewise.

How should i start with scripting a particular part of the game? Any reference,blogs,sources,code snippets will be helpful.

Any scripting language will do as i have to overlook some examples directly of different scripting languages.

Please try to provide a small example of scripting for some part of game say cutscene,battle,combat system etc. in UnrealScript.

# Answer
> 6 votes
Lua is what's often used for game scripting, and the big reason for this is that its libraries are small, it has a fairly small memory footprint, and it's pretty simple to integrate with c++.

Before you begin to script or choose a language or start to integrate support for a language you need to have a good idea of what you want your scripting system to be able to do, and you need to prepare your underlying code to support it. You ought to isolate actions that you want the scripting system to perform so its easy to write wrappers for the scripting system to access this code. If you do this, it will be much easier to set up and effectively use ANY scripting system you want.

For example, if you are doing a topdown rpg, you probably have a way to walk around on your c++ layer. You want your scripting system to be able to tell your NPC to walk from point A to point B, so it's important that your walking logic is in its own function in c++. This can be a black box to anything outside of it...all your scripting system and the rest of your c++ code needs to know is that this function will cause your player to walk from point a to point b. Your input system calls this function when you use the wasd keys. Your lua script calls it when you call actions.walk(mypointer, pointA, pointB). This seems really obvious, but a lot of people just code by the seat of their pants and don't think about design. At this point, integrating the walk function becomes a matter of wrapping your c++ function in a glue wrapper and handling parameter passing between the scripting language and c++.

# Answer
> 1 votes
World of Warcraft uses Lua for scripting. There are a lot of tutorials about Lua:

http://csl.sublevel3.org/lua/

http://lua-users.org/wiki/LearningLua

---
Tags: scripting
---


# Question
Title: Can custom maps in Starcraft 2 automatically enable certain unit upgrades?
If I create a custom map with the Starcraft 2 map editor, how can I specify that some unit upgrades are already researched?

For example, if I want all the units to already have the weapons upgrade 1 at the beginning of the game, can I specify this in the editor?

I've looked through the menus but didn't find anything that looked like it would relate to unit upgrades.

# Answer
> 4 votes
To enable upgrades or set other special properties for a map you have to use a trigger that is executed at the start of the game.

In the map editor, `Modules -> Triggers (F6)` opens the trigger editor:

The only default trigger is "Melee Initialization", which is executed at the start of the game. New actions can be added to this trigger by choosing `New -> New Action (Ctrl-R)` in the right pane's context menu. Searching for "upgrade" brings up the correct action to add:

Double-clicking on `Upgrade: (No Value)` then shows a window that lets you choose which upgrade you want to enable for the player.

The action created this way will be executed at the start of the game and enable the selected upgrade.

# Answer
> -1 votes
Since I don't have the editor at hand at the moment I can't answer you accurately... I can however tell you with some confidence that YES it is possible.

I have used the Warcraft III editor extensively, and I know there's a way to do this in that editor. There is no reason for it not being possible in the SC2 editor.

Look under the upgrades section and see if you can find a field called starting value or something. I know there's some section where you can define the starting value of your upgrades, and the maximum number of upgrades of that type.

Sorry I can't give you anything more specific.

---
Tags: maps, modding, starcraft-2
---


# Question
Title: Self-set vs explicit goals and their efficacy
Just curious if anyone has an insight onto the efficacy of self-set goals as opposed to explicit ones in regards to player retention.

Content requirements aside are there any anecdotal or quantitative results on which method provides a more immersive experience for a player, and thus is more likely to keep them around and playing?

# Answer
> 2 votes
Usually you want a bit of both. Dwarf Fortress and minecraft are popular for their emergent gameplay. however, World of Warcraft is almost 100% explicit drag-you-around-by-the-nose goals.

Both are quite popular.

Explicit Goals can be extremely boring if they're not tied to purpose, or good rewards.

Emergent Goals can be frustrating if the user isn't given enough tools or background information to formulate their own.

Games like Fallout 3 and Mass Effect offer a bit of both. They give you a completely immersive world, with explicit goals that feel like they are self-set. The illusion of player control and suspension of disbelief are key to any game that wants to retain players.

I don't know of a lot of research, but I did find this.

# Answer
> 0 votes
Players are not the same: some people are keen to establish their own goals, but others need a lot of hand-holding. And some people may be different at different times: maybe they want a casual game with explicit goals for their commute, but then are willing to put in more thought and effort on a solid weekend session.

A game with self-set goals tends to have more gameplay in the long run, but be harder to get into in the first place (you need to understand a lot about how the game works before you can start to set appropriate goals) and have a smaller audience. It's also more work for the developer to make a world with enough possibilities and flexibility for players to be creative.

So it all comes down to, what kind of game are you trying to make? What kind of players are you trying to appeal to? And what's your budget?

---
Tags: game-design
---


# Question
Title: Multiplayer architecture in games like Diablo 2
So I've been wondering, what kind of architecture would games like world of warcraft, diablo 2 (which is most probably a different beast than WoW) use?

As far as I know, RTS games state-syncs every client and server, and the input from the clients get relayed to the server, and all states from all clients will get the same input, because everything is synced.

And because everything is synced, state changes can be done safely, thus allowing large numbers of entities in the game (e.g zerglings), because the clients only need to know the players' inputs.

This is all fine and well, but AFAIK diablo 2 allows players to join servers mid-game, which leads me to believe they use a different architecture. I'm stumped on how they do this though, and if elegant solutions exist for such a thing. Does anyone have a better idea?

# Answer
> 2 votes
I don't know about D2 specifically, but I would imagine it is similar to most MMOs out there. Our basic method is that when new clients connect they request the entire state of the area around them (for D2 it would likely just be the state of the whole server) and then from that point on the server just sends differential updates.

# Answer
> 1 votes
I dont know anything about the network design behind Diablo or the rest you mention, but I would, make a "node based" mapsystem and when people join you only need to sync them with the current node + surrounding nodes (those directly connected) then you can always update those outside viewpoint once you reach the "border"...

Consider the tiles in a map Like this, I have filled it with the same pattern as A\* pathfinding to figure out which tiles are closest to my "X" (starting/current location)

```
....3.......
6...2.......
5...1...567.
4321X1234.89
....1...567.
..43234.....
.65..456789.

```

Sorry there might be some "wrong numbers" as I just did them very quick by hand, but the idea is that I would say from my X - update the client initially with up to 10 nodes/distance from my location.

By using star algoritme logic, I can quick figureout which part of the map I need to provide to the client. Once the client is update, and begins to move, I just keep updating the outer border in the direction the client moves.

I dont know if this idea/plan makes any sense, but I hope you can use it somehow.

---
Tags: architecture, multiplayer
---


# Question
Title: What new programming languages are being used to develop web-based games?
I've got around 10 years behind me of casually creating AS1/2/3 games and have found myself wondering recently what other options are available for web-based games.

I have recently found haXe and will probably start coding in that, since it is largely based on AS3/ECMAScript, and I am also aware of JavaScript/jQuery etc and HTML5 being suitable for purpose, but what else is there?

What up and coming languages are being used to develop / are targeted at making web-based games?

# Answer
You're on the right track with HTML5. Most of the tech around it is certainly not "new" per se, but JavaScript games being considered for real-world game development is. Mozilla recently started an initiative called Game On 2010 which is getting a lot of attention, so you can bet that Canvas and JavaScript-based games will be picking up tons of speed in the next few months.

Another choice for web-based games would be Unity. The major downside is that the games require the Unity browser plugin, and its penetration is very low at the moment. While something like 90%+ of average Internet users have installed flash, Unity is much lower (in the single digits last I read). That said, Unity is very powerful and has been gaining lots of ground with developers this year.

Most modern browsers can handle almost all of the tech that HTML5 games require. The biggest hit in user base is currently that Canvas isn't supported in current versions of Internet Explorer, but that'll change when IE9 is released. So my suggestion is definitely to beef up on your understanding of JavaScript and Canvas.
> 6 votes

# Answer
I've seen a number of interactive "things" lately done in Processing. Not sure I would call most of them games, but they are on that spectrum.
> 1 votes

# Answer
I am going for Unity3D as I like the fact that I can develop crossplatform once I buy the license for this game-engine.

For a start I will do Webbased crossplatform (PC/MAC) applications, but later I might go for the smartphones.

I've done some stuff with Flash and Actionscript 3.0, but I feel that I have to reinvent too many things for games, Unity3D fx. comes with build in Physiscs, 3D world, camera, lights, texturemapping, shaders, collision, input-controls, sound engine etc. I know it needs to be installed (2 mb plugin) but its very fast to install and the results looks stunning compared to most of the 3D samples I've seen so far with Flash.
> 1 votes

# Answer
Have you considered Silverlight?
> 0 votes

---
Tags: web
---


# Question
Title: Should I share the same tile structure for display and pathfinding?
I know how to display a 2D map with tiles.

I know how to make a pathfinding algorithm using A\*.

Those two things demand a structure or a class. My question is : do you use the same structure for displaying and path-computing ? Node structure for pathfinding demand to add some data : x position, y position, F, G, H plus the Parent Node. Tile structure for displaying can be optimized to almost only one information : the value of the tile.

Do you use a big class for your tiles, that handle both displaying and pathfinding, or do you use a different method ? Thank you for your advices !

# Answer
> 6 votes
> My question is : do you use the same structure for displaying and path-computing ?

No, I don't. You can get some optimisation out of calculating your A\* directly onto the tile-map, but then you can't easily use your A\* algorithm for things that don't map directly to the tiles. Also, it means you can't run the A\* algorithm simultaneously in multiple threads as they end up sharing the map data. Finally, certain methods of moving don't allow the tile=node optimisation; a vehicle that needs space to turn around could potentially arrive at the same tile from different directions and have different options in each case - they can't be merged into one score.

So I suggest keeping the data separate.

# Answer
> 3 votes
From a software development perspective, it's always good to **keep different things separate**.

For a quick and dirty solution, put everything together and start working on game specifics.

For an extendable solution, keep things apart: you don't want to be changing tile classes because your pathfinding algorithm got changed! Keep two structures: one representing visible game tiles and one representing the pathfinding structure. Ideally, a pathfinding algorithm is kept low level, so maybe an array of x,y points as input to the algorithm is a better idea than to provide it with your tile classes. The algorithm itself can setup arrays for F,G,H values.

I think in this case (and I assume that you strive to be a good programmer), you should go for the extendable solution, because it won't take you that much extra effort but it keeps your code cleaner and you will gain good practice experience.

# Answer
> 2 votes
I was once building a tilebased game on the Amiga 500 with 512x512 tiles but the player could only move 8 tiles, so I generated a "9x9" tiles "wall map" pr. soldier. If I had done this with the original map, I would first of all have had to "clear it up" after each calculation + the amount of memory needed to have both tile data + pathfinding data would make 512x512 become a much begger memory hog.

So no, keep things as small as possible and seperate so you can tweak them pr. object/class if needed. Another thing to think of might also be that some of your moving objects MIGHT move differently over certain parts of the map. Eg. slow in sand, can/cannot swim, can open doors etc.

---
Tags: path-finding, tiles, data-structure
---


# Question
Title: What resources are available to read and share pyglet code?
I am a Python programmer (I know the ins and outs decently well), and I have dabbled with Pygame. I want to make 3D applications and games, and so naturally I've been looking at OpenGL.

pyglet uses OpenGL, and the programming website and documentation is up there with the best I've seen as far as libraries and APIs go.

Is there a place on the net where other pyglet programmers go to share projects and source code, like there is for Pygame?

I would love to see how other people are combining game logic and OpenGL graphical code to create a simple game (it really helps the learning process).

# Answer
pyglet has a mailing list but no active web presence (or development at all) right now. In general people working on pyglet code are encouraged to submit to pygame.org, and many also participate in PyWeek; there are many completed pyglet games there, although because of the time pressure the code is usually not great, even when the programmers are skilled.
> 4 votes

# Answer
People post things made using Pyglet and PyOpenGL to pygame.org. The games list is open to anything in Python, not just the Pygame library.
> 2 votes

# Answer
I wrote a lengthy post about producing retro vector graphics using OpenGL from pyglet:

https://www.tartley.com/posts/flying-high-opengl-from-python-part-2/
> 1 votes

---
Tags: 3d, opengl, python, pyglet
---


# Question
Title: Generating background tiles for a side-scroller with variable player speed
I'm currently working on a side-scroller which lets the player alter their speed and I wondered how should I properly generate and control background tiles for such a kind o game. I'm using Flixel but I believe it's a strictly mathematical problem. Here's how I see and do it right now:

* actually the player is static but he has a pseudo-velocity, that can be increased and decreased (but there is some minimal pseudo-velocity)
* tiles are random so they are not kept in any tilemap - they are generated by an emitter instead
* background tiles observe player's pseudo-velocity and alter their own velocity (base velocity is static for a given tile but different tiles can have different base velocities) based on it (so they use their velocity to move in the opposite direction to the player but they also increase/decrease this velocity according to the player to create the illusion of acceleration/deceleration)
* the starting velocity of each background tile is maintained no matter what the pseudo-velocity of player is (so when the player accelerates, two given tiles with different velocities approach faster to the player but there is no change in the delta of their velocities, so you can say that one tile aproaches the player fast and the other even faster :-))
* background tiles are generated based on same frequency which is also dependend on the player's pseudo-velocity (so when for example the velocity of all tiles is constant, the distance between consecutive tiles is also constant but when the player accelerates, the frequency of tile generation should increase to retain the same distance between generated tiles)
* and the last one trick: when the player is moving at minimal speed their sprite is located exactly on the center of the screen but when they accelerate the sprite floats to the left edge of the screen (proportionally to the current speed but with some lag) so the player can see more and has more time to react

Ok, now it's finally time for the problems! :D

* I cannot come up with the proper formula for the tile generation frequency according to the player's pseudo-velocity (when the player accelerates the frequency increases too slowly and the distance between tiles increases, and when the player decelerates the frequency decreases also too slowly and the distance between tiles gets much too small, they begin to clutter)
* the problem is also intensified by the last point of the above list - when the pseudo-velocity increases the player's sprite is moved to the left so the tile generation frequency should be additionally increased (and respectively delayed during player's deceleration)

Phew! I think that's a whole description of the problem. Has any of you ever fiddled with such a game mechanic and if yes, have you encountered similar problems and what were your solutions?

If the description is not clear enough, please let my know and I'll provide working example showing above concerns.

# Answer
I think you should make the algoritm work differently.

Place your "view" in an array (2D tilemap) and then look forward eg. 20 tiles. The "scroll" is the amount of pixels for 1 tile, so if your scroll becomes negative, just add the size of a tile, and increment offset for "view" with 1. Repeat until scroll pos is postive again.

Then repeat this pattern each frame.

Here is my suggested loop in pseudo programming language.

1. ScrollPos -= speed;
2. while (ScrollPos\<0) { scrollPos += tilewidth; viewOffset +=1 ; if (viewOffset\>has }
3. "Reposition every active tile inside view" (called updating the frame)

The ScrollPos is the "fraction" of a tile. The viewOffset is the current screen/view position in the tilemap (left side of screen)

Array/tilemap is needed pr. "row" of background. You could do this in multiple levels too, to produce a "parallax" depth - and with 3D this might look even more cool.

```
var back[10] : array;
back[0] = ".....................X.........X........X...........X............XXXXX"
back[1] = "....................X.........X........X...........X............XXXXX."
back[2] = "...................X.........X........X...........X............XXXXX.."
back[3] = "..................X.........X........X...........X............XXXXX..."
back[4] = ".................X.........X........X...........X............XXXXX...."
back[5] = ".................X.........X........X...........X............XXXXX...."
back[6] = "..................X.........X........X...........X............XXXXX..."
back[7] = "...................X.........X........X...........X............XXXXX.."
back[8] = "....................X.........X........X...........X............XXXXX."
back[9] = ".....................X.........X........X...........X............XXXXX"

```

Now start with "offset=0" and perhaps look 15 tiles ahead (depending on screen and game size).

Everytime you scroll a tile, your viewOffset will give you an extra "cell" this means that the most left set tiles must be destroyed and a new set should be inserted.

I think I might do it vertically instead of horisontally while displaying the tiles, because the horisontal arrays makes it easy to build a level here, but the vertial array would make it easier to scroll in realtime I think. But you decide.

Look up how the old "snake game" is build too. There is the idea too, as the head and the end of the snake is a matter of positions in a growing array (same trick with the view here, just a "horisontal snake pr. row".

Does it make any sense?
> 2 votes

# Answer
Don't 'spawn and move' individual tiles. That way will only lead to pain.

Create a big 2-dimensional array of tile types (the 'tilemap') containing your whole level, and display the section that is currently on-screen.

Just keep track of a 'scroll position' - either the location of the top-left or centre of your screen measured in pixels within the entire tilemap. Then use this to determine which range of tiles to draw, and where they should be on the screen.
> 0 votes

# Answer
It appears that the problem was the tile generation algorithm itself. I've completely rebuild the mechanism according to the solution given here: http://forums.tigsource.com/index.php?topic=15642.msg450370#msg450370

So instead of applying velocity adjustments to each and every tile and generating one tile at a time with adjusted frequency, it proved to be much easier and efficient to just generate tiles in groups that can be refilled with tiles and reused after they get out of the screen.

I hope this question (and answer) will be useful for someone.
> -2 votes

---
Tags: 2d, mathematics, actionscript-3, tiles, parallax-scrolling
---


# Question
Title: Developing 3D card game. Is C# good enough?
I was thinking of developing several rather simple card games in DirectX (3D), but I'm not sure if C# and XNA are powerfull enough for this.

Perhaps the most appropriate question is: can you choose one or several already available 3D games that you think are the best XNA can achieve?

# Answer
Yes.

See also this question: What are some famous games developed with .NET and/or XNA?
> 6 votes

# Answer
You're thinking about it all wrong. XNA pretty much is DirectX 9 for C#. Especially on the PC where there is little overhead on the draw calls compared to the Xbox 360. Further more, any shader code you write will run exactly the same as it would using DirectX 9. Therefore, almost everything that can be done with DirectX 9 can also be done with XNA.

The question you should be asking is "would I benefit from using c++ over c#?".
> 3 votes

# Answer
Now you even have a starter kit for XNA for card games:

http://create.msdn.com/en-US/education/catalog/sample/blackjack
> 2 votes

---
Tags: xna, c#, directx
---


title: World of Warcraft servers

text:
# Question
Title: World of Warcraft servers
Does anybody knows or have any info about the OS of the servers of World of Warcraft?

I have a "debate" with some friends about the OS behind WoW. They say it could be Win, which is very strange for me.

# Answer
Most MMOs use Windows for servers mostly because of Visual Studio. VS is basically the only development and debugging environment that is worth its salt (cue \*nix users saying that gdb is just as powerful as VS). This means that we all are generally developing both the clients and servers on Windows, so it is just easier to also deploy on Windows. There are some out there that will cross-compile the servers for production (clients are clearly always targeting Windows at the very least, even if you have a Mac version) but it ends up being a hard thing to maintain and it makes debugging production systems that much harder. The big exception is web-based games, those are almost always Linux based (and usually running Apache and/or Nginx).
> 1 votes

---
Tags: mmo, operating-system
---


title: .XNB file reader

text:
# Question
Title: .XNB file reader
I'd like to open an XNB file on Linux.

It should be an `XNA Game Studio Express XNA Framework Content Pipeline Binary File`.

Any tool to open it? (also for windows which I can emulate on wine)

# Answer
> 6 votes
The GXView program inside Gametools Suite should do the work, although I haven't tested it myself.

---
Tags: xna, file
---


title: Webworkers HTML5 for game AI?

text:
# Question
Title: Webworkers HTML5 for game AI?
So I am designing a game like scrabble in which a user has to make words using the letters on the screen. When the there is no possible combination of word that can be made with the letter the game is automatically supposed to tell the user to shuffle. Which changes the present set of alphabets with a new set (odds are very very very low that the new set cannot form a word either.)

So I now its a simple word game, but I am making this on HTML5 Canvas. It hugely resource consuming. And I need to run this even heavier computation on the client machine of whether a new word is possible from the selection on the screen. Ideally I would run a thread were this an app for the native code, and check after every new word created whether new words are possible with the remaining alphabets. Alas on the web browser I am afraid, it will toast the computer, crash the browser and a lot of other horrible things. So I would like to know is there a way that I could make such a computation feasible with all the other actions I am already running!?

Thanks

# Answer
> 2 votes
You can't rely on web workers for anything practical, they are missing in way too many browsers.

In any case, this is about finding and implementing an efficient algorithm.

Here is how I would do it, presuming the rules that new letters must be connected to existing, and that they may only be placed in a single row or column:

First make an index of words and wordparts. A single JS object containing all words and wordparts as index, and a value to determine if an index is a word or a wordpart. E.g. for the word "old" the object would have to contain `{"old":2, "o":1, "l":1, "d":1, "ol":1, "ld":1}` where the value 2 denotes a legal word, and 1 denotes a part of a legal word that is not a word on it's own.

```
For each open space next to at least one letter
  Try placing each letter on the players hand on the space
    If the placed letter connect to other letters both horizontally and vertically
      Check the value of both formed words in your index
      If both values are 2 you have found a legal move and should stop searching
      If one value is 1 and one is 2 you need to try expanding the value 1 word
        For each letter added any word in the other direction must have value 2
        If the word being expanded reach a state not in the index no further
        expansion will make it legal
        If it reach value 2 you have a legal combination
      Else that letter placement can not be part of a legal combination
    Else
      Check the value of the word formed
      If the value is 2 you have found a legal combination
      If the value is 1 continue like the 1,2 combination

```

# Answer
> 0 votes
I think you should just first start by implementing this without WebWorkers. Then measure and see how much it slows down the browser. If this is as bad as you think it will be, then go for a Webworker. This shouldn't be a very hard refactoring if you structure your code well.

---
Tags: ai, web, html5
---


# Question
Title: MYST/RIVEN and Quicktime Video Integration
How was Quicktime video integrated into the MYST series games? I was watching a Making of MYST video and noticed that they used a small green screen and for the sequels like Riven they continued to use a green screen but with a much bigger stage. How is it that they match up the video file and integrate it seamlessly into the game? I'm really curious as to how they did it with Riven, where full body actors actually move around with a greater degree of freedom.

My guess is that the video recording is an exact duplicate of a pre-rendered scene. When the player enters into a certain area where a movie is supposed to take place, the video is drawn onto the screen and played. After the video ends, the pre-rendered screen is drawn back to the screen that reflects the changes that took place in the video.

Any other ideas how it might have been done?

# Answer
I wouldn't know where to find them anymore, but the Miller brothers made a lot of "making of" type stuff for Myst at least, and it is basically as you describe except with a heaping helping of manual effort and tweaking to make it look good.
> 1 votes

---
Tags: methodology
---


title: Must read game development books

text:
# Question
Title: Must read game development books
Let's make a list of the best books that every game developer should read.

Each answer should have a single book (by title and optionally author), a link to buy the book, and a short synopsis of what the book is about.

# Answer
**Game Programming Gems, all of them.**
**Internet Archive: Game Programming Gems**

Even just reading them will give you a lot of ideas and insights in different approaches that will spark your thought processes and will give you a nice interdisciplinary toolbag. Also, lots of references to other interesting works.
> 57 votes

# Answer
**Game Engine Architecture by Jason Gregory**
Touches on most areas involved in game development. Because of the number of subjects covered the book doesn't go into depth in any specific area but gives a broader view. I recommend anyone interested in game development read this book.

**Real-time Rendering**
If your interests lie in 3D rendering; this is **the** reference book to own. The book is theoretical and requires the reader have strong math skills.

Also if you're developing shaders (then you probably already know this but) the ShaderX series are a great read, and the series will continue under the name GPU Pro. (I have not read this one yet though)

**Real-Time Collision Detection by Christer Ericson<br>**
Collision detection has always been an integral part of game development, and this is a great book on the subject covering a huge area.
> 45 votes

# Answer
**The Art of Game Design: A book of lenses**

**A Theory of Fun for Game Design**
> 26 votes

# Answer
**Mathematics and Physics for Programmers**

I see no one talked about this one, wich I think is a must-must for any game programmers. A lot of good stuff about mathematics used in video games like trigonometry, vectors, ballistic and collisions and some more complex motion laws. It's a must have in your bookshelf !

---

And I almost forget... "**Clean Code**" and "**The Pragmatic Programmer**" are really nice books to read and keep not too far when working in a developer team. Teach you about how to make good programs that will save time and money to your team.

Don't have the Rep to post more than one hyperlink sorry...
> 26 votes

# Answer
**Programming Game AI by Example, by Mat Buckland**
> 24 votes

# Answer
**The Pragmatic Programmer: From Journeyman to Master**

I learn something every time I read this.
> 19 votes

# Answer
For Programmers:
> 16 votes

# Answer
**Real Time Cameras**
I really liked this one. Its contents are pretty standard in terms of engine/rendering structure, but it also considers game narrative through cameras.
> 15 votes

# Answer
**The Design of Everyday Things**

Someone said it's a must read for all programmers and I completely agree with that.
> 15 votes

# Answer
**Game Coding Complete 3rd, Ed.**

This one is great for programming best practices and tips from the trenches. Tons of game programming books have you go down the same path with whatever scripting language or engine they are pimping. This book goes into WHY you should do things for game development. For example, the networking section talks about why you should do things for games that normally would never be done for non-game applications. Those nuggets of information, backed up by experience, are priceless.

For game design, the best book, hands down, is The Art of Game Design (linked in other answers)
> 13 votes

# Answer
**Game Engine Architecture**

It gives an overview of a game engine.
> 11 votes

# Answer
**Code Complete 2**

Although it is a general programming book, you shouldn't miss it! It teaches you a lot of things every programmer should know.
> 10 votes

# Answer
**The Pragmatic Programmer : Journeyman to Master**

If I'm putting together a project, it's the authors of this book that I want. . . . And failing that I'd settle for people who've read their book." -- Ward Cunningham

A book that present tips on various topics. The book doesn't need to be red from the beginning to the end, just read about the tips you want ! Here are the topics covered :

* Fight software rot;
* Avoid the trap of duplicating knowledge;
* Write flexible, dynamic, and adaptable code;
* Avoid programming by coincidence;
* Bullet-proof your code with contracts, assertions, and exceptions;
* Capture real requirements;
* Test ruthlessly and effectively;
* Delight your users;
* Build teams of pragmatic programmers;
* Make your developments more precise with automation.
> 10 votes

# Answer
**Game Development Essentials**

I'm just starting them but the series looks promising.
> 7 votes

# Answer
### Tricks of the 3D Game Programming Gurus

All Aspects of the 3D Pipeline and how to optimize and implement them in software most efficiently as possible. Has many techniques that transfer to hardware well too.
> 7 votes

# Answer
**Introduction to 3D Game Programming with DirectX 9.0c: a Shader Approach**

This was the best book I've ever found on teaching game/graphics development. It starts with an overview of the math involved and moves on to explaining DirectX. But the lessons can useful beyond DirectX: it explains, at a mathematical level, lighting and shadows and normals and many other things.

I recommend it for all the newbies like me
> 6 votes

# Answer
**Rules of Play**

Personally, I'm a huge fan of this one for game designers. It offers a lot of examples and exercises for people looking into game design as a career.
> 5 votes

# Answer
**3D Game Engine Design and 3D Game Engine Architecture**

both by David Eberly, are quite good, if a bit heavy on the math.
**Game Engine Gems**

*just* came out, and I've been enjoying its content so far. It's been a lot more helpful in some areas than the Game Programming Gems series (of which I've read up to Vol. 5).
> 4 votes

# Answer
**Tricks of the Windows Game Programming Gurus (2nd Edition)**

This book taught me a lot...
> 3 votes

# Answer
**Design Patterns : Elements of Reusable Object-Oriented Software**

A must have reference book written by the GOF who are highly know in the litterature of programming. Begins with a quik presentation of each patterns in the book and then explain them one by one with exemples, when to use, UML representation and more.
> 3 votes

# Answer
### Programming A Multiplayer FPS in DirectX

Great book that covers making an FPS engine with DirectX with multiplayer and an engine that supports Octree and Occlusion Culling
> 3 votes

# Answer
**Programming Role Playing Games With DirectX** This is a great book that goes through everything about the basics of DirectX and Role playing games. It includes many examples that can be used for many different games. Some topics include:

1. Particles
2. Octree/Quadtree
3. Netplay (Client/Server and P2P)
4. Marketing your game
5. 1st and 3rd Person Cameras
6. FFVII Style Pre-rendered Background
7. Parsing and Displaying .X Models
8. Scripting
9. And a lot more.
> 3 votes

# Answer
**OpenGL Red Book**

This is a must have on your bookshelf as a developer.
> 2 votes

# Answer
**Game Scripting Mastery**

takes you up from the basics of scripting to assemblers, compilers and virtual machines. I love this book.
> 2 votes

# Answer
**Refactoring : Improving the Design of Existing Code**

I think this book is the logic one to read when you finish Clean Code (See other answer). It teach you how to deal with bad design of code and rework it into well-designed, robust code. The author present you how to deal with such code in a nice and easily-understandable way. A must have in your bookshelf !
> 2 votes

# Answer
**David Perry On Game Design: A Brainstorming Toolbox by David Perry, Rusel Demaria**

---

It's the biggest book on game design ever written, at over 1,000 pages long. It's designed to help students & designers come up with innovative new ideas, and also to expand current ideas.
> 2 votes

# Answer
**"For The Win"**

This is a novel book but seems like a perfect book for Gamedev according to me. Free download at http://craphound.com/ftw/download/ by the BoingBoing founder.
> 1 votes

# Answer
The Mastering Unreal Technology books are really good for learning how a great engine works. Learning how a great engine works doesn't necessary teach the nuts and bolts of how to create an engine. But, it will teach you the features of a great engine and how those features should work.

There are two versions of the books. An older book and a new set of three (, , )
> 1 votes

# Answer
**Rapid Development (Amazon.com)**

Even though it's more about the development process than actual programming, I'd still recommend anyone involved in development to read Rapid Development (the "other" Steve McConnell book)
> 1 votes

# Answer
**Creating Interactive Fiction with Inform 7**

Although I'm not nearly a good enough writer (yet?) to do much with Inform 7, I think the platform is a model for accessibility in programming, and a great environment for game designers with weak programming skills as well as strong programmer/writers.

Aaron's book is a worked example of a full Inform project, and goes into details on writing styles for interactive fiction as well as the technical details of the Inform language, interpreter, and editor.
> 1 votes

# Answer
**Clean Code**

A nice book that teach you how to write code that can be easily understood, a must-read that taught me much more than I though at first. Talks about meaningful names, comments, functions, formatting, objects and data structure and much more. I highly recommend !
> 1 votes

---
Tags: books
---


# Question
Title: How to model multiple "uses" (e.g. weapon) for usable-inventory/object/items (e.g. katana) within a relational database
So I'm working on expanding the uses of items over at www.ninjawars.net, and I'm not exactly sure how to represent them flexibly in the relational database that we use.

I may be barking up the wrong tree, so feel free to make suggestions in other directions, but currently I'm thinking that each item should have relational "tags".

For example, a Katana is currently a row in the "items" database. To make it into a weapon, and a holdable thing, I was thinking that I would have a database of "traits", and a item\_traits table that simply linked between them.

```
// Objects and their basic data

item_id | item
1 | Naginata

// Things that objects can do

trait_id | trait
1 | weapon
2 | holdable

// How those objects do those things, e.g. powerfully, weakly, while on fire

_item_id | _trait_id | item_trait_data
1 | 1 | damage: 5, damage_type: sharp, whatever, etc

```

I'm not really sure how to model the extra data that results (e.g. the damage that a sword will do, the damage\_type, etc).

I'm also not especially happy that the whole of an item would be stored in more than one place, e.g. in order to create a copy of an item with a different name, like a "short sword", I would have to copy from multiple tables to create the duplicate item.

Is there a better way to lay this stuff out that I'm missing?

**Edit:** I should just note that I've already got a postgresql database in use on the site, which is why I want to use it for my data storage.

**Edit:** I've added an answer for the implementation that I'm currently looking at.

# Answer
Here's what I'm now considering:

Since every "trait" essentially requires changes in the code anyway, so I've decided to just keep the traits (and any default data they require) in the code itself (at least for now).

E.g. `$traits = array('holdable'=>1, 'weapon'=>1, 'sword'=>array('min_dam'=>1, 'max_dam'=>500));`

Then items get a "trait\_data" field in the database that will use the `json_encode()` function to get stored in the JSON format.

```
item_id | item_name | item_identity | traits
1 | Katana | katana | "{"holdable":1,"weapon":1,"sword":{"min_dam":1,"max_dam":1234,"0":{"damage_type":"fire","min_dam":5,"max_dam":50,"type":"thrown","bob":{},"ids":[1,2,3,4,5,6,7]}}}"

```

Plan is that items will inherit all the default stats from their parent traits, and will only have over-ride traits that specify differences from what the traits set as defaults.

The downside of the traits field is that while I could edit the json part by hand... ...it won't be really easy or safe to do so with data that's in the database.
> 0 votes

# Answer
I'm going to mildly disagree with everyone and say that the relational approach is reasonable here. What's interesting here is that items can have multiple roles. The main issue will be that the mapping between this relational layout and an OO layout in the code won't feel “natural”, but I think on the database side multiple roles can be expressed cleanly (without weird encodings or redundancy, just joins).

The first thing to decide is how much of the data is item specific and how much is shared by all items of a given type.

Here's what I'd do if *all* data is item specific:

```
// ITEMS table: attributes common to all items
item_id | name        | owner         | location             | sprite_id | ...
1       | Light Saber | 14 (Tchalvek) | 381 (Tchalvek house) | 5663      | ...

// WEAPONS table: attributes for items that are weapons
item_id | damage | damage_type | durability | ...
1       | 5      | sharp       | 13         | ...

// LIGHTING table: attributes for items that serve as lights
item_id | radius   | brightness | duration | ...
1       | 3 meters | 50         | 8 hours  | ...

```

In this design, every item is in the Items table, along with attributes that all (or most) items have. Each additional role that an item can play is a separate table.

If you want to use it as a weapon, you'd look it up in the Weapons table. If it's there, then it's usable as a weapon. If it's not there, then it can't be used as a weapon. The existence of the record tells you whether it's a weapon. And if it's there, all its weapon-specific attributes are stored there. Since those attributes are stored directly instead of in some encoded form, you'll be able to perform queries/filters with them. (For example, for your game's metrics page you might want to aggregate players by weapon damage type, and you'd be able to do that with some joins and a group-by damage\_type.)

An item can have multiple roles, and exist in more than one role-specific table (in this example, both weapon and lighting).

If it's just a boolean like "is this holdable", I'd put it into the Items table. It may be worth caching "is this a weapon" etc. in there so that you don't have to perform a lookup on the Weapons and other role tables. However, it adds redundancy so you have to be careful to keep it in sync.

Ari's recommendation of having an additional table *per type* can also be used with this approach if some data won't vary per item. For example, if the weapon damage doesn't vary per item, but the roles still vary per item, you can factor shared weapon attributes out into a table:

```
// WEAPONS table: attributes for items that are weapons
item_id | durability | weapon_type
1       | 13         | light_saber

// WEAPONTYPES table: attributes for classes of weapons
weapon_type_id | damage | damage_type
light_saber    | 5      | energy

```

Another approach would be if the roles played by items do not vary by item, but only by item type. In that case you'd put the item\_type into the Items table, and can store the properties like "is it a weapon" and "is it holdable" and "is it a light" in an ItemTypes table. In this example I also make item names not vary per item:

```
// ITEMS table: attributes per item
item_id | item_type    | owner         | location
1       | light_saber  | 14 (Tchalvek) | 381 (Tchalvek house)

// ITEMTYPES table: attributes shared by all items of a type
item_type   | name        | sprite_id | is_holdable | is_weapon | is_light
light_saber | Light Saber | 5663      | true        | true      | true

// WEAPONTYPES table: attributes for item types that are also weapons
item_type   | damage | damage_type
light_saber | 5      | energy

```

It's likely that itemtypes and weapontypes don't change during the game, so you can just load those tables into memory once, and look up those attributes in a hash table instead of with a database join.
> 10 votes

# Answer
Unfortunately, situations like this are where relational databases (such as SQL) fall short, and non-relational databases (such as MongoDB) excel. That being said, it is not impossible to model the data in a relational database, and since it seems like your codebase is already reliant on SQL, here is the model I would go with:

Instead of creating an item and uses table, create a table and "\[item\]\_type" reference table for each item type.

Here are a few examples:

```
weapon_type_id | weapon_type
1 | sharp

weapon_id | weapon| weapon_type_id | damage
1 | Short Sword | 1 | 5

potion_type_id | potion_type
1 | HP
2 | Mana

potion_id | potion| potion_type_id | modifier
1 | Healing Elixer | 1| 5
2 | Mana Drainer | 2| -5

```

This solution gives you a lot of long-term flexibility and scalability, it reduces (if not eliminates) wasted space, and is self-documenting (unlike "item\_use\_data"). It involves a little more setup on the developer's end, but, in my opinion, it is the most elegant solution available for situations where you need to use a relational database to store your data. Generally speaking, non-relational databases are much better for game development, as they are more flexible in how they model data, while being more performant than SQL-based databases - making them a "win-win" choice.

**Edit 1:** Corrected an error with the potion\_type\_id field

**Edit 2:** Added more detail on non-relational vs relational databases to provide additional perspective
> 3 votes

# Answer
First off, dump the object-oriented inheritance approach and go with a component-based system.

Once you've done that, the SQL layout suddenly gets far easier. You have one table for each component type with a shared ID number. If you want item #17, you go look up "item ID 17" in every table. Any table that has a key gets its component added on.

Your Item table contains all the required data for items in general (name, sell price, weight, size, anything else that's shared among all items.) Your Weapon table contains all the appropriate data for weapons, your Potion table contains all the appropriate data for potions, your Armor table contains all the appropriate data for armor. Want a breastplate, that's an entry in Item and an entry in Armor. Want a swordhelm that you can drink, you just put an entry in each table, and bam, you're done.

Keep in mind that this same pattern isn't particularly item-specific - you can use this for creatures, zones, anything else you may want. It's surprisingly versatile.
> 3 votes

# Answer
Using SQL was your grave mistake. It absolutely NOT suited for storing static game-design data.

If you can't move away from SQL, I'd consider storing items in a serialized from. I.e.

```
item_id (int) | item (BLOB)
1             | <binary data>

```

Of course, that's ugly and throws all the SQL "niceties" out of the window, but do you actually *need* them? Most probably, you read all of your item data at the game start anyway, and never `SELECT` by anything other than `item_id`.
> 2 votes

# Answer
Depending on how many traits you're likely to need you could use a simple bitmask for objects with the different bits corresponding to different traits:

```
000001 = holdable
000010 = weapon
000100 = breakable
001000 = throwable
010000 = solids container
100000 = liquids container

```

Then you can do simple bit tests to see if an object can be used for a certain function.

So "glass bottle" might have a value of 101111 meaning it's holdable, can be used as a weapon, it breaks easily, you can throw it and it can contain liquids.

Any editor you create for items can then have a simple set of check boxes to enable/disable traits on an object.
> 2 votes

# Answer
On our project we have **item\_attributes** for the different "extra data" that an item may have. It's laid out something like this:

```
item_id | attribute_id    | attribute_value | order
1        25 (attackspeed)       50             3

```

Then we have an attributes table that looks like so:

```
id |   name       | description
1    attackspeed    AttackSpeed:

```

Ari Patrick is right though, ultimately relational db's aren't made for this. The downside is that we have some pretty complex procedures to generate new items (done through an external tool - which I highly recommend, Do not try and manually add these, you'll only confuse yourself)

**The other option** you have is using a scripting language to create the item templates, then you can easily parse those in and use that to create new items. You still of course have to save the item data in the database but at that point you don't need to worry about specifics of creating new items, you can pretty much just copy and old script file, change some information and you're good to go.

Honestly, if we were to re-do how we create new static items we would probably go for a much simpler approach using scripting item templates.
> 1 votes

# Answer
This is your typical many-to-many relationship, nothing too esoteric for any capable relational database. You have many traits for any one objects, and any one trait may be used by one or more different object types. Model three relations (tables), with one being an association relation, and you're done. Proper indexing will assure you of speedy data reads.

Layer an ORM in your code and you should have very few issues going back and forth between DB and middleware. Many ORMs are able to auto-generate the classes themselves too, and so become even more "invisible".

As for the NoSQL databases, there's no reason you can't do it with those. It's currently fashionable to cheerlead for that technology in trade rags and blogs, but they come with a slew of its own issues: relatively immature platforms, great for simple infrequently-changed reads (like a one-to-many twits in a profile) but poor for complex dynamic reads or updates, poor supporting toolchain, redundant data and the accompanying integrity issues, etc. However, they offer the appeal of better scalability because they eschew to varying degree transactional capabilities and its overhead, and easier models of distribution/replication.

The usual hobgoblin of relational databases vs NoSQL databases is performance. Different RDMBSes have different degrees of overhead involved that make them less preferred for scaling to the levels of Facebook or Twitter. However, it is very unlikely you'd face those issues. Even then, simple SSD-based server systems can make the performance debate useless.

Let's be clear: most NoSQL databases are fundamentally distributed hash tables, and will limit you the same way a hash table in your code would, ie. not all data fits well into that model. The Relational Model is much more powerful for modeling relations between data. (The confounding factor is that most RDBMSes are legacy systems that are poorly tuned for the demands of the popular 0.0001% of the web, namely Facebook et al.)
> 1 votes

# Answer
This is where I find more modern OR mappers to be really useful, like Entity Framework 4 and its (CTP) code-first feature. You just write the classes and their relationsships in regular code and without even having to decorate them or manually run any tools, EF will generate the backing store in SQL format for you, with required link tables and all... it really unleashes creativity imo ^^
> 0 votes

# Answer
This is a bit hacky, and I make no guarantees it's good DB design; my DB classes were a while ago, and they're not coming quickly to mind. But if items are guaranteed to have, say, fewer than 10 items, you could give each item an attribute1 field, and attribute2 field, and so on up to attribute10. It would eliminate your need for the many-to-many item-attribute table, at the cost of limiting the number of attributes.

Looking back on that, I'm pretty sure it's terrible design, but it does mean you can stick with a comfortable relational database and not have to go into uncharted territory. It's up to you to decide if the trade-off is worth it.
> -1 votes

# Answer
Nevermind gave a good answer, but I wonder, do you even need a database for this? Storing all the data in a plain file and loading it into the program at launch seems like the smartest way of doing this.

Edit:
Right, in a stateless request driven environment you better keep the data in a database. Write your data in a file and write a piece of code to turn it into a database of the type Nevermind suggested.

Alternately if the number of objects is not too big declaring the lot literally in a code file may be the fastest method.
> -1 votes

---
Tags: architecture, web, databases
---


# Question
Title: Calculating Experience Points earned after a battle
I'm developing a simple text battle game and having some issues calculating how much XP should be earned after a battle, theres a few factors that i want to consider:

1) Players should of course earn good XP if they beat someone of the same level

2) Players should earn great XP if they beat someone of a higher level

3) Players should earn poor XP if they defeat someone of a lower level

4) The above should scale nicely, i.e. if player A is level 10 and battles Player B who's level 9 or 11 the difference shouldn't be huge (they would of course gain more XP for defeating the level 11 character but we wouldn't expect this to be huge), but if he was to battle a level 5 or 15 this difference should be huge.

Just having trouble calculating something that works well in all scenarios, currently my XP table looks like the below:

```
Current Level   XP Needed   Increase from Last Level
1   30  0
2   65  35
3   106 41
4   154 48
5   210 56
...
10  672 123

```

In PHP my code looks like the below to calculate the XP Needed:

```
$offset = 30;
$multiplier = 1.17;
$base = $prevXp * $multiplier;

$xp = $base + $offset;

```

I've tried a few different things but i haven't been impressed with any of them, I'd like to work with calculating the difference in XP and then using some kind of multiplier but i haven't been impressed with the results.

Any help / input would be appreciated.

# Answer
Two suggestions:

Exponents! Calculate some "base xp reward" for each level. Then the formula for a kill is base\_xp\_reward * pow(1.1, target\_level - player\_level). You might want to clamp the gain to a maximum, to somewhat nullify exploits, and you might want to give zero XP below a certain difference, to prevent farming of lowbies.

(Base XP reward can be a simple exponential progression also, if you like - constant\_factor * pow(1.25, level), perhaps. Then you can define the "exp to level" in terms of a multiple of the base XP reward. Might be easier to balance this way.)

Alternatively, let's make this really simple. Do the same base-XP-reward thing. Then figure out a table by hand for the bonuses you want from various level differentials. Make it ratio-based, so that killing someone one level above you always gives, say, 10% bonus XP over the base reward. And now you don't need to worry about a formula at all - you can just make the numbers do what you want.

Formulas are overrated, sometimes you just need to jam some numbers in and play it by ear.
> 13 votes

# Answer
I'd say something like "gain xp by the damage delt/recieved". So if a level 10 with 100hp fights a level 15 with 200 hp. It seems unfair but if the level 10 would be able to kill the level 15 he would get twice the xp of what he would get if fighting a level 10 with only 100hp.

Also this way you don't have to worry about stuff like if two people would fight the same enemy with different equipment. For example, if a level 8 and a level 10 fight a level 13. If the level 8 has better equipment/armor then he would get more xp then the level 10 simply becasue he delt more damage to the level 13.

But the most important thing: Set rules, playtest, set rules, playtest, set rules, plasytest, etc, etc...

Even the best MMOs from the best developers adjust their xp distribution system as long as the game lives.
> 2 votes

# Answer
Just IMHO, the most important thing to get right is the scaling amount of XP required to level up. A friend of mine used a fibonacci variation for his browser Rogue-like, for instance 100XP,100XP,200XP,300XP,500XP,800XP etc etc.

I have also heard of a mechanic in some games where the level is subtracted from the XP earned by each battle. For instance, if a particular battle earns 50XP, and they are at level 20, then they only receive 30XP. If they were at level 50 or above, they would earn nothing.
> 0 votes

---
Tags: game-design, mathematics, php
---