Complexity of a reaching-a-node 2 player graph game - time-complexity

The game:
there is an undirected simple graph with some special, winning nodes, and 2 players, who take turns
player one (Seeker) moves on the graph (sits on a node, and moves along an edge), and tries to reach a winning node. If she can, she wins.
player two (Eraser) can turn the winning nodes into regular nodes. She wins, if the other player can't win, that is, she erased all the winning nodes into regular ones.
I am interested about this game.
E.g. if this game "can be solved" in polynomial or even in NP or coNP time, that is, whether it is possible to decide who has a winning strategy.
Or whether this game is in the literature, and is known to be easy or hard, possibly in a different form.
Thank you!
edit:
I gave the players names according to their roles.
P1's position is part of the initial setup

Related

Concept of Program Making Own Class Instances

This is probably a basic question with a simple answer, but I just can't seem to wrap my head around the logic behind it.
I will start with a simple example with a well-known Java game, Minecraft. A player is put into a world and is allowed to interact with different objects. Say the player wants wood. He sees a tree, walks over, and cuts it down. He sees another tree, walks over, and does the same. He can do this as many times as he wants, and the game will load in more trees if the player explores far enough. But how is this done? In other words, how can a program make an essentially endless amount of trees that the player will always be able to interact with?
I imagine there is a tree class in the code. But obviously, the programmer has not coded in different class instances, such as tree1, tree2, and so on, since he has no idea how many trees will need to be loaded in the game. So how does the program do this without being told how many trees there will be?
In other words, I do not understand how programs can decide on their own to make x number of class instances instead of the programmer having to manually code his/her own class instances. How do game developers and other programmers do this?
Thank you.
Consider how we might generate a random game map. Let's say the environment of the map will be in a forest. What sorts of objects are part of a forest?
Trees
Critters (i.e. squirrels, rabbits)
Forest floor texture (i.e. grass or fallen leaves)
We start with a basic 100x100 unit game map. We will have the program generate a number of trees between 10 and 30, and also generate the tree's X and Y coordinates with the condition that no tree can have the same X and Y coordinates. We do the same for the other objects.
Now we tell the program to load the game map with all of these objects in place. Done.
Consider a simple grid where each position on the grid can be occupied
by an object. The object could be a tree, rock, or creature.
In this world, I have areas on the map defined as 'growable'.
In these areas, something will grow if there isn't something there already.
The game would have a set of turns. During each turn, I run a routine to
find all the growable spots, and if there isn't something growing there
randomly determine if something should sprout. This way if someone
chops down a tree, that spot can sprout a new tree later in the game.
Perhaps the game is more complex and a simple grid isn't good enough.
Whatever the case, the game has to track all the objects in some way.

SKPhysicsBody optimization

