## What are the six basic primitives in Turing Complete - turing-machines

### Snake Game Artificial Intelligence

```I am developing a snake game for iOS:
https://github.com/ScottBouloutian/Snake
My goal is to have the AI complete the game of snake optimally (have the snake fill the board).
I am using IDA* to find a path from a snake's current location to the food. This works. However, the algorithm doesn't take into account the fact that it may need to get more food in the future. As a result, sometimes it tends to box itself in.
i.e. The snake's goal at any given time is to find the food, whereas it's goal should be to fill the board (finding food along the way).
How can I add to or modify this approach to make the AI win the game of snake? Is there a better approach I should use instead? I'm just trying to come up with some ideas. Thanks!
```
```If a board is a static rectangle (not torus - so no crossing though the borders) then the only optimal strategy is to find a set of longest closed paths through the board, such that each point in the board is in at least one path.
If a board is empty (there are no obstacles) then there exists an "ultimate" path in the form
16|.1|.6|.7
15|.2|.5|.8
14|.3|.4|.9
13|12|11|10
which goes through all tiles, snake following this pattern will eventually eat all food, and fill the whole board
If there are some obstacles, then such path does not have to exist, then you should find set of such longest paths, and switch between them, when food appears in the unreachable spot of a current path.
For example
#######
#.....#
#.#.#.#
#.....#
#######
Here you have two paths you have to consider, one-longest, going around the whole board, but missing the central spot, and one small loop going through it. As long as food does not appear in the center, you should use the outer loop. Hopefully, if food appears in the center when you fill all the remaining blocks - you will "win". If it appears there sooner - you have to eat it (switch to the other loop) and depending on your current length - you will get back to the best loop, or hit your tail and "lose". In each case, your score will be the best possible to achieve on the board with this locations of foods.
Non A* based approach will find the optimum, this is completely different problem, you should look for the longest closed path, not shortest.```

### Pacman: how do the eyes find their way back to the monster hole?

```I found a lot of references to the AI of the ghosts in Pacman, but none of them mentioned how the eyes find their way back to the central ghost hole after a ghost is eaten by Pacman.
In my implementation I implemented a simple but awful solution. I just hard coded on every corner which direction should be taken.
Are there any better/or the best solution? Maybe a generic one that works with different level designs?
```
```Actually, I'd say your approach is a pretty awesome solution, with almost zero-run time cost compared to any sort of pathfinding.
If you need it to generalise to arbitrary maps, you could use any pathfinding algorithm - breadth-first search is simple to implement, for example - and use that to calculate which directions to encode at each of the corners, before the game is run.
EDIT (11th August 2010): I was just referred to a very detailed page on the Pacman system: The Pac-Man Dossier, and since I have the accepted answer here, I felt I should update it. The article doesn't seem to cover the act of returning to the monster house explicitly but it states that the direct pathfinding in Pac-Man is a case of the following:
continue moving towards the next intersection (although this is essentially a special case of 'when given a choice, choose the direction that doesn't involve reversing your direction, as seen in the next step);
at the intersection, look at the adjacent exit squares, except the one you just came from;
picking one which is nearest the goal. If more than one is equally near the goal, pick the first valid direction in this order: up, left, down, right.
```
```I've solved this problem for generic levels that way: Before the level starts, I do some kind of "flood fill" from the monster hole; every tile of the maze that isn't a wall gets a number that says how far it is away from the hole. So when the eyes are on a tile with a distance of 68, they look which of the neighbouring tiles has a distance of 67; that's the way to go then.
```
```For an alternative to more traditional pathfinding algorithms, you could take a look at the (appropriately-named!) Pac-Man Scent Antiobject pattern.
You could diffuse monster-hole-scent around the maze at startup and have the eyes follow it home.
Once the smell is set up, runtime cost is very low.
Edit: sadly the wikipedia article has been deleted, so WayBack Machine to the rescue...
```
```You should take a look a pathfindings algorithm, like Dijsktra's Algorithm or A* algorithm. This is what your problem is : a graph/path problem.
```
```Any simple solution that works is maintainable, reliable and performs well enough is a good solution. It sounds to me like you have already found a good solution ...
An path-finding solution is likely to be more complicated than your current solution, and hence more likely to require debugging. It will probably also be slower.
IMO, if it ain't broken, don't fix it.
EDIT
IMO, if the maze is fixed then your current solution is good / elegant code. Don't make the mistake of equating "good" or "elegant" with "clever". Simple code can also be "good" and "elegant".
If you have configurable maze levels, then maybe you should just do the pathfinding when you initially configure the mazes. Simplest would be to get the maze designer to do it by hand. I'd only bother automating this if you have a bazillion mazes ... or users can design them.
(Aside: if the routes are configured by hand, the maze designer could make a level more interesting by using suboptimal routes ... )
```
```In the original Pacman the Ghost found the yellow pill eater by his "smell" he would leave a trace on the map, the ghost would wander around randomly until they found the smell, then they would simply follow the smell path which lead them directly to the player. Each time Pacman moved, the "smell values" would get decreased by 1.
Now, a simple way to reverse the whole process would be to have a "pyramid of ghost smell", which has its highest point at the center of the map, then the ghost just move in the direction of this smell.
```
```Assuming you already have the logic required for chasing pacman why not reuse that? Just change the target. Seems like it would be a lot less work than trying to create a whole new routine using the exact same logic.
```
```It's a pathfinding problem. For a popular algorithm, see http://wiki.gamedev.net/index.php/A*.
```
```How about each square having a value of distance to the center? This way for each given square you can get values of immediate neighbor squares in all possible directions. You pick the square with the lowest value and move to that square.
Values would be pre-calculated using any available algorithm.
```
```I think your solution is right for the problem, simpler than that, is to make a new version more "realistic" where ghost eyes can go through walls =)
```
```Here's an analog and pseudocode to ammoQ's flood fill idea.
queue q
enqueue q, ghost_origin
set visited
while q has squares
p <= dequeue q
for each square s adjacent to p
if ( s not in visited ) then
s.returndirection <= direction from s to p
enqueue q, s
end if
next
next
The idea is that it's a breadth-first search, so each time you encounter a new adjacent square s, the best path is through p. It's O(N) I do believe.
```
```I don't know much on how you implemented your game but, you could do the following:
Determine the eyes location relative position to the gate. i.e. Is it left above? Right below?
Then move the eyes opposite one of the two directions (such as make it move left if it is right of the gate, and below the gate) and check if there are and walls preventing you from doing so.
If there are walls preventing you from doing so then make it move opposite the other direction (for example, if the coordinates of the eyes relative to the pin is right north and it was currently moving left but there is a wall in the way make it move south.
Remember to keep checking each time to move to keep checking where the eyes are in relative to the gate and check to see when there is no latitudinal coordinate. i.e. it is only above the gate.
In the case it is only above the gate move down if there is a wall, move either left or right and keep doing this number 1 - 4 until the eyes are in the den.
I've never seen a dead end in Pacman this code will not account for dead ends.
Also, I have included a solution to when the eyes would "wobble" between a wall that spans across the origin in my pseudocode.
Some pseudocode:
x = getRelativeOppositeLatitudinalCoord()
y
origX = x
while(eyesNotInPen())
x = getRelativeOppositeLatitudinalCoordofGate()
y = getRelativeOppositeLongitudinalCoordofGate()
if (getRelativeOppositeLatitudinalCoordofGate() == 0 && move(y) == false/*assume zero is neither left or right of the the gate and false means wall is in the way */)
while (move(y) == false)
move(origX)
x = getRelativeOppositeLatitudinalCoordofGate()
else if (move(x) == false) {
move(y)
endWhile
```
```dtb23's suggestion of just picking a random direction at each corner, and eventually you'll find the monster-hole sounds horribly ineficient.
However you could make use of its inefficient return-to-home algorithm to make the game more fun by introducing more variation in the game difficulty. You'd do this by applying one of the above approaches such as your waypoints or the flood fill, but doing so non-deterministically. So at every corner, you could generate a random number to decide whether to take the optimal way, or a random direction.
As the player progresses levels, you reduce the likelihood that a random direction is taken. This would add another lever on the overall difficulty level in addition to the level speed, ghost speed, pill-eating pause (etc). You've got more time to relax while the ghosts are just harmless eyes, but that time becomes shorter and shorter as you progress.
```
```This was the best source that I could find on how it actually worked.
http://gameai.com/wiki/index.php?title=Pac-Man#Respawn
When the ghosts are killed, their disembodied eyes return to their starting location. This is simply accomplished by setting the ghost's target tile to that location. The navigation uses the same rules.
It actually makes sense. Maybe not the most efficient in the world but a pretty nice way to not have to worry about another state or anything along those lines you are just changing the target.
Side note: I did not realize how awesome those pac-man programmers were they basically made an entire message system in a very small space with very limited memory ... that is amazing.
```
```Short answer, not very well. :) If you alter the Pac-man maze the eyes won't necessarily come back. Some of the hacks floating around have that problem. So it's dependent on having a cooperative maze.
```
```I would propose that the ghost stores the path he has taken from the hole to the Pacman. So as soon as the ghost dies, he can follow this stored path in the reverse direction.
```
```Knowing that pacman paths are non-random (ie, each specific level 0-255, inky, blinky, pinky, and clyde will work the exact same path for that level).
I would take this and then guess there are a few master paths that wraps around the entire
maze as a "return path" that an eyeball object takes pending where it is when pac man ate the ghost.
```
```The ghosts in pacman follow more or less predictable patterns in terms of trying to match on X or Y first until the goal was met. I always assumed that this was exactly the same for eyes finding their way back.
```
```Before the game begins save the nodes (intersections) in the map
When the monster dies take the point (coordinates) and find the
nearest node in your node list
Calculate all the paths beginning from that node to the hole
Take the shortest path by length
Add the length of the space between the point and the nearest node
Draw and move on the path
Enjoy!
```
```My approach is a little memory intensive (from the perspective of Pacman era), but you only need to compute once and it works for any level design (including jumps).
Label Nodes Once
When you first load a level, label all the monster lair nodes 0 (representing the distance from the lair). Proceed outward labelling connected nodes 1, nodes connected to them 2, and so on, until all nodes are labelled. (note: this even works if the lair has multiple entrances)
I'm assuming you already have objects representing each node and connections to their neighbours. Pseudo code might look something like this:
public void fillMap(List<Node> nodes) { // call passing lairNodes
int i = 0;
while(nodes.count > 0) {
// Label with distance from lair
nodes.labelAll(i++);
// Find connected unlabelled nodes
nodes = nodes
.flatMap(n -> n.neighbours)
.filter(!n.isDistanceAssigned());
}
}
Eyes Move to Neighbour with Lowest Distance Label
Once all the nodes are labelled, routing the eyes is trivial... just pick the neighbouring node with the lowest distance label (note: if multiple nodes have equal distance, it doesn't matter which is picked). Pseudo code:
public Node moveEyes(final Node current) {
return current.neighbours.min((n1, n2) -> n1.distance - n2.distance);
}
Fully Labelled Example
```
```For my PacMan game I made a somewhat "shortest multiple path home" algorithm which works for what ever labyrinth I provide it with (within my set of rules). It also works across them tunnels.
When the level is loaded, all the path home data in every crossroad is empty (default) and once the ghosts start to explore the labyrinth, them crossroad path home information keeps getting updated every time they run into a "new" crossroad or from a different path stumble again upon their known crossroad.
```
```The original pac-man didn't use path-finding or fancy AI. It just made gamers believe there is more depth to it than it actually was, but in fact it was random. As stated in Artificial Intelligence for Games/Ian Millington, John Funge.
Not sure if it's true or not, but it makes a lot of sense to me. Honestly, I don't see these behaviors that people are talking about. Red/Blinky for ex is not following the player at all times, as they say. Nobody seems to be consistently following the player, on purpose. The chance that they will follow you looks random to me. And it's just very tempting to see behavior in randomness, especially when the chances of getting chased are very high, with 4 enemies and very limited turning options, in a small space. At least in its initial implementation, the game was extremely simple. Check out the book, it's in one of the first chapters.```

### NetLogo - Checkers(Draughts) [closed]

```This year I need to finish my bachelor theses, and my task is to create a game known as checkers(or draughts). It wouldn't be a problem, but I have to write it in NetLogo using the Mutli-agent approach. So I cant use those well-known algorithms as Min-max or alfa-beta pruning. As I said, I have to use the Multi-agent approach, because in NetLogo every single piece is an agent, and they can communicate with each other. So as my teacher said me, I have to create a completely new algorithm. Could someone give me any advice or suggestion how to start, or describe it how it should work?
```
```You can get ideas from this model and get started to develop your own:
CHECKERS by ALBERT LEE MCS1 PD. 5
This is the board game checkers. It follows the same rules as regular checkers, but without double-jumps, or triple-jumps, etc. The goal of the game is to jump every single of your opponent's pieces. Jumping pieces is done by jumping diagonally, over an opponent's piece. Only one color of the board is used for moving. Players take turns moving. On a regular move, when you don't want to jump an opponents piece, movement of one diagonal space is allowed. A red piece can only move in the direction toward the black pieces when the board is set up, and the black pieces do likewise. However, when either player's pieces get to the other end of the board, they become a king, known as "kinging," and either color king can move both forwards and backwards. The same one diagonal space rule applies, unless the king jumps, which it can jump also either forwards or backwards.
In my program, there are two steps to moving. First, you select the piece with your mouse. Then, you select the patch that you want to move the piece to. If you select a piece and select another piece instead of the patch, instead of moving the initially selected piece to that new piece, the new piece becomes selected, and the same rule of moving applies. To jump a piece, select the piece you want to jump with, and if the piece you want to jump is "jumpable," which means that the piece you want to jump with is one space diagonally with the piece you want to jump, and the next patch in that direction has no pieces. After selecting the piece you want to jump with, select that patch with no pieces. The "jumped" piece leaves the board.```

### advantages of a 2 stack PDA and a multitape Turing Machine

```What are the advantages of a 2 stack PDA and a multitape Turing Machine?
2 stack:
Can work like a Turing Machine using one stack as the left tape and one as the right
Can take context sensetive data
2 Tape:
Seperates the input and the computation
Anymore?
```
```A 2 stack PDA can not only work like a Turing machine, it is functionally equivalent to a Turing machine. This answer on the CS stack exchange goes into further detail .
This wikipedia article explains that a multitape Turing machine can always be represented by a single tape Turing machine, and therefore cannot compute anything a single tape Turing machine cannot. There can be an advantage to having multiple tapes in that the multitape machine will be faster.
```
```Pair pieces of this answer,
Firstly, the class of languages acknowledged by Turing Machines is not context sensitive, it's recursively enumerable (context sensitive is the class of languages you get from directly made automata).
The second part, considering we adjust the question, is that yes, a two-stack PDA is as robust as a TM. It's mildly simpler to believe that we're using the model of TMs that has a tape that's incessant in one direction only (though both directions are not much harder, and equivalent).
To see the equality, just think of the first stack as the contents of the tape to the left of the popular position, and the second as the contents to the right. Start by pushing the normal "bottom of stack" markers on both stacks, then we can simulate the TM by popping from the right stack and pushing to the left to move right, and vice versa to move left. If we hit the bottom of the left stack we behave accordingly (halt and reject, or stay where you, depending on the model), if we hit the bottom of the right stack, we just push a blank symbol onto the left.
The relationship the other way should be even more obvious, i.e. that we can simulate a two-stack PDA with a TM.
and you can say that, Turing machine tape is infinite in one direction, extending indefinitely to the right. We use one stack to represent the tape content on the finite portion of the tape to the left of the head and another to represent the content of the finite non-blank portion of the tape to the right of the head. The two-stack PDA resembles a move of the TM by suitably pushing and leaping the two stacks.```

### Representation and heuristic of Connect6 game in Prolog

```I want to represent game connect6 wiki (maybe predicate stone(P, X, Y), where P is player, X,Y are coords would by good). Also I want to use any good heuristic to solve the problem (to make opponent). Can you give me a hint to any article about game AI in Prolog? Thanks
```
```You probably want to look up http://en.wikipedia.org/wiki/Minimax game trees. To optimize the search, you probably don't want to consider all possible moves. Maybe just moves that are in-line with an existing piece and 6 or less spaces from it.
Then you need an http://en.wikipedia.org/wiki/Evaluation_function. Probably something like assigning a score to "how close am I to completing a line" overall the lines in progress.
Building and optimizing a game tree is more of a mechanical process. Creating an evaluation function is the fun part that will give your AI opponent it's unique flavor.
Searching google for "minimax game tree prolog" turned up a nice powerpoint:
http://staff.science.uva.nl/~arnoud/education/ZSB/2009/
```
```If you're implementing Connect6 on a finite board, then a possible representation for this game would be a list of lists of variables, initially unbound. You'd "place a stone" by unifying a variable with one of the atoms black or white. You can then test whether a position P is still empty with var(P). This representation should be a lot faster to manipulate than a list of stone/3 terms. It works because in Connect6, you can't ever remove a stone.
I assume that by heuristic you mean an evaluation function suitable for minimax, negamax or alpha-beta search. Considering the game rules, I'd suggest that for each player, you count the number of rows of length five and score those 5, score those of length four 4, etc. This gives you two scores S1 and S2. Subtracting S2 from S1 yields the relative advantage for player 1. Then find some way to normalize these into the range [-1,1] or score a situation where the game is over infinity of minus infinity. (How to represent all that in Prolog is left as an exercise.)```