# Question
Title: How do I tile a specific region of a sprite?
I have a sprite that I use as a sprite sheet, where regions of the image represent various UI elements (window corner, border, background, etc.).

I want to use a certain region of that sprite as a texture that I can tile over a larger destination rectangle.

Setting the SamplerState to LinearWrap and then calling SpriteBatch.Draw with destination rect and source rect ends up stretching that region of the image, not tiling it.

All the examples I've seen that implement tiling use the entire sprite - I only want to use a region of it, and tile that region.

Is there any way to do this?

Edit for clarity:

Here's an example spritesheet

where I want that colored region. I have a rectangle that represents a window border, that is larger than the region in the source image.

Here's what I want to end up with

Here's the code I've been using.

```
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.LinearWrap, null, null);
spriteBatch.Draw(sourceTexture, windowTopBorderRect, sourceTextureRegionRect, Color.White, 0, Vector2.Zero, SpriteEffects.None, 0);
```

And what I get is the image stretched across the window border rectangle, instead of tiling the source region within that rectangle.

# Answer
> 3 votes
I don't think using `LinearWrap` will work in this case, the reason being that `LinearWrap` takes place automatically when the texture coordinates fall *beyond the edges of the texture*, but you're using a source rectangle that falls entirely within the texture, so it's not even doing anything.

I can think of three solutions (in the order I'd probably choose):

1. Create a new `Texture2D` and copy only that portion of the texture into the new one, or do this offline in your image editor. Then draw it with a source rectangle that has *the same size as the destination rectangle*. Since this source rectangle will be larger than the texture, wrapping will take place. And since they both have the same size, there won't be any stretching.

To be more specific what I mean is something like:

```
Rectangle windowTopBorderRect = /* wherever you want it to draw */
Rectangle sourceTextureRegionRect = new Rectangle(0, 0, windowTopBorderRect.Width, windowTopBorderRect.Height);

```

You could also use the `position` parameter instead of the `destinationRectangle` and let the `sourceRectangle` determine the size.
2. Alternatively do the tiling manually with multiple `SpriteBatch.Draw` calls. Basically calculate how many times you need to draw the texture to fill that space, and draw them in the loop. In the case of an horizontal strip like your example, the last draw call will probably need a source rectangle, to crop only the remaining portion that fits that space.
3. You could also probably draw using a special pixel shader effect that calculates a new texture coordinate that wraps around the original source rectangle without stretching, but this might be tricky.

# Answer
> 1 votes
Pass the SpriteBatch a rectangle instead of null for the sourceRectangle parameter. It is defined as a nullable type in the method signature so it is optional and defaults to the whole texture.

Edit: You will also need to change your destination rect with each draw call. Sorry I left that out.

---
Tags: xna-4.0, textures
---


# Question
Title: Are there any narrative (or at least non-spatiotemporal) focused engines/frameworks?
EDIT (2): Since there are two answers and I haven't accepted any of them I figured I'd motivate what I'd consider an answer here: Either something strongly suggesting any such approach would be impossible/not at all useful or, alternatively, a reference to a research (field) or examples of an at least somewhat general such system beyond text adventure games/interactive fiction.

While I won't pretend I've done any deeper investigation I've noticed that all the game engines/frameworks I have looked into seemed to be something like a glorified graphics engine in the sense that they speak of shapes/entities in a two or three dimensional euclidean space with, possibly, some form of concurrency model "tucked on" allowing one to specify some form of logic attached to these "entities".

Game "rules" and narrative is then written in a somewhat ad-hoc (with respect to the engine) way on top of these primitives.

Obviously the above description is rather simplified (take more specialised engines such as the infinity engine which does include some form of quest/narrative system), and I realise that this model can work quite well (a lot of people seem to have used it).

I'm wondering, though, what attempts have been made to create engines/frameworks that take notions such as (high level) description of ~~game rules/logic or~~ narrative (or at least a non-spatial aspect of the game) as their primary basis?

EDIT (4): This doesn't mean that the game would not include any spatial/graphical aspects, just that rather than having spatial entities to which you associate logic, you have a notion of plot (or gameplay or "board game rules") which you then describe a graphical interface to/realisation of.

Especially I'd be interested in any declarative approaches that try to capture some kind of (semi-)formal semantics of some reasonably large class of games, in a way useful for actual implementation (as opposed to, for example, a framework exclusively for qualitative analysis of games/narrative).

What I've seen are some investigations into modeling/analysing narrative with a petri net-based model and some interesting approaches in langauges for writing interactive fiction.

EDIT (1): I figured I'd add a toy example to illustrate.

Say we were interested in creating point & click style adventures (think SCUMM games). One might analyse these as being based on a notion of more or less linear and discrete *progression* from a starting situation to an end.

Focusing on the notion of discrete progression, and allowing for some non-linearity, one might choose the theory of (bounded) DAGs as ones basic theory. Specifying a game of this type, in its (relative to this theory) most abstract form thus corresponds to adding additional axioms to this theory (either so that the theory specifies a *specific* graph or simply enough to capture whatever one thinks is required to capture ones "plot").

Turning this into an actual game now turns into the HCI/Interface design problem of embedding this theory into something playable (i.e. building a model of the theory/finding an homo(iso?)morphism of graphs from the collection of user interface states with transitions into the DAG "specifying the game").

In the above hypothetical scenario I can see at least three things that should be possible to capture in libraries. Firstly one needs tools for transforming/reasoning about DAGs or graphs in general. Secondly a user interface library clever enough to help in verifying that our representation of our graph as a playable game actually models the graph (thus for example, at least partially/informally, proving the game has no stuck states, due to the boundedness condition). Finally a collection of higher level libraries for specifying the graph could be given; such as a library for expressing characters and their interaction and generating (parts of) graphs in terms of such.

Why keep the "middle" theory of DAGs, rather than just have the low level implementation with some help libraries on top? The answer is all the usual reasons for a formal semantics. Given that we have decided on a formal foundation we can verify certain properties of the game allowing one to reason about things like optimisations in the low level interface library (as long as it models the DAG we can do what we want), without having to worry about incomparability with the high level description (of characters/dialogue e.t.c.), as those descriptions must themselves describe such structures.

I'm in no way implying the above approach in specific would work, and the idea isn't that a DAG has to be what is actually kept in memory (rather it forms something akin to a computational formalism such as a lambda calculus), but I hope that this illustrates the kind of approach I'm curious about.

In short, I guess an alternative title to this question might have been: How would Dijkstra have written computer games?

# Answer
A quick note about narrative and game rules: in interactive fiction it can be argued that the game is that of traversing a graph of branching narrative, but ultimately the narrative lives outside of the game mechanic - you could replace all the words with something unreadable and yet the steps to complete the game (or to lose when playing it) would be exactly the same. This in turn implies the narrative is irrelevant to the gameplay, except where a developer chooses to change one to suit the other. In games, the narrative is essentially a façade over the mechanics that can make the mechanics more compelling to a player who enjoys that narrative, but that is all. There are some games (although some don't call them games) where the narrative is the primary form of entertainment and the game mechanics are mostly perfunctory, such as the recent release Dear Esther, but developers don't need a formal method for telling stories any more than fiction writers do, so I won't consider narrative further. Generally speaking, any game which looks like "playable narrative" is a tree or graph of game events that can exist and be discussed meaningfully without the narrative at all.

> I've noticed that all the game engines/frameworks I have looked into seemed to be something like a glorified graphics engine in the sense that they speak of shapes/entities in a two or three dimensional euclidean space \[...\]

Yes, most "game engines" are obviously "video game engines", and their main responsibility over time has been to facilitate the software engineering side of a video game, not the game side. Arguably this makes sense because it is the software engineering that is the newest and most expensive and hence most risky aspect. By comparison, game design in an abstract sense has been done by hand for thousands of years without the aid of tools, which may explain to some degree why that continues to be the case.

> what attempts have been made to create engines/frameworks that take notions such as (high level) description of game rules/logic or narrative (or at least a non-spatial aspect of the game) as their primary basis?

There have been few serious attempts, none successful, as far as I know.

Storytron is one. *"Unlike traditional interactive fiction, a Storyworld is more concerned with modeling actors' actions and reactions and their emotions and inclinations rather than the game world geography or the mundane objects that populate it."* It follows a previous effort called Erasmatron, which didn't really succeed, and Storytron isn't really looking like succeeding either. The following article is a good read on this: Chasing the Dragon

On a less ambitious level, there are lots of people who have come up with simple ways of representing simple games. One paper out of many is this: Multigame — A Very High Level Language for Describing Board Games (link is behind a login, but you may be able to search for it) but all you have at the end is a computer readable set of possible states, state transitions, and victory conditions or score-keeping functions - fine for discrete board games such as Chess or card games such as Poker, but they don't generalise to games with large amounts of continuous state or those with semantics that are more like simulations (eg. shooter games) or sports (eg. racing games). Such games can't adequately be represented via a simple tree of game states.

One way to approach the understanding of these more complex systems is to try and categorise each existing mechanic into one of several basic forms, and then work out how the basic forms can be combined to form more complex gameplay, under the assumption that all gameplay can be comprised of these fundamental units, or combinations thereof. Dan Cook has an article called "What Are Game Mechanics?" and a follow-up "The Chemistry of Game Design" which attempt to document this compositional approach to game design. In theory it might be possible to construct a declarative system on top of that, but in practice the mechanics only form a small portion of the game and so the resulting output would presumably be constrained within a presentation framework that would not be flexible enough to capture the attention of most gamers.

Other attempts at formalising game design concepts are often called "game grammar" - one such article is called "Multiplayer Game Atoms" but that refers back to various previous works.

> Say we were interested in creating point & click style adventures (think SCUMM games). \[...\] one might choose the theory of (bounded) DAGs as ones basic theory. \[...\] Firstly one needs tools for transforming/reasoning about DAGs or graphs in general. Secondly a user interface library clever enough to help in verifying that our representation of our graph as a playable game actually models the graph (thus for example, at least partially/informally, proving the game has no stuck states, due to the boundedness condition). Finally a collection of higher level libraries for specifying the graph could be given; such as a library for expressing characters and their interaction and generating (parts of) graphs in terms of such.

The problem here is that the computer doesn't add much to the process. Designers of games like this will often draw up exactly this, a graph in digital or physical form, which shows the flow through the game. It's trivial to see whether the game can theoretically be completed or not. Even encoding the various rules for progressing through a point and click adventure are trivial. The hard part is making it follow an interesting narrative, setting it in a compelling-looking world, creating the art and sound assets to portray the game and the interface properly, and the various software engineering tasks that hold it all together. The directed graph of significant states through the game is usually relatively trivial; it's all the stuff around it that is the problem. And this is why there's not much interest in it, except in interactive fiction where (a) the mechanics and presentation are a solved problem, and (b) the typical developer is non-technical.

I personally am currently working with a team on a product called Storybricks which attempts to allow for the construction of interesting gameplay through specifying various rules, and these rules may state a person's initial state, their needs, and so on. It is easy to take these rules and verify whether a person's needs can be met, and if so how, and therefore to declaratively create tasks that need to be completed in-game. However this itself doesn't inherently create interesting gameplay, because once you abstract things down to the level of "X needs Y - fetch it for them" players start to spot the pattern and cease to enjoy it. (For example: people tired quickly of the auto-generated quests in Skyrim, because they could see that there was no inherent meaning to a procedurally generated mission, compared to the designer-crafted ones.) So our job will be to use AI methods to make these situations more interesting, and that is something we're still working on. (Storybricks is still in a very early alpha stage). But our research indicates that few people are attempting anything like this, and that it's a very hard problem.

Another problem with the declarative approach is that it is not very usable. Scientists like it because it is easy to process, for example to prove that a situation is solvable or that a set of logic rules are consistent. But in the real world, neither computer game programmers nor end users are generally as comfortable with a declarative representation that focuses on the results as they are with an imperative representation that tells them how to act in order for the results to happen. The current top 10 programming languages are all imperative, and real world instructions are also generally in imperative form, whether that's how to bake a cake or how to construct furniture. This lack of enthusiasm from either end of the spectrum means there is no commercial incentive to produce formal specifications for modern games, and this looks unlikely to change in the near future.
> 4 votes

# Answer
I've been considering how to reply for awhile, and I'm not quite sure how to put this.

It's a good question. Unfortunately the answer kind of boils down to that it either doesn't make sense to program anything let alone a game engine this way, or that this is already how things kind of are.

---

There seems to be this emphasis on graphics, because there needs to be a way to define the physical existence of objects. This is kind of where things start getting existential because what we're really talking about is a representation of dimension, but let's just ignore this for now. The main point is, this is something that really is quite involved. Allowing for the representation of space is going to be something that inherently takes up a lot of the programming of a game engine. And if designers want to make nice scenes they'll need a lot of control over how things are placed. So you're going to see a lot of stuff about graphics.

So, that's the low level side of things. Someone needs to put a lot of deep thought into all of these little technical issues.

As far as narrative and game rules go? That's out of scope of what a game engine is supposed to do. This is the part where the development group comes in.

What's more, it's not like a lot of thought hasn't been put in to how to represent ideas through programming. That's really what the history of computer science *is*. And, this is why game engines frequently have interfaces to high level languages. It's easier to represent thoughts through them.

---

So with that in mind, could a language be made specifically for games with a narrative emphasis? I would say probably not. Again this all comes down to representation. The language needs to be able to be able to describe details in such a way that the computer knows what to do with it. If the purpose is to make a language that is specific to game creation, then any design decisions should be centered around that.

And again, there's a lot of choices of languages as is. And more people than just those in the games industry have been developing them. It generally makes sense to use one of those.

---

In summary you asked an interesting, but very difficult question. And I'm not entirely sure what it is, or if I actually answered it.

\*edit: In hindsight, I realize that I was only considering 3D Game Engines, as if they were the only ones that exist. Some games don't have a person acting in a physical space at all. Though in such instances I'm not sure that a game engine would contribute much.
> 3 votes

# Answer
Early in the history of hobby computing (i.e. the 80's) there were some commercial Game development kits available for both text and sprite based games. The sprite based ones were very like the current "graphics engines".

The other type included things like natural language parsers. This type seems to live on in the modern "level editors". Most of those seem to include support for something like Lua or Python scripting. I would also note that I do not see a lot of activity in open source level editing, but that is because these things are usually very tightly coupled to the specifics of the game in question. I am thinking here about something like the Elder Scrolls construction sets.

The Kinect may bring the parser back. As a fan of the old text-based adventure game, I am excited about Bethesda's direction here as well. It most certainly is proprietary, but maybe some young genius...
> 2 votes

---
Tags: architecture
---


title: Rendering Loop Problem (Java)

text:
# Question
Title: Rendering Loop Problem (Java)
I'm not new to programming, but I am relatively new to game programming. I am trying to create a version of Breakout, as a good basic game to get myself introduced to 2d game programming.

I currently have a class structure as the following:

The BreakoutRunner class is the basic initialization stuff for a JFrame. It holds a BreakoutView, which is a JPanel that contains the update logic, and the renderer.

First off, is this a correct structure?

Secondly, I am having problems getting this to work correctly. In BreakoutView, I have the following constructor:

```
public BreakoutView()
{
    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    setBackground(Color.black);

    state = GameState.PLAYING;

    gameBlocks = new Block[NUM_ROWS][BLOCK_ROWS];
    gameBall = new Ball(WIDTH / 2, HEIGHT /2);
    player = new Player(WIDTH / 2);

    initializeGrid();

    //start();
}

```

I have the method `start()` which is commented because it is causing the problems. With the line commented, the game looks like so:

But the problem arises when I take away the comment, and add the `start()` method.

The start method:

```
private void start()
{
    while(state == GameState.PLAYING)
    {
        update();
        repaint();

        try
        {
            Thread.sleep(50);
        }
        catch(InterruptedException e)
        {
            assert(e == null);
        }
    }
}

```

Which includes calls to update:

```
private void update()
{
    checkBlocks();
    moveBall();
}

```

and `repaint`, which I believe calls the `paintComponent` method:

```
public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    drawWalls(g);
    drawBlocks(g);
    drawPlayer(g);
    drawBall(g);
}

```

When the code is run with `start()` uncommented, it gets thrown into an infinite loop, while the frame and the panel get turned into something that looks like this:

What is going on here? Any idea why I'm just sent into an infinite loop?

Thanks Everyone!

DISCLAIMER: I know the update loop is not completely correct. I am more worried about getting it to work period, rather than at an even frame rate... (IE. sleep == bad).

# Answer
> 2 votes
You're not supposed to call your start() method inside the class's constructor, is your problem.

You need to create a separate Thread object that handles your main logic/rendering loop.
*That* you can start in your constructor, but it would be safer to start in your main(String\[\] args) method, just in case.

By not allowing control to drop back into Swing, you're preventing it from actually pack()ing the JFrame and preparing it for rendering.

---
Tags: 2d, java, rendering, game-loop
---


title: Help with Open GL terrain

text:
# Question
Title: Help with Open GL terrain
I have a terrain class like so:

```
class Terrian  {
    public:
        Terrian(int width, int height);
        virtual ~Terrian();

        GLuint get_vertexbuffer();
        GLuint get_colorbuffer();
        GLuint get_elementbuffer();
    protected:
    private:
        Vector3 **terrian_vertices;
        Color **terrian_colors;
        GLushort *terrian_elements;

        GLuint vbo_terrian_vertices;
        GLuint vbo_terrian_colors;
        GLuint ibo_terrian_elements;

        GLint width;
        GLint height;

        void construct_vertices();
        void construct_buffers();
        void construct_elements();
};

```

My problem is that the terrain simply never shows, I don't know if I am doing anything incorrectly but here is how the vertices are generated (I commented out the actual code and create a box instead).

```
void Terrian::construct_vertices()  {
    terrian_vertices = new Vector3*[8];
    terrian_colors = new Color*[8];

    /* actual code ...*/

    GLfloat cube_vertices[] =  {
        -1.0, -1.0,  1.0,
         1.0, -1.0,  1.0,
         1.0,  1.0,  1.0,
        -1.0,  1.0,  1.0,
        // back
        -1.0, -1.0, -1.0,
         1.0, -1.0, -1.0,
         1.0,  1.0, -1.0,
        -1.0,  1.0, -1.0,
    };

    GLfloat cube_colors[] = {
        // front colors
        1.0, 0.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 0.0, 1.0,
        1.0, 1.0, 1.0,
        // back colors
        1.0, 0.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 0.0, 1.0,
        1.0, 1.0, 1.0,
    };

    int index = 0;

    for (int i = 0; i < 8; i++)  {
        terrian_vertices[i] = new Vector3(cube_vertices[index], cube_vertices[index+1], cube_vertices[index+2]);
        terrian_colors[i] = new Color(cube_colors[index], cube_colors[index+1], cube_colors[index+2]);

        index+=3;
    }
}

void Terrian::construct_elements()  {
    int index = 0;

    GLushort cube_elements[] = {
        // front
        0, 1, 2,
        2, 3, 0,
        // top
        1, 5, 6,
        6, 2, 1,
        // back
        7, 6, 5,
        5, 4, 7,
        // bottom
        4, 0, 3,
        3, 7, 4,
        // left
        4, 5, 1,
        1, 0, 4,
        // right
        3, 2, 6,
        6, 7, 3,
    };

    terrian_elements = new GLushort[36];

    for (int i = 0; i < 36; i++)  {
        terrian_elements[i] = cube_elements[i];
    }

    /* actual code ...*/
}

void Terrian::construct_buffers()  {
    glGenBuffers(1, &vbo_terrian_vertices);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_terrian_vertices);
    glBufferData(GL_ARRAY_BUFFER, sizeof(terrian_vertices), terrian_vertices, GL_STATIC_DRAW);

    glGenBuffers(1, &vbo_terrian_colors);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_terrian_colors);
    glBufferData(GL_ARRAY_BUFFER, sizeof(terrian_colors), terrian_colors, GL_STATIC_DRAW);

    glGenBuffers(1, &ibo_terrian_elements);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_terrian_elements);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(terrian_elements), terrian_elements, GL_STATIC_DRAW);
}

```

My Vector3 and Color structure look like the following:

```
struct Vector3  {
    GLfloat xyz[3];

    Vector3(GLfloat x, GLfloat y, GLfloat z)  {
        this->xyz[0] = x;
        this->xyz[1] = y;
        this->xyz[2] = z;
    }

    Vector3()  {
    }

    void set_x(GLfloat x);
    void set_y(GLfloat y);
    void set_z(GLfloat z);

    GLfloat get_x();
    GLfloat get_y();
    GLfloat get_z();

    Vector3 operator=(Vector3 param);

    void normalise();
};

```

Color:

```
struct Color  {
    GLfloat rgb[3];

    // Storing a one byte value in four bytes FTW

    Color(GLfloat r, GLfloat g, GLfloat b) {
        this->rgb[0] = r / 255.0;
        this->rgb[1] = g / 255.0;
        this->rgb[2] = b / 255.0;
    }

    Color()  {
    }

    GLfloat get_r();
    GLfloat get_g();
    GLfloat get_b();

    void set_r(GLfloat r);
    void set_b(GLfloat g);
    void set_g(GLfloat b);
};

```

I render the terrain like:

```
void render(sf::Window *app, Terrian *terrian)  {
    app->SetActive();

    glClearColor(0.0, 0.0, 0.0, 1.0);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(program);
    glEnableVertexAttribArray(attribute_coord3d);

    // Describe our vertices array to OpenGL (it can't guess its format automatically)
    glBindBuffer(GL_ARRAY_BUFFER, terrian->get_vertexbuffer());

    glVertexAttribPointer(
        attribute_coord3d, // attribute
        3,                 // number of elements per vertex, here (x,y,z)
        GL_FLOAT,          // the type of each element
        GL_FALSE,          // take our values as-is
        0,                 // no extra data between each position
        0                  // offset of first element
    );

    glEnableVertexAttribArray(attribute_v_color);

    glBindBuffer(GL_ARRAY_BUFFER, terrian->get_colorbuffer());

    glVertexAttribPointer(
        attribute_v_color, // attribute
        3,                 // number of elements per vertex, here (R,G,B)
        GL_FLOAT,          // the type of each element
        GL_FALSE,          // take our values as-is
        0,                 // no extra data between each position
        0                  // offset of first element
    );

    /* Push each element in buffer_vertices to the vertex shader */
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, terrian->get_elementbuffer());

    int size;
    glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);

    glDrawElements(GL_TRIANGLES, size / sizeof(GLushort), GL_UNSIGNED_SHORT, 0);

    glDisableVertexAttribArray(attribute_coord3d);
    glDisableVertexAttribArray(attribute_v_color);
}

```

I really have no idea what is wrong, and why nothing is being drawn, I've checked my code against numerous examples but still can't find the issue, in the case that my world transformations may be a problem here they are:

```
void update(sf::Window *app, sf::Clock *clock)  {
    float angle = clock->GetElapsedTime() * 45;

    glm::vec3 axis_y(0, 1, 0);
    glm::mat4 anim = glm::rotate(glm::mat4(1.0f), angle, axis_y);

    glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0, 0.0, -4.0));
    // position, centre, up
    glm::mat4 view = glm::lookAt(glm::vec3(0.0, 2.0, 0.0), glm::vec3(0.0, 0.0, -4.0), glm::vec3(0.0, 1.0, 0.0));
    glm::mat4 projection = glm::perspective(45.0f, 1.0f * 800 / 600, 0.1f, 100.0f);

    glm::mat4 mvp = projection * view * model * anim;

    glUseProgram(program);
    glUniformMatrix4fv(uniform_mvp, 1, GL_FALSE, glm::value_ptr(mvp));
}

```

**Edit**

Updated code according to Viclund's answer:

```
#ifndef TERRIAN_H
#define TERRIAN_H

#include "Vector3.h"
#include "Color.h"

#include <GL/glew.h>
#include <GL/glu.h>
#include <GL/gl.h>
#include <stdlib.h>
#include <vector>

class Terrian  {
    public:
        Terrian(int width, int height);
        virtual ~Terrian();

        GLuint get_vertexbuffer();
        GLuint get_colorbuffer();
        GLuint get_elementbuffer();
    protected:
    private:
        Vector3 *terrian_vertices;
        Color *terrian_colors;
        GLushort *terrian_elements;

        GLuint vbo_terrian_vertices;
        GLuint vbo_terrian_colors;
        GLuint ibo_terrian_elements;

        GLint width;
        GLint height;

        void construct_vertices();
        void construct_buffers();
        void construct_elements();
};

#endif // TERRIAN_H

```

...

```
void Terrian::construct_vertices()  {
    terrian_vertices = new Vector3[8];
    terrian_colors = new Color[8];

    GLfloat cube_vertices[] =  {
        -1.0, -1.0,  1.0,
         1.0, -1.0,  1.0,
         1.0,  1.0,  1.0,
        -1.0,  1.0,  1.0,
        // back
        -1.0, -1.0, -1.0,
         1.0, -1.0, -1.0,
         1.0,  1.0, -1.0,
        -1.0,  1.0, -1.0,
    };

    GLfloat cube_colors[] = {
        // front colors
        1.0, 0.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 0.0, 1.0,
        1.0, 1.0, 1.0,
        // back colors
        1.0, 0.0, 0.0,
        0.0, 1.0, 0.0,
        0.0, 0.0, 1.0,
        1.0, 1.0, 1.0,
    };

    int index = 0;

    for (int i = 0; i < 8; i++)  {
        terrian_vertices[i] = Vector3(cube_vertices[index], cube_vertices[index+1], cube_vertices[index+2]);
        terrian_colors[i] = Color(cube_colors[index], cube_colors[index+1], cube_colors[index+2]);

        index+=3;
    }
}

void Terrian::construct_elements()  {
    int index = 0;

    GLushort cube_elements[] = {
        // front
        0, 1, 2,
        2, 3, 0,
        // top
        1, 5, 6,
        6, 2, 1,
        // back
        7, 6, 5,
        5, 4, 7,
        // bottom
        4, 0, 3,
        3, 7, 4,
        // left
        4, 5, 1,
        1, 0, 4,
        // right
        3, 2, 6,
        6, 7, 3,
    };

    terrian_elements = new GLushort[36];

    for (int i = 0; i < 36; i++)  {
        terrian_elements[i] = cube_elements[i];
    }
}

void Terrian::construct_buffers()  {
    glGenBuffers(1, &vbo_terrian_vertices);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_terrian_vertices);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3) * 8, terrian_vertices, GL_STATIC_DRAW);

    glGenBuffers(1, &vbo_terrian_colors);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_terrian_colors);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Color) * 8, terrian_colors, GL_STATIC_DRAW);

    glGenBuffers(1, &ibo_terrian_elements);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo_terrian_elements);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * 36, terrian_elements, GL_STATIC_DRAW);
}

```

**Edit 2**

```
X: 5.69408e-039 Y: 5.745e-039 Z: 5.745e-039
X: 4.12098e+021 Y: 4.74227e+030 Z: 4.74227e+030
X: 1.93472e-019 Y: 1.80569e+028 Z: 1.80569e+028
X: 1.35662e-019 Y: 1.3556e-019 Z: 1.3556e-019
X: 2.79324e+020 Y: 1.15701e+027 Z: 1.15701e+027
X: 4.23282e+021 Y: 1.65846e+019 Z: 1.65846e+019
X: 3.52687e-012 Y: 4.12098e+021 Z: 4.12098e+021
X: 1.46091e-019 Y: 7.03684e+028 Z: 7.03684e+028

```

# Answer
I reluctantly used the std::vector type to store my vertices, colours, and elements.
> 0 votes

# Answer
There's two core problems here that I have seen.

* You've got the wrong type for your `terrian_vertices` and `terrian_colors` arrays.
* You're passing in the wrong sizes for your glBufferData calls.

First, your arrays contains pointers to `Vector3` and `Color`, which you provide as-is into the call to `glBufferData`. Interpreting pointer addresses as floating point numbers does not make sense, and will not result in uploading the attributes they point to

Compare your index array to your position and color arrays, and see how it has one less indirection.

What you have is a pointer to an array, whose elements point to objects of Vector3 or Color type. What you *need* is a pointer to an array, whose elements *are* of Vector3 or Color type.

In crude ASCII art, you have:

```
colors -> [ pt0   pt1  .. ptN ]
             |     |       |
             v     v       v
           (rgb) (rgb)   (rgb)

```

and want

```
colors -> [ (rgb) (rgb) ... (rgb) ]

```

Turn this

```
Vector3 **terrian_vertices;
terrian_vertices = new Vector3*[8];

terrian_vertices[i] =
    new Vector3(cube_vertices[index], cube_vertices[index+1], cube_vertices[index+2]);

```

into

```
Vector3 *terrian_vertices;
terrian_vertices = new Vector3[8];

terrian_vertices[i] =
    Vector3(cube_vertices[index], cube_vertices[index+1], cube_vertices[index+2]);

```

Secondly, your glBufferData call uses a size you probably did not intend to use.

`sizeof(object-of-pointer-type)` is the size of that pointer type, not whatever array it may point to. You need to pass in the byte size of the whole buffer, which is the size of a single element multiplied by the number of elements, `sizeof(Vertex3)*NumberOfVertices`.

As a final note, you might want to correct the spelling to "terrain" from "terrian".
> 1 votes

---
Tags: c++, opengl, rendering, terrain-rendering
---


title: Asteroids Ship Movement

text:
# Question
Title: Asteroids Ship Movement
I have read source code of asteroids game. I want to know why when updating the ship's position in X, and Y Axis, we must write it in sin and cosine of the current angle. Is it angular velocity ? why we can't use linear velocity and update the position by a linear velocity?

# Answer
> 2 votes
Look at the unit circle below, \[cos(t), sin(t)\] simply gives you a 2D unit vector for an angle of t. For any direction between 0 and 2PI (0\* and 360\*) just feed cos/sin the correct angle. Want to go west? Use t=PI radians (or 180\* degrees), this gives you the unit vector \[cos(PI), sin(PI\] or \[-1,0\].

# Answer
> 1 votes
Think of it as shooting a cannon.

When you shoot a cannon parallel with the ground with a given force, it is guaranteed to go horizontally and not vertically. This is because we apply force in this direction. However, if we were to apply a linear velocity to both the 'X' and 'Y' components, this would create a constant speed which would look silly.

For Asteroids, you want to make sure a force is applied in the right direction. Otherwise, what would happen is your asteroid was pointing directly east or west? Would you still want it to move at the same direction each time? While pushing Right, you want the computed magnitudes of each components velocity to be correct.

---
Tags: opengl, mathematics, physics
---


# Question
Title: android game: how to approach mutliplayer
I'm making a single player game that is near completion, and I am already starting to think about giving the game multiplayer. The multiplayer would basically be finding someone to play against, likely in a waiting room or just have a match-making function, and then having a pokemon style battle between the people in real time. I think it would be relatively simple as I'm just sending information about each attack(move chosen and damage) and what it did back and forth, but I'm not sure what resources to consult for this. I am very new to Android/Java development and really just learning as I go.

I have heard a bit about Skiller, but I'm still unfamiliar with using other SDK's and how easy it may be. Does anyone have any suggestions as to what SDK's or methods for accomplishing this. I currently have no money to spend on software development, but I'd like to get started on learning how to do this.

# Answer
> 2 votes
I wouldn't discourage attempting it but even simple multiplayer is a bit involved..

> I think it would be relatively simple as...

Realtime vs. Turn Based multiplayer are very different beasts. Matchmaking would require a publicly accessible ip address so you would need to use a service or host your own. There are issues with NAT traversal, firewalls, etc. Stick with something fast like UDP, keep your messages lightweight and try not to get too chatty.

I'm not sure what advice to give you regarding retrofitting for something like multiplayer once your game is done. Honestly, I can't even imagine the task given how much the game mechanics/flow would require some forethought up front. You have to think very differently when you don't know when/if a message will arrive?

---
Tags: android, multiplayer
---


# Question
Title: Design pattern for creating multiple enemies
I'm currently attempting to implement a factory method pattern for creating multiple different enemies after loading data from a file. But I'm having second thoughts on what would be the best design pattern to implement or if in fact I am even using it correctly, below is how I intended to use it:

The Enemyfactory determines which enemy to create according to enemy type specified in the xml level file. For example:

```
<enemy>
    <type>
    NORMAL
    </type>
   ...
</enemy>

<enemy>
    <type>
    BRAWLER
    </type>
   ...
</enemy>

```

This data is read in the LevelLoader and then can be used to construct enemies. In the LevelLoader class I could easily have somehting like this instead:

```
if(node.equal("NORMAL")){
 return new NormalEnemy(//parameters from file to construct enemies);
  }else if (node.equal("BRAWLER")) {
  return new BrawlerEnemy();
}

```

With this information, what would be the best way/best design pattern to use to create multiple enemies.

# Answer
Not only you can encapsulate the mechanisms of object creation into Factory, but you can use Decorator pattern to define flexible enemy structure. Because you use a xml to define object structure, it would be very flexible to define a bunch of decorators and to play with them in the xml. Possible class diagram for enemy composition:

I can't define behaviour of decorators for now, because I don't know the responsibilities of your enemies, but as far as I can see decorators would escalate render call to wrapped object, but add some behavior on update method. In addition, you can consider creating other principal classes besides NormalEnemy.

You can also examine using Composite pattern or similar way in dealing with this complexity, which if described in this article: Refactoring Game Entities with Components
> 5 votes

# Answer
You can use **factory method** or you can use array of objects **prototype pattern** (prototypes or templates, how to name them your choice) from which you create objects just copying and instantiating if required. I've seen only this two ways of problem solution, if someone suggest another one I'll be glad to see them (possibly they are better)
> 2 votes

---
Tags: java, architecture, design-patterns
---


title: Saving big maps

text:
# Question
Title: Saving big maps
When the map is relatively small, it takes a few milliseconds to save it, so it's generally ok. But with other, much much bigger maps, it could take several seconds, which is both annoying and hangs the game's networking, and overall leads to many problems.

Threading kind of is the answer, but it creates another problem — while map is being saved, all changes user makes are also being saved, after the save button was pressed (so if the user decides to blow up the map right after pressing Save button, he might be unaware of that it might be saved). So this either calls for user-map interaction block until map saves, or something else entirely.

# Answer
> 0 votes
When it takes a lot of time to save a map, and it can't be divided into chunks, one way to do it is to copy the map into a new instance of map class and save that instead of the live map.

---
Tags: xna, multithreading, savegame
---


# Question
Title: Resource and game state management for multiplayer game server
I'm building a virtual world kind of engine. It's mostly for fun and learning. But I would like to get it right from the very beginning, so it is stable and can be scaled relatively easily.

I've been reading a lot lately about architecture of multiplayer real-time games (and real-time 3D games in general) but still there are some questions unanswered.

For now, I know the following:

* the server will be the authority, and clients will be "slaves";
* the game engine core will be based on subsystems (like physics subsystem, game logic subsystem etc.) and all the communications between those subsystems will be implemented using pub/sub approach;
* I'll use enet for networking, and my network layer will be as a separate subsystem, which will just plug into the pub/sub system (so other game server components don't have to know anything about the network layer);
* physics engine - some free library, haven't decided yet. I guess, I'll use the same physics engine on the server and on the clients, and implement client-side prediction;
* I would like my server to be cross-platform (Windows and Unix/Linux) so I'm thinking about using new C++11 features (like cross-platform threading support etc.). I know, C++11 is not stable yet, but I guess, it will be stable at the time when I have something working (Visual Studio 11 Beta and the latest GCC already support many C++11 features, so I guess, it's good to go). Using C++11 I could avoid some other 3rd party libraries, like Boost;
* game state storage - MySQL. I'm not yet sure, what strategy I'll use to flush the game state from memory to the database, but I think, it'll be mixed - more important state changes will be stored immediately, and less important ones will be stored in batches in some background process.

I guess, this information should be enough to see where I'm going to. And now the questions.

There are going to be lots of various resource files - textures, audio, meshes etc. Do I need a resource manager also on the game server or it will be enough to have a good resource manager on the clients only? As the game world gets bigger and the number of clients grow, the resource manager needs lots of careful planing to avoid loading all the resources in memory and thus possibly causing low-memory issues. What is the best practice - do game servers load and keep the resources cached in RAM (and also unload them as necessary to avoid low memory issues) or this task is relayed completely to clients?

I've heard a lot about memory managers/heap allocators and how the game engine might benefit from a custom memory manager to track memory allocations, collect statistics, debug etc. Will a custom memory manager give something valuable to the multiplayer server or it is enough to use custom macros around new/delete to track standard C++ memory allocations?

Could I use some NoSQL RAM database engine which periodically (or when there are enough dirty objects, or when system goes out of free physical RAM) flushes its state to some persistent database? Will the game server benefit from such approach? I don't want to use something just because it's modern and cool, I prefer simple (but still scalable) solutions.

# Answer
Servers don't use "resources," they're completely headless and never touch memory heavy things like textures, audio or full resolution meshes, those are the client's job. A server will send the client the recipe and the client will bake the cake, a server will send the client a match and the client sets itself on fire.

The thing to keep in mind is that a server runs a numerical simulation while the client visualizes what is going on.

As for memory mostly you're concerned about leaks and any solution that lets you track who allocated a block will only help.

"don't want to use something just because it's modern and cool" != "thinking about using new C++11" I'm just sayin' =) And especially cross platform, you're going to have a bad time.

Databases are used for persistence, sometimes internal info transfer, and what you want a server to store is not transient object state but what's needed to restore the world.

Example: You have an "enemy camp" object that spawns 3 enemies and repopulates them on a timer if any are killed. You never persist the enemies, just the spawn object. When your world restarts it rebuilds the spawn object and it goes about business of recreating the enemy camp. Everything else is kept in RAM, there's no need to keep a permanent copy of temporary objects.

The point is that if your server crashes or is taken down for any reason you do not need to position every single enemy and put them at exactly the right animation and AI state, what you do need is enough to kick start their appearance in the world and then let the simulation take over.

Of special note for databases is that players get special attention. Any item/money/whatever that a player owns must be handled with ACID transactions and changes stored as soon as possible. There is nothing that can stand up against a wolverine except a pissed off customer who just lost his Sword of 1000 Truths because your server screwed up the transaction =)
> 3 votes

---
Tags: multiplayer, server, resource-management
---


# Question
Title: Compare new Vector2 position with previous Vector2 position
I'm trying to place different objects in the game area like a grid, but I have some problem with my method that creates this objects and there positions. I'm trying to store each new positions in a List and then compare each new positions with the ones in the List before it's OK to use it as a new position in the grid of the game area. I only want to use each random position once. Help is preciated! Thanks!

Perhaps ther is a better way to do this?

```
    public void AddItemsToGameArea(ContentManager content)
    {
        foreach (string buildingPart in contentHouseOne)
        {
            Vector2 newPosition = NewRandomPosition;
            if (!checkPreviousPositions)
            {
                listHouseParts.Add(new HousePart(content, buildingPart, newPosition));
                listUsedPosition.Add(newPosition);
                checkPreviousPositions = true;
            }
            else
            {
                for (int i = 0; i < listUsedPosition.Count(); i++)
                {
                    // Check??
                }

            }
        }
    }

    public Vector2 NewRandomPosition
    {
        get
        {
            return new Vector2(gridPixels * Game1.random.Next(1, 8), gridPixels * Game1.random.Next(1, 8));
        }
    }

```

# Answer
From your code, it looks like one can create a conceptual grid, index it, and then convert a grid index to a vector position. If so, then your problem is to choose random unique grid indices from a given range of indices. In other words, you want to create a random permutation of the indices in this range.

Here is a code sample on stackoverflow for C#, but I have not checked the performance characteristics of shuffle.
> 1 votes

# Answer
From your code I can understand that you might be comparing the floats directly. Comparison will not directly as you think in case of floats.

Try checking for the difference and decide whether they are equal or not. Because floating point precision is a problem all the times.

Just go through these links which a programmer must know. http://docs.oracle.com/cd/E19957-01/806-3568/ncg\_goldberg.html

PS: As its tagged XNA, vector2 has floats as attributes. Please complete your question for clear details.

Hope this helps.
> 0 votes

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


title: Simulating probability

text:
# Question
Title: Simulating probability
Stupid stupid question but here we are..

so, I want to generate some random events for an iPhone game but I guess this could be applied to any game written with a framework that suppports calls to "C" functions as I am using CCRANDOM that calls the random(void) function from the **C stdlib.h**.

I have written a function "verifyEvents" that I call each time I load a particular view (game scene).

To associate a probability to an event I assigned a value to each event (e.g. kill player: 0.05, give extra bonus 0.08).

In the function I generate a random number using CCRANDOM\_0\_1() and if the number is less than the assigned value I trigger the event (below there is the code).

**Is this the best approach or do you use something else in your games?**

```
-(void) verifyEvents
{
    float value = CCRANDOM_0_1() ;
    float eventPValue = 0.05f;

    if(value<eventPValue){
        CCLOG(@"EVENT!");
    }
}

```

PS: CCRANDOM\_0\_1() is defined as following:

```
#define CCRANDOM_0_1() ((random() / (float)0x7fffffff ))

```

# Answer
> 4 votes
Yes, your general approach is fine (define a subset of some range as the "activation" range and produce a random number, if that number falls into the activation range you trigger something, otherwise you don't) -- provided your method of random number generation produces a sufficient distribution for your needs.

As is noted in the comments, there are various implementation details that could factor in to whether or not your RNG is sufficient.

This isn't directly related to your question, but this article on probability in games was linked recently in the #gamedev IRC channel on Afternet, and I thought you might find it interesting reading.

# Answer
> 2 votes
Since I can't comment, I have to point to people suggesting what RAND\_MAX should be, that RAND\_MAX is implementation defined, and you can easily determine it with a little program.

```
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char ** argv)
{
    printf("RAND_MAX = %i\n", RAND_MAX);
    return 1;
}`

```

On my machine this gives `RAND_MAX = 2147483647`, much like what the gcc manual says. I would suggest an approach of

```
#define CCRANDOM_0_1() ((random() / (float)RAND_MAX ))

```

but actually, I would make this a function

```
float CCRANDOM_0_1() { return (random() /  (float)RAND_MAX) }

```

and also realize you probably want to seed the random number generator too. I wouldn't worry about the quality of your random number generator unless it becomes an apparent issue.

Back to your original question, I am not sure I fully understanding what you are trying to ask. Are you asking us if this is the best place to do this? They best way to do this? I think your code is generally fine, although I tend to be a "if it works" type programmer.

---
Tags: random, events
---


# Question
Title: I need to make a create-a-class system like in COD
I need to make a create-a-class system like in COD but I don't know what code I need. I am also wondering if I have to make a photoshop image for every way it could look or do I type in the code to load a certain image.

# Answer
In your player class you would need say 3 power up classes declared, in your constructor for your class you could set them as default power ups. Then in the player class you would need a get and set method, a get method to return the current power ups and set method to set them.

For your actual powerups just have an image stored in the class and draw that when you create the class object.
> 0 votes

---
Tags: c#, graphics-programming
---


# Question
Title: What exactly are sprites and entities and what are the differences between the two?
Well I was looking at a few game based tutorials, as well as articles. I found out about two terms:

`Entities` and `Sprites`. Now they seem related but different, what is each and how are they the same and/or different?

I have some basic ideas already:

> 1. An entity is an item/thing/object/person any object that can be interacted with in the world.
> 2. A sprite is like an entity, but usually for NPCs/players/monsters.
> 3. Or a sprite can be the name of a picture assigned to a specific entity.

Do I have the right idea or are sprites and entities something completely different?

# Answer
> 7 votes
An entity is a thing which exists in the world that is not represented by terrain. Entities generally have a position in the world, collision with the terrain and/or other entities, etc.

A sprite is a 2D bitmap that is drawn to the screen somewhere. Entities can *have* sprites, but they don't have to (in which case, they generally aren't drawn), but sprites cannot have entities. A sprite is purely a visual construct.

Sprites do not even *have* to be associated with entities at all. Particle systems, which are usually just visual fluff (ie: don't have gameplay effects) will generate one or more sprites.

In short, you need a separation between what is happening in terms of the game and what the player is seeing. The player sees sprites, while the gameplay code deals with entities and collision regions.

Sprite-less entities are often used for just their collision-detection properties. That is, you place an entity somewhere in the world and set something to happen when the player or something else touches their collision region. This lets you know when the player has reached a location or something.

---
Tags: sprites
---


# Question
Title: Language and learning of an MMO Game server
I am creating a MMO using XNA framework for the client and want to create the server using .Net sockets in C#. I am not a total rookie to network programming, but I am having trouble finding resources, and learning material on developing a game server or learning .Net Sockets. I scanned the MSDN library for quite a while but I feel a tutorial or a step by step book would not go amiss. I considered a WCF program for the server but I want a more educated persons opinion before traveling down that road.

What do you think? Is there a reference I overlooked? Would WCF be appropriate?

# Answer
This creators club thread suggests that WCF has some unnecessary overhead compared to just using the lower level socket API.

Have you looked at a third party library like Photon? They're built on top of Enet (C++) and allow you to add logic via .NET. They handle providing infrastructure like message channels, packaging multiple messages, and reliable UDP. There's also Lidgren.

Ryzom is a MMORPG that has open sourced their game.

And be sure to check GameDev.net's section on multiplayer programming.
> 3 votes

---
Tags: mmo, server, .net
---


# Question
Title: How do I play background music in Slick/LWJGL?
I'm trying to play music in the background for my opening menu, but cant seem to find a tutorial specifically on how to play a music file. Does anyone know how this can be accomplished?

# Answer
```
@Override
public void init(GameContainer gc) throws SlickException {
    Music openingMenuMusic = new Music("res/openingMenuMusic.ogg");

    openingMenuMusic.loop();
}

```

http://slick.cokeandcode.com/javadoc/org/newdawn/slick/Music.html
> 2 votes

---
Tags: java, lwjgl, music, slick
---


# Question
Title: Using pixel art on small high resolution screens
I'm making a game and I would like to utilize pixel art as my style. But I faced a problem, modern displays on my target platform (iOS) have extremely high resolution. So if my artist makes me some sprites in 1 to 1 pixel resolution, each character sprite will look like 2x3 millimeters, and that's not what I want.

How do I fix this problem? Do i just use 4 pixel blocks as 1 pixel in my art, or there is some other way?

Another question, is how do I utilize high-crisp display of those devices with pixel art?

How do I go with using images on older devices? Do I have to make double assets or downscale/upscale some images?

# Answer
> 5 votes
There are various scaling algorithms that are specifically crafted for enlarging pixel art for modern displays. They usually work with factors 2x or 3x and produce nice non-blurred and non-blocky results.

Take a look at this Wikipedia article, which has many examples.

# Answer
> 0 votes
You could always upscale your graphics with a nearest neighbor interpolation to keep the pixel-style. When you do this, only scale by integer amounts, eg. 2x, 3x etc.

The problem with this is that you'll have to create upscaled versions for regular- and retina-displays. Personally I would rather keep the original artwork and scale it on the device (eg. via OpenGL).

The advantage of this approach is that it uses less texture memory (you can pack a *lot* of sprites into a 1024x1024 or 2048x2048 atlas) and will also produce a smaller app size. To achieve the desired scaling, you could either scale your `CCLayer` by the desired factor or use the `camera` property of the layer and set the eye position to a closer value.

To achieve a pixel-look even with scaled textures you should set the texture scale-mode to `GL_NEAREST`. There's a shortcut function for that, called `setAliasTexParameters`. Eg.

```
[[mySprite texture] setAliasTexParameters];

```

Please note that this affects the texture, not only the sprite at hand. So if you're using a texture-atlas, the whole atlas will be affected by that. But I think this is really useful behavior in your case.

---
Tags: cocos2d-iphone, ios, pixel
---


title: MasterMind Game Algorithm Problem

text:
# Question
Title: MasterMind Game Algorithm Problem
Please find below the code that I use to make a MasterMind like game. For now people can see the PC selection so I can check if my algorithm works. Further more colors are only as visual part and don't have any functionality in the code.

My main problem is that my algorithm populates the matched array correctly but when it's time to count variable "a" it always brings me "zero"

I have tried to explain with details what every part of my code does but if you have further questions please don't hesitate to post.

```
    <!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<style>
#red {background-color : red;}
#yellow {background-color : yellow;}
#blue {background-color : blue;}
#green {background-color : green;}
</style>
</head>
<body>
<div id="firstcolor" name="firstcolor">
<script>
var x1 = Math.floor((Math.random()*4)+1); // here PC selects the first random number (color)
document.write(x1);
if(x1==1){
$("#firstcolor").css({'background-color': 'red'});
}
else if (x1==2){
$("#firstcolor").css({'background-color': 'yellow'});
}
else if (x1==3){
$("#firstcolor").css({'background-color': 'blue'});
}
else if (x1==4){
$("#firstcolor").css({'background-color': 'green'});
}
</script>
</div>
<div id="secondcolor">
<script>
var x2 = Math.floor((Math.random()*4)+1);  // here PC selects the second random number (color)
document.write(x2);
if(x2==1){
$("#secondcolor").css({'background-color': 'red'});
}
else if (x2==2){
$("#secondcolor").css({'background-color': 'yellow'});
}
else if (x2==3){
$("#secondcolor").css({'background-color': 'blue'});
}
else if (x2==4){
$("#secondcolor").css({'background-color': 'green'});
}
</script>
</div>
<div id="thirdcolor">
<script>
var x3 = Math.floor((Math.random()*4)+1);  // here PC selects the third random number (color)
document.write(x3);
if(x3==1){
$("#thirdcolor").css({'background-color': 'red'});
}
else if (x3==2){
$("#thirdcolor").css({'background-color': 'yellow'});
}
else if (x3==3){
$("#thirdcolor").css({'background-color': 'blue'});
}
else if (x3==4){
$("#thirdcolor").css({'background-color': 'green'});
}
</script>
</div>
<div id="fourthcolor">
<script>
var x4 = Math.floor((Math.random()*4)+1);  // here PC selects the fourth random number (color)
document.write(x4);
if(x4==1){
$("#fourthcolor").css({'background-color': 'red'});
}
else if (x4==2){
$("#fourthcolor").css({'background-color': 'yellow'});
}
else if (x4==3){
$("#fourthcolor").css({'background-color': 'blue'});
}
else if (x4==4){
$("#fourthcolor").css({'background-color': 'green'});
}
</script>
</div>
<form name="myForm" action="" method="post" onsubmit="return false">
<select id="firstselection" name="first" onchange="saveSelections(this)">
  <option >Choose</option>
  <option id="red">1</option>
  <option id="yellow">2</option>
  <option id="blue">3</option>
  <option id="green">4</option>
  </select>
<select id="secondselection" name="second" onchange="saveSelections(this)">
  <option >Choose</option>
  <option id="red">1</option>
  <option id="yellow">2</option>
  <option id="blue">3</option>
  <option id="green">4</option>
</select>
<select id="thirdselection" name="third" onchange="saveSelections(this)">
  <option >Choose</option>
  <option id="red">1</option>
  <option id="yellow">2</option>
  <option id="blue">3</option>
  <option id="green">4</option>
</select>
<select id="fourthselection" name="forth" onchange="saveSelections(this)">
  <option >Choose</option>
  <option id="red">1</option>
  <option id="yellow">2</option>
  <option id="blue">3</option>
  <option id="green">4</option>
</select>
<button onclick="showSelections()">Show choices</button>
</form>
<script>
var choices = []; // in this array i save the options that the player choosed from the drop down lists
function saveSelections(info) { // that's the function that stores the options that the player did did
 if (info.value != '') {
   choices.push(info.options[info.selectedIndex].text);
 }
}
function showSelections(){
var matched =[]; // In this array i store the selections of the player that are correct numbers (colors) and are in the correct positions.
var colors = [x1,x2,x3,x4]; // In this array i store the random number (color) selections that the PC did.
var a=0; // Variable "a" is a variable that counts how many numbers are correct but in the wrong place.
for (var i=0 ; i < choices.length ; i++) // with this for loop i check "choices array" with "colors array" position by position
if (choices[i] == colors[i]){ // and if their value match
matched.push(choices[i]); // i populate the "matched array" with this value otherwise i populate the matched array with the value "zero"
choices[i]=0 // Also i change the value of "color and choices array" to zero for these positions so i know and won't check these positions again.
colors[i]=0} //
else if (choices[i] != colors[i]){ // here as i said if the values of "choices array" and "colors array" don't match i put a value "zero" in this position
matched.push(0);} // by doing this i can count later on how many values in this array are NOT "zero" and get the number of correct number (colors) in the correct position.
for ( var j=0 ; j<choices.length ; j++) // with this for loop i can check which selected number (colors) are correct but in the wrong place
if ((choices[j] != 0) && (colors.indexOf(choices[j]) != -1)){ // if this position has NOT value "zero AND the value of choices is contained in the colors array
var a =a+1; // THEN the variable "a" is increased by +1
colors[colors.indexOf(choices[j])]=0;} // and the position that was found in "colors array" is getting value "zero" so i won't count this position again.
alert("matched "+matched); // pop ups an alert with the "matched array"
alert("variable a "+a); // pop ups an alert with the count of "a" variable
};
</script>
 </body>
</html>

```

# Answer
* Please indent JS properly, would've appreciated if you used jsFiddle or something.
* You're redeclaring a in the same scope, please avoid that. (**it might just solve your problem**)
* Use ids and classes.
> 2 votes

---
Tags: javascript
---


title: GLSL Shader Editors for Linux

text:
# Question
Title: GLSL Shader Editors for Linux
Are there any good IDE's for linux that lets us edit GLSL shaders and visualize their effect?

Note : Shader Designer By Typhoon Labs is a good option but I am looking for alternatives as this software has some issues with Ubuntu 11.10

# Answer
Try Shader Maker or Lumina.
> 7 votes

# Answer
Try using QtCreator, the latest version has GLSL shader support, code completition and syntax highlighting.
> 2 votes

---
Tags: shaders, glsl, linux
---


title: Learning storywriting - where to start?

text:
# Question
Title: Learning storywriting - where to start?
Over the years, games that affected me emotionally convinced me that storywriting is a very rewarding work.

Where could one start to get guidance for learning storywriting for games? I haven't really done indepth storywriting for all my life though.

I thought about learning from novelists or screenplay writers. But it seems the general consensus is that learning to write stories for games is a different animal compared to writing novels or screenplays.

**EDIT:** The kind of story I want to write is deep and emotional, which may require years of practice.

# Answer
Well the basic principles stay the same with story writing as novels. One of the things that are very important in writing a screenplay is, you should develop a broader imagination on how to build a character and to what extent you wish for the character to be the focus of your/your audiences attention. I'd also recommend analyzing characters from games/movies..
> 6 votes

# Answer
I have a few links here:

In short words:

1. Grab your character.
2. Grab your main key in your story (for example, in Super Mario, "save the princess").
3. Grab your checkpoints and/or enemies.
4. Write your way to Rome.
> 4 votes

# Answer
I recommend you read the book "David Perry on Game Design". He brings up some important key points in compelling story telling, using the Hero's Journey as example.
> 2 votes

---
Tags: storyboard
---


title: What can I do with an old XNA game?

text:
# Question
Title: What can I do with an old XNA game?
I have this little amusing game that I made in my second year of high school, and I'm rather impressed with it. It isn't anything that I could present in any style of major game conference or anything, it is simply a castle-defense I enjoyed creating greatly that got me through my programming course with highest grades. It is simply too small to do anything big with, I made the majority of it in a single week Easter holiday, but I still want to share it. It was made in C#, Visual Studio 2008, XNA 3.1. It can be played by either Xbox controller connected to the computer, or by keyboard. It relies heavily on XNA codes, I only thought of making things work so I saw it and not for everyone else. Now, my question.

If I want to share it, is this possible, where do I do it, and what should I expect for incidents? I am entirely new to the concept of sharing my game online, so I don't even know where to start. Is the game simply too old? Is there someplace similar to, like, Newgrounds except for XNA games? What could I possibly release the game for?

This kind of question must arise all the time, so I don't mind if I'm linked to some other question I've been unable to locate. All questions I've been able to find are asked before the people have even started the project, which is possibly smart. Me, I'm already done with this game and I'm wondering what I can do with it.

Anyone who can sate my curiosity?

# Answer
> 4 votes
With a few edits you could probably get it on the windows phone or xbox indie games store?

For the phone you would have to make sure the game follows the rules which have been set by microsoft for uploading games. I've never uploaded to the xbox indie games store before but I'm sure its not difficult!

EDIT:

http://create.msdn.com/en-US/home/about/how\_it\_works\_submit

# Answer
> 3 votes
If you just want to share it and you don't want to set up your own website for that purpose, you could always use any file hosting service and share the link via gaming forums. It doesn't get much easier than that.

However, as people are wary (or at least should be) of downloading executables from an unknown source, you could always share the code itself through something like Sourceforge. You can quite easily set up an online repository, forum, wiki, all sorts of things, depending how much effort you want to put into it. That way, people can still download the executable, but can also verify the code that it contains nothing harmful/malicious. Also, if your game contains something that piques someone's interest, your game might, with your consent, get developed further into something even better.

# Answer
> 3 votes
You are in the catbird seat. You have a complete and working game. Your options are limited only by how much additional effort you'd like to put into this game. In my mind you have three basic options:

1. Publish to Microsoft Store (Windows Phone Indie / Xbox Indie)
2. Drop it on a file share somewhere and have people download it
3. Open source it on Github (or whatever repo you prefer)

For option #1 you'd probably need to modify it a bit to conform to the rules of the marketplace. Depending on how your game works, this could be a minimal effort or a huge task, but you have the opportunity to earn a bit of money (probably not much, but you might eventually buy yourself a very nice dinner, and maybe even more, without seeing your game its hard to say). If your game is really good, you could even try publishing it to Steam, but their requirements are much more strict than Xbox Live Indie games.

For option #2, you can just put it up there and link to it in some online forms (though not here, maybe in chat though).

For option #3, again you don't have to make any changes, you can just put it up as is.

# Answer
> 1 votes
have a look at indiecity, you never know you may make a few quid (dollars!)

depending on the game also, it shouldnt be too hard to release on WP7

# Answer
> 1 votes
You might get some added attention from the XNA community by uploading your project to CodePlex. It's Microsoft-hosted and thus you can expect a lot of C#/.NET stuff. A lot of open-source XNA games, engines and frameworks are easily found there.

# Answer
> 1 votes
Using monogame you could publish it to the Win8 store and even the Apple store. Perhaps you could make some money on it there.

---
Tags: xna, c#, publishing
---


title: XNA stuttering at regular intervals

text:
# Question
Title: XNA stuttering at regular intervals
I'm trying to do hardware instancing but I'm hitting some strange performance problem. The average framerate is around 45, but it's extremely choppy.

* Windowed
* SynchronizeWithVerticalRetrace = false
* IsFixedTimeStep = false
* PresentationInterval = PresentInterval.Immediate

The image below shows my measured timing (with `Stopwatch`). The topmost graph is the time spent in the `Draw` method and the bottom graph is the time from the end of `Draw` until the start of `Update`

The spikes are almost exactly 1 second apart and are always 2,3,4 or 5 times the usual time. The frames immediately following the spike take no time at all. I have checked that it is not the garbage collector.

I'm currently instancing a mesh consisting of 12 triangles and 36 vertices as a triangle list (I know it's not optimal, but it's just for testing) with 1 million instances. If I batch the instancing draw calls into small parts of 250 instances each the problem is alleviated, but cpu usage increases significantly. The run above is at 10000 instance per draw call, which is much easier on the cpu.

If I run the game in fullscreen the bottom graph is almost non-existent, but the same problem occurs now in the `Draw` method.

Here is a run inside PIX, which makes no sense to me at all. It seems for some frames there is no rendering done...

Any idea, what might be causing this?

**EDIT**: As requested, the relevant portions of the render code

A `CubeBuffer` is created and initialized, then filled with cubes. If the amount of cubes is above a certain limit, a new `CubeBuffer` is created, and so on. Each buffer draws all instances in one call.

Information needed only once is `static` (vertex, index buffer and vertex declaration; although it makes no difference so far). The texture is 512x512

Draw()

```
device.Clear(Color.DarkSlateGray);
device.RasterizerState = new RasterizerState() {  };
device.BlendState = new BlendState { };
device.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true };

//samplerState=new SamplerState() { AddressU = TextureAddressMode.Mirror, AddressV = TextureAddressMode.Mirror, Filter = TextureFilter.Linear };
device.SamplerStates[0] = samplerState
effect.CurrentTechnique = effect.Techniques["InstancingTexColorLight"];
effect.Parameters["xView"].SetValue(cam.viewMatrix);
effect.Parameters["xProjection"].SetValue(projectionMatrix);
effect.Parameters["xWorld"].SetValue(worldMatrix);
effect.Parameters["cubeTexture"].SetValue(texAtlas);
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
    pass.Apply();

foreach (var buf in CubeBuffers)
    buf.Draw();
base.Draw(gameTime);

```

CubeBuffer

```
[StructLayout(LayoutKind.Sequential)]
struct InstanceInfoOpt9
    {
    public Matrix World;
    public Vector2 Texture;
    public Vector4 Light;
    };

static VertexBuffer geometryBuffer = null;
static IndexBuffer geometryIndexBuffer = null;
static VertexDeclaration instanceVertexDeclaration = null;
VertexBuffer instanceBuffer = null;
InstanceInfoOpt9[] Buffer = new InstanceInfoOpt9[MaxCubeCount];
Int32 bufferCount=0

Init()
    {
    if (geometryBuffer == null)
        {
        geometryBuffer = new VertexBuffer(Device, typeof (VertexPositionTexture), 36, BufferUsage.WriteOnly);
        geometryIndexBuffer = new IndexBuffer(Device, typeof (Int32), 36, BufferUsage.WriteOnly);
        vertices = new[]{...}
        geometryBuffer.SetData(vertices);
        indices = new[]{...}
        geometryIndexBuffer.SetData(indices);

        var instanceStreamElements = new VertexElement[6];
        instanceStreamElements[0] = new VertexElement(sizeof (float)*0, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 1);
        instanceStreamElements[1] = new VertexElement(sizeof (float)*4, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 2);
        instanceStreamElements[2] = new VertexElement(sizeof (float)*8, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 3);
        instanceStreamElements[3] = new VertexElement(sizeof (float)*12, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 4);
        instanceStreamElements[4] = new VertexElement(sizeof (float)*16, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 5);
        instanceStreamElements[5] = new VertexElement(sizeof (float)*18, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 6);

        instanceVertexDeclaration = new VertexDeclaration(instanceStreamElements);
        }

    instanceBuffer = new VertexBuffer(Device, instanceVertexDeclaration, MaxCubeCount, BufferUsage.WriteOnly);
    instanceBuffer.SetData(Buffer);
    bindings = new[]
        {
        new VertexBufferBinding(geometryBuffer),
        new VertexBufferBinding(instanceBuffer, 0, 1),
            };
    }

AddRandomCube(Vector3 pos)
    {
    if(cubes.Count >= MaxCubeCount)
        return null;
    Vector2 tex = new Vector2(rnd.Next(0, 16), rnd.Next(0, 16))
    Vector4 l= new Vector4((float)rnd.Next(), (float)rnd.Next(), (float)rnd.Next(), (float)rnd.Next());
    var cube = new InstanceInfoOpt9(Matrix.CreateTranslation(pos),tex, l);

    Buffer[bufferCount++] = cube;

    return cube;
    }

Draw()
    {
    Device.Indices = geometryIndexBuffer;
    Device.SetVertexBuffers(bindings);
    Device.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0, 36, 0, 12, bufferCount);
    }

```

Shader

```
float4x4 xView;
float4x4 xProjection;
float4x4 xWorld;
texture cubeTexture;

sampler TexColorLightSampler = sampler_state
{
texture = <cubeTexture>;
mipfilter = LINEAR;
minfilter = LINEAR;
magfilter = LINEAR;
};

struct InstancingVSTexColorLightInput
{
float4 Position : POSITION0;
float2 TexCoord : TEXCOORD0;
};

struct InstancingVSTexColorLightOutput
{
float4 Position : POSITION0;
float2 TexCoord : TEXCOORD0;
float4 Light : TEXCOORD1;
};

InstancingVSTexColorLightOutput InstancingVSTexColorLight(InstancingVSTexColorLightInput input, float4x4 instanceTransform : TEXCOORD1, float2 instanceTex : TEXCOORD5, float4 instanceLight : TEXCOORD6)
{
float4x4 preViewProjection = mul (xView, xProjection);
float4x4 preWorldViewProjection = mul (xWorld, preViewProjection);

InstancingVSTexColorLightOutput output;
float4 pos = input.Position;

pos = mul(pos, transpose(instanceTransform));
pos = mul(pos, preWorldViewProjection);

output.Position = pos;
output.Light = instanceLight;
output.TexCoord = float2((input.TexCoord.x / 16.0f) + (1.0f / 16.0f * instanceTex.x),
                         (input.TexCoord.y / 16.0f) + (1.0f / 16.0f * instanceTex.y));

return output;
}

float4 InstancingPSTexColorLight(InstancingVSTexColorLightOutput input) : COLOR0
{
float4 color = tex2D(TexColorLightSampler, input.TexCoord);

color.r = color.r * input.Light.r;
color.g = color.g * input.Light.g;
color.b = color.b * input.Light.b;
color.a = color.a * input.Light.a;

return color;
}

technique InstancingTexColorLight
{
 pass Pass0
 {
 VertexShader = compile vs_3_0 InstancingVSTexColorLight();
 PixelShader = compile ps_3_0 InstancingPSTexColorLight();
 }
}

```

# Answer
> 3 votes
I'm guessing that your performance is GPU-bound. You're simply asking your graphics device to do more work per unit time than it's capable of handling; 36 million vertices per frame is a pretty decent number, and hardware instancing can actually increase the amount of processing work necessary on the GPU side of the equation. Draw fewer polygons.

Why does reducing the batch size make the problem go away? Because it makes the CPU take longer to process a frame, which means it's spending less time sitting inside of `Present()` waiting for the GPU to finish rendering. That's what I think it's doing during that gap at the end of your `Draw()` calls.

The reason behind the specific timing of the gaps is harder to divine without understanding the whole of the code, but I'm not sure it's important, either. Do more work on the CPU, or less work on the GPU, so that your workload is less uneven.

See this article on Shawn Hargreaves' blog for more information.

# Answer
> 2 votes
I think you have a garbage problem... maybe you are creating/destroying to many objects and that spikes are the garbage collector routine working...

be sure to reuse all your memory structures... and don't use 'new' too often

---
Tags: xna, performance
---


# Question
Title: How change the size of sprite in cocos2d?
I want to change the scale of sprite like a paper in 'Paper Toss' game.

'Paper Toss' is the game is available on the App store. I want to make a sprite like a paper and change the scale of sprite like a paper in 'paper Toss'.

# Answer
You can change the size of a sprite like so:

```
[mySprite setScaleX: newWidth/mySprite.contentSize.width];
[mySprite setScaleY: newHeight/mySprite.contentSize.height];

```
> 4 votes

---
Tags: iphone, cocos2d-iphone, ios, box2d, objective-c
---


# Question
Title: Cocos2d Box2d contact listener call different method in collided object
I have the building object, when it collides with another object I want to call some method inside it. *Building.mm*

```
-(void)printTest
{
    NSLog(@"printTest method work correctly");
}

```

in my ContactListener I'm trying to call it so: *ContactListener.mm*

```
#import "ContactListener.h"
#import "Building.h"
void ContactListener::BeginContact(b2Contact* contact)
{
    b2Body* bodyA = contact->GetFixtureA()->GetBody();
    b2Body* bodyB = contact->GetFixtureB()->GetBody();

    Building *buildA = (Building *)bodyA->GetUserData();
    Building *buildB = (Building *)bodyB->GetUserData();
    if (buildB.tag == 1) {
        NSLog(@"tag == 1");
    }
    if (buildA.tag == 2) {
        NSLog(@"tag == 2");
        [buildA printTest];
    }
}

```

**NSLog(@"tag == 2");** work correctly, **but \[buildA printTest\];** get error

> Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-\[CCSprite printTest\]: unrecognized selector sent to instance 0x18595f0'

Obviously I'm referring to the wrong object. How I can get different method and property in contacted objects from contactlistener class?

# Answer
> 1 votes
I found a solution on my own.

When I create the body, I forgot to set the `UserData` correctly.

```
body->SetUserData(self);

```

Adding the line above (in `Building.mm`) solved the problem.

---
Tags: collision-detection, cocos2d-iphone, box2d
---


title: Grouping game objects

text:
# Question
Title: Grouping game objects
I'm trying to create a simple turn based console (command line) game but I'm confused of what approach to use when creating classes for objects. My concern is maintainability and flexibility.

First Approach:

```
class Weapon{
    ...
}

class Sword:Weapon{
    ...
}

class ShortSword:Sword{
    ...
}

class TwoHandedSword:Sword{
    ...
}

class Axe:Weapon{
    ...
}

class HeavyAxe:Axe{
    ...
}

```

Second Approach:

```
class Sword{
    SwordType type;
    ...
}

class Axe{
    AxeType type;
    ...
}

```

So which is better, first or second? Why?

Important Note: I'm a beginner in game development.

# Answer
Essentially what Aron\_dc said, though I would go even farther. Generally you should try to keep your class-structure as shallow as possible and separate code(algorithms) from data(attributes).

You only need one weapon class for melee/instant-hit-weapons. This class can either instantly check what it hit, or is given an object to apply damage to. This includes ranged weapons, that are insta-hit, like a laser (a gun might be too, if you don't want to model it too realistically).

```
class InstantWeapon{
  Sprite sprite; //should be inherited from EquippableObject, or DrawableGameObject, or something
  WeaponType weaponType;
  DamageType dmgType;
  Double dmgOnHit;
  ...

  void Hit(ObjectWithHitPoints o){...}
  void Hit(Ray hitRay)
}

```

A second class is used for particle-spawning weapons, such as a wand of fireball. These weapons don't damage directly, but instead spawn a new object that moves according to its own logic and does damage when it collides with an object. In this case the particle holds all information needed (damage amount and type, radius etc) and it makes it easy to give them custom logic (homing missile, or loosing damage the longer it travels, ...)

```
class ParticleSpawner{
  InteractiveParticle sampleParticle;

  void Fire(Vector3 position, Vector3 direction){
    ParticleEngine.Add(sampleParticle.Clone());
  }
}

```

Depending on how complex you want your weapon and damage system to be you can have a look at the component pattern. The basic principle is that you would have one `Weapon` class and a list with multiple instances of the `DamageComponent` class. The `DamageComponent` class holds the algorithm and data for all weapon effects that apply to this one weapon.

```
class Weapon{
  List<DamageComponent> damageComponents;

  void Fire(Ray hitRay){
    foreach(component : DamageComponent)
      component.Apply(hitRay);
  }
}

```

Each component can now spawn a fireball, reduce enemy armor, do standard damage, apply an "on fire" effect to targets, etc. Additionally each component can handle the weapon-swing the way it wants. Get only the target directly in front, or cleave in a wide arc, etc...

Also note that the component system can come in handy in other places.

* Different types of armor components protect differently against different damage types
* Particle on update components can influence a single particle in different ways
* Abilities granted by skills or objects only need to be implemented once, since they simply add the can-fly or the can-see-underground component to the player.

Generally it empowers you to create lots of small components that each on their own don't do much, but can form extremely complex systems, since their combinations grow exponentially with each new implementation.

The resulting effects of the system can become quite complex, which is nice, when you want emergent behavior and model things in a complex fashion, but that makes it harder to do things like weapon balance or enemy difficulty. For a popular example, look at Diablo3's with their random ability components. Certain combinations are way stronger than the others.
> 11 votes

# Answer
Disadvantages of the first one (subclassing):

1. you clutter your code with many sublclasses, that you obviously don't need
2. you have to keep track of your depth of inheritance (?) if you change something in your weapon classification hierarchy
3. I don't think there are many advantages to this approach

Disadvantages of the second one (Strategy pattern):

1. You still have many classes (but they don't stick as tough together as in the 1st variant)

Advantages of the second one (Strategy pattern):

1. There are many ways of reusing your classes this way. Want a cannon that is also a sword? Just put the two types together in a class and implement a supertype SwordWithCannon ;) (you can't do that with the first approach that easily)
2. Less code
3. You could even change the behaviour of the weapon during the game. So your Sword gets blunt, just change the swordType to "bluntSword" (or something similar)

If your weapons only differ in some stats, you dont have to use any of this. Just put the stats in the base class and fill them accordingly to your wishes (boolean twoHandedness,int damage, String name, ....).
> 8 votes

# Answer
If you only change parameters, then there is no need for inheritance. But, if you plan to add different functionality, then I suggest you use sub classes. I doubt that you will have additional functionality in a console game, only parameters such as `damage` and `addsAttributes`.

But this is really specific to the implementation.
> 2 votes

# Answer
I tend to avoid using inheritance as much as possible when it comes to classifying objects based on *data* used in games as opposed to classifying *systems* used in games. What I mean is, it may make sense to have a `Animator` class and then a `SpriteAnimator` and `TileAnimator` inherit the `Animator` if the behavioral differences will have to be hard-coded discretely in their functions. But if the differences in behavior of a `Sword` and an `Axe` are simply going to be determined by the values in a group of stats, things that are best treated as data containers for games, they should just be defined by parameters that all objects share.

If you're familiar with the MVC pattern, using multiple inheritance to make similar data containers is like creating a bunch of controllers that only differ in the values in its data members. Obviously it's better to just have one controller and rely on the model to fetch the values that are needed.

You didn't go in-depth as to what properties your classes have, but weapon inventory seems to benefit a lot more from a *data-driven* design. So have just one Weapon class and assign it different properties, and to name them, the name is simply a read-only string member.

If you want to have hybrid items (as the `SwordWithCannon` mentioned before), perhaps then define a Weapon class that can take properties of multiple Weapon objects, ie. in a Vector or List containing one or more sets of properties.
> 2 votes

---
Tags: architecture
---


title: Text fields in a java canvas

text:
# Question
Title: Text fields in a java canvas
So I'm trying to have some form of input in my game and I understand all the keyPresses and whatnot but the only issue is I have no idea of adding a textfield to the game. JTextfield doesnt seem to appear so I started taking keypresses and adding them to a string but this proves to ether be too slow or too fast. Is there any way of adding a textfield to the game?

I'm using just plain java and swing.

Here is a code snippet:

```
JFrame frame = new JFrame("Game");
    //Sorts out JFrame variables and settings.
    frame.setLayout(null);
    setBounds(0,0,800,600);
    frame.add(this);
    frame.setSize(800,600);
    frame.setResizable(false);
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            gameRunning = false;
            System.exit(0);
        }
    });
    frame.addKeyListener(this);
    addKeyListener(this);
    addMouseListener(this);
    addMouseMotionListener(this);
    int columns = 25;
    TextField localTextField = new TextField("Text", columns);
    Insets insets = frame.getInsets();
    Dimension size = localTextField.getPreferredSize();
    localTextField.setBounds(25 + insets.left, 5 + insets.top,
                 size.width, size.height);
    frame.add(localTextField);
    frame.setVisible(true);
    //Double Buffer set up.
    createBufferStrategy(2);
    strategy = getBufferStrategy();

```

Ok, so I pressume the only way of doing this is the way in which I'm currently doing it.While the text box is open it adds all keypesses together with a slight delay between each key press. I just thought that there might have been an easy method of doing this.

# Answer
Please give some code snippets. Normally you would use a JFrame as your window and add up your elements eventually using some kind of LayoutManager.

edit after codesippet appeared:

You have 3 main problems that I can figure out from this snippet.

1. Why do you set the layout of the frame to null? Just take the standard.
2. You are missing frame.pack() before the frame.setVisible(true) this would pack all the Elements (e.g. the Textfield) according to the used layout
3. You centralize all your code to one class (this) it is your Canvas, and also key-,action-, and mouse listener. You should put them in different classes or at least make a Listener Class that handles all the logic.
> 0 votes

# Answer
One possibility:

```
int columns = 25;
TextField localTextField = new TextField("my game text", columns);

```
> 0 votes

# Answer
Please look at this visual guide to layouts, pick a suitable layout and add the textfield and canvas so that they do not overlap.

---

If you do not wish to have an actual textbox, then it sounds more like your interested in listening to the keypresses, to detect when the player holds down aswd-keys for instance. Implement a key listener and there record which keys are held down. Alternatively, if your interested in making a hang-man type game, you can record each keypress in a List or a StringBuilder.

Hiding a textbox will cause problems, pressing left key would move the caret and change the functionality for instance.
> 0 votes

---
Tags: java, html-canvas
---


# Question
Title: Number of Impressions on Admob for Revenue
Just curious for a rough estimate; how many impressions would it take to make 300 dollars, a day, in ad revenue?

# Answer
> 19 votes
It is not possible to determine an accurate estimate, because the rate of each click-through or impression changes for each ad that is displayed.

However, if we take some made up stats from http://developer.admob.com/wiki/Definitions, it gives that you could theoretically have a estimated cost-per-1000-impression (eCPM) of $1.11. Based on that, it means you would need over 270,000 **unique** impressions a day to make $300. If your eCPM was only half of that, you would have to double the numbers.

If we look at the cost-per-click model, and you assume the average cost-per-click is $0.30 (again, a made up figure obtained from the link above), then it will take 1000 **unique** clicks a day to make $300/day.

Remember, the above stats are completely made up. Each person will have a different experience and the only true way to find out is to implement it in your app and record your own stats.

# Answer
> 14 votes
I can give some stat from AdMod for a long running game to give you some ideas.

* Last 7 days: eCPM $0.21, impressions 2.7M, fill rate 99%
* Last 90 days: eCPM $0.28, impressions 31.4M, fill rate 99%
* Last 365 days: eCPM $0.32, impressions 133M, fill rate 92%

This is with AdWords enabled for when there are no graphical ads to show.

You'll also notice that there is quite a seasonal effect. eCPM varies quite a bit, so take the 32c as a baseline to figure out your $300/day. It would take ~1M impressions a day.

Also note that it depends on the frequency and placement of your ads. Too many of them will annoy the user, etc.

# Answer
> 7 votes
You may have 100,000 impressions and may be 0 revenue. It all depends on number of clicks you have which is measured by eCPM. If you had more clicks in the initial period of launch but later it decreases, you will see decrease in eCPM and your revenue if eCPM * Impressions/1000.

So, if you are fortunate and your App Users likes the ads that pops up and click on them, you make money else you may make little or no money if the users don't click.

My experience: In last 1 week, the impressions on my app went up by 5000 and no change in revenue because no one clicked on the ads appearing on my App.

Good luck...

---
Tags: android, revenue
---


title: How to obtain contrail visual effect?

text:
# Question
Title: How to obtain contrail visual effect?
I have objects moving in OpenGL ES1 application. I want some of them to leave behind contrail – like if they would emit some radiation or something.

**EDIT:** the kind of contrail is:

* light contrail – not smoke contrail,
* the same effect occurs on LCD monitors with long pixel-switch time (it is called response time AFAIK).

HERE IS THE EXAMPLE IMAGE: https://i.stack.imgur.com/w3dHZ.jpg

# Answer
> 5 votes
The example image makes it much clearer what you want. "Contrail" probably isn't the right word for this; at my company we call it a "swoosh" but other people probably call it something like "sword trail", "sword slash" or similar.

Anyway, the way to do this is basically to generate dynamic geometry, by recording the position of two points on the sword (one at the hilt, one at the tip) each frame and keeping a history for the last n frames. Then draw a triangle strip that connects these points, with a translucent or additive shader.

To make it look better, you'll probably want to fade out the trailing edge of the swoosh, e.g. using vertex alpha based on the age of each vertex. You can also generate UVs for each vertex so you can put a texture on the swoosh. Finally, if sampling the sword once per frame doesn't give you smooth enough geometry, you can interpolate additional vertices using Hermite splines (these require calculating the velocites of the two sample points each frame, which are used as tangent vectors for the splines).

---
Tags: opengl-es, graphic-effects, particles
---


# Question
Title: When I select one vertex it selects multiple vertices?
I'm trying to do some kind of a face. When I select a vertex it selects two other vertices. However, when I try to select one of the two other vertices it doesn't select them.

I want to move only one vertex to make it right.

My model is an editable poly.

Link to my model so if you want to inspect it properly.

**Front view :**

**Linked vertices :**

# Answer
> 5 votes
I don't use 3DS max, so I can't give you specific direction, but I can tell you generally what's happening. I assume you were following some kind of tutorial, so you may not remember doing this. However, it looks like **you have the model set up to be mirrored down the center**. So, selecting one vertex will mirror to the other side. Typically this is very useful for creating symmetrical models like a face. However, if you want the model to be asymmetrical, it's not so useful. Here's a video showing the use of mirror.

I suggest keeping this mirror mode on until you're finished making most of the changes to your model. Then, when you're done with that, disable it and make your asymmetrical changes.

Sorry I don't know exactly how to disable it.

---
Tags: 3dsmax, vertex
---