title: Peer-to-peer first person shooter

text:
# Question
Title: Peer-to-peer first person shooter
I've been developing a first person shooter/massive multiplayer online roleplaying game for my small business, and was wondering if it would be feasible to use peer-to-peer technology to communicate between players, without the use of an intermediary server (as our company does not have enough funds for a high-speed connection to run a game server on). How would such Peer-to-peer technology be best implemented in such a game? Here's a few of the options I've been considering:
a) Divide the game into segments, and have each segment be played on a separate P2P "mesh" (currently named XRevolution)
b) Have one mesh for all portions of the game, and place all of the players on a single grid
c) Some other P2P solution
I've already used option A (considering only one area of the game is done) on a small scale (4 computers), but am wondering how well that would scale when thousands of computers would potentially be bound to the same mesh.
Here's a list of possible concerns with P2P technology

- During penetration testing, it was identified that a client could spoof packets to lie about the state of the game to other peers, allowing people to cheat. This is identified as "medium" risk, as it could be prevented to a certain extent through various security routines that would be integrated within the game (such as encryption, movement prediction, double-checking state with other peers, AI, etc.)
- Lag was originally a problem on slower networks, but now movement prediction and other techniques are used to reduce the effect of lag, and disconnect peers whose lag is too high. However, a problem which remains is the amount of time it would take on a larger-scale network to find peers (other players), and establish connections. Due to the amount of time it would take to connect to so many peers, solution A would seem optimal to solve this particular problem
- A problem with solution A, would be in-game chat between meshes (as no two peers in different meshes can communicate with each other, except for the purpose of relaying), however, this problem could be potentially solved by using something in-between solutions A and B (such as creating a separate mesh for inter-mesh communication, which would be specific to each player or something)

What's the best way to do something like this? Solution A, or B, something in-between the two, or an entirely different solution altogether. Due to our budget, using a server to facilitate communication between players is completely out of the question, so it would be nice to use a P2P solution, otherwise the project would have to be abandoned.

# Answer
One idea, borrowed from distributed communication models, is to use a gossip-like approach. Gossip protocols are mostly concerned with scalability and reliability. The nice thing, however, is that they all use a very low bandwidth, which is crucial for P2P systems. The cost is latency, but read on, it might be solvable.

The main idea of gossip protocols is that each client sends a message to a small number of peers - let's say log(n) - and whenever a client receives a message it sends it against to log(n) peers. This creates redundancy (a client can receive a message more than once) which is good for reliability but bad for you - but on the other hand, this can lead to very fast broadcasts.

The question is, *how* to choose those log(n) clients in a way that will

1. Guarantee all clients will eventually get the message in X time.
2. Minimize the travel time of messages between two clients *that are close to each other in the game world*.

Point (2) above is - in my opinion - the key here. As long as not all peers can affect each other immediately in the game world, having high latency between them is less of an issue. A FPS in a small arena is a poor candidate here, but a massively-multiplayer online game is a great candidate.

So, how do you choose which peers will be connected to which? What you want is to build a small world network (also called small world graph). You can find some algorithms used to create it (see Harari Graph), as well as algorithms that will allow you to change it on-the-fly according to user data (I recall something involving darknet which can change links according to location). I wouldn't just use a plain Harari Graph - instead, you're probably better off with a variation that takes super nodes into consideration, I'm just not familiar with any.

I think using these kinds of protocols is a better approach than the less-scalable (and more discrete - what happens in edge boundaries?) local mesh concept.
> 1 votes

# Answer
One of the major problems about peer-to-peer is connectivity. I mean, really- a *lot* of customers just won't be able to connect to each other. Symmetric NAT, firewalls, and all this kind of thing is something that your customer will *not* want to deal with, the average customer just *can't*. Lag is also going to be an incredible problem as the number of players speeds up, and you're going to significantly increase your minimum hardware requirements as every player is running a server, effectively.

I would say, fundamentally, there's a reason that most FPS games are hosted on servers, and it's client-server works far better. If you can't afford to host your own servers, then get the users to host them- but don't go for BitTorrent-style mass peer-to-peer. That just won't work.

Develop as a client/server architecture, allow players to host both dedicated and non-dedicated, is the best way you can go. Most FPS games don't have significant server quantities provided by the developer themselves- it's nearly all third party servers. If you can't afford to host even a few servers for yourself, then it's time to seriously re-consider if you have genuinely considered the budgetary requirements for developing a first-person shooter.

Edit:

Ok, so hang on, let me get this straight. You can't afford to host a server for yourself, but you still want to have centralized server worlds, a'la an MMORPG. User hardware and user software configurations are not up to that kind of strain. I think that what you want is fundamentally impossible.
> 2 votes

---
Tags: opengl, networking, security, peer-to-peer
---


# Question
Title: Console Text game: Vertical Scroller collision problems
Alright so i'm making a **vertical side scroller where you are an '8' character traveling downward while avoiding my randomly generated walls (*the "generation" function*) on the left and right sides of the screen, and made of 'X's. you can collide with this wall 4 times before losing.**

When you collide with the wall you can no longer move, and are basically are stuck in that column of the screen until you pop out into an open space, known as a ' ' (space) character. You lose *one life* for each **INITIAL** collision with the X wall, and do not lose another until you have popped out and been freed from it.

As an added touch i have made it so after you collide while traveling down the randomly generated map (or rather as the walls move uppward while your character stays put) the X chars you've collided with are deleted. However I am having trouble getting the INITIAL COLLISION with the wall to be detected correctly. the result is the playe incorrectly losing 4 lives after hitting 1 wall and traveling throug it. This is due to some odd reason for the "numb\_collisions", which is used to count how many collisions have occured since initial collision (if it's 0 it means it *IS* the **initial collision occuring= -1 shield**), keeps getting reset to 0. The detect\_collision function seems to having some sort of problems as the returned value is allowing the if statement to pretend there is no collision, reseting "numb\_coll" to 0 and screwing the lives/shields up. **All this nonsense is located at the bottom of the main function**

Finally the **Screen.Insert()** \*function and others like it simply saves the data into a vector which represents the console window. It is later used to print the "screen" to the console at a set rate (long double speed), as seen in the for loop after the map drawings in the main function *

not Finally.. but i believe that te numb\_coll problem has something to do with the time and framrate. When running full speed i quickly die upon entering a wall as numb\_coll doesn't change or gets changed back to 0 somehow. When putting a stop in my msVS++ it works perfectly... and when holding F5 (shortcut for "continue") it partly works but numb\_coll still gets set to 0 every 3 or 4 X's down in the wall...

I hope this is enough explination, Thanks for any Help, and **LOOK AT PREVIOUS POST ABOUT COLLISION DETECTION FOR MORE SPECIFIC FUNCTION PROBLEMS** otherwise, heres all the code: Thanks again!

```
#include <iostream>
#include <time.h> // or "ctime"
#include <stdio.h> // for
#include <cstdlib>
// Windows stuff
#include <Windows.h> // GOD DAMMNIT WINDOWS WHY????
#include <conio.h>
// Ncurses
#include<curses.h>
// STL stuff
#include <algorithm>
#include <string>
#include <vector>
//String/Int conversion
#include <sstream>
// gives access to rand function
#include <cstdlib>
//gives access to time functions
#include <ctime>

// mySTOPWATCH   i think i'm gonna cry.... =')
#include <myStopwatch.h> // for keeping times
#include <myMath.h>      // numb_digits() and digit_val();
using namespace std;
enum{ NUMB_LINES= 24, SEC= 1000};                   // time stuff
enum{TIME= 345, HEALTH = 346, MAP= 247};    // for Refresh() command
enum{NONE= 256};                                    // for Refresh() transition
enum{NEW = 590, OLD = 591};                         // for the old/new screen command

// Some nCurses setup
 int r = 0,
     c = 0; // current row and column (upper-left is (0,0))
 const int nrows = 56, // number of rows in window
           ncols = 79; // number of columns in window
// Timer Setup
 Stopwatch myStopwatch(3, START);

 ///////////////////////////        RandNumb()  ///////////////////////////////////////
int RandNumb(int scope){
    srand(GetTickCount());
    return rand() % scope;};
//////////////////////////      GeneratePathStart() ///////////////////////////////
void GeneratePathStart(vector<string>& buff){
    int wall= RandNumb(80)/2,
        space = (RandNumb(75)/2)+5,
        wall2= 80- (wall+space);
    buff.push_back("");
    for(;wall> 0; wall--){
        buff[0].push_back('X');}
    for(;space> 0; space--){
        buff[0].push_back(' ');}
    for(; wall2 > 0; wall2--){
        buff[0].push_back('X');}
    };

//////////////////////////      GeneratePath()  ////////////////////////////////////
void GeneratePath( vector<string>& buff){// the buff is the seed  too
    int wall= RandNumb(80)/2,
        space = (RandNumb(75)/2)+5,
        wall2= 80-(space+wall);
    int swall= 0;
        for(char i= '0'; i!= ' ';swall++)
            i= buff[buff.size()-1][swall+1];
    int sspace= 0; int I= swall+1;
        for(char i= '0'; i!= 'X';sspace++, I++)
            i= buff[buff.size()-1][I];
    int swall2 = 80-(sspace+swall);

    // now the actual generation
    int cwall= wall-swall;
    int cspace= space-sspace;
    int cwall2= wall2-swall2;
    for(;cwall!= 0 || cspace!= 0 /*|| cwall2 != 0*/;){
            buff.push_back("");
//cwall
            if(cwall!= 0){
                if(cwall>0){
                    swall++;
                    cwall--;}
                else{ // cwall is negative
                    swall--;
                    cwall++;}}
            for(int w= 0; w <swall; w++)
                buff[buff.size()-1].push_back('X');
// cspace
            if(cspace!= 0){
                if(cspace>0){
                    sspace++;
                    cspace--;}
                else{ // cspace is negative
                    sspace--;
                    cspace++;}}
            for(int s= 0; s <sspace; s++)
                buff[buff.size()-1].push_back(' ');
// cwall2
            //if(cwall2!= 0){
            //  if(cwall2>0){
            //      wall2++;
            //      cwall2--;}
            //  else{ // cspace is negative
            //      wall2--;
            //      cwall2++;}}
            for(int w2= 0; w2 <80- (swall+sspace); w2++)
                buff[buff.size()-1].push_back('X');
    }}// end of function

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////    Sprite Class    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Sprite
{

private:
    string name;
    char symbol;
    float shield;
    int location[2];
    bool alive;

public:
///////////////////// Get and SET all the privates  ///////
    Sprite(){};
    Sprite(string a_name, char a_symbol, float a_health){
        name = a_name;
        symbol = a_symbol;
        shield = a_health;};

    char get_symbol() {return symbol;};
    void set_symbol(char sym) {symbol = sym;};

    float get_shield() {return shield;};
    void set_shield(float numb) {shield = numb;};
    void add_shield (float numb) {shield += numb;};
    void destroy_shield() {shield--; if(shield<0) alive= false;}

    string get_name() {return name;};
    string set_name(string aName) {name = aName;};

    int* get_location(){return location;};
    void set_location(int X, int Y) {
        location[0] = X;
        location[1] = Y;};

    bool Alive() {return alive;};
    void SetLife(bool f) {alive= f;};

////////////////////////////////    Move    ////////////
    bool move(int X, int Y) {
                location[0] += X;
                location[1] += Y;
                return true;};
};// end of sprite

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////   Player Class    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
class Player : public Sprite
{
public:
    Player(string name,int X, int Y, float health){
        set_symbol('8');
        set_name(name);
        set_location(X,Y);
        set_shield(100);};
private:
    // none?

};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////      Map class   ///////////////////////////////////////////////////////////////////////////////////////////////////
class Map
{
private:
///////////////////////////////////////////     Map Variables ///////////////
    string name;
    vector <string> contents;
    vector <string> save;

public:
    Map(){};
    Map(string* lines, int i, string name= "map"){name = name;
                                           contents.resize(56);
                                           Insert(lines, i);};
    ~Map(){};

///////////////////////////////////////////     generate    ////////////////////
    void generate(){GeneratePath(contents);};
///////////////////////////////////////////     Return()    ////////////////////
    string Name()               {return name;};
    vector <string> Contents()  {return contents;};
    string Contents(int Y)      {return contents[Y];};
    char Contents(int Y, int X) {return contents[Y][X];};
    vector <string> Save()      {return save;};
    int size()                  {return contents.size();};

///////////////////////////////////////////     Insert()    ////////////////////
            //  string* to an array of 24 strings;
    void Insert(string* lines, int i)
    {contents.assign(lines, lines+i);}; //insert lines 1-24

    void Insert(string astring, int Y)   {contents[Y] = astring;};

    void Insert(char achar, int X, int Y){contents[Y][X] = achar;};

    void Saveline(string line)           {save.push_back(line);};
};

/////////////////////////   SCREEN CLASS        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Screen
{
private:
///////////////////////////////////////////     Screen Variables ///////////////
    string _name;
    vector <string> new_map;
    vector <string> old_map;
    vector <Sprite*> sprites_p;

public:
    Screen(string name){_name = name;
                        new_map.resize(nrows);
                        old_map.resize(nrows);};
    ~Screen(){};

////////////////////////////////////////////    Get contents    ///////////////////////////
    vector <string> get_contents(int comm= NEW)              {switch(comm){ case NEW: return new_map; break;
                                                                            case OLD: return old_map; break;}};
    string get_contents         (int Y, int comm= NEW)       {switch(comm){ case NEW: return new_map[Y]; break;
                                                                            case OLD: return old_map[Y]; break;}};
    char get_contents           (int X, int Y, int comm= NEW){switch(comm){ case NEW: return new_map[Y][X]; break;
                                                                            case OLD: return old_map[Y][X]; break;}};

////////////////////////////////////////////    Refresh     ///////////////////////////
void Refresh(int command= ALL, int transition= NONE)
{
    //old_map = new_map;    // update the old map
    for(int r= 0; r< nrows; r++){ move(r,0);
                                  addstr((char*)new_map[r].c_str());}                   // make sure this works later
    // Insert Time
    if(command== ALL || command== TIME){
    enum{ time_loc_y= 22,
          time_loc_x= 38 };
    mvaddstr(time_loc_y, time_loc_x, myStopwatch.ClockTime().c_str());}

refresh();}; // end of function

///////////////////////////////////////////     Insert  ////////////////////////
                                                            /////////////////// Map
    void Insert(Map& map, int y1, int y2)   {for ( int mc = y1, nm= 0; mc< map.size() && mc< y2; mc++, nm++){
                                                new_map[nm] = map.Contents(mc);}
    };
                                                            /////////////////// string
    void Insert(string astring, int Y)      {new_map[Y] = astring;};
                                                            ///////////////////// char
    void Insert(char achar, int X, int Y)   {new_map[Y][X] = achar;};
                                                            ////////////////////  sprite
    void Insert(Sprite& sprite)         {new_map[sprite.get_location()[1]][sprite.get_location()[0]] = sprite.get_symbol();
                                         sprites_p.push_back(&sprite);};    // save a pointer to the sprite

///////////////////////////////////////////     Collision Detection ///////////
    bool check_collision(Sprite& sprite,int X, int Y, char& buff)
    {
    ////////////////////// check whats already there /////
        char newloc = new_map[sprite.get_location()[1]+Y]
                             [sprite.get_location()[0]+X];
        if(newloc == '|' || newloc == '/' || newloc == '_' || newloc == '=' || newloc == 'X' || newloc == '-' || newloc == 'x' ) {
            buff = newloc;
            sprite.destroy_shield();
            return true;}

        else return false;
    };
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////   MAIN    ////////////////////////////////////  MAIN  ////////////////////////////////////////////////////////////////////////
int main()
{
cout << "Maximize the screen for optimum experience!... type ok when done" << endl;
char response; cin >> response;

    WINDOW *wnd;
 wnd = initscr(); // curses call to initialize window and curses mode
 //cbreak(); // curses call to set no waiting for Enter key
 noecho(); // curses call to set no echoing
 //curs_set(a number); (0 = invisible, 1 = normal, 2 = very visible)
 int row,col; getmaxyx(stdscr,row,col);     /* get the number of rows and columns */
 clear(); // curses call to clear screen, send cursor to position (0,0)

 Screen theScreen("ascreen");

        string splashScreen[24] = {    // HERE"S THE SPLASH !
//                    1        2        3       4        5         6        7        8
//                         123456789         123456789         123456789         123456789
//               0123456789         123456789         123456789         123456789         1234567
/* 0 */         "________________________________________________________________________________",
/* 1 */         "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 2 */         "|XXXXXXX   XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 3 */         "|XXXXXX  /  XXXXXXXXXXXXXXXXXXXXX     xXXXXXXXXXX  XXXXXXXXXXXx  xXXXXXXx  xXXX|",
/* 4 */         "|XXXXX  /0}  XXXXXXXXXXXXXXXXX   /XXXXx  XXXXXXx /X xXXXXXXXXX    XXXXXX    XXX|",
/* 5 */         "|XXXX  /000}  XXXXXXXXXXXXXX   /XXXXXXXx  XXXXX  /X  XXXXXXXX  /X  XXXX  /X  XX|",
/* 6 */         "|XXX           XXXXXXXXXXXX   /XXXXXXXXxx XXXX  /XXX  XXXXXXX /XX  XXXX  |X  XX|",
/* 7 */         "|XX   /XXXXXX   XXXXXXXXXX   /XXXXXXXXXXXXXXXX  /XXX  XXXXXX  |XXX  XX   /X  xX|",
/* 8 */         "|X   /XXXXXXXX   X*X*X*XXX  /XXXXx        xXX          XXXXX  |XXX      /XXX  X|",
/* 9 */         "|XXXXXXXXXXXXXXXXXXXXXXXXX   XXXXXXXXXXX   XX  /XXXXX  XXXX   |XXXX    /XXXX  X|",
/* 10 */        "|XXXXXXXXXXXXXXXXXXXXXXXXXX   XXXXXXXXX    Xx /XXXXXXX xXXX   |XXXXx  /XXXX   X|",
/* 11*/         "|XXXXXXXXXXXXXXXXXXXXXXXXXXXX            XXXx /XXXXXXX xXX     XXXXXxxXXXX    x|",
/* 12 */        "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 13 */        "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxxxxxxxxxxxxxxxxXXXX|",
/* 14 */        "|XXX  XXxXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX                  XXX|",
/* 15 */        "|XXX  XXXx  XX/  XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX_____XX     XXXXXXXXXXXXXXXX|",
/* 16 */        "|XXX    XXX  /  XXXXXXXXXXXXXXXXXXXX  XXXXXXXXXXXXXXXXXXXX     XXXXXXXXXXXXXXXX|",
/* 17 */        "|XXX /0] XX/  XXXXx      xXX  XXXXXXXXXXX    xXXX    xXXXX                 xXXX|",
/* 18 */        "|XXX    XX/  XXXXX  XXXXXXXX    xXXX  XXX  XXXXXX  XXXXXXX                 xXXX|",
/* 19 */        "|XXXXXXXX  XXXXXXX  XXx  xXX  XXXXXX  XXX    xXXX    xXXXX     XXXXXXXXXXXXXXXX|",
/* 20 */        "|XXXXXXXXXXXXXXXXX  XXXX  XX  XXXXXX  XXX  XXXXXX  XXXXXXX     XXXXXXXXXXXXXXXX|",
/* 21 */        "|XXXXXXXXXXXXXXXXXx      xXXxxXXXXXXxxXXX xXXXXXX xXXXXXXX                  XXX|",
/* 22 */        "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXxxxxxxxxxxxxxxxxxxXXX|",
/* 23 */        "|______________________________________________________________________________|",};

    string _lines_[56] = {
//                    1        2        3       4        5         6        7        8
//                         123456789         123456789         123456789         123456789
//               0123456789         123456789         123456789         123456789         1234567
/* 0 */         "________________________________________________________________________________",
/* 1 */         "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 2 */         "|XXXXXXXX                    XXXXXXXXXXXXX              XXXXXXXXXXXX   XXXXXXXX|",
/* 3 */         "|XXXXX                 XXXXXXXXXXXXXXXX     XXXXXXXXX     XXXXXXXXXX   XXXXXXXX|",
/* 4 */         "|XXXX      XXXXXXXXXXXXXXXXXXXXXXXXXX    XXXXXXXXXXXXXXX    XXXXXXXX   XXXXXXXX|",
/* 5 */         "|XXX      XXXXXXXXXXXXXXXXXXXXXXXXXXX    XXXXXXXXXXXXXXX    XXXXXXXX   XXXXXXXX|",
/* 6 */         "|XX       XXXXXXXXXXXXXXXXXXXXXXXXXX    XXXXXXXXXXXXXXXXX    XXXXXXX   XXXXXXXX|",
/* 7 */         "|XX       XXXXXXXX           XXXXXXX    XXXXXXXXXXXXXXXXX    XXXXXXX   XXXXXXXX|",
/* 8 */         "|XXX       XXXXXXXXXX         XXXXX    XXXXXXXXXXXXXXXXXXX    XXXXXX   XXXXXXXX|",
/* 9 */         "|XXXX        XXXXXXXXXXXX     XXXXX    XXXXXXXXXXXXXXXXXXX    XXXXXX   XXXXXXXX|",
/* 10 */        "|XXXXX        XXXXXXXXXXX     XXXXX    XXXXXXXXXXXXXXXXXXX    XXXXXX   XXXXXXXX|",
/* 11 */        "|XXXXXXX        XXXXXXXXX     XXXXXX    XXXXXXXXXXXXXXXXX    XXXXXXX   XXXXXXXX|",
/* 12 */        "|XXXXXXXX        XXXXXXX      XXXXXX    XXXXXXXXXXXXXXXXX    XXXXXXX   XXXXXXXX|",
/* 13 */        "|XXXXXXXXXX       XXXXX       XXXXXXX    XXXXXXXXXXXXXXX    XXXXXXXX___XXXXXXXX|",
/* 14 */        "|XXXXXXXXXXX                XXXXXXXXX    XXXXXXXXXXXXXXX    XXXXXXXXxxxXXXXXXXX|",
/* 15 */        "|XXXXXXXXXXXX              XXXXXXXXXXXX     XXXXXXXXX    XXXXXXXXXXx   xXXXXXXX|",
/* 16 */        "|XXXXXXXXXXXXXXXXX       XXXXXXXXXXXXXXXXX              XXXXXXXXXXXx   xXXXXXXX|",
/* 17 */        "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 18 */        "|    MOVE USING 'WASD' |=|  avoid the walls |=|  SURVIVE!!  |=|  press 'O' quit|",
/* 19 */        "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 20 */        "|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 21 */        "|XXX                                                                        XXX|",
/* 22 */        "|XXX                                                                        XXX|",
/* 23 */        "|XXX                                                                        XXX|",
/* 0 */         "|XXX                                                                        XXX|",
/* 1 */         "|XXX                                                                        XXX|",
/* 2 */         "|XXX                                                                        XXX|",
/* 3 */         "|XXX                                                                        XXX|",
/* 4 */         "|XXX                                                                        XXX|",
/* 5 */         "|XXX                                                                        XXX|",
/* 6 */         "|XXX                                                                        XXX|",
/* 7 */         "|XXX                                                                        XXX|",
/* 8 */         "|XXX                                                                        XXX|",
/* 9 */         "|XXXX                                                                      XXXX|",
/* 10 */        "|XXXXX                                                                    XXXXX|",
/* 11*/         "|XXXXXX                                                                  XXXXXX|",
/* 12 */        "|XXXXXXX                                                                XXXXXXX|",
/* 13 */        "|XXXXXXXX                                                              XXXXXXXX|",
/* 14 */        "|XXXXXXXXX                                                            XXXXXXXXX|",
/* 15 */        "|XXXXXXXXXX                                                          XXXXXXXXXX|",
/* 16 */        "|XXXXXXXXXXX                                                        XXXXXXXXXXX|",
/* 17 */        "|XXXXXXXXXXX                                                        XXXXXXXXXXX|",
/* 18 */        "|XXXXXXXXXXXX                                                      XXXXXXXXXXXX|",
/* 19 */        "|XXXXXXXXXXXX                                                      XXXXXXXXXXXX|",
/* 20 */        "|XXXXXXXXXXXXX                                                    XXXXXXXXXXXXX|",
/* 21 */        "|XXXXXXXXXXXXX                                                    XXXXXXXXXXXXX|",
/* 22 */        "|XXXXXXXXXXXXXX                                                  XXXXXXXXXXXXXX|",
/* 23 */        "|XXXXXXXXXXXXXX                                                  XXXXXXXXXXXXXX|"
/* 24 */        "|XXXXXXXXXXXXXXX                                                XXXXXXXXXXXXXXX|",
/* 25 */        "|XXXXXXXXXXXXXXXXX                                            XXXXXXXXXXXXXXXXX|",
/* 26 */        "|XXXXXXXXXXXXXXXXXX                                          XXXXXXXXXXXXXXXXXX|",
/* 27 */        "|XXXXXXXXXXXXXXXXXXXX                                      XXXXXXXXXXXXXXXXXXXX|",
/* 28 */        "|XXXXXXXXXXXXXXXXXXXXXXX                                XXXXXXXXXXXXXXXXXXXXXXX|",
/* 29 */        "|XXXXXXXXXXXXXXXXXXXXXXXX                              XXXXXXXXXXXXXXXXXXXXXXXX|",
/* 30 */        "|XXXXXXXXXXXXXXXXXXXXXXXXX                            XXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 31*/         "|XXXXXXXXXXXXXXXXXXXXXXXXXXXX                      XXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
/* 32 */        "|XXXXXXXXXXXXXXXXXXXXXXXXXXXX                      XXXXXXXXXXXXXXXXXXXXXXXXXXXX|",
};

    //////////////////////////////////  Splash Screen   /////////////////////////////
    Map splashScreen_map(splashScreen, 24);
    theScreen.Insert(splashScreen_map, 0, nrows);
    theScreen.Refresh(MAP);
    myStopwatch.Wait(3);
    myStopwatch.Restart();
    /////////////////////////////////////////////////////////////////////////////////

    Map L1(_lines_, nrows, "L1");
    theScreen.Insert(L1, 0, nrows);
    Sprite player("Player",'8', 5);   //(8, 12, 16);
    player.set_location(47, 22);

    ////////////////////// Check if new line is needed;
    double refreshes= 0;
    int newlines= 0;
    const double speed= .1;

    int numb_coll= 0;
    bool dead= false;
/////////////////////////   start of the for loop
    for (bool quit = false; quit != true && dead== false;)
    {   double newTime= myStopwatch.ElapsedTime()- refreshes;
        if(newTime >= speed){
            theScreen.Insert(L1, 0+newlines, nrows+newlines);
            refreshes+= speed;
            newlines++;
            if(L1.size()<= nrows+newlines+2)
                L1.generate();}
    /////////////////   Keypress    ///////////
    int xMove = 0;
    int yMove = 0;
    if (kbhit()){
        int key = getch();
        key = toupper(key); // makes whatever key uppercase

                        int stepSize = 1;
                        bool validPress = true;
        switch(key){
    // update health here............
        case 'W': yMove = -stepSize;break;
        case 'S': yMove = stepSize; break;
        case 'A': xMove = -stepSize;break;
        case 'D': xMove = stepSize; break;

        case 'P': getch();          break;
        case 'O': quit = true;

        default: validPress = false;}

        if(validPress == true){/*do something here or i might not need it.....*/}
        } /* end of if(kbhit())*/

        char coll; // the buffer for the collided char
        theScreen.check_collision(player, xMove, yMove, coll);
        if(coll== 'X'){
            if(player.Alive()== false){}
                // do something about it
                // if there is life
            else{
                for(int I= 0; I< numb_coll && numb_coll< player.get_location()[1]; I++){
                    theScreen.Insert(' ',player.get_location()[0], player.get_location()[1]-(I+1));}
                if(numb_coll>0)
                    player.add_shield(1);
                numb_coll++;
                theScreen.Insert(player);}}
        else if(coll != 'X'){
            theScreen.Insert(' ', player.get_location()[0],player.get_location()[1]);// get rid of old player placing
            player.move(xMove, yMove);                                               // put in new charater placing
            theScreen.Insert(player);
            numb_coll= 0;}

    theScreen.Refresh();}// so refresh and restart the for loop
if(dead== true){
//  theScreen.Insert(a gameover map);
               }
endwin(); // curses call to restore the original window and leave
return 0;
}

```

# Answer
alright i figured it out: i was "**colliding with myself**" as the check collision function saw my character sprite in the location it was checking, even if it was still in the wall... This happened in-between the map scrolling and changes.
> 0 votes

# Answer
This code is a mess, but after a cursory glance I'm going to go out on a limb and say you probably want to check against the value of check\_collision. The char you pass by reference into the function is uninitialized (albeit probably zeroed out in debug builds) and you don't set it in the false case of the function, but you immediately check it afterwards.

Really what you need to do is attach a debugger to it and step through it to see what's going on.
> 2 votes

---
Tags: c++, game-loop, console
---


title: Render only some of graphics?

text:
# Question
Title: Render only some of graphics?
In XNA I am building my own textbox, and listbox.

For the textbox, I want it to render all text it can, and then cut off at the end of the textbox. But I don't want it to cut whole letters. I want it to cut exactly where the pixel limit is, so that if I write "SPAAAAAAAACE", and the size is 50 for instance, then it will only render "SPAAAA" and then a half A, or whatever is remaining in the pixels.

For my listbox, it's kind of the same thing. If I am scrolled half down, one element needs to be only half-visible.

How can I do this? Is it possible to add something to a buffer, and then before drawing it, clearing a specific rectangle from the buffer again?

# Answer
> 2 votes
You could use a scissor rectangle. It's a property on the GraphicsDevice class that you can set. Scissor testing must also be enabled.

The scissor rectangle only allows draws in a certain area (a rectangle). This would cut off the pixels, not the letters, of the text you are trying to draw. There are other ways to do this, but you might find this to be the easiest.

# Answer
> 6 votes
Set your `GraphicsDevice.Viewport` or `GraphicsDevice.ScissorRectangle` so that you are only drawing over the top of your text area. You must be outside of a sprite-batch when you do this (ie: between end and begin). Remember to set it back when you're done.

Remember that `SpriteBatch`'s drawing area covers the viewport (so (0,0) is the top-left of the viewport).

---
Tags: xna, directx, xna-4.0
---


title: Best way to create bullet-proof counter

text:
# Question
Title: Best way to create bullet-proof counter
I am building a gaming system where many players can play together some sort of table game. There could be hundreds of game tables at the same time. The system consists of several components where main components are gaming servers and DBworker and in between there is rabbitMQ. DBWorker is something that takes care about databases.

So, I need to make sure that each game has unique ID to properly track results of the games. I would love to have some sort of auto-increment solution. Of course I can do some sort of sequence in PostgreSQL DB and pull new ID every time but for me it seems as an obvious bottleneck (I don't want to be linked to DB all the time. In case DB goes down show must go on while our engineers recover DB).

So, any ideas or personal experience of implementing something similar?

p.s. I am thinking about timestamp as ID but real ID would be better. Cannot figure out why - if I am wrong, please correct me.

Thank in advance for everyone!

# Answer
> 7 votes
That's the domain of GUID's which are not normal counters and supposed to be globally unique. Since you didn't mention the language and framework you use, I throw in this: How to create a GUID/UUID in Javascript

For other frameworks just google your framework + GUID

# Answer
> 2 votes
AFAIK, there is no way to be absolutely 100% safe from collision but you could make it very, very unlikely. Take for example the algorithm John Millikin posted in Maik Semder's link above and attach a hashed timestamp at the end.

That way, even if two users manage to log in at precisely the same millisecond, the chances of them getting the same ID would be one in 22,300,745,198,530,623,141,535,718,272,648,361,505,980,416

:-)

