# Question
Title: What kind of system can I use to balance an RPG?
I'm developing a 2D RPG game, like Zelda. I've developed a first version, for studies. Now, I'd like rewrite it in better way

The character has strength, agility, willpower, constitution, dexterity and concentration and has to fight monsters. Typical.

But I'm a noob, and I would like advice for creating the game system that the characteristics for damages, level-up, resistance, and so on. The one I used in the first version was not balanced.

So, ***what kind of system can I use ?***

# Answer
I ran across a (now defunct) site a while ago, and there were a series of posts about this topic.

In part 1, the author talks about the basic formulas, and how different stats equate to damage, health, MP, and so on.

Part 2 is much smaller, and all you really need is to grab the word doc he links to in the post. It is a small document that goes deeper into the concepts talked about in part 1. He provides the base stat formulas, how to calculate attack damage, and some other examples. From what I have seen it is quite balanced.

The only thing I don't like about his approach, is how fast everything scales up. I just tweaked the math a bit to fit my taste.

---

I just realized that since the site is no longer maintained it could be taken down. For posterity sake, I mirrored the document on my own site.
> 9 votes

# Answer
There are as many different ways to write the numbers as there are drops in the ocean. The best approach I could suggest would be to look at games (or recall games you've played) until you find one where you feel the numbers work well... your preference is going to be based on your past gaming experiences, as much as anything else. Even a statistician game developer has to have an idea for how the game rules need to "feel", because games are for people to enjoy, not for number-crunchers to crunch.

Once you've found one or two that you think work well in this sense (could be anything: a pen & paper RPG, a card game, a computer game) then research how they did it by googling and asking questions about that individual game on forums like this one and gaming.stackexchange.com (because the players may in fact have a better idea of how the numbers work, than anyone else). Gradually it will become clear to you why the numbers work, and why you like the feel of the game, and how to implement similar yourself.
> 4 votes

# Answer
It's not that hard to build a somewhat working RPG game mechanic, especially when there are so many inspirations around like pen and paper RPGs with Dungeons and Dragons being the prime example. But to balance your system, that's a different story. There are several facets of balance even for a simple RPG:

1. Are there overpowered or useless character development strategies? Like choosing level up stats|abilities in a way which guarantees more "gain" than all other ways.
2. Are there overpowered or useless character equipment|abilities|whatever else interchangeable on a character? Leveled comparison of course, so it's cracked wooden club versus rusted iron dagger and Gae Bolg versus Excalibur. Note the cost/benefit ratio.
3. Overall, is there one approach in a subsystem which is always better or worse than the others? Like one battle tactics which can ~always perform better than all another tactics.
4. Is the difficulty curve and challenge level appropriate?

I created a completely fluid system for a TRPG once where one could have any crazy combinations of abilities, stats and overall behaviour, so it was impossible to balance it manually very well. But we have an edge against pen-and-papers — ability to run lots of simulations on our fancy machines and not in our minds, so let's tackle those problems one by one. I won't give useless implementation specifics, just a general approach I've used:

1. Perturbate all gains for a level and assign each perturbation to some of your RPG role. Like if character gained +5 STR and Shield Bash ability, it becomes a fighter type. That'll be easier if your RPG have rigid classes. Then take snapshots of resulting character statistics and abilities per level and compare them one to another within those archetypes. That way you can see if one way of developing "fighter" is better than the other. Even on that stage you may notice that, for example, mages gain some unintended edge over fighters.
2. Build a combat simulator. Take one of your snapshots from a previous step and equip it with an item. Clone that shapshot and equip it with another item with the same "level range". Now run them through a combat simulator against enemy of that item's "level range" many times and check results. You may want to take abilities into account, then don't use fighter snapshot with "Spear Thrust" ability to test a mace.
3. Simulate that subsystem, e.g. tactical combat. That's the most difficult step, since you'll have to emulate a real player with some form of AI. It needs to know most typical combos, so tag your abilities like "damage", "stun", "slow", e.t.c., and define combos in terms "stun-\>slow-\>damage over time-\>damage nuke". Things will be easier if you introduce "turns" even if your game is real-time. Take your typical combat situations and run them with your snapshots with equipment and abilities appropriate to "situation level". Note which snapshots of the same type perform better than others, and which combos resulted in a complete devastation of enemy. Take your results with grain of salt, keep in mind that it's your combat AI fighting, not a player. So you may want to use several types of said AI, and playtest your balance changes yourself.
4. The biggest problem is that players can be progamers or complete casuals, and you'll have to decide on your "homogenized target audience". You can test out challenge level by taking average leveled snapshots and average equipment for current game stage, and testing them agains current game map enemies. "Average" here depends on a target audience. Difficulty curve is not that simple, it's mostly subjective feeling, so you'll have to playtest it with your target audience.

After all that, use your game designer's instincts over data and make a balance which feels balanced to you. Also a very important note: don't make a bunch of balance changes at once. Try to do a small change, test it, then introduce another change.

As you can see, there is a big room for a failure here. So you may want to stop striving for a perfect balance, I mean, if game's going to be imbalanced, try to make it fun to abuse, like Morrowind :)
> 2 votes

---
Tags: 2d, character, game-design
---


# Question
Title: Framebufferobject crashes when I do pop without resetting the framebuffer to the original
```
glPushAttrib(GL_ALL_ATTRIB_BITS);
glBindTexture(GL_TEXTURE_2D, 0);

glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fboId);
gl::drawFilled(mesh_);
//glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

glAssert();
glPopAttrib();
glAssert(); // <= crashes here

```

If I uncomment the line `//glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);` it works, how come?

# Answer
> 1 votes
I would suppose the FBO manages some of its own state (there are some pushed/popped states whose values depend on the framebuffer binding) and it gets somehow messed up when you pop these and the framebuffer has suddenly changed. Maybe it's a driver fault where they didn't integrate the FBOs correctly with the rare case of intermediate state pushes/pops (which are quite old and deprecated anyway).

But don't use `glPush/glPopAttrib` anyway, it's quite slow, as you surely don't need to push **every** state. Don't do that just out of laziness.

---
Tags: c++, opengl
---


# Question
Title: Which are the most futureproof languages for graphics (shader) programming?
I have written some GLSL and Cg shaders a couple years back. I am starting another graphics engine project and I want to choose my technologies carefully so that my code will be accessible years down the road.

It seems to me that GLSL and Cg and HLSL are just slightly different syntaxes. Are there any other alternatives to these shader languages? It used to be I only cared about my code compiling correctly on ATI and nVidia hardware (their drivers, to be accurate) but these days I'd like it to function well on Intel's integrated solutions as well. From what I know since all vendors support OpenGL, GLSL should work, and HLSL is its counterpart for DirectX, so there shouldn't be problems there either. What about Cg?

Another question I have is whether these languages are still relevant for using newer techniques. I think they are, but maybe what I don't know is that nobody uses Cg anymore because it's gone out of style, or whatever. When I get around to learning and implementing these techniques myself, I'll surely find out all about the ins and outs, but I'd like to get a feeling for which languages and toolkits are being used NOW by those who are on the cutting edge, so I don't end up building my framework on software that will become obsolete.

# Answer
> 5 votes
Thinking about your target platform is the right approach, and modern Intels actually have a quite good (for Intel) GLSL compiler. If you need to run on downlevel Intels you'll have to re-evaluate (I actually went back to ARB ASM recently for that very reason).

Beware of NVIDIA - their GLSL compiler will even accept some HLSL syntax/keywords, and if you only ever develop or test on NVIDIA you stand a real danger of producing something that will only ever work on NVIDIA.

I like HLSL a lot. One of the key differences is that whereas with GLSL the driver vendor must provide the compiler, with HLSL the compiler is provided by Microsoft as part of your DirectX install. That way you get to be certain that all of your users are on a standard baseline so far as the compiler is concerned, and can rule out one possible source of bugs or variations. The Effects framework makes things much easier for managing shaders in your program, although Microsoft are downplaying this a little in D3D11 (it's provided as source only which you must compile yourself and I'm not certain of the redistribution legalities).

# Answer
> 2 votes
GLSL and CG/HLSL are **completely** different, not just *slightly*. CG and HLSL were developed in parallel, and CG was nvidia's effort to create a standard shader language. The ARB rejected it in favour of GLSL.

CG is used because it supports OpenGL **and** DirectX.

All three shader languages are under active development:

* The current GLSL 4.20 specification came out this August.
* I can't find any dates for the current HLSL, but the current revision supports Shader Model 5, which came out with DirectX 11, which came out in October 2009.
* The current CG toolkit was released in February 2011, the first version from 3.0 in July 2011.

---
Tags: opengl, shaders
---


# Question
Title: database design for a game like "Empires and Alies" in facebook
recently im trying to create a isometric game for facebook pretty much like Empires and Allies in facebook , i have used as3isolib to create the game , the user interactions are almost ready , but im stuck in designing the database for it .

i tried to search online but i could'not find any source or sample db designs for it ,,, i have big problem in design db in the way that can handle the different item types , like , housing , research labs , units , their staus and so on, let's say when we build a house it would have different levels to be completed , or different building has different product , and some item's product is still a product , like military house which produce soldiers ... if any body can guid me or a sample design i'll really appreciate it . Thanks.

# Answer
> 1 votes
Marco even though it's a huge project doesn't mean you have to think about everything at once. Try and take it step by step, think about what the core feature is of this game you are trying ot make is and build out from that. Don't try and think of the entire scope and design EVERYTHING at once.

When using a relational database you want to think about everything in how they relate to each other, try and visualize everything you are trying to make as an object with their own properties and then figure out the relation ship between them all. For instance you have a player object that represents the player, the player has an email address, password, and lets say and avatar image, Well there you go! That's your first table. Now we have all these different kinds of item objects, such as buildings which have names, types (housing, research lab, etc), then their are unit objects and so on... Well you have your buildings table, and units table. Then what you can do is create a new table called "player\_units" which could just contain a player id and the units id, that would be defining a relationship right there.

If you try not to over think everything and take baby steps, building out and thinking about features as you needed them it won't be that difficult to design the database.

---
Tags: databases
---


title: Synchronize turn based browser game

text:
# Question
Title: Synchronize turn based browser game
I'm writing a browser game in php and Sql. I'm also using Javascript - Ajax and Mysql.

I'm stack on the battle system because I want to Synchronize the turns of the players in the battle.

What I doing is to put two players on a battle. So from the first turn a countDown of 60sec will start. What I am thinking is to use a server function to check the countdown, not to the client side. This because I think that in that case a bad synchronization will came, instead if it is the server to count down.

But.. how can I let the server do all this stuff?

# Answer
You need to coordinate the turns on the server, I'd think of some entity that represents fight state, something like

1. GET /fight =\> Returns { player: 1 }
2. Player 1 POSTs to /fight he acknowledges it's his turn, timestamp starts
3. Player 1 POSTs his action(s) to /fight, server computes the actions and updates the fight state, clears the timestamp and now it's player 2's turn
4. Player 2 is GETTing /fight (some pool maybe), then, suddenly the app receives { player: 2 } (hey, it's my turn!)
5. Player 2 POSTs he acknowledges it's his turn, timestamp starts
6. Player 2 does not play, as Player 1 is pooling the server for changes on the fight state, after 60 seconds it will be player 1's turn. Back to step 1.

You could use something like Socket.io/Comet for real time communication, but cleverly sending timestamp information to the clients may suit you and save some requests. Most of these decisions depend on your gameplay.

General advice is - don't worry about the technology if it doesn't work on paper (this example could be easily implemented in any language/db pair), it's easier to abstract when you don't have to care about storage or requests. If it gets too complicated, try to simplify it and then build more complex processes on top of the simpler ones.
> 1 votes

# Answer
I am not a php programmer (.NET developer), but if you're using Ajax it seems to me that the best thing to do is to use javascript to keep track of a client side counter. Then every 5 or 10 seconds or so you could make an ajax call to get the official server time to see how many seconds have actually passed and update your counter accordingly.

On the server side whenever a request comes in you could check to see how long it has been since the other client has made a request. If one of the clients haven't responded in a while then you can assume that client has closed their browser and instead of updating the counter you can notify the client that's still connected of this status change.
> 0 votes

---
Tags: server, client-server, browser-based-games, turn-based
---


# Question
Title: Which Database (RDBMS vs NoSQL vs BOTH) to use for a Realtime Multiplayer Game?
I'm working on a realtime multiplayer game that will require a database (for features such as player profiles, friends, unlocks, news, etc.) This is a standard PC game (not browser-based) and will use a client-server architecture. I am new to using databases, and have done some research over the past few days when I stumbled upon the heated debate: RDBMS vs NoSQL. Currently I am leaning towards NoSQL but after reading about the uses for each (RDBMS and NoSQL), I'm tempted to use both. I know that may seem strange, but let me explain my situation:

My team has a shared webhosting package that offers unlimited mySQL storage and bandwidth, the only caveat being that we can only have 25 connections open at one time (shared hosting rule). I am intending on using this for my website (a typical usage no doubt) in order to post news updates, support community features (like comments, uploading fan art, etc.) and the like. That's all fine and good - but! this is where things get interesting... I want to display this same information that is posted on my website, in-game. This means using mySQL for both my website and my game. In addition to news posts and the like, I plan on using it in-game for things like chat and a server list. I am concerned about that 25-connection-rule mostly.

Which leads me to ask Question #1: Will this work and is there a better alternative?

Now besides this, I have read about how well NoSQL performs and is suited for realtime games (I could be wrong, I've walked through a huge RDBMS vs NoSQL flame war to get here and probably am burned). Basically, I would like to use MongoDB for all of my game object data.

And again, it will be helpful if I provide some context: I have found a host (MongoLab) which offers a 240MB MongoDB package for free, which I intend on using until it's necessary to upgrade. Given 240MB, I've calculated that I will be able to store roughly 60,000 players (if each player is roughly 4KB and we ignore other things that might be stored). The storage space, and having to pay for more in the future (should our game be successful) is not a problem. The only reason I currently intend on using MongoDB for all of my game object data is because of how often this game object data will be accessed (such as whenever a player is killed, picks up an item, fires a gun, etc.) I also like the straight forward schema-free documents (which make it easier to map game object data). I should note that, at one time, there will only ever be one server writing to a player's profile in the database (the server the player is in).

I intend on using the same MongoDB in my website, to display player profile information (I'm not concerned with complete consistency, some delay from in-game updates is fine). Which leads me to my second question, Question #2: Is this a good idea or is there something better I should do?

The game will have a start up experience similar to this:

1. Client logs in (MongoDB)
2. Client is at in-game home page w/ chat rooms (MySQL)
3. Client goes to server list (MySQL)
4. Client connects to a server and plays in it
5. Server communicates updates for all players (MongoDB)

This is just the way I imagined it would work. Does this look good to you, or do you have suggestions on how this plan can be improved?

# Answer
My suggestion is to have your game communicate to a web service that you created that itself deals with querying the database. At that point, it's very simple to try different kinds of databases by "switching" web service implementations (your web service interface always stays the same so your game doesn't break) and decide which one is right for you.

It's also a lot more secure to not expose your database to the internet directly.
> 12 votes

# Answer
> we can only have 25 connections open at one time (shared hosting rule).

That's more than enough for your game. The problem is that if your website uses multiple connections, you could run out. You need to configure your web server to only use a small number of them, leaving the rest for your game server. Your game server doesn't really need more than 1 connection, but might benefit from having a handful.

> Now besides this, I have read about how well NoSQL performs and is suited for realtime games (I could be wrong, I've walked through a huge RDBMS vs NoSQL flame war to get here and probably am burned). Basically, I would like to use MongoDB for all of my game object data.

It's a bit of a false argument, because *neither* system is fast enough to use as the main store for a fast-paced realtime game - you really need to keep and manipulate the values in memory. So you only hit the database when you absolutely have to, which might just be to save the whole character every so often (eg. once a minute), at which point the speed differences become negligible.

The funny thing is, if you tweak MongoDB for top speed, you can just about get it to a point where it would be fast enough for you to perform synchronous writes from within a reasonably fast-paced game, but this would be at the cost of data integrity because the writes are buffered. This means you lose that data in the event of a crash, so there was little point performing the write at all, and it's *still* slower than if you just performed the edit in memory and saved it later, so you get the worst of both worlds.

> The only reason I currently intend on using MongoDB for all of my game object data is because of how often this game object data will be accessed (such as whenever a player is killed, picks up an item, fires a gun, etc.)

Ask yourself why you need to write to the database when a player fires a gun. Why can't that just be handled in-memory on the game server? If your game crashes, and later restarts, and the player finds out they have 3 bullets more than they expected to have, is that a critical business problem?

> I also like the straight forward schema-free documents (which make it easier to map game object data).

This is a much better reason to choose a NOSQL approach than the performance issue.

> I intend on using the same MongoDB in my website, to display player profile information (I'm not concerned with complete consistency, some delay from in-game updates is fine).

That's fine, and sensible. Later on you might want to use a separate instance, so that web reads aren't contesting with game reads and writes, but that problem is a trivial one to solve compared to the problem of getting popular enough for this to be a problem.

Personally I would just pick one of the two databases, based on which one would be less work for me, and standardise on that - but there's no reason you can't keep with two if you like.
> 7 votes

# Answer
All the real time data needs to be kept in application memory, anything else would be silly.

Keeping users login data, stats etc. is a pretty light task, so I'll be bold and say that you can use pretty much whatever you want. Though you might want to be careful with the website, stuff like user lists could suck up a lot of database performance if you don't make a proper caching system.

And like bummzack said, you should keep everything in the same network. On top of that, beware about free stuff, 240 MB free database storage sounds good, but since the machine is probably split between a large number of free users service could be pretty slow.
> 5 votes

# Answer
Do you trust your 60,000 users per database? If not, you should nix the "database access from the client" idea, unless your level of expertise in the security of the database software is top-notch, and you are confident that you can accommodate any issues that result.
> 2 votes

---
Tags: multiplayer, performance, client-server, databases
---


title: How do you make a water shader?

text:
# Question
Title: How do you make a water shader?
I'm working on a minecraft-like world and recently saw this video with a water shader. I searched but couldn't find any good info on how to do something similar. Maybe I'm just googling the wrong thing. Does anyone have any resources on how to do something like this?

minecraft water shader video

# Answer
> 1 votes
A long time ago, when I was programming similar water simulation, I used this as a source. It's written in C++/OpenGL. You can find there PDF with description and also source codes.

You can see, there are faked waves - if you don't want them there, you just don't have to use "noise" textures.

---
Tags: shaders, lighting, water
---


# Question
Title: Android BitmapFactory.decodeStream loading BGR format?
It is very odd.I want to load .png file via asset manager which is provided by android sdk. AssetManager manager; /........./ BitmapFactory.decodeStream(manager.open(path));

It returns BGR format data but opengl es 2.0 uses RGB format so , Blue seems red , red seems blue, how odd.

Is there any solution for it?

I use Nvıdia Tegra 2 (Android 2.2) device for test the application along with c++ via JNI.

# Answer
> 1 votes
You should be able to specify the pixel-format to be `GL_BGR` instead of `GL_RGB`.

For glTexImage2D this would be the *format* parameter.

# Answer
> 0 votes
You can use this extension: EXT\_texture\_format\_BGRA8888. But, you need to check that your device can handle it. Galaxt Spica or Moment doesn't. Otherwise just do a conversion. In my engine, i swap BGRA to RGBA before loading into glTexImage.

---
Tags: opengl, android
---


title: Networking in real-time strategy games

text:
# Question
Title: Networking in real-time strategy games
What is the current state-of-the-art to network real-time strategy games?

I seem to recall that a few years ago, some AAA titles only transmitted the player inputs (Starcraft 1, Age of Empires). Since this requires you to keep everything else totally deterministic, is this still a viable option? Synchronizing random number generators seems feasible, but what about subtle differences in FPU implementations etc..?

Or are strategy games using something closer to action-game networking, where individual entities are transmitted instead (with some form of prediction and (delta) compression)?

If so, how are volatile items like projectiles treated?

What about client/server versus peer-to-peer? I'm guessing that all this is strongly interrelated.

Thank you for your time!

# Answer
> 5 votes
http://www.gamasutra.com/view/feature/3094/1500\_archers\_on\_a\_288\_network\_.php This is still how networking is done in RTS games. P2P is also the normal way of handling connections. Using a lock timestep model however results in the irritating case of desync and cheating handling. There is good way of recovering when a desync happens and all RTS games simply says "Quit the match". Bug tracing desync errors is also a nightmare.

# Answer
> 2 votes
This is a great read, and will answer a lot of your questions:

http://udn.epicgames.com/Three/NetworkingOverview.html

In my strategy/tower defence game, I am using a client/server model and am able to keep everything deterministic so far. The client only sends the server requests to do stuff (but doesn't ever actually **do** anything), and the server sends updates, creations, and deletions down to the clients when things change. Even though my game is currently deterministic, I never trust my clients to do anything right, the server is the boss and has full control over the game. The client is just a dumb terminal.

To make everything really simple, I am using a combination of Reflection and Eventing to keep my entities completely in the dark about the networking side of things. I also use the concept of an Actor and a "Force" (as opposed to an Actor and Pawn in an FPS like Unreal). This allows for really nice encapsulation and a place to store the Force's money and stuff.

# Answer
> 2 votes
Not for RTS but any fast-paced game will need interpolation & prediction

http://developer.valvesoftware.com/wiki/Source\_Multiplayer\_Networking

---
Tags: algorithm, networking, strategy
---


# Question
Title: How do I create particles that react to the player and enemies?
I'm currently making a game with my own game engine which I've written in C++ and I'm using the most recent directx SDK.

The game is a top down space shooter (with a pretty interesting twist) and I'm looking to have a sort of nebula effect that the player will fly through. I really want to try and nail that nice tactile feel of hundreds of particles moving out of the way of the player ship as it flies into them. Somewhat like how particles would move out the way of the player in Geomtry Wars on XBLA.

I'm an experienced programmer when it comes to C++. I don't know, however, how to start implementing this effect. Does anyone have any cool ideas or design choices I might want to look into? Feel free to answer to any degree of depth you fancy.

# Answer
It's a cool idea. You'd need some sort of diffusion gradient around your ship. There are three physical models I can think of that you might want:

1. You want it to seem almost like it's a liquid medium, where the pressure gradient rebalances, i.e. once you've passed some particles, they move back into your wake (like water behind a boat). In this instance, the particle's positions are absolute, and it's only their relation to the player which temporarily modifies their *rendering* position. This is a bit like when you pass a thick magnifying glass over things, and the diffraction seems to make them move — but only until you move the glass away. In this case, your ship is the glass.
2. If you want them to move away from the ship, and continue moving once they've moved. This is like standard physics in generally empty space where there are no (or very small) pressure gradients.
3. You want to move the particles away from the ship swiftly as it approaches, as in (1) and (2), but once the ship is gone, the particles will slowly re-balance themselves to be equidistant in your wake.

**Common to all three solutions**: you need to have a diffusion field that moves with your ship. In this example, we'll make it circular. You then detect vector — call it v1 — between the ship and each particle within that region. Push your particle away along that vector. How strongly you'll push it away will depend on its distance from the ship: use `1 - v1.magnitude`. This formula will give you a linear strength, however you could modify it to use something else like a circular strength curve that diminishes in strength toward the edges. This would give it more of a look as though there's a spherical rather than circular pressure gradient around the ship.

**For solution 1**: All you now do is modify the *render* position of that particle (that is, the sprite position) on every *render* update, by this vector. Because you're doing it this way, this is purely a rendering effect and has no effect on the particle's actual world position. So you add the world position to the render offset (v1) and you now have nicely displaced particles as you move past, toward or beside them, and smoothly reverting particles as you pass by (behind you).

**For solution 2**: Instead of just applying v1 to the view position, apply it on each *logic* update, to the particle's position. So, `p1.position += v1`. So you're applying an accelerative force to the particle, which translates into velocity. You'll probably want each particle's velocity to be dampened, so that they they'll gradually slow down and come to a halt once you've passed. You can see how this solution will result in bunched-up particles in your nebula because they'll never re-diffuse. Not very realistic, I'm sure, since nebulae have pressure gradients within them, no matter how weak in reality.

**For solution 3**: Same as (2), but in this case you're going to have to re-diffuse your particles. To do this easily is a bit of a brute-force approach, but since these are only particles and thus eye-candy, you probably don't need to cover a huge area of interest (probably only a radius of playerPosition + maxPlayerSpeedPerTick, or whatever rectangular area circumscribes that, for logic purposes). Each particle will apply a force on each other particle within the area of interest. They'll apply forces based, once again, on their distances from one another. Calculate all inter-particle forces in a single sweep across the area of interest and then apply all the forces in a single sweep. Lastly, make sure that you only perform this inter-particle force processing on particles that have zero velocity. And once any given particle reaches some minimum speed, cut it's velocity vector to zero, so that it's no longer using up processor time.

There are all kinds of diffusion formulae, etc., out there, but I think in this case, a simple solution works best.
> 65 votes

---
Tags: c++, directx, particles
---


# Question
Title: Dungeon map generator not working in javascript
I am trying to convert this dungeon algorithm from java into javascript, however, my script works 70% of the time. When it works, the rooms are missing a wall on one side, and when it does not work, it is stuck in an infinite loop.

(Sorry the images are small, getting the pixels to scale is another problem :P)

I am guessing the makeRoom() is the problem, and if not, its definitly createDungeon(). So when the algorithm works, after the first makeRoom() call, I get some 1 and 2, in my dungeon\_map array, where 1 is the brown wall, and 2 is the yellow floor. When the algorithm does not work, there arent any 1 or 2 in the dungeon\_map array, leading to an infinite loop.

I am pretty sure the java code works, because here is one with the output online. And here is the original.

The only thing that differs between my code and the others is the getRand() method, which I am pretty sure, just returns a number between the min and max that is passed in.

My entire code:

```
//size of the map
var xsize = 0;
var ysize = 0;

var tileSize = 100;
var objects = 0;

//define the %chance to generate either a room or a corridor on the map
//BTW, rooms are 1st priority so actually it's enough to just define the chance
//of generating a room
var chanceRoom = 75;
var chanceCorridor = 25;

//map
var dungeon_map = [];

//a list over tile types we're using
var tileUnused = 0;
var tileDirtWall = 1;
var tileDirtFloor = 2;
var tileStoneWall = 3;
var tileCorridor = 4;
var tileDoor = 5;
var tileUpStairs = 6;
var tileDownStairs = 7;

//setting a tile's type
function setCell(x, y, celltype)
{
   dungeon_map[x + xsize * y] = celltype;
}

//returns the type of a tile
function getCell(x, y)
{
   return dungeon_map[x + xsize * y];
}

function getRand(min, max)
{
   return Math.floor(Math.random() * (max - min + 1) + min);
}

function makeCorridor(x, y, length, direction)
{
   var len = getRand(2, length);
   var floor = tileCorridor;
   var dir = 0;

   if (direction > 0 && direction < 4)
      dir = direction;

   var xtemp = 0;
   var ytemp = 0;

   if (x < 0 || x > xsize)
         return false;
   if (y < 0 || y > ysize)
         return false;

   if (dir == 0)
   {
      // north
      xtemp = x;

      //make sure its not out of bounds
      for (ytemp = y; ytemp > (y - len); ytemp--)
      {
         if (ytemp < 0 || ytemp > ysize)
            return false;
         if (getCell(xtemp, ytemp) != tileUnused)
            return false;
      }

      //start building
      for (ytemp = y; ytemp > (y - len); ytemp--)
      {
         setCell(xtemp, ytemp, floor);
      }
   }
   else if (dir == 1)
   {
      // east
      ytemp = y;

      for (xtemp = x; xtemp < (x + len); xtemp++)
      {
         if (xtemp < 0 || xtemp > xsize)
            return false;
         if (getCell(xtemp, ytemp) != tileUnused)
            return false;
      }

      for (xtemp = x; xtemp < (x + len); xtemp++)
      {
         setCell(xtemp, ytemp, floor);
      }
   }
   else if (dir == 2)
   {
      // south
      xtemp = x;

      //make sure its not out of bounds
      for (ytemp = y; ytemp < (y + len); ytemp++)
      {
         if (ytemp < 0 || ytemp > ysize)
            return false;
         if (getCell(xtemp, ytemp) != tileUnused)
            return false;
      }

      //start building
      for (ytemp = y; ytemp < (y + len); ytemp++)
      {
         setCell(xtemp, ytemp, floor);
      }
   }
   else if(dir == 3)
   {
      // west
      ytemp = y;

      for (xtemp = x; xtemp > (x - len); xtemp--)
      {
         if (xtemp < 0 || xtemp > xsize)
            return false;
         if (getCell(xtemp, ytemp) != tileUnused)
            return false;
      }

      for (xtemp = x; xtemp > (x - len); xtemp--)
      {
         setCell(xtemp, ytemp, floor);
      }
   }

   return true;
}

function makeRoom(x, y, xlength, ylength, direction)
{
   console.log("DIRECTION: " + direction);
   //define the dimensions of the room, it should be at least 4x4 tiles
   //(2x2 for walking on, the rest is walls)
   var xlen = getRand(4, xlength);
   var ylen = getRand(4, ylength);

   //tile type its going to be filled with
   var floor = tileDirtFloor;
   var wall = tileDirtWall;

   var dir = 0;
   if (direction > 0 && direction < 4)
      dir = direction;

   if (dir == 0)
   {
      //north
      //check if there is enough space left for a room
      for (var ytemp = y; ytemp > (y - ylen); ytemp--)
      {
         if (ytemp < 0 || ytemp > ysize)
            return false;

         for (var xtemp = (x - xlen / 2); xtemp < (x + (xlen + 1) / 2); xtemp++)
         {
            if (xtemp < 0 || xtemp > xsize)
               return false;
            if (getCell(xtemp, ytemp) != tileUnused)
               return false;
         }
      }

      //we're still here, build
      for (var ytemp = y; ytemp > (y - ylen); ytemp--)
      {
         for (var xtemp = (x - xlen / 2); xtemp < (x + (xlen + 1) / 2); xtemp++)
         {
            //start with the walls
            if (xtemp == (x - xlen / 2))
               setCell(xtemp, ytemp, wall);
            else if (xtemp == (x + (xlen - 1) / 2))
               setCell(xtemp, ytemp, wall);
            else if (ytemp == y)
               setCell(xtemp, ytemp, wall);
            else if (ytemp == (y - ylen + 1))
               setCell(xtemp, ytemp, wall);
            else
               setCell(xtemp, ytemp, floor); //and then fill with the floor
         }
      }
   }
   else if (dir == 1)
   {
      //east
      for (var ytemp = (y - ylen / 2); ytemp < (y + (ylen + 1) / 2); ytemp++)
      {
         if (ytemp < 0 || ytemp > ysize)
            return false;

         for (var xtemp = x; xtemp < (x + xlen); xtemp++)
         {
            if (xtemp < 0 || xtemp > xsize)
               return false;
            if (getCell(xtemp, ytemp) != tileUnused)
               return false;
         }
      }

      for (var ytemp = (y - ylen / 2); ytemp < (y + (ylen + 1) / 2); ytemp++)
      {
         for (var xtemp = x; xtemp < (x + xlen); xtemp++)
         {
            if (xtemp == x)
               setCell(xtemp, ytemp, wall);
            else if (xtemp == (x + xlen - 1))
               setCell(xtemp, ytemp, wall);
            else if (ytemp == (y - ylen / 2))
               setCell(xtemp, ytemp, wall);
            else if (ytemp == (y + (ylen - 1) / 2))
               setCell(xtemp, ytemp, wall);
            else
               setCell(xtemp, ytemp, floor);
         }
      }
   }
   else if (dir == 2)
   {
      //south
      for (var ytemp = y; ytemp < (y + ylen); ytemp++)
      {
         if (ytemp < 0 || ytemp > ysize)
            return false;

         for (var xtemp = (x - xlen / 2); xtemp < (x + (xlen + 1) / 2); xtemp++)
         {
            if (xtemp < 0 || xtemp > xsize)
               return false;
            if (getCell(xtemp, ytemp) != tileUnused)
               return false;
         }
      }

      for (var ytemp = y; ytemp < (y + ylen); ytemp++)
      {
         for (var xtemp = (x - xlen / 2); xtemp < (x + (xlen + 1) / 2); xtemp++)
         {
            if (xtemp == (x - xlen / 2))
               setCell(xtemp, ytemp, wall);
            else if (xtemp == (x + (xlen - 1) / 2))
               setCell(xtemp, ytemp, wall);
            else if (ytemp == y)
               setCell(xtemp, ytemp, wall);
            else if (ytemp == (y + ylen - 1))
               setCell(xtemp, ytemp, wall);
            else setCell(xtemp, ytemp, floor);
         }
      }
   }
   else if (dir == 3)
   {
      //west
      for (var ytemp = (y - ylen / 2); ytemp < (y + (ylen + 1) / 2); ytemp++)
      {
         if (ytemp < 0 || ytemp > ysize)
            return false;

         for (var xtemp = x; xtemp > (x - xlen); xtemp--)
         {
            if (xtemp < 0 || xtemp > xsize)
               return false;
            if (getCell(xtemp, ytemp) != tileUnused)
               return false;
         }
      }

      for (var ytemp = (y - ylen / 2); ytemp < (y + (ylen + 1) / 2); ytemp++)
      {
         for (var xtemp = x; xtemp > (x - xlen); xtemp--)
         {
            if (xtemp == x)
               setCell(xtemp, ytemp, wall);
            else if (xtemp == (x - xlen + 1))
               setCell(xtemp, ytemp, wall);
            else if (ytemp == (y - ylen / 2))
               setCell(xtemp, ytemp, wall);
            else if (ytemp == (y + (ylen - 1) / 2))
               setCell(xtemp, ytemp, wall);
            else setCell(xtemp, ytemp, floor);
         }
      }
   }

   return true;
}

//print map to screen
function showDungeon()
{
   for (var y = 0; y < ysize; y++)
   {
      for (var x = 0; x < xsize; x++)
      {
         var cell = getCell(x, y);

         if (cell == tileUnused)
         {
            ctx.fillStyle = "#fff"; //white
         }
         else if (cell == tileDirtWall)
         {
            ctx.fillStyle = "#663300"; //brown
         }
         else if (cell == tileDirtFloor)
         {
            ctx.fillStyle = "#FFFFCC"; //yellow
         }
         else if (cell == tileStoneWall)
         {
            ctx.fillStyle = "#000"; //black
         }
         else if (cell == tileCorridor)
         {
            ctx.fillStyle = "#0033FF"; //dark blue
         }
         else if (cell == tileDoor)
         {
            ctx.fillStyle = "#00CCFF"; //lightblue
         }
         else if (cell == tileUpStairs)
         {
            ctx.fillStyle = "#00FF33"; //green
         }
         else if (cell == tileDownStairs)
         {
            ctx.fillStyle = "#FF0000"; //red
         }

         ctx.fillRect(x, y, tileSize, tileSize);
      }
   }
}

function createDungeon(inx, iny, inobj)
{
   if (inobj < 1)
      objects = 10;
   else
      objects = inobj;

   //adjust the size of the map, if it's smaller or bigger than the limits
   if (inx < 3)
      xsize = 3;
   else
      xsize = inx;

   if (iny < 3)
      ysize = 3;
   else
      ysize = iny;

   console.log("X size of dungeon: \t" + xsize);
   console.log("Y size of dungeon: \t" + ysize);
   console.log("max # of objects: \t" + objects);

   //redefine the map var, so it's adjusted to our new map size
   dungeon_map = new Array(xsize * ysize);

   //start with making the "standard stuff" on the map
   for (var y = 0; y < ysize; y++)
   {
      for (var x = 0; x < xsize; x++)
      {
         //ie, making the borders of unwalkable walls
         if (y == 0)
            setCell(x, y, tileStoneWall);
         else if (y == ysize - 1)
            setCell(x, y, tileStoneWall);
         else if (x == 0)
            setCell(x, y, tileStoneWall);
         else if (x == xsize - 1)
            setCell(x, y, tileStoneWall);
         else
            setCell(x, y, tileUnused);
      }
   }

   /*******************************************************************************
   And now the code of the random-map-generation-algorithm begins!
   *******************************************************************************/

   //start with making a room in the middle, which we can start building upon
   makeRoom(xsize / 2, ysize / 2, 8, 6, getRand(0,3));
   console.log("make room\n" + dungeon_map);
   //keep count of the number of "objects" we've made
   var currentFeatures = 1; //+1 for the first room we just made

   for (var countingTries = 0; countingTries < 1000; countingTries++)
   {
      //check if we've reached our quota
      if (currentFeatures == objects){
         break;
      }

      //start with a random wall
      var newx = 0;
      var xmod = 0;
      var newy = 0;
      var ymod = 0;
      var validTile = -1;

      //1000 chances to find a suitable object (room or corridor)..
      for (var testing = 0; testing < 1000; testing++)
      {
         newx = getRand(1, xsize - 1);
         newy = getRand(1, ysize - 1);
         validTile = -1;

         if (getCell(newx, newy) == tileDirtWall || getCell(newx, newy) == tileCorridor)
         {
            //check if we can reach the place
            if (getCell(newx, newy + 1) == tileDirtFloor || getCell(newx, newy + 1) == tileCorridor)
            {
               validTile = 0;
               xmod = 0;
               ymod = -1;
            }
            else if (getCell(newx - 1, newy) == tileDirtFloor || getCell(newx - 1, newy) == tileCorridor)
            {
               validTile = 1;
               xmod = +1;
               ymod = 0;
            }
            else if (getCell(newx, newy - 1) == tileDirtFloor || getCell(newx, newy - 1) == tileCorridor)
            {
               validTile = 2;
               xmod = 0;
               ymod = +1;
            }
            else if (getCell(newx + 1, newy) == tileDirtFloor || getCell(newx + 1, newy) == tileCorridor)
            {
               validTile = 3;
               xmod = -1;
               ymod = 0;
            }

            //check that we haven't got another door nearby, so we won't get alot of openings besides
            //each other
            if (validTile > -1)
            {
               if (getCell(newx, newy + 1) == tileDoor) //north
                  validTile = -1;
               else if (getCell(newx - 1, newy) == tileDoor)//east
                  validTile = -1;
               else if (getCell(newx, newy - 1) == tileDoor)//south
                  validTile = -1;
               else if (getCell(newx + 1, newy) == tileDoor)//west
                  validTile = -1;
            }

            //if we can, jump out of the loop and continue with the rest
            if (validTile > -1)
               break;
         }
      }

      if (validTile > -1)
      {
         //choose what to build now at our newly found place, and at what direction
         var feature = getRand(0, 100);
         if (feature <= chanceRoom)
         {
            if (makeRoom((newx + xmod), (newy + ymod), 8, 6, validTile))
            {
               //a new room
               currentFeatures++; //add to our quota
               //then we mark the wall opening with a door
               setCell(newx, newy, tileDoor);
               //clean up infront of the door so we can reach it
               setCell((newx + xmod), (newy + ymod), tileDirtFloor);
            }
         }
         else if (feature >= chanceRoom)
         { //new corridor
            if (makeCorridor((newx + xmod), (newy + ymod), 6, validTile))
            {
               //same thing here, add to the quota and a door
               currentFeatures++;
               setCell(newx, newy, tileDoor);
            }
         }
      }
   }

   console.log("\ndone making room\n" + dungeon_map);
   /*******************************************************************************
   All done with the building, let's finish this one off
   *******************************************************************************/

   //sprinkle out the bonusstuff (stairs, chests etc.) over the map
   var newx = 0;
   var newy = 0;
   var ways = 0; //from how many directions we can reach the random spot from
   var state = 0; //the state the loop is in, start with the stairs

   while (state != 10)
   {
      for (var testing = 0; testing < 1000; testing++)
      {
         newx = getRand(1, xsize - 1);
         newy = getRand(1, ysize - 2); //cheap bugfix, pulls down newy to 0<y<24, from 0<y<25

         ways = 4; //the lower the better

         //check if we can reach the spot
         if (getCell(newx, newy + 1) == tileDirtFloor || getCell(newx, newy + 1) == tileCorridor)
         {
            //north
            if (getCell(newx, newy + 1) != tileDoor)
               ways--;
         }
         if (getCell(newx - 1, newy) == tileDirtFloor || getCell(newx - 1, newy) == tileCorridor)
         {
            //east
            if (getCell(newx - 1, newy) != tileDoor)
               ways--;
         }
         if (getCell(newx, newy - 1) == tileDirtFloor || getCell(newx, newy - 1) == tileCorridor)
         {
            //south
            if (getCell(newx, newy - 1) != tileDoor)
               ways--;
         }
         if (getCell(newx + 1, newy) == tileDirtFloor || getCell(newx + 1, newy) == tileCorridor)
         {
            //west
            if (getCell(newx + 1, newy) != tileDoor)
               ways--;
         }

         //console.log("ways: " + ways);

         if (state == 0)
         {
            if (ways == 0)
            {
               console.log("upstairs");
               //we're in state 0, let's place a "upstairs" thing
               setCell(newx, newy, tileUpStairs);
               state = 1;
               break;
            }
         }
         else if (state == 1)
         {
            if (ways == 0)
            {
               console.log("downstairs");
               //state 1, place a "downstairs"
               setCell(newx, newy, tileDownStairs);
               state = 10;
               break;
            }
         }
      }
   }

   //all done with the map generation, tell the user about it and finish
   console.log("# of objects made: \t" + currentFeatures);

   return true;
}

///////////////////////////////////////////////////////////////////////////////////////////////////
// Create the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 70;
canvas.height = 70;
document.body.appendChild(canvas);

//test
var x = 70;
var y = 70;
var dungeon_objects = 40;

//then we create a new dungeon map
if (createDungeon(x, y, dungeon_objects))
{
   //always good to be able to see the results..
   showDungeon();
}

```

and jfiddle.

# Answer
You have a full algorithmic description there.

It seems to me this is a simple matter of intercepting your code flow after each step that the author describes, looking at the inputs and outputs by generating a log of sorts, and then just see where things go wrong, no?

I mean, unless you are a really sharp with Java and JavaScript both (i.e. you know like the back of your hand the difference in how the collections work, how null-values are handled, how the math functions differ etc.), then you are going to likely need to understand the algorithm to some degree, in order to know *where* it's going wrong, and thus in order to port it successfully. This has been my experience in porting game algorithms. Some of them were really tough, but only once I understood each step, could I know if things were going wrong in that step.

Learn to use a step-through debugger like FireBug. Learn to watch values as they change. Either log values for perusal after runtime, or in realtime code, keep readouts on your screen that are constantly updating, Matrix-style.

As Lo'oris said, few people will want to trawl through your broken code to help you... we'd rather give you the tools to learn how to do this not only this time around, but in the future too.
> 6 votes

---
Tags: algorithm, javascript, html5, procedural-generation, roguelikes
---


title: Inheritance vs Composition

text:
# Question
Title: Inheritance vs Composition
I make my money in C# Generally in that language I like to decouple everything to the high heavens using interfaces. This has served me well in enterprise code but in writing games in C# I find myself tending towards inheritance due to being able to define some default behaviors for base classes. I feel dirty doing this though, like I'm disobeying some architecture god who once said "favor composition over inheritance". I know its not black and white but I also feel like i could use interfaces with a bit more work and achieve roughly the same thing.

What do other people do? Is inheritance the right approach for games or should I refactor in some interfaces?

# Answer
> 24 votes
Inheritance in games is actually one of the worst things you can do -- in particular in regards to entities. Read this for why. Composition over inheritance takes you a long way with games. As for other areas of your engine, it doesn't really matter. Say for example you are making a call to some sort of external network service, then you can inherit one generic type Service to eg. HTTPService and SocketService -- very much as in the enterprise apps you're used to.

Unless your game is really simple, you *will* want to use an component-based entity (CBE) architecture. The general idea is that with entities, the reason they are so commonly composed rather than inherited is because *you cannot know until runtime what capabilities a given entity will have*. For example, take the player's ship in a space shooter. You don't know until some point during the gameplay, what weapons, armour, systems (i.e. components) that player is going to pick up, purchase, sell, lose, have destroyed, etc. So the only realistic way to model this is through object composition. The plus side in this scenario is that you can also have fully customisable enemies, built in the same way, rather than enemies that are always exactly the same every time you see that enemy type. So with CBEs, you might see a Martian Freighter and think, "Ah it only has tiny lasers, I'll take it down", and usually that would be true but when you get in range suddenly you realise it has a big-ass wormhole gun. Surprise surprise!

Componentisation is removing implicit coupling of logic, and that is GOOD.

# Answer
> 3 votes
For those who speak german an interesting book: http://www.amazon.com/Architektur-Kerns-einer-Game-Engine-Implementierung/dp/3639324471/ref=sr\_1\_1?ie=UTF8&qid=1314875533&sr=8-1

A closer look about when and why use which architecture may be found here: https://stackoverflow.com/questions/1901251/component-based-game-engine-design

For my self I decide my architecture depending on the size of the project and the possibility to extend or reuse the code. Why invest hours and hours into the architecture of a micro project where there is no chance that you use the code again? In the same time you can have the project finished.

Composition vs Components Components are cool fancy stuff but in most projects/architectures composition will do the stuff also (without component-based overhead). It depends what your component-system can provide that composition can't.

---

> For example, take the player's ship in a space shooter. You don't know until some point during the gameplay, what weapons, armour, systems (i.e. components) that player is going to pick up, purchase, sell, lose, have destroyed, etc. So the only realistic way to model this is through object composition.

all that was possible without components a long time ago too

---
Tags: c#, architecture
---


title: 3D game: is a spatial index necessary?

text:
# Question
Title: 3D game: is a spatial index necessary?
I'm working on a 3D space simulation game in C++.

I've read that in many cases games use spatial indexing (hashing) that allows to quickly detect collisions, find out what entities to draw and so forth.

Is this really necessary for my game, considering that collisions between entities can happen, but are very rare? Is there any viable (and simpler) alternative?

# Answer
No, you don't have to. Remember that spatial subdivision is an *optimisation*. That means it isn't necessary until you've proven that there is no way your game can run fast enough without it. And optimisations are always prioritisable; what could be optimised with an octree, you might be able to optimise at a lower level, or in another way, so that no spatial subdivision is required. Prematurely optimising is a bad thing. If you've never written a game that *required* octrees before, chances are you won't have a sense of at what level they actually become a necessity.

Broadly speaking, you're not going to be capable of the same level of processing (read: number of entities in your world) without it, if only for physics purposes. Literally, because of the recursive nature of quad- and octrees, they improve performance by (an) order(s) of magnitude. So you'll probably have to be happy with a relatively simpler world as a result in the meantime (or *per se*).

Really, spatial subdivision is not such a tough concept to grasp. If you take quadtrees (2D) as a simple example, you can write very basic demo to get familiar with them, using a typical "balls bouncing around screen" type demo as a basis for learning how quadtrees work, and how to apportion collisions using them. You can then directly transfer your knowledge to octrees (3D). That would be my recommended path to a beginner in these.

Anyway, for now, just keep going using a uniform grid, and if things begin to grind, and you've already optimised a good amount in other areas, then look into spatial hashing.
> 5 votes

# Answer
The fact that collisions are rare is mostly irrelevant - it's how often you need to check for them that matters. The optimisation is to reduce the number of object-to-object checks you have to make, not to reduce the cost of each check.

I totally agree with Nick Wiggill and would stress that spatial hashing is an optimisation, nothing more. Don't do it until you need it. However, I also agree with him that it's not such a tough concept to grasp, and you can go a long way simply with a uniform grid. eg. `grid_x = universe_x % GRID_WIDTH`, repeat for all dimensions. This partitions the space into several cubes, and it's easy to keep a list of ships inside each cube of space. Then, when checking collisions, you only need to check a ship against other ships in that cube and the ones in adjacent cubes. (Providing ships can all fit entirely inside a cube - if not, start with bigger cubes.)
> 3 votes

---
Tags: c++, architecture, design-patterns
---


title: Are games designed to be addictive?

text:
# Question
Title: Are games designed to be addictive?
When I was younger I used to play games a lot for hours. I would say I got addicted to them. Now I'm a software developer and was wondering if games are explicitly designed to be addicting?

Game developers are interested in keeping their users playing as long as possible. I've read about Operant Conditioning and Virtual Skinner Boxes. According to psychologists, most games use a fixed reward system to get the player hooked at first. For example, you can level up pretty fast in beginning. Then reward frequency gradually drops, but player keeps playing because they are hooked. In the end, you switch to variable reward frequency, which means rewards occur randomly and rarely. By this stage, the player might not even enjoy the game, but still play in order to get his reward fix and the resulting good feeling from it. This is very similar to how rats are conditioned in Skinner boxes.

Rewards can be in the form of social status recognition in the game world, working hard for a virtual item therefore giving it great value when acquiring it, feeling in control and power that are not met in the real world, escaping to somewhere else, being able measure progress to some goal and getting instant feedback. If the player abstains from the game, a punishment is applied, i.e losing social status or items. After a while, the rewards will be associated with the game itself and therefore even the sight of the game can evoke craving, much like in case of Pavlov's dog

In addition, there is another research which states that the immersive nature of video games, the rich visual stimulus from realistic graphics, the complex thinking required for playing, great autonomy and fast feedback loop can result in increased dopamine levels in the brain, and create a sense of flow. Combined with an effective rewarding system, games can stimulate the feel good centres of the brain. This means that after several sessions, the player needs to play longer in order to achieve the same dopamine levels as before. Some even experience euphoric feeling and relief from withdrawal when they play. They replace real world with game world and focus on in-game motivations only. Players may stop showering for long time, have reduced hygiene, become socially isolated, drop out of school, become overweight, withdraw from their family, have dreams about the game, think and plan about the game while doing other activities, stop doing non game related activities, have trouble concentrating.

References:

http://www.cracked.com/article\_18461\_5-creepy-ways-video-games-are-trying-to-get-you-addicted.html

http://www.betabunny.com/behaviorism/Conditioning.htm

http://www.world-science.net/exclusives/081111\_gaming.htm

Can a game be simply too fun to resist?

# Answer
## Short Answer

Some games are designed purely to be addictive, without regards to any depth to gameplay or aesthetics/narrative. Other times well designed gameplay that naturally encourages "return customers" can be addiction forming to those with more addictive personalities, though such addictions cannot be blamed on the game itself.

---

## Long Answer

In terms of games as a money-making industry, the design of a game vis-a-vis its addictiveness depends entirely on the payment structure of the game.

For instance, Zynga is a well-known producer of facebook games such as Farmville. Addictiveness to the product is very desirable for them, as they work off the freemium payment model, whereby you can play for free, but to speed things up or get the good stuff, you need to make a per-item payment. For them, the more you play the game, the more likely you are to give them money. Addictiveness is so important to this model that there are in fact credible rumors that Zynga has psycho-analysts on payroll to analyse and help increase the addictive qualities of their products.

On the other hand, consider a game like Quake. You pay to purchase the game. From that point on, you pay no more money, but the longer you play, the more you actually diminish their profits, via an increased maintenance cost (releasing fixes and patches) and server costs (for hosting the servers. I can't remember if quake had public-dedicated servers or only official ones, but you get my point). From their perspective, as long as you buy the sequel, if you bought it day one and didn't play it longer than an hour, mission accomplished.

However, throwing a spanner into the works is this idea of "community". If you keep people playing, but more importantly **talking about** your game, you can command a greater control of the mindshare. This is very important for selling merchandise, increasing hype and thus sales of sequels/spinoffs, and generating goodwill. Thus, the moderate costs of maintaining a game and it's community can lead to a massive payout for future endeavours.
> 17 votes

# Answer
Generally speaking, **yes** -- although that "yes" depends on the target market you're referring to. Any product a company develops for the purpose of generating sales is designed to be effective within that market. Do not be confused by the fact that many developers generate ideas and prototypes for games based out of passion and a love for their craft -- even indies must eat, pay the bills, and ultimately make a profit to move onto their next project. For games, effective = addictive.

For any game project, the level of effectiveness/addictiveness is a case of how much time you are able to sink into that aspect. Like any artwork, there comes a time when the artist must lay down his brushes and say, "I could do more, but there is no more that I could reasonably do." That decision is based on what your expected R.o.I. is, what constraints you have on project time due to pressures from investors who are paying for the project to live and breathe, and even how important the current project is as a stepping stone in your career. For this reason important to be exceedingly efficient in your technological choices, as this saves you time that you can spend on improving gameplay/addictiveness.

However for the most part games are designed to be *addictive enough* and no more than that. This makes development time commensurate with the return on that investment. For the general consumer market, over the last 10-15 years particularly, games have been developed with an average play-time incoporated into their design via the marketing plan that goes hand-in-hand with that design. On average, you are paying for 8-12 hours of playtime when purchasing most titles. Gradually this is changing, as games of a more procedural and free-play sort of nature are "renewing" the marketplace. Much of this sort of innovation hails from the indie market, whether self-published or not -- take World of Goo, Eskil Steenberg's Love, Crayon Physics, MineCraft as examples.

There *are* games from the hobbyist market that don't exist for the purpose of being addictive to any particular target market. Some exist as an exercise for a developer to prove what they capable of. There games designed to be enjoyable to the designer/developer, but not necessarily to anyone else -- you can always choose to go down this route, but don't expect to make a fortune, or even a penny. And then there are non-profit games that are developed purely as free educational tools, for instance. But all of these form fringes of along the body of gaming as a whole.

At an individual/subjective level, we are easily trained to grow more and more enamoured of a game, as you mention. Because games provide a very easy "single point of access" to (near) instant gratification which we often don't see in our real lives, they are a powerful way to keep us entertained. I agree with your first and second paragraphs, however its important to realise that a great many things in life are just this way -- we are forever psychologically trained to favour one thing, disfavour another, in varying degrees. It doesn't mean we shouldn't use that power irresponsibly. You can see this as a sliding scale between sociopathically manipulating people purely for your own gain (and possibly to their harm), versus on the opposite end of the scale, teaching someone that if they show you love and support, you'll offer them the same genuine love and support in return. Unconditional love aside, that *is* how strong relationships are formed. And again, it's also how con-men slowly condition you so they can take your money.

Go figure, Pavlov's dog.
> 2 votes

# Answer
Usually the nature of the games makes them addictive.In game goals, achievement systems really makes sure that the player thinks that he/she can achieve it with just a little more effort because otherwise no one will play.But actually its these small range goals that keeps on adding and they ultimately move towards the final big goal.Most of the time the gap between the short term goal increases as game progresses.

If the gameplay mechanics are simple and engaging then it leads to addictive gameplay as the users don't want to spend time learning how to play the game.
> 0 votes

---
Tags: game-design
---


# Question
Title: What tools are needed for making 3D games?
Hi I'm new to 3D games developing, I can a little c++, C#, VB.Net, 3D Max, ArchiCad ..etc. my problem is where to get started, which tools I need to start a own 3D game like GTA, I have tried some tools like : 'Unity3D' (crashes on start), '3D Rad' (uses only built-in items), 'Game Maker A7' (only 2D games can be made there).. could you help me to find the tools of making a 3D game..plz I'm using Windows XP SP 2, I don't have pixel shader 1.1 into my video card

# Answer
> 3 votes
Go back and try Unity3D again. It's a good product, and I'm sure with a bit of work you can figure out why it's crashing.

# Answer
> 1 votes
Currently, Unity 3d and Unreal Development Kit are the "best" options for making a 3d game, and are free to use. Torque 3d is another option, but it's currently $99 for the non-demo version. Other options are much more limited in what you can do, or are horribly expensive and probably not worth it if you're new to 3d development.

Other options are to make a mod of an existing game (saves you even more time, but can be even more limiting of what you can do), or to make your own engine (not a good idea if you're new to 3d, and rarely a great idea if you are experienced in 3d)

# Answer
> 1 votes
The best place you can start, given your description/knowledge base is **write mods**. Use *an already existing game engine*/toolkit such as Aurora (Neverwinter Nights 2 engine) (for NWN type games) or Source engine (Half-Life 2 engine) for FPS type games.

Make sure you **play the games** thoroughly first, it will help you understand how the engine's level creator works.

---
Tags: tools
---


# Question
Title: Starcraft II Galaxy Editor - Eventdefinition
I can create an Action with parameters using an Actiondefintion.

But how can I create an Eventdefinition ? I'd like to make an Event that is 'called' when a Unit, that is saved in a variable, dies. Like an Event called 'My unit dies'.

The desired behavior is the following:

* Called when a unit defined in a variable dies
* the deceased unit should be returned by 'Triggering Unit()'
* the owning player of the deceased unit should be returned by 'Triggering Player()'

I hope you get my point, Thanks

# Answer
> 1 votes
It's not possible to create useful Event Definitions for this purpose. Creating a custom event definition basically requires custom scripting and you should probably avoid it.

What I think you want to do is create a Trigger that uses the Unit Dies event. Right click in the trigger list and select New -\> New Trigger (Ctrl+T). Then right click Events in the trigger pane and select New Event (Ctrl+E). This should bring up a dialog that lets you pick the Unit Dies event.

After adding the Unit Dies event you can hook it up to only trigger when your hero dies by double clicking the Unit: Any Unit item and choosing your hero unit.

Then you can add any actions you want to this trigger that will be run when your hero dies.

---
Tags: modding, starcraft-2, map-editor
---


# Question
Title: DirectX 10 - determining if hardware device is available
I am writing an offline renderer using SlimDX and Direct3D 10 that will need to be run on machines without graphics cards (servers). On these machines, I'll be using the WARP software renderer.

Is it possible to tell if a hardware device is present without throwing an exception in SlimDX? Currently I'm having to do this:

```
            try
            {
                Device device = new Device1(DriverType.Hardware, deviceCreationFlags,
                    FeatureLevel.Level_10_1);

                return device;
            }
            catch (Direct3D10Exception)
            {
                return null;
            }

```

And then create a WARP device if null is returned.

However, each time the exception is thrown, it breaks Visual Studio, which is annoying, and it doesn't seem like I should be catching an exception to determine if a feature is available.

Any way to do this?

# Answer
> 4 votes
In general you can use `SlimDX.Configuration.ThrowOnError` to almost-globally enable or disable exceptions. You can also set up more complex exception exclusions via `SlimDX.Configuration.AddResultWatch`.

You cannot, however, prevent SlimDX from throwing exceptions of a constructor (by design). This is because that's the only way to signal failure of a construction aside from constructing an object in a zombie state (which is ugly). The static method `Device.CreateWithSwapChain` should be usable for constructing your device without throwing (if you disable exceptions). If this doesn't work, please file a bug on the SlimDX issue tracker.

You are correct that it's generally preferable to avoid relying on exceptions for flow control (that is, it's better to be able to ask if something will fail than to have to try it and wait for it to fail, although this is not always possible). SlimDX should support this and if not, it's a bug.

As an aside, you probably have "break on throw" enabled in Visual Studio via the Debug -\> Exceptions menu. You can configure how VS reacts to exceptions from that window -- unchecking everything will prevent the debugger from triggering a breakpoint when an exception is raised.

# Answer
> 0 votes
Why not? Exceptions are how you signal error conditions in objects. If a constructor fails, throwing an exception is the only way to signal that failure.

You ask the `Device` constructor to create a D3D10 device. If no such device exists, what should it do? Create a broken `Device` object that you can't use, which you have to check to see if it is a working? That's basically assuming that your users will properly code the proper fallbacks into their applications. That's a recipe for disaster; it's much better to use an exception to *force* the user to code fallbacks, rather than hope that they'll do the right thing.

As for "breaking Visual Studio", I have never seen VS "break" under throwing an exception. What kind of breakage are you experiencing? VS will only halt if the exception goes uncaught. Maybe you're not catching the right type of exception?

---
Tags: c#, slimdx, directx10
---


# Question
Title: how could RTT be so slow on my intel card?
I simply draw something into a render target, and use it as an normal texture. It's always working greate to me with my nvidia video card. But today I found my program ran terribly slow (less than 5 fps) on a intel card.

After running an analyse I found glGenerateMipmapEXT is the trouble maker, it costs most of the cpu time. Here's how I bind a RT texture:

```
  glBindTexture(GL_TEXTURE_2D, m_textureID);<br>
  glGenerateMipmapEXT(GL_TEXTURE_2D);

```

without glGenerateMipmapEXT the texture is nothing but pure white pic. Something wrong with my RTT?

# Answer
> 2 votes
Please remove the MipMapping flag for your texture... You need glGenerateMipmap because you use MipMapping and OpenGL need a smaller texture. On bad cards(INTEL), GenerateMipmap is a costly operation. This operation must be called one times.

Add this instruction when you load your texture after glBindTexture :

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

```

# Answer
> 3 votes
First reason - Intel's OpenGL drivers are universally acknowledged to be rubbish. Sudden and mysterious crashes, artefacts, performance differences, etc are the order of the day here. This is normal, nothing to see here, move along.

Second reason - RTT is always going to be slower than just rendering direct to the backbuffer. Not RTT in and of itself, but the overhead of rendering to a texture, then rendering that same texture to your backbuffer - that's some extra fillrate overhead you're incurring. Even on a very very good driver/hardware combo with fillrate being the only major bottleneck and everything else being equal, it will always be slower.

Third reason - mipmapping a rendertarget texture is not a great idea. It may not even be supported in hardware, which means that the driver must pull the texture back to system memory, update the miplevels in software, then put it back to GPU memory.

---
Tags: opengl
---


# Question
Title: When/how to use GameService, GameComponent, Initialize()?
So I've finally got around to playing around with XNA and have been toying around with making a 2D game (I have a bunch of art assets from a friend who developed it on iOS)

A lot of things seem to be easy to do and come out of the box however I'm left stumped for a bunch of stuff since most of the literature (the books I bought for instance) don't pay too much attention to 2D.

I'd really appreciate any clarification or being pointed to more information on the following questins:

1. What is the point of a Game Service? I understand the whole idiom of registering an object as a service so that any other GameComponent can grab it, however how does this beat out simply making it perhaps public or static? For instance, my book recommended registering the SpriteBatch object in the Game.cs class. I'm not sure how this is preferrable to simply making it public/static since there should only be one instance of Game anyways (singleton)?
2. I'm confused on when I should inherit from GameComponent or RenderableGameComponent. I'm trying to follow a Manager/Controller design, such that all entities are created/owned by a single manager and the same for other things. I currently have each Manager/Controller inherit from GameComponent, however how does this beat out having the Game object own all the Managers and manually call update on them and draw ?
3. I noticed that Initialize is called **before** ContentLoad(), I found this annoying since in my Initialize is where I'd like to create some of my entities (i.e. Sprite, Player etc..), however I can't give them their loaded SpriteSheets or Textures since the call to load them hasn't occurred yet. Am I perhaps initializing incorrectly or do people just assign the texture further down in ContentLoad?

Those seem to be my biggest "*WTF*" of not really understanding

# Answer
> 12 votes
The answer to your question is simply: Do whatever works. Ideally do what is *simple* and works. Often using the built-in architecture is **not** simple because, as you are finding, you have to jump through hoops to structure your game the way you want.

To answer question one, I will refer you to my answer to the question "Why use services?". The short answer is that services are a good way to avoid coupling (versioning, dependency, extensibility) issues *that you will never encounter in a self-contained game*. Most of the time it's simpler to just make a member `public` (and perhaps even `static`, if you're in a hurry) and worry about more interesting problems.

To answer your second question, I will refer you to my answer to the question "What are the cons of using DrawableGameComponent for every instance of a game object?" as well as my thoughts on game architecture. The short answer is: there is no benefit to using the `GameComponent` over simply creating your own classes and calling methods like `Draw` and `Update` yourself. If `GameComponent` matches your desired architecture exactly, by all means use it - but almost always it doesn't.

Using services and components only really becomes interesting if you're building a library for third-party consumption. XNA itself does this - it has `IGraphicsDeviceService` and `GamerServicesComponent`, for example. These fulfil *specific* decoupling requirements that you typically don't encounter when developing a game.

Finally, the answer to your third question is quite simple: Just create your game entities in `LoadContent`. There is nothing particularly special about `Initialize`.

It's worth pointing out that the entire `Microsoft.Xna.Framework.Game` assembly is **optional**. It provides an extremely useful starting point - but it should by no means be considered as "the one right way" to do things.

# Answer
> 3 votes
For your first question, I must admit that I don't really know the actual answer. I guess it would be for the same reason as to why singleton is generally a bad design pattern. I'll refer you to a quote from this link:

> The first one we thought of (and one of the reasons behind introducing services) was making a GraphicsDevice reference available across a game.Originally we had the Game own the GraphicsDevice and expose it via a property like Game.GraphicsDevice. The problem with this was that this tightly bound the GraphicsDevice to the Game, not allowing someone else to “own” the device (such as a renderer) and preventing someone from using a future updated GraphicsDevice without shipping a new version of Game that wouldn’t be backwards compatible.

For your second question, I'd assume using Components like this would be more useful if you would be following a *component-based* approach instead, as if you would have a list of `Sprite` components that would know how to draw and update themselves instead of a manager that knows how to update and draw every sprite. I agree, it sounds the same but I prefer a component-based design because I really like the object-oriented approach it has.

For your third question, yes you should load any form of content (assets, fonts, etc.) in the LoadContent method. As for the initialization, you would usually create the Player object within the Initialize function and then load its content within LoadContent.. Or you can just do it all within LoadContent if you wish.

---
Tags: 2d, architecture, xna-4.0
---


title: C# Top down movement limitation

text:
# Question
Title: C# Top down movement limitation
I'm using C# and Visual Studios 2010 with XNA 4.0+lua, and my teacher has asked us to make a 2D RPG game similar to zelda(top down). I was aiming to use just one image for each map region, instead of using the tile approach, however i'm stuck on the aspect of movement limitation.

My teacher mentioned being able to mask another image on top of the map's current image, using only back and white colors and using those to be able control where the avatar can move(move where black is and restrict movement where white is). He did not, however, instruct us on how to do this, and I have been unable to find any tutorials anywhere.

I'm fairly new to C# in general, so if anyone can point me in the direction of a tutorial that could help me accomplish this, or add their own advice I would really, greatly appreciate it.

# Answer
You can use the Texture2D's GetData method to access the colour of a pixel on a texture: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.texture2d.getdata.aspx

So... using your method, you would load 2 textures, one that contains the colour image you want, and a matching black and white (2 colours, not grey-scale) texture that will be your "collision map" for each region. You can use the GetData method to determine whether a particular (x,y) location is black or white (walkable or not) on the collision map.

You will want to test one pixel on each edge of your character. Good choices for these test pixels would be the centres of each edge, or the corners. Depends on how you want it to look and feel. Testing these 4 pixels every time you move should tell you if you will be walking into a wall. This same set of tests will need to happen for any projectiles or bad guys you create.

One problem you **may** come across is called "Tunnelling". Tunnelling occurs when an object is moving fast enough to "tunnel" through a wall without noticing the wall. To prevent this, make sure your walls are never really thin, and avoid fast-moving objects. There are ways to properly handle this, but they are more complex and unnecessary for a project of this magnitude. You can research more about tunnelling if you come across this problem, or want to learn more about how to prevent it properly.
> 3 votes

---
Tags: c#, movement, rpg
---


# Question
Title: What is the name of perspective of Age of Empires II?
One would describe Age of Empires 1's "perspective" as a 2D sprite game:

Below is a screenshot of Age of Empires II. How would you describe the "perspective"? Is it also a 2D sprite game?

"Perspective" may not even be the correct word. If it isn't, what should I use?

# Answer
> 38 votes
This is a **dimetric projection** (a special case of the axonometric projection) with the horizontal axes at tan<sup>-1</sup>(0.5) ≈ 26.565° (an isomeric projection would have them at 30°, by the way) from the horizontal line.

It's commonly *called* "isometric projection", but it isn't exactly one.

EDIT:

A simple transformation matrix for this one, assuming the *x* and *y* axes lie on the horizontal plane, the *z* axis points up and the *x* axis points to the right after projection is

```
|  1   -1    0 |
|  0.5  0.5  n |
|  0    0    0 |

```

... with *n* (the vertical scale factor) being usually chosen arbitrary somewhere between 0.75 and 1.0 (the "true" one would be about 1.118).

This projection gets chosen over the true isomeric one *because* of this simple transformation matrix, and the fact you can more easily produce matching tiles for it.

# Answer
> 14 votes
It's isometric projection or perspective. Isometric perspective can work very well with a 2D game, and there is the example of the Flexible Isometric Free Engine which is a 2D engine, with an isometric view (though as it is flexible, that is not forced).

# Answer
> 3 votes
Yes, they are 2D sprites. These sprites, as those in Diablo I, II, Starcraft I, Warcraft II as just a few (Blizzard) examples, were pre-rendered from a 3D content creation package like 3DSMax, Maya or Lightwave. That means you have a camera swivelling around them taking every possible frame of animation from a set number of camera angles. So if you character had 10 animations of 40 frames each, to be rendered from 16 different angles, that would take you to a total of 6400 frames of animation for just that character alone. However it allows you to use 2D instead of 3D in your game, and the characters are lit as they were when rendered, which usually gives them a very particular look. These are then imported into the game (usually as spritesheets) and rendered as 2D sprites.

Generally these sort of sprites are touched up by hand after the rendering process, using a raster package like Photoshop or Cosmigo, particularly when quite small as in Age of Empires I & II.

As for the perspective, strictly (mathematically) speaking I agree with Martin Sojka, whereas in broader terms, most gamers and game developers would refer to this as isometric. I tend to favour strictness of terminology; kudos to you Martin.

---
Tags: 2d, graphics, projection
---


# Question
Title: How to not-unroll loops in Shader Model 3 HLSL
I'm working on raycaster in HLSL, unfortunately it have to be in DX9. But it cannot be compiled

I did similar raycaster in DX11 and i know that there is always problem with FXC compiler that it tries to unroll loops, this problem can be solved in DX11 by \[loop\] command before loop, which tells to compile to not unroll loops. Can i do something similar in DX9? I'm using february 2010 compiler.

My loop is not doing any divergent flow control stuff. And i would like to have it to be able to do early out.

# Answer
> 1 votes
I've never had this problem, but I guess you can just make the loop bounds dynamic, so compiler won't be smart enough to unroll it :) Then pass the loop bounds as shader constant when binding.

---
Tags: directx, shaders, raycasting
---


title: Water simulation in Isometric game

text:
# Question
Title: Water simulation in Isometric game
I'm creating a game in Flash AS3 in which the player needs to modify land in order to direct the water in the right direction.

However, water simulation is a new topic for me and I'm kinda stuck. It doesn't have to be like realistic water, with ripples and stuff, but it has to flow, and if there's enough water, it needs to rise.

I've thought up two different types of water:

* A Spring: Infinite source of water. Used for simulating seas and stuff.
* Water block: Just one unit of water.

My current implementation shows how I'd like the water to spread, but it doesn't rise, and doesn't allow for finite water. Also, the spreading isn't accounting for any amount of water, it just duplicates instead of actually moving units of water.

I'm curious to how you guys would solve this problem. Any examples/pseudo-code is always appreciated.

---

Current version: http://dl.dropbox.com/u/319897/ProjectWater.swf You can manipulate the land by pressing left mouse. And can simulate one step of water at a time by pressing A.

Source of the water part: http://pastebin.com/Js2kYt4y

# Answer
> 7 votes
You need to check out cellular automata, and possibly fluid dynamics. Tarn Adams implemented a cell based fluids system in Dwarf Fortress, and those are the tools he claimed to use in an interview I read some time back (and also in 3 dimensions as per your use case). I think for your purposes, cellular automata (self-replication/propagation of water cells) will be enough. Cellular automata are basically what you see in the classic game of Life by John Conway.

The roguelike development community has a *ton* of information on this sort of stuff, because those games are inherently cell-based. I believe there is a rec.games.roguelike mailing list somewhere on teh webz where you could get some in depth info.

Also suggest you check out the Voxeltron videos on youtube, one of them (there are only about 2 or 3) shows liquid lava in motion. If you were to use small enough subcubes within your main cubic grid, you could get pretty cool non-blocky water going, using sine waves and the like for surface motion. Once again, for propagation you'd be using cellular automata techniques.

For an introduction to CAs, check this out.

# Answer
> 1 votes
A good approach might be a flood fill.

A time dimension can be easily added by tracking the nominal quantity of water in each cell and only allowing the transfer of a certain proportion of water with each timestep of the simulation. This proportion could be divided equally among water-based neighbouring cells in a breath-first fill. This simple approach would mean that water fills out over plains and fills basins and such.

If you want to play with carving canons or rivers as a side-effect of high water transfer rates and such you can build a whole fun psuedo-physics sim on the side that will be pleasing for the players.

Artistically, this would give you the opportunity to put in waterfall blocks if water is transferring in terrain height and such.

You could make it so that there are sinks as well as springs, and perhaps the edge of the board is a natural sink, otherwise a spring would eventually flood the map.

---
Tags: flash, isometric, water
---


# Question
Title: What are the different ways to balance an online multiplayer game where user spend different amounts of time online?
Let's consider a game where every player is building his own medieval town. To make this question simple, let's assume that, on this persistent world, some people will play an hour every day (heavy players), and others will spend an hour per week (light players).

To keep the game fair, a gamer with a lot of free time shouldn't be able to grow much faster than a less present gamer just because he connects more often to the game.

So the first idea is to have a sort of time-based budget: You are saving "action points" as the time is passing. When you connect, you are able to spend this "action points". This way, players are fairly treated...

I see 2 problems:

* On one hand, heavy gamers should have the opportunity to play. As often that they want to...
* On the other hand, light gamers will be able to connect and make a lot of "actions" in a really short range of "real time" (for instance without been "seen" as the heavy players are..)

So my question is:

What are the solutions that allows light and heavy players to play flairly and balanced regardless of free time to play?

# Answer
Make this "action points" system plus a multipliers system: The more the player keeps online, the less actions points he gets. Heavy players will be never happy in any kind of blocking system.
> 1 votes

# Answer
The game economy should run at a set speed, you could make it so simply by everything taking a set amount of time. Just like any other other game, if you order a building constructed, it will take an amount of time, and your builders won't be available for any other job before that time has passed.

In order to keep this kind of system fair to light users it is important that all orders can be queued, even if the player at the time of giving the order lacks the requirements for giving an order, as that may have changed when the order is executed.

If you want a form of PvP combat in the game that is a more difficult task, you don't want someone to get stomped because they are offline when the battle happens. As I see it that leaves two options:

* Defenders can't prepare for the individual battle, they may perhaps set up their defence in some general manner, but by the time they know that they will be attacked, it's too late to do anything about it.
* Defenders have plenty time to respond (at least 24 hours from they know that they will be attacked until it's too late for changing the defence plan), some things, like what resources they have for the defence, will be frozen as in the above method, and it shouldn't be possible to alter the economy to make more soldiers available for the defence than there would otherwise be. But a making a defence plan, setting up units, giving battle-orders etc. might be possible.

Remember, it's always an advantage to spend more time. Spending more time thinking, discussing strategies on the forum etc. will simply make you play better. In some games you may however also get a far more material advantage in the form of being able to execute more orders or do them more timely.
> 1 votes

# Answer
I find the Bonus-Pool mechanic in Starcraft 2 quite interesting in that regard. It's basically a pool of bonus-points that accumulates over time. When you win a match, you get "regular" points plus additional points from the bonus-pool.

Frequent players will deplete the bonus-pool quickly and therefore don't get extra points when they play. Less frequent players benefit from points from the pool.

How could this mechanic be transferred to a game like yours? I guess it would be interesting if you could earn your action-points (or currency) by completing tasks. The amount of points could also be dependent on how well you performed.

A frequent player will be able to play all the time and amass action-points he can use (to build stuff or whatever). Less frequent players also have to perform tasks (obviously) but they will get additional points from the "bonus-pool", so that they don't fall behind too much.

While this might sound quite similar to what you had in mind (action-points are given over time) it is different in that regard that you have to *actually* play the game to earn stuff (it doesn't happen automatically over time). The bonus will only kick in if you earn something during gameplay.

Just make it so that you get a slight benefit if you play regularly, but so that you don't fall too far behind if you only play once a week.
> 1 votes

---
Tags: game-mechanics, mmo, balance
---


# Question
Title: Which language is best for 2D and 3D games to be played on the desktop and on the web?
I am B.Tech. student and have done some CS courses and have some knowledge about programming languages. I know C++ (I've made some small desktop GUI programs with Qt and in Visual Studio), Java (also have done some GUI in Swing) and Python.

Now I want to learn to make 2D and 3D games which can be played on the desktop and also on the web. So which language will be best for this? I have played some web games and they all need Flash player to run, so are they all made in AS or some other Flash language?

# Answer
1. Read what industry veteran Tom Sloper has written about a career in games design and development. It is the ultimate source for getting started.
2. Start by making at least one 2D game, so you know what the game development process entails.
3. 1. If you are more used to Java, ActionScript 3.0 is a good language to learn in; it is forgiving; and deployment is very, very easy and deploys to nearly all platforms through desktop/mobile/web. You do not need to buy Flash Professional or Flash Builder, you can get a free IDE like FlashDevelop instead. The difference between Flash Pro and the others is that Flash Pro is a bit like Photoshop, Illustrator or InDesign in that it you can use it to draw vector graphics you'll use in your game. But this is not actually necessary. And yes, ActionScript is the central language supporting Flash development.
    2. PyGame is another option, if you are more used to Python. I have used Python briefly, but I find it to be a sensible and concise language that does not restrict the user unnecessarily. I don't doubt that writing games in Python is good fun, but I would suggest to you that there is without a doubt more reference material for Flash/ActionScript. Python is generally for desktop apps.
4. During development, when you get stuck, use this (this!) Q&A site for good questions that you can't answer through googling, or one of the forums I list below.
5. (Optional, really) Get yourself some good books on game development, preferably specific to the language you choose. Amazon ratings are your friend.

General links:
> 12 votes

# Answer
From your explanation it sounds more like you want to learn about Game Development, not Game Design. If you are interested in Game Development, take Nick's advice. I've done a whole lot of Flash Game development in the past, and all the resources he listed are top notch.

Also, you should definitely check out the following...

mochimedai.com: they provide lots of great resources and tools for Flash game developers, I used to hang out on their forums back in the day when I was creating my first indie Flash game.

BUT, If you want to learn actual **Game Design**, which is a whole different concept from game development, you should check out this blog

http://gamedesignconcepts.wordpress.com/

It's by a guy named Ian Schreiber, who co-authors a book called "Challenges for Game Designers". He wrote a blog in which he taught a free game design course over the net, the only requirement is that you had to buy his book, which he uses through the course, which is about 20 bucks on Amazon.

I started the course and then realize that Game Design was not for me, I was far more interested in game development. But if you want to dable into Game Design I definitely recommend it. The course was designed for total beginners, so you need no prior experience in game design to take it.

One of the great things about the course is that you don't do any programing, it's all paper prototypes, which really allows you to focus on the design. Of course this doesn't stop you from taking one of the games you designed during the course and turning into an actually playable prototype/game.

Good luck!
> 3 votes

---
Tags: flash
---