Skip to content

Instantly share code, notes, and snippets.

@devm33
Last active August 29, 2015 13:58
Show Gist options
  • Select an option

  • Save devm33/10339400 to your computer and use it in GitHub Desktop.

Select an option

Save devm33/10339400 to your computer and use it in GitHub Desktop.
/*
* robotMaze.js
*
* The blue key is inside a labyrinth, and extracting
* it will not be easy.
*
* It's a good thing that you're a AI expert, or
* we would have to leave empty-handed.
*/
function startLevel(map) {
map.getRandomInt = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
map.placePlayer(map.getWidth()-1, map.getHeight()-1);
var player = map.getPlayer();
map.defineObject('robot', {
'type': 'dynamic',
'symbol': 'R',
'color': 'gray',
'onCollision': function (player, me) {
me.giveItemTo(player, 'blueKey');
},
'behavior': function (me) {
// vars (lazy me)
var x = me.getX(),
y = me.getY();
// track visited and done
if(typeof me.visited == 'undefined') {
me.visited = {};
for(i = 0; i < map.getWidth(); i++) {
for(j = 0; j < map.getHeight(); j++) {
me.visited[i+' '+j] = 0;
}}
}
if(typeof me.done == 'undefined') {
me.done = {};
}
me.visited[x+' '+y]++;
// move to an unvisited neighbor or backup
var moves = [], backups = [];
[['right', x+1, y],
['left', x-1, y],
['down', x, y+1],
['up', x, y-1]].forEach(function(v){
if(me.canMove(v[0])) {
if(me.visited[v[1]+' '+v[2]] == 0) {
moves.push(v[0]);
}
else if(!me.done[v[1]+' '+v[2]]){
backups.push(v);
}
}
});
if(moves.length > 0) {
me.move(moves[0]);
}
else {
if(backups.length == 1) {
me.done[x+' '+y] = true;
me.move(backups[0][0]);
}
else {
var min_v = backups[0],
min_c = me.visited[min_v[1]+' '+min_v[2]];
backups.forEach(function(v){
if(me.visited[v[1]+' '+v[2]] < min_c){
min_v = v;
min_c = me.visited[v[1]+' '+v[2]];
}
});
me.move(min_v[0]);
}
}
}
});
map.defineObject('barrier', {
'symbol': '░',
'color': 'purple',
'impassable': true,
'passableFor': ['robot']
});
map.placeObject(0, map.getHeight() - 1, 'exit');
map.placeObject(1, 1, 'robot');
map.placeObject(map.getWidth() - 2, 8, 'blueKey');
map.placeObject(map.getWidth() - 2, 9, 'barrier');
var autoGeneratedMaze = new ROT.Map.DividedMaze(map.getWidth(), 10);
autoGeneratedMaze.create( function (x, y, mapValue) {
// don't write maze over robot or barrier
if ((x == 1 && y == 1) || (x == map.getWidth() - 2 && y >= 8)) {
return 0;
} else if (mapValue === 1) { //0 is empty space 1 is wall
map.placeObject(x,y, 'block');
} else {
map.placeObject(x,y,'empty');
}
});
}
function validateLevel(map) {
map.validateExactlyXManyObjects(1, 'exit');
map.validateExactlyXManyObjects(1, 'robot');
map.validateAtMostXObjects(1, 'blueKey');
}
function onExit(map) {
if (!map.getPlayer().hasItem('blueKey')) {
map.writeStatus("We need to get that key!");
return false;
} else {
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment