Feeds:
Posts
Comments

Archive for the ‘download’ Category

Bresenham’s line algorithm is a fairly simple algorithm that takes two tile positions in a grid and returns a list of all tile positions that a line drawn between the two positions touches. It is well described along with easy-to-read pseudo code here.

When is this useful? According to what I’ve read, this algorithm and variations of it are useful in graphics programs. I’m sure you’ve seen programs that let you draw icons in a zoomed-in view. While you draw lines it just colors in boxes. It is likely this algorithm was used for that. However, I use this algorithm for game-related purposes. The last time I used it was probably 5 or 6 years ago in a Flash pool game. I set up a grid with an arbitrary tile size on the pool table (that the user can’t see). Every frame I determined in memory which tiles a ball covered as it moved (assuming no collisions). Then I would only run collision detection against balls that touched the same tiles. This let me cut down on the number of collision checks per frame.

I’m coming back to this algorithm again now because of a first person shooter game I’m working on. I hope to create a blog post on how the algorithm is used in that game (on the server) to keep the collision detection calculations to a minimum.

I created a Flash demo of Bresenham’s line algorithm that you can play with by clicking on the image. Or you can download the source files here.

click to view example (drag dots around)

Advertisements

Read Full Post »

Note – I have edited this post. My initial post stated some things incorrectly and had a bug in the example.

For a current game project of ours users answer a tough triva question with a free form text entry. They only get one shot at answering the question — and they can only answer one question per day.

The answer comparison is done on the server so Mike Grundvig (Electrotank’s server guy) found a good Soundex algorithm to use on the server. The Soundex algorithm analyzes a string and assigns it a value. It does this by ignoring certain characters and repetition, and assigning values to certain characters. It essentially reduces any string to a phonetic value.

Soundex is really cool because words that sound similar will likely have matching phonetic values. Common misspellings usually yield the exact same phonetic value. So you can use Soundex to give a little “wiggle room” to entered answers in a trivia game (as a specific example). For example, Rosie O’Donnel and Rosy Odonel have the exact same score. This allows a person to know the correct answer but not how to spell it.

Who was the stellar actor in Kindegarten Cop? Arnold Schwartzegneger…or is it Arnold Schwarzenegger? Luckily Soundex returns the same value for each!

It seems like Soundex would be some complicated and intense algorithm. But it is actually pretty simple. This Wikipedia link shows the logic. And I was able to port over some Java code to ActionScript 3 in minutes.

Here is a simple Soundex example in AS3. Just enter any two strings and click the ‘compare’ button.

Download here.

click to view example

Read Full Post »

I recently finished a small series of posts on the AI topic of emergent behavior. Now I will be posting a few entries on the AI topic of search algorithms, aka pathfinding.

Almost everything I program is from a game programmer’s perspective. As such, search algorithms are pathfinding algorithms as far as I’m concerned. In the most generic sense though a search algorithm finds…something. Path, state, item, what ever. During my posts I plan to cover at least Depth-first (that is this post), A*, and Dijkstra’s algorithm.

Depth-first search is an algorithm used to search tree structures. Let’s call the node you’re looking for the goal. Generally with a depth-first search you’re looking for either the location the goal or the path to it.

Here is the pseudocode for this algorithm:

find(n, goal)   if n == goal      end and return path   else      for all children of n          find(child, goal))

I am no pseudocode expert so I hope I formatted that in an understandable way. The concept though is this:

  • Write a function that takes a node and a goal node
  • If the node is the goal node, stop and return the path
  • If the node is not the goal node, then run this function for all children of the node

In my experience depth-first searches are suited well in games for two purposes:

  1. Generating perfect mazes. A perfect maze is a maze in which there exists exactly one unique path between any two cells.
  2. Finding a path in a very constricted environment, such as a maze.

I have used depth-first a few times and it has always been for mazes!

I have created an ActionScript 3 demo. This demo creates a perfect maze using depth-first search. It also finds a path between a start node and where ever you place your mouse real-time. This search also uses depth-first search.

