Skip to content

Instantly share code, notes, and snippets.

@steverichey
Last active December 14, 2015 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steverichey/5014898 to your computer and use it in GitHub Desktop.
Save steverichey/5014898 to your computer and use it in GitHub Desktop.
Very very basic ActionScript code to procedurally generate a Flixel level as an array of ones and zeroes. My first attempt at this sort of thing, turned out much better than expected.
var data:Array = new Array();
var xPosition:uint = 0;
var yPosition:uint = 0;
// Set x and y boundaries
var xHeight:uint = 40;
var yHeight:uint = 30;
// Higher number means more blank spaces
var whiteSpaceWeight:Number = 1.5;
// Iterate through vertical, horizontal spaces, assigning ones or zeroes to array
while( yPosition < yHeight) {
while( xPosition < xHeight ) {
// Creates solid blocks at top and bottom of space
if ( yPosition == 0 || yPosition == 29 ) {
data.push( 1 );
} else {
// Create solid blocks at left and right of space
if ( xPosition == 0 || xPosition == 39 ) {
data.push( 1 );
// Makes every third line empty, creates empty horizontal space for player to move
} else if ( yPosition % 3 == 0 ) {
data.push( 0 );
// Creates a slightly higher chance to create blocks next to other blocks horizontally
} else if ( data[ data.length - 1 ] == 1 ) {
data.push( Math.round( Math.random() ) );
// Creates a slightly lower chance of creating a block not near other blocks
} else {
data.push( Math.round( Math.random() / whiteSpaceWeight ) );
}
}
xPosition++;
}
xPosition = 0;
yPosition++;
}
var i:uint = 0;
// Cycle through whole array and erase orphan blocks; emphasizes "platform" element
while ( i < data.length ) {
if ( data[i] == 1 && data[i - 1] == 0 && data[i + 1] == 0 ){
data[i] = 0;
}
i++;
}
// Generate and add the level using the created array
level = new FlxTilemap();
level.loadMap( FlxTilemap.arrayToCSV( data, 40 ), FlxTilemap.ImgAuto, 0, 0, FlxTilemap.AUTO );
add( level );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment