Good heuristic for Tron - artificial-intelligence

I have an assigment to do a tron game with AI. Me an my team almost made it but we're trying to find a good heuristic. We taught about Voronoi, but it's kinda slow :
for yloop = 0 to height-1
for xloop = 0 to width-1
// Generate maximal value
closest_distance = width * height
for point = 0 to number_of_points-1
// calls function to calc distance
point_distance = distance(point, xloop, yloop)
if point_distance < closest_distance
closest_point = point
end if
next
// place result in array of point types
points[xloop, yloop] = point
next
next
We have 5 seconds to make a move and this algorithm doesn`t sound too good ! I don't need code ... we just need an ideea !
Thank you !
Later edit : Should we try Delaunay Triangulations ?

Have a look at the postmortem of Google's AI Challenge about this.

well i am considering redesigning my old Wurmeler game (AI including) so i stumped on your question while searching for new ideas so here is my insight from my old AI
Wurmeler is similar to tron but much slover and worms turn smoothly
game space is 2D bitmap
each AI is very simple ... stupid,...
but navigate better than me
unless they are closed by other player
or crush into local min/max
but still they are fun
OK now the AI algorithm in every decision move:
create few rays from Worm
one in movement direction
few turned to the left by some angle (5 degree step is fine)
few turned to the right
evaluate the ray length
from worm until it hit border
or another worm path curve
use the max rule to change heading
This old AI maintain only navigation but I want to implement more (this is not yet done):
divide map to square sections
each section will have the average density of already filled space
so if possible AI will choose less filled area
add strategies
navigate (already done)
flee (go away from near player if too close and behind)
attack (if on relative parallel course and too close and in the front)
may be conversion from raster to vector
should speed up the ray traceing and colision detection
but with growing length may be slower ... have to try it and see
possible use of field algorithms

Related

Following 3D Spiral Path

I would like to produce a realistic 3D demonstration of a ball rolling down a Conical Helix path. The reference that has helped me get close to a solution can be found here. [I am creating my solution in Actionscript 3, using Stage3D, but would be happy to have any suggested coding solutions in other languages, using other 3D frameworks, with which you may be more familiar.]
As I entered the title for my posting, the system pointed me to a wealth of "Questions that may already have your answer", and that was helpful, and I did check each of them out. Without wanting to hijack an existing thread, I should say that this oneincludes a good deal of very helpful commentary about the general subject, but does not get to the specific challenges I have been unable to resolve.
Using the cited reference, I am happy with this code snippet that traces the path I would like the ball to follow. [N.B. My reference, and most other math-based references, treat Z as being up-down; my usage, however, is the more usual 3D graphics of Y for up-down.]
This code is executed for each frame.
ft += 0.01; // Where ft is a global Number.
var n:Number = Math.pow (0.5, (0.15 * ft));
// Where s is a constant used to scale the overall path.
obj.moveTo (
(s * n * Math.cos (2.0 * ft)),
(s * n),
(s * n * Math.sin (2.0 * ft))
);
The ball follows a nice path, and owing to the lighting and other shader code, a very decent effect is viewed in the scene.
What is not good about my current implementation is that the ball does not appear to be rolling along that path as it moves from point to point. I am not using any physics engine, and am not seeking any solution dealing with collisions, but I would like the ball to correctly demonstrate what would be happening if the movement were due to the ball rolling down a track.
So, to make a little more clear the challenge, let's say that the ball is a billiard ball with the stripe and label for #15. In that case, the visual result should be that the number 15 should be turning head over heals, but, as you can probably surmise from the name of my obj.moveTo() function, that only results in changes in position of the 3D object, not its orientation.
That, finally, brings me to the specific question/request. I have been unable to discover what rotation changes must be synchronized with each positional change in order to correctly demonstrate the way the billiard ball would appear if it rolled from point 1 from point 2 along the path.
Part of the solution appears to be:
obj.setRotation ((Math.atan2 (Math.sin (ft), Math.cos (ft))), Vector3D.Y_AXIS);
but that is still not correct. I hope there is some well-known formula that I can add to my render code.

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.

How to use Random Walk to generate a dungeon map?

Ok so, I'm making a 2d dungeon crawler and I want to randomize a map for it. Right now it's look like I'm going to use a Random Walk algoritm for the path, combined with a Perlin Noise for different the underworld enviroments (currently only 1, as I'm using my own shitty looking tile set consisting of only 1 rook image and 1 grass image, but whatever :D)
So in figuring out how random walks work, it looks like I'm supposed to do something along the lines of this:
*create two-dimensional array sized after the map.
*pick random start postion and end postiont (I chose to put these on opposite sides of the map, randomly distributed across its side.
*follow these steps until you hit your finish point:
*pick a direction to 'walk' at random (only up, down, left, right because you otherwise I'm left with diagonal passes which the player can't walk through)
*'walk' that direction for a random amount of steps (I randomize amount of steps first then walk one by one for bound checking later, rather than just drawing a line).
*Everytime you 'walk' on a tile, turn that tile to 1 from originally 0.
*repeat above steps until you hit your finish point.
This leaves me with too much open ground, and too much closed ground. What I'm looking for is a path covered with rooms, sort of, but I want to control how big the 'rooms' become. I don't want 'rooms' to get too big, which some become. So I want the feeling of being in an enclosed space, but also I want to use as much of the map grid as possible.
Is a random walk not suited for this? I was thinking about making every step have a certain width to it, maybe that could work.
Or maybe I'm just implementing it wrong! I'm not a math genious sadly ;P

Evaluation function of an abstract strategy game

I'm coding an abstract strategy game with C# & XNA. As for the AI, I'm currently using Negascout and a depth of 5. The following is the description of the game:
The game consists of a board of 6x7 hexagonal locations, 42 hexagonal tiles, and 6 pieces (1 king & 5 pawns) for each player (max 2 players).
During the first phase of the game, the players alternately place a random tile on an empty location of the board. Each tile can have a maximum of 6 arrows pointing at the edges. Some arrows can be double-pointed. The arrows mean the direction/s of movement from that tile. A double-pointed arrow makes a piece move/jump 2 locations if there's a valid location. The players are not allowed to place tiles in their opponent's row if there are still empty locations left on the board.
Once this phase is complete, the next player in turn places his king on any one of the 6 tiles of the row nearest to him. Next, the movement of the pieces commences. Pieces are moved according to the arrows on the tiles. The game is won by capturing or blocking the king.
Ok, so now to my move generation function.
Tile placement stage
a) Place a tile on the nearest row. The tile is rotated to find the optimal rotation.
b) Once the nearest row is full, place a tile on an empty location that is surrounded by locations on all sides (ie no edge of board). Rotate the tile to find the optimal rotation.
c) If no locations are found, add all remaining empty locations, trying to find the optimal rotation.
King placement stage
a) Locate the location with the best tile and place the king there.
b) Place the remaining pawns on the remaining empty locations on the row.
Movement stage
a) If king is attacked, try to attack the attacking piece if that piece is not defended.
b) Add moves for all player's pieces that are being attacked.
c) Add all opponent pieces that the player can attack.
d) Add all locations player can move to.
Now to the evaluation function.
Tile placement stage
score = No. of tiles current player placed so far + current player's tiles on the nearest row - no. of tiles opponent placed so far - opponent's tiles on the furthest row (nearest to the opponent).
King placement stage
score = current player's tiles on the nearest row - opponent's tiles on the furthest row (nearest to the opponent).
Movement stage
score = current player's pieces' value - opponent's pieces' value.
The weighting of the tiles is 100 for every valid location an arrow points to. The weighting of the pieces is as follows:
piece value = piece type (king = 10000, pawn = 1000) + mobility + defended - attacked - enprise - blocked
where:
mobilty = no. of locations node can move to (free or occupied by the opponent) * 1000
defended = no. of current player pieces surrounding this piece that can actually move to this location * 1000
attacked = no. of opponent pieces surrounding this piece that can actually move to this location * 1000
blocked = (king = -10000, pawn = -1000) piece cannot move because all arrows point to invalid locations and the piece has no chance of moving again in this game.
Quite long, but here come my problems:
When placing tiles, the AI sometimes places a tile using the wrong rotation (ie. places a tile in location where the arrows point to no valid locations). Sometimes this occurs in his 'home' row.
When moving pieces, the AI is ignoring king safety. Moves mostly the king and is captured in about 4-6 moves.
Anybody, especially with chess AI experience, has ideas and suggestions on how to improve my AI, in particular my move generation and evaluation functions?
Thanks
Ivan
btw... If anyone is interested in trying out the mail, just let me know and I'll upload a setup on my website.
Quite long, but here come my problems:
Quite long, indeed.
When placing tiles, the AI sometimes places a tile using the wrong rotation (ie. places a tile in location where the arrows point to no valid locations). Sometimes this occurs in his 'home' row.
In other words, you have a bug in your code. There's no way to answer this question, even with all this extensive preamble. This question should be in a separate, concisely-phrased question that includes a copy of the relevant code.
When moving pieces, the AI is ignoring king safety. Moves mostly the king and is captured in about 4-6 moves.
Same as above. This question can't be answered based on even the extensive preamble you've written.
My advice to you is to be more concise with your questions, post only the details relevant to the problem, and not to combine multiple questions into a single post.
Anybody, especially with chess AI experience, has ideas and suggestions on how to improve my AI, in particular my move generation and evaluation functions?
This is an overly vague question that would normally get closed. If you want some advice about your code, you would have to provide that code in order for anyone to give you a helpful answer that goes beyond blind speculation!

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.
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.
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
add s to visited
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.
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.

Resources