Here is the logic for creating a maze:

  • Create a grid pattern of some size (mine is 20 X 20)
  • All nodes are initialized with all 4 walls turned on.
  • Pick any node to start with and run the following pseudocode

expand(n)  set n as visited  randomize order of n's neighbors  for all neighbors of n      if neighbor not visited          knock down wall between n and neighbor          expand(neighbor)

The logic above will touch every tile and create a unique looking maze. To find a path within the maze you can run a similar search from a starting node until you reach the destination node. In that search though you only consider neighbors of a node that have open pathways (eg doorways).

DOWNLOAD

click to view example

Read Full Post »

This is my second post in a series covering some popular AI topics. Previously I discussed emergent behavior and the game of life. In this post I continue with a slightly more advanced and practical example, Boids. I finish by showing an example and how I modified the classic Boids approach just a little.

Boids is a set of 3 simple rules. When these rules are applied to many agents (birds in this case) they behave like flocks of birds. Agents group together to form flocks and fly together as one. Flocks can merge into one or divide into multiple new flocks. These set of rules can be added to and modified fairly easily and applied to other types of creatures to achieve a wide range of behaviors.

Here is the classic Boids rule set. Each agent (boid) follows these rules:

  • Separation – If the agent is too close to another agent, then steer away.
  • Alignment – Steer toward the average heading of nearest boids
  • Cohesion – Attempt to match the speed of the nearest boids

If you think about the above rules you can visualize how flocking will occur. In my example below I added a fourth rule:

  • Avoidance – If too close a non-boid object (such as a tree), then steer away.

In addition to the 4th rule I added a restriction. An agent is only affected by an agent that it can see. It can see an agent if it is within a certain distance of that agent, and if the cone of view is such that it can actually see that agent. So, the leader of a flock of birds is not affected at all by its followers because from its perspective they aren’t even there. What this gives us though is a a flock that mostly follows the leaders. If you give a minor perturbation to the a leader then you can affect the entire flock!

Enough rambling. Check out the example below. Download the source if you’re interested.

One last note: In my example you might notice the birds rotating a little funny sometimes (wobbling or spinning). The movement is right, the rotation needs a little love. Right now they rotate to face the instantaneous direction of movement. In reality a bird won’t rotate directly to the right if its going to slide a bit to the right while in flight (wow that rhymes).

click to view example

Read Full Post »

Emergent Behavior

Like many programmers I find working with artificial intelligence fascinating. Most of my next several post will discuss common AI topics; and of course I’ll provide source files.

The focus of my first two or three AI posts will be on emergent behavior. Some AI is very complicated (think deep blue here). But what I think is extremely cool is when you have a simple set of rules and get a lot of interesting behavior out of it.

Emergent behavior can be described as behavior that isn’t explicitly defined by the system or by any rule in the system, but still occurs. Well, that’s my definition anyway :). Think of a line of ants walking across a yard. No ant knows how long the line is, or even that its a line. The ant just follows a scent or taste and the emergent behavior is dozens of ants following what looks like a long organized line.

I love emergent behavior! From a programmatic standpoint here is generally how it works.

  • Your system supports at least 1 agent type. An agent is anything that you want to follow a set of rules. Such as an ant, bird, monster, etc.
  • Each interval you apply the rule set to each agent.

That’s it! Well, the devil is in the details. Applying the rule set of course depends on the rules. Luckily this is usually not too complicated.

As an example of emergent behavior I’ve created a Conway’s Game of Life example (below). This is a very simple example. In this case, there is a larges grid of agents. There are around 2,000. The agents cannot change positions. Each agent is either alive or dead.

Every iteration these simple rules are applied to every agent.

  • A lonely agent dies. So, if it has two or fewer living neighbors then it dies.
  • An overcrowded agent dies. If the agent has greater than 3 living neighbors then it dies.
  • A content agent lives. If the agent has 2 or 3 neighbors then it lives.
  • Resurrection. A dead agent with exactly three neighbors is given life.

As you can see, the rule set is simple. But when applied to every agent you get some interesting behavior. Check it out below. Read even further to learn about some seed patterns.

