# Question
Title: General directions on developing a server side control system for JS/Canvas Action RPG
Well, yesterday I asked on anti-cheat JS, and confirmed what I kind of already knew that it's just not possible.

Now I wanna measure roughly how hard it is to implement a server side checking that is agnostic to client input, that does not mess with the game experience so much.

I don't wanna waste to much resource on this matter, since it's going to be initially a single player game, that I **may** or would like to introduce some kind of ranking, trading system later on. I'd rather deliver better more cool game features instead.

I don't wanna have to guarantee super fast server response to keep the game going lag free. I'd rather go with more loose discrete control of key variables and instances. Like store user's action on a fifo buffer on the client, and push that actions to the server gradually.

I'd love to see a elegant, generic solution that I could plug into my client game logic root (not having to scatter treatments everywhere in my client js) - and have few classes on Node.js server that could handle that - without having to mirror/describe all of my game entities a second time on the server.

# Answer
> 4 votes
To continue from where we left off - the ideal solution is to do all the *important* work on the server. Since you haven't really said what your game is (Action RPGs can be along a wide spectrum) here are thoughts on how to hide the delays for the user without compromising security in a general way.

It is worth it to investigate what working on games in the DOS era was like. A lot of the solutions that were devised to do an RTS on such limited hardware apply here for the delay introduced because of HTTP.

It is worth bearing in mind that not all games can be made this way. It doesn't make much sense for many of the more complex action games to do everything on the server. However there are some general tricks to speed things up:

* Use Comet/Long-polling AJAX for anything the server does independent of the player. Monster movement, timed tile falls in a puzzle game, responses from the AI engine.
* Liberally separate calls from responses where you can. It is tempting to calculate a path with A\* on request, but it will be better if the task is broken into multiple steps. Step one just says "Yes, you can travel in that direction." and then over Comet, after the path is calculated, the unit is updated with proper path directions.
* Build the delays into your game design. If there is a long delay for units to start moving, have them do a little salute or something before they move. The extra time it takes to do that will cover over the delay if you can do nothing else to remove it. (Which you can, see above and below)
* Make use of the extra processing. Like doing the pathfinding on the server, you can make the client side's job easier by doing most things on the server.
* Once critical things are being done on the server, you can in most cases get away with doing double-checks on less-critical things. With unit movement, you can start them off in the direction clicked, so long as the final path only comes over the wire.
* Make sure you perform any economy change that is difficult to reverse on the server. This includes changing resources in an RTS, spending coins on items, gaining score, anything that has a value and a quantity. Changes to unit damage happen on the server and are passed up. Changes to HP in a turn-based-rpg are passed up.
* Make sure you retain all economy values on the back end and only perform actions on that model given the NAME of the action and not the numbers involved. If Tom the Barbarian has just made an attack on Ginger the Kobold, All the numbers for the attack should be taken from the server-side model of the game, not the client side. Then the final HP change is sent up to the game.
* Separate animations from actions. Tom the Barbarian's attack is a big swing that takes .5 seconds to complete. That's .5 seconds you can use to get the results of the attack from the server. If the action was a cheat, then the kobold just doesn't take any damage. Peace is restored to the universe.

There are no silver bullets here. Network gaming is some of the hardest stuff you can endeavor to build as a programmer. And you will mess things up. Keep your source un-obfuscated and offer in-game or out-of-game rewards to people that help you find errors with the game. Rather than cheating, some of the crackers will turn their exploit in for the bounty.

# Answer
> 3 votes
Since it is a single player game, you can do it without any lag at all (assuming you send/receive asynchronous messages).

coming to difficulty, its fairly simple implementation. All you do is cross check the action (like price, item available etc.,) which 99.99% will be valid.

Now you decide what should happen when some thing fishy happens (like something tried to buy without sufficient gold), usually your client should handle this first (by disabling to buy without sufficient gold or prompting a message) and your sever next will handle the hackers/cheaters by double checking it.

Best way is that you don't wait for server response, its unnecessary to wait for confirmation from server that the action is valid. But when when you receive the response that an invalid action has received then you can prompt a message saying "something went wrong in the server, reloading..." and reload the page. Never prompt a message "caught you cheater" or something because it could be a bug in your code. Just log such events in your server and analyze the scenario by simulating the same scenario in your environment.

Hope this helps.

# Answer
> 1 votes
Well, I've been busy lately and wasn't able to implement or even plan nothing really solid. But I've come up with some ideas that will probably disencourage most of the cheaters in the first builds.

For starters I'm going with the combo Node.js + Socket.io.

I don't wanna do monsters AI and/or track it's movements in the server, or do collision detection or anything that may overload the server with requests or processing.

I'll process and keep on the server, of course, some of the keys actions for gameplay, the ones that players I'll be most interested on cheating. Like spawning, shopping, dealing/taking damage, killing/generating monster loot.

As I told on one of my comments, the game will have no Exp/Leveling system, and I'll have character progression more dependent on loot/craft/equipment (there will be other stuff, but that's the core). That's interesting cause, since almost everything players cheat on boils down to killing mobs and getting the drop, and since loot is generated randomly on the server, I can ruin the drop if I detected or suspect that player used some sort of cheating.

In order to decide if a player is cheating or not, the server will be taking as input a series of key info data that may be evidence against the cheater on some consistency checks that will process at each request.

like shown bellow

//checks if the monster HP was compromised on the client if (target.id == lastTarget && eClientHP != target.currHP) //possible cheat detected - this monster wont drop loot

//checks if the player is spamming attacks on random targets that are impossible to hit //warping - cheating on movespeed - or something like that if (euclideanDist(enemy.X, enemy.Y, last.enemy.X, last.enemy.Y) \> (timeDiff \*hero.moveSpeed) + tolerance )
//Detect as cheater - callFBI();

The more info I get as input along with request, more checks I'll be able to do. And depending on how much a I player do suspect actions, I can ban his IP or apply cloaked gameplay penalties on the server side.

---
Tags: javascript, server, client-server, node.js, server-push
---


# Question
Title: Is there any online programmer's community, focusing on core game development?
I am looking for a stricktly/mostly programming oriented game community, focusing on core graphics, middleware, and research. Any suggestions?

Edit: I am specifically looking for people/community/group, having expertise in core game engine design/programming, directx/opengl reservoir.(And specifically targetting the programming part only).(The platforms can be anything from PC to xbox360/ps3/wii and even 3ds.)

# Answer
I love these site for core game programming
> 5 votes

# Answer
It depends on which platform you are interested in making the games as there are numerous communities available focusing on 2D, 3D game development.

The question you are asking is very broad making it difficult for anyone to answer. So, please elaborate i bit more.

However if you prefer to tweek with the graphics part, you can opt for OpenGL.

In case of Android/iOS game development, Go for openGL ES. If you prefer to go in desktop games development, go for openGL or D3D.

In case of android, as far as i know, there are many 2D and 3D engines available.

But if you are a starter, you should start from the book focusing on core openGL concepts. Hope this helps.

PS : i am unable to post this as a comment, So please don't mark DOWN my answer. I am a new member here.
> -1 votes

---
Tags: software-engineering
---


# Question
Title: AI Game Programming : Bayesian Networks, how to make efficient?
We know that AI is one of the most important part of Game Programming. Bayesian networks is one of the core part of AI at Game Programming.

Bayesian networks are graphs that compactly represent the relationship between random variables for a given problem. These graphs aid in performing reasoning or decision making in the face of uncertainty.

I am utilizing the `monte carlo method` and `genetic algorithms`.

* But this take too much time and sometimes crashes due to memory.

Is there any way to implement this efficiently?

# Answer
> 4 votes
Try to implement your network in an existing Bayesian tool like these:

This will help you see if the issue is the complexity of your network or your code.

I suggest you Google for "bayesian network" and "real time". There are many articles that talk about how to speed up processing.

---
Tags: algorithm, ai, game-mechanics
---


# Question
Title: Dynamic libraries are not allowed on iOS but what about this?
I'm currently using LuaJIT and its FFI interface to call C functions from LUA scripts. What FFI does is to look at dynamic libraries' exported symbols and let the developer use it directly form LUA. Kind of like Python ctypes.

Obviously using dynamic libraries is not permitted in iOS for security reasons. So in order to come up with a solution I found the following snippet.

```
/*
(c) 2012 +++ Filip Stoklas, aka FipS, http://www.4FipS.com +++
THIS CODE IS FREE - LICENSED UNDER THE MIT LICENSE
ARTICLE URL: http://forums.4fips.com/viewtopic.php?f=3&t=589
*/

extern "C" {

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

} // extern "C"

#include <cassert>

// Please note that despite the fact that we build this code as a regular
// executable (exe), we still use __declspec(dllexport) to export
// symbols. Without doing that FFI wouldn't be able to locate them!

extern "C" __declspec(dllexport) void __cdecl hello_from_lua(const char *msg)
{
    printf("A message from LUA: %s\n", msg);
}

const char *lua_code =
"local ffi = require('ffi')                   \n"
"ffi.cdef[[                                   \n"
"const char * hello_from_lua(const char *);   \n" // matches the C prototype
"]]                                           \n"
"ffi.C.hello_from_lua('Hello from LUA!')      \n" // do actual C call
;

int main()
{
    lua_State *lua = luaL_newstate();
    assert(lua);
    luaL_openlibs(lua);

    const int status = luaL_dostring(lua, lua_code);
    if(status)
        printf("Couldn't execute LUA code: %s\n", lua_tostring(lua, -1));

    lua_close(lua);
    return 0;
}

// output:
// A message from LUA: Hello from LUA!

```

Basically, instead of using a dynamic library, the symbols are exported directly inside the executable file.

The question is: is this permitted by Apple?

Thanks.

# Answer
> 2 votes
Yes. I have declared functions in iOS code. I do not use these functions. I just forgot to remove them. They were used for debugging the code on other platform.

Such declaration is similar to putting functions in array if you have all your code loaded statically.

```
typedef int32 (*Func1) (void* userData);
Func1 funcs[] = {func1, func2, func3, NULL};

```

I have a set of apps with LUA. I use LUA to describe levels and debug.

You may submit a test app with such functionality to be reviewed by Apple. You can also make app to be not available for sale after review.

# Answer
> 0 votes
Better you create static libraries, and even "static frameworks" (that is, like a classic framework is, a folder with the ".framework" extension and containing your Headers, resource files if any, and the lib itself, except that your lib must be a static library).

Apple doesn't want you doing this for App Store apps, but the operating system certainly allows it. Jailbreak apps use this technique all the time. You basically use a standard UNIX technique to dynamically open a library/framework, and then use stuff in it.

From `iOSTechOverview`

"If you want to integrate code from a framework or dynamic library into your application, you should link that code statically into your application’s executable file when building your project."

---
Tags: ios, lua
---


title: webgame engine how does it works

text:
# Question
Title: webgame engine how does it works
How does the engine of a webgame works? I'm thinking of games like tribalwars, grepolis and forge of empires.

How does that keeping alive work. I mean, a user is building an building, and quit the browser... The building is built even when the session of the user is expired. But the points of the user are updated when the building is finished... So how does that works.

What do you guys think? Do they have some kind of cronjob that is fired every second, and that walks throug the database, and search for finished buildings, and updates the stuff? Or do you guys think that they do it differently?

I hope that I was clear. -NOTE- I don't need any code, I'm just intrested in the progress behind the game...

# Answer
If I developed a game like that, I would store all info in database and pass deltatime (time since last update) for each user profile to update their status to current time. When the user is logged in, the server will often update or else, it will update next time when the user logs in.
> 0 votes

---
Tags: architecture
---


# Question
Title: Draw depth works on WP7 emulator but not device
I am making a game on a WP7 device using C# and XNA. I have a system where I always want the object the user is touching to be brought to the top, so every time it is touched I add `float.Epsilon` to its draw depth (I have it set so that 0 is the back and 1 is the front).

On the Emulator that all works fine, but when I run it on my device the draw depths seem to be completely random.

I am hoping that anybody knows a way to fix this. I have tried doing a Clean & Rebuild and uninstalling from the device but that is no luck. My call to `spritebatch.Begin` is:

```
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);

```

and to draw I use

```
spriteBatch.Draw(Texture, new Rectangle((int)X, (int)Y, (int)Width, (int)Height), null, Color.White, 0, Vector2.Zero, SpriteEffects.None, mDrawDepth);

```

Where `mDrawDepth` is a float value of the draw depth (likely to be a very small number; a small multiple of `float.Epsilon`.

Any help much appreciated, thanks!

# Answer
This note from MSDN seems relevant:

> On ARM systems, the value of the Epsilon constant is too small to be detected, so it equates to zero. You can define an alternative epsilon value that equals 1.175494351E-38 instead.
> 4 votes

---
Tags: xna, c#, windows-phone-7
---


title: Compressing 2D level data

text:
# Question
Title: Compressing 2D level data
So, I'm developing a 2D, tile based game and a map maker thingy - all in Java.

The problem is that recently I've been having some memory issues when about 4 maps are loaded. Each one of these maps are composed of 128x128 tiles and have 4 layers (for details and stuff).

I already spent a good amount of time searching for solutions and the best thing I found was run-length enconding (RLE). It seems easy enough to use with static data, but is there a way to use it with data that is constantly changing, without a big drop in performance?

In my maps, supposing I'm compressing the columns, I would have 128 rows, each with some amount of data (hopefully less than it would be without RLE). Whenever I change a tile, that whole row would have to be checked and I'm affraid that would slow down too much the production (and I'm in a somewhat tight schedule).

Well, worst case scenario I work on each map individually, and save them using RLE, but it would be really nice if I could avoind that.

EDIT: What I'm currently using to store the data for the tiles is a 2D array of HashMaps that use the layer as key and store the id of the tile in that position - like this: private HashMap\< Integer, Integer \>\[\]\[\]

# Answer
Its unlikely that the map itself is taking too much RAM, even on low-end Java phone targets.

Voxel-based editors are editing RLE models - which is analogous to your use-case - every time the user clicks; we were doing that last century and it wasn't a performance problem then; so no worry now.

One small detail; why use a `Map<Integer,Interger>` ?

Why not just have an array of columns e.g. `Tile[][] map` where the first dimension is `(y*width)+x`? This isn't performance-related particularly, in that map-access should be a fraction of the cost of rendering anything, but using a single-dimension array for a x\*y map is fairly standard.
> 2 votes

# Answer
I usually write some kinda of imageCache class which merely holds the tiles graphics. Let's say I have 20 different coloured tiles representing different terrains. My world(s) then are simple 2D dimensional arrays of ints, where each int is just an index back to what colour/type of tile needs to go in that position when I need to draw the map/world.
> 0 votes

# Answer
Depending on your compression target, you have plenty of choices that are always a tradeoff of space vs implementation complexity (and processing time).

I have to make plenty of assumptions here, but the general principles should apply.

The raw data is 128x128x4x4 bytes (1 byte per tile).

```
128x128x4x4 = 256k

```

Accessing this goes something like..

```
tile = map[mappos]

```

The easiest solution is to tile the tiles. The compression ratio depends on the source data, but let's assume that there are a bunch of identical "pilars" - same configuration of tiles in the z direction. Stuff like actual pilars, railings, etc. Save unique Z slices and then genrate maps that refer to these by index.

Assuming there's only 256 unique "pilars", we get down to:

```
128x128x4 + 256x4 = 65k

```

Indexing this data is still pretty trivial. The compression ratio is naturally worse if there are more uniques (as you have to pump up the indexes to 16 bit ints and store more pilars).

```
tile = pilar[map[flat_mappos]][z]

```

You could go a level deeper and start storing unique 2x2 pilar sets (adding yet another indirection); let's say there's 256 of these as well. The result is

64x64x4 + 256x2x2 + 256x4 = 18k

Accessing this gets a bit hairy though (still relatively fast)

```
tile = pilar[quadmap[map[quaded_flat_mappos]][quadpos]][z]

```

Another way to slice would be to take horizontal or spans, but it's less likely that you end up with a small number of uniques. But if you do, the result is much better even with one iteration:

```
128x4x4 + 256x128 = 34k

```

If you need even more compression, you COULD go and use RLE compression, but that will make the data less efficient to access. The compression described above gives you random access.

If you only ever access the data sequentially, RLE is a good match. A trade-off is to only RLE one scanline at a time, but the compression ratio gets worse; you'll have to benchmark and see whether the compression ratio is good enough AND whether you can keep framerate high enough. Again, you can slice your data in various ways, and some are better than others, depending on your exact use case.

Finally, for even further compression, you could use ZLIB or some other general-purpose compressor. You could, for example, only keep the currently active level in memory in an uncompressed form. And here "uncompressed" may still mean any of the methods mentioned above.
> 0 votes

---
Tags: 2d, java, tiles, tilemap, map-editor
---


# Question
Title: Exporting .FBX model into XNA - unorthogonal bones
I create a butterfly model in 3ds max with some basic animation, however trying to export it to .FBX format I get the following exception.. any idea how i can transform the wings to be orthogonal..

One or more objects in the scene has local axes that are not perpendicular to each other (non-orthogonal). The FBX plug-in only supports orthogonal (or perpendicular) axes and will not correctly import or export any transformations that involve non-perpendicular local axes. This can create an inaccurate appearance with the affected objects: -Right.Wing

I have attached a picture for reference . . .

# Answer
> 1 votes
I *think* the error message implies that you performed scaling on some of the bones.

You could try to do an XForm reset on the bones and/or reset the scale of the pivot from the Hierarchy panel. (I don't rig much though, I don't know if either of these will work as intended for bones)

If that doesn't help, I suppose you can try to recreate the bones and make sure not to scale them after creating them.

---
Tags: xna, 3dsmax, fbx
---


# Question
Title: WPF or WinForms for Game Development and learning resources?
I'm looking to create a game framework for my own personal use... I want to use WPF, but I'm unsure if that is a wise choice...

The games I will be writing should not require high performance graphics, so I am hoping to build on native classes... I do not want to rely on external DLL's unless I generate them myself.

The games will be for young children, say 4 to 8. Most will be learning puzzles or simple shooters.

The most advanced will be a platform game (non-scrolling screen like the old Atari Miner 2049er game).

I think I know how to write something like the old Atari Chopper Command (partially written and my 4 year old loves it, but I used WinForms and GDI), Pac-Man, Tetris, Astroids, Space Invaders, Slider Puzzle, but I do not really know how to write the platform game... In my mind, I'm getting caught in collision detection and how to make a character jump and how to make a character walk up a slope or steps...

Can anyone point me to information on developing a platform game in C#?

Would you suggest WinForms or WPF for game development?

I'm not looking for great graphics and speed, just entertaining game play...

# Answer
"I'm getting caught in collision detection and how to make a character jump and how to make a character walk up a slope or steps..."

Why do you want to write it yourself? You could (if you want simple 2d graphics) use an existing framework for platformers and save a lot of time and energy.

How to make characters walk up and down a slope or a stairway entirely depends on how you model this slope and or stairway in the code. :) It also depends on the kinds of physics you would like to involve, is the steep slope, slippery? I think these questions could all find answer, however it would be simpler to ask them one at a time and have some base code to start with.

I will start by answering the question about collision detection. This is implemented in a lot of existing frameworks. If you are using a 2d-array to represent a tilemap, you can handle collision between the character and the wall this way: Assuming the character starts in a collision free area and her feet are positioned in (x,y), you check which tile that is:

```
tilePos.x = character.x / TILE_WIDTH;
tilePos.y = character.y / TILE_HEIGHT;

```

If the character is less wide than one tile and is positioned around the center of the current tile, you simply check if there is a tile directly underneath it.

```
//Tile exists is a function that looks at the 2d-array that represents the tile map
//and checks if a floor tile exists in (int x, int y)
onGround = tileExists(tilePos.x, tilePos.y - 1);
//if the character is not positioned in the center of the tile, you'd have to check
//tileExists(tilePos.x +/- 1, tilePos.y - 1); depending on where it is leaning to.
//This is also true if the character is too wide to stand on a single tile.

```

if there is no tile, the character begins to fall..

```
character.speed.y -= GRAVITY; //a constant you could define

//Checking if a character can move left or right is just the same
movementDirection = 1 * isRightKeyPressed() - 1 * isLeftKeyPressed();
//Assuming the character is two tiles high
canMove = !tileExists(tilePos.x + movementDirection, tilePos.y) && !tileExists(tilePos.x + movementDirection, tilePos.y + 1);

```

now jumping is made simple:

```
if(isUpKeyPressed() && onGround) character.speed.y += jumpSpeed();

```

This is psuedo code and it needs some refining.. It should give you an idea.

If you never made a platformer, I suggest you learn about states too.
> 2 votes

# Answer
I would reiterate that neither WinForms nor WPF would be good, even for simple games. XNA is specifically made for this scenario.

WinForms has an immediate graphics mode so you will have to refresh and repaint the window every "frame." The trouble is that GDI painting isn't great for performance and you have to play games with double buffering to prevent flickering.

WPF uses retained graphics, which is somewhat easier on you. You can create all your shapes and images, give them to WPF and update them when need be. WPF will automatically redraw what needs redrawn and properly sort everything for you. It also has the benefit of hardware acceleration in some cases. You could potentially do some crazy stuff in WPF to achieve some fancy effects (tranformations, shaders, etc.). But while its great that WPF has this power, it is not meant for real-time graphics.

XNA is built using C# and is designed to be easily understood. The starter-project provided with the install gets a game window up and running with a `SpriteBatch` ready to go. You can get 2D sprites drawing in no time. There is some learning curve with the content pipeline, since it is part of the build procedure. Like most graphics frameworks, it is an immediate renderer, so every frame you have to tell XNA what sprites to draw and where to put them. XNA also abstracts out other parts of game development to make your life easier: audio, input (mouse/keyboard/gamepad), content management, etc.
> 3 votes

# Answer
Seems like a bit of a loaded question. I would use neither as they are both for windows applications, not particularly good for writing games. Have you looked into the XNA framework? It uses c# which you seem to want to use, but is actually meant for writing games.
> 2 votes

# Answer
Writing games with a WinForms or WPF UI is perfectly fine. There are thousands upon thousands of popular and enjoyable games that don't need or benefit from hardware support. Just think, if nothing else, of the classic Windows games Minesweeper, Solitaire, or Freecell. I could easily imagine those games being implemented today with Forms or WPF. In fact, being the casual games that they are, that might be even the preferred way to go for me.

That being said, **it's important to pick the right tools for the job.** Since you mentioned Jump & Run mechanics and collision detection, then you *probably* could cook something up in WPF, creating your own game loop and drawing and whatnot, working with UI components instead of your own specialized classes.

However, is that the smart thing to do when there is XNA? Definitely not, as specialized game development frameworks ease your work so much when creating games with somewhat higher technical or design demands.

So as a conclusion, you should really learn how to use a game development framework as your design goals become more complex, and if C# is what you know, XNA would be the most obvious answer as to which you should be using.
> 2 votes

---
Tags: c#, wpf
---


title: Is there any Card Game Framework?

text:
# Question
Title: Is there any Card Game Framework?
Please let's avoid the discussion of creating/using a game framework or not.

I would like to create a small framework for card games or use one if it exists. Does anyone knows one?

Preferably written in Java or C#.

Thanks in advance,

# Answer
> 8 votes
**For C#**

I have used and really helpful the following card game framework

Microsoft has built a nice library/framework for Card Game

**For Java**

Both of them I used and will be helpful for you

# Answer
> 1 votes
I've never used them but you can try those:

http://code.google.com/p/wagic/

http://www.ethanwilder.com/node/23

http://gccg.sourceforge.net/

And for the future - Google really IS your friend :)

# Answer
> -2 votes
not a framework, but here's some java code that may be of use:

```
package sample;
import java.util.*;
enum Rank {
    joker(new Character('*'),"Joker"),aceLow(new Character('a'),"Ace(low)"),deuce(new Character('2'),"Deuce"),trey(new Character('3'),"Trey"),four(new Character('4'),"Four"),five(new Character('5'),"Five"),six(new Character('6'),"Six"),seven(new Character('7'),"Seven"),eight(new Character('8'),"Eight"),nine(new Character('9'),"Nine"),ten(new Character('T'),"Ten"),jack(new Character('J'),"Jack"),queen(new Character('Q'),"Queen"),king(new Character('K'),"King"),aceHigh(new Character('A'),"Ace");
    Rank(final Character c,final String s) {
        this.c=c;
        this.s=s;
    }
    public static Rank fromInt(int n) {
        for(Rank r:Rank.values())
            if(r.ordinal()==n)
                return r;
        return null;
    }
    public static Rank fromCharacter(char c) {
        for(Rank r:Rank.values())
            if(r.c==c)
                return r;
        return null;
    }
    public static Rank[] fromCharacters(final String cards) {
        final Rank[] rank=new Rank[5];
        for(int i=0;i<5;i++)
            rank[i]=Rank.fromCharacter(cards.charAt(i));
        return rank;
    }
    public Character toCharacter() {
        return c;
    }
    public String toString() {
        return s;
    }
    public static String toString(final Rank[] rank) {
        String s="";
        for(Rank r:rank)
            s+=r.toCharacter();
        return s;
    }
    final Character c;
    final String s;
}
enum Suit {
    joker(new Character('*'),"Joker"),clubs(new Character('c'/* try character for a real dimond? */),"Club"),diamonds(new Character('d'),"Diamond"),hearts(new Character('h'),"Heart"),spades(new Character('s'),"Spade");
    Suit(final Character c,final String s) {
        this.c=c;
        this.s=s;
    }
    public static Suit fromCharacter(char c) {
        for(Suit s:Suit.values())
            if(s.c==c)
                return s;
        return null;
    }
    public Character toCharacter() {
        return c;
    }

    public String toString() {
        return s;
    }
    public static String toString(final Suit[] suit) {
        String s_="";
        for(Suit s:suit)
            s_+=s.toCharacter();
        return s_;
    }
    public static boolean areSuited(final Suit[] suit) {
        final int n=suit.length;
        for(int i=0;i<n-1;i++)
            if(suit[i]!=suit[i+1])
                return false;
        return true;
    }
    final Character c;
    final String s;
}
enum Card {
    joker(Rank.joker,Suit.joker),
    aceLowOfClubs(Rank.aceLow,Suit.clubs),
    aceLowOfDiamonds(Rank.aceLow,Suit.diamonds),
    aceLowOfHearts(Rank.aceLow,Suit.hearts),
    aceLowOfSpades(Rank.aceLow,Suit.spades),
    dueceOfClubs(Rank.deuce,Suit.clubs),
    dueceOfDiamonds(Rank.deuce,Suit.diamonds),
    dueceOfHearts(Rank.deuce,Suit.hearts),
    dueceOfSpades(Rank.deuce,Suit.spades),
    treyOfClubs(Rank.trey,Suit.clubs),
    treyOfDiamonds(Rank.trey,Suit.diamonds),
    treyOfHearts(Rank.trey,Suit.hearts),
    treyOfSpades(Rank.trey,Suit.spades),
    fourOfClubs(Rank.four,Suit.clubs),
    fourOfDiamonds(Rank.four,Suit.diamonds),
    fourOfHearts(Rank.four,Suit.hearts),
    fourOfSpades(Rank.four,Suit.spades),
    fiveOfClubs(Rank.five,Suit.clubs),
    fiveOfDiamonds(Rank.five,Suit.diamonds),
    fiveOfHearts(Rank.five,Suit.hearts),
    fiveOfSpades(Rank.five,Suit.spades),
    sixOfClubs(Rank.six,Suit.clubs),
    sixOfDiamonds(Rank.six,Suit.diamonds),
    sixOfHearts(Rank.six,Suit.hearts),
    sixOfSpades(Rank.six,Suit.spades),
    sevenOfClubs(Rank.seven,Suit.clubs),
    sevenOfDiamonds(Rank.seven,Suit.diamonds),
    sevenOfHearts(Rank.seven,Suit.hearts),
    sevenOfSpades(Rank.seven,Suit.spades),
    eightOfClubs(Rank.eight,Suit.clubs),
    eightOfDiamonds(Rank.eight,Suit.diamonds),
    eightOfHearts(Rank.eight,Suit.hearts),
    eightOfSpades(Rank.eight,Suit.spades),
    nineOfClubs(Rank.nine,Suit.clubs),
    nineOfDiamonds(Rank.nine,Suit.diamonds),
    nineOfHearts(Rank.nine,Suit.hearts),
    nineOfSpades(Rank.nine,Suit.spades),
    tenOfClubs(Rank.ten,Suit.clubs),
    tenOfDiamonds(Rank.ten,Suit.diamonds),
    tenOfHearts(Rank.ten,Suit.hearts),
    tenOfSpades(Rank.ten,Suit.spades),
    jackOfClubs(Rank.jack,Suit.clubs),
    jackOfDiamonds(Rank.jack,Suit.diamonds),
    jackOfHearts(Rank.jack,Suit.hearts),
    jackOfSpades(Rank.jack,Suit.spades),
    queenOfClubs(Rank.queen,Suit.clubs),
    queenOfDiamonds(Rank.queen,Suit.diamonds),
    queenOfHearts(Rank.queen,Suit.hearts),
    queenOfSpades(Rank.queen,Suit.spades),
    kingOfClubs(Rank.king,Suit.clubs),
    kingOfDiamonds(Rank.king,Suit.diamonds),
    kingOfHearts(Rank.king,Suit.hearts),
    kingOfSpades(Rank.king,Suit.spades),
    aceOfClubs(Rank.aceHigh,Suit.clubs),
    aceOfDiamonds(Rank.aceHigh,Suit.diamonds),
    aceOfHearts(Rank.aceHigh,Suit.hearts),
    aceOfSpades(Rank.aceHigh,Suit.spades);
    private Card(Rank rank,Suit suit) {
        this.rank=rank;
        this.suit=suit;
    }

    public Rank rank() {
        return rank;
    }
    public Suit suit() {
        return suit;
    }
    public String toString() {
        if(rank.equals(Rank.joker)||suit.equals(Suit.joker))
            return "Joker";
        else return rank+" of "+suit+'s';
    }
    public static String toString(final Card[] card) {
        String s=new String();
        for(int i=0;i<card.length;i++) {
            if(i>0)
                s+=", ";
            s+=card[i].toCharacters();
        }
        return s;
    }
    public String toCharacters() {
        return ""+rank().toCharacter()+suit().toCharacter();
    }
    public static Card instance(Rank rank,Suit suit) { // some hack for speed
        final int n=4*rank.ordinal()+suit.ordinal();
        //System.out.println(rank+" "+suit+" "+n);
        return element[4*rank.ordinal()+suit.ordinal()];
    }
    static Card[] create(int standards,int jokers) {
        int cards=0;
        Card card[]=new Card[standards*52+jokers];
        for(int i=0;i<standards;i++)
            for(Suit suit:EnumSet.range(Suit.clubs,Suit.spades))
                for(Rank rank:EnumSet.range(Rank.deuce,Rank.aceHigh))
                    card[cards++]=instance(rank,suit);
        for(int i=0;i<jokers;i++)
            card[cards++]=instance(Rank.joker,Suit.joker);
        return card;
    }
    private final Rank rank;
    private final Suit suit;
    private static final Card element[]={joker,joker,joker,joker,joker,aceLowOfClubs,aceLowOfDiamonds,aceLowOfHearts,aceLowOfSpades,dueceOfClubs,dueceOfDiamonds,dueceOfHearts,dueceOfSpades,treyOfClubs,treyOfDiamonds,treyOfHearts,treyOfSpades,fourOfClubs,fourOfDiamonds,fourOfHearts,fourOfSpades,fiveOfClubs,fiveOfDiamonds,fiveOfHearts,fiveOfSpades,sixOfClubs,sixOfDiamonds,sixOfHearts,sixOfSpades,sevenOfClubs,sevenOfDiamonds,sevenOfHearts,sevenOfSpades,eightOfClubs,eightOfDiamonds,eightOfHearts,eightOfSpades,nineOfClubs,nineOfDiamonds,nineOfHearts,nineOfSpades,tenOfClubs,tenOfDiamonds,tenOfHearts,tenOfSpades,jackOfClubs,jackOfDiamonds,jackOfHearts,jackOfSpades,queenOfClubs,queenOfDiamonds,queenOfHearts,queenOfSpades,kingOfClubs,kingOfDiamonds,kingOfHearts,kingOfSpades,aceOfClubs,
        aceOfDiamonds,aceOfHearts,aceOfSpades};
}

```

---
Tags: c#, java, card-game
---


# Question
Title: What is this type of sound effect called?
There is a sound typically associated with a bright flash of light, which starts with a lower whirring noise, then breaks into a higher pitched sound. What is that type of sound called? I'm not sure how to begin searching for that, so a typical name for it would be very helpful.

It's something similar to what occurs at 0:41 in this youtube video (here's a link to a few seconds beforehand), where Naruto 6 tails transforms into Kyuubei in *Naruto Generations*.

# Answer
> 5 votes
Don't really think there's a name for either the "blue chakra rising" or the "zoom in on eyes" effect. From what I can tell, the first is a waveform (maybe saw or triangle) that has a high pass filter with the cutoff frequency being swept up.

The second sounds like it uses a multi oscillator with a triangle/saw waveform and a noise wave which again uses a high pass filter with the cutoff frequency being swept up. The noise wave creates the sort of "whoosh" windy sound.

I am by no means an expert, but that's what it sounds like just for starters (along with a bunch of other effects, reverb, compression etc).

To demonstrate this go here: http://www.bfxr.net/

Change the wave to saw or triangle, set the "frequency" to low, the "frequency cutoff" all the way to the left and slowly increase the "frequency slide" towards the right.

---
Tags: terminology, sound-effects
---


title: Pattern for performing game actions

text:
# Question
Title: Pattern for performing game actions
Is there a generally accepted pattern for performing various actions within a game? A way a player can perform actions and also that an AI might perform actions, such as move, attack, self-destruct, etc.

I currently have an abstract BaseAction which uses .NET generics to specify the different objects that get returned by the various actions. This is all implemented in a pattern similar to the Command, where each action is responsible for itself and does all that it needs.

My reasoning for being abstract is so that I may have a single ActionHandler, and AI can just queue up different action implementing the baseAction. And the reason it is generic is so that the different actions can return result information relevant to the action (as different actions can have totally different outcomes in the game), along with some common beforeAction and afterAction implementations.

So... is there a more accepted way of doing this, or does this sound alright?

# Answer
> 18 votes
I don't think there's *one* accepted way of implementing this concept, but I'd really like to share how *I* usually deal with this in my games. It's a bit of a combination of the **Command** design pattern and the **Composite** design pattern.

I have an abstract base class for actions which is nothing more than a wrapper around an `Update` method that gets called each frame, and a `Finished` flag to indicate when the action has finished running.

```
abstract class Action
{
    abstract void Update(float elapsed);
    bool Finished;
}

```

I also use the composite design pattern to create a type of actions that is capable of hosting and executing other actions. This too is an abstract class. Boils down to:

```
abstract class CompositeAction : Action
{
    void Add(Action action) { Actions.Add(action); }
    List<Action> Actions;
}

```

Then I have two implementations of composite actions, one for **parallel execution** and one for **sequential execution**. But the beauty is that since parallel and sequence are actions themselves, they can be *combined* in order to create more complex execution flows.

```
class Parallel : CompositeAction
{
    override void Update(float elapsed)
    {
        Actions.ForEach(a=> a.Update(elapsed));
        Actions.RemoveAll(a => a.Finished);
        Finished = Actions.Count == 0;
    }
}

```

And the one that governs sequential actions.

```
class Sequence : CompositeAction
{
    override void Update(float elapsed)
    {
        if (Actions.Count > 0)
        {
            Actions[0].Update(elapsed);
            if (Actions[0].Finished)
                Actions.RemoveAt(0);
        }
        Finished = Actions.Count == 0;
    }
 }

```

With this in place it's simply a matter of creating concrete action implementations, and using the `Parallel` and `Sequence` actions to control the flow of execution. I'll end with an example:

```
// Create a parallel action to work as an action manager
Parallel actionManager = new Parallel();

// Send character1 to destination
Sequence actionGroup1 = new Sequence();
actionGroup1.Add(new MoveAction(character1, destination));
actionGroup1.Add(new TalkAction(character1, "Arrived at destination!"));
actionManager.Add(actionGroup1);

// Make character2 use a potion on himself
Sequence actionGroup2 = new Sequence();
actionGroup2.Add(new RemoveItemAction(character2, ItemType.Potion));
actionGroup2.Add(new SetHealthAction(character2, character2.MaxHealth));
actionGroup2.Add(new TalkAction(character2, "I feel better now!"));
actionManager.Add(actionGroup2);

// Every frame update the action manager
actionManager.Update(elapsed);

```

I have successfully used this system to drive all of the gameplay in a graphic adventure before, but it should probably work for pretty much anything. It was also simple enough to add other types of composite actions, which were used for creating execution loops and conditionals.

---
Tags: ai, design-patterns
---


# Question
Title: Issue with TurnBased Multiplayer Game in Game-kit
I am working with cocos2d game in which i am implementing Game-kit. My game supports multiplayer option. Actually as given example Raywenderlich link. I am GKTurnBasedMultiplayer class from Game-kit. But now the issue when first player connected to game center and will select option of "Play Now" it automatches for another player. but issue is it directly connects and starts the match, and doesn't wait for another player. I am using

```
[[GCTurnBasedMatchHelper sharedInstance] findMatchWithMinPlayers:2 maxPlayers:4 viewController:viewConroller];

```

for connecting and playing with other players but directly connects the match.

I want to wait for another player. That is the issue. I am also using GCTurnBasedMatchHelper Class.

# Answer
> 1 votes
Make sure your resource bundle id is the same as the iTunes Connect app you submitted...but my guess is you haven't done this?

https://developer.apple.com/support/resources/itunes-connect.html

---
Tags: cocos2d-iphone, game-center
---


# Question
Title: How should I share variables between instances/classes?
I'm making a game using LOVE, so everything is programmed in Lua. I've been experimenting with using classes and object orientation recently. I've found out that a nice system to use is having most of the game's code in different classes, and having a table of instances with all of the instances of any class in it. This way, I can go through every instance of every class and update and draw it by calling the same function.

There is a problem, though. Let's say I have an instance of a player with variables for health and recharge time of a weapon. I also have a master instance which is responsible for drawing the HUD. How can I tell the master instance what the player's health is? Bad solutions:

* Assuming that the player instance will always have the same position in the table - that can be easily changed.
* Using global variables. Global variables are evil.
* Have the master instance outside of the instances table, and have the player set variables inside the master instance, which it then uses for HUD drawing. This is really bad because now I have to make a duplicate of every variable the master instance needs.

What is the proper, standard way of sharing variables between instances? Do I need to change the way I keep track of instances?

Edit: the hump library for LOVE has a signal/slot system. Would that be a reasonable way to share variables between instances?

# Answer
> 3 votes
From the easy to the scalable and complex to implement, kind of:

A fast to write option is simply to let the HUD know where the player is and let it grab what variables it needs directly. It's not very flexible, but for games where the player is well defined and the scope of the game is tightly contained it can work well enough. This is a tightly coupled solution.

Add some structure to the attachment and get...

Another option is to take a look at MVC (model-view-controller) architectures. There are a few varieties but the basic idea is that the model only deals with data (ie. your health) and has one or more views (ie. your HUD) that attach to it and retrieve the data either immediately when it needs it or more commonly the data tells any views when its value changes. The controller you won't have to worry about for your needs. This is a moderately coupled solution, someone somewhere has to directly connect all these models and views.

Then add a go-between so you don't have to connect directly to the object and get...

Another option is a messaging system where there is a global post office. The health sends letters to the post office, who then delivers copies to anyone who's registered to receive things like that. Or vice versa, your HUD can send a letter asking for players to send back their health. This method is very flexible, nice to have in dynamic environments where players come and go constantly. Much less coupled, and gains flexibility.

And add a layer of smarts to the data itself so both sides are talking to the data instead of holding it, to get...

A third option which is more database-like would be to keep one global table of character data (like health) that the character writes to and the HUD queries from, using some kind of ID (identifier) to let the database-like table know what you're asking for. This is kind of like how large, complex games like MMOs work. Barely coupled at all, like the post office your data can come from anywhere but it also includes a layer that neatly packages it for you and streamlines the send-receive-respond cycle.

---
Tags: entity-system, lua, objects, love2d, instancing
---


# Question
Title: Using Event Driven Programming in games, when is it beneficial?
I am doing a refresher on ActionScript 3.

Other than using rudimentary tools like, Event.ENTER\_FRAME and using events to receive input from the user's mouse and keyboard, I find that I rarely use events and prefer to use public functions.

I am starting to reconsider this approach. From what I have learned thus far, the event system works this way:

Each dispatcher can listen to itself during the target phase. Each display object on the stage, can listen to it's children before the target phase, during Capture or after the target phase, during bubbling.

1. I would like to see an example of good use of the Event class for game programming. Have you used Event driven programming in a game and have a good example you could share?
2. A lot of times I want to pass a message to a 'sibling' so I could have their methods listen to the stage or the parent object. Is that the best way to communicate between objects that are not parents of the dispatcher they want to listen to?
3. I would like to know if events are better performance wise than public functions. Are there cases where using events can result in superior performance than avoiding events and sticking to function calls?

# Answer
> 3 votes
The native Flash Events such as `ENTER_FRAME` etc. are quite fast and there's no way around them. If you want to learn more about the event flow, read this article. Personally I try to avoid the event system whenever possible though. Custom events (subclasses of Event) are slow. Using events can also cause memory issues when not used carefully (because a pointer to your object will remain in the event-dispatcher and therefore the memory will never be freed by the GC, even when the object is no longer needed).

Still, events are a great way to decouple components. Using public functions and calling them directly is of course much faster, but it means a tight coupling. In an event driven system, you fire an event and be done with it. You don't have to know anything about who receives the event and what kind of function you have to call.

Instead of events, I prefer a system called "signals and slots". There's a great implementation of that pattern in actionscript, called as3-signals. There's also the (slightly) faster but less versatile turbosignals.

So how does this work. Consider the following example (using as3-signals, unnecessary code bits stripped away):

```
class GameClock
    public var timeChanged:Signal = new Signal(int);

    private function update():void {
        // time has changed, dispatch signal
        timeChanged.dispatch(currentTime);
    }

```

The GameClock class has a public property "timeChanged" which is a Signal. The "int" parameter specifies one parameter of type `int`. In an update method, I can now dispatch the current time.

As you can see, this is a loosely coupled system.. we don't call any public methods of other objects, just dispatch the signal (much like dispatching an event) and be done with it.

Now any other component can be connected to this signal, as long as it has a "slot" that fits, that means a function that matches the signature of the signal.

Example:

```
class GameGui
    public function updateTime(time:int):void {
        // update the GUI with the current time
    }

```

To connect the GameGui to the GameClock, you would do the following (maybe in your game start-up method)

```
var gui:GameGui = new GameGui();
var clock:GameClock = new GameClock();
clock.timeChanged.add(gui.updateTime);

```

You can connect to as many components as you want to listen for this signal. Eg. you could add a component that looks for remaining game-time and plays a warning sound if 10 seconds remain, etc.

So why did I propose Signals/Slots instead of public functions or Events? The Signals/Slots pattern is really powerful, because it is almost like calling public functions directly, but it allows for loose coupling of components. Another benefit is, that you can *see* the type of signals a class dispatches by looking at its interface. You don't have that with events. They aren't declared anywhere and any bit of code could fire an event... therefore events need much better documentation to be understandable.

---
Tags: actionscript-3, performance, events
---


# Question
Title: Getting Model & Movement from Blender to OGRE3D
I just delved myself into game development. I have created a simple character in Blender, together with its walking animation. I am planning to import the model and the movement so that I could use it in OGRE3D. How can I achieve this? Will the import thing have to separate model and movement? Is there any good and comprehensive guide for this?

# Answer
> 2 votes
For those who are looking the for the same question, I achieved that by using a plugin called blender2ogre.

---
Tags: blender, ogre
---


title: Why is my shadowmap all white?

text:
# Question
Title: Why is my shadowmap all white?
I was trying out a shadowmap. But all my shadow is white. I think there is some problem with my homogeneous component. Can anybody help me? The rest of my code is written in xna

Here is the hlsl code I used

```
float4x4 xWorld;
float4x4 xView;
float4x4 xProjection;

struct VertexToPixel
{
float4 Position         : POSITION;
float4 ScreenPos        : TEXCOORD1;
float Depth : TEXCOORD2;
};
struct PixelToFrame
{
float4 Color            : COLOR0;
};

//------- Technique: ShadowMap --------
VertexToPixel MyVertexShader(float4 inPos: POSITION0, float3 inNormal: NORMAL0)
{
VertexToPixel Output = (VertexToPixel)0;

float4x4 preViewProjection = mul(xView, xProjection);
float4x4 preWorldViewProjection = mul(xWorld, preViewProjection);
Output.Position =mul(inPos, mul(xWorld, preViewProjection));
Output.Depth = Output.Position.z / Output.Position.w;
Output.ScreenPos = Output.Position;

return Output;
}

float4 MyPixelShader(VertexToPixel PSIn) : COLOR0
{
PixelToFrame Output = (PixelToFrame)0;

Output.Color = PSIn.ScreenPos.z/PSIn.ScreenPos.w;

return Output.Color;
}

technique ShadowMap
{
pass Pass0
{
    VertexShader = compile vs_2_0 MyVertexShader();
    PixelShader  = compile ps_2_0 MyPixelShader();
}
}

```

# Answer
> 1 votes
I got it working, this is my solution. Why does this work? and the other one doesnt?

```
VertexToPixels MyVertexShaders(float4 inPos: POSITION0, float3 inNormal: NORMAL0)
{
VertexToPixels Output = (VertexToPixels)0;

    Output.Position2D = mul(inPos, mul(xWorld,mul(xView,xProjection)));
Output.Depth  = Output.Position2D.zw;

return Output;
}

float4 MyPixelShaders(VertexToPixels PSIn) : COLOR0
{
PixelToFrames Output = (PixelToFrames)0;

float4 color = float4(PSIn.Depth.x / PSIn.Depth.y, 0.0f, 0.0f, 1.0f);
return color;

}
technique ShadowMap
{
pass Pass0
{
    VertexShader = compile vs_2_0 MyVertexShaders();
    PixelShader  = compile ps_2_0 MyPixelShaders();
}
}

```

---
Tags: xna, hlsl
---


title: Negamax for turn based game

text:
# Question
Title: Negamax for turn based game
I am working on a fast paced turn based game, each turn the player can move left, right or stay put and choose whether or not to fire. Each turn the shots move one block in the direction they are pointing.

I would like to implement NegaMax on this game for curiosity's sake.

Could anyone recommend a brilliant tutorial they tried and found satisfactory?

Thanks

# Answer
> 1 votes
I found Hamed's tutorial the best one from all the links I've read. Also, look at chessprogramming.

---
Tags: ai, turn-based
---


title: Platformer Enemy AI

text:
# Question
Title: Platformer Enemy AI
I'm currently developing a platformer shooter. The game is multiplayer and while my net code could use some real work I have put that off for the time, so currently I'm trying to implement the AI.

The game is pretty simple; Players run around on a map filled with a X amount of zombies that try to eat their brains, classic and overused I know. Weapons spawn at random intervals around the map. The problem is that the zombies, when they find their pray the have to follow it for some while.. And here is the problem, running the AI navcode seems to take for ever.

So here is the ideas I have come up with so far

1. Have the AI update at different intervals with a maximum of Y ms with no updates.
2. Have the zombies assigned to groups of zombies. One is appointed the leader of the group who finds the way to the player - the rest just follows the leader. If the leader dies another one of the zombies in the group is appointed president of the zombie swarm. If there is less than five zombies in a group they try to meet up with other zombies.(Aka they are assigned to a different group and therefor a new leader)
3. Multi-threading option one or two?

For navigation I have some kinda navmesh(since the game is not tile-based) that tells the zombies where they can walk etc. If anyone else got some ideas on how to do navigation I would love some input.

For LoS(zombie -\> player) I have split the map into grids. If the players grid is connected to the zombies grid(if I go with option two I would only need to check if leader zombies grid is connected to player, aka less checks) - if they are connected and there is more than 250ms since last check do a raytrace..

This is my first time programming AI so input on any field is appreciated.

# Answer
> 4 votes
Perhaps you could try an algorithm that does not update all its data in one step, but can do *partial* improvements (in smaller time steps). Even if the calculated path is not always the shortest one -- you have to check this: maybe the difference is so small the player will not really notice (and also zombies *are* supposed to be kind of stupid).

Here is a suggestion of an algorithm; I did not test it.

First, split the map into segments. For each segment remember all neighbor segments, and a distance towards each of them. (For example the distance from center of segment A to center of segment B.)

Each segment will remember its "target" segment, which is one of the neighbor segments where the zombies are supposed to go from here. (The idea is that when the player is in this segment, or perhaps in one of the neighbor segments, zombies will ignore this value and navigate per pixel. But if the player is further away, zombies will navigate using the segment-to-segment map.) You can initialize these values randomly; just choose a random neighbor as a "target".

Now you can calculate a segment-distance between a segment and a player. If the player is in the segment, the distance is zero; otherwise it is a distance from this segment to its target segment, plus distance from target segment to player. (If you detect a loop on the path, the distance is infinite.)

When player moves from segment A to segment B, you *must* set A's "target" to B. This part is necessary to ensure that every segment ever visited by a player will contain a path (not necessarily the shortest path) towards the player. All other improvements are optional.

An optional improvement for a segment X is done by choosing all its neighbors, for each of them calculating the distance to player plus distance between these two segments, and choosing the one with the smallest result as X's "target". This operation can only improve the segment-to-segment map, it never makes it worse. (The quality of the map degrades automatically by the player moving. It changes from "shortest path to player" to "follow the player's path".)

You can repair the whole map in a linear time. First, improve the neighbor segments near the player's segment. Then, recursively improve the neighbors of those neighbors which changed, *starting with the ones with shorter distances to player*. If you have enough time to fix the whole map, that's great. But if you don't... then you need some heuristic.

One idea is that you only fix 10 or 100 nearest segments in one step. If in the next step the player stays in the same segment, you continue fixing next 10 or 100 segments. But if the player moves to another segment, you start again from the beginning. If the player stays in one segment long enough, the whole map will be fixed.

Another idea is that you can fix all the map in one slow wave. Start the wave from the player, fix the nearest 10 or 100 segments, and in another step fix additional 10 or 100 segments (avoiding those which were already fixed in this wave), until the whole map is fixed. The problem is that the later fixes will direct the zombies towards the position where the player was at the *beginning* of the wave.

Or you can combine these two ideas, and in each step fix the nearest 10 or 100 segments, *and* the next 10 or 100 segments of the slow wave.

# Answer
> 1 votes
I hope I understood the question correctly, you are asking how to help the zombies navigate to the player? Basically in your game all the zombies do, is find a path to the current location of the closest player?

I would recommend running a 'Probabilistic roadmap' beforehand (not during game) and saving the resulting graph data to a file for that map. Than navigating the graph using a BFS or a Dijkstra algorithm for each group of zombies to the node on the tree that is closest to the player. You can find the node quickly by dividing the map into sectors (like a spacey grid) and only checking for nodes in the four sectors closest to the player position.

To speed things up I would recommend breaking the Dijkstra process into chunks and running only a little of it each frame. You can then repeat the process once it is finished if the player moves to the proximity of a different node.

If you would like more info, please comment and I will gladly elaborate.

---
Tags: 2d, ai, platformer
---


# Question
Title: Sprite animation in openGL - Some frames are being skipped
Earlier, I was facing problems on implementing sprite animation in openGL ES.

Now its being sorted up. But the problem that i am facing now is that some of my frames are being skipped when a bullet(a circle) strikes on it.

What I need : A sprite animation should stop at the last frame without skipping any frame.

What I did : Collision Detection function and working properly.

PS : Everything is working fine but i want to implement the animation in OPENGL ONLY. Canvas won't work in my case.

------------------------ EDIT-----------------------

My sprite sheet. Consider the animation from Left to right and then from top to bottom

Here is an image for a better understanding.

My spritesheet ...

class FragileSquare{

```
FloatBuffer fVertexBuffer, mTextureBuffer;
ByteBuffer mColorBuff;
ByteBuffer mIndexBuff;
int[] textures = new int[1];
public boolean beingHitFromBall = false;
int numberSprites = 20;
int columnInt = 4;      //number of columns as int
float columnFloat = 4.0f; //number of columns as float
float rowFloat = 5.0f;
int oldIdx;

public FragileSquare() {
    // TODO Auto-generated constructor stub

    float vertices [] = {-1.0f,1.0f,            //byte index 0
                         1.0f, 1.0f,            //byte index 1
                                    //byte index 2
                         -1.0f, -1.0f,
                         1.0f,-1.0f};           //byte index 3

    float textureCoord[] = {
                            0.0f,0.0f,
                            0.25f,0.0f,
                            0.0f,0.20f,
                            0.25f,0.20f

    };

    byte indices[] = {0, 1, 2,
            1, 2, 3 };

    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*2 * 4); // 4 vertices, 2 co-ordinates(x,y) 4 for converting in float
    byteBuffer.order(ByteOrder.nativeOrder());
    fVertexBuffer = byteBuffer.asFloatBuffer();
    fVertexBuffer.put(vertices);
    fVertexBuffer.position(0);

    ByteBuffer byteBuffer2 = ByteBuffer.allocateDirect(textureCoord.length * 4);
    byteBuffer2.order(ByteOrder.nativeOrder());
    mTextureBuffer =  byteBuffer2.asFloatBuffer();
    mTextureBuffer.put(textureCoord);
    mTextureBuffer.position(0);

}

public void draw(GL10 gl){

    gl.glFrontFace(GL11.GL_CW);

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(1,GL10.GL_FLOAT, 0, fVertexBuffer);

    gl.glEnable(GL10.GL_TEXTURE_2D);
       if(MyRender.flag2==1){ /** Collision has taken place*/
    int idx = oldIdx==(numberSprites-1) ? (numberSprites-1) : (int)((System.currentTimeMillis()%(200*numberSprites))/200);
    gl.glMatrixMode(GL10.GL_TEXTURE);
    gl.glTranslatef((idx%columnInt)/columnFloat, (idx/columnInt)/rowFloat, 0);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    oldIdx = idx;
    }

    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); //4
    gl.glTexCoordPointer(2, GL10.GL_FLOAT,0, mTextureBuffer); //5
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); //7

    gl.glFrontFace(GL11.GL_CCW);

    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    gl.glMatrixMode(GL10.GL_TEXTURE);
    gl.glLoadIdentity();
    gl.glMatrixMode(GL10.GL_MODELVIEW);

}

public void loadFragileTexture(GL10 gl, Context context, int resource)
{
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resource);
    gl.glGenTextures(1, textures, 0);
    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);

    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

    bitmap.recycle();
}

```

# Answer
I think that the problem is that you are getting the time from System.currentTimeMillis(). You don't know when your code will be executed so the initial value of idx is unknown. You should save a timestamp when you detect a collision then replace System.currentTimeMillis() with (System.currentTimeMillis()-timestamp)

Pseudocode:

```
long timestamp;
...
if(new collision detected){
    timestamp = System.currentTimeMillis();
}

```

In this way your time will start from the moment you detect the collision and idx will always start from 0

---

EDIT

copy and paste this code, it's not tested but should work.

```
class FragileSquare{

FloatBuffer fVertexBuffer, mTextureBuffer;
ByteBuffer mColorBuff;
ByteBuffer mIndexBuff;
int[] textures = new int[1];
public boolean beingHitFromBall = false;
int numberSprites = 20;
int columnInt = 4;      //number of columns as int
float columnFloat = 4.0f; //number of columns as float
float rowFloat = 5.0f;
int oldIdx;

long timestamp = System.currentTimeMillis();
lont time=0;

public FragileSquare() {
    // TODO Auto-generated constructor stub

    float vertices [] = {-1.0f,1.0f,            //byte index 0
                         1.0f, 1.0f,            //byte index 1
                                    //byte index 2
                         -1.0f, -1.0f,
                         1.0f,-1.0f};           //byte index 3

    float textureCoord[] = {
                            0.0f,0.0f,
                            0.25f,0.0f,
                            0.0f,0.20f,
                            0.25f,0.20f

    };

    byte indices[] = {0, 1, 2,
            1, 2, 3 };

    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4*2 * 4); // 4 vertices, 2 co-ordinates(x,y) 4 for converting in float
    byteBuffer.order(ByteOrder.nativeOrder());
    fVertexBuffer = byteBuffer.asFloatBuffer();
    fVertexBuffer.put(vertices);
    fVertexBuffer.position(0);

    ByteBuffer byteBuffer2 = ByteBuffer.allocateDirect(textureCoord.length * 4);
    byteBuffer2.order(ByteOrder.nativeOrder());
    mTextureBuffer =  byteBuffer2.asFloatBuffer();
    mTextureBuffer.put(textureCoord);
    mTextureBuffer.position(0);

}

public void draw(GL10 gl){
    long delta = System.currentTimeMillis() - timestamp;
    timestamp = System.currentTimeMillis();

    gl.glFrontFace(GL11.GL_CW);

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(1,GL10.GL_FLOAT, 0, fVertexBuffer);

    gl.glEnable(GL10.GL_TEXTURE_2D);
    if(MyRender.flag2==1){ /** Collision has taken place*/
        int idx = oldIdx==(numberSprites-1) ? (numberSprites-1) : (int)(((time+=delta)%(200*numberSprites))/200);
        gl.glMatrixMode(GL10.GL_TEXTURE);
        gl.glTranslatef((idx%columnInt)/columnFloat, (idx/columnInt)/rowFloat, 0);
        gl.glMatrixMode(GL10.GL_MODELVIEW);
        oldIdx = idx;
    }else{
        time = 0;
    }

    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]); //4
    gl.glTexCoordPointer(2, GL10.GL_FLOAT,0, mTextureBuffer); //5
    gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4); //7

    gl.glFrontFace(GL11.GL_CCW);

    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    gl.glMatrixMode(GL10.GL_TEXTURE);
    gl.glLoadIdentity();
    gl.glMatrixMode(GL10.GL_MODELVIEW);

}

public void loadFragileTexture(GL10 gl, Context context, int resource)
{
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resource);
    gl.glGenTextures(1, textures, 0);
    gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);

    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

    bitmap.recycle();
}

```
> 3 votes

---
Tags: android, sprites, opengl-es
---


# Question
Title: What's the recommended way of doing a HUD for an android game?
Basically the question is in the title.

I'm creating a RTS game and I will need buttons like attack move / attack ground, etc. I am not using any engine.

When people do games in OpenGL for android (my case), do they ever use android components to control the game or do they create their components in the game? What are the general recommended approach, if there's any? How about more complex components like scrolling lists of items , etc? I would also appreciate you to pair your answer with a brief comment about how was your experience using the approach(es) you describe.

Thanks :)

# Answer
You can add your controls using `ImageView`, `View` to your `SurfaceView` like if this one was a `RelativeLayout`.

With this method you will easily track `touchEvent`, `OnClick` etc...

Well this is how I do for my game and it works well !

NB: I didn't try with `ListView` etc... but if you customize its UI to have the same look as your game I don't see where the problem can be.
> 2 votes

---
Tags: opengl, android, gui, game-component
---


# Question
Title: Why is it so expensive to develop an MMO?
I want to develop an MMO, like *World of Warcraft*, but some basic research says that it is going to take a lot of time and money. I'd like to know why.

Why is it so expensive to develop an MMO?

# Answer
> 189 votes
The first problem is that the software itself is very complicated, particularly for a new or inexperienced game developer. You have to maintain (at the very least) a client and server application while providing more content than you would expect for a "regular" multiplayer or single-player game.

Even on their own as a single player game, an RPG with the complexity of a World of Warcraft would take professional teams years to develop to the same level of polish: an enormous content investment, lots of work up front and afterward with balancing and playtesting, and some of the most complicated interactions of any game genre. These are commercial-level games, and while yours might be smaller, it will still require a lot of effort just to be a good *game* before you pour in the extra work to make it become a good multiplayer game.

Networked game development is not trivial; there are large obstacles to overcome in not only latency, but cheat prevention, state management and load balancing. If you're not experienced with writing a networked game, this is going to be a difficult learning exercise.

Building it shouldn't be your sole concern for manpower and money, either; also consider the costs of running it *after* it's developed. Even a small massively multiplayer online game will need constant improvements to its hardware/software to keep up with demand and staff to manage the game and provide support for your players.

Think about the following:

* Hosting - Where are you going to host the servers? How will you pay for the bandwidth? How will you load balance players between servers and keep a minority of players from monopolizing the resources of the game? You'll need people to keep an eye on the condition of your hardware and software hosting the game in order to make sure that it will continue to work well.
* Technical support - Not just getting the game to run, but dealing with problems between players and handling player feedback in a way that will keep them loyal. If you're charging money (say, for a subscription), the billing system will be even more complicated (and most likely require legal assistance and possibly international representation and banking/processing fees). People who deal with these things need salaries.
* Security - Not just of their game accounts, but you have to consider cheat prevention and doing frequent repairs and community maintenance effort whenever a new exploit is discovered by players.

# Answer
> 321 votes
World of Warcraft has:

* **5,500,000 – Lines of code**
* **1,500,000 – Art assets**
* 33,681 – Production tasks
* 70,167 – Spells
* 37,537 – NPCs (non-player characters)
* **27 – Hours of music**
* 2600 – Quests in the original World of Warcraft
* 2700+ - Additional quests in WoW: The Burning Crusade
* 2350+ - Additional quests in WoW: Wrath of the Lich King
* 7650+ - Quests total (how many have you finished?)
* 4,449,680,399 – Achievements earned by players since their implementation (this figure is already a few days old, and therefore outdated)

Patches:

* 4.7– Petabytes (4700 terabytes) of data delivered to players through patches
* **126 – Different versions issued of every patch**, including those streamed to players and issued as self-extracting executables
* Half – Of every patch’s size is audio

Servers:

* **13,250 – Server blades** running WoW servers, with a total of
* 75,000 – CPU cores, and
* 112.5 – Terabytes of RAM

Support:

* **179,184 – Bugs tracked by Blizzard** (most of which have been fixed, according to the presenters)
* 2,056 – Game masters
* 340 – Employees in the billing department
* 2,584 – Total customer service employees

International:

* 10 – Languages into which WoW is translated

Blizzard Online:

* 12,000,000+ – Battle.net accounts
* 900,000+ - Files on WorldofWarcraft.com

Source: World of Warcraft by the Numbers by The Game Reviews

# Answer
> 94 votes
The thing to remember is that an MMO is literally the most complicated piece of software one can make. Take every single problem that exists in software engineering, and you have it in an MMO.

**A) Every problem from a normal game.**

1) Resource streaming for an open world.

2) Particle system running on 5 year old commodity hardware

3) Physics system to handle projectiles (Even if it's not havok you still need something for the characters falling from the sky.)

**B) Every problem that a business app would have.**

4) High availability clusters

5) Billing systems

6) Massive databases

7) Customer Support back end

8) Call center support

**C) Every problem that 'internet companies' have**

9) Latency kills

10) World wide datacenters mapping 1:1 and 1:many architecture pieces

**D) Some nice unique problems for MMOs only**

11) Cross server object replication

12) More hackers targeting it than they would some banks.

# Answer
> 72 votes
It's not so much hard to develop an MMO, as to develop another **World of Warcraft**. If you're willing to settle for only having a few thousand players, you *can* make an MMO, such as:

I'm not saying that it was *easy* to make those games :) But it *can* be done by a small number of (skilled, dedicated) people.

# Answer
> 55 votes
I'll disagree with most of the popular posts on here and say that it's really NOT that much work to create an MMO. But don't confuse MMO with WOW.

Really, the idea of an MMO can be broken down into:

O - Online. This is a game played over the net

M - Multiplayer. Not just you.

M - Massive. This implies that you are playing multiplayer with people you don't know, and it implies that the game persists past when you start/stop playing.

Doing something like that wouldn't really take much work as other people here have pointed out. The rolling ball example, Runescape, Travian, etc.

I think people confuse 'Why is it hard to make an MMO' with

'Why is it hard to make a huge 3D interactive world with thousands of animated monsters, weapons, spells, character classes, craploads of sound effects, music, and enough plot to fill 40 fantasy novels.'

And when you phrase it like that it's pretty obvious. It makes you realize that just making a one player offline version of WOW would take almost as much time.

# Answer
> 32 votes
Developing an MMO is super easy. It takes no more than four hours.

Developing an MMO that people want to PLAY is a very different matter.

# Answer
> 31 votes
I asked myself the same question a long time ago. The best way to answer it is this: Design the simplest, dumbest MMO you can imagine. Say, each player is a little ball rolling around, doing absolutely nothing but watch other players. Use, no textures, just solid colors. No lighting, no combat, no interactions. Nothing. Simple, right? Now write it, complete it to the point where you can distribute it online and people can install it, play with it and report errors. See how that goes. This world is about 3 orders of magnitude simpler than WoW, so factor that in and you'll get your answer. Only with experience you will see what a giant time sink building games to completion is. Ask any good developer how long it took them to finish a prototype of their game that looked *almost* as what they imagined the final version would look like. Then ask them how long it took to finish the game.

# Answer
> 13 votes
Unlike most of the other posts in this thread, I'm going to go the other way and say making an MMO is actually not that hard if you make realistic goals for it.

I made an MMORPG myself when I was in high school, which took about 8 months to put together. It got to the point of having just over 1000 users and an average of 80 on at a time before my ISP made me shut it down because apparently that's not allowed on residential ISPs. Oops.

Compared to making a traditional RPG, the online component doesn't actually add many complications, if you are clever about it. The biggest mistake game developers tend to make in MMORPG development is to start with the client. A well-programmed MMO should actually be not that different from a VNC system--essentially all the client should do is send keyboard and mouse states to the server, render graphics and play sounds. You are much better off starting by making a basic MUD server and a simple console-based client, even telnet should work.

What the players sees is mostly irrelevant to the server, and what the player does is mostly irrelevant to the client. If you think in those terms it's actually not that hard, it's mostly just syncing state changes.

# Answer
> 9 votes
One reason that mmos are expensive and lengthy to create is the need to have great amounts of commercial quality content such as visuals and gameplay.

# Answer
> 8 votes
Lots of reasons:

Supporting hundreds or thousands of players introduces a lot of problems. For the programmers, its essentially a giant N^2 problem. For example, imagine something as simple as updating a players position. In addition to dealing with internet latencies, once the position update reaches the server from the player's machine it now needs to be sent to all other player's machines. That's N number of messages being sent, for each player potentially 10 times a second.

Content for an MMO needs to support all these players as well, and provide enough play experience so that players don't "beat the game" after only 40 hours.

Server hardware to run an MMO as well as bandwidth costs are typically very expensive.

TLDR: MMOs are big and complex.

# Answer
> 7 votes
I would like to point you to an article by Shamus Young of Twenty Sided on the issue of server population in MMOs:

http://www.shamusyoung.com/twentysidedtale/?p=6185

This is one reason. Other's are the overpopulation of MMOs(seriously, do you not see enough ads of MMOs already?) and the strain to provide a lag-free, scalar game that can be improved over and over again.

The market is difficult, the management is difficult, the users are difficult lots of times and the profit is often lackluster (P2P or the usual market that uses real money for premium items a la Atlantica Online).

# Answer
> 5 votes
Ugh. Did I miss an As-Seen-On-TV ad?
Any game is a lot of work to make. Not just an MMO. Most console titles take somewhere from 18-30 months and from 30 to 200 people working on it, and that is generally with the basic infrastructure already in place (render engine, content framework, core libraries) and people with background in game development joining together years of experience.
With an MMO you throw some extra ingredients in the mix, like scalability, networking, lots of playtesting, and (generally) even more content.
Yeah, I'm fairly sure that if you'd try to do that by yourself you'd indeed need a couple of months....

# Answer
> 5 votes
The problems with an MMO can be broken down into 4 major groups. All of which can be solved. Or at least reduced somewhat. However, you'll have to sacrifice your personal vision of the game to do it, in most cases.

**Content**

There are many ways to solve the Content problem. The obvious one is collecting a ton of talented people and paying them to make the content. However, this isn't the only way. It can be done on the cheap/slow through various channels. The most elegant is the user-generated model. Some examples of user-generated content in MMOs are the recent lego universe MMO (however in very limited scope) and, of course, second life.

But you can take this much further. Kingdom of loathing is a fine example of a system that would lend itself well to user-generated content. (they chose not to do that) Enemies consist of a static hand-drawn image, and various stats and attacks that come from a pool of possible attacks. Each of these elements could be user generated. Finding unique ways to get the users to make your weapons, armor, spells, enemies, cities, countryside, attacks, and even quests and NPCs is a perfectly viable way to source your content. You simply need to bear in mind that this content will never be particularly on-point with a story. It will be what the users want it to be.

For 3D? Look towards games like Spore.

**Billing**

Yes, billing can be a terribly expensive proposition. However, there are ways to make this easier. Such as paypal. Yes, you'll be asking your users to all have paypal to play, but it certainly doesn't have to stay as paypal only if the game takes off.

**Programming**

The trick with any MMO is to build systems that accept any data. Don't program spells. Program a universal spell system that accepts data from a database or file to create spells. Don't program quests, program the tools you use to make quests.

Start very simple. Get the core mechanics in place. Consider using an already existing platform. But go about it smartly.

Maybe open source?

**Hosting**

No matter what, this will cost you. But it doesn't have to start costing you right away. If you are willing to languish in obscurity for a few years, you can slowly build a passionate following and use the money you do make to upgrade. Keep the game simple. Don't ask too much from your hardware. And push off as much as you can to the users.

Pioneer something in bit-torrent and validate through multiple peers responding. You might be able to eliminate the server entirely. Or at least relegate it only doing very important things. However, I don't know of anyone out there doing this.

# Answer
> 4 votes
Even "simple" indie games take months for a small team to make. This goes into design, programming, art, audio, business, marketing, etc. With MMOs, the complexity is greater -- you need a rock-solid (ideally, exploit-proof) game client and server, plus a billing system, a back-end database that can handle a large number of players, etc. These take time to make, test, debug, and sometimes remake from scratch.

The fact that games cost money to make comes mainly from the fact that people need to eat (and developers are people). Even with a team of three, you need a few thousand dollars a month for housing, food, and other necessities.

# Answer
> 4 votes
The cost is related most intensely to the labor required for developing assets. The cost of most tools pale in comparison to what it costs to pay people to use them and produce assets.

Consider that the cost of one fulltime developer can be anywhere between 20k - 100k+. This already equates to very high budgets for normal games, but MMOs require significantly more assets to create. This longer development time means more cost paying the workers, and significantly higher overhead.

That wouldn't really be all that bad though, but until recently, the 'wheel' so to speak wasn't readily available. So each group that has had to create a MMO has had to essentially create their own. Flying blind means alot of work that may be unnecessary gets created, and things that later on are discovered to be very necessary are overlooked.

The process of wasting time on things that you don't need, and having to painfully go back and create things where you should have before (introducing further complexity in the form of bugs and whatever else) becomes **very** expensive.

That's how it is for most big teams. But Indie/hobbiest teams also run into a few more issues. Usually the big one is not looking at it realistically. People have the tendency of looking at finished, (sometimes) polished work and dramatically underestimating the work that went into creating it. Indie teams usually fail because they do just that, they believe that reaching X level of status would be easy, even with all of their other potential commitments (as most Indies aren't fulltime).

