PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

2d Platform Game - Random Level Generation

Hi all,
I'm creating a platform game, and was wondering if anyone has any good ideas on creating random levels, the levels consist of multiple layers:

Layer 1: (background)
Layer 2: (objects) etc etc etc....

these are in the form of a linked list etc....

the random generation would have to produce (plaforms, walls, etc) the background behind the layers would be std... it would also be good for it to add items to the level, i.e a key to open a door, items to collect to complete the level etc, as well as the bad guys ;-)


The levels range from [20][20] to [500][500] in size, so there is quite a range.

Does anyone have any "good" way of doing this, or is there some code out there already?

The way I see it there are 2 ways, create the path first, then put in "bugus" material, or randomly create and test until it is playable.....

anyhow ideas?
Can't help much, but I have a feeling this will be a tough project. Never seen randomly generated sidescroller levels before. You could have a preset bank of sorts, sections of levels, and have these sections of levels pieced together. That would ensure the quickest, playable random generator.
yes, that may work, if they consisted of about 8x8 "blocks", but then you would have to define then as a 1-16 block for entry/exit points, i.e left,right,up,down or any combination 2^4 and then you would have to make sure the entry/exit point existed in the "middle" of the 8x8 section...

All you then need to do it have a start group and an end group of blocks... creating the groups in between types 1-16, there could also be a few different variation on a group block etc ie 16 types of group type 1 (left exit etc), this could be selected randomly.

this should simplify the random generation part, i.e just checking theres a path.... but with 16 type of blocks with 16 variations etc it would look random enough!

I suspect the code would be somewhat like a "pipe" game with the water comming down the line....

;-)

(anyhow still complicated)
You mean have one start section, anything in between, then one end? That would work better, make things even more random.

What's the environment going to be like, more closed in, ala the tunnel levels of Mario, or large and wide open like SMB3? That method would work better for wide open levels. If the physics are constant (always jump however high, not however high plus or minus a bit) playing through the level perfectly with AI should be a great deal easier. This would allow you to make simple skill levels, in hard you would have only so much leeway, and in easy, a lot more.

You could also have these sections with random heights, just sink the section down into the ground a bit.

What about using very small sections, flagging valid entry/exit points, and putting it all together? Flag small sections that would make good entries, good exits, etc.

If you do use sections for random levels, this will allow 3rd party users to come in and stick in their own sections.

This will be some game to see when it's released :P
New platform game? I thought you were going to keep doing the Squish series untill "Squish 20: Dr. Evils great great grandson, strikes again in 3D." :D


By then we would have 10Ghz PPCs with 4 Terabyte storage cards. :lol:
I never said Mr P was not going to feature in the game as the main character, as for squish4, I think not..... maybe somthing different.... ;-)

Hey maybe I can get hold of the weeboo code, was that project actually finished?

-B
already heard of the unofficial fullscreen weeboo ? take a look at this 4mb .avi file: weeboo.avi
[edit] if the .avi link doesn't work try this one: weeboo.zip

again, this is not official, it was another experiment since i've been a big weeboo fan from the very beginning of its availibility. so, the game idea, it's name and the used sound effects in this video are copyright by frederik malmer ! everything else (graphics & code) was done by me...

maybe, if someone really likes to release a final version, featuring more levels, i could provide code or help a little here and there, there's also a small level-editor i made for this version...

anyway, the whole thing is still courtesy of frederik malmer, so he really should be asked first ;)
delete?
pazazzo.

Howcome you never told me of this? It's cool.

As for Weeboo, I won't give out the sourcecode to it, because it is so crappy I'm somewhat ashamed of it. Was a port of a DHTML game I made, so it is basically translating JScript code into C++. Add to that that I had to change some things and it eventually turned out to be pretty messy. In other words: It is a wonder it even works.

Either way...this is so fun. Just one thing. My name is spelled the swedish way: Fredrik Malmer. No extra 'e' in Fredrik.

Oh...for all you fans out there...if there is time in the future there might be a future for a new Weeboo game. I mean...quite a lot could be done with the little hairy guy. Oh, incase you didn't know. Weeboo is a rabbit. :)
Oh, the reasons for weeboo not being fullscreen are:

1) Quite bad code makes it slow so on lowerend devices (MIPS, SH3) it really wouldn't run very well
2) The DHTML version had that size, so I feel like changing all too much.
ups, sorry for the extra 'e' fredrik :)
never told you about this because it's now almost a year old and unmodified and was one of my very first ppcapps... anyway, now i've sent you this demo per mail, hehe
hrmm ARE YOU PORTING WORMS!!!!!!!
Don't know if this helps but I made this code for a raycaster:

Code:

// Maze Generator

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int MazeX=12,MazeY=12;
// &1 = North wall, &2 = West wall, 4=In, 8=Out, C=frontier
static unsigned char *Maze=NULL;
static unsigned char MazeNull=0;

static int MazeOutput()
{
int x=0,y=0,fy=0;
// Output maze as text
for (y=0;y<MazeY;y++)
{
for (fy=0;fy<4;fy++)
{
printf(" \"");
for (x=0;x<MazeX;x++)
{
int d=0;
d=Maze[x + y*MazeX];
if (fy<=0) { if (d&1) printf("1111"); else printf("1 "); }
else { if (d&2) printf("1 "); else printf(" "); }
}
printf("\"\n");
}
}

printf("\n\n");
return 0;
}

// Find a cell in the maze (or if outside return MazeNull)
static unsigned char *MazeFind(unsigned int x,unsigned int y)
{
if (x<(unsigned)MazeX && y<(unsigned)MazeY) return Maze+x+y*MazeX;
MazeNull=0;
return &MazeNull;
}

static int MazeNext()
{
int cx=0,cy=0;
unsigned char *pmc=NULL,*pa=NULL;
int Front=0,r=0,i=0;

// Count up the cells on the frontier
for (pmc=Maze,cy=0; cy<MazeY; cy++)
for ( cx=0; cx<MazeX; cx++,pmc++)
{
if ((pmc[0]&0xc)==0xc) Front++;
}
if (Front<=0) return 1; // No more frontier left

// Pick a random cell from the frontier
r=rand()%Front;

// Find it
for (pmc=Maze,cy=0; cy<MazeY; cy++)
for ( cx=0; cx<MazeX; cx++,pmc++)
{
if ((pmc[0]&0xc)==0xc) r--;
if (r<0) goto Quit; // Found it
}

Quit:
if (cy>=MazeY) return 1; // Didn't find the frontier cell

// Change Frontier to In
pmc[0]&=3; pmc[0]|=4;
// Change any adjacent Out to Frontier
pa=MazeFind(cx ,cy-1); pa[0]|=4;
pa=MazeFind(cx ,cy+1); pa[0]|=4;
pa=MazeFind(cx-1,cy ); pa[0]|=4;
pa=MazeFind(cx+1,cy ); pa[0]|=4;

// Pick an random adjacent cell in In to link with, (NWSE)
r=rand();
for (i=0; i<4; i++,r++)
{
r&=3;
switch (r)
{
case 0: pa=MazeFind(cx ,cy-1); break;
case 1: pa=MazeFind(cx-1,cy ); break;
case 2: pa=MazeFind(cx ,cy+1); break;
case 3: pa=MazeFind(cx+1,cy ); break;
}
if ((pa[0]&0xc)==4) break; // Found one in In
}
if (i>=4) return 1; // Couldn't find a wall

// Knock down the connecting wall
switch (r)
{
case 0: pmc[0 ]&=~1; break;
case 1: pmc[0 ]&=~2; break;
case 2: pmc[MazeX]&=~1; break;
case 3: pmc[1 ]&=~2; break;
}

return 0;
}

static int MazeInit()
{
int cx=0,cy=0;
unsigned char *pmc=NULL;

Maze=(unsigned char *)malloc(MazeX*MazeY);
if (Maze==NULL) return 1;
memset(Maze,0xb,MazeX*MazeY); // Reset to all wall segments and all Out

// Starting cell:
cx=rand()%MazeX;
cy=rand()%MazeY;

pmc=MazeFind(cx ,cy ); pmc[0]&=3; pmc[0]|=4; // Mark as in
pmc=MazeFind(cx ,cy-1); pmc[0]|=0xc; // Mark as frontier
pmc=MazeFind(cx ,cy+1); pmc[0]|=0xc; // Mark as frontier
pmc=MazeFind(cx-1,cy ); pmc[0]|=0xc; // Mark as frontier
pmc=MazeFind(cx+1,cy ); pmc[0]|=0xc; // Mark as frontier

while (MazeNext()==0) { }
return 0;
}

static int MazeExit()
{
free(Maze); Maze=NULL;
return 0;
}

int main()
{
int i=0;
for (i=0;i<5;i++)
{
MazeInit(); MazeOutput(); MazeExit();
}
return 0;
}



It uses a maze generating algorithm (I forget which one - it's the frontier-based one though) in order to make a random maze for a Raycaster.

You could probably change it to make little platforms on the edge of each wall, so that they could be climbed? Also the place I found the algorithm there were hints for growing two mazes and having a key to access the other part. Hope that helps...
Hey, that's pretty cool that you're one of the guys that ported Repton. 80s games rock! Now all we need is my all time favorite, Spy Hunter.
I've been playing around with the code, and come up with the following:

Code:

static int MazeOutput()
{
int x=0,y=0,fy=0;
// Output maze as gfx
for (y=0;y<MazeY;y++)
{
for (fy=0;fy<4;fy++)
{
for (x=0;x<MazeX;x++)
{
int d=0;
d=Maze[x + y*MazeX];
if (fy<=0)
{
if (d&1) bar(x*10,y*10,(x*10)+10,(y*10)+1,38912,screen_buffer_p);
else bar(x*10,y*10,(x*10)+1,(y*10)+10,38912,screen_buffer_p);
}
else
{
if (d&2) bar(x*10,y*10,(x*10)+1,(y*10)+10,38912,screen_buffer_p);
}
}
}
}
return 0;
}


but it does not seem to be outputting any "useful" mazes? what is the fy loops for? can anyone shead any light on this subject? All I was trying to do was place "bars" where the "ones" were to give a gfx output to the screen, btw shouldent the output be a 12x12 grid?, because im getting 12 in the y axis, but 240+ in the x axis (what Im seeing on the screen)

any ideas?

-B
I've played around with this code a bit, (it is screwy), it was doing all sorts of wierd stuff. it was creating a maze ok in the x axis, but twice the size it should have been in the y axis, after changing MazeX and Y to consts, rather than ints it sort of fixed the problem.

i.e

const MazeX=10;
const MazeY=10;

Does anyone else have code that "works" it seems the maze is built on an array or chars.... eg? why not ints? or somthing else?

maybe having a byte telling cell information, like bit 1, north, bit 2, east etc

so 00001010 would mean west and east exits etc.... the other spare bits can be used for defining "frontier" blocks etc.. while creationg the maze.

-B
Anyone any good at translating? I dont think it would require much to get working in c++, I'm not real famillar with the changes in java.... But I know this code works.... it even has the explanation. ;-) just the generate function would be nice :-)

Code:


Public class WallMaze extends Maze {

public static final byte BLOCKED = (byte) (TOP | RIGHT | BOTTOM | LEFT);

public WallMaze () {
lineWid = lineHyt = 1;
setBackground(Color.white);
}

protected byte initSq () { return (byte) (BLOCKED | DIRTY); }

public boolean isOpen (int x, int y) {
return inBounds(x, y) && sqr(x, y) != BLOCKED;
}

/*
* Here is the algorithm used to generate the maze:
* 1. Set all the squares in maze grid to the BLOCKED state.
* 2. Randomly select a square on the left side of the maze as the current square,
* clear the wall on the left side of the square, and set <lastSide> to LEFT.
* 3. Randomly choose a sequence to rotate through the remaining sides (the sides
* other than <lastSide>) of the current square.
* 4. Set nextSide to the next selected side in the rotation.
* 5. If there is a BLOCKED square adjacent to the <nextSide> of the current
* square, then goto step 9.
* 6. If there are more sides rotation sequence, then goto step 4.
* 7. You get to this step when the current square is not adjacent to any
* BLOCKED squares. Randomly select a non-BLOCKED square (a square already
* added to the maze) as the current square. This creates a new branch
* in the maze.
* 9. You get to this step when you have found a square to add to the maze.
* Remove the wall between the current square and the square adjacent to
* its <nextSide>.
* 10. Set the new current square to the adjacent square and set <lastSide> to
* the side of this square that was removed in step 9. This sets <lastSide>
* to the side opposite <nextSide>. For example, if <nextSide> is TOP, then
* the new <lastSide> is BOTTOM.
* 11. If there are any BLOCKED squares remaining in the maze grid then goto
* step 3, otherwise youÕre done.
*/
public synchronized void generate (boolean displayConstruction) {
int xx, yy, sq, lastSide = LEFT, count = mzWid * mzHyt, threshold = count / 8;

// Step #1 - initialize the maze
clearMaze();
if (displayConstruction)
showMaze(true);

// Step #2 - select and set the starting square
startX = xx = 0;
startY = yy = rint(mzHyt);
sq = (byte) ((BLOCKED | DIRTY) & ~LEFT);

while (--count >= 0) {
// Step #3 - choose a sequence to rotate through the sides
int nextSide, nx = 0, ny = 0, nsq;
int scnt = 3; // # of sides left to try in current square
int sideInc = rint(3); // offset from <lastSide> to try next
boolean branch = false, found = false;
do {
// Step #4 - set <nextSide> to direction to search
nsq = 0;
if ((nextSide = lastSide << (sideInc + 1)) > BLOCKED)
nextSide >>= 4;
switch (nextSide) { // get next square to add to maze
case TOP:
if (yy > 0)
nsq = sqr(nx = xx, ny = yy - 1);
break;
case BOTTOM:
if (yy < mzHyt - 1)
nsq = sqr(nx = xx, ny = yy + 1);
break;
case LEFT:
if (xx > 0)
nsq = sqr(nx = xx - 1, ny = yy);
break;
case RIGHT:
if (xx < mzWid - 1)
nsq = sqr(nx = xx + 1, ny = yy);
else if (finishX < 0) { // mark this square as maze exit
found = branch = true;
finishX = xx; finishY = yy;
}
break;
}
if (!found) {
if (nsq == BLOCKED) // unused square, use it
found = true; // Step #5 - add the square
else if (--scnt > 0) // try next direction
sideInc = (sideInc + 1) % 3; // Step #6 - try a new side
else // dead end, start a new branch
branch = true; // Goto step #7 (below)
}
if (found || branch) {
// Step #9 - add the square to the maze
// Note that <sq> contains the current square which was either
// inited in step #2 before the main loop or set below in
// step #9a at the bottom of the main loop. If <found> then the
// <nextSide> wall is cleared in <sq> before setting <maze[][]>.
maze[xx][yy] = (byte) (found ? (sq & ~nextSide) : sq);
dirtySquare(xx, yy);
if (displayConstruction)
showMaze(false);
if (branch) {
// Step #7 - select a square to branch from
if (count < threshold) { // exhaustively search for remaining squares
sq = BLOCKED;
SEARCH: for (xx = 0; xx < mzWid; xx++)
for (yy = 0; yy < mzHyt; yy++)
if (sqr(xx, yy) == BLOCKED) {
int dir = rint(4);
for (int ii = 4; --ii >= 0; ) {
nx = xx; ny = yy;
switch (dir = ++dir & 3) {
case 0: nx--; break;
case 1: nx++; break;
case 2: ny--; break;
case 3: ny++; break;
}
if (inBounds(nx, ny) && (sq = sqr(nx, ny)) != BLOCKED) {
xx = nx; yy = ny;
break SEARCH; // found square for branch
}
}
}
if (sq == BLOCKED)
break; // maze done
}
else { // randomly search for a square to start a new branch
do {
xx = rint(mzWid);
yy = rint(mzHyt);
sq = sqr(xx, yy);
} while (sq == BLOCKED);
}
// Step #8 - set <lastSide> to an open side
for (lastSide = 1; (lastSide & sq) != 0; )
lastSide <<= 1;
scnt = 3;
sideInc = rint(3);
branch = found = false;
}
}
} while (!found);

// Step #10 - init the new square and set &lt;lastSide&gt; to the side opposite &lt;nextSide&gt;
if ((lastSide = nextSide << 2) > BLOCKED)
lastSide >>= 4;
sq = nsq & ~lastSide; // Step #9a
xx = nx; yy = ny;
if (!displayConstruction && (count & 0xFF) == 0)
Thread.yield(); // give some time to other threads
// Step #11 - check for more squares (at top of loop)
}

if (finishX < 0) { // no exit square selected, do it now
maze[xx = mzWid - 1][yy = rint(mzHyt)] &= (byte)~RIGHT;
dirtySquare(xx, yy);
if (displayConstruction)
showMaze(false);
}
if (!displayConstruction)
repaint();
} // generate()


public synchronized boolean traverse (int xx, int yy, int fx, int fy, boolean displaySearch) {
if (!inBounds(xx, yy) || !inBounds(fx, fy))
return false;

int count = 0, sq = maze[xx][yy], side = LEFT, sx = xx, sy = yy;
boolean solve = (xx == startX && yy == startY && fx == finishX && fy == finishY);

resetPath();
if (solve) { // mark path to enter maze
path[xx][yy] = LEFT;
dirtySquare(xx, yy);
side = TOP;
}
while (xx != fx || yy != fy) {
while ((sq & side) != 0) // search for a direction to try
if ((side <<= 1) > BLOCKED)
side = TOP;
path[xx][yy] ^= side; // set exit path from current square
dirtySquare(xx, yy);
switch (side) { // set entrance path to new square
case LEFT: path[--xx][yy] ^= RIGHT; side = BOTTOM; break;
case TOP: path[xx][--yy] ^= BOTTOM; side = LEFT; break;
case RIGHT: path[++xx][yy] ^= LEFT; side = TOP; break;
case BOTTOM: path[xx][++yy] ^= TOP; side = RIGHT; break;
}
sq = dirtySquare(xx, yy);
if (xx == sx && yy == sy && side == LEFT) {
// we've searched the entire maze and we're back at
// the starting square, so there's no solution
resetPath();
if (displayPath)
repaint();
return false;
}
if (displaySearch)
showMaze(false);
else if ((++count & 0xFF) == 0)
Thread.yield();
}
if (solve) { // mark path to exit maze
path[xx][yy] |= RIGHT;
dirtySquare(xx, yy);
}
if (displayPath)
repaint();
return true;
} // traverse()

} // public class WallMaze

well fellas, here it is, some real working code, the design etc is much easier to play with etc:

So dont say I dont share, this took me ages to find ;-)