# Answer
> 1 votes
You could use HI/LO algorithm with database sequences. Obtain sequence value, multiply by N and keep internal counter running from 0 to N-1 and add it to multiplied value. When the counter hits N, you get a new value from database sequence. The you'll hit the database only at every Nth ID. Of course this will not help if your database goes down for too long time.

# Answer
> 0 votes
So far I've decided to use lovely rabbitMQ in the following way:

1. I will create a service that will put 1, 2, 3 etc. messages into the rabbitMQ. It will also sometimes check if there are enough numbers or not (let's say in one hour 1000 games in average, so for one day I won't need more that 24000 numbers).
2. When a new game starts gameKeeper will pull new number from the rabbitMQ and use it.

Since rabbitMQ is extremely stable and many other very important things are linked on it - it is ok. If rabbit dies - no problem with number, because whole system will die. So, for me it seems ok.

Why I don't use UUID? UUID is not really good for me for few reasons:

1. I cannot know order of the games (of course I can add extra fields in DB like timestamp or something like this)
2. It is not nice to tell to players something like this: "Yo bro, you are laying game:XXXXX-XXXXXXXXXXXXXX-XXXXXXXXXXXXX-XXXXXXXXX-XXXX" :-)

So, I think my dummy approach will work for me for some while. Thank you for your advices! Ups in you reputations.

---
Tags: architecture
---


# Question
Title: Collision Detection for sidescrolling Tile based Game
I've been working on a tile based game with a 2d array as fundamental ground for my tiles. Now my next step is to have the wall tiles be impenetrable, so that the player can walk ontop of them and collide against their sides/bottom.

So as this is loosely based on tonyPa tutorial, it uses the corners of the player character (top-left, top-right, bottom-left, bottom-right corners) to check if any corner hits a wall (walls are assigned as "1" in the 2d array). When a corner touches a tile that is recognized as "1" (wall), I want to check from what side the player is hitting, and then move the player next to the tiles side, to simulate a collision.

Now what I've noticed is, it's easy to check if any corner is touching a wall, but its harder to determine which side the corner is hitting. Because of this, my current code is not simulating a satisfying collision detection. As my hero walks on the ground, he randomly stops because the bottom corners not only touch the top of the tiles, but also the sides it seems.

### **UPDATE**

So I changed my code based on the first answer by **bummzack**. Using center points of each side of player entity instead of each corner. And now my character slides down walls without getting stuck and walks across grounds fairly smoothly, but another problem arises. If the player jumps on a tile, and the center part of the bottom is NOT within the tiles width, he falls right through. And this is because I am just comparing a POINT (the center point specifically) and not the full bottom side against the top of the tile beneath the player.

Here's a link to the **SWF-file**, http://dl.dropbox.com/u/28271061/\_TileGameFLA.swf , X to JUMP, Z to RUN, ARROWKEYS to MOVE, which should give you a visual example of what's happening:

Here is the **UPDATED** code (all collision code is within "collisionCheck" function)

```
    private function onKEYDOWN(event:KeyboardEvent):void{
        var pressedKey = event.keyCode;

        if(pressedKey == Keyboard.RIGHT){
            rightKey = true;
        }

        if(pressedKey == Keyboard.LEFT){
            leftKey = true;
        }
        if(pressedKey == Keyboard.Z){
            runKey = true;
        }
        if(pressedKey == Keyboard.X){
            jumpKey = true;
        }
    }

    private function onKEYUP(event:KeyboardEvent):void{
        var releasedKey = event.keyCode;

        if(releasedKey == Keyboard.RIGHT){
            rightKey = false;
        }

        if(releasedKey == Keyboard.LEFT){
            leftKey = false;
        }
        if(releasedKey == Keyboard.Z){
            runKey = false;
        }
        if(releasedKey == Keyboard.X){
            jumpKey = false;
        }
    }

    private function collisionCheck():void{

        centerY = Math.floor((theHero.y + (theHero.width/2))/ts);
        centerX = Math.floor((theHero.x + (theHero.width/2))/ts);
        top = Math.floor(theHero.y / ts);
        bottom = Math.floor((theHero.y + theHero.height) / ts);
        left = Math.floor(theHero.x / ts);
        right = Math.floor((theHero.x + theHero.width) / ts);

        //If there is no ground under the player, start falling.
        if(curMap[bottom][centerX] != 1 && curMap[bottom][centerX] != 1){
            gravity = 3;
            onGround = false;
        }

        if(vy > 0 && oldBottom < bottom){

            if(curMap[bottom][centerX] != 0){//If either on of the bottom corners are touching a "1"-tile (a wall)

                theHero.y = ((bottom - 1) * ts) + 2 ;
                gravity = 0;
                vy = 0;
                onGround = true;
                jumped = false;
                jumpSpeed = 9;

            }
        }

        if(vy < 0 && oldTop > top){
            if(curMap[top][centerX] != 0){
                theHero.y = (top + 1) * ts;
                gravity = 3;
                vy = 0;
                jumpSpeed = 0;
            }
        }

        if(vx < 0 && oldLeft > left ){
            if(curMap[centerY][left] != 0){
                vx = 0;
                theHero.x = (left + 1) * ts;

            }
        }
        trace(curMap[bottom][centerX]);
        if(vx > 0 && oldRight < right ){
            if(curMap[centerY][right] != 0 ){
                vx = 0;
                theHero.x = ((right - 1) * ts )+ 1.8; // 1.8 so it doesnt touch wall, it goes right through if its the accurate 2.0

            }
        }

    }

    private function moveChar():void{

        if(rightKey){
            if(runKey){
                vx = 7;
            }else{
                vx = 4;
            }
        }
        if(leftKey){
            if(runKey){
                vx = -7;
            }else{
                vx = -4;
            }
        }

        //Stand still if you're not pressing left or right ON THE GROUND (in air you should after one key press)
        if(!leftKey && !rightKey && onGround){
            vx = 0;
        }

        if(jumpKey && jumpSpeed > 1 && !jumped){
            vy -= jumpSpeed;
            jumpSpeed *= 0.8;
            onGround = false;
            gravity = 3;
        }

        vy += gravity;

        if(vy > 14){
            vy = 14;
        }

    }

    private function onENTERFRAME(event:Event):void{

        if(myStage.stage.focus != myStage){
            myStage.stage.focus = myStage;
        }

        //These variables represent where the hero WAS before being moved
        //, this helps to see if hero approached the tile from the left/right/top/bottom
        //, thus gives us an additional way to check where player is coming from
        oldBottom = Math.floor((theHero.y + theHero.height) / ts);
        oldLeft = Math.floor(theHero.x / ts);
        oldRight = Math.floor(theHero.x + theHero.width) / ts;
        oldTop = Math.floor(theHero.y / ts);

        moveChar();

        theHero.y += vy;
        theHero.x += vx;

        collisionCheck();

    }

}

```

}

This is by far not the smartest way to check collisons, but I think it might work well enough. I just need someone to throw me in the right direction for making a solid collision detection engine for a simple tile based game.

# Answer
> 2 votes
Instead of checking the corners of your sprite, I suggest you check the midpoints. Like in this image:

The bottom "sensor" checks for ground collisions, the front checks for "wall" collisions. Usually you'll need maximum two active sensors. Examples:

* Player walks forward, *FRONT* and *BOTTOM* must be checked
* Player stands still: *BOTTOM* must be checked
* Player performs forward jump. While moving upward, *FRONT* and *TOP* must be checked, when falling, *FRONT* and *BOTTOM* must be checked.
* etc.

---
Tags: collision-detection, actionscript-3, tiles
---


title: To sell or give for free

text:
# Question
Title: To sell or give for free
I am currently making a game that I was originally planning to sell. It is a simple 2D arcade style game for the PC. I've seen many indie games become popular and generate revenue from advertisements, but the game itself remains free. I need some advice on whether or not I should sell my game, release it for free with advertisements, or ask for donations and keep the game free.

I feel that my game is fun, but of course the graphics aren't tip top because I am a programmer, not an artist. I just take screenshots of 3D models I get from Turbosquid and crop around it to make a sprite. Also, and I could be very wrong about this, it seems that there are more legal issues surrounding selling a game than making it free and generating revenue from advertisement, or asking for donations. If I am wrong, someone please correct me.

Also, I am very interested in generating some revenue for my work, but that isn't at the very top of my list. I am in my last year of high school, soon to be going to college, and I am going to major in computer science/software engineering. So I am trying to gain some preliminary experience at home by coding stuff every day. One way of getting this experience is by making this game.

So what do you think? What route should I take? What has worked well with other indie games?

Thanks in advance.

# Answer
Due to your young age, i would give it for free and build a reputation for your self.
> 6 votes

# Answer
Unless your game can compete with commercial games (like Magicka, $10) you probably won't make much money by selling the game. People bying games are more often comparing games to each other and visual appeal does a lot. Also, small price games aren't very great sellers on PC, because handling payment is trickier.

Nick Gravelyn shares some insight about low price mobile games in his blog and says that ads were more profitable for him. I wouldn't think selling games on PC would be easier.
> 4 votes

# Answer
Considerung how many such arcade games there are, I'd give it away for free. If the people like it, they'll probably buy add-ons, a second part or donate money (although you won't get rich with the latter …).

If you want to keep the Ad-route open, make sure you add an automatic update check or something like that - if you feel you have enough users to start, you can always enable/add this feature ;-)
> 2 votes

# Answer
Make it "**pay what you want**", i.e. ask for payment to unlock full version, but allow the user to decide how much to pay. Bear in mind to set a minimum price to cover the transaction fees (if you use paypal it's ~.40¢).

**Don't give full version asking for donations**, because — as Jeff Vogel often points out — users are lazy and will just "delay" paying you if they can.

*Of course* the game should be worth buying in the first place (if it isn't, it doesn't really matter which system you chose).
> 2 votes

# Answer
Giving it for free would like you said, keep you from most legal obligations but if you put a very prominent donate button next to the download link I would guess many people that like the game would come back and make a donation. If you really wanted to you could even put a non-obtrusive donate button somewhere in the game that would open up a web browser. The most important thing though is to not have the donate buttons become annoying.

Alternatively you could go for an Android market style approach where most of the game is free, but a purchased version has a couple more features that reward those that donate.
> 1 votes

# Answer
**Ask for payment but allow people to download it without paying**.

That way people can try the full game easily, and they know you wish to be paid, and they know you respect them as you've allowed them to try and keep the entire game at no risk to themselves. If they have a **happy experience** they may be come back to give you money. (This is the model I'll be using for my game.)

Keep the purchase price above $5, there is a lot of fraud/hassle with credit card purchases $5 and under.
> -1 votes

---
Tags: game-industry, marketing, revenue
---


# Question
Title: Where can I go to find a game graphic artist?
Where's a good place to post to find a decent game artist to create a small number of 32-bit sprites? This is for an internal code war framework so it's minimal work - maybe a couple of hours.

Any suggestions where I should post to find someone to do this?

# Answer
The answer depends on your intention to pay or not to pay for this work, but whatever is the answer you can try on "art & design" forums such as:

or "game creation" forums:

Finally you can ask on "pixel art" forums:

However, it's indeed harder to find people ready to work for free (not impossible trough) and if you can't afford for this kind of small help you can also consider to make it yourself as ashes999 suggested.
> 18 votes

# Answer
This is a frequent problem that game developers encounter that's hard to surmount. Unless you can get someone on-board full-time for free (like a partner on your development team), I would really recommend learning how to create basic artwork yourself.

With tutorials and basic stuff available on the internet (sprites, textures, icons, etc.) you can quickly learn to create polished *technical* art -- not the most beautiful, but good enough to launch.

I also personally find that Flash is a great tool for creating (vector) art assets. It has a simple but sufficiently diverse toolset to allow you to create good technical art. (Technical means not necessarily creative or polished or stylistic; but technically clean.)
> 4 votes

# Answer
If you wish to pay an artist to create custom sprites try:

Alternatively, for internal work that will not be demoed in public you could just use **sprite sheets** that are floating around on the net as a temporary solution.
> 1 votes

# Answer
I'd recommend TIG Source as a nice place to visit. There are many good people in this Indy gaming and gamedev community.

If you go there, please remember to introduce yourself!

EDIT: if it's XNA related, you could also ask/look at the XNA forums: team positions/services wanted/offered
> 0 votes

---
Tags: sprites
---


title: Ellipsoid v. Box collision detection

text:
# Question
Title: Ellipsoid v. Box collision detection
I'm trying to write some collision detection code.

ATM i have the code properly resolving Ellipsoid v. Ellipsoid collisions, and Box v. Box collisions, but Ellipsoid v. Box collisions doesnt work.

In general how do you test for interesection between these two.

What i've been doing is:

Finding the closest point on the ellipsoid to the box, and vice versa.

```
vector3 closestVertexOnBox = // Closest vertex on the box to the ellipsoid;
vector3 closestPointOnEllipsoid = // Closest vertex on the ellipsoid to the box

```

In this case ( ellipsoid v. box ) you have 4 axes.

* The axis from the center of the circle to the nearest point on the box.
* The X,Y,Z standard axes ( assuming its an AABB ) -

Put them all in an array

```
 vector3[] axes = { normalize( closestVertexOnBox - ellipsoid.origin ), unitX, unitY, unitZ }

```

Then for each axis in that array, Project the vector from the center of each shape, to its vertex closest to the other shape; onto each axis to find the projected half widths.

```
float minOverlap = infinity
vector3 overlapAxis;

for each axis in axes
{
    float prjBoxHalfWidth = Dot ( axis , closestVertexOnBox - box.origin )
    float prjEllipsoidHalfWidth = Dot ( axis , closestPointOnEllipsoid - ellipsoid.origin )

```

If the sum of any of the projected half widths are smaller than the projected distance between the two, then their is no collision

```
    float prjDistance = Dot( axis , box.origin - ellipsoid.origin )

    if(prjBoxHalfWidth + prjEllipsoidHalfWidth < prjDistance) return // no collision

```

Now get the axis with the least overlap out of all of them

```
    float overlap = prjBoxHalfWidth + prjEllipsoidHalfWidth - prjDistance

    if(overlap < minOverlap) {

         minOverlap = overlap;
         overlapAxis = axis;

    }

```

Then resolve the overlap

```
ellipsoid.origin += overlapAxis * minOverlap/2
box.origin -= overlapAxis * minOverlap/2

```

Thats pretty much my ( pseduofied ) code. If thats good, then i might have an error, but thats wrong, then what am i not taking into consideration or forgetting.

# Answer
How do you store the ellipsoid?

If it has a position, orientation and the radius in local x- and y-axis, it might be easier to calculate the inverse transformation matrix, that transforms the ellipsoid to a circle. Transform the AABB into that space too using that matrix, then you can make simple triangle-circle collision tests.

Edit: In the left image you see the original ellipsoid with the axis aligned box. In the right image both objects are transformed by the ellipsoid's inverse matrix, so the ellipsoid becomes a circle and the AABB becomes 2 triangles. Now its only a matter of 2 triangle-circle tests.
> 9 votes

---
Tags: collision-detection, intersection
---


title: Flash framerate reliability

text:
# Question
Title: Flash framerate reliability
I am working in Flash and a few things have been brought to my attention. Below is some code I have some questions on:

```
addEventListener(Event.ENTER_FRAME, function(e:Event):void
{
    if (KEY_RIGHT)
    {
        // Move character right
    }
    // Etc.
});

stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e:KeyboardEvent):void
{
    // Report key which is down
});

stage.addEventListener(KeyboardEvent.KEY_UP, function(e:KeyboardEvent):void
{
    // Report key which is up
});

```

I have the project configured so that it has a framerate of 60 FPS. The two questions I have on this are:

1. What happens when it is unable to call that function every 1/60 of a second?
2. Is this a way of processing events that need to be limited by time (ex: a ball which needs to travel to the right of the screen from the left in X seconds)? Or should it be done a different way?

# Answer
> 2 votes
**About your code:** I think it's funny that you use anonymous functions for event listeners, it's something I don't see that often in ActionScript (it is more common with JavaScript). You should be aware that you can run into some garbage-collection issues if you add event listeners like that (because you're no longer able to remove them later on). As long as your event listeners stay up during the whole execution time of your app, it isn't an issue though.

**Regarding your questions:**

1. An update step can take longer to execute than 1/60 of a second, even if you specified the FPS to be 60. It just means it won't go *above* 60, but can easily drop *below* 60 FPS. You can test this yourself by adding some dummy loop in your event listener, something like: `for(var i:int = 0; i < 1000000; i++){ var tmp:Number = 1000.0/20.0; }`. The Flash runtime will use as much time as required for a frame. That means it will try to run at the specified framerate, but it won't enforce it in any way (eg. stopping execution of code). An endless loop (`while(true){}`) will freeze your game on the first frame...
2. I don't understand what you mean by "limited by time"? Are you asking whether or not to use/assume a fixed or variable timestep?

**Update** (regarding 2.): To make an object travel some distance in a given time, you could either use a tweening-library like tweenlite or implement it yourself like this:

```
// initalize this with getTimer() in your constructor or init method
private var _time:Number;

// how long the sprite should be animated.. here 3.5 seconds
private var _duration:Number = 3.5;

// event listener. needs to be bound to Event.ENTER_FRAME using addEventListener
private function handleEnterFrame(evt:Event):void {
    var t:Number = getTimer();
    var elapsed:Number = (t - _time) * 0.001;
    _time = t;

    _duration -= elapsed;
    if(_duration <= 0){
         // ensure that elapsed doesn't overshoot the duration
         elapsed += _duration;

         // remove the event listener.. this will stop executing further updates
         removeEventListener(evt.type, handleEnterFrame);
    }

    // the sprite will travel 200 pixels per second (in the x-axis)
    // so 700 pixels in total (200 * 3.5)
    _sprite.x += 200 * elapsed;
}

```

# Answer
> 0 votes
The question you need to ask yourself is: Is the duration of this motion related to the frame rate of the final swf? In the past the only to create motion was through the timeline or enterFrame making the framerate extremely crucial. Today you can create motion independent of the framerate. You will be surprised that most swfs today are set to a standard rate that works for video or audio imports on the timeline (30 fps). I would recommend you explore: fl.transitions.Tween.

# Answer
> 0 votes
This tutorial at 8bitrocket offers a good method of maintaining smooth movement and a fairly constant framerate, for many applications this is more than necessary, but built into it is a method of changing the framerate on the fly with a great deal of precision.

# Answer
> 0 votes
This is all known as the Elastic Racetrack.

---
Tags: flash, actionscript-3, events, frame-rate
---


# Question
Title: Best pathfinding algorithm for a tower-defense game?
What do you suggest would be the best algorithm for a tower-defense game? It's a 2D based tile game, where there is walls and towers blocking the way, between spawnpoints and their destination points.

Constantly, as the player places a new tower to block the way, or to help shoot spawning units before they reach their destination, a new path for the affected spawnpoint's path will have to be recalculated, and the units must be re-routed to that new path.

Therefore, I need performance.

I tried the A\* algorithm, but everytime the player places a new tower, and path has to be recalculated, the existing units who haven't gone past the tower yet, get lost, and stand still, since they were a part of the old path that has now lost its pathing information.

# Answer
A\* should be plenty fast enough. Each time a tower is placed you should calculate a new path for each spawn point, and assign that path to each unit that is spawned there. You should also calculate a new path for the units "in the field". Units in the field can have their paths calculated as the shortest path to get back on track, as in a path to the new path. Or the units can have their path calculated from their current position to the destination.

You can likely save calculations by grouping units in the field and calculate a common path for them all. For example if you have a group of units in tile (4,7), they can all use the same path, so you just have to calculate it once.

Additionally (depending on what your rules are) you should consider doing these calculations as a check before the tower is placed. This will disallow the player from placing towers that block all paths. Or as some tower defense games work, if the play blocks all paths, the units just ignore towers when path finding.
> 3 votes

# Answer
### Answer:

Rather than calculating a path from one point to another you could calculate the movement direction for each separate tile. Start from the exit, mark each adjacent tile with a pointer to the exit, then from each of these tiles let all adjacent unmarked tiles point to that tile etc.

The maths are really the same as Dijkstra's algorithm (A\* without distance optimization), you just don't throw away any data and therefore end up with a many-to-one path.

You should end up with a data-array that looks something like this, generated in linear time:

```
|---|---|---|---|
|   |   |   |   |
| | | X | ->| e |
| v |   |   |   |
|---|---|---|---|
|   |   | ^ | ^ |
| | | X | | | | |
| v |   |   |   |
|---|---|---|---|
|   |   | ^ | ^ |
| ->| ->| | | | |
|   |   |   |   |
|---|---|---|---|
| ^ | ^ |   | ^ |
| | | | | X | | |
|   |   |   |   |
|---|---|---|---|

```