Eventually not being able to completely objectively look at the project discourages them, and they fall apart.

# Answer
> 4 votes
In addition to the technical and logistics reasons mentioned above there is another huge one:

MMOs are designed to satisfy a large and diverse set of people. To get an MMO going you need to satisfy at least several of the types of players from the Bartle Test. So you're game is going to need to include some social features, some exploration features such as art, and probably some competition features.

Much like the audience for an MMO, the creative team needed to build an MMO has to be very diverse. They have to include some really strong engineers to solve the technical issues above. You need some great artists to make a living, breathing world. You need some designers who can both crank out tons of content and make it engaging over long periods of time. You need a full QA and CSR architecture to deal with player feedback and the tons of bugs that will result. Very likely, all of these creators will be interested in the design direction of the project and will either like or dislike whatever direction is chosen. Put all that together and you need a creative team with the ability to drive that diverse collection of people towards a common goal.

There's simply no way to make an MMO of any scale with an "indie" style team. As your team scales up various creative and personal issues tend to spiral out and the rigors of running a business can really get in the way of building a game. Even if you have all the components above it's very difficult to bring it all together to make a successful, launched MMO.

# Answer
> 3 votes
If you're going to independently develop an MMO, you will likely be using pre-existing libraries and API's and engines instead of creating your own from scratch, which is what takes a good deal of time for developers like Blizzard.

However, it's unlikely that you are going to find your own custom-built MMO Engine online all ready for you to take and use yourself.

It requires massive amounts of architecture and design. Have you ever tried programming a simple game? If you have, I doubt that you would be asking this question.

Once you have that down, there is the question of art design. Artists cost money. And if you are going to do the art yourself, it'll take time. Lots of time. Imagine drawing everything in WoW from scratch -- every single item, character, every detail of the world. Art itself is what will take a large portion of the time.

Of course, you don't need art. You can just release a wireframe game. But good luck getting people to play your game then.

With Blizzard, especially, there is the fine-tuning of gameplay. Blizzard has to test and run through and explore every single possibility of their gameplay for months and months just to make sure that it's fair. That nobody can find some exploit and ruin the game for everybody else; that things are balanced and fun to play. And even with all that playtesting, things can still slip through. You can't *possibly* know how the player's full gaming experience will be, once they are interacting with thousands of other players, with just a few weeks of testing.

In addition, it takes a lot of money to run a server that is powerful enough to host your MMO.

# Answer
> 3 votes
If you want to make a MMORPG like WoW, of course it will be long and hard, but the main reasons for that are the content making, the server/network knowledge required to set up a smooth game, and also a team and a good set of tools to maintain the whole game running with as few problem as possible.

Programming a game like WoW is of course a complex work, but the most problematic challenge of such a game is to think about a good architecture for it, in terms of "which data is where, where events happens on which machine would it be a client or a server and what data can be omitted and what cannot" etc, and at the end, benchmark the system to see how a server can handle a certain quantity of players, and when it start to be "laggy".

Technically speaking, WoW is a good product, but don't forget it is very much optimized in term of network and server load.

Now if you want to make a MMORPG, you have to ask yourself if you would make a game as massive as WoW: it is impossible to make content as good as the one WoW features: it's coherent, artistically beautiful, and has not too many polygons.

Personally I wouldn't think about making such good content: you have good artists or you don't have them. I think the bigger problem in a MMORPG like WoW is the bandwidth: 5000 players at the same time costs a lot of bandwidth, and I'm sure some day when the internet is a little faster, the server will be able to manage less traffic thanks to p2p protocols... but that's just an idea...

# Answer
> 0 votes
Do not listen to them!

You do not have to recreate WoW in 7 days. That's BS. As is BS everyone who says a motivated person can't do something.

Start small, read about decentralized systems and other success histories.

One good example, done in 48 hours ... yes, HOURS:

http://www.startupmonkeys.com/2010/09/building-a-scrabble-mmo-in-48-hours/

Learn from that, add some weeks to create a basic 3D client, and you're on.

Have fun.

# Answer
> 0 votes
Its not very difficult if you are not planning to clone WoW or something very similar in terms of number of game mechanics, chars, skills, quests etc., WoW has (and I assume you are not).

But its moderately difficult to develop MMO for sure because it has two overheads (online, massive players) involved when compared to standalone games.

And yes, the cost in terms of money and time is gonna depend on how big and good game you are going to create.

You can cut down time to some extent if you consider buying assets, and using existing game engines/APIs

# Answer
> -5 votes
developers are not cheap

---
Tags: mmo, costs
---


# Question
Title: Is there is IO text files in actionscript2 or 3?
i tried actionscript recently,am little scared i want to make a game that input a word from about 3000 randomly, do actionscript support that,or should i try another language?

# Answer
The question isn't really about ActionScript supporting it, but rather if your output platform supports it. With Flash/ActionScript you can build AIR applications, which can read files (all kinds of files) from the file-system (using the FileStream class).

If want to create a SWF file that runs in a web-browser instead, `FileStream` won't work. If you want to read local files or files from a different server, you'll face some security/sandboxing issues. The easiest way to load a file in a web-based flash-application is to have the text-file in the same directory as your swf file and then load it using URLLoader (the file and your SWF have to be on a web-server).

So yes, loading such a file and picking words randomly should be easy, as long as you use the correct methods to load it...
> 0 votes

# Answer
AS3: Do you want to the change the word collection frequently? You could embed the word collection in the game itself using:

```
[Embed(source="textFileName.txt")]
private var TextFile:Class;

```

If it is under 10,000 words, I would create a static literal vector of all the words.

```
var words:Vector.<String> = new <String>["word", "another word", "third word", "more words", "etc"];

```

This can be accomplished easily with a Text Editor like notepad++ or running some simple regular expression on the text content of the file. You will likely wanna replace all line breaks ("\n") with a comma (","). This would save you the time of messing with loading assets externally. Which according to my best knowledge is not approved of in some game websites.
> 0 votes

---
Tags: actionscript-3
---


title: Little and big endianness in games

text:
# Question
Title: Little and big endianness in games
Do we have to worry about byte orders in the process of programming a game? Do game consoles use different byte orders?

# Answer
> 15 votes
If you're writing networking code, this often is something you have to deal with, yes.

Also it's possible that the byte ordering in a file format is not what your platform uses, so sometimes it matters there too.

# Answer
> 8 votes
Do you have to worry about it? Likely not. A vast majority of game programming is going to be at such a level that the endianness is abstracted away. Even in networking, you're almost certainly going to be using a library for networking protocols. It's good that you're aware of it, but I doubt you'd run into an issue with it.

# Answer
> 6 votes
**Most of the time, no.**

Endianess is usually abstracted away in the high level modules of a game engine, and you don't have to worry about it on a daily basis. If it isn't abstracted, then the engine has a serious issue and should be fixed, because this isn't the kind of details you should be worrying about when making a game.

**However if you're working on some low-level parts of a C/C++ multi-platform engine, you might have to deal with it.** All three current-gen consoles use a PowerPC architecture, which is big-endian, whereas the x86 architecture used on PC is little-endian. So if you're working on some code that reads raw bytes from somewhere to put them in data structures (binary serialization, networking...), yes you will have to deal with it.

For instance, in C/C++, it's common to see this kind of byte swapping in action (not tested, welcoming corrections):

```
// Assume bytes comes ordered as big-endian
u16 u16FromBytes(void* data)
{
#if BIG_ENDIAN
    return (u16(data[0]) << 8) + u16(data[1]);
#else // LITTLE_ENDIAN
    return (u16(data[1]) << 8) + u16(data[0]);
#endif
}

```

Once again, this is OK in low-level code, but this shouldn't be something used everywhere.

# Answer
> 3 votes
It depends on the platforms you're targetting. For example, I believe that the PS3 is big-endien so if that's one of your targets then it's something you need to be aware of, yes.

In the home computer space the "Big 3" (Windows, Linux, Mac) are all exclusively, or all but excelusively, on Intel x86/x64 architectures these days, so endienness concerns are no longer relevant.

---
Tags: software-engineering
---


title: Can't get sprite to rotate correctly?

text:
# Question
Title: Can't get sprite to rotate correctly?
I'm attempting to play with graphics using Java/Slick 2d. I'm trying to get my sprite to rotate to wherever the mouse is on the screen and then move accordingly. I figured the best way to do this was to keep track of the angle the sprite is at since I have to multiply the cosine/sine of the angle by the move speed in order to get the sprite to go "forwards" even if it is, say, facing 45 degrees in quadrant 3. However, before I even worry about that, I'm having trouble even getting my sprite to rotate in the first place. Preliminary console tests showed that this code worked, but when applied to the sprite, it just kind twitches. Anyone know what's wrong?

```
int mX = Mouse.getX();
    int mY = HEIGHT - Mouse.getY();
    int pX = sprite.x;
    int pY = sprite.y;
    int tempY, tempX;
    double mAng, pAng = sprite.angle;
    double angRotate=0;

    if(mX!=pX){
        tempY=pY-mY;
        tempX=mX-pX;

        mAng = Math.toDegrees(Math.atan2(Math.abs((tempY)),Math.abs((tempX))));
        if(mAng==0 && mX<=pX)
            mAng=180;
    }
    else{
        if(mY>pY)
            mAng=270;
        else
            mAng=90;
    }

    //Calculations
    if(mX<pX&&mY<pY){ //If in Q2
        mAng = 180-mAng;
    }
    if(mX<pX&&mY>pY){ //If in Q3
        mAng = 180+mAng;
    }
    if(mX>pX&&mY>pY){ //If in Q4
        mAng = 360-mAng;
    }

    angRotate = mAng-pAng;
    sprite.angle = mAng;

    sprite.image.setRotation((float)angRotate);

```

# Answer
In your last statements, you're calculating the angle difference then calling setRotation.

```
angRotate = mAng-pAng;
sprite.angle = mAng;

sprite.image.setRotation((float)angRotate);

```

`setRotation` as the name indicates: **Sets** the rotation. You should replace the above with:

```
sprite.angle = mAng;

sprite.image.setRotation((float)sprite.angle);

```
> 1 votes

# Answer
Not sure if this is actually causing your issue, but you shouldn't have to `abs` the arguments of `atan2`. That will also get rid of most of the rest of this code as well.
> 0 votes

---
Tags: java, sprites, rotation, movement, slick
---