Code:


struct cell {
int setNumber; // used when constructing maze
bool leftHedge; // sides of the cell, true if blocked
bool rightHedge;
bool topHedge;
bool bottomHedge;
};

cell myMaze[20][20];

int MTSZ = 20;

void GenerateMaze()
{
// first initialize all matrix cells
int count = 0;
int numSets = 0;
for (int col=0; col<MTSZ; col++) {
for (int row=0; row<MTSZ; row++) {
myMaze[col][row].setNumber = count;
count++;
myMaze[col][row].leftHedge = true;
myMaze[col][row].rightHedge = true;
myMaze[col][row].topHedge = true;
myMaze[col][row].bottomHedge = true;
}
}
numSets = count;

// srand((int)time(NULL));
while (numSets > 1) {
int aCol = rand() % MTSZ; // choose random cell
int aRow = rand() % MTSZ;
int bCol = aCol;
int bRow = aRow;
int testdir;
while (aCol == bCol && aRow == bRow) { // and random neighbor
testdir = rand() % 4;
switch (testdir) {
case 0:
if (aCol > 0) bCol = aCol-1; break; // left cell candidate
case 1:
if (aCol < MTSZ-1) bCol = aCol+1; break; // right cell candidate
case 2:
if (aRow > 0) bRow = aRow-1; break; // top cell candidate
case 3:
if (aRow < MTSZ-1) bRow = aRow+1; break; // bottom cell candidate
}
}

// we have two adjacent cells.
if (myMaze[aCol][aRow].setNumber != myMaze[bCol][bRow].setNumber) {

// join them by going through all cells and sharing set number
int changeToSet = myMaze[aCol][aRow].setNumber;
int changeFromSet = myMaze[bCol][bRow].setNumber;
for (int col=0; col<MTSZ; col++) {
for (int row=0; row<MTSZ; row++) {
if ( myMaze[col][row].setNumber == changeFromSet )
myMaze[col][row].setNumber = changeToSet;
}
}

// now remove common hedge
switch (testdir) {
case 0: myMaze[aCol][aRow].leftHedge = false;
myMaze[bCol][bRow].rightHedge = false;
break;
case 1: myMaze[aCol][aRow].rightHedge = false;
myMaze[bCol][bRow].leftHedge = false;
break;
case 2: myMaze[aCol][aRow].topHedge = false;
myMaze[bCol][bRow].bottomHedge = false;
break;
case 3: myMaze[aCol][aRow].bottomHedge = false;
myMaze[bCol][bRow].topHedge = false;
break;
} // end of switch
numSets--;
}
}

// make an entry and exit point to the maze
myMaze[0][0].leftHedge = false;
myMaze[MTSZ-1][MTSZ-1].rightHedge = false;
}
just to keep you all in on the action, it works :-) the maze generation as a basis for a random level, looks good!

-B