# Question
Title: How can I create beautiful, random, abstract images?
To generate random, beautiful, abstract images – which algorithms are not too complex and give good results?

# Answer
> 11 votes
An approach I saw once was to generate a random mathematical function mapping x, y to a color. It was represented as a parse tree, built top-down, where each node was randomly chosen to be +, -, \*, /, a trigonometric function, a constant color, or a variable (x or y); then any required subtree(s) were recursively generated. Then you evaluate the function for each pixel to get the image. It produced an interesting mix of structure (repeated elements, broken symmetries, etc.) and randomness.

Here are a couple examples. These use a slightly different algorithm than what I just described: they generate three separate random functions, one each for R, G, and B. Unfortunately the result tends to look like three independent images composited, which is why I suggested just using one random vector-valued function.

EDIT: I wrote up a slightly more detailed version of this answer as a blog post, including a Python implementation of the algorithm.

# Answer
> 12 votes
Using a cellular automata for simulation of a relaxion-diffusion equation might be right up your lines - the equations aren't really all that complex and the results are pretty striking. Have a look at http://www.cc.gatech.edu/~turk/reaction\_diffusion/reaction\_diffusion.html for some of the first papers on applying the results to computer graphics; http://www.sci.utah.edu/~allen/reaction-diffusion.html has some other fine examples, including for instance:

# Answer
> 7 votes
Comment gone answer, as per Nathan Reed's suggestion :)

Karl Sims did some work about 20 years ago producing (among other things) wonderful abstract images, see here for details. Scroll about halfway down to see some beautiful samples.

Basically a syntax tree is created, mapping X and Y coordinates to colors, and then genetic programming was applied using exhibition (IIRC) visitors for scoring.

In the actual implementation described, the syntax trees are expressed and evaluated using Lisp. Section 4.1 in the linked paper lists the available functions, which are about half normal mathematical functions and half image processing/generation functions such as blur or bw-noise.

---
Tags: procedural-generation, graphic-effects
---


title: Isometric tile map format

text:
# Question
Title: Isometric tile map format
I've just knocked up a fairly basic isometric tile based game and I'm looking for the best way to store the level data.

Each tile coordinate is assigned one or more numbers that correspond to a tile from the tile set. At the moment I have a small level set up in the code but I'm looking for a quicker way to populate a level with tiles and load them into the game.

I was thinking just making XML files would be the way to go and if that's the case any ideas on how I should write them?

# Answer
> 6 votes
Take a look at Tiled. It has support for Isometric maps and stores them as XML.

# Answer
> 2 votes
Not exactly what you were asking but might be of interest to you.

Do you know Mappy Tile Editor ? it's very popular in the subject

You could get some inspiration from it or there is the extension for XNA you could use : XNA Content Pipeline Extension to Mappy Maps(.FMP). This way would save you some time : you won't have to write a ContentImporter and a ContentProcessor. (That can be painful sometimes :-)

# Answer
> 2 votes
Maybe take a look at tIDE? It's a XNA 3.1/4.0 solution for using tiles. It also has support for Tiled and Mappy (suggested in the other answers).

And to answer your basic question, XML is the way to go.

---
Tags: xna-4.0, isometric, tilemap, xml
---


title: Replay system: record inputs or events?

text:
# Question
Title: Replay system: record inputs or events?
I read this: How to design a replay system But it don't really answer my question.

My game is built with the client "view" of the game as a separate program from the server "model" and "controller". (a bit like a mmo, or any multiplayer game built this way). The server side is always the "truth" of the game, it only accept action requests as input from the clients and output events and "current state" messages.

The game model and rules are fully deterministic with a fixed "tick" update cycle, so on the server side I can record both the events sent to the client views, and the action requests. Both are associated to specific cycle number.

The question is: **in this case, to setup a replay system, should I use the input, or user action requests (as suggested in there) or the events?**

It looks to me that both would give exactly the same output. The only differences I can see are:

* Events gives the real output while action requests have to be processed to give events.
* Action requests might be far less data to record.

Are there other things to consider?

# Answer
> 5 votes
Given a deterministic system they are logically equivalent so your summary is pretty much correct. However there are 2 more things that would sway me towards recording input actions rather than output events:

1. If you save the actions, you can use them as test data later, as they exercise more of your code than just replaying events will. This can help with diagnosing crash bugs, finding behavioural regressions between builds, etc.
2. In future you might change the events that you send for a certain action, or you might send different events to different clients for some reason. In this case, the replay could become invalid or incomplete. The same problem could in theory apply to inputs, but usually the domain of inputs is more constrained than outputs and so is less likely to change and easier to accommodate with backwards compatibility when it does. (Inputs are limited to what the player and other input sources (eg. random number generator) can do, whereas the outputs include all the results of those inputs plus any other outputs generated by the game rules, such as presentation hints, periodic server-side events, etc.)

# Answer
> 1 votes
Either works, though there are a few things to consider.

First, remember that you need to record time information. For games with any kind of variable frame rate, this can be particularly tricky; you need to ensure your replay data can provide the exact same timing information that the game originally used for simulation.

You also need to account for tweaks to the game behavior. If you record input and then tweak *any* part of how input is handled, how physics resolves, etc, your recording becomes invalid. Even if you record game events, if any part of how those events get interpreted changes, you're stuck.

If you just want playbacks, a good approach is to record a specific list of positions and rotations for the player entity along with timing information. Disable as much of physics and other gameplay logic while running the playback as you can. How easy or feasible this is depends on how many other objects you need to sync up.

---
Tags: replays, game-loop
---


title: Missing triangles in model

text:
# Question
Title: Missing triangles in model
I am having an issue where triangles in a model aren't being shown.

The left is wireframe, the right is the finished image. For some reason a bunch of the triangles aren't being shown.

The project is in C#, using OpenGL (OpenTK). I'll provide more information if neccessary (such as code), but there's a lot of code, so i'd rather check if anyone has a simple solution first... Please comment if you need more info though.

EDIT: Here's the buffer code if it helps...

```
public void LoadBuffers(MeshData m, out uint indexBuffer, out uint dataBuffer, out int vertOffset, out int normOffset, out int texcoordOffset)
    {
        float[] verts, norms, texcoords;
        uint[] indices;
        m.OpenGLArrays(out verts, out norms, out texcoords, out indices);
        GL.GenBuffers(1, out dataBuffer);
        GL.GenBuffers(1, out indexBuffer);

        int buffersize = (verts.Length + norms.Length + texcoords.Length);
        float[] bufferdata = new float[buffersize];
        vertOffset = 0;
        normOffset = verts.Length;
        texcoordOffset = (verts.Length + norms.Length);

        verts.CopyTo(bufferdata, vertOffset);
        norms.CopyTo(bufferdata, normOffset);
        texcoords.CopyTo(bufferdata, texcoordOffset);

        bool v = false;
        for (int i = texcoordOffset; i < bufferdata.Length; i++)
        {
            if (v)
            {
                bufferdata[i] = 1 - bufferdata[i];
                v = false;
            }
            else
            {
                v = true;
            }
        }

        GL.BindBuffer(BufferTarget.ArrayBuffer, dataBuffer);
        GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)(buffersize * sizeof(float)), bufferdata,
                      BufferUsageHint.StaticDraw);

        GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBuffer);
        GL.BufferData<uint>(BufferTarget.ElementArrayBuffer,
                      (IntPtr)(indices.Length * sizeof(uint)), indices, BufferUsageHint.StaticDraw);
    }

    public bool DrawBuffer(MeshData m, uint tex, uint indexBuffer, uint dataBuffer, int vertOffset, int normOffset, int texcoordOffset)
    {
        tex = tempTexture;
        GL.CullFace(CullFaceMode.Back);
        GL.PushClientAttrib(ClientAttribMask.ClientVertexArrayBit);
        GL.ClientActiveTexture(TextureUnit.Texture0);
        GL.BindTexture(TextureTarget.Texture2D, tex);
        GL.BindBuffer(BufferTarget.ArrayBuffer, dataBuffer);
        GL.NormalPointer(NormalPointerType.Float, 0, (IntPtr)(normOffset * sizeof(float)));
        GL.TexCoordPointer(2, TexCoordPointerType.Float, 0, (IntPtr)(texcoordOffset * sizeof(float)));
        GL.VertexPointer(3, VertexPointerType.Float, 0, (IntPtr)(vertOffset * sizeof(float)));
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBuffer);
        GL.DrawElements(BeginMode.Triangles, m.Tris.Length * 3, DrawElementsType.UnsignedInt, IntPtr.Zero);
        GL.PopClientAttrib();

        return true;
    }

```

EDIT 2: And here is my OBJ loader... There's quite a chance this is the problem.

```
public class ObjLoader
{
    public MeshData LoadStream(Stream stream)
    {
        StreamReader reader = new StreamReader(stream);
        List<Vector3> points = new List<Vector3>();
        List<Vector3> normals = new List<Vector3>();
        List<Vector2> texCoords = new List<Vector2>();
        List<Tri> tris = new List<Tri>();
        string line;
        char[] splitChars = { ' ' };
        while ((line = reader.ReadLine()) != null)
        {
            line = line.Trim(splitChars);
            line = line.Replace("  ", " ");

            string[] parameters = line.Split(splitChars);

            switch (parameters[0])
            {
                case "p":
                    // Point
                    break;

                case "v":
                    // Vertex
                    float x = float.Parse(parameters[1], CultureInfo.InvariantCulture.NumberFormat);
                    float y = float.Parse(parameters[2], CultureInfo.InvariantCulture.NumberFormat);
                    float z = float.Parse(parameters[3], CultureInfo.InvariantCulture.NumberFormat);
                    points.Add(new Vector3(x, y, z));
                    break;

                case "vt":
                    // TexCoord
                    float u = float.Parse(parameters[1], CultureInfo.InvariantCulture.NumberFormat);
                    float v = float.Parse(parameters[2], CultureInfo.InvariantCulture.NumberFormat);
                    texCoords.Add(new Vector2(u, v));
                    break;

                case "vn":
                    // Normal
                    float nx = float.Parse(parameters[1], CultureInfo.InvariantCulture.NumberFormat);
                    float ny = float.Parse(parameters[2], CultureInfo.InvariantCulture.NumberFormat);
                    float nz = float.Parse(parameters[3], CultureInfo.InvariantCulture.NumberFormat);
                    normals.Add(new Vector3(nx, ny, nz));
                    break;

                case "f":
                    // Face
                    tris.AddRange(parseFace(parameters));
                    break;
            }
        }

        Vector3[] p = points.ToArray();
        Vector2[] tc = texCoords.ToArray();
        Vector3[] n = normals.ToArray();
        Tri[] f = tris.ToArray();

        // If there are no specified texcoords or normals, we add a dummy one.
        // That way the Points will have something to refer to.
        if (tc.Length == 0)
        {
            tc = new Vector2[1];
            tc[0] = new Vector2(0, 0);
        }
        if (n.Length == 0)
        {
            n = new Vector3[1];
            n[0] = new Vector3(1, 0, 0);
        }

        return new MeshData(p, n, tc, f);
    }

    public MeshData LoadFile(string file)
    {
        // Silly me, using() closes the file automatically.
        using (FileStream s = File.Open(file, FileMode.Open))
        {
            return LoadStream(s);
        }
    }

    private static Tri[] parseFace(string[] indices)
    {
        Point[] p = new Point[indices.Length - 1];
        for (int i = 0; i < p.Length; i++)
        {
            p[i] = parsePoint(indices[i + 1]);
        }
        return Triangulate(p);
        //return new Face(p);
    }

    // Takes an array of points and returns an array of triangles.
    // The points form an arbitrary polygon.
    private static Tri[] Triangulate(Point[] ps)
    {
        List<Tri> ts = new List<Tri>();
        if (ps.Length < 3)
        {
            throw new Exception("Invalid shape!  Must have >2 points");
        }

        Point lastButOne = ps[1];
        Point lastButTwo = ps[0];
        for (int i = 2; i < ps.Length; i++)
        {
            Tri t = new Tri(lastButTwo, lastButOne, ps[i]);
            lastButOne = ps[i];
            lastButTwo = ps[i - 1];
            ts.Add(t);
        }
        return ts.ToArray();
    }

    private static Point parsePoint(string s)
    {
        s += "//";
        char[] splitChars = { '/' };
        string[] parameters = s.Split(splitChars);
        int vert, tex, norm;
        vert = tex = norm = 0;
        vert = int.Parse(parameters[0]) - 1;
        // Texcoords and normals are optional in .obj files
        if (parameters[1] != "")
        {
            tex = int.Parse(parameters[1]) - 1;
        }
        if (parameters[2] != "")
        {
            norm = int.Parse(parameters[2]) - 1;
        }
        return new Point(vert, norm, tex);
    }
}

```

# Answer
Checked the .obj loader, there was a flaw in it so that it didn't correctly load in quads and split them into triangles... It split quad ABCD into ABC and BCA instead of ABC and ACD

Sorry, thanks for all the attempted help though!

next time... I'm writing my own importer :P
> 2 votes

# Answer
Looking at your screen it seems that the model consists of quads. Now there are two possible problems you could have:

1. You render quads as 2 triangles, without properly paying attention to CW/CCW order of vertices. That is one triangle comes facing camera and second facing away.
2. Or you could be rendering triangles instead of quads. So instead of 4 vertices you render just 3 and 4th gets skipped.
> 1 votes

# Answer
It's possible that you're not being consistent with whether faces are drawn clockwise or counterclockwise, meaning that some of the faces are "backwards," that is, facing away from the camera. If you have backface culling enabled or any of various lighting setups, those faces will not be rendered or will appear black.
> 0 votes

# Answer
The most common problems are (1) that the triangles in question are interpreted as backward facing (2) that the triangles in question are thought to be invisible, but the blocking triangle is transparent, or nearly so. (3) that the corners of the triangle are all invisible, but the "body" of the triangle is not.

In general, there are many ways to lose triangles, especially if floating point numbers are used to represent coordinates.
> 0 votes

---
Tags: c#, opengl, 3d-meshes, opentk
---


# Question
Title: How do I make more bullets shoot in this game code?
I'm having trouble in the "Bullet.prototype.draw = function ()" section of this code below. I'm trying to fix it so that I can shoot more at a time instead of just one bullet like it is now. Thus, what could I add to my code below to make that work. I wrote a comment below in the section that I need help in (i.e. the "Bullet.prototype.draw = function" part), so that the part I need help in could be easier to find. Thanks.

```
      <title>HE</title>

<body style="background:#808080;">
        <br>

        <canvas id="canvasBg" width="800px" height="500px" style="display:block;background:#ffffff;margin:100px auto 0px;"></canvas>

        <canvas id="canvasMan" width="800px" height="500px" style="display:block;margin:-500px auto 0px;"></canvas>

        <canvas id="canvasBullet" width="800px" height="500px" style="display:block;margin:-500px auto 0px;"></canvas>

<script>

var isPlaying = false;
var requestAnimframe = window.requestAnimationFrame ||
                                             window.webkitRequestAnimationFrame ||
                                             window.mozRequestAnimationFrame ||
                                             window.msRequestAnimationFrame ||
                                             window.oRequestAnimationFrame;

var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');

var canvasMan = document.getElementById('canvasMan');
var ctxMan = canvasMan.getContext('2d');
var Man1;  Man1 = new Man();

var canvasBullet = document.getElementById('canvasBullet');
var ctxBullet = canvasBullet.getContext('2d');

//I think is might be where the error might be (according to when I ran this as an "hta" file).
//but I'm not sure. I haven't really seen anything written in JavaScript like this yet (since
//I'm new to the language too. So, I don't know if this is an error or not. But, it might be
    //this "var bullets = new List<Bullet>();" part.

var bullets = new List<Bullet>();

var imgSprite = new Image();
imgSprite.src = 'SpritesI.png';
imgSprite.addEventListener('load',init,false);

function init() {

        drawBg();
        startLoop();
        document.addEventListener('keydown',checkKeyDown,false);
        document.addEventListener('keyup',checkKeyUp,false);
}

function startLoop(){
        isPlaying = true;
        loop();
}

function stopLoop(){
        isPlaying = false;

}

function loop() {
         if (isPlaying === true){
                     Man1.draw();

                     //specifically the "bullets.toArray();" part might be undefined but I
                     //don't know for sure.

                     var tempBullets = bullets.toArray();
                     for (var i = 0; i < tempBullets.length; i++)
                     {
                        tempBullets[i].draw();
                     }
                     requestAnimframe(loop);
         }

}

function drawBg() {
        var srcX = 0;
        var srcY = 0;
        var drawX = 0;
        var drawY = 0;
        ctxBg.drawImage(imgSprite,srcX,srcY,800,500,drawX,drawY,800,500);
}

function clearctxBg() {
         ctxBg.clearRect(0,0,800,500);
}

function Man() {
        this.srcX = 10;
        this.srcY = 540;
        this.width = 40;
        this.height = 115;
        this.drawX = 100;
        this.drawY = 260;
        this.noseX = this.drawX + 30;
        this.noseY = this.drawY + 560;
        this.speed = 10;
        this.actualFrame = 1;
        this.speed = 2;
        this.isUpKey = false;
        this.isRightKey = false;
        this.isDownKey = false;
        this.isLeftKey = false;
        this.isSpacebar = false;
        this.isRight = false;
        this.isLeft = false;
}

Man.prototype.draw = function () {
        clearCtxMan();
        this.updateCoors();
        this.checkDirection();
        this.noseX = this.drawX + 100;
        this.noseY = this.drawY + 30;

        ctxMan.drawImage(imgSprite,this.srcX,this.srcY+this.height*this.actualFrame,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
        }; //careful

Man.prototype.updateCoors = function(){

        this.leftX = this.drawX;
        this.rightX = this.drawX + this.width;
        this.topY = this.drawY;
        this.bottomY = this.drawY + this.height;

}

Man.prototype.checkDirection = function () {

        if (this.isUpKey && this.topY > 240){
                this.drawY -= this.speed;

        }
        if (this.isRightKey && this.rightX < 800) {
                this.drawX += this.speed;
                this.isRight = true;
                this.isLeft = false;

        }
        if (this.isDownKey && this.bottomY < 500){
                this.drawY += this.speed;

        }
        if (this.isLeftKey && this.leftX > 0) {
                this.drawX -= this.speed;
                this.isRight = false;
                this.isLeft = true;

        }

        if (this.isRightKey && this.rightX < 800) {

                 if (this.actualFrame > 0) {
                         this.actualFrame = 0;
                    }
        else {
            this.actualFrame++;
        }
}

        if (this.isLeftKey) {

                 if (this.actualFrame > 2) {
                         this.actualFrame = 2;
                    }
        else {
            this.actualFrame++;
        }
}

};

function checkKeyDown(e) {

        var keyID = e.keyCode || e.which;
        if (keyID === 38) { //up arrow or W key
                Man1.isUpKey = true;
                e.preventDefault();
        }
        if (keyID === 39 ) { //right arrow or D key
                Man1.isRightKey = true;
                e.preventDefault();
        }
        if (keyID === 40 ) { //down arrow or S key
                Man1.isDownKey = true;
                e.preventDefault();
        }
        if (keyID === 37 ) { //left arrow or A key
                Man1.isLeftKey = true;
                e.preventDefault();
        }

        if (keyID === 32  ) { //spacebar
                Man1.isSpacebar = true;
                var b = new Bullet();
                b.isShootingRight = man.isRight;
                b.isShottingLeft = man.isLeft;
                bullets.add(b);
                e.preventDefault();
        }

}

function checkKeyUp(e) {
        var keyID = e.keyCode || e.which;
        if (keyID === 38 ) { //up arrow or W key
                Man1.isUpKey = false;
                e.preventDefault();
        }
        if (keyID === 39 ) { //right arrow or D key
                Man1.isRightKey = false;

                e.preventDefault();
        }
        if (keyID === 40 ) { //down arrow or S key
                Man1.isDownKey = false;
                e.preventDefault();
        }
        if (keyID === 37 ) { //left arrow or A key
                Man1.isLeftKey = false;

                e.preventDefault();
        }

        if (keyID === 32 ) { //Spacebar

                Man1.isSpacebar = false;
                e.preventDefault();
        }

}

function clearCtxMan() {
         ctxMan.clearRect(0,0,800,500);

}

function Bullet() {
        this.srcX = 430;
        this.srcY = 545;
        this.width = 20;
        this.height = 25;
        this.drawX = Man1.drawX;
        this.drawY = Man1.drawY +50;
        this.isSpacebar = false;
        this.isRightKey = false;
        this.isLeftKey = false;
        this.isRight = false;
        this.isLeft = false;
        this.isShootingRight = false;
        this.isShootingLeft = false;
}

//Here is where I'm having trouble. Now, it only shoots 1 bullet, but I want to shoot more
//bullets at a time. Thus, what do I add to this code to do that?

Bullet.prototype.draw = function () {

        clearCtxBullet();

        ctxBullet.drawImage(imgSprite,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height); // I grabbed this line out from below

            if (this.isShootingRight){

                this.drawX = this.drawX + 2;

            }

            if (this.isShootingLeft){

                this.drawX = this.drawX - 2;

            }

            if (this.drawX > 800){

                bullets.remove(this);

            }

            if (this.drawX < -20){

                bullets.remove(this);

            }

};

    function clearCtxBullet() {
             ctxBullet.clearRect(0,0,800,500);

    }

    </script>

    <style>
    .top{
            position: absolute;
            top: 4px;
            left: 10px;
            color:black;
    }

    .top2{
            position: absolute;
            top: 60px;
            left: 10px;
            color:black;
    }

    </style>

        <div class="top">
                        <p><font face="arial" color="black" size="4"><b>Henry's Game</b><font/><p/>
                    <p><font face="arial" color="black" size="3">

                                Below is a game featuring me. The game won't work in Internet Explorer (I wish it did).
                                Firefox might take a little while to load but it'll still work. I'm not done with it yet.
                                The game is not going anywhere now,
                <font/><p/>

        </div>

                <div class="top2">

                    <p><font face="arial" color="black" size="3">
                                         but it's something else to play around with until I get done with it.
                <font/><p/>

        </div>

```

# Answer
> 2 votes
You have code here:

```
    if (Bullet1.isShootingLeft || Bullet1.isShootingRight) {

            Man1.isSpacebar = false;
    }

```

which disables a second shot from firing, as your game so far only works with one bullet (without this code, the 'old' bullet would disappear and the 'new' bullet would appear). Instead, try implementing an array to hold new bullets, instead of limiting yourself to only one.

(Though you may want to implement a cooldown on firing, otherwise space could be held for an extremely rapid fire)

EDIT: Quite a few changes to the code had to be made... As i havn't used javascript or HTML5 before, i couldn't really test all of this, though it should be fine. I commented out lines of code instead of deleting them, and tried to point out where i modified stuff.

```
    <title>HE</title>

<body style="background:#808080;">
        <br>

        <canvas id="canvasBg" width="800px" height="500px" style="display:block;background:#ffffff;margin:100px auto 0px;"></canvas>

        <canvas id="canvasMan" width="800px" height="500px" style="display:block;margin:-500px auto 0px;"></canvas>

        <canvas id="canvasBullet" width="800px" height="500px" style="display:block;margin:-500px auto 0px;"></canvas>

<script>

var isPlaying = false;
var requestAnimframe = window.requestAnimationFrame ||
                                             window.webkitRequestAnimationFrame ||
                                             window.mozRequestAnimationFrame ||
                                             window.msRequestAnimationFrame ||
                                             window.oRequestAnimationFrame;

var canvasBg = document.getElementById('canvasBg');
var ctxBg = canvasBg.getContext('2d');

var canvasMan = document.getElementById('canvasMan');
var ctxMan = canvasMan.getContext('2d');
var Man1;  Man1 = new Man();

var canvasBullet = document.getElementById('canvasBullet');
var ctxBullet = canvasBullet.getContext('2d');
//var Bullet1; Bullet1 = new Bullet();
var bullets = new List<Bullet>(); //here we create an array of bullets instead of a single one

var imgSprite = new Image();
imgSprite.src = 'SpritesI.png';
imgSprite.addEventListener('load',init,false);

function init() {

        drawBg();
        startLoop();
        document.addEventListener('keydown',checkKeyDown,false);
        document.addEventListener('keyup',checkKeyUp,false);
}

function startLoop(){
        isPlaying = true;
        loop();
}

function stopLoop(){
        isPlaying = false;

}

function loop() {
         if (isPlaying === true){
                     Man1.draw();
                     //Bullet1.draw();
                     var tempBullets = bullets.toArray(); //creating a temporary array to store the bullets means that we can freely modify the 'bullets' list even during the drawing of bullets, without any issues.
                     for (var i = 0; i < tempBullets.length; i++)
                     {
                        tempBullets[i].draw(); //Here we are looping through all the bullets and drawing each of them
                     }
                     requestAnimframe(loop);
         }

}

function drawBg() {
        var srcX = 0;
        var srcY = 0;
        var drawX = 0;
        var drawY = 0;
        ctxBg.drawImage(imgSprite,srcX,srcY,800,500,drawX,drawY,800,500);
}

function clearctxBg() {
         ctxBg.clearRect(0,0,800,500);
}

function Man() {
        this.srcX = 10;
        this.srcY = 540;
        this.width = 40;
        this.height = 115;
        this.drawX = 100;
        this.drawY = 260;
        this.noseX = this.drawX + 30;
        this.noseY = this.drawY + 560;
        this.speed = 10;
        this.actualFrame = 1;
        this.speed = 2;
        this.isUpKey = false;
        this.isRightKey = false;
        this.isDownKey = false;
        this.isLeftKey = false;
        this.isSpacebar = false;
        this.isRight = false;
        this.isLeft = false;
}

Man.prototype.draw = function () {
        clearCtxMan();
        this.updateCoors();
        this.checkDirection();
        this.noseX = this.drawX + 100;
        this.noseY = this.drawY + 30;

        ctxMan.drawImage(imgSprite,this.srcX,this.srcY+this.height*this.actualFrame,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
        }; //careful

Man.prototype.updateCoors = function(){

        this.leftX = this.drawX;
        this.rightX = this.drawX + this.width;
        this.topY = this.drawY;
        this.bottomY = this.drawY + this.height;

}

Man.prototype.checkDirection = function ()
{
        if (this.isUpKey && this.topY > 240){
                this.drawY -= this.speed;

            //if (!Bullet1.isShootingRight && !Bullet1.isShootingLeft){      DON'T NEED THESE
            //    Bullet1.drawY -= this.speed;
            //}
        }
        if (this.isRightKey && this.rightX < 800) {
                this.drawX += this.speed;
                this.isRight = true;
                this.isLeft = false;

            //if (!Bullet1.isShootingRight && !Bullet1.isShootingLeft){      DON'T NEED THESE
            //    Bullet1.drawX += this.speed;

            //}
        }
        if (this.isDownKey && this.bottomY < 500){
                this.drawY += this.speed;

            //if (!Bullet1.isShootingRight && !Bullet1.isShootingLeft){      DON'T NEED THESE
            //    Bullet1.drawY += this.speed;

            //}

        }
        if (this.isLeftKey && this.leftX > 0) {
                this.drawX -= this.speed;
                this.isRight = false;
                this.isLeft = true;
            //if (!Bullet1.isShootingRight && !Bullet1.isShootingLeft){      DON'T NEED THESE
            //    Bullet1.drawX -= this.speed;
            //}
        }

        if (this.isRightKey && this.rightX < 800) {

                 if (this.actualFrame > 0) {
                         this.actualFrame = 0;
                    }
        else {
            this.actualFrame++;
        }
}

        if (this.isLeftKey) {

                 if (this.actualFrame > 2) {
                         this.actualFrame = 2;
                    }
        else {
            this.actualFrame++;
        }
}

};

function checkKeyDown(e) {

        var keyID = e.keyCode || e.which;
        if (keyID === 38) { //up arrow or W key
                Man1.isUpKey = true;
                e.preventDefault();
        }
        if (keyID === 39 ) { //right arrow or D key
                Man1.isRightKey = true;
                e.preventDefault();
        }
        if (keyID === 40 ) { //down arrow or S key
                Man1.isDownKey = true;
                e.preventDefault();
        }
        if (keyID === 37 ) { //left arrow or A key
                Man1.isLeftKey = true;
                e.preventDefault();
        }

        if (keyID === 32  ) { //spacebar
                Man1.isSpacebar = true;
                var b = new Bullet();
                b.isShootingRight = man.isRight;
                b.isShottingLeft = man.isLeft;                    //I've implemented bullet firing here.
                bullets.add(b);
                e.preventDefault();
        }

        //if (Bullet1.isShootingLeft || Bullet1.isShootingRight) {      DON'T NEED THIS
        //
        //        Man1.isSpacebar = false;
        //}
}

function checkKeyUp(e) {
        var keyID = e.keyCode || e.which;
        if (keyID === 38 ) { //up arrow or W key
                Man1.isUpKey = false;
                e.preventDefault();
        }
        if (keyID === 39 ) { //right arrow or D key
                Man1.isRightKey = false;

                e.preventDefault();
        }
        if (keyID === 40 ) { //down arrow or S key
                Man1.isDownKey = false;
                e.preventDefault();
        }
        if (keyID === 37 ) { //left arrow or A key
                Man1.isLeftKey = false;

                e.preventDefault();
        }

        if (keyID === 32 ) { //Spacebar

                Man1.isSpacebar = false;
                e.preventDefault();
        }

}

function clearCtxMan() {
         ctxMan.clearRect(0,0,800,500);

}

function Bullet() {
        this.srcX = 430;
        this.srcY = 545;
        this.width = 20;
        this.height = 25;
        this.drawX = Man1.drawX;
        this.drawY = Man1.drawY +50;
        this.isSpacebar = false;
        this.isRightKey = false;
        this.isLeftKey = false;
        this.isRight = false;
        this.isLeft = false;
        this.isShootingRight = false;
        this.isShootingLeft = false;
}

//Here is where I'm having trouble. Now, it only shoots 1 bullet, but I want to shoot more
//bullets at a time. Thus, what do I add to this code to do that?

Bullet.prototype.draw = function () {

        clearCtxBullet();

        ctxBullet.drawImage(imgSprite,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height); // I grabbed this line out from below

        /* ALL OF THIS CAN GO!!!
    for(var i = 0; i < 1; i++) {
        if (this.isShootingRight || this.isShootingLeft){
        ctxBullet.drawImage(imgSprite,this.srcX,this.srcY,this.width,this.height,this.drawX,this.drawY,this.width,this.height);
        }

            if (Man1.isRight && Man1.isSpacebar){

                this.isShootingRight = true;

            }

            if (Man1.isLeft && Man1.isSpacebar){

                this.isShootingLeft = true;

            }*/

            if (this.isShootingRight){

                this.drawX = this.drawX + 2;

            }

            if (this.isShootingLeft){

                this.drawX = this.drawX - 2;

            }

            if (this.drawX > 800){

                bullets.remove(this);
                //this.isShootingRight = false;        THESE LINES ARE IRRELEVANT, THE BULLET IS BEING DELETED
                //this.drawX = Man1.drawX;
                //this.drawY = Man1.drawY + 50;

            }

            if (this.drawX < -20){

                bullets.remove(this);
                //this.isShootingLeft = false;        THESE LINES ARE IRRELEVANT, THE BULLET IS BEING DELETED
                //this.drawX = Man1.drawX;
                //this.drawY = Man1.drawY + 50;

            }

        }

};

    function clearCtxBullet() {
             ctxBullet.clearRect(0,0,800,500);

    }

    </script>

    <style>
    .top{
            position: absolute;
            top: 4px;
            left: 10px;
            color:black;
    }

    .top2{
            position: absolute;
            top: 60px;
            left: 10px;
            color:black;
    }

    </style>

        <div class="top">
                        <p><font face="arial" color="black" size="4"><b>Henry's Game</b><font/><p/>
                    <p><font face="arial" color="black" size="3">

                                Below is a game featuring me. The game won't work in Internet Explorer (I wish it did).
                                Firefox might take a little while to load but it'll still work. I'm not done with it yet.
                                The game is not going anywhere now,
                <font/><p/>

        </div>

                <div class="top2">

                    <p><font face="arial" color="black" size="3">
                                         but it's something else to play around with until I get done with it.
                <font/><p/>

        </div>

```

---
Tags: javascript, html5, browser-based-games
---


title: Collision detections too fast?

text:
# Question
Title: Collision detections too fast?
I'm creating a simple asteroids game and I have three lists with: big asteroids, small asteroids and missiles. When the player hits a big asteroid two small asteroids are created. But The problem is that for the most of the time, the two small asteroids never get time to show up! It seems like the missile hits them too, despite that I remove the missile from the list, before the small asteroids are created. The code below is from my object manager.

What is wrong and how can I improve my code to avoid this?

```
 // Check if missile hit big asteroid
    public void CollisionControlMissileHitAsteroidBig(ContentManager content)
    {
        for (int i = 0; i < missilesList.Count(); i++)
        {
            for (int ii = 0; ii < asteroidsBigList.Count(); ii++)
            {
                if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsBigList.ElementAt(ii).Bounds()))
                {
                    missilesList.RemoveAt(i);
                    for(int x = 0; x < 2; x++)
                        AddNewSmallAsteroidToList(new AsteroidSmall(content, asteroidsBigList.ElementAt(ii).Position));

                    asteroidsBigList.RemoveAt(ii);
                    i--;
                    ii--;
                }
            }
        }
    }

    // Check if missile hit small asteroid
    public void CollisionControlMissileHitAsteroidSmall()
    {
        for (int i = 0; i < missilesList.Count(); i++)
        {
            for (int ii = 0; ii < asteroidsSmallList.Count(); ii++)
            {
                if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsSmallList.ElementAt(ii).Bounds()))
                {
                    missilesList.RemoveAt(i);
                    asteroidsSmallList.RemoveAt(ii);
                    i--;
                    ii--;
                }
            }
        }
    }

```

EDIT:

I'm not sure I have done right? There are some problems, the big asteroids is still on the screen and then I guess the missile is still there to, because when two new small asteroids are created, most of the time there is only one, which I think is because it collide with the old missile? That's why I removed the missile from the list before I created the new small asteroids. More help is appreciated!

```
    public void CollisionControlMissileHitAsteroidBig(ContentManager content)
    {
        for (int i = 0; i < missilesList.Count(); i++)
        {
            for (int ii = 0; ii < asteroidsBigList.Count(); ii++)
            {
                if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsBigList.ElementAt(ii).Bounds()))
                {
                    //missilesList.RemoveAt(i);
                    for(int x = 0; x < 2; x++)
                        AddNewSmallAsteroidToList(new AsteroidSmall(content, asteroidsBigList.ElementAt(ii).Position));

                    asteroidsBigListRemove.Add(asteroidsBigList.ElementAt(ii));
                    missilesListRemove.Add(missilesList.ElementAt(i));
                }
            }
        }
        asteroidsBigListRemove.Clear();
        missilesListRemove.Clear();
    }

```

# Answer
Are you accidentally firing more than one missile at a time? Is it possible that your code creates two missiles at the same point in time and it's the second one that's hitting the asteroids?

Edit:

To solve the problem of removing asteroids and missiles, you create 'to remove' lists. Using your code:

```
public void CollisionControlMissileHitAsteroidBig(ContentManager content)
{
    for (int i = 0; i < missilesList.Count(); i++)
    {
        for (int ii = 0; ii < asteroidsBigList.Count(); ii++)
        {
            if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsBigList.ElementAt(ii).Bounds()))
            {
                //missilesList.RemoveAt(i);
                for(int x = 0; x < 2; x++)
                    AddNewSmallAsteroidToList(new AsteroidSmall(content, asteroidsBigList.ElementAt(ii).Position));

                asteroidsBigListRemove.Add(asteroidsBigList.ElementAt(ii));
                missilesListRemove.Add(missilesList.ElementAt(i));
            }
        }
    }

    foreach( var asteroid in asteroidsBigListRemove )
    {
        asteroidsBigList.Remove( asteroid );
    }
    asteroidsBigListRemove.Clear();

    foreach( var missile in missilesListRemove)
    {
        asteroidsBigList.Remove( asteroid );
    }
    missilesListRemove.Clear();
}

```

This means that you don't remove items from the list while you're still iterating over them. If you don't want to do this, the second option is to check items from the back first:

```
for (int i = missilesList.Count() - 1; i >= 0; i--)
{
    for (int ii = asteroidsBigList.Count() - 1; ii >= 0; ii--)
    {
        if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsBigList.ElementAt(ii).Bounds()))
        {
            missilesList.RemoveAt(i);

```

and so on.
> 1 votes

---
Tags: xna
---


# Question
Title: OpenGL behaviour depending on the graphics card?
This is something that never happened to me before. I have an OpenGL code that uses GLSL shaders to texture a 3D model. The code involves a lot of GPU texture processing, blending, etc...

I wanted to check how the performance of my code improves using a faster graphics card (both new and old are NVIDIA, using always the NVIDIA development drivers). But now I have found that once I run the code using the new graphics card, it behaves completely different (the final render looks wrong), probably because some blending effect is not performed correctly.

I haven't really look into what has changed, but I am guessing that some OpenGL states are, by default, set different. Is this possible? Have you ever found different OpenGL/GLSL behaviour using different graphics cards? Any "fast" solution? (So far I've thought of plugging back the old one, push all OpenGL default states, and compare with the ones I initially get using the new card..)

**Edit #1**: The graphics cards are NVIDIA Quadro GX7300 (in which my code works OK) and NVIDIA GeForce GTX 560 Ti (in which the results changes / fails)

**Edit #2** I have commented out a lot of my code, and apparently the strange behaviour has nothing to do with texture handling. A simple chessboard-like floor looks differents. The diagonal white lines did not appear using the *old* NVIDIA Quadro GX7300. Any guess what OpenGL related thing could be causing this?

Figure 1

---

**Edit #3** I have now fixed the issue commented on the previous edit, regarding the weird unwanted diagonal thin whit lines. As I commented below, I had to remove the `glEnable(GL_POLYGON_SMOOTH);`, which was affecting the NVIDIA GeForce GTX 560 for whatever reason (probably due to reasons explained by mh01 in his answer.

However, I am still facing a "texture blending" problem when using the NVIDIA GeForce GTX 560. I have a 3D model that is being textured using a shader that blends 8 different images to compute the right texture, depending on where the camera is at that particular moment. The resulting texture is then a combination of different images, and ideally they were blended nicely, using a set of blending weights computed each time the camera moves. The blending weights are still well computed, but the resulting texture is wrong. I am guessing that the GL\_BLEND function is somehow behaving different, but I have checked it in both graphics cards and it is actually the same one. I have no idea what else can be involved in getting this wrong result:

As you can imagine, the black line is where two original textures are being blended in order to get a seamless texture. If I use the exact some code and a NVIDIA Quadro GX730, the shader works as expected. However, when I use the NVIDIA GeForce GTX 560, the texture blending goes wrong. Any guess?

**This** is the GLSL shader I am using.

# Answer
> 1 votes
I have finally figured out what was going on. The undesired thin white diagonal lines on the floor appeared because I was using `glEnable(GL_POLYGON_SMOOTH);`, which is apparently a **bad practice**.

The problem regarding the unexpected result when blending textures was caused due to a strange behaviour of a `discard;` operation in the shader. More details about it in **this other question**.

# Answer
> 4 votes
If two different drivers have different default states then one of them is not in conformance with the OpenGL specification, although on the other hand there are no conformance tests for more recent GL\_VERSIONs, so things are a bit Wild West at the moment.

What you're actually doing here is comparing the output from a professional/workstation class gfx card with the output from a consumer/desktop class card, and what you're seeing is most likely the expected result of a performance/quality tradeoff.

OpenGL allows leeway in the spec in many cases, and the Quadro will be erring on the side of quality so that the latest CAD or modelling software is more accurate, whereas the GeForce will be erring on the side of performance so that the latest game will run faster.

So the white lines will be as a result of lower floating point precision being used by the GeForce. NVIDIA has traditionally run at one of two internal precisions - 16 bit or 32-bit - and will occasionally take the lower precision path even in cases where it shouldn't.

You may be able to work around this by pushing the various available sliders towards "quality" in your NVIDIA control panel, or - if you're using shaders - you may be able to get a better result by explicitly specifying higher precision types.

It may also be the case that you're working on too large a scale, and that taking things down to 10% or 1% of their size (and adjusting everything else to match) is the solution you need.

---
Tags: opengl, graphics, nvidia
---


# Question
Title: What data structure should I use for a 3D platformer game?
I am developing a platformer game with the XNA framework, like *"Metroid"*, but in 3D. I have to draw models, and I have the question of the title. I read many posts, and I know that the main data structures for draw polygons are octrees, quadtrees, BSP and Portals; but I read and read, and I don't know what is best.

What data structure should I use for a 3D platformer game?

# Answer
> 4 votes
The first thing you should do is get your game working. You can always change the data structure you use to store polygon data later on. It might be a lot of work, but you can still do it. The most important thing is to get your game working as soon as possible, even if it is inefficient.

This means getting a character on the screen, allowing the player to control them, adding some platforms to jump on and having some basic goal to complete. Worry about efficient rendering later - you might not need to worry at any point.

Once your game is working a bit you will have a clearer idea of what you want to do and this will help you decide whether a BSP tree or an Octree (or quad tree if you only need 2d partitioning) is the most appropriate for your game. Also keep in mind that you can use both of these storage structures by using them in different situations or merging them together.

It is my preference to use an octree to spatially partition the separate objects in my world. So that's where the tables, cars, characters, guns etc go. I would class these objects as the dynamic ones (although I won't necessarily allow them to move I will allow that possibility in my data structure). So in this situation I'm not splitting up the polygon meshes for each object, I'm just finding a box to put the whole thing in. This is useful for collision detection and also for just getting rid of things that are definitely outside of the view frustum. I do it this way because it's easier to rebuild an octree on the fly that is built in this way, so when things move, I just work out where in the tree they belong now.

The static mesh that makes up the world, if you use one, won't sit well in the octree. It's gonna be big. This will be one huge mesh that defines all the buildings and all the roads and rooms. In this situation I would either put it in a BSP tree or I would carve it up so each part fits in an octree leaf.

So in conclusion, what I think is you shouldn't worry about spatially partitioning polygon meshes at this stage, just get some basic stuff working and MAYBE give thought to putting those whole objects in an octree.

---
Tags: xna, 3d, data-structure
---


# Question
Title: What is the MTV (Minimum Translation Vector) in SAT (Seperation of axis)?
What is the MTV (Minimum Translation Vector) in SAT (Seperation of axis)? and how can i use it?

Im trying to create my first game, where a ball can hit a a static brick (rectangle). Now if a ball collides with a brick, then i need to figure out which side the ball collided with so i can tell the ball which direction it should bounce off to.

For example, if a ball is heading nortwest and hitting the brick on its right side, then it should bounce in a northeast direction.

however if the ball hit's the bottom side of the brick, then the ball should be heading southwest.

So can the MTV be used in this situation? can MTV tell me which side of a rectangle the ball has impacted?

Please note i have implemented SAT in my game, and the **collision detection** works fine, my question now is, can i use MTV to actually handle a **collision response**?

Any help is appreciated.

# Answer
> 7 votes
The minimum translation vector is the shortest distance that the colliding object can be moved in order to no longer be colliding with the collidee.

Most of the time, this will be the normal of the face which first impacted. When this is the case, you can use this to handle collision response by (in the case of perfectly elastic collisions with an immobile brick) reflecting the velocity of the ball with respect to the normal of the MTV, and adding twice the MTV to the position of the ball.

There are cases where the minimum translation vector isn't the normal of the face impacted: planing, and when the translation of the ball is approaching the size of the brick. These may occur sufficiently rarely that you don't need special-case handling for them, depending on your timestep, velocities involved and object sizes.

edit: For example, given your diagram, you're going to get tunnelling effects if the ball ends up penetrating the brick more than halfway - at that point, it'll end up getting pushed out of the other side of the brick.

Further edit: Just realised, you can solve both planing and tunnelling by calculating the dot product of the various translation vectors with the relative velocity of the objects. Any translation vector which has a positive dot product with the velocity can't be a collision face, as the object is moving away, not towards, that face. Of those which give a negative dot product, it's the one which gives the smallest value which will be the first side impacted.

---
Tags: collision-detection, physics, game-mechanics, separating-axis-theorem
---


# Question
Title: Handling multiple AI updates for simultaneous movement
How would I go about having multiple AI on the screen all at once all calculating separate movements without too much lag and within sane working memory. Before I have had many on the screen by putting objects of them in an array and looping through calling the move method, however this isn't the fastest method of handling them. Is it okay to use threads when you have say 200 AI at the same time on the screen? Can anyone help me work out the best structure for having multiple AI (which all move)?

# Answer
It is highly unlikely that you will have so many enemies, that calculating their movements slows the game down.

In a game with a large number of enemies (thousands), most will be off the screen, hence presumed to be (largely) dormant, at any given time. This reduces the amount of effort to do them to very little (perhaps zero).

Using threads is going to hugely increase the complexity of your code, introduce many bugs, and may not actually increase performance at all (for example, if you have more threads than cores). But worst of all, it makes the game nondeterministic, which is never a good thing. You want to be able to replay the game with the same inputs (for example, many mutliplayer network games depend on this).
> 2 votes

# Answer
Pluses: Java does fine with hundreds of threads used this way. You get to use all your cores. And while you only have a few cores, many of your threads will be blocking and unable to run, so having a few unblocked ones ready keeps things moving. (Though most of your threads should be sleeping most of the time. You want a bit of spare CPU usage to the OS can respond rapidly to things outside your game (internet connection, for instance) and even things *in* your game besides AI.)

Minus: This kind of multithreaded programming is a monster. If you want to do this, study it well. Write your code carefully, because the bugs will not repeat themselves when you want them to and so are extremely difficult to track down. And writing safe code is not enough; you have to minimize blocking. If you have 8 cores, but all the threads are trying to get one lock, you'll have only 12.5% CPU usage. Worse, the player is apt to notice the slowdown. Basically you need to synchronize everything and synchronize nothing at the same time.
> 0 votes

---
Tags: java, ai
---


# Question
Title: GLSL if-else statement unexpected behaviour
This question is related to this **other one** I asked a few days ago. Because I have finally get to the bottom of the issue, I have rather preferred to open a new question with a more detailed information of what is going on.

I basically have a GLSL fragment shader that is giving me unexpected results, depending on whether it is executed using a NVIDIA Quadro, in which works as expected, or a NVIDIA GeForce, in which does something weird. After a detailed evaluation of what is going on, I have realised that the issue is around the `discard` operation when using the NVIDIA GeForce 560 Ti.

Can someone explain me why these the two codes behave different in a NVIDIA GeForce 560 Ti, but exactly the sume in a NVIDIA Quadro?

---

**EDIT #1**: After some deeper evaluation I can conclude that the `discard` statement it is not the problem. The problem occurs when running the `sumw if-else` statement at the end of the shader, once `colour` has been computed. For whatever reason, if I run the `sumw if-else` at the end the shader, the final render is not the expected one. On the other hand, if the `sumw if-else` statement is in the middle of the shader, right before running the code that computes the final value of `colour`, the shaders works as expected.

---

**VERSION #1** (works *wrong* in GeForce 560, basically doesn't discard the pixel)

```
i = 0;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[0],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 1;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[1],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 2;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[2],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 3;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[3],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 4;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[4],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 5;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[5],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 6;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[6],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 7;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[7],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }

if (sumw<=0.0)           // Evaluating this here makes that the shader behave wrong
{
    discard;
}
else
{
    gl_FragColor = vec4(colour, 1);
}

```

**VERSION #2** (works the same in both graphics card)

```
if(sumw<=0.0)            // Evaluating this here makes that the shader perform as expected
{
    discard;
}
else
{
i = 0;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[0],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 1;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[1],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 2;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[2],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 3;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[3],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 4;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[4],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 5;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[5],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 6;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[6],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
i = 7;
    if (i<numCameras && sumw>0.0)
    {
        vec4 texCoord = gl_TextureMatrix[i] * p;
        vec4 texColour = texture2DProj(texSampler[7],texCoord);
        float w = camw[i] / sumw;
        if (w>1.0) w = 1.0;
        colour += texColour.rgb*w;
    }
}
gl_FragColor = vec4(colour, 1);

```

If I am not mistaken, the only difference between the two codes is that the first version does not discard the pixel until the rest of operation have been compleated, whereas the second version discards the pixel if necessary, otherwise carries on with the rest of the computation.

However, they should behave the same, because the computation of `colour` **dos not affect the condition** to discard or not, because `sumw` doesn't change its value.

Any explanation to this?

# Answer
You are inducing undefined behavior.

The behavior of the texture functions that need implicit derivatives is *undefined* if the texture coordinate provided to it is not within uniform flow (ie: in a conditional branch or uses the results of such a conditional branch).

The texture coordinates you use, not to mention the samplers, are all based on the results of conditional branching logic. Therefore, the results of accessing the texture with them are undefined.

To resolve this, you must either do all of your texture accesses *before* deciding which results to use, or you must get gradients for all of your texture coordinates and then use the texture "Grad" function(s). Or you can use a texture "Lod" function for a specific Lod of the image (but you won't get mipmaping, for obvious reasons).
> 13 votes

---
Tags: opengl, shaders, glsl, nvidia
---


# Question
Title: What is the "pricing standard" on Windows Phone?
On iOS, I find it is more usual to see light versions of a game for free (with ads and less features) and a full version for a cost and all the features.

On Android, I see more games that have both a full version for free and one for a cost. One with ads and the other without.

**On WP7, how are games usually priced?**

Talking about a rather simple and small game here and I'm trying to figure out how to price it. I'm thinking of going for a 1$ app with full features no ads, but I'm not so sure. Would it be more profitable to put it for free with ads instead? How do other developers usually make that choice?

# Answer
If your game has little or no replay value (which is not a bad thing, but it does change the way that I think you should price your wares) **then you should charge your fee upfront. Get your money and be done.** It will reduce the number downloads of your game gets, but at least you will make some money. Since you anticipate 30-60 minutes of total playtime for your game showing ads wont make you very much money. **Ads supported games/apps work best when there is a strong reason to come back** and play or use the app again (and thus see more ads).

Based on your comments, question, **I think that $.99 is the most you should charge for a game that plays through in 30-60 minutes**. Most short games are in that price point. I think that Angry Birds (mentioned in another answer) is the exception likely due to its low/free cost on other platforms. **Most Xbox Live games on WP marketplace are in the $2.99 range, but most of these provide at least a few hours of gameplay** before being boring, and IMHO many provide tens of hours of play.
> 2 votes

# Answer
From the various reports, tweets, articles I've read it still seems that unless you're an Xbox Live game the best way to earn money is via ads.

For example and the most successful indie dev so far Elbert Perez \*(based on 12 month old data). He's recently tweeted that his ad revenue for the past two months (as at July 2012) has been abysmal though.

Our first non ad supported game made $204 in the first year as an XNA game. Just enough to cover the App Hub costs for two years.

Here's another example of a profitable WP7 dev in Australia.

The stats bear out using trial \> full game increases downloads by 70x and conversion by 7x but if your game is only 30 mins long in total with little replay value, you'll want to be careful not to give too much away in your trial.
> 3 votes

# Answer
DISCLAIMER: This answer is based on some spontaneous research, but I hope it sets you off in the right direction.

A good start would be to do a bit of market research on the Windows Marketplace website. http://www.windowsphone.com/en-GB/games (British localisation. You can change the localisation at the top-right of the website).

From my initial impression looking through myself, most developers seem to go straight in with pay-for full-version games. There are a few cases of demo or free versions being released, but none of which are under the XBox Live tag. ( http://www.windowsphone.com/en-GB/search?q=demo ).

In the XBoxLive submission tutorial, there is mention of, "Remember that the .ccgame file must come from an Xbox 360 project in XNA Game Studio, and must be a complete game with no errors." ( http://create.msdn.com/en-US/home/about/how\_it\_works\_submit ). This could also mean that developers cannot submit demo versions of their games to the XBL section of the marketplace, as ordinarily you would see demo versions floating around (to not see an Angry Birds demo is a surprise to me).

As for the pricing itself, it seems to range anywhere between 50 pence and £8-£10. The price seems to be entirely dependant on content and/or the brand which is being sold. Based on this, for a "simple and small" game, $1 seems reasonable enough. Games like Angry Birds and Fruit Ninja sell for 79 pence ($1), and you rarely see full-featured games going for cheaper than that.

Cheers.
> 1 votes

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


title: How to create biomes

text:
# Question
Title: How to create biomes
I am creating an 2D XNA Tile Based Platformer. I have a tile engine and a world/terrain generator. However, I am trying to create biomes or areas, For example, Desert in one part of the world, ocean on the ends, City in the middle, forests scattered around etc. I can easily make it generate them, but My problem is defining the actual areas to be generated in.

# Answer
Without any specific knowledge of your generation algorithm, I would suggest the following.

Assuming that your world is defined in a multi-dimensional array `Tile[999,99]`

1. Decide how many "biomes" you want and of what type
2. Define the size of each biome
3. Go through your world array, and pick a start point for each biome
4. Update the world array with each biome's tile data

For example:

```
Tile[,] World = new Tile[999,99];
Tile[,] Ocean = new Tile[50,10];
// assume we want the ocean to be top left of the world, flowing off the edge
for(int i = 0; i < 50; i++)
{
    for(int j = 0; j < 10; j++)
    {
        World[i,j] = Ocean[i,j];
    }
}

```

You could, as @Nathan suggested, use a distance from water to define which tile-set to use for each area. This could help keep your maps looking fresh and consistent, yet still be generated on-demand.
> 5 votes

# Answer
There is a great discussion of procedurally creating random biomes on a map in Polygonal Map Generation for Games by Amit Patel. His maps are arbitrary polygonal shapes, not tiles, but the same ideas should be applicable.

Briefly: generate elevation and lakes/rivers on your map using whatever method works for you, then define biomes in terms of elevation and moisture (distance to water). There is a nice table in the article that suggests different biomes for different combinations of elevation and moisture level.
> 5 votes

---
Tags: xna, c#, 2d, xna-4.0
---


title: What is server mod?

text:
# Question
Title: What is server mod?
I know what a game mod is. But what is a server mod? Do clients need to install the server mod to get the features of that server mod?

Also, if I have a mod for a game installed on my computer, and I play the multiplayer version of that game, will I be able to enjoy that mod's features if the server doesn't have that mod installed?

# Answer
From a development perspective, anything you would have on a usual server (world objects etc.) must be modded into the server mod while things such as rendering those world objects, must be included in the client mod. If the client mod has no need to have data from the server that it can't already access, then it doesn't need a server mod.

So a mod that adds flying cows throughout the game world, would need modification to both the server (to control, spawn, etc.) the cows, while the client would also need a mod to display the cows. However if the mod simply added the scoreboard to the top of your screen, you wouldn't need a server mod, because chances are the scoreboard is already being sent from the server anyway.
> 7 votes

# Answer
Server mods are just a sub classification of game mod. It's a modification to the way the server processes data. This could be anything from extra logging to a text file to changing the core mechanics of the game being played.

The client side requirements depend on what the mod does and the game the mod is applied to. Depending on the game, the server may have lots of control over the client or very little.

The more control the server has the less likely it is you'll need to install the mod on the client too. This would include the client getting resources from the server like new maps, textures and sprites or 3D models.

The less control the server has (i.e. clients do all the simulation and the server syncs it, there is no transfer of content from server to client), you'd likely need to install the mod on the clients as well.

Further, the above also depends on the extend of the modification. The more the mod changes the more likely you'll need to install it on the client too and vise versa.
> 3 votes

# Answer
Depends on how that game is made and what the mod change.

See Minecraft. I think I can arrange probably all mods on 2 distinct groups: UI mods and Mechanic mods.

UI Mods change one the appearence of the game. Like textures, chat mods and etc. Mechanic Mods and or change some behavior of the game. Like adding new drops and blocks, add a new monster, add quests or economy to the game.

Most of (if not all) the UI Mods change the game only for you. Other players don't know or see what or how you see the game. This kind of mod don't need to be on server side, only on client. For Mechanic Mods it a bit different. On singleplayer all the mods need to be installed on client, of course. On multiplayer, some changes on the behavior of the game don't need additions in the client, like altering the rate of droping some item, or changing a monster spawn time. But some other mods need changes in client. If you need to add a new monster you need to add it to the server. But need to add a new model of this monster in the client too.

Like Kikaimaru and I said, its depend on what is the game and how it was made.
> 1 votes

---
Tags: modding
---


title: Facebook App  Game Canvas Size

text:
# Question
Title: Facebook App  Game Canvas Size
I am building a Facebook App Game and was wondering what a safe height and width for my canvas. I know that the current standard is 760 and there are questions about that, but I would like to know what a good height would be. I would like it to take into account smaller screen sizes. My game is a sidescroller.

I know there are a few Facebook App questions similar to this but I feel mine is different because I am concerned with the height in addition to the width

# Answer
It depends on your **aspect ratio**. For normal screens this is either approximately 4:3 (Standard TV or monitor) or 16:9 (Widescreen). There's slight variations on this like 16:10 as well, but the two above are a good guide.

If you're creating a side-scroller, I'd imagine it's the left-right that matters more than the top-bottom. I'd suggest a widescreen format, so **around the 420-430 mark** will do for height.

**In terms of small screen resolutions**: if you're happy with 760 then you don't really need to go any lower than 420. Since most monitors will have at worst this 16:9 resolution, if it can fit 760 across then it can fit 420 down. Even a really old resolution like 800x600 can fit it comfortably.

If you're talking about supporting phones or people making their Facebook window take up half the monitor rather than the full amount, then I'd check out this tutorial on resizing your game dynamically. You want to **keep your aspect ratio constant** and resize the whole thing to make the game as big as it can be.
> 1 votes

---
Tags: facebook
---


# Question
Title: How can I simulate limited AI vocabulary for a word game?
I've got a small handful of competitive word games in progress, and while the preference is for (mostly asynchronous) play against other human opponents, I'd like to provide players the option of playing against an AI. I have my dictionary and I can easily give the AI full dictionary knowledge while it's playing, but my concern is that having the AI regularly playing words they're not familiar with will be a frustrating experience for players: 'I would have won that game if it'd just used words I know!' — even if the AI's overall skill level is turned down.

I'd rather create a weaker AI through a combination of (un)tuned play parameters and a weaker vocabulary — but I'm not sure how to limit that vocabulary to 'common' words. I've looked at several word frequency lists (for instance, the list of all words that appear in the Project Gutenberg books, sorted by number of occurences) but they all have a number of false negatives: words that everyone knows that simply don't show up with any real frequency (for instance, CHEETAH shows up less frequently in the PG texts than VOCATIVE or SUTTEE). I've tried using search results to get estimates of a word's popularity, but they also tend to be prone to spurious mis-estimates, and of course it's hard to get search results for an entire dictionary without running afoul of the terms of service on the search engines.

Does anyone have suggestions on other good means of determining a rough frequency of word usage, or other ways of limiting word game AI that will feel natural to players?

# Answer
> 7 votes
I think your solution would still be to go with some word frequency list. The Project Gutenberg might not be the one for you as it contains mainly older texts where the copyright has expired, giving strange frequencies for modern english speakers. I guess there was a time when "vocative" was actually a more commonly used word than "cheetah"...

So I think the solution is to find the *right* frequency list. Searching around a little had me stumbling on the 5000 most used words in all Simpsons episodes, that might be a bit more up to date. You might want to cross reference this list against a real dictionary though to sort out words like "krabappel" for instance :)

Hope it helps, I'm excited to hear what solution you go with!

# Answer
> 5 votes
Crowd source it. Use all the multi-player games your players play to build up a word frequency table. I think any analytics service could help collect and organize this data. You could even weight the entries by how "good" the player using the word is.

# Answer
> 3 votes
Start with basic vocabulary according to your AI level. For example let below is your AI level list.

* basic : 1000 words vocabulary
* average : 2000 words vocabulary
* hard : 5000 words vocabulary

You may choose this words from following web sites which you can see with google search.

These sites will give your starting words but I think google n-grams may be better choice. Anyway do not worry to much about your starting words, with updating/adding mechanism explained below your AI dictionary should straighten itself according to your players.

since your players learns while they play this game your AI should learn too. Allow it to learn most used words by their opponents.

For example 10 persons played against your AI basic, they used 100 unknown words, that is words which are not in your AI dictionary. Choose most used words and add them to your basic AI dictionary, also to your average and hard dictionary. You should also choose to update some words which are not used in your dictionary with words people use. This way your starting dictionary will be more suitable for your players knowledge. You may start with fewer words/bunch of different words but your AI will learn while they play against humans.

You may also consider starting your AI with basic level and upgrading it to other levels only when it learnt enough words.

---
Tags: ai
---


# Question
Title: Easiest way to create a 2d game in Java?
I would like to create a 2d game in Java, but tutorials online for game libraries such as LWJGL are usually filled with errors once I compile the project. Most people do not explain very well, and just go on very quickly. Can someone please provide me a couple examples with source code, and somewhere to have a starting point? I used to have trouble with making a GUI and you guys helped me through, hopefully you can do the same again!

# Answer
A very simple and effective method to write small software rendered games is to use the methods and tools swing offers. Begin a new Swing project and add a single component to the window. That is the component everything is being rendered into. It might look like this:

```
public class SwingRenderTarget extends JComponent {
    private final BufferedImage image;

    ...

    @Override
    public void paint() {
        swapBuffers();
        repaint();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        g.setColor(Color.BLACK);
        g.fillRect(0, 0, canvasWidth, canvasHeight);

        g.drawImage(image, 0, 0, canvasWidth, canvasHeight, null);
    }

    private void swapBuffers() {
        System.arraycopy(currentPixels, 0, ((DataBufferInt)image.getRaster().getDataBuffer()).getData(), 0, gameSizeX*gameSizeY);
    }
}

```

What it does is rendering a single `BufferedImage` to the screen that contains all the game data. But how to draw images to the `BufferedImage`? This is simple! Create an array of `int`s (called `currentPixels` in this example) and just treat every int as a single pixel of your screen! In the method `swapBuffers` this array of pixels is written to the previously created `BufferedImage` which is then rendered to screen.

How about an example how to render a simple Sprite to the screen? First of all create a Sprite class:

```
public interface Sprite {

    int[] getPixels();

    int getHeight();

    int getWidth();
}

```

The `int` array will serve as the pixels of the Sprite. You can fill the array programmatically or just load any bitmap from disk. Then when it's time to draw that Sprite just copy the pixels from the Sprite over to our pixel array in the `SwingRenderTarget`. Here is an example to fill the whole screen. To use smaller Sprites one has to copy one row from the Sprite pixel array to the `SwingRenderTarget` pixel array at a time:

```
@Override
public void drawFullscreenBitmap(Sprite sprite) {
    int[] data = sprite.getPixels();

    System.arraycopy(data, 0, currentPixels, 0, data.length);
}

```

Throw in a game loop that has a fixed timestep and there you go: a basic game in no time!
> 4 votes

# Answer
I would suggest using Slick 2d (Slick is built on top of the lwjgl, so you have a great community you can turn to with problems). I just did a little game with it and it worked just fine. It's really easy to grasp and provides all the groundwork, e. g., you don't have to worry about buffers and such. Just define your graphics (images) and draw them. Furthermore, Slick provides states so you can really easy develop the single parts of your game indepent from one another (main menu, options, gameplay and so on).

The states themselves provide you with two alternating methods, update() and render(), so you can divide your code effectively:

```
public void update(){
     // your gamelogic, such as collision-detection, controls, etc.
     // simple example for handling input:
     Input in = getInput();
     if(in.isKeyPressed(Input.KEY_DOWN)){
          player.move("down");
     }
     player.checkCollision();
}
public void render(){
     // draw your assets
     drawUI();
     drawEnvironment();
     player.draw();
}

```

Slick also handles all input, it even has support for controllers. On the page, there are several good tutorials for beginners, explaining how a simple game could look.
> 1 votes

# Answer
I think starting with an existing simple game, then adding to it or changing it is a good route to take. So, find a 2D opensource game to start with as a base. Perhaps you can find one that suits you on one of the game jam sites like ludum dare? I know they usually post their code for people to look at when they're done. This also makes sure that everything is included so you don't have issues with all those compile errors you were talking about.
> 0 votes

---
Tags: 2d, java, lwjgl
---


# Question
Title: Advanced Animation for 2d Isometric Game?
I need help with workflow suggestions for a flash game. (although the concepts would apply to other game engines, too).

In a game like: Hero Academy

There are several different character models each with a multiplicity of animations (walking, standing, getting hurt, attacking, etc.). I am certain that each of these could be manually animated and a sprite sheet generated and used, but when you add up how many animations and core drawings would be needed...that would be near insanity to complete.

So, in research I found that some are creating character models in Blender, Maya, a 3d engine of some kind - setting the camera angle to 45deg, etc. animating and exporting that sprite.

In each of these examples however, the character models were 3d looking i.e.: 3d to 2d

When I look at Hero Academy, they still look like a 2d drawing.

If I am looking to re-create a similar art style to Hero Academy and need several animations per model what is the most efficient/correct workflow to creating the animation? Manually creating each animation sprite in Flash? Or utilizing 3d and texturing it to look 2d?(if that is even possible)?

EDIT: Thank you to all those who have posted great answers. To add information to the concept, one 'issue' I am contending with is the modeling/view of our desired game. To further clarify, if you look at Hero Academy's grid system (a la chess board) if you wanted an entity to be able to move vertically or diagonally this would need it's own sprites. However, is this still a simple 2d side scrolling game since the camera is fixed? And they have simply designed the background map to have the EFFECT of perspective?

If that is the case, then using Nuoji's comments, a 2d skeleton would then again be possible.

The base question is: if we are looking at close to 100 different character entities all with their own movement animation, long and close range attack animations, taunts, etc. what is the most expeditious method of doing this?

Note that I have experience in programming but no design/modeling experience. Whether we went the flash animation route or 3d modeling route I would be learning from scratch so any previous skill or preference is nullified.

# Answer
After looking at the trailer in your link, they are indeed hand-drawn sprites. The animation seems smooth, so I wouldn't be surprised if they used some sort of skeletal 2D animation. This style involves drawing the movable parts of the character separately, so limbs, head, etc are separate sprites and they are posed and rotated accordingly to create keyframes, and tween the animation by code.

The other method as you mentioned, would be to make 3D models and export their animations individually for use in a 2D medium. If you are familiar with 3D modeling, this approach can be a lot quicker. You'd make your keyframes and tween them as usual but you will be able to export the entire animation as a sequence of images ready to be used in your game.

Ultimately, it depends on the aesthetic you want to achieve. Skeletal animation isn't suited for complex deformations.
> 1 votes

# Answer
3D models are certainly a possibility. A 3D model with the combination of cell shading could easily achieve this effect. Project zomboid, while not really cartoon looking, doesn't look very much like 3D models when their animations are playing. However, as they said in a post about animation, they indeed use 3D models to generate their animations.

However, from the looks of it, Hero Academy looks like 2D art that's been attached to a skeletal system and animated. For example, their appears to be no 3D rotation of any of the limbs or head. They only rotate around an axis normal to the screen.

Using the 2D skeleton will allow you to attach the same animations to multiple characters.
> 0 votes

---
Tags: 2d, 3d, flash, isometric
---


title: Unity RTS Movement

text:
# Question
Title: Unity RTS Movement
I am trying Unity out and I want to try and write an RTS. What would be the best way to go about getting the basic, right click to set a destination working within Unity? I know how to get the `mousePosistion Vector3`, but past that not much. Please show some code examples if you can, it would help much more than just telling how to do it.

# Answer
> 6 votes
When just starting out it's useful to see an example. See here for an example RTS game in Unity. From that project you should be able to answer a good number of your own questions regarding how to get started with RTS development in Unity.

---
Tags: c#, unity
---


# Question
Title: What is the standard way of delivering HTML5 games to portals and such?
Let me explain what I mean by "standard way of delivering"...

Think about Flash games sites. Flash games can be delivered as a single file, either hosted by the site, or, I guess, provided by someone else.

HTML5 games, on the other hand, don't have something so standard. Usually, they have their own page, and portals just link to that page. I think that it greatly hinders the purpose of that portal, because, well, you want people to stay on your site and look for other games.

Now, I think that a some kind of iframe way of delivering games would help solve this problem greatly. I saw some games doing that, and they were often included on tutorial sites to show a live example, which is obviously a great thing.

So, is there a standard at all? Any suggestions? Can you create a game that just preloads itself in an iframe (I heard something about a "single document" or something)?

# Answer
> 4 votes
I'm not aware of a standard way to deliver a HTML5 game (yet). Most portals I'm aware of just list the games (together with ratings), but then link to external sites where the games are hosted (eg. to the site of the game-creator).

As things evolve, I'm sure there will be efforts to keep people on the portal-site and similar things that are currently known from flash-games (eg. centralized high-scores, ads within the game etc.).

Currently I see two valid approaches:

* Integrate the game via iFrame. This is very easy to do, doesn't introduce any JavaScript conflicts and also offloads server-load to third-party sites.
* Provide a JavaScript framework with asset-loaders, highscores etc. Game-Developers would have to prepare their game for the framework but would benefit from easy asset-loading and centralized high-scores.

With the plethora of currently available JavaScript game engines/libraries the second solution seems unlikely, as a lot of engines will already have their own means of loading assets and depending on how the game was implemented, JS conflicts can occur. It would work well in an environment where the game-engine is already known, eg. for a showcase of an engine developer.

Another approach are packaged applications. Google allows this as a way to package apps for their web store. Packaged apps can be downloaded and can also use the Chrome Extension APIs. This could be a great way to distribute games but if there's ever going to be a cross-browser standard is questionable.

# Answer
> 1 votes
it's ironic how HTML5 distribution isn't standardized (when the language itself is).

someone's got to make it a single package, for all websites/portals/app stores.

---
Tags: flash, javascript, html5, browser-based-games
---


# Question
Title: What algorithm can I use to detect simple shapes in a 4x4 matrix?
I'm working on a simple multiplayer game that receives a random 4x4 matrix from a server and extracts a shape from it.

For example:

```
XXOO       OXOO
XXOX       XXOO
XOOX  and  XOOO
XXXX       OXXX

```

So in the first matrix the shape I want to parse is:

```
  oo
  o
 oo

```

and the 2nd:

```
  oo
  oo
 ooo

```

I know there must be an algorithm for this because I saw this kind of behavior on some puzzle games but I have no idea how to go about to detecting them or even where to start.

So my question is: How do I detect what shape is in the matrix and how do I differentiate between multiple colors? (it doesn't come only in `X` and `O`, it comes in a maximum of 4). Additionally, the shape must be a minimum of 4 blocks.

# Answer
> 3 votes
What data type is the matrix? If its all stuffed into a single int for example and represented with bits then you could just check masks like so

```
ooxo
oxxo
xxxx
oooo

```

would equal

```
0010011011110000

```

which you could then store in an enum, a #define or what have you and use the simple

```
if(inValue & MaskNumber1 == MaskNumber1) { // we have a perfect match }

```

Since they are also integers you could use a switch statement if you wanted as well (assuming the patterns are exclusive of each other).

If this is not a matrix of Off and On values then let me know and I will try and update my answer.

Hope this helps.

# Answer
> 2 votes
You can use a slightly modified version of a depth first search algorithm to extract connected shapes of items with same color.

If you have a matrix of size 4x4 with items, you need to have additional matrix of the same size with boolean flags stating that given item with (x,y) coordinates was traversed or not.

Then, you may construct a recursive function to extract connected items, given with a description:

```
function traverse(item, currentShape)
    mark item as traversed
    add item to currentShape list
    for each N,E,W,S neighboring item
        if neighboring item with the same color
            if neighboring item not traversed
                traverse(neighboringItem, currentShape)

```

Using a particular order of scanning elements from items matrix (eg. from left to right and from top to bottom) call this function on every non-traversed item and in return, you'll be given an list of items connected to the starting one. There may be many lists of such kind, from whose you can choose ones that have length of 4 or more.

# Answer
> 0 votes
A single 32 bit integer can store all the data. 00,01,10,11. You could even set up some macros so you can use strings for visuals just with bit shifts orred together You can #define each shape and use a switch, case for all of the masks.

```
#include <stdio.h>
#define shapeit(s) ( ( s[0]-'0' )|( s[1]-'0'<<2 )|( s[2]-'0'<<4 )|\
( s[3]-'0'<<6 )|( s[4]-'0'<<8 )|( s[5]-'0'<<10 )|( s[6]-'0'<<12 )|\
( s[7]-'0'<<14 )|( s[8]-'0'<<16 )|( s[9]-'0'<<18 )|( s[10]-'0'<<20 )|\
( s[11]-'0'<<22 )|( s[12]-'0'<<24 )|( s[13]-'0'<<26 )|( s[14]-'0'<<28 )|\
( s[15]-'0'<<30 ) )

/* acceptable values in shape strings are 0123 */
#define LSHAPE shapeit( \
(   "1000" \
    "1000" \
    "1000" \
    "1111" ))

```

which gives this binary representation 1010101000000010000000100000001 of the integer 1426129153 (thus the macros - it would be painful to read otherwise)

since you now have each shape defined as an integer it is possible to use a switch, case to check an unlimited amount of shapes simultaneously (you can change to `long long` instead of `int` later to get larger shapes, but you will need to cast each one in the macro , so it may be easier to just say that an 8x8 is 4 4x4s - maybe only use long long for adding more colors or other "attributes") One big advantage is that since all of the predefined shapes are calculated by the preprocessor into `const int` prior to compiling, a lot of code can be optimized and each incoming shape would only need to be converted to integer and compared ... typically optimizing to a jump table for larger data sets on a switch case

---
Tags: algorithm, objective-c, c
---