I have a 2D sidescrolling game. Right now, in order to jump, the player must be touching the ground. Therefor, I have a boolean, isOnGround, that is set to YES when the player collides with a tile object, and no when the player jumps. This generates a LOT of calls to didBeginContact method, slowing down the game.
Firstly, how can I optimise this by using one big physics body for the tiles on the floor (for example clustering multiple adjacent tiles into one single physics body)?
Secondly, is this even efficient? Is there a better way to detect if the play is on the ground? My current method opens up a lot of bugs, for example wall jumping. If a player collides with a wall, isOnGround becomes YES and allows the player to jump.
Having didBeginContact called numerous times should in no way slow down your game. If you are having performance issues, I suspect the problem is probably elsewhere. Are you testing on device or simulator?
If you are using the Tiled app to create your game map, you can use the Objects Layer to create a individual objects in your map which your code can translate into physics bodies later on.
Using physics and collisions is probably the easiest way for you to determine your player's state in relation to ground contact. To solve your wall issue, you simply make a wall contact a different category than your ground. This will prevent the isOnGround to be set to YES.
You could use the physics engine to detect when jumping is enabled, (and this is what I used to do in my game). However I too have noticed significant overhead using the physics engine to detect when a unit was on a surface and that is because contact detection in sprite kit for whatever reason is expensive, even when collisions are already enabled. Even the documentation notes:
For best performance, only set bits in the contacts mask for
interactions you are interested in.
So I found a better solution for my game (which has 25+ simultaneous units that all need surface detection). Instead of going through the physics engine, I just did my own surface calculation and cache the result each game update. Something like this:
final class func getSurfaceID(nodePosition: CGPoint) -> SurfaceID {
//Loop through surface rects and see if position is inside.
}
What I ended up doing was handling my own surface detection by checking if the bottom point of my unit was inside any of the surface frames. And if your frames are axis-aligned (your rectangles are not rotated) you can perform even faster checks to see if the point is inside the frame.
This is more work in terms of level design because you will need to build an array of surface frames either dynamically from your tiles or manually place surface frames in your world (this is what I did).
Making this change reduced the cpu time spent on surface detection from over 20% to 0.1%. It also allows me to check if any arbitrary point lies on a surface rather than needing to create a physics body (which is unnecessary overhead). However this solution obviously won't work for you if you need to use contact detection.
Now regarding your point about creating one large physics body from smaller ones. You could group adjacent floor tiles using a container node and recreate a physics body that fits the nodes that are grouped. Depending on how your nodes are grouped and how you recycle tiles this can get complicated. A better solution would be to create large physics bodies that just overlap your tiles. This would reduce the number of total physics bodies, as well as the number of detections. And if used in combination with the surface frames solution you could really reduce your overhead.
I'm not sure how your game is designed and what its requirements are. I'm just giving you some possible solutions I looked at when developing surface detection in my game. If you haven't already you should definitely profile your game in instruments to see if contact detection is indeed the source of your overhead. If you game doesn't have a lot of contacts I doubt that this is where the overhead is coming from.

Using Pathfinding, such as A*, for NPC's & character without Tiles

I've been reading a book called "iOS Games by Tutorials" (recommend it to anyone interested in making iPhone games) & I'm learning how to make Tiled Maps with Sprite Kit with an overhead view (like the legend of zelda link's awakening). So far, I have made a tiled map using tiles that are 32x32, placed the player character & several NPC's into the world. Even made the NPC's randomly move around the map, though the way it teaches in the book is having them move from tile to tile (any of the 8 tiles surrounding the NPC at any time - if a tile has some property such as categoryBitMask then it won't move to that tile).
I am going to change NPC movement to physics-based (which is its own problem) just like the player character has right now (which means NPC's will collide with objects that have a physicsBody like the player character does). It's more fluid & dynamic.
But here is where the question begins. I want to implement Pathfinding (such as the A* algorithm) into the NPC & player character movement due to the map containing buildings, water, trees, etc. with their own physicsBodies. It's one thing to limit NPC's random movement or to force them to walk a predetermined path (which will kill the point of this game), but it's another to have to tap the screen very often to have the player character avoid all the buildings/trees he has to walk past. I don't want to use a grid system. Is it possible to implement some pathfinding algorithm into x,y coordinates? Is this more resource intensive? Could you share your thoughts about this?
Thank you.
This is a very interesting topic.
There are algorithms for finding paths in continuous spaces. For example, you can use a potential based method with the objective having a very low potential and obstacles being "hills" (perhaps infinitely high, although this requires a bit of care). The downside of potential methods is that you have to take special precautions to keep them from getting stuck at a local minimum. Situations like this
P
+----+
| M|
| |
+ ---+
Where M is a monster trying to get to the player, P can occur. In the example, the monster is at a local minimum, and it would have to go to a higher potential in order to get out the door at the lower left of the building. A variant of potential algorithms (in fact, it's often useful to reduce it to one), is to assign anti-gravity to obstacles and gravity to objectives. This is also somewhat non-deterministic and requires special precautions to avoid getting "stuck".
As #rickster points out, SpriteKit provides an SKFieldNode class that can help you implement a potential based solution.
Other approaches include "wall following" (for example, Pledge's algorithm) and are useful for finding your way around in a maze like environment.
One drawback to continuous methods is that NPC movement will often seem a bit unnatural -- for example, even if our monster in the example above is able to decide that it's at a local minimum and increase the "temperature" of it's search (that is, make larger moves, perhaps at random, against the potential gradient), it will bounce around instead of going straight for the door.
An alternative to searching in continuous spaces is to quantize the space. A simple method is to tile it, cover it with polygons, or represent it as a quadtree. Essentially, you want to have a way of mapping every point in the continuous space to a vertex on a graph representing the quantized space. At this point, graph search algorithms like A* and friends are applicable.
Graph search is somewhat resource intensive, but for a 2d zelda like game, it should be doable on a mobile device, especially with various optimizations like only "waking up" NPCs that are within a certain distance of the player (think aggro).
This page is a bit thin on implementation details, but it'll give you the right terms to google.
As always, start simple and iterate. Tiling is incredibly easy, and will let you experiment with the graph search method before optimizing.

Implementation of achievement systems in modern, complex games

Many games that are created these days come with their own achievement system that rewards players/users for accomplishing certain tasks. The badges system here on stackoverflow is exactly the same.
There are some problems though for which I couldn't figure out good solutions.
Achievement systems have to watch out for certain events all the time, think of a game that offers 20 to 30 achievements for e.g.: combat. The server would have to check for these events (e.g.: the player avoided x attacks of the opponent in this battle or the player walked x miles) all time.
How can a server handle this large amount of operations without slowing down and maybe even crashing?
Achievement systems usually need data that is only used in the core engine of the game and wouldn't be needed out of there anyway if there weren't those nasty achievements (think of e.g.: how often the player jumped during each fight, you don't want to store all this information in a database.). What I mean is that in some cases the only way of adding an achievement would be adding the code that checks for its current state to the game core, and thats usually a very bad idea.
How do achievement systems interact with the core of the game that holds the later unnecessary information? (see examples above)
How are they separated from the core of the game?
My examples may seem "harmless" but think of the 1000+ achievements currently available in World of Warcraft and the many, many players online at the same time, for example.
Achievement systems are really just a form of logging. For a system like this, publish/subscribe is a good approach. In this case, players publish information about themselves, and interested software components (that handle individual achievements) can subscribe. This allows you to watch public values with specialised logging code, without affecting any core game logic.
Take your 'player walked x miles' example. I would implement the distance walked as a field in the player object, since this is a simple value to increment and does not require increasing space over time. An achievement that rewards players that walk 10 miles is then a subscriber of that field. If there were many players then it would make sense to aggregate this value with one or more intermediate broker levels. For example, if 1 million players exist in the game, then you might aggregate the values with 1000 brokers, each responsible for tracking 1000 individual players. The achievement then subscribes to these brokers, rather than to all the players directly. Of course, the optimal hierarchy and number of subscribers is implementation-specific.
In the case of your fight example, players could publish details of their last fight in exactly the same way. An achievement that monitors jumping in fights would subscribe to this info, and check the number of jumps. Since no historical state is required, this does not grow with time either. Again, no core code need be modified; you only need to be able to access some values.
Note also that most rewards do not need to be instantaneous. This allows you some leeway in managing your traffic. In the previous example, you might not update the broker's published distance travelled until a player has walked a total of one more mile, or a day has passed since last update (incrementing internally until then). This is really just a form of caching; the exact parameters will depend on your problem.
You can even do this if you don't have access to source, for example in videogame emulators. A simple memory-scan tool can be written to find the displayed score for example. Once you have that your achievement system is as easy as polling that memory location every frame and seeing if their current "score" or whatever is higher than their highest score. The cool thing about videogame emulators is that memory locations are deterministic (no operating system).
There are two ways this is done in normal games.
Offline games: nothing as complex as pub/sub - that's massive overkill. Instead you just use a big map / dictionary, and log named "events". Then every X frames, or Y seconds (or, usually: "every time something dies, and 1x at end of level"), you iterate across achievements and do a quick check. When the designers want a new event logged, it's trivial for a programmer to add a line of code to record it.
NB: pub/sub is a poor fit for this IME because the designers never want "when player.distance = 50". What they actually want is "when player's distance as perceived by someone watching the screen seems to have travelled past the first village, or at least 4 screen widths to the right" -- i.e. far more vague and abstract than a simple counter.
In practice, that means that the logic goes at the point where the change happens (before the event is even published), which is a poor way to use pub/sub. There are some game engines that make it easier to do a "logic goes at the point of receipt" (the "sub" part), but they're not the majority, IME.
Online games: almost identical, except you store "counters" (int that goes up), and usually also: "deltas" (circular buffers of what's-happened frame to frame), and: "events" (complex things that happened in game that can be hard-coded into a single ID plus a fixed-size array of parameters). These are then exposed via e.g SNMP for other servers to collect at low CPU cost and asynchronously
i.e. almost the same as 1 above, except that you're careful to do two things:
Fixed-size memory usage; and if the "reading" servers go offline for a while, achievements won in that time will need to be re-won (although you usually can have a customer support person manually go through the main system logs and work out that the achievement "probably" was won, and manually award it)
Very low overhead; SNMP is a good standard for this, and most teams I know end up using it
If your game architecture is Event-driven, then you can implement achievements system using finite-state machines.

Representing the board in a boardgame

I'm trying to write a nice representation of a boardgame's board and the movement of players around it. The board is a grid of tiles, players can move up, down, left or right. Several sets of contiguous tiles are grouped together into named regions. There are walls which block movement between some tiles.
That's basically it. I think I know where to start if all the players were human controlled, but I'm struggling with what happens with a computer controlled player. I want the player to be able to say to itself: "I'm on square x, I want to go to region R a lot, and I want to go to region S a little. I have 6 moves available, therefore I should do..."
I'm at a loss where to begin. Any ideas? This would be in a modern OO language.
EDIT: I'm not concerned (yet) with the graphical representation of the board, it's more about the route-finding part.
I'd say use a tree structure representing each possible move.
You can use a Minimax-type algorithm to figure out what move the computer should take.
If the problem is with pathfinding, there are quite a few pathfinding algorithms out there.
The Wikipedia article on Pathfinding has a list of pathfinding algorithms. One of the common ones used in games is the A* search algorithm, which can do a good job. A* can account for costs of passing over different types of areas (such as impenetrable walls, tiles which take longer to travel on, etc.)
In many cases, a board can be represented by a 2-dimensional array, where each element represents a type of tile. However, the requirement for regions may make it a little more interesting to try to solve.
Have a Player class, which has Map field associating Squares to probability of moving there, that is, Map<Square, Double> if you'll represent them as a 0..1 double.
Have a Board class encapsulating a series of Squares. Each Square will have four booleans or similar to mark where it has a wall, its coordinates, and which Player, if any, is on it.
I can tell you what worked for me on a commercial board game style product.
Break your representation of the board and core game logic into it's own module, with well defined interfaces to the rest of the game. We had functions like bool IsValidMove(origin, dest), and bool PerformMove(origin, dest), along with interfaces back to the GUI such as AnimateMove(gamePieceID, origin, dest, animInfo).
The board and rules only knew the state of the board, and what was valid to do. It didn't know anything about rendering, AI, animations, sound, input, or anything else. Each frame, we would handle input from the user at the GUI level, send commands to the board/game state code, and then be done. The game state code would get commands, resolve if they were valid or not, update the game state and board, then send messages back to the GUI to visually represent the new state of teh board. These updates were queued by the visual representation system, so we could batch a bunch of animations to happen in sequence.
The good thing about this is that the board doesn't know or care about human vs. AI players. Your AI can be a separate submodule that acts on it's turn. It can send the same commands as the human player, and the game logic and visual results will be the same. You'll need to either have a local per-AI bit of info about the game board state, or expose some BoardSnapshot() functionality from the game logic that lets the AI "see" the board, but that's it. Alternately, you could register each AI as an Observer Pattern on the game state, so they get notified when the board updates as well, in case they need to do any complex realtime planning.
Keeping each section of your game separate and isolated will help with unit testing, and provide a more robust system. Well defined interfaces are your friend.
If you are looking for in-memory representation of the games (and it's state), a matrix is the simplest. However, depending on the complexity of the board, the strategy, you may have to maintain a list of states.
If you mean on-screen representation, you'd need some graphics library to begin with.