DOWNLOAD

The Game Of Life is a well known system. Certain seed patterns have been found that end up exhibiting certain features. For instance, a ‘spaceship’ is a pattern that moves itself across the board. In the example above I show two such examples – glider and light weight spaceship. The ‘diehard‘ example is a pattern that looks interesting and dies after 130 generations.

So, is this useful at all? Not really. Or at least not to me. The Game of Life isn’t something you can just take and use in a useful way (or if you can then please clue me in). It is generally just used as a simple example of emergent behavior.

The next example I’ll show in a day or so is more useful, and way cooler!

click to view example

Read Full Post »

The ELO Rating System has been around for decades. It was originally used for rating chess players but is portable to other games and really fits in well with web games. We’ve been using it in various projects for 5 or 6 years.

Here’s what it does:

  • First of all, ELO is used to rate players based on skill level. It is generally used for two player games like chess. But with some modifications it can be used for more than that.
  • A new player is assigned a default rating, say 1200.
  • Two players compete and end with one of three results: player 1 wins, player 2 wins, tie.
  • The two player’s ratings are fed into an algorithm along with the end state of the game and a new rating for each player is returned.

If two players both rated 1200 played and player 1 wins. Then player 1 will have a rating of about 1205 and player 2 will be 1195.

What makes ELO so cool is what happens over time. Players that win a lot end up with higher ratings. But the higher rated player starts to see diminishing returns for defeating low ranked players. So in order for a high ranked player to increase his rank, he must defeat other higher ranked players. If a high ranked player loses to a low ranked player, he loses much more of his rating then he’d gain if he won the match.

Over time the game players will end up being rated based on their skill level rather than other factors.

Last year we (at Electrotank) created a series of 10 multiplayer minigames for The Daily Show with Jon Stewart. These multiplayer games support 2 to 4 players per game. Mike Grundvig wrote a modified ELO system to support this. The end result is a pretty cool rating system. Players can view their own ratings and the ratings of other players in the game.

You can download an example ELO algorithm written in AS2 by me here: DOWNLOAD

Or here is the code:

function determineRatingConstant(rating:Number) {

	var returnVal:Number = 10;

	return returnVal;

	if (rating<2000) { 		returnVal = 30; 	} else if (rating>=2000 && rating<2400) {

		returnVal = 20;

	} else {

		returnVal = 10;

	}

	return returnVal;

}

function calculateNewRating(player1Rating:Number, player2Rating:Number, player1Victory:Boolean):Number {

	var outcome:Number = 0;

	if (player1Victory) {

		outcome = 1;

	}

	//Takes the rating of two players, the outcome of the game, and returns the new rating of the first player

	var d:Number = player1Rating-player2Rating;

	var exponent:Number = -d/400;

	var expected_outcome:Number = 1/(1+(Math.pow(10, exponent)));

	var k:Number = determineRatingConstant(player1Rating);

	var new_rating:Number = Math.round(player1Rating+k*(outcome-expected_outcome));

	return new_rating;

}

var player:Object = new Object();

player.rating = 2000;

for (var i=0;i<1000;++i) {

	player.rating = calculateNewRating(player.rating, 2100, true);

	trace("i: "+i);

	trace(player.rating);

}

ELO is O.G.!

Read Full Post »

I was going through a list of games that I’ve programmed recently and was reminded about Dynamite Fishing, a game we (at Electrotank) created for Comedy Central. For that game I programmed a series of wave physics classes that shows waves moving through water at a side view.

I had fun creating that and thought that I’d rewrite it a little more cleanly for ActionScript 3 and make the source available. It allows you to inject waves at any x position with any amplitude. Waves obey superposition – that means that you can continually inject waves and they’ll add/subtract each other to produce the appropriate result.

In the source provided you can specify any DisplayObject to show up and float in the water.

Download source

In the example below you can just click anywhere to inject a wave. Notice too that the water never quite settles down. That’s because I set it up to inject a small disturbance at random intervals.

click to view example

Read Full Post »

Older Posts »