Tag Archive for 'games'

PacMan capture-the-flag: a fun game for artificial intelligence development and education

At the beginning of September I’ve been invited to teach at a summer school about scientific programming. The whole experience has been really rewarding, but it was the student’s project that got me going: we had the students write artificial intelligence algorithms for the agents of a PacMan-like game, and organized a tournament for them to compete against each other.

The PacMan capture-the-flag game has been written originally by John DeNero, and has been used to teach an artificial intelligence course by him at Berkley and by Hal Daume III at University of Utah. Very often, this kind of games have a single strategy that dominates all others, and once you find it the interest fizzles out. In this case, I was impressed by how rich this game is. The game offers a lot of opportunities to develop and test complex learning and planning algorithms, including cooperation strategies for games with multiple agents.

capture_the_flag

The rules of the game are quite simple: the board is a PacMan maze, divided in a red and a blue half. The two halves belong to two teams of agents, who are controlled by computer programs to eat the opponent’s food and protect their own. When in the opponent’s half, the agents are PacMan (PacMen?), while in their own half, the agents are ghosts and can kill the opponent’s PacMan agents, in which case these are returned to their initial position. The players get one point for each food dot they eat; no points are assigned for eating the other team’s agents. The game ends when one of the two teams eats all of the opponent’s food, or after 3000 moves; the team with the highest score wins.

To make the game more interesting, one can only observe the position of the other team’s agents when they are very close to one’w own agents (5 squares away); otherwise, one can only obtain a noisy estimate of their distance.

The game is written in Python, my programming language of choice, which allows to write rapidly even sophisticated algorithms. I recommend the game to anyone wanting to organize an artificial intelligence course, or simply have fun writing AI agents. I plan to dedicate a couple of posts to the basic strategies to write successful agents in this game.

Here’s a video of the best students’ agents (red team) playing against the best tutors’ agents (blue team). The tutors won, saving our reputation!

Update: The authors of the PacMan capture-the-flag game decided to keep the game close-source, and in particular would prefer not to publish the code of agents playing their game, fearing that it might interfere with their course. It’s a shame because I was planning to write some Genetic Programming agents for the game, but of course I respect their decision. I guess there will be no series of posts re:PacMan…

My AI reads your mind and kicks your ass (part 2)

Get Adobe Flash player

In the last post I discussed how it is possible to program a game Artificial Intelligence to exploit a player’s unconscious biases using a simple mathematical model. In the karate game above, the AI uses that model in order to do the largest amount of damage. Give it a try! You get 10 points if you hit your opponent with a punch or a kick, 0 points if you miss, and 5 points if you block your opponent’s move. As you play, the AI learns your strategy and adapts to knock you down as often as possible.

How does it work? According to decision theory, we need to maximize the expected score. To compute the expected score for an action ‘x’ (e.g., ‘punch’), one needs to consider all possible player’s moves, ‘y’, and weight the possible outcome with the probability of the player doing that move, i.e.

E[score for x] = sum_y P(y) * Score(y,x)

where P(y) is the probability of the player choosing action ‘y’ (obtained using last post’s model), and Score(y,x) gives the score of responding ‘x’ to ‘y’.

For example, in the karate game using a low kick has a priori the highest chance of success: you score in 3 out of 4 cases, and only lose 5 points if the opponent decides to block your kick. This is why, at the beginning, the AI tends to choose that move. However, if you know that the AI uses that move often, you will choose the kick-blocking move more often, increasing P(kick-block). This change will make the punch more likely to score points. As you play, the optimal strategy changes and the AI continues to adapt to your style.

With a bit of practice, you’ll notice that you can compete with the AI and sometimes even gain the upper hand over it. This shows that you are in turn forming an internal model of the computer’s strategy. I think that the game dynamics that results from this interaction makes the game quite interesting, even though it is extremely simple. Unfortunately, it’s very rare to see learning AIs in real-life video games…

As always, you can download the code here.

Update: Instead of always making the best move, the AI now selects the move with a probability related to its score, which makes it less predictable. More details in the next post…

My AI reads your mind (part 1)

I regularly read about people complaining that AI in games should be improved. I definitely agree with them, but here’s a argument why pushing it to the limits might not be such a good idea: computers can easily discover and exploit our unconscious biases.

Magic? ESP? More like a simple application of decision theory. In order to make an unbeatable AI one needs two steps: 1) build a model of a player’s response in order to predict his next move, and 2) choose actions that maximize the expected score given the prediction of the model.

The basic idea behind 1) is that even if we try to be unpredictable, our actions contain hidden patterns that can be revealed using a pinch of statistics. Formally, the model takes the form of a probability distribution: P(next move | past observations).

Try it out: In the Flash example below, you can type in a sequence numbers 1-4, and the AI will try to predict your next choice. If your choices were completely random, the AI would only be able to guess correctly 25% of the time. In practice, it often guesses correctly 35-40% of the numbers! (It might take a few numbers before the AI starts doing a decent job.)

Get Adobe Flash player

In this example I used a 2nd order Markov model, i.e., I assumed that the next number, n(t+1), only depends on the past 2 choices: P(n(t+1) | past observations) = P(n(t+1) | n(t), n(t-1)). The rest is just book-keeping: I used two arrays, one to remember the past 3 numbers, and one to keep track of how many times the player chose number ‘k’, given that his past two moves were ‘i’ and ‘j’:

1
2
3
4
5
// last 3 moves
public var history:Array = [1, 3, 2];
// transition table: transitions[i,j,k] stores the number
// of time the player pressed 'i' followed by 'j' followed by 'k'
public var transitions:Array;