### Somewhat related random ramblings:

Regarding point-to-point pathfinding it's worth noting that A\* lose a lot of it's advantage to the simpler Dijkstra algorithm when operating in a twisted maze. A\* will probably still search fewer nodes, but it is also slower per node than Dijkstra.

For the typical tower defence maze, entry and exit points are placed at the edge of the field, this means that Dijkstra won't as otherwise waste time by searching a big field in the wrong direction. In conjunction with the maze this means that Dijkstra and A\* will search almost the same number of nodes, thus Dijkstra takes the win in this case for being faster per node.
> 11 votes

# Answer
I actually wrote a game once which did this sort of thing perfectly. And the amount of recalculation was very little compared to A\*.

In a grid base map (even if the characters don't move in a grid base way), you have a 2dimensional array, and mark the finish with 0,0.

Add the four adjacent squares to a list.

Then using a for or while loop, iterate through the list, and simply give each square a value of the minimum of the four surrounding squares + 1.

Then add the four surrounding squares to that square to the list (if their value is still not set).

basically, on an empty map, you could receive an effect like this in the array:

* 3,2,1,2,3,4
* 2,1,0,1,2,3
* 3,2,1,2,3,4
* 4,3,2,3,4,5
* 5,4,3,4,5,6

However on a map with obstacles...

* 3,2,1,2,3,4
* 2,1,0,X,4,5
* 3,2,1,X,5,6
* 4,X,2,X,6,X
* 5,4,3,X,7,8

Now this method has 3 main benefits.

If i place a block on a 4 for example. Then only the squares with a value of 5 or higher need to be updated! I simply have a loop which goes through the values of 5 upwards (make sure you have all the 5's done before you do the 6's, and all the 6's before the 7's, etc.

Or you could do it from an empty array again. It's extremely fast!

The second benefit, is that the grid is exactly the same for all enemies! Every enemy in the map follows this array. If it is on a 7, then it wants to move to a 6! Doesn't matter which 6 it takes, because they all are the same distance (6 squares) away from the end!

Thirdly, if, during your loop to work out the values of this array, if a square doesn't get reached, (if the value stays unset, and there isn't a tower there), then it means that part of the map is cut off from the base. In most tower defenses, this isn't allowed. So if you check this before confirming a towers placement, it means you know whether it is a legal or illegal build.

Hope this helped, Randomman159
> 3 votes

# Answer
You need to compute a new path for each existing unit, *and* a new one for the newly-spawning units.
> 1 votes

# Answer
It really depends on the type of tower defence you are developing.

Case 1: If your towers can't block your runners (so you can't change the path), you can simply develop a simple region system. It is really easy to implement:

Unit1 enters region1 -\> run to region2 Unit1 enters region2 -\> go to region3 ...

All you need is to position you regions in way that there is no blocking objects between two linked regions.

Case 2 (Your case): Your towers can block. If its the case you will need to design a A\* algorithm system. The system can be harder to implement for beginners but don't worry, there is a lot of A\* pathfinding system on the web that you can reuse. You will need to recalculate the path every time something change the actual path. But don't worry, a good A\* system can recalculate the path of thousand of units in a blink of an eye!

You can mix the region system and the A\* path finding for a faster results! You will only have to calculate the path to the next region and not to the endpoint so you will improve you performance.
> 0 votes

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


# Question
Title: How do I determine the collision normal in an axis aligned bounding box collision?
I have a 3d moving box and a stationary box. I can detect collisions ok but now I would like to slide the moving box against the stationary box as a collision response. For this I need the normal of the face that collides with the moving box. Does anyone know how I figure this out? It doesn't seem like the collision test gives me this information. Any help is appreciated.

# Answer
In order to calculate the normal to a plane (the collided AABB face) you need:

* 3 points of this plane (2 non parallel edges).
* The cross product of two edge vectors of this plane (usually from the same point of origin).

This will produce a vector perpendicular to this plane (but a plane have 2 sides).

---

Here is an example of how to calculate the cross product.

Let A, B, C and D be the four points of your AABB collided side.

```
[B]---(c)
 |     |
[A]---[D]

```

If we use ABC, then the normal to the plane is

```
ADxAB (if we want a normal pointing out of the screen)
ABxAD (if we want a normal pointing inside the screen)

```

*(it's just because our example is facing the screen, if the plane is seen from left side, the fist normal will point right and the second will point left)*

As you can see the order in which you take the points will impact the side the normal will point to. That's why developers usually store their points in a specified order (clockwise or counter-clockwise, but the same for all faces) so they know in which order to use them.

---

See this on more details now:

```
AB = [ Bx-Ax, By-Ay, Bz-Az ]
AD = [ Dx-Ax, Dy-Ay, Dz-Az ]

```

Here is how to get the first normal

```
ADxAB = [ ADx, ADy, ADz ] X  [ ABx, ABy, ABz ]
      = [ (ADy*ABz - ADz*ABy), (ADz*ABx - ADx*ABz), (ADx*ABy - ADy*ABx) ]

```

And here come the second normal pointing to the other side

```
ABxAD = [ ABx, ABy, ABz ] X  [ ADx, ADy, ADz ]
      = [ (ABy*ADz - ABz*ADy), (ABz*ADx - ABx*ADz), (ABx*ADy - ABy*ADx) ]

```

If you replace the ABx, ABy, ABz etc. values with the differences calculated just before (Bx-Ax, By-Ay, Bz-Az etc.) the cross products you will get the normal vectors.
> 1 votes

---
Tags: collision-detection, geometry, normals, bounding-boxes
---


# Question
Title: Observing particular Port for measuring network game performance
How can I check/inspect the performance of some network application via observing the port it used, I want to test the performance of my network game.

If my game is using port 1009, how can I check the different parameters, like data outflow, inflow and other metrics on this port?

# Answer
I would suggest Wireshark (ex Ethereal) as an interesting solution.

* Wireshark is free, open source and cross-platform.

I worked with Ethereal (before it changed to Wireshark) in the past, and I must admit that it was a very powerful tool. So WireShark is probably as powerful as Ethereal was and is probably more user friendly than it was in old days.

According to Wikipedia

> Wireshark is a free and open-source packet analyzer. It is used for network troubleshooting, analysis, software and communications protocol development, and education. Originally named Ethereal, in May 2006 the project was renamed Wireshark due to trademark issues.
>
> Wireshark is cross-platform, using the GTK+ widget toolkit to implement its user interface, and using pcap to capture packets; it runs on various Unix-like operating systems including Linux, Mac OS X, BSD, and Solaris, and on Microsoft Windows. There is also a terminal-based (non-GUI) version called TShark. Wireshark, and the other programs distributed with it such as TShark, are free software, released under the terms of the GNU General Public License.

Here is a video introduction to quickly have an idea of the interface and how it can be used and another one that shows you the ins and outs of advanced graphing.

Finally, here is the Wireshark User's Guide.
> 2 votes

# Answer
If you only want to check how much data is passed trough that specific port and suming that you are using windows vista or windows 7 you can also use windows resource manager, in network tab there is tcp connections which show you how much data is passed trough specific connection at time you are monitoring, you can also filter connections by process in that tab.
> 1 votes

---
Tags: java, networking, multiplayer, performance, testing
---


title: Help implementing virtual d-pad

text:
# Question
Title: Help implementing virtual d-pad
**Short Version:**

I am trying to move a player around on a tilemap, keeping it centered on its tile, while smoothly controlling it with SneakyInput virtual Joystick. My movement is jumpy and hard to control. What's a good way to implement this?

---

**Long Version:**

I'm trying to get a tilemap based RPG "layer" working on top of cocos2d-iphone. I'm using SneakyInput as the input right now, but I've run into a bit of a snag.

Initially, I followed Steffen Itterheim's book and Ray Wenderlich's tutorial, and I got jumpy movement working. My player now moves from tile to tile, without any animation whatsoever.

So, I took it a step further. I changed my `player.position` to a `CCMoveTo` action. Combined with `CCfollow`, my player moves pretty smoothly. Here's the problem, though: Between each `CCMoveTo`, the movement stops, so there's a bit of a jumpiness introduced between movements.

To deal with that, I changed my `CCmoveTo` into a `CCMoveBy`, and instead of running it once, I decided to have it `CCRepeatForever`. My plan was to stop the repeating action whenever the player changed directions or released the d-pad.

However, when the movement stops, the player is not necessarily centered along the tiles, as it should be. To correctly position the player, I use a `CCMoveTo` and get the closest position that would put the player back into the proper position. This reintroduces an earlier problem of jumpiness between actions.

What is the correct way to implement a smooth joystick while smoothly animating the player and keeping it on the "grid" of tiles?

**Edit:**

It turns out that this was caused by a "Bug Fix" in the cocos2d engine.

# Answer
There are three ways to solve this problem :

1. you can just implement update function for your player class and move it in that update function, this approch will eliminate use of CCMoveBy or CCMoveTo classes and you can easily control how you want the movement be applied, for example just wait until x or y is just in center of tile and then stop moving.
2. The second approch is to just eliminate CCRepeatForever when you want to stop our player and then add CCMoveBy Directly to the player action list, this way you'll be sure that CCMoveBy will finish what all the movement you requested.
3. And the last choice is to Implement your code to do what CCRepeatForever does, this is how CCRepeat for ever is implemented in c++, and I also added another if to make sure you have to repeat CCMoveBy just one more time.(sorry for c++ code I hope you can convert it to objective-c)

```
void myCCRepeatForever::step(ccTime dt)
{
    CCMoveByInstance->step(dt);
    if (direction is still the same)
        if (CCMoveByInstance->isDone())
        {
            ccTime diff = dt + CCMoveByInstance->getDuration() - CCMoveByInstance->getElapsed();
            CCMoveByInstance->startWithTarget(m_pTarget);
            CCMoveByInstance->step(diff);
        }
}

```
> 0 votes

---
Tags: iphone, cocos2d, joystick
---


title: Help understanding gluLookAt()

text:
# Question
Title: Help understanding gluLookAt()
I am fairly new to openGL( 3 months ) and am asking for assistance in understanding the fundamentals behind gluLookAt().

Currently I have spent most of my time with openGL modeling scenes with fixed views, and I wanted to begin using gluLookAt combined with keyboard and mouse callbacks to "explore" my scenes. I created a simple program to play around with the functionality of gluLookAt when I first realized I may not understand fully what is happening.

My program creates a world using `glOrtho(-4,4, -4,4, -4,4)` confining my area somewhat around the origin (0,0,0) upon which I place the standard `glutSolidTeapot(0.5)`. Then in an attempt to create a "camera" revolve around the teapot, in an idle callback function I write this

```
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt( cos(business), 0, sin(business), 0.0,0.0,0.0, 0.0,1.0,0.0 /*up vector*/ );
glutPostRedisplay();

```

Turns out, this worked. The view shows a revolving teapot. So I take another step and attempt to create an elliptical path around the teapot, multiplying either cos() or sin() (not both) by 2. This works as well but does not have the same effect I was expecting. The view rotates around the teapot, but I imagined along the path the teapot would "appear" to be closer at points, a zooming in effect of sorts. This leads to my question.

What exactly do I not understand about this? or.. Why is this not doing what I am expecting?

# Answer
That is simple. You are using orthographic projection (viewing rays are parallel), so it doesn't make any difference if you are at distance 1 or 100.

Use gluPerspective and it will work how you expect.

*(left img ortho projection, right img perspective proj)*

your code may look like this:

```
glMatrixMode(GL_PROJECTION);
gluPerspective( PI / 3.0f, window_width/window_height, zNear, zFar);

...

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt( cos(business) * radius, 0, sin(business) * radius, 0.0,0.0,0.0, 0.0,1.0,0.0 /*up vector*/ );
glutPostRedisplay();

```

img source
> 6 votes

---
Tags: opengl, c++, matrix, projection
---


title: Networking SFML Berkley Sockets

text:
# Question
Title: Networking SFML Berkley Sockets
So I'm starting work on a multi-player space shooter. And I've run into some issues. As I type this, my system is currently:

```
//Main While Loop
Gather Input
Update Own Sprites Based on Input
Send Position Information to Server. [Owner,Obj#,Image,X,Y,Theta] (TCP)
Receive All Position Information for All Objects From Server
Update Game Screen.

```

Now I won't end up using this, it's for the initial networking testing phase. I'll probably end up using dead reckoning. However I have a couple questions:

*1:* I am using TCP for all my networking. However it jumps and skips if you drop any packets at all, so I'd like to switch to UDP and have a numbering mechanism to make sure all packets arrive. Is there a preferred Networking Schema for game communication?

*2:* For critical things like object hits with bullets Should I implement a second port for these important events, or just use the same UDP proto?

*3:* (Side Question) How should I regulate my framerate with the networked game? I don't want to have an unnecessary Sleep in each frame...

# Answer
> 1: I am using TCP for all my networking. However it jumps and skips if you drop any packets at all, so I'd like to switch to UDP and have a numbering mechanism to make sure all packets arrive.

Then you will just have reimplemented TCP on top of UDP, and will get exactly the same symptoms you describe.

If you really can't cope with TCP - and most games can - the solution is not to code your own method of resending packets, but to ensure that most of your data can be lost without a problem. For example, object positions are rarely important enough to require a resend unless they reflect a final destination after which no further movement will be sent. `Receive All Position Information for All Objects From Server` is generally not practical. `Receive whatever movement information is available` is what you'd typically do instead.

> Is there a preferred Networking Schema for game communication?

No.

> 2: For critical things like object hits with bullets Should I implement a second port for these important events, or just use the same UDP proto?

Use the same port. Your messages should have a flag in them that indicates whether they are reliable or unreliable. The reliable messages (ie. the important ones) will also contain a sequence number, allowing you to spot if any are missing. If one does appear to be missing (ie. the incoming sequence number is bigger than the last sequence number plus 1) then buffer the message and wait. Allow a certain amount of time for reordering (eg. 50ms, 100ms, whatever) and then ask the other side to resend whatever is missing. It's best if you can include this information inside a message you were going to send anyway, to avoid sending extra packets (which is the last thing you want to be doing when the network connection is poor).

More info here: http://gafferongames.com/networking-for-game-programmers/reliability-and-flow-control/

> 3: (Side Question) How should I regulate my framerate with the networked game? I don't want to have an unnecessary Sleep in each frame...

The network is just an input source like any other - it has no effect on how you handle your rendering frame rate. It's often wise to separate out the logic updates so that they happen the same number of times per second no matter how fast your rendering is going: see http://gafferongames.com/game-physics/fix-your-timestep/ for more details.
> 6 votes

---
Tags: c++, software-engineering, networking, multiplayer
---


# Question
Title: How to make animated 2D texture on 3D cube with XNA 4
I'm looking for how to make 3D gauge on Windows Phone 7, that's mean a 3D object (a watch for example) with a basic 2D texture (= Numbers of my watch) and a rotating 2D texture (=neddle of my watch). The shaders can't be used for this (WP7 !!).

I did not find anything on this (books or internet).

There are 2 big problems for me : 1) load 2 textures on the same object. 2) rotating one of this 2D texture and update it on the 3D model.

algorithmic I use for is:

In LoadContent()

1) load 3D model + Final 2Dtexture + Basic 2Dtexture and rotating 2Dtextures
2) Apply final 2Dtexture on 3D object 3) Load RenderTarget2D and SpriteBatch

In Draw()

1)Use TargetRender as back buffer 2)draw Basic 2dTexture and Rotate Rotating 2Dtexture with spritebatch 3)put the back buffer into my Final 2DTexture 4) free the back buffer

But that's not working at all !!!

If you have idea or interesting links, thanks for help.

JeanGil

# Answer
> 1 votes
I would create a seperate quad for the watch needle and rotate that instead. Remember you need to translate, rotate and then -translate to rotate around a specific point.

If you do this, your first question should be invalid. If you still wish to do this however, you could pack the two textures into one file, then play around with the UV's to get the right texture at the right part.

# Answer
> 0 votes
Since we can't solve all your requests in one question, my best advice is: search for tutorials with example programs.

Here is one for XNA on Windows 7 including texture-loading and rendering.

Alternatively, please ask one specific question to focus on.

---
Tags: xna-4.0
---


# Question
Title: Persistent Browser Based Game: To Captcha or not to Captcha?
I've been working (off-and-on) on a pbbg that's pretty old school. If you've ever played Carnage Blender then you get the idea.

If not, it's a simple idea that's been done a lot: A player is allocated a certain number of "points" each day, and spends those points to attack other players. Points accrue over time, up to a certain cap.

The point system is designed to prevent over-achievers from completely out-pacing casual players.

In the case of carnage blender, a CAPTACHA system prevents a user from "gaming" the system with a bot or a script designed to use all of their points each day with minimal effort. Every once in a while a random CAPTCHA is displayed, and if not passed the user will be suspended for an hour.

What I'm wondering is how to make this more user friendly for my game. I recognize that I must prevent bad behavior like this, and I could easily take the same CAPTCHA approach, but is there a more user friendly alternative?

Initial research uncovered ASIRRA by Microsoft, but the fluffy/cute vibe doesn't work well with my intended game theme.

**UPDATE**
What I'm most interested in are alternatives to the standard "spell this word" CAPTCHA. I want to try to keep game-play as uninterrupted as possible for the good players.

I've seen what I call *One-Time-Use* CAPTCHAs, like asking a user "what is five plus six minus two?" But this would require too much effort compiling a large enough database of questions to foil the malicious users. Especially since the CAPTCHA is intended to be used so often.

**UPDATE #2**
As Joe Wreschnig pointed out in his answer, having a CAPTCHA system to limit bots from playing the game *faster* than humans is a bit redundant if turns are limited per day. I didn't explain my point system to-the-letter, and that was my fault. In reality, 10 or 20 points accrue every few minutes, and cap off at 200. So, a very competitive player could return every few hours and use his points. I want to reward those people who like my game so much that they return so often. If I prevent them from playing until the next day when they get their points, I would be turning away players who would otherwise be enjoying my webgame. This prevents a player from spending points **constantly** while still giving them a few points every few minutes.

This is open to abuse.

# Answer
"is there a more user friendly alternative?"

A more user friendly alternative to what end? What is the captcha designed to achieve in your system?

It sounds like it's designed to prevent botting, under the premise that bots can play "faster" than regular players. But you have also already capped the number of actions a user can take per day, which achieves the same goal. So the captcha seems redundant.

I would encourage you to look at Kingdom of Loathing's alternate frontends. It uses a similar turns-per-day system, and has several popular alternate frontends such as KoLmafia, which are in many ways indistinguishable from "botting" the game. Most players feel these add to, rather than take away from, the game, even for casual players. They make it easier to batch actions, automate some of the slower parts, and offer more options for in-game UI.

If you already have checks in your game to ensure AIs can't simply play faster than humans - and by having turns-per-day, you have such a check - then I suggest you try *encouraging* automating your game, as if your design is balanced, it can only improve player experience.
> 8 votes

# Answer
I'd never bother to play a game that demands captchas: they are really a terrible practice that should be avoided.

Your game seems to have deeper problems than that anyway: ideally a game should give no advantage to a stupid bot, so that it would be pointless to use a stupid bot in the first place. If you cannot achieve that, that's a design problem that will have no real solution, only more-or-less valid workarounds.

*With "stupid bot" I mean bots that do not take any meaningful decision and instead just "farm" (that's what happens here). Smart bots (such as aim-bots or chess playing bots) are a completely different matter.*

Still, assuming you are comfortable with the idea of making a design-flawed game, there is still room for improvements.

Accept the fact that you can't stop a really determined bot and instead focus on the only thing you can do: make it useless to use a bot. If people have no reason to use a bot... they won't use them (and if they do anyway it won't matter).

A possible solution is to allow one login per week instead of one per day. If people will forget to login for more then a week, they are unlikely to be really interested in playing anyway, so they won't be using bots to keep gaining credits. If, on the other hand, there is someone so screwed that makes a bot that logs once a week and then comes back three months later to attack random people, well, you have just found someone so determined that would have cracked you anyway, whatever system you chose (unless you chose a non-flawed system, of course).

ps: don't make the mistake of putting more effort into working-around design flaws then actually solving them in the first place!
> 3 votes

# Answer
I would not ban a failed CAPTACHA for an hour, that seems harsh, I would just prevent them moving forward until they successfully complete the CAPTACHA and allowing for a new CAPTACHA image to be shown.

I would also only display the captcha if they making requests too quickly, I'd store the a DateTime on every request, and then compare it to the next request, if its less than 2-4 seconds, you display the CAPTACHA, otherwise let them go. You'll need to determine what a reasonable interval is for your game, server, and bandwidth.

You could also do a "forced" CAPTACHA every X times that an action is taken, this will prevent even an automated script with a `pause` built in so it doesn't trigger the time limit CAPTACHA.
> 2 votes

# Answer
If players spend point to attack other players, and points are limited, the obvious abuse seems to me to be to create multiple accounts.

If you successfully manage to limit people to a single account, then the issue with bots to me would be that under your system people can fire them off when they are asleep or at work.

So given the constraints: (1) no advantage for bots (2) reward people for logging in multiple times per day

It seems to me the ideal thing is to cap the number of actions they can use during a day to some reasonable number.

E.g. you might decide that someone could reasonably log in multiple times over an 8 hour period, and tweak the system appropriately. Or someone might check it before they go to school/work in the morning, check it when they get home, check it again after dinner, and check it before going to bed.

Determine what your 'ideal' user is doing, and then make the point system reward that.

---

I'd build a system that rewarded spending a chunk of points all in one go. To do this I'd have a variable recharge rate on the points. Every time you spend points, the recharge time to get the next point increases... so if a bot is spending points as fast as they get them, it will take longer and longer to get the next one, whereas if a person spends all the point they accumulated overnight before leaving the house in the morning, they will have got them all back by the time they get home from work/school (8-12 hours later).
> 2 votes

# Answer
In a game, I would recommend replacing "captcha" with "puzzle mini-game". The difference being the level of fun involved. There're really little reason for a captcha in a game unless you have tried a custom mini-game and that is still getting botted. In which case make it require more intelligent tactics.
> 2 votes

# Answer
As suggested by Tchalvak, I would go the 'puzzle mini-game' route, however I would reward a few points for passing it so as to make it more user-friendly
> 1 votes

---
Tags: web, game-mechanics, interface, security
---


# Question
Title: Execute code at specific intervals, only once?
I am having an issue with XNA, where I want to execute some code in my Update method, but only at a given interval, and only once. I would like to avoid booleans to check if I've already called it once, if possible.

My code is here:

```
    if ((gameTime.TotalGameTime.TotalMilliseconds % 500) == 0)
    {
        Caret.Visible = !Caret.Visible;
    }

```

As you may have guessed, it's for a TextBox control, to animate the caret between invisible and visible states. I just have reason to believe that it is called twice or maybe even 3 times in a single update-call, which is bad, and makes it look unstable and jumpy.

# Answer
`TotalMilliseconds` is a `double`, so you should not be doing an equality comparison there. There is every chance that the timer gets a fraction of a millisecond off, and your conditional never triggers. Also, there is no mechanism in your description for that code to run more than once per update.

I recommend storing an integer frame number somewhere: `int frameNumber;`

Then, in your update function, simply do this:

```
frameNumber++;
Caret.Visible = (((frameNumber / 30) % 2) == 0);

```

30 frames, at 60 frames per second, is 500 milliseconds.

---

The alternative method, which is more generally useful, is to store a countdown timer: `double timeLeft;`

And then do something like this:

```
timeLeft += gameTime.ElapsedGameTime.TotalMilliseconds;
const double triggerTime = 500;
if(timeLeft > triggerTime)
{
    timeLeft -= triggerTime;
    Caret.Visible = !Caret.Visible;
}

```

---

Just to comment on your code, and on mpnk121's answer: It's fine in this case, but in general the downside of using `TotalGameTime` (instead of `ElapsedGameTime`) is that you have no mechanism for pausing it.

By the way: 500 milliseconds seems like a very fast rate for a caret blink? Perhaps slow it down a bit.
> 11 votes

# Answer
Your update function probably isn't called in multiples of 500ms every time, which is what your modulus would imply.

You could save the last time it was called, then compare it with the current time , like

```
int lastcaret = gameTime.TotalGameTime.TotalMilliseconds;
// in loop
if((gameTime.TotalGameTime.TotalMilliseconds - lastcaret) >= 500)
  ToggleCaret();
  Lastcaret = gameTime.TotalGameTime.TotalMilliseconds;

```
> 3 votes

---
Tags: xna, xna-4.0, timer, control
---


title: WM_PAINT and Direct3D

text:
# Question
Title: WM_PAINT and Direct3D
I've seen people who've written in code where the graphics of a scene are rendered in response to WM\_PAINT. I only ever rendered the scene once all Windows messages were done translating, and then rendered the scene. Is this the wrong way to go about it, or should I only use DirectX rendering in response to WM\_PAINT?

# Answer
WM\_PAINT response code is a convenient place to put rendering routines, especially when rendering in a window, but I believe - it is not the best.

WM\_PAINT message is recieved by window message loop when system wants to update its contents, eg. during moving or resising window or when window content is showed again due to closing other overlapping window. Rendering in response to WM\_PAINT assures that rendered content stays accurate. It is up to programmer to assure that WM\_PAINT is posted to window's message queue often enough, to keep up to the desired rendering framerate. It can be achieved by calling

```
BOOL InvalidateRect(__in  HWND hWnd, __in  const RECT *lpRect, __in  BOOL bErase);

```

function.

It is not necessary to do it that way, as in fact- posting and processing window messages can introduce a significant delay to rendering pipeline.

Better way is to call rendering routines from the message loop itself, something like this:

```
BOOL done = false;
while (!done)
{
    if (PeekMessage(&msg, wnd, 0, 0, false))
    {
        int result = GetMessage(&msg, wnd, 0, 0);

        if (result == -1)
        {
             // process GetMessage() error
        }
        else
        {
             if (msg.message == WM_QUIT)
                 done = true;

             TranslateMessage(&msg);
             DispatchMessage(&msg);
        }
    }

    DoTheUpdatingHere();
    DoTheRenderingHere();
}

```
> 6 votes

---
Tags: directx, windows
---


title: Closest point on an ellipsoid

text:
# Question
Title: Closest point on an ellipsoid
I need to know how to get the closest point on the surface of an ellipsoid to another point.

I had an idea, but apparently i was wrong, and oversimplfying.

What i did was squash the ellipsoid and point into local space, so the ellispoid is a unit circle

```
vector3 pointLocalCoord = ( pointOriginal - ellipsoid.origin ) / ellipsoid.radii

```

Then from there, the closest point should be 1, in the direction of the transformed point from the origin

```
vector3 closestPointOnEllipsoidLocal = norm ( pointLocalCoord )

```

Then get back into standard space

```
vector3 closestPointOnEllipsoidWorld = closestPointOnEllipsoidLocal * ellipsoid.radius + ellipsoid.origin

```

But of course, all of this seems not to work, i was curious if any body could point me in the direction of some pre-existing code or such; as some of the articles i've tried reading kinda go a bit out of my scope of knowledge.

Also, if that seems right to you, please do tell. I'm pretty sure its wrong though.

**Edit: Sorry for the unresponsiveness with this and my other question. They're different, i was axperimenting with something else**

# Answer
> 11 votes
As your feared, you are oversimplifying. If you transform your scene so that the ellipse becomes a circle, you are using a non-isometric transformation and relative distance is not preserved. This can be best seen in the following diagram, where the point closest to the black point clearly changes:

Finding the closest point on an ellipse is a non-trivial problem. It requires the root of a 4th-degree polynomial that usually does not have a computable answer. However, you can refine an approximate answer with Newton's method and converge reasonably well.

I suggest you read David Eberly's *Distance from a Point to an Ellipse in 2D* for both a written proof of the formula, and 50 to 100 lines of code that you can reuse to solve your problem.

---
Tags: xna, collision-detection, intersection
---


# Question
Title: Is it okay to release a playable, but not graphical, game to the Android Marketplace?
I'm working on my first simple game for release. I'm going to have it to a point of being playable, interface complete, but very few if any graphics, and no overall style aside from the basic Android white text on black. Should I go ahead and release this game, with a graphics upgrade to come in the next week or two, or should I just wait until I have the better graphics?

The name doesn't require any graphics to play, it's a simple causal type. The graphics won't matter really for play, but will include things like a logo, screen when you die, enhanced opening screen, etc.

# Answer
The downside will be that if people get turned off by the lack of graphics that they may just assume that any future releases won't have any graphics (even if you make it clear to them when they first try it), and so you could lose many of them as potential members of your audience in the future.

I suggest you release it with a different title the first time, such as "*name-of-game* pre-graphical beta" if you do decide to release early, then later you can release a newer one called "*name-of-game* beta" once you're satisfied that the graphics have improved enough, and then (eventually?) release it again as simply "*name-of-game*."

On a note about text-mode games, these tend to be adventure games and there still is a serious following for them, so you may get some interest from that crowd as well. The point is that if the gameplay is entertaining/enticing enough, the graphics may be able to take a backseat anyway (South Park would be an example of a television cartoon that is certainly better known for its content than its graphical prowess).
> 5 votes

---
Tags: android, graphics
---


# Question
Title: Suitable Client Server setup for Network Game testing
I want to test my Client/Server game for which, currently, I am using localhost for both Client and Server.

Obviously I'm not getting any fluctuation in data and measure idea of performance, and in other parameters, what I wanted to ask how I would test a real world scenario:

if i create a little network with two computers or

if check that on LAN on which i am or

**Are these cases (localhost included) equivalent?**

or do I really need to test my game on different LANs to have reliable and realistic testing data?

**How these different network setups influence the testing process?**

Can somebody please suggest methods for testing the effect of network latency and packet loss on my game?

**which above setup will give me more up and downs in number with LEAST setup/implementing efforts.**

The game is supposed to be played on a LAN but it IS capable of more.

# Answer
> 2 votes
Its hard to tell exactly what you're asking, but there's my thoughts.

When testing networking code, its perfectly acceptable to use `localhost` for both client and server to get it working, because its quick to debug and you can easily debug both client and server. It is important to note, that this is NOT sufficient for testing and final development.

In order for your testing to have maximum impact, you must test as many situations as you can. The minimum you can get away with are (IMO) these:

1. One client and server on same computer
2. One client and server on the same SUBNET
3. One client and server on the same SUBNET with additional players from other SUBNETS (Internet, etc) connecting to server via NAT
4. Server on the Internet and multiple additional Internet clients connected

# Answer
> 2 votes
You can download software emulators that will artifically add packet loss, network latency, and whatever else you might like into the connection. On reflection, I actually don't know where to get these packages, but I know that they do exist.

# Answer
> 2 votes
**Local Host:**
All the network testing I've done on localhost has been completely misleading. Since it's a perfect environment it's useless...

**Packet Loss:**
The packet loss and latency you experience will differ based on your current lan set up. I've set up on several separate routers, and gotten completely different results.

**Recommendation:**
It would be horrifically slow to compile, throw the executable elsewhere, recompile (in the beginning, before menus and such) run it on your compie, and connect, then test. What I've done lately is have a persistant server (on another computer) that simply forwards whatever is sent over any port to a partner, and set my program up as a client, so there's no further config necessary. It's a path that's treated me well so far.

---
Tags: java, networking, multiplayer, performance, testing
---