Skip to content

Instantly share code, notes, and snippets.

@mernen
Created July 26, 2010 03:52
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 mernen/490161 to your computer and use it in GitHub Desktop.
Save mernen/490161 to your computer and use it in GitHub Desktop.
Nerdson Labs: algoritmo de movimento estilo jogo TBS
$(document).ready(function(){
$("#tactics form").submit(function(e){
e.preventDefault();
});
//syntax highlight
ChiliBook.recipeFolder = "./";
//observação: criei variáveis globais aqui a nivel de exemplo, mas isso não é recomendado. O ideal é criar objetos para armazenar esses valores. ;)
var TILE = 30;
var X, Y = 0;
//matriz relativamente grande. Cuidado :)
var grid = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],
[0,0,0,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0],
[0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],
[1,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0],
[0,0,0,1,1,1,0,0,1,1,0,0,0,0,1,1,1,0,0],
[0,0,0,1,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,1],
[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0]];
var WIDTH = grid[0].length;
var HEIGHT = grid.length;
var closed_tiles = {};
var tiles = [];
var MOV = 2;
//helpers
function get_x(obj){
return parseInt(obj.css("left"), 10);
}
function get_y(obj){
return parseInt(obj.css("top"), 10);
}
//Retorna os tiles ao normal
function clear(){
$.each(closed_tiles, function(key, value) {
var coords = key.split(",");
var tile = tiles[coords[1]][coords[0]];
tile.css("background", "#DDD");
});
closed_tiles = {};
}
//função descrita no tutorial
function tile_walk(xn, yn, movement)
{
// acrescentar custo do tile-alvo
movement += 1;
// não ultrapassar limite de pontos de movimento
if (movement > MOV)
return;
// não passar dos limites da grade/tabuleiro
if (xn < 0 || xn >= WIDTH || yn < 0 || yn >= HEIGHT)
return;
// não andar por cima de obstáculos
if (grid[yn][xn] == 1)
return;
var coords = xn + "," + yn;
if (!(coords in closed_tiles) || closed_tiles[coords] > movement) {
closed_tiles[coords] = movement;
tiles[yn][xn].css("background", "#88F");
tile_walk(xn+1, yn, movement);
tile_walk(xn-1, yn, movement);
tile_walk(xn, yn+1, movement);
tile_walk(xn, yn-1, movement);
}
}
//constrói o cenário
for(var j = 0; j < HEIGHT; j++)
{
tiles[j] = [];
for(var i = 0; i < WIDTH; i++)
{
var type = "tile";
if (grid[j][i] == 1)
type = "obstacle";
var elem = $("<div/>").attr("class", type).css("top", j*TILE).css("left", i*TILE);
elem.click(function() {
MOV = $("#mov").val();
if (MOV < 1 || MOV > 7 || isNaN(MOV)) {
alert("Intervalo permitido: de 1 a 7");
MOV = 2;
$("#mov").val(2);
} else {
MOV = parseInt(MOV, 10);
X = get_x($(this)) / TILE;
Y = get_y($(this)) / TILE;
clear();
tile_walk(X, Y, -1);
}
});
tiles[j][i] = elem;
$("#game").append(elem);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment