# Question
Title: Are the same number of tiles displayed in an isometric game regardless of phone orientation?
I would like to make an isometric RPG game that can be played with one hand in portrait mode. This will primarily be for smartphones like the iphone 6 and samsung galaxy s7. I've been looking at many examples online but most isometric smartphone games seem to be landscape games. Making Isometric Social Real-Time Games with HTML5, CSS3, and JavaScript By Mario Andres Pagella also claims that

> In isometric games, presenting the game in landscape mode is a better use of screen real state than presenting it in portrait mode.

Why is this true? Don't both orientations display the same number of tiles?

# Answer
In a typical isometric-style projection, tiles are roughly twice as wide as they are tall (depending on whether you're using true isometric or its close cousin often used in games, the 2:1 dimetric projection).

So, as you move around the tile grid, measuring out from the player's current focus, you eat up horizontal space about twice as fast as vertical.

Check out the two crops of a scene below, both using the same zoom:

(modified game image from fldr, using Kenney game assets)

* In the landscape crop, we can see every tile 3 hops away from the central focus (in white), and nearly every tile 4 hops away.
* In the portrait crop, we've already hit the edge at two hops from the center, and some of the tiles 3 hops away are missing. So although the total tile area on screen is the same, we can't see as far in all directions.

If we have things like enemies that can attack from 3 tiles away, then we'd need to zoom out to keep the game fair in a portrait crop. (But, if most of your gameplay is vertical, then the extra visibility above & below might be helpful)

So, if showing a broad flat area is important to your game, then a landscape crop might help you keep your assets larger on-screen without losing important information off the sides. Levels with a lot of vertical variation can turn this on its head though, so consider carefully what kind of game spaces you want to create.
> 4 votes

# Answer
This is a square grid shown using an isometric projection:

Note how it's wider than it's tall.

In fact, even if the grid was a rectangle with unequal sides, it still will be wider than taller, due to the nature of isometric projection.

If you use a different projection, you can reduce the width-to-height ratio but you'll never get it taller than wide. The best you can do is equal width to height, which is a top-down perspective.

The only way you'll end up with a grid that is taller than it's wide is to use non-rectangular shapes, like this (only taller):

But notice that it produces jagged edges, which are less aesthetically pleasing, and it's a bit harder to check bounds.

Some isometric games use portrait orientation though, usually because they have a lot of verticality. For example, here's *Monument Valley*, a game with lots of vertical structures, and uses portrait orientation:
> 4 votes

---
Tags: isometric, mobile
---


# Question
Title: Matching a chunk of procedurally generated world to a chunk of other world
Have you read The Chronicles of Amber by Roger Zelazny?

Imagine yourself playing in 3rd person MMO game. You spawn in the world and start to wander around. After some time, when you think, that you've learned the map, you realize, that you are in a place, that you have never seen before. You go back to the last place you were sure you know and it is still there. But the rest of the world has changed and you didn't even notice how did it happen.

I've read about procedural world generation. I've read about Perlin noise and octaves, Simplex noise, Diamond-square algorithm, about simulation of tectonic plates and water erosion. I believe I have some vague understanding of general approach in procedural world generation.

And with this knowledge I have no idea on how can you do something like written above. Every idea that comes to my mind encounters some theoretical problems. Here are some ideas I can think of:

1) "Reversible" world-generation with a seed number as input and some fully-describing-a-chunk-number

I doubt that it is even possible, but I imagine a function, that will receive a seed and produce a matrix of numbers, upon which chunks are built. And for each unique number there is an unique chunk. And a second function, that gets this unique chunk number and produces a seed, that contains this number. I've tried to make a scheme in the picture below:

2) Making chunks completely random and make a transition between them.

As Aracthor suggested. The benefits of this approach is that it is possible and it doesn't require a *magic* fuction :)

The cons this approach has in my opinion, is that it's likely not possible to have a diverse world. If you have let's say both archipelago and a continent represented by just one number and it's adjacent chunks, then wouldn't the size of a chunk be equal to continent. And I doubt that it is possible to make good-looking transition between chunks. Am I missing something?

So, in other words, you are developing a MMO with procedurally generated world. But instead of having one world, you have **many**. What approach would you take to generate worlds and how would you implement transition of player from one world to another without player noticing the transition.

Anyway, I believe you've got the general idea. How would you have done it?

# Answer
Use a slice of higher-order noise. If you used 2d noise for a height-map before, use 3D noise with the last coordinate fixed instead. Now you can slowly change the position in the last dimension to modify the terrain. Since Perlin noise is continuous in all dimensions, you'll get smooth transitions as long as you smoothly change the position where you sample the noise function.

If you want to only change the terrain far from the player, you could store the offset for every coordinate on the map and only increase but never decrease it. This way the map only gets newer but never older.

Also, take a look at Simplex noise. It's the improved version of Perlin noise and works better for more dimensions.
> 23 votes

# Answer
Your idea to split the world into several chunks is not bad. It is just incomplete.

The only problem is junctions between chunks. For instance, if you use perlin noise to generate relief, and a seed different for each chunk, and risk this to happen:

A solution would be to generate chunk relief not only from its Perlin noise seed, but as well from other chunks around it.

Perlin algorithm use values of random map around them to "smooth" themselves. If they use a common map, there would be smoothed together.

The only problem is if you change a chunk seed to make it different when the player recede, you'll have to reload chunks around too, because their borders should change as well.

This wouldn't change the size of chunks, but It would increase the minimal distance from the player to being loaded/unloaded, because a chunk must be loaded when the player see it, and, with this method, as adjacent chunks must be too.

## UPDATE:

If each chunk of your world is of a different type, the problem grows up. This is not just about relief. An costly solution would be the following:

Let's suppose green chunks are forest worlds, blue ones archipelagos and yellow ones flat deserts.
The solution here is to create "transition" zones, where your relief and ground nature (as well as objects grounded, or anything else you want) would progressively turn from one type to another.

And as you can see on this picture, the hell part to code would be little squares in chunk corners: they have to make a link between 4 chunks, potentially different natures.

So for this complexity level, I think classic 2D-world generations like Perlin2D just *cannot* be used. I refer you to @danijar answer for that.
> 5 votes

# Answer
While danijar's idea is pretty solid, you could end up storing a lot of data, if you wanted to have the local area the same and the distance shift. And requesting more and more slices of more and more complex noise. You can get all of these in a more standard 2d fashion.

I developed an algorithm for procedurally generating random fractal noise, in part based on the diamond square algorithm that I fixed to be both infinite, and deterministic. So diamond-square can create an infinite landscape, as well as my own fairly blocky algorithm.

The idea is basically the same. But, rather than sampling higher dimensional noise, you can iterate values at different iterative levels.

So you still store the values you requested before, and cache them (this scheme independently could be used to speed up an already super-fast algorithm). And when new area is requested, it is created with a new y value. and any area not requested in that request is removed.

So rather than scoping through different space in an additional dimensions. We store an extra bit of monotonic data to mix in different (at progressively larger amounts at different levels).

If the user travels in a direction the values are moved accordingly (and at each level) and new values are generated at the new edges. If the top iterative seed is changed, the entire world will be drastically shifted. If the final iteration is given a different result, then the change amount will be very minor +-1 block or so. But, the hill will still be there and the valley etc, but the nooks and crannies will have changed. Unless you go far enough, and then the hill will be gone.

So if we stored 100x100 chunk of values each iteration. Then nothing could change at 100x100 from the player. But, at 200x200 things could change by 1 block. At 400x400 things could change by 2 blocks. At 800x800 away things will be able to change by 4 blocks. So things will change and they will change more and more the further you go. If you go back they will be different, if you go too far they will be completely changed and completely lost as all the seeds would be abandoned.

Adding a different dimension to provide this stabilizing effect, would certainly work, shifting the y at distance, but you'd be storing a lot of the data for a great many blocks when you shouldn't have to. In deterministic fractal noise algorithms you can get this same effect by adding a changing value (at a different amount) as the position moves beyond a certain point.

https://jsfiddle.net/rkdzau7o/

```
var SCALE_FACTOR = 2;
//The scale factor is kind of arbitrary, but the code is only consistent for 2 currently. Gives noise for other scale but not location proper.
var BLUR_EDGE = 2; //extra pixels are needed for the blur (3 - 1).
var buildbuffer = BLUR_EDGE + SCALE_FACTOR;

canvas = document.getElementById('canvas');
ctx = canvas.getContext("2d");
var stride = canvas.width + buildbuffer;
var colorvalues = new Array(stride * (canvas.height + buildbuffer));
var iterations = 7;
var xpos = 0;
var ypos = 0;
var singlecolor = true;

/**
 * Function adds all the required ints into the ints array.
 * Note that the scanline should not actually equal the width.
 * It should be larger as per the getRequiredDim function.
 *
 * @param iterations Number of iterations to perform.
 * @param ints       pixel array to be used to insert values. (Pass by reference)
 * @param stride     distance in the array to the next requestedY value.
 * @param x          requested X location.
 * @param y          requested Y location.
 * @param width      width of the image.
 * @param height     height of the image.
 */

function fieldOlsenNoise(iterations, ints, stride, x, y, width, height) {
  olsennoise(ints, stride, x, y, width, height, iterations); //Calls the main routine.
  //applyMask(ints, stride, width, height, 0xFF000000);
}

function applyMask(pixels, stride, width, height, mask) {
  var index;
  index = 0;
  for (var k = 0, n = height - 1; k <= n; k++, index += stride) {
    for (var j = 0, m = width - 1; j <= m; j++) {
      pixels[index + j] |= mask;
    }
  }
}

/**
 * Converts a dimension into the dimension required by the algorithm.
 * Due to the blurring, to get valid data the array must be slightly larger.
 * Due to the interpixel location at lowest levels it needs to be bigger by
 * the max value that can be. (SCALE_FACTOR)
 *
 * @param dim
 * @return
 */

function getRequiredDim(dim) {
  return dim + BLUR_EDGE + SCALE_FACTOR;
}

//Function inserts the values into the given ints array (pass by reference)
//The results will be within 0-255 assuming the requested iterations are 7.
function olsennoise(ints, stride, x_within_field, y_within_field, width, height, iteration) {
  if (iteration == 0) {
    //Base case. If we are at the bottom. Do not run the rest of the function. Return random values.
    clearValues(ints, stride, width, height); //base case needs zero, apply Noise will not eat garbage.
    applyNoise(ints, stride, x_within_field, y_within_field, width, height, iteration);
    return;
  }

  var x_remainder = x_within_field & 1; //Adjust the x_remainder so we know how much more into the pixel are.
  var y_remainder = y_within_field & 1; //Math.abs(y_within_field % SCALE_FACTOR) - Would be assumed for larger scalefactors.

  /*
  Pass the ints, and the stride for that set of ints.
  Recurse the call to the function moving the x_within_field forward if we actaully want half a pixel at the start.
  Same for the requestedY.
  The width should expanded by the x_remainder, and then half the size, with enough extra to store the extra ints from the blur.
  If the width is too long, it'll just run more stuff than it needs to.
  */

  olsennoise(ints, stride,
    (Math.floor((x_within_field + x_remainder) / SCALE_FACTOR)) - x_remainder,
    (Math.floor((y_within_field + y_remainder) / SCALE_FACTOR)) - y_remainder,
    (Math.floor((width + x_remainder) / SCALE_FACTOR)) + BLUR_EDGE,
    (Math.floor((height + y_remainder) / SCALE_FACTOR)) + BLUR_EDGE, iteration - 1);

  //This will scale the image from half the width and half the height. bounds.
  //The scale function assumes you have at least width/2 and height/2 good ints.
  //We requested those from olsennoise above, so we should have that.

  applyScaleShift(ints, stride, width + BLUR_EDGE, height + BLUR_EDGE, SCALE_FACTOR, x_remainder, y_remainder);

  //This applies the blur and uses the given bounds.
  //Since the blur loses two at the edge, this will result
  //in us having width requestedX height of good ints and required
  // width + blurEdge of good ints. height + blurEdge of good ints.
  applyBlur(ints, stride, width + BLUR_EDGE, height + BLUR_EDGE);

  //Applies noise to all the given ints. Does not require more or less than ints. Just offsets them all randomly.
  applyNoise(ints, stride, x_within_field, y_within_field, width, height, iteration);
}

function applyNoise(pixels, stride, x_within_field, y_within_field, width, height, iteration) {
  var bitmask = 0b00000001000000010000000100000001 << (7 - iteration);
  var index = 0;
  for (var k = 0, n = height - 1; k <= n; k++, index += stride) { //iterate the requestedY positions. Offsetting the index by stride each time.
    for (var j = 0, m = width - 1; j <= m; j++) { //iterate the requestedX positions through width.
      var current = index + j; // The current position of the pixel is the index which will have added stride each, requestedY iteration
      pixels[current] += hashrandom(j + x_within_field, k + y_within_field, iteration) & bitmask;
      //add on to this pixel the hash function with the set reduction.
      //It simply must scale down with the larger number of iterations.
    }
  }
}

function applyScaleShift(pixels, stride, width, height, factor, shiftX, shiftY) {
  var index = (height - 1) * stride; //We must iteration backwards to scale so index starts at last Y position.
  for (var k = 0, n = height - 1; k <= n; n--, index -= stride) { // we iterate the requestedY, removing stride from index.
    for (var j = 0, m = width - 1; j <= m; m--) { // iterate the requestedX positions from width to 0.
      var pos = index + m; //current position is the index (position of that scanline of Y) plus our current iteration in scale.
      var lower = (Math.floor((n + shiftY) / factor) * stride) + Math.floor((m + shiftX) / factor); //We find the position that is half that size. From where we scale them out.
      pixels[pos] = pixels[lower]; // Set the outer position to the inner position. Applying the scale.
    }
  }
}

function clearValues(pixels, stride, width, height) {
  var index;
  index = 0;
  for (var k = 0, n = height - 1; k <= n; k++, index += stride) { //iterate the requestedY values.
    for (var j = 0, m = width - 1; j <= m; j++) { //iterate the requestedX values.
      pixels[index + j] = 0; //clears those values.
    }
  }
}

//Applies the blur.
//loopunrolled box blur 3x3 in each color.
function applyBlur(pixels, stride, width, height) {
  var index = 0;
  var v0;
  var v1;
  var v2;

  var r;
  var g;
  var b;

  for (var j = 0; j < height; j++, index += stride) {
    for (var k = 0; k < width; k++) {
      var pos = index + k;

      v0 = pixels[pos];
      v1 = pixels[pos + 1];
      v2 = pixels[pos + 2];

      r = ((v0 >> 16) & 0xFF) + ((v1 >> 16) & 0xFF) + ((v2 >> 16) & 0xFF);
      g = ((v0 >> 8) & 0xFF) + ((v1 >> 8) & 0xFF) + ((v2 >> 8) & 0xFF);
      b = ((v0) & 0xFF) + ((v1) & 0xFF) + ((v2) & 0xFF);
      r = Math.floor(r / 3);
      g = Math.floor(g / 3);
      b = Math.floor(b / 3);
      pixels[pos] = r << 16 | g << 8 | b;
    }
  }
  index = 0;
  for (var j = 0; j < height; j++, index += stride) {
    for (var k = 0; k < width; k++) {
      var pos = index + k;
      v0 = pixels[pos];
      v1 = pixels[pos + stride];
      v2 = pixels[pos + (stride << 1)];

      r = ((v0 >> 16) & 0xFF) + ((v1 >> 16) & 0xFF) + ((v2 >> 16) & 0xFF);
      g = ((v0 >> 8) & 0xFF) + ((v1 >> 8) & 0xFF) + ((v2 >> 8) & 0xFF);
      b = ((v0) & 0xFF) + ((v1) & 0xFF) + ((v2) & 0xFF);
      r = Math.floor(r / 3);
      g = Math.floor(g / 3);
      b = Math.floor(b / 3);
      pixels[pos] = r << 16 | g << 8 | b;
    }
  }
}

function hashrandom(v0, v1, v2) {
  var hash = 0;
  hash ^= v0;
  hash = hashsingle(hash);
  hash ^= v1;
  hash = hashsingle(hash);
  hash ^= v2;
  hash = hashsingle(hash);
  return hash;
}

function hashsingle(v) {
  var hash = v;
  var h = hash;

  switch (hash & 3) {
    case 3:
      hash += h;
      hash ^= hash << 32;
      hash ^= h << 36;
      hash += hash >> 22;
      break;
    case 2:
      hash += h;
      hash ^= hash << 22;
      hash += hash >> 34;
      break;
    case 1:
      hash += h;
      hash ^= hash << 20;
      hash += hash >> 2;
  }
  hash ^= hash << 6;
  hash += hash >> 10;
  hash ^= hash << 8;
  hash += hash >> 34;
  hash ^= hash << 50;
  hash += hash >> 12;
  return hash;
}

//END, OLSEN NOSE.

//Nuts and bolts code.

function MoveMap(dx, dy) {
  xpos -= dx;
  ypos -= dy;
  drawMap();
}

function drawMap() {
  //int iterations, int[] ints, int stride, int x, int y, int width, int height
  console.log("Here.");
  fieldOlsenNoise(iterations, colorvalues, stride, xpos, ypos, canvas.width, canvas.height);
  var img = ctx.createImageData(canvas.width, canvas.height);

  for (var y = 0, h = canvas.height; y < h; y++) {
    for (var x = 0, w = canvas.width; x < w; x++) {
      var standardShade = colorvalues[(y * stride) + x];
      var pData = ((y * w) + x) * 4;
      if (singlecolor) {
        img.data[pData] = standardShade & 0xFF;
        img.data[pData + 1] = standardShade & 0xFF;
        img.data[pData + 2] = standardShade & 0xFF;
      } else {
        img.data[pData] = standardShade & 0xFF;
        img.data[pData + 1] = (standardShade >> 8) & 0xFF;
        img.data[pData + 2] = (standardShade >> 16) & 0xFF;
      }
      img.data[pData + 3] = 255;
    }
  }
  ctx.putImageData(img, 0, 0);
}

$("#update").click(function(e) {
  iterations = parseInt($("iterations").val());
  drawMap();
})
$("#colors").click(function(e) {
  singlecolor = !singlecolor;
  drawMap();
})

var m = this;
m.map = document.getElementById("canvas");
m.width = canvas.width;
m.height = canvas.height;

m.hoverCursor = "auto";
m.dragCursor = "url(data:image/vnd.microsoft.icon;base64,AAACAAEAICACAAcABQAwAQAAFgAAACgAAAAgAAAAQAAAAAEAAQAAAAAAAAEAAAAAAAAAAAAAAgAAAAAAAAAAAAAA////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8AAAA/AAAAfwAAAP+AAAH/gAAB/8AAAH/AAAB/wAAA/0AAANsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////////////////////////////////////////////////////////////////////////gH///4B///8Af//+AD///AA///wAH//+AB///wAf//4AH//+AD///yT/////////////////////////////8=), default";
m.scrollTime = 300;

m.mousePosition = new Coordinate;
m.mouseLocations = [];
m.velocity = new Coordinate;
m.mouseDown = false;
m.timerId = -1;
m.timerCount = 0;

m.viewingBox = document.createElement("div");
m.viewingBox.style.cursor = m.hoverCursor;

m.map.parentNode.replaceChild(m.viewingBox, m.map);
m.viewingBox.appendChild(m.map);
m.viewingBox.style.overflow = "hidden";
m.viewingBox.style.width = m.width + "px";
m.viewingBox.style.height = m.height + "px";
m.viewingBox.style.position = "relative";
m.map.style.position = "absolute";

function AddListener(element, event, f) {
  if (element.attachEvent) {
    element["e" + event + f] = f;
    element[event + f] = function() {
      element["e" + event + f](window.event);
    };
    element.attachEvent("on" + event, element[event + f]);
  } else
    element.addEventListener(event, f, false);
}

function Coordinate(startX, startY) {
  this.x = startX;
  this.y = startY;
}

var MouseMove = function(b) {
  var e = b.clientX - m.mousePosition.x;
  var d = b.clientY - m.mousePosition.y;
  MoveMap(e, d);
  m.mousePosition.x = b.clientX;
  m.mousePosition.y = b.clientY;
};

/**
 * mousedown event handler
 */
AddListener(m.viewingBox, "mousedown", function(e) {
  m.viewingBox.style.cursor = m.dragCursor;

  // Save the current mouse position so we can later find how far the
  // mouse has moved in order to scroll that distance
  m.mousePosition.x = e.clientX;
  m.mousePosition.y = e.clientY;

  // Start paying attention to when the mouse moves
  AddListener(document, "mousemove", MouseMove);
  m.mouseDown = true;

  event.preventDefault ? event.preventDefault() : event.returnValue = false;
});

/**
 * mouseup event handler
 */
AddListener(document, "mouseup", function() {
  if (m.mouseDown) {
    var handler = MouseMove;
    if (document.detachEvent) {
      document.detachEvent("onmousemove", document["mousemove" + handler]);
      document["mousemove" + handler] = null;
    } else {
      document.removeEventListener("mousemove", handler, false);
    }

    m.mouseDown = false;

    if (m.mouseLocations.length > 0) {
      var clickCount = m.mouseLocations.length;
      m.velocity.x = (m.mouseLocations[clickCount - 1].x - m.mouseLocations[0].x) / clickCount;
      m.velocity.y = (m.mouseLocations[clickCount - 1].y - m.mouseLocations[0].y) / clickCount;
      m.mouseLocations.length = 0;
    }
  }

  m.viewingBox.style.cursor = m.hoverCursor;
});

drawMap();
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="500" height="500">
</canvas>
<fieldset>
  <legend>Height Map Properties</legend>
  <input type="text" name="iterations" id="iterations">
  <label for="iterations">
    Iterations(7)
  </label>
  <label>
    <input type="checkbox" id="colors" />Rainbow</label>
</fieldset>
```
> 1 votes

---
Tags: algorithm, procedural-generation, procedural
---


# Question
Title: How to avoid players getting lost in and/or bored by the meta game?
Yesterday, I noticed something that I had never noticed consciously before, but which had "ruined" more or less all games that I have ever played:

***The longer you play a game, the more you get lost in and bored by the meta game.*** What I mean is that the longer you play, the more you know the meta game. Once you know the meta game by heart, you basically stop playing the game and instead *only* play the meta game anymore.

Here are a few examples from different genres to show what I mean:

**DotA:** In the beginning, DotA is super fun, although you totally suck at it. You learn new heros, you are happy when you are able to buy an expensive item and so on. After being "pro" in DotA, you basically only play the meta game anymore: You pick exactly the hero that can counter the enemy and play exactly a perfect meta game for your hero (e.g., go to jungle until you are fat, time creep spawns to stack, and so on). You know basically exactly at which time you will be able to buy which item and you execute this. You no longer play the game, you just play the meta game. You execute a well-thought-out choreography, which you perfected by executing it 100 or more times. Eventually this gets boring!

**Anno XXXX:** In the beginning, you build an island and have to master more and more challenges to keep you citizens happy. Cool! Once you know the meta game the whole game becomes a "Oh, I need these 10 resources in these proportions, then the people are happy. I build a fleet and capture the enemy or keep on playing until my island is full".

**Cities: Skylines (or any Sim City):** In the beginning, it is fun to master what your people need. In the end, you know exactly what they need, so it becomes more or less a burden: E.g., for each new residential district, I need a police station, a fire station, garbage incineration plant, crematory, a hospital, I connect everything to the highway, add a subway station and add bus lines. Done. Lame. It starts feeling totally mechanic. I no longer feel like building a real city. I feel like building a mathematically simulation of a city and just responding to optimize all parameters for this simulation.

**Civilizations:** A super nice game to explore in the beginning! So many technologies, just wow! In the end: I know exactly which technology to develop when. I have a more or less complete ordering among the technologies. I know where exactly to place the next city and which units to build. Heck, I think I could even write an AI that does more than 95% of the things I do, since everything has become so mechanic.

I could go on forever. Almost all games have this. For some players, this is where the game gets really cool. *Some players want to play the meta game!* But for others, including me, it gets boring. I want to feel like playing a game, like exploring. Not optimizing a numerical simulation.

So, when designing a game, how can you avoid that this will happen? Is it possible to hide the meta game to such an extent that the player no longer *feels* it, even when playing the game for long.

# Answer
> 155 votes
*I apologize beforehand for the book I have written. I got carried away. I just hope it gives you some good ideas.*

What you are describing seems to be a fundamental shift in the way you view and play the game, and I think the clue in making games that avoid it, is in trying to understand the shift, so I'm hoping to explain it in this post.

And that fundamental shift is going from **solving problems** to **executing solutions**.

**Solving problems**

When you start a game, it is completely new. Your understanding of how it works is likely limited to maybe some reviews, a trailer, or perhaps a "what is X?" video.

At this point; everything you see is a problem and everything you try is new. Even the simple question of "I wonder what happens when I click 'new game'?" can have surprising answers. It might jump into a movie, or a character generation screen, a tutorial, or straight into the game. Whichever it is, you're going to have to figure it out as it happens and it is almost certainly going to present new problems to solve. (Such as "How do I get started?" and "How do I win?")

As you become better at a game, you start gathering more and more answers to problems. At some point you *know* that when starting the game, you need to collect X resource and find Y person and build Z building. But new questions will start coming up; more advanced ones that you could not even have attempted to answer before. "How do I beat the Hard AI?" or "How can I beat this level?" are questions that are only of interest to a good player, but they still put you in problem solving mode; you simply don't *know yet* how to do it, but you're going to try and come up with some possible answers and try them out, and see if any of them work.

And in doing so, you'll learn some new things about the game. New experiences will be had, and you'll gather more knowledge which you can use to solve even harder problems. (like "How do I beat the Extreme AI?" ;) )

**Executing solutions**

But at some point, for some parts of the game, problems stop requiring you to *solve* them. You already know the best solution. What you need to learn or do, is to *execute* those solution to the best of your abilities.

For example, in a platformer, the first time you find a ravine that you need to jump over, it's a problem you need to solve. Can I jump far enough? Do I need a powerup? Do I need a running jump? These are problems to solve. But when you get to level 10, the "jump this ravine" problem has been solved. You know exactly how far you jump, how much of a running start you need. But *this* ravine is big. And the landing point is small. And if you want to make it, you need to time your jump *just* right, or you'll fall in.

This is executing a known solution, which can also be challenging in its own right, but is a completely different type of skill to work on.

In all your examples, you are describing the move from solving problems to executing solutions. When you know exactly which hero to pick, or which tech to research, or how to keep your people happy, all that remains is to perfect the execution. Can you reach a higher score? Can you beat a better opponent? You don't need to solve any complex problems; you mostly need to learn how to build faster or aim better.

**But how do we fix that?**

So you're asking for design methods to fix the shift from solving to executing. In order to be stuck in solving mode, what you need is a problem with no clear-cut solution. And, ideally, if you want to make this work for competitive games, a problem that can't be perfectly solved at all.

**Procedural generation**

A big one for single-player games that want to stay fresh for a long time, is procedural generation. The fact that your levels are randomly created means that all of them start with problem solving: "where am I?", "what here can I use?", "what do I need to be on the lookout for?"

Procedural generation will work you keep you in solving mode, until you intuitively figure out the restrictions on the generator and start expecting things. "Okay, the game gives me a two minute grace-period to set up. Also, there has to be a box with some weapon nearby. Let's go."

So, the best way to keep players on their toes, is to make the pattern as broad as possible. But that will play into the second point, also.

**Multi-strategy games**

Another one that helps a game stay fresh, is to have multiple paths to victory. Civilization has a set of different victory conditions (tech, diplomacy, conquest, etc) and each requires a different way to play. In addition, defending against each also takes a different approach. This means that a game where a strong player is going to win a diplomatic victory will go very different from one where a strong player is going to win through conquest.

This, in turn, means that while you can have a good idea what *you* will do in your rush to win, you won't know what you're going to defend against, and that will keep games different. At least, assuming that you actively need to prevent other players from winning and there isn't one fixed method to do so, which sadly in Civ is not the case usually.

You can get pretty extreme with this approach, too. In civilization, most races are roughly the same. But for example in Endless Legend, some races get traits like "You cannot be at peace with anyone" or "You can ban other players from trading resources at will", which force you to try even more things.

Multi-strategy games will work until the player figures out a 'certain win' strategy, or until they have tried all possible strategies. (In the latter case; congratulation game designer, you won.)

**Limitless games**

You can also keep a game fresh by doing away with limitations and letting players go completely wild. This is a fairly new phenomenon that has been made wildly popular by (of course) Minecraft. I'm not sure what the creators thought people would build in the game, but I'm fairly sure that "A working processor" or "All of Minas Tirith" weren't it. But there you have it.

Limitless games will keep you in problem solving mode until you get bored of something else in the game, so really they are the perfect thing you're looking for. Of course, at some point, you are no longer "playing a game", but are just rebuilding a different hobby inside a piece of software that was once a game.

Another issue with these games is often that they lack a clear goal. Goals can drive players towards something and keep them coming back, but not everyone sets their own goals. And it's very hard to set goals in a game that can go anywhere.

**Evolving games**

Another approach is games that change as you play them more. This type of game on its own seems to be very rare, but you can often see it implemented by continuous developer attention.

For example; collectible card games that have new cards released, MMOs with expansions, DLC in strategy games, balance tweaks, etc. These are always a delicate balance between keeping the metagame moving enough that it keeps people interested but not moving it so much that is makes investing in the game seem pointless.

Games that do this intuitively would be awesome, but it might be future music for now. Game design and balance remains an art for now, and computers are not very good at art.

**Combining things**

Many of the above options can be combined for greater effect. I'm going to hypothesize a game based on the 4X principle (like Civilization) that tries to go for maximum "problem solving mode". (But it will take huge developer involvement to run it, I think. So it might not actually be a very *good* game.) We'll make this an MMO game, because those are by far the *hardest* to do this way, due to all the players getting together to write down solutions.

First up; take a working chassis for a 4X game. Some setting, some tech, buildings, unit types, victory conditions, etc. Since this is an MMO type game, we don't expect players to be logged in constantly and the runtime will be fairly high; let's say one month. When you are absent, your AI advisor will play for you. (There's some games in the market like this)

Now, we create a procedural world. This is common practice for these games, but we'll take it a small step further: while we strive to keep the game balanced, we make *no* attempt to allow all types of victory conditions and all strategies possible from each starting location. Start without iron? You'll have a hard time fielding a strong military; might want to rethink that conquest victory. Stuck on island? Guess expansion isn't for you. We want the start position to be fair towards "Can this player reasonably win?", not towards "Can this player reasonably play a fixed strategy?"

Then, to make it even harder to have a fixed strategy before game start, we'll vary (but make it known) how hard each type of victory is on this map. Maybe this time around, conquest is made easier, but technology is more expensive. This means that the "best strategy" from the previous game is now useless if it can't bridge the gap created by your completely different starting position and the different relative complexity of the win condition. But if you understand the game well, this just means that you have been given a hard problem to solve; which is exactly what we want.

(Note that it's not automatically true that everyone will aim for the easiest objective. Since we know the relative difficulty of each objective at generation, we can give a bonus to players that are in a region which is naturally geared towards a hard objective for this map. Kinda like how some games have special "2vs1" maps where the 1 player has a defensive advantage.)

Then, let's give the game a mechanic where the players can make broad changes to the rules. Civilization's World Congress had some of those, but they were a bit tame and came in late. I've played a board game where you had rules like "nobody can build more than X warships" or "if you don't protect your colonies with armies, they revert to neutral" and a bunch more, including ones targeted at players. That's more like what we need. This means you can't plan out your strategy from the start; you need to adapt to the rules of the game changing. But still, if you know the game, you'll know *roughly* what you can expect, so you can still get better, but the available rules for each game will vary. You can learn the game, you can be good at the game, but you can't *solve* the game, and so you'll never get bogged down in the "Perform X, only slightly faster this time" metagame.

At this point, I think you've got a game that won't get boring for a long time because it **cannot** evolve a metagame of the sort that DotA or Civilization has. It will change too much to have a fixed metagame, while also changing very little, so that you can learn to become really good at it. It just takes a completely different skill to be good: you need to be adaptive and good at solving problems, not good at executing the best strategies the fastest.

# Answer
> 41 votes
The state you describe as "getting lost in the meta-game" is actually a state where the player has achieved a mastery of the game which makes them play it differently (and arguably much better) than they did in the beginning. But for some player this new way of playing is less interesting than the way they played the game in the beginning. But the beginner way of playing is not rewarding for the player, because it means they will be less successful. The result is frustration and abandonment of the game.

Please keep in mind that **not all players react that way**. Many in fact enjoy exploring and learning the deeper mechanics of a complex game in detail. The reason why DotA or League of Legends are so successful is precisely because of the long-term motivation which comes from mastering its deep meta-game. But the premise of this question is that we want explicitly to appeal to the players who do not, so let's continue based on the assumption that breaking immersion by understanding the game mechanics is not what our audience wants.

* Keep the game mechanics simple and easy to understand. That way any new players will soon discover if they like them or not and multiplayer will have less of a learning curve, because all players have roughly the same level of understanding of the meta-game. **Case Study: Blobby Volley**.
* Alternatively, make the game mechanics so complex that nobody really understands them. Try to hide all numbers from the game interface to prevent players from figuring out your formulas. This really only leaves intuition as a decision-making criteria for the players. **Case Study: Most modern first person shooters.** The more diligent explorers will try to obtain the numbers from your game files and will soon create a wiki where they are all listed in detail. The only counter-measure is to keep them server-sided.
* Don't make a competitive game. When you encourage competition, you put the players in a mindset where they feel they need to do whatever it takes to win. Create a game which focuses on creative expression, socializing and world exploration. Such games are far more rewarding to play when they are played in an immersive manner. **Case Study: Minecraft, Starbound**.

# Answer
> 14 votes
May I suggest the book "The theory of fun", by Raph Koster?

In essence, he suggests that a game is only fun until you've grokked it and it is human nature to figure out the optimal solution to a problem and move onto the next problem.

(It's called learning, apparently. Once something is learned, the mind seeks further variety. Therefore, I guess you need to change the metagame continuously, keeping it between "Too hard, this is chaos" and "Too easy, this is boring". User-generated content seems to help, people end up making their own problems - and entertainment.)

# Answer
> 11 votes
# Reactiveness

"No plan survives contact with the enemy."

The enemy chose hero X.

So, you have selected hero Y and have started plan Y2, since that is the recommended counter to hero X.

Unfortunately the enemy guessed that, and started executing plan X-counterY2.

But, AHA, you guessed that and segued over into plan Y2-counterXcounterY2.

But what is the enemy doing? That doesn't look like X-counterY2 anymore...

And you lose.

A few games later, the enemy again chooses hero X. And you choose hero Z. Wait, what? Nobody plays Z against X! However, this means that the enemy does not know what to do!

You on the other hand have studied this matchup. You know how the enemy is likely to react, you know what to do against that, you know their counter to your counter to their counter.

And you win, that one game. Unfortunately you were streaming this and now everybody knows what you know.

The next game, you choose hero X. And somebody who saw that stream choose Z. You know you are going to win this, because you know **exactly** why Z-vs-X is a bad choice.

# How do you design a game like that?

Having a Rock-Paper-Scissors aspect to game helps a lot. It shouldn't be as blatant as RPS, but even small advantages makes sure there is no single "best" answer anymore.

One typical RPS trio is Growth - Defense - Attack. Growth beats Defense. Defense beats Attack, Attack beats Growth.

You can have Armour, that make some weapons ineffective. You can have Armour Penetration, which can be very useful or very useless.

And so on.

The main point is that the strategies must not be locked in from the start, the player must be able to change things around when they see what the enemy is doing. However, your early-game choices must have *some* consequences or they become meaningless.

Add limited information into the mix and things start getting interesting. Scouting can give you the ability to out-strategize the enemy, but it also costs resources sorely needed elsewhere.

# Answer
> 10 votes
I'm surprised nobody has mentioned this, but chess is a pretty good example of a game where the meta is so hard to master that people have been playing for centuries. The only portion that people maybe have gotten bored of is openings (which is why Bobby Fischer proposed a chess-like game that had randomized starting places).

Chess actually has a small set of rules, so what can be gleaned from its success is that it's not necessarily the number of rules and stats and such that keep a game interesting. Chess remains popular because there's an exponentially large number of *situations*, and each of these situations may need a unique application of logic.

I think what you're experiencing is games with limited situational variety, at least on some level. "I've seen this, I know what to do here" is maybe uttered a lot, and the mastery comes more from execution. Knowing what to do in a given chess situation, on the other hand, is probably rarely straight-forward.

This probably all plays into Erik's answer about problem solving. In general there's two solutions: have a game rely heavily on strategy that builds up over many moves or actions (like chess) so each application of strategy can produce exponentially large amounts of responses (situations), or rely on randomness to create a large variety of situations (procedural generation, or multiplayer (other humans can be very unpredictable opponents)).

# Answer
> 8 votes
## TLDR: Give more power to players' actions.

EverQuest Next had some ideas that could alleviate this issue. That game was apparently cancelled (I'm not sure why as I haven't kept up with it), but if plausible, many of their ideas would make player's actions much more important.

## Persistent, destructible environment

If you let your players loose in a destructible world, then the game changes with the players. This area used to be a great place to mine, but it's been cleaned out and no one went there anymore, so now the assassins guild took it as one of their bases of operation.

## Wandering, limited AI

The forest around the town is full of goblins? Send the players to kill them all. You found out the best strategy for killing goblin bosses, hooray! Now there are no goblins, but the orcs and ogres are moving in. Maybe the goblins weren't so bad. Goblin meta-strategies aren't working here, so you're back to square 1.

## PvP incentives

The two player factions went to war over *\[insert reason\]* and now they are in shambles, allowing the other factions to take power. These new factions have raised taxes on swords and made significant improvements to bows. the archers are loving it, but there's talk of a knight uprising.

There's tons of potential with this kind of system. Maybe frost mages are rampant and it's making the world too cold and food prices skyrocket. Lavamancers aren't worrying about accuracy, now there are lava pools all over the map.

Granted, most of these examples work best in the MMO genre, but you could likely extend to other genres. For example, have FPS which has destructible maps that don't refresh for the next game (That sniper nest got destroyed!? There used to be a wall *right here*!).

# Answer
> 6 votes
There are a bunch of great answer so I'm not sure I'm actually adding useful information here, but one thing that works in almost every genre of games is to make up a bunch of modifiers to your game and pick one or more random modifiers each time. Examples:

* If it's a game where economy comes into play (city builders, RTS games) a simple modifier could be a multiplier to resources (gold x1.2 but everything else x0.9)
* A game featuring any kind of physics (platformers, simulators) can modify its physics (altered gravity strength/direction)
* A game with enemies (shooters, action games, RPGs) can modify them (enemy health, enemy damage, amount of enemies, enemy positions)

For literally any game you could think up a few of these and the great thing is that it's not very hard to implement in your game. If you list, say, 20 of these for your game and re-randomise them when it makes sense (every session, every level, after every x minutes) you are constantly changing the way a player has to play the game. You are forcing them to stay cautious and not get overconfident and with the amount of possible combinations it will take way more time for a player to learn all the possible strategies.

# Answer
> 4 votes
<sub>Note: I write this answer from the perspective of a video game player.</sub>

If you don't want to create a game where the meta-game plays as much as a role, you have a few options:

* Create a game that makes no sense. Any choice the player makes is by definition meaningless, and can be both good and bad. Basically, truly eliminating the meta-game completely is eliminating the difference between a good and a bad choice. A `rand()` simulator. A game that is overly complex in such a way that you can't master anything could as well be a `rand()` simulator, because every choice you make is more or less random; the choice makes no sense, and the outcome makes no sense either. (I personally think that is not a fun game to play. I list this option, because in my mind this is the only way you can completely eliminate the "meta-game", but I think you should not create such a game, because in return it removes any goal the player can have.)
* Create a game that is intended to be only played once. Look at a game like **The Talos Principle**, an atmospheric puzzle game. Everything in the game can be completed in the first playthrough and right until the end of the game you can revisit any areas if you deem it necessary. A few silly people will replay the ending for a few more achievements. There is little reason to play the game again, but that does not detract from the game itself.
* Create a game that randomizes certain attributes. In **XCOM: Enemy Within** and **XCOM 2** (incl. Long War Toolbox) you can enable options that randomizes level up stats of soldiers, which allows for additional choices during the game; and allows players to play to the strengths and weaknesses of otherwise equal characters. Similarly, **Civilization: Beyond Earth** randomizes the tech tree if I remember correctly. It forces the player to make some choices in the tech tree that are different from earlier playthroughs, giving the player an edge in something different. I have not played C:BE personally, so I can't tell you how well that concept is executed in that game.
* Create many goals. A great example is the achievement list of **Civilization V**. Each faction has a specific goal that counts for an achievement. Some of these goals require you to play in a very specific way, probably differently than you are used to. This gives the game more longevity. The achievement list of **Team Fortress 2** contains many goals to play the game in a non-standard way.

You might need to add a way to let the player know that such options exist. For example, given your description of the Civilization series, you likely did not know of these alternate goals.

# Answer
> 3 votes
> And that fundamental shift is going from solving problems to executing solutions.

How can you delay that shift? One way is to make it unclear *which* solution must be executed by introducing variety from game to game.

For instance, consider Master of Orion 1. Its core game mechanic is designing ships superior to your opposition, but both you and your opponents can only use the technologies you have acquired, and technology acquisition is different for every game. Specifically, there are 4 ways to acquire a technology:

* research: Each player can only research a random subset of available technologies, so the desired tech may be unavailable ...
* trade with another empire: The empire must have the tech and be friendly, and want some other tech you have ...
* espionage: The empire must have it, and you must be willing to piss them off (or so superior in computer tech that you can reliably frame another empire)
* conquest of a developed world: The empire must have it, needs temporary space and ground forces superiority, must be willing to piss them off, as well as their allies, but boost relations with their enemies.

... or the best solution may be to do without the tech ;-)

Note how all of these approaches are highly situational? In MOO1, there is no approach that's always best, even though there is always a best approach ;-)

Variety can be introduced in various ways:

* random situation (abilities, obstacles, goals, ...)
* dependency on unpredictable choices of other players (absence of a nash equilibrium, opaque or evolving metagame, ...)

# Answer
> 3 votes
**There are many different players with many types of tastes**, but I think I'm fairly close to your tastes, so I'll offer with what keeps my interest. I think it applies to many other gamers with similar tastes.

I noticed this sort of thing decades ago, and for me it was pretty much the same thing. At some point, I stop relating to the game as the situation it is supposedly about, and start relating to it as its artificial game mechanics.

After decades of game playing and designing, I'm convinced that for myself, **the main thing that I find interesting in games, and that holds my interest, is when a game's mechanics do a satisfying job of modelling the situation**, and when the situation is complex and dynamic and involves many systems. As long as the mechanics are fairly close to how I understand the situation, and the situation involves various layers and changes so that a large situation has lots of logical cause and effect at various levels, I can continue to relate to the game as being about the situation it says it's about, and not about gamey abstractions that I don't care about.

Some of the systems that tend to help a lot, too, are:

* multiple agents with different goals that are consistent with what the game is about, and that are often not just simple oppositions
* incomplete knowledge by the player and other agents about the situation
* persistent cause and effect, so actions and choices have effects that last

**Games that model real interesting situations well can approach (and sustain) the interestingness of their subject matter**, at least for players like myself. Abstract games tend to simplify things to the point that they can be formulaic, however, and feature more certainty and control that a real person in the situation would have. That removes elements from play and reduces the situation to something formulaic and not a real interesting series of choices.

The opposite is also very true for me. As soon as I can see the gamey mechanics and don't think they represent the situation well, I lose interest quickly.

**Mod support helps too.** If I can mod the parameters of a game to have it match the way I'd like to be, that can save it from me rejecting it. Because for example it will bother me if you can destroy a buttoned up tank by shooting it enough times with bullets, but if I can mod it so you need to penetrate the armor, then I can stop groaning at the non-tank-like mechanics, and relate to it as a tank whose armor needs to actually be penetrated to hurt it.

It has also inspired me to release some mods that extend the interest for other players, too.

Other games I've played for years which held a following tended to also be ones which the **designer supported** for years and **listened to the intelligent suggestions of players** (and at most provided mod support for the goofy suggestions of players).

# Answer
> 2 votes
I'm don't know a lot but what you say can be "solved" by adding new content regularly that can change/improve the meta-game. Making new content always helps players learn new stuff and don't feel so bored. Take WoW for example, if they stopped at Burning Crusade the game would be *DED.* but because they add new expansions every X time they keep their subscriber base pretty much constant.

New content is good, and more if it's free!!!!

# Answer
> 1 votes
What about a learning AI? It would be like your nega-companion, learning about you after each interaction and figuring out a way to beat you accordingly.

With the current processing power and memory available for calculation, it could be a hard time to understand it and to beat it! (especially because it knows the rules perfectly).

On top of that you add a procedurally generated world, random starter boosts for each (you and the AI) and it should do!

The game becomes more intuitive and less rational, which increase the "meta".

# Answer
> 1 votes
The problem you are addressing is, as you have so cogently pointed out, not one unique to any game, but rather is found in all games. This is, in and of itself, suggestive of the true answer.

Each game mentioned has some sort of hard limit, beyond which one simply cannot go. These seem to fall into two main categories: execution limitations (limitations to the hardware, software, or programmer's imagination/budget/deadlines), and story limitations (goals, playable content, story line and plot.)

Story limitations are limited only by the imagination, which again is suggestive of the true answer.

The real problem here is a people problem, whether of the one playing the game or the one designing the game. The answer is not necessarily to seek new horizons (another game), but rather to have new eyes. The goals and expectations each person sets when designing or playing a game are the actual problem, AND the solution. It remains only for one to become aware of what their current rules and limits are, and to perceive how they can continue to grow.

The only game I'm aware of that truly has no limits is expanding who and what one knows.

# Answer
> 1 votes
**A Few Notes Before You Begin**

* I generally play story-based RPGs, so most of the games I will cite are going to be story-based RPGs.
* I plan on talking about the ideas of games themselves, then moving on to concrete examples to explain the points (usually discussing games that I think did well in certain aspects and games I think did poorly in others), and then end with a general analysis and answer to the question.

## Theory

---

As far as I can tell, the six defining features of a task in a game are **completion time**, **complexity**, **difficulty**, **frequency**, **interdependence**, and **reward**. These six features are deeply interconnected, and having any of them out of proportion with will make a task monotonous or frustrating.

**Completion time** is how long it takes to complete the task. Generally, with all other variables held constant, the shorter the completion time, the less tedious the task (i.e. you press a button to fire a gun vs. collecting all the flags in Assassin's Creed). Just because a task is time consuming does not mean that it is necessarily boring.

**Complexity** is how much effort you have to put into something to figure out what you need to do. Figuring out how to open a door with a button next to it that says "Press this button to open the door." is a simple task. On the other hand, this is not. Complexity is probably most associated with the idea of a meta game. A task can only be as time consuming as it is complex. Firing a gun is a simple task, and it has a correspondingly low time consumption. Collecting all the flags in Assassin's Creed is a simple task in that all you have to do is find them all, but it takes hours. The first task is not really tedious, but the second one definitely is.

**Difficulty** is how well a player is able to achieve his goal. Killing a Radroach is one of the easiest things you can possibly do. If I want to kill a Radroach, I can kill a Radroach. On the other hand, a Mirelurk Queen will destroy you. You will need your most powerful guns, dodge all her attacks, and make every shot count. There are other forms of difficulty, too. For instance, I would consider a game in which you flip a coin to determine if you win or lose to be a sort of difficult game, as you can only win about half the time. As a really quick side note, a perfect player should always be able to complete a task, so he should never be randomly punished.

**Frequency** is a measure of how often you need to do something to achieve a goal. A very frequent task is using a weapon. Whenever you want to kill an enemy, you need to attack him. Other examples of frequent tasks include going to an in-game store or fighting a grunt. A much rarer task would be trying (and failing) to kill Sephiroth in Kingdom Hearts. This task is completely different from killing any other enemy in the game, as you have to find ways to counter his various attacks, find his weaknesses, etc. A frequent task gets annoying when it is both time-consuming and simple. Easiness makes the task mundane and tedious, hardness makes it frustrating. The interdependence doesn't really matter with this one as it is already considered in determining the frequency of a task. A constant reward has a diminishing effect on how fun a frequent task is, but an increasingly good reward can help to counter it. I cannot remember the exact name of this principle, but I think it has something to do with Diminishing Returns. Frequency and difficulty should have some sort of an inverse relationship.

**Interdependence** is what other tasks depend on that task. Killing enemies and hitting targets both require firing a gun or using a ranged weapon. Although firing a gun is a basic task, using it to achieve other goals removes any mundanity of the task. This really only applies to extremely basic tasks that I will call **Fundamental Tasks** that are necessary to play the game.

**Reward** (Finally on the last definition.) is what you get for doing a task. Rewards must be at least proportional to all the other variables of the task (i.e. getting a pretty good sword for a decently hard quest is a good reward, but you certainly wouldn't mind if you got a legendary UltraMegaDeathbringer of Death). An important note is that reward doesn't include the actual fun of doing the task. It is literally just the in-game reward. The actual fun you get from getting the reward is considered when determining how fun the task is.

## Examples of Tasks

---

Now, let's consider a bunch of different tasks. The first will be a **Fundamental Task**. This task must be quick, simple, easy, frequent, independent, and provide a minor reward. It is literally just pressing a button on the controller or a task like that. Moving, jumping, looking around, using weapons, reloading, etc. would be fundamental tasks. You can't really change any of the features of the fundamental tasks without moving into extreme absurdity (Dibs on the band name.) and mundanity. No one really minds fundamental tasks because they form the interface between the player and the game.

The next task will be defeating an enemy. The features of the task "Defeating an Enemy" vary depending on something like the **level** and the **type** of enemy. A level twenty grunt should take more time than, be harder than, and provide a better reward than a level three grunt. On interdependence, the level twenty grunt should be more common in difficult tasks than a level three grunt. The level twenty grunt may not necessarily provide a better reward (Assassin's Creed, for instance), but they generally do. Because these enemies are the same type, the complexity of fighting them shouldn't really change all that much. Enemies of different types should have different complexities or be as complex, but in different ways. Frequency is game-dependent. In this task, all the features are proportional. Now, let's consider what happens when we change these features. A higher level enemy that is easier and can be killed quicker than a lower level enemy in the exact same circumstances is just stupid. A lower level enemy that gives out better rewards than a higher level enemy leads the player to fight lower level enemies, which leads to a whole bunch of problems. A harder task must have harder enemies or else it is not really harder (excluding things such as puzzles). When you get really good at defeating enemies, this becomes like a fundamental task. You want to kill an enemy? Aim and shoot.

**Note:** This next section has a little rant about the combat systems of *Fallout 3* vs. *Skyrim*. I love both games, but I had a problem with the combat system in *Skyrim* that I think *Fallout 3* dealt with well. I'm not trying to start a flame war.

This was my main and only problem with *Skyrim*. Other than the combat, I loved it, but the fighting in *Skyrim* for most enemies was just mashing the attack button, or summoning someone to fight my battles, or using a spell, or chugging 30 health potions. The stealth was fun when it started, but once I figured it out, it was easy. Just walk up to someone and kill them or shoot them from far away. On the other hand, *Fallout 3* had a great combat system. You had to run away and find cover. You had to get good at aiming, you had to use a bunch of different guns because yours just ran out of ammo. You had to use your VATS well. The closest thing *Skyrim* had to this were the bows, but you only had a bow. You did not have a bow with rapid fire, you did not have a bow with a scope, you did not have a bow that did energy damage, you did not have a long range bow or a short range bow, etc. Granted, you did have bows with different enchantments, but even they got old. The difference here is that once you learn how to use one bow, you learn how to use any bow, but learning how to use a shotgun is completely different from learning how to use a sniper rifle or a magnum or a hunting rifle. The same general idea goes with spells, one handed weapons, shields, and two handed weapons.

tl;dr: The weapons in *Skyrim* are too similar. Once you figure out a general class of weapon, you figure out them all.

Let us consider a more complex task: the infamous fetch quest. Fetch quests tend to take a pretty decent amount of time to complete, are very simple (this will be discussed later), and appear very frequently. You have to go find some dungeon, kill all the enemies, get the item, and come back. They are often boring and used to pad the length of a game. They are often too simple for the amount of time they require and they appear very frequently. The simplicity combined with the frequency make mastering fetch quests extremely easy. You either have to remove them or make them more complex. *Fallout 3* did an amazing job of making fetch quests more complex. The quest line Scientific Pursuits combined with Tranquility Lane in which you have to "fetch" your dad and a story-related invention ignored all the clichés of fetch quests. Instead of just going into some vault and killing its inhabitants, you end up trying to escape a simulation of a neighborhood controlled by an insane scientist who loves torturing the inhabitants for fun. You had to either help the sadist, which led to complex problems that you would need to solve or find a failsafe, which had a complex problem in itself to solve.

Finally, I will talk about sandbox games like Minecraft. In Minecraft, a lot of the gameplay is extremely simple. Go to a crafting table to build things. Use a pickaxe to mine, a shovel to dig, an axe to chop wood, a sword or bow to defend yourself, and a hoe to plant. Eat food to not die. Use a bed to sleep at night. Attach blocks to other blocks to build objects. Etc. These are fundamental tasks to playing the game. The fun in Minecraft comes from building huge or amazing structures or machines. The players themselves come up with the challenge. They make their own quests. The amount of fun a player has is determined entirely by the player. All the quests give the exact reward the player wants, and have the difficulty, frequency, completion time, and complexity that the player wants. This allows for a great balance between all the features of a task.

## Answer

---

The basic idea of how to keep players interested in the meta game depends almost entirely on increasing the complexity of the meta game, and then changing the other features to coincide with the complexity. Instead of having just one meta game, create several meta games inside a meta game. You want to beat an enemy? To do that, you're going to have to learn to master ten different guns. You want to go on a quest? To do that, you're going to have to learn how to defeat seven different types of enemies. Instead of letting the player control troops on a flat battlefield, give him some different terrain. Put a mountain pass on his left and a river on his right. Give him multiple troops with different advantages and disadvantages. Give him some Calvary.

Another option is to somehow constrain the player to force him to adopt new tactics without making it unnecessarily difficult. Don't take away all his weapons, just make his main one run out of ammo. Now he has to use a weapon he isn't nearly as good with, which leads to him having to think his way out of the situation. This is a big part of why I loved *Bioshock Infinite*. It forced me to think about whether I should keep my empty carbine and hope I find ammo later or pick up another gun and hope I find another carbine later.

I hope this helps spawn some discussion or give you some new ideas. Feel free to add any info or other ideas.

# Answer
> -3 votes
1. Keep the meta advantage low % and pregame choices of limited importance. You don't want rock-paper-sciccors with a 15-30 minute delayed, "rock beats scissors" screen.
2. To accomplish the above, characters need a well rounded kit, that is standalone and does not rely on roles that are stiff, or a lot of hardcounters. Every character should have 2-3 harcounters, but keep the rest soft.
3. Another way is punishing stupid wins by quick games. Your players can create more fun games for themselves by choosing games. If a player gets dominated so hard in the first 5 minutes of the game, because 1 hero is totally broken and the enemy chose him, then the player should be able to leave. There is no point in playing a game where 1 team will win in 10 minutes after the result is already apparent. Your enemy looses or knows he will loose and should not be forced to play.
Suddenly short wins and breaking the game is less fun. People play for fun. Someone winning 12 games in 1 hour with the same hero has less fun, than someone winning 2 games in 1 hour, with well earned victories and close games that he could potentially have lost. (This also makes cheating less apealing, remember as a kid, you break the rules and noone wants to play with you ? Yeah, basically that, you cheat, you get 5 minutes or less wins and don't have fun.)
This is going to make people choose less broken strategies, because while fun once in a while, it get's stale to win quickly and be able to "earn it". A quick victory because of a broken champion isn't going to feel nice, especially if the matchmaking takes longer than the actual game.
4. Limit resources. Force players to compete for resources with their own team and also the enemy. If you have a game with (nearly) unlimited resources then the game becomes trivial, it's just get the most resources as fast as possible, the character able to gain them most efficiently and beeing able to use them most efficiently will become meta. The character list becomes ordered by those factors and suddenly you have a clear cut tierlist, with little dynamic in it.
5. Give the ability to deny resources and produce stalling in progress for both sides. While this sounds boring at first, stalling is important to some degree. Those stalls should not be easy to accomplish and not last forever, but they act as equalizers.
If both sides don't gain any resouces during a period and need to battle for them or show of their skill to gain them, this will stop snowballing. If 1 player got a small/medium advantage and can just progress to the next goal without needing to risk anything, then this is going to be the easy strat. Gain advantage, defend it pretty easily, cause defense is always easier. Wait for upgrade, overpower enemy or deny him resources more easily. Repeat.
With stalling, the advantage has to be actively defended. If I don't get closer to my upgrade because both me and my enemy deny each other resource gain, then we have to fight it out tactically, my enemy even though slightly behind has a valid strategy before I snowball. I can't snowball by just defending I need to actually get 2-3 kills to gain an item, or outskill him in cs in dota, to be able to buy an item in the early/mid game.
6. Don't make it easy. Don't give the defender a too big advantage. But the give the attacker checkpoints that put up a fight if they are attacked ahead of time. In dota every hit counts, playing defensively will barely regen my hp if I ran out of regen items, which cost gold. The tower makes it hard to get cs, loose hp. Still the tower puts up a fight and shoots ahead of time if I directly click an enemy. My enemy can comfortably stay in range of his tower at the start with medicre/full health, but can't really rely on staying there forever, cause his cs is hurting.
7. Realize that if you skill ceiling is below the maximum human capabilities, then everyone is basically at the highest level in skill in the higher ranks, the only thing to be abused then to gain rank is the meta game/strategy which can be complex to figure out perfectly without using complex math. You can't do anything about that, beside try to balance it so no hero hard counters more than 3 other heroes and that most things are softcounters. This keeps the game dynamic, the meta becomes less tight and you have more variety, even at the higher level.
8. Balance, real balance. This means that anything that doesn't softcounter each other should have a 50% winrate against each other.
Softcounters shouldn't be auto-wins and not exceed 60% winrate. They should still have a hard game and some trouble with their enemies.
Hardcounters should be able to be adressed by lane swapping, so keep hardcoutners few.
9. Everything needs a downside. Anything that is just plainly good is broken. Things good in the early game shouldn't scale. High burst dmg should have high mana cost/cooldown. Put stuff into conditions in general. Keep kits unique and have a large ability space. No hero should be comfortable just doing the same thing without beeing killed in a game, the enemy team should always have counter plays.
10. Don't go overboard with variance in mobility. Blinks and teleports, slow and high movement speed should be rare. They should have a very very good design reason. If there is to much variance it's impossible to balance in the long term.
11. Give the player tradeoff upgrades (items), which can be used to counter 1 thing, but give up/weaken another thing. Spending resources on it usually is not a tradeoff (unless it's cost inefficient, but it should not be an auto include for a dominating player).
12. Limit lategame potential to a constant. If growth in a game is unlimited snowballing will never stop, so a dominating player is never going to loose his advantage.

# Answer
> -3 votes
As a player, I've found myself in the exactly position of boredom, after "solving" the game.

From my perspective I find that the more competitive a game is, the more the players tend to copy other player's effective strategy, where available. This degrades to an infinite loop of 'try-work-faster' to sharp skills and precision in RTS, MOBA and FPS.

The less challenging a game is, the more boring will be; so how do you find the perfect balance?

My answer was to play ArmA with a co-op oriented mil-sim clan (not all-realism) to always shape this Sandbox game with a different approach to a different problem with no advice and based on the improvised decision and skills of the players combined.

---
Tags: game-design
---


# Question
Title: Parent and child with different Animators
I'm animating my 2D game (Unity 5.4).

Is it a good/bad practice to have parent and child gameobjects with different Animators?

Example: a 2D bug, that has sprites for every body part. On the "body container"=parent object I add an Animator and animate all parts except the head. For the head, that is a child gameobject to the body (in scene's hierarchy) I want to add a separate Animator and animate only the head.

Also is that influencing performance in any way?

# Answer
On the side of performance, there is no impact, if you have multiple animator components on child objects and on the parent too. The questions is rather, do you need this?

Why should you just animate the head from the rest of the body? If you can answer this question in your case in any situation with yes, then go on an do what you want. If you can't find an answer leading to yes and it is just because it is easier to animate for you in such a case, go on and do it.
> 1 votes

---
Tags: unity, 2d, animation
---


# Question
Title: C++ Pass the reference of the class to a vector inside the constructor
Okay so i have an extern vector of pointer type 'Entity', and what i want to do is, when a new Entity type class gets constructed it gets pushed back in the vector of Entities, in C# this would be possible by passing 'this' as a parameter, but i'm unable to do that in c++ ! Here is my code:

'Public.h':

```
// other code
    #ifndef Entity_h
    #include "Entity.h"
    extern vector <Entity*> AllEntities;
    #endif
// other code

```

I've put the code in Include guards to not get in trouble, because i'm including 'Public.h' from 'Entity.cpp' and if i didn't have guards it would become a circular dependency !

'Public.cpp':

```
// other code
#ifndef Entity_h
vector <Entity*> AllEntities;
#endif
// other code

```

Everything fine, no errors!

'Entity.cpp':

```
#include "Public.h"
#include "Entity.h"

Entity::Entity()
{
// other code
    AllEntities.push_back(this);
}

```

i'm trying to do this, but doing this causes me some linker errors:

```
   Error    3   error LNK2005: "void __cdecl AddToAllENT(class Entity *)" (?AddToAllENT@@YAXPAVEntity@@@Z) already defined in Entity.obj    C:\Users\drin-_000\Documents\Visual Studio 2013\Projects\ECSystem\ECSystem\Public.obj   ECSystem
    Error   4   error LNK2001: unresolved external symbol "class std::vector<class Entity *,class std::allocator<class Entity *> > AllEntities" (?AllEntities@@3V?$vector@PAVEntity@@V?$allocator@PAVEntity@@@std@@@std@@A) C:\Users\drin-_000\Documents\Visual Studio 2013\Projects\ECSystem\ECSystem\Entity.obj   ECSystem
    Error   5   error LNK1120: 1 unresolved externals   C:\Users\drin-_000\Documents\Visual Studio 2013\Projects\ECSystem\Debug\ECSystem.exe    1   1   ECSystem

```

When i try to do this:

```
Entity::Entity()
{
// other code
    AllEntities->push_back(this);
}

```

it gives me these errors!

```
Error   1   error C2819: type 'std::vector<Entity *,std::allocator<_Ty>>' does not have an overloaded member 'operator ->'  c:\users\drin-_000\documents\visual studio 2013\projects\ecsystem\ecsystem\entity.cpp   9   1   ECSystem
Error   2   error C2232: '->std::vector<Entity *,std::allocator<_Ty>>::push_back' : left operand has 'class' type, use '.'  c:\users\drin-_000\documents\visual studio 2013\projects\ecsystem\ecsystem\entity.cpp   9   1   ECSystem
    3   IntelliSense: expression must have pointer type c:\Users\drin-_000\Documents\Visual Studio 2013\Projects\ECSystem\ECSystem\Entity.cpp   9   2   ECSystem

```

# Answer
> 1 votes
Eventually i fixed this, by removing the include guards in 'Public.cpp', they were unnecessary because i already put them inside 'Public.h', and they were causing the errors !

---
Tags: c++
---


# Question
Title: Unity C# - Modifying eulerAngles with slider issues
I'm using a slider to rotate an object on the z axis. The slider has a value of 1-360 (Whole Numbers); when the slider is moved, I use that value for the eulerAngles z axis value. (NOTE: The object is part of a child/parent 'string' of instantiated objects and it should only ever rotate on the local z axis). This method is working for some objects in the 'string', but not others. When it's not working, the object I'm trying to rotate spins wildly on the z axis because the objects z value is not a reflection of the slider value (I tested this in the inspector). I can't figure where these 'random' slider values are coming from.

Here is the rotation function I'm using for the sliders On Value Change event:

```
 public void SliderRotate () {
     Target.transform.eulerAngles = new Vector3(
         Target.transform.eulerAngles.x,
         Target.transform.eulerAngles.y,
         mySlider.GetComponent<Slider> ().value);
 }

```

BTW - If I change the x and y values to zero, the problem goes away. However, the objects then loose their correct orientation to their parent (I need the x and y to stay where they are).

Thanks in advance for any insight you can offer into this issue.

Windows - Unity 5.3.5f1

Here is an image that might help clarify:

# Answer
The wild rotation happens because you don't get the same number for `Target.transform.eulerAngles.x` every frame.

Internally, Euler angles that you give are converted to quaternions and when you read it back they are converted back to Euler angles. This conversion is not one-to-one because Euler angles are an ambiguous representation of 3D rotation (meaning the same rotation can be represented by more than one set of Euler angle numbers). Therefore it makes sense that it goes wild, what you give is not always what you get back.

(Btw, like @DMGregory said, you should be using localEulerAngles, but that's only part of the story.)

**Here are your options:**

**Simplest option:** Have two gameobjects per an object that you want to turn like this. They should be a parent and a child. The parent contains the rotation that's not going to change, such as `parent.transform.localEulerAngles = new Vector3(x, y, 0);` or any other rotation that makes sense. The child will have the rotation that changes, such as `child.transform.localEulerAngles = new Vector3(0, 0, mySlider.GetComponent<Slider> ().value);`. This would be the cleanest option. If you don't want to use two game objects, the two other options below may help.

**Option #2:** Keep x and y fixed. Get the x and y of the rotation in the beginning, perhaps in Start() as such:

```
float x, y;
Start() {
    x = Target.transform.localEulerAngles.x;
    y = Target.transform.localEulerAngles.y;
}

```

and then later change your function to use them, rather than reading it from transform everytime:

```
public void SliderRotate () {
    Target.transform.localEulerAngles = new Vector3(
        x,
        y,
        mySlider.GetComponent<Slider> ().value);
}

```

This will ensure that you don't keep getting different values for x and y because of Euler angles being ambiguous. Again, we use localEulerAngles because you want to use local z axis.

**Option #3:** Like the previous step but keep quaternions instead.

```
Quaternion initialRotation;
Start() {
    initialRotation = Target.transform.localRotation;
}

public void SliderRotate () {
    // you can also use any other axis other than Vector3.forward
    Target.localRotation = initialRotation * Quaternion.AngleAxis(mySlider.GetComponent<Slider> ().value, Vector3.forward);
}

```
> 1 votes

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


# Question
Title: In trying to get vertex positions on a Blender-generated mesh in Unity, they seem to be badly off?
I've imported a number of track-terrain pieces into a game I'm working on, and I would like to get the mesh vertex arrays so I can position objects at their exact end. However, when I try to collect the arrays, they're off by a huge amount. A vertex located at the start of the object is 0,-0,-0.01 and a vertex located at the end of the object is.. 1, 0, 0.1. This doesn't seem to make any sense.

These are also -after- the coordinates are transformed into world space.

For a mesh that is 16 meters long and comprised of 70 points, I would expect vertex 65 to be at 3,0,16.

This is the code I am using to collect the information.

```
CurrentObject = Instantiate(TerrainObjects[0]) as Transform;
meshFilter = CurrentObject.GetComponent<MeshFilter>();
vertices = meshFilter.mesh.vertices;
CurrentObject.transform.parent = gameObject.transform;
//Vector3 EndVectorLocation = transform.InverseTransformDirection(vertices[10]);

```

Debug.Log(transform.TransformPoint(vertices\[10\]));

Have I missed something in getting the correct transform positions?

# Answer
> 0 votes
You might want to look at the documentation of `transform.InverseTransformDirection`:

> Transforms a direction from world space to local space.

You want to do the opposite.

> You should use Transform.InverseTransformPoint if the vector represents a position in space rather than a direction.

In your case it does represent a position in space.

So the method you should be using is `transform.TransformPoint`.

However, I would not recommend you to give specific meaning to specific vertices of your 3d models. Blender does not guarantee that these numbers stay constant. So when you make the slightest modification to your models, it might break your game until you figured out the new index of the "magic vertex".

A better solution is to turn all the imported models into prefabs. Then add child game-object to them which you position at the position you want to have a special meaning. For example, when you have road segments which are straights and curves, you would place a "Connection Anchor" in the middle of both ends and then spawn the next one so their "Connection Anchors" align.

---
Tags: unity, c#, vertex, mesh
---


# Question
Title: How to iterate tiles around an index tile?
I am not exactly sure how to state this question, what I basically want to do is to seed a tile based map with some values. So I asked myself how I could spread some values outgoing from a start tile, with values being reduced the further I get away from that start tile. Does that make any sense? What algorithms are there to calculate spreading of fire for example, or pollution?

```
[0,0,0,0,0,0,0,0,
 0,0,0,0,0,0,0,0,
 0,0,0,0,0,0,0,0,
 0,0,0,0,S,0,0,0,
 0,0,0,0,0,0,0,0,
 0,0,0,0,0,0,0,0,
 0,0,0,0,0,0,0,0,]

[0,0,0,0,0,0,0,0,
 0,0,2,2,2,2,2,0,
 0,0,2,3,3,3,2,0,
 0,0,2,3,X,3,2,0,
 0,0,2,3,3,3,2,0,
 0,0,2,2,2,2,2,0,
 0,0,0,0,0,0,0,0,]

```

And what if I have another starting tile, can the values be added?

```
[2,3,3,3,2,0,0,0,
 2,3,Y,5,4,2,2,0,
 2,3,5,6,5,3,2,0,
 2,2,4,5,X,3,2,0,
 0,0,2,3,3,3,2,0,
 0,0,2,2,2,2,2,0,
 0,0,0,0,0,0,0,0,]

```

Maybe it's like an explosion. Not sure what to look for though, I cannot find anything in my endless searches on tile based games.

# Answer
> 2 votes
This looks like a job for Breadth-First Search. The algorithm in this case would work like this...

1. Initialize a "Concentration" value for each tile to 0.
2. For each source tile, initialize its Concentration value to your desired peak at that point, and add it to a Queue of tiles.
3. While the queue is non-empty...

i) remove the first tile from the queue and call it the "Parent" for this round

ii) for each (passable) "Child" tile neighbouring the Parent...

if the Child tile's Concentration is less than the Parent's Concentration minus one:

* Set the Child tile's Concentration to the Parent's Concentration minus one, and...
    * Add the Child tile to the end of the Queue (Optionally: only do this if its concentration is \> 1, so we skip redundant iteration at the outermost edges)

This will give you a linear falloff by hopcount from the nearest source. Note that doing it this way, the space between two sources will choose the larger of the concentration values from the two sources affecting it, rather than summing them together.

If you'd prefer to *sum* the concentration values, you'd make the following changes to the algorithm above:

* Also track a "Total Concentration" value for each tile.
* Whenever you set the Concentration value, *add* that number to the Total Concentration
* Process your sources one at a time. Ie. Add your first source to the queue, iterate until it's empty, then clear your Concentration values and add your second source to the queue...

---

Note that this handles the most general case of arbitrary tile connections, where tiles could be obstructed and the concentration needs to "flow around".

If instead all you need is to stamp a pyramid values in a square region of your grid, ignoring obstacles, you could do this by...

* iterating over the square region `(startX - range, startX + range)x(startY - range, startY + range)` and...
* adding the value `(range - max(abs(x - startX), abs(y - startY)) + 1)` at each tile

---
Tags: tilemap, tiles
---


# Question
Title: how to detect if an object is hit by a certain raycast in it's own code
I have been working on a sandbox game in Unity, and I am wanting to use a raycast on the cursor, but I am needing for the blocks themmselves to detect whether the cursor's raycast is hitting. I am needing the code in javaScript. Thanks in advance!!!

# Answer
You would need to:

1. Detect if the user clicked the mouse
2. Convert the mouse to a world Ray
3. Fire a raycast with the Ray
4. Use the RaycastHit object to determine if hit.collider.gameObject == this

This will end up in, when the player clicks their mouse, will fire a raycast from their mouse and determine if it hits the object that the script is running on (hence the `RaycastHit.collider.gameObject`). Using LayerMasks might also be helpful in optimizing your search.
> 2 votes

# Answer
add some event to block which is called on that block, or add some field to manager that stores last clicked block and then block can check if Manager.lastClicked = this, then it's clicked
> 2 votes

---
Tags: unity, javascript
---


# Question
Title: How to create an API for event-based, modular Java game?
I don't really know how to explain what I am trying to do that well, but yeah I'll try my best.

I'm currently creating a game with LWJGL 3, and I hope to make it event based and rather abstract as to allow the game to be hopefully easily moddable by community members through their own .jar files. To give them the ability to modify the current functions of the game, I want to make the game event based so they can listen to events and modify them or cancel them completely before my function executes, and provide a way for them to create their own structures, entities, events, artifacts(items), et cetera. I just cannot wrap my head around how to do this exactly, at least with creating the API.

I spent a lot of time researching and I just came up with allowing modules through Unity or with Lua, but that's not what I am looking for. So, what is the best way to set up an API like this? Do I create interfaces for all of my own events, entities, items, and things or do I just create base interfaces which I implement in my own classes? Then however I do this, what do I actually provide for them to create their mod/module? My whole game or just these interfaces. I just cannot figure out a good way to set up the API especially since I've never created one myself, let alone for a game.

# Answer
You may use Java 8's builtin JavaScript engine Nashorn for solving this type of problem. The main game loop update game objects with a certain frequency (x times per second)

JavaScript files may be loaded from a ZipInputStream, Jar using getResourceAsStream(), external file or even a socket. Using Zip-files make modding quite easy, especially when combining them with JSON as data files for definitions.

Just call the JavaScript implementations as regular Java using the getInterface method to get an instance of the interface.

```
public static ScriptEngine createScriptEngine() {
    return new NashornScriptEngineFactory().getScriptEngine("-strict", "--no-java");
}

public static void loadScript(final ScriptEngine scriptEngine, final InputStream inputStream) throws IOException {
        try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
            scriptEngine.eval(reader);
        } catch (ScriptException e) {
            throw new IOException(e);
        }
}

public static <C> C getInterface(final ScriptEngine scriptEngine, final String objectName, final Class<C> clazz)
        throws ScriptException {
    final Invocable invocable = (Invocable) scriptEngine;

    final Object def = scriptEngine.get(objectName);
    if (def == null) {
        throw new ScriptException("Missing object " + objectName);
    }

    final C object = invocable.getInterface(def, clazz);

    if (object == null) {
        throw new ScriptException("Failed to create instance for " + objectName);
    }

    return object;
}

```

Using an interface like this:

```
public interface ScenarioCallback {
    public boolean isLevelUnlocked(int level);
}

```

JavaScript code in scenario.js

```
var Scenario1 = new Object();

Scenario1.isLevelUnlocked = function(level) {
    return true;
};

```

Use callback from Java

```
ScriptEngine scriptEngine = createScriptEngine();

loadScript(scriptEngine, getClass().getResourceAsStream("/scenario.js"));

ScenarioCallback scenarioCallback = getInterface(scriptEngine, "Scenario1", ScenarioCallback.class);

if(scenarioCallback.isLevelUnlocked(7)) {
    // You win
}

```

Use small simple methods that for callbacks. But you need to identify what type of game objects that you use, and that is unique for each game.
> 1 votes

# Answer
I haven't done this before, but the approach I would take would be to have a `mods` folder that I put in the classpath. There would be a high level `EventListener` interface that all listeners must implement, and you can use reflection to find all implemented concrete classes. Then, create an instance of each implemented concrete class and load it into your event system. You can create sub-interfaces for specific interface types (`ItemEventListener`, `BuildingEventListener`, `CharacterEventListener`, etc.) that can be shuffled into the appropriate systems. If you want to get really complex, you can have listeners for different stages (`BeforeAttackListener`, `AttackListener`, `AfterAttackListener`). You'll also need interfaces for the concrete objects (`Item`, `Character`, `Building`) and for events (`ItemEvent`, `CharacterEvent`, `BuildingEvent`).

The interfaces will have two methods, `fireEvent` and `getPriority`. `fireEvent` will take one argument, a subtype of `Event`. The method will modify the event as appropriate (reduce HP, remove from inventory, etc.) and return the event. The event will traverse the stack of relevant listeners until it comes out the other side, resulting in the final state of the event. Then, the event will act upon its relevant concrete objects. You don't want the listeners acting *directly* on the objects while the event traverses the listener stack, otherwise you wouldn't be able to override previous listener behaviors. `getPriority` is used to determine stack order.

Obviously, the final implementation will only bear a passing resemblance to this, as additional complexities are discovered, but this is where I would start. Then, once you finish the system, the *really* hard part will begin: documenting your API! In addition to explaining this system, you will *also* need to document every single one of *your* `Listener`s, `Event`s, and `ConcreteObject`s along with their various attributes and priorities. Which, honestly, sounds like a job for a custom Javadoc generator.
> 0 votes

---
Tags: java, architecture, lwjgl, events, modding
---


title: When to use Command and RpcClient

text:
# Question
Title: When to use Command and RpcClient
I'm working on a multiplayer turn-based project in unity 5.4 and Unity Networking. I'm trying to learn Networking and one thing I am wondering is when to use `[Command]` and `[RpcClient]`.

I know the difference between both :

* `Command` are executed by the server, and client are synced with it (I.E.: player X fired a bullet, send the command to the server, calculated the trajectory, and sync it with the clients).
* `RpcClient` are command sent to the client (I.E. Player died?)

When I write a function, what question do I need to ask myself to know if it's a Command or a Remote Procedure Call.

# Answer
> 6 votes
### Background

In normal client-server games, the server is *authoritative* meaning it has the final say over how the games state exists and is in charge of making sure the clients know the current game state. It does this by taking all of the game logic and running it instead of the clients\* and then sending updates as it sees fit. The most basic building blocks of these mechanics are the `[Command]`, `[ClientRpc]`, and `[TargetRpc]` attributes. These aren't super high level like the automatic syncing stuff like `[SyncVar]` and `NetworkTransforms` nor are they super low level like sockets.

*It does this to the extent possible by which to not introduce too much network bandwidth (causing poor performance) and complexity. So usually the client is responsible for simulating and predicting physics, lighting, and other intensive tasks while the server just syncs object state, positions, and provides game notifications for playing client-side sounds and changing the UI.

### How they differ

* \[Command\] - The `[Command]` attribute is called by a client (!) and executed by the server on that same object. The client can only call this on objects it has authority over. These usually relay some sort of client intent like fire my gun or send a chat message. Ignoring all the automatic syncing (`SyncVars`, `NetworkTransform`, etc) this is the only way for the client to do something on the server and as such all client network actions that have the chance to change the game or affect other clients need to be a `[Command]` that the client can call to run on the server.
* \[ClientRpc\] - The `[ClientRpc]` attribute is called on the server and executed on **all** of the clients that are currently connected to the server for a given object. `[ClientRpc]` is most commonly used to notify the clients of game changes like a change in score or that they have died (to play sound and death animations on all players' screens).
* \[TargetRpc\] - **Added in Unity 5.4** \- The `[TargetRpc]` attribute is the same as above but is only executed on a **specific** client when called on the server. The server passes a `NetworkConnection` object to denote which client it would like to execute the `TargetRpc` on.

A super helpful overview of all this (including a nifty diagram) can be found in the UNET tutorial series.

### When server authority matters

What I described above is the most common uses for these type of commands where server authority is very important (like competitive games). More casual games where cheating isn't a huge deal (coop games, games where you trust the other players to not cheat) might be structured differently.

An example might be a game where you fire a gun to shoot an enemy. In a non-competitive game where cheating isn't an issue, I might have a `ShotObject` command which clients call with the objects they shot. This is really easy to cheat but low complexity. In a competitive multiplayer game however, I would need have a `FireGun` command that takes no arguments and simulates the Raycast for the gunshot on the server alone so clients couldn't cheat. This introduces the added complexity of backing up the server simulation to when the client shot, doing the raycast, and then proceeding with the game.

The basic rule here is that when server authority matters, run as much as you can on the server. When it doesn't you're free to do what you want.

---
Tags: unity, multiplayer, unity-networking
---


# Question
Title: How to get status of LEDs on keyboard and blink LED on keyboard from Unity 3D on Android?
On Android, with Unity how do I get the status of caps lock, scroll lock and num lock LED's and blink these LEDs for caps lock, scroll lock and num lock from Unity 3D?

Blinking the LEDs will of course enable caps, num or scroll lock.

# Answer
Unity3D's Input class has no function for firing a keypress, only reading it.

You'll need to find some other solution to emulate keypresses. Which on other platforms isn't all that easy ( Windows w/ user32.dll hook, MAC OSX (similar to Windows), Linux with xdotool ).

On Android these won't do (as while Android is Linux, it probably won't work with xdotool as there's no X windowing system). My proposal would be to use a Java program with this code and call it from the JNI from C#.
> 1 votes

---
Tags: unity, android, keyboard
---