When the player makes a new choice, I update the history, and increment the corresponding entry in the transition table:

1
2
3
4
5
6
7
/*
* Update history and transition tables with player's move.
*/

public function update(move:int):void {
history = [history[1], history[2], move];
transitions[history[0]][history[1]][history[2]] += 1;
}

The probability that the next choice will be n(t+1), is given by the number of times the player pressed n(t+1) after n(t) and n(t-1) before, normalized by the number of time the sequence n(t-1), n(t) occurred in the past:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
* Return probability distribution for next move.
*/

public function predict():Array {
// probability distribution over next move
var prob:Array = new Array(4);

// look up previous transitions from moves at time t-2, t-1
var tr:Array = transitions[history[1]][history[2]];

// normalizing constant
var sum:Number = 0;
for (var k:int = 0; k < 4; k++) {
sum += tr[k];
}

for (k = 0; k < 4; k++) {
prob[k] = tr[k] / sum;
}

return prob;
}

The best prediction is given by the choice with maximum probability. You’re welcome to have a look at the code!

In the next post, I’ll show how the AI can choose the best actions in order to maximize its expected score in a Virtual Karate game.

Spatial database for collision detection

In games and other graphical applications one has to keep track multiple sprites and detect collisions between them. A naif approach would loop over all sprites and check for collision with *every other sprite*. This is, of course, terribly inefficient and can be very slow even for a small number of sprites.

One way out of this nightmare  is to register the sprites in a spatial database that stores them according to their position, and is able to determine which of them is close to a given point. As a result, one only needs to check for collision between neighboring sprites. There are many implementations of spatial databases, some of which are quite sophisticated. In this post I’m going to describe an ActionScript 3 implementation of a grid-based spatial database, that can be used for simple flash games.

Grid: 2D Array with neighborhood

A Grid is a two-dimensional array with a concept of neighborhood. In addition to be able to store and retrieve information on the 2D grid, one can request neighboring elements of a given array element.

For example, let’s create a simple 4×4 grid, and store at each point an increasing number:

1
2
3
4
5
6
7
var grid:Grid = new Grid(4, 4);
var k:int = 1;
for (var i:int = 0; i < 4; i++) {
    for (var j:int = 0; j < 4; j++) {
        grid.set(i, j, k++);
    }
}

This image shows the resulting grid, with small numbers indicating grid coordinates and large, bold ones the stored values:

grid11

We can now query the grid to get neighbors of a given position: For example, the following code

1
2
3
4
var neighbors:Array = grid.getNeighbors(1, 1);
trace(neighbors);
neighbors = grid.getNeighbors(1, 3);
trace(neighbors);

displays 1, 2, 3, 5, 7, 9, 10, 11 and 3, 4, 7, 11, 12, respectively, as shown here:

grids2and3

Note that, by default, the neighbors stop at the border. It is possible to work on a “toroidal” grid, meaning that the opposite borders of the grid are connected:

grid4

1
2
3
grid.setToroidal(true);
neighbors = grid.getNeighbors(1, 3);
trace(neighbors);

which prints 3,4,1,7,5,11,12,9 .

I added two functions that simplify working with neighbors. The first, mapOnNeighbors(x, y, fct), applies a function fct to all neighbors of (x,y). Let’s  see which of the neighbors of (1,3), are even numbers, just for fun:

1
2
3
function isEven(x:int):Boolean { return (x % 2 == 0); }
var neighborsAreEven:Array = grid.mapOnNeighbors(1, 3, isEven);
trace(neighborsAreEven);

This gives false,true,false,false,false,false,true,false. There are several interesting uses of this method: collecting information from elements in a region of the grid, activating neighboring elements, …

The second function, reduceOnNeighbors(x, y, fct), is a bit more difficult to explain, but equally useful: it returns a single value constructed by iterating over the neighbors of (x,y) and calling fct(a, b) on the first two items of the sequence, then on the result and the next item, and so on. We can use this function to compute the sum of all neighbors:

1
2
3
function sum(x:Number, y:Number):Number { return x + y; }
var sumOfNeighbors:Number = grid.reduceOnNeighbors(1, 1, sum);
trace(sumOfNeighbors);

prints 48 = 1+2+3+5+7+9+10+11 . This function could have been used for example in the previous post in the Cellular Automaton code, to compute the number of alive neighbors for every cell of the CA.

SpatialDatabase

The SpatialDatabase class registers sprites in a Grid with coarser resolution. For example, a Shape at position (31, 23) on the stage would be stored in element (3,2) if the resolution of the grid is 10 pixels.

That’s basically all there is to it! For collision detection, we can query the spatial database for sprites registered at neighboring elements in the grid:

1
2
3
4
5
6
7
8
9
10
// Check collision with shape:Shape
// 1. get neighbors
var neighbors:Array = spatialDatabase.getAllNeighbors(shape.x, shape.y);
// 2. loop over all neighbors and check collision
for each (var s:Shape in neighbors) {
    // check collision
    if (checkCollision(shape, s)) {
        // do something (bounce, explode, ...)
    }
}

A higher resolution gives an optimal performance. Just keep in mind that the grid size should be larger than the size of the largest sprite, otherwise some collisions may go undetected.

There exist much more sophisticated methods to improve the efficiency of collision detection (see for example this post and the excellent tutorial at metanet software). However, this simple grid-based approach can be *very* efficient for many applications!

You can grab the code for the Grid and SpatialData`base classes here (including AsUnit tests for the Grid class). I have a nice example of this class at work, but this post is already long enough, have a look at the next one!