JavaScript - Improve my grid search algorithm - javascript

I have made my own "GhettoSearch," which is used to find the closest path between 2 given coordinates over a Grid, AKA a "list of coordinates."
The grid is an array like this:
var grid [ [somedata, [x,y,z], somedata], [somedata, [x,y,z], somedata] ]etc..
My start and stop positions is only coordinates, the Z coordinate is irrelevant at the moment.
I can almost get to the end, but some detoures are made because of my cost function.
Here is how the search looks complete: http://i.imgur.com/2ZjQBrh.png
Here is the code I currently use for the search:
var Main = {
GhettoSearch: function(Start, Stop, Grid){
var Pgreed = 1; //From current position to next nearby nodes
var Tgreed = 0.25; //from current position to target node
var Pcost = 0;
var Tcost = 0;
var open = [];
var closed = [];
var aReturn = [];
for (i = 0; i < Grid.length; i++) {
Worldmap.GetNode("Node_" + Grid[i][0]).style.backgroundColor = "#FFFFFF";
Pcost = Heuristics.Distance.Manhattan(Grid[i][1], Start, Pgreed);
Tcost = Heuristics.Distance.Manhattan(Grid[i][1], Stop, Tgreed);
open.push([i, (Pcost + Tcost)]);
}
do {
var TmpData = [0, Infinity];
var TmpForI = null;
for (i = 0; i < open.length; i++) {
if (open[i][1] < TmpData[1]) {
TmpData[0] = open[i][0];
TmpData[1] = open[i][1];
TmpForI = i;
}
}
closed.push(TmpData);
open.splice(TmpForI, 1);
for (i = 0; i < open.length; i++) {
Start = Grid[TmpData[0]][1]; //is now the start for recently closed node
Pcost = Heuristics.Distance.Manhattan(Grid[open[i][0]][1], Start, Pgreed);
Tcost = Heuristics.Distance.Manhattan(Grid[open[i][0]][1], Stop, Tgreed);
open[i] = [open[i][0], (Pcost + Tcost)];
}
} while (open.length > 0);
var PathID = null;
var TmpDist = Infinity;
for (i = 0; i < closed.length; i++) {
var NodeID = Grid[closed[i][0]][0];
var NodeCoords = Grid[closed[i][0]][1];
var NodeCost = closed[i][1];
aReturn.push([NodeID, NodeCoords, NodeCost]);
//var Dist = Heuristics.Distance.Manhattan(NodeCoords, Stop, 1);
if (NodeCost < TmpDist) {
TmpDist = NodeCost;
PathID = i;//Because you will remove the closest cord elese. OR? will u xD
}
}
aReturn.splice(PathID, closed.length);
return aReturn;
}
};
As you can see on the image, while going upwards it goes back and fills the empty spots besides the straight path up, how can I avoid this?
Yes, I have looked at different search aproaches such as BFS and a star, but I have problems implementing this in my own search function

Related

Reset values Issue

Building a dice game and you get 3 rolls. Once you finish your turn i'm trying to have a "reset" button that will reset the values back to the original spot so the "next person" can play. The values reset as I expected but when I "roll" none of the functions are taking place and i'm pretty new in js so i'm not sure what the problem is.
var playerScore = document.getElementById('firstPlayerScore');
var rollButton = document.getElementById('roll_button');
var dice1 = new dice(1);
var dice2 = new dice(2);
var dice3 = new dice(3);
var dice4 = new dice(4);
var dice5 = new dice(5);
var diceArray = [dice1, dice2, dice3, dice4, dice5];
var cargo = 0;
var numOfRolls = 0;
var cargoButton = document.getElementById('cargo');
var canHaveCargo = false;
function restart(){
dice1 = new dice(1);
dice2 = new dice(2);
dice3 = new dice(3);
dice4 = new dice(4);
dice5 = new dice(5);
diceArray = [dice1, dice2, dice3, dice4, dice5];
cargo = 0;
numOfRolls = 0;
canHaveCargo = false;
addGlow();
updateDiceImageUrl();
document.getElementById("dice1").classList.remove('glowing');
document.getElementById("dice2").classList.remove('glowing');
document.getElementById("dice3").classList.remove('glowing');
document.getElementById("dice4").classList.remove('glowing');
document.getElementById("dice5").classList.remove('glowing');
}
//dice object
function dice(id){
this.id = id;
this.currentRoll = 1;
this.previousRoll = 1;
this.isSelected = false;
this.diceImageUrl = "img/dice/dice1.png";
this.roll = function(){
this.previousRoll = this.currentRoll;
this.currentRoll = getRandomRoll(1, 6);
}
}
//returns an array of all dice that are not currently selected so they can be rolled.
function getRollableDiceList(){
var tempDiceList = [];
for(var i = 0; i < diceArray.length; i++){
if(!diceArray[i].isSelected){
tempDiceList.push(diceArray[i]);
}
}
return tempDiceList;
}
// gets a random number between min and max (including min and max)
function getRandomRoll(min,max){
return Math.floor(Math.random() * (max-min + 1) + min);
}
// calls the roll function on each dice
function rollDice(rollableDiceList){
for(var i = 0; i < rollableDiceList.length; i++){
rollableDiceList[i].roll();
}
}
// updates each dice with the new url for the image that corresponds to what their current roll is
function updateDiceImageUrl(){
for(var i = 0; i < diceArray.length; i++){
var currentDice = diceArray[i];
currentDice.diceImageUrl = "http://boomersplayground.com/img/dice/dice" + currentDice.currentRoll + ".png";
//update div image with img that cooresponds to their current roll
updateDiceDivImage(currentDice);
}
}
//Displays the image that matches the roll on each dice
function updateDiceDivImage(currentDice) {
document.getElementById("dice"+currentDice.id).style.backgroundImage = "url('" + currentDice.diceImageUrl +"')";
}
// returns an array of all
function getNonSelectedDice(){
var tempArray = [];
for(var i = 0; i < diceArray.length; i++){
if(!diceArray[i].isSelected){
tempArray.push(diceArray[i]);
}
tempArray.sort(function(a, b){
return b.currentRoll - a.currentRoll;
});
}
return tempArray;
}
function getSelectedDice(){
var selectedDice = [];
for(var i = 0; i < diceArray.length; i++){
if(diceArray[i].isSelected){
selectedDice.push(diceArray[i]);
}
}
return selectedDice;
}
//boolean variables
var shipExist = false;
var captExist = false;
var crewExist = false;
//checks each dice for ship captain and crew. Auto select the first 6, 5 , 4.
function checkForShipCaptCrew(){
//array of dice that are not marked selected
var nonSelectedDice = getNonSelectedDice();
for(var i = 0; i < nonSelectedDice.length; i++){
//temp variable that represents the current dice in the list
currentDice = nonSelectedDice[i];
if (!shipExist) {
if (currentDice.currentRoll == 6) {
shipExist = true;
currentDice.isSelected = true;
}
}
if (shipExist && !captExist) {
if (currentDice.currentRoll == 5) {
captExist = true;
currentDice.isSelected = true;
}
}
if (shipExist && captExist && !crewExist) {
if (currentDice.currentRoll == 4) {
crewExist = true;
currentDice.isSelected = true;
canHaveCargo = true;
}
}
}
}
function addGlow(){
var selectedDice = getSelectedDice();
for (var i = 0; i < selectedDice.length; i++){
var addGlowDice = selectedDice[i];
var element = document.getElementById('dice' + addGlowDice.id);
element.className = element.className + " glowing";
}
}
function getCargo(){
var cargo = 0;
var moreDice = getNonSelectedDice();
if (canHaveCargo){
for(var i=0; i < moreDice.length; i++){
cargo += moreDice[i].currentRoll;
playerScore.innerHTML = 'You have got ' + cargo + ' in ' + numOfRolls + ' rolls!';
}
} else {
alert("You don't have Ship Captain and the Crew yet!");
}
}
rollButton.addEventListener('click', function(){
//generate rollable dice list
if (numOfRolls < 3) {
var rollableDiceList = getRollableDiceList();
//roll each dice
rollDice(rollableDiceList);
//update dice images
updateDiceImageUrl();
getNonSelectedDice();
// //auto select first 6, 5, 4 (in that order)
checkForShipCaptCrew();
addGlow();
// //adds a red glow to each dice that is selected
numOfRolls++;
}
});
cargoButton.addEventListener('click', getCargo);
var startButton = document.getElementById('restart');
startButton.addEventListener('click', restart);
http://boomer1204.github.io/shipCaptainCrew/
Here is a link to the live game since it's the only way I can describe the problem since I don't know what's not working. If you roll the dice a couple times the dice will get a blue border and be "saved" according to the rules. Now after you hit th restart button that doesn't happen anymore.
Thanks for the help in advance guys
Just add this to your restart()
function restart(){
...
shipExist = false;
capExist = false;
crewExist = false;
...
}
It's hard to replicate without a fiddle, but it seems that you are adding and removing the 'glowing' class using separate processes. Have you tried adding the glowing class the same way you are removing it?
element.classList.add("glowing")
See an example within a fiddle: https://jsfiddle.net/5tstf2f8/

Having issue On Loading All JSON Data into Markers Layer With in For Loop

I have a code like below which is suppose to add over 600 points into a GraphicLayer projectsG and eventually add the projectsG to layer1 and map but I am not sure what I am doing wrong in
projectsG = new esri.Graphic(project, symbol).setInfoTemplate(projectInfoTemplate);
}
console.log(thepoints);
layer1 = new esri.layers.GraphicsLayer();
for (i = 0; i < points.length; ++i) {
layer1.add(projectsG);
}
part which only adds the last project into the map! Can you please take a look at following code and let me know what I am doing wrong in looping?
var layer1,
var thepoints=[];
var projectInfoTemplate;
var projectsG;
var points = [
{
"ProjectID":"15260",
"Longitude":"-118.641508",
"Latitude":"51.949915",
},
{
"ProjectID":"17043",
"Longitude":"-125.444557",
"Latitude":"51.097552",
},
....
{
"ProjectID":"13009",
"Longitude":"-130.257086",
"Latitude":"56.882834",
},
{
"ProjectID":"17088",
"Longitude":"-124.160699",
"Latitude":"50.897618",
}
];
function drawSeries1() {
for (var i = 0; i < points.length; i++) {
var projects = points[i];
var project = new esri.geometry.Point(projects.Longitude, projects.Latitude);
project = esri.geometry.geographicToWebMercator(project);
var symbol = new esri.symbol.PictureMarkerSymbol("e-Chartreuse.png", 32, 32);
projectInfoTemplate = new InfoTemplate();
projectInfoTemplate.setTitle("Project Details");
projectInfoTemplate.setContent('<div>Some Att Here</div> ');
projectsG = new esri.Graphic(project, symbol).setInfoTemplate(projectInfoTemplate);
thepoints.push(projectsG);
}
console.log(thepoints);
layer1 = new esri.layers.GraphicsLayer();
for (i = 0; i < points.length; ++i) {
layer1.add(projectsG);
}
map.addLayer(layer1);
}
try this for loop :
for (var i = 0; i < thepoints.length; ++i) {
layer1.add(thepoints[i]);
}
even "better", you could skip that last for loop, and replace thepoints.push(projectsG); with layer1.add(projectsG); in the previous for loop

Detect coherent neighbors / neighborhood in 2d array

Im having an arbitrary 2d array and each field has an id and a teamid (here illustrated as colors 1).
I want for every neighborhood an array with the ids
in it.
A neighborhood consists of fields with neighbors with the same teamid horizontally and vertically (not diagonally)
e.g.:
This is what i have:
array[0][0] = {id:1,teamId:1}
array[1][0] = {id:2,teamId:1}
array[2][0] = {id:3,teamId:0}
array[3][0] = {id:4,teamId:2}
array[4][0] = {id:5,teamId:2}
array[5][0] = {id:6,teamId:0}
array[0][1] = {id:7,teamId:1}
array[1][1] = {id:8,teamId:1}
array[2][1] = {id:9,teamId:1}
array[3][1] = {id:10,teamId:2}
array[4][1] = {id:11,teamId:2}
array[5][1] = {id:12,teamId:0}
//and so on..
This is what i want:
neighborhood[1] = [1,2,7,8,9,13,14]
neighborhood[2] = [4,5,10,11]
neighborhood[3] = [16,22,23,24,29,30]
neighborhood[4] = [25,31,32,37,38]
neighborhood[5] = [35,41]
I am not searching for the images, but for the array
neighborhood
thanks in advance!
You can use the logic from dots and block games. A block belongs to a player if he has surrounded it with the walls. So, you need for each cell also 4 walls except for the outer cells. To test if a cell is closed you can use 4 class variables:
var Block = function() {
this.isclosed=0;
this.left=0;
this.top=0;
this.right=0;
this.bottom=0;
return this;
}
Block.prototype = {
isClosed : function () {
if (this.isclosed==true) {
return false;
} else if (this.left && this.top && this.right && this.bottom) {
this.isclosed=true;
return true;
} else {
return this.left && this.top && this.right && this.bottom;
}
}
}
You can try my implementations of dots and blocks game # https://dotsgame.codeplex.com/.
The method for solving this issue is refered as Connected Component Labelling
A similar question was asked once before from which i have my solution:
// matrix dimensions
var row_count = 20;
var col_count = 20;
var numOfTeams = 2;
// the input matrix
var m = [];
// the labels, 0 means unlabeled
var label = [];
var source = document.getElementById("source");
for (var i = 0; i < row_count; i++) {
var row = source.insertRow(0);
m[i] = [];
label[i] = [];
for (var j = 0; j < col_count; j++) {
//m[i][j] = Math.round(Math.random());
m[i][j] = getRandomInt(0, numOfTeams + 1);
label[i][j] = 0;
var cell1 = row.insertCell(0);
cell1.innerHTML = m[i][j];
}
}
// direction vectors
var dx = [1, 0, -1, 0];
var dy = [0, 1, 0, -1];
function dfs(x, y, current_label, team) {
if (x < 0 || x == row_count) return; // out of bounds
if (y < 0 || y == col_count) return; // out of bounds
if (label[x][y] || team != m[x][y]) return; // already labeled or not marked with 1 in m
// mark the current cell
label[x][y] = current_label;
// recursively mark the neighbors
for (var direction = 0; direction < 4; ++direction) {
dfs(x + dx[direction], y + dy[direction], current_label, team);
}
}
function find_components() {
var component = 0;
for (var i = 0; i < row_count; ++i) {
for (var j = 0; j < col_count; ++j) {
if (!label[i][j] && m[i][j]) dfs(i, j, ++component, m[i][j]);
}
}
}
find_components();
var result = document.getElementById("result");
for (var i in label) {
var string = ""
var row = result.insertRow(0);
for (var j in label[i]) {
string += label[i][j] + " "
var cell1 = row.insertCell(0);
cell1.innerHTML = label[i][j];
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
table tr td {
min-width: 14px
}
<div style="float:left">
<table id="source"></table>
</div>
<div style="float:right">
<table id="result"></table>
</div>

How do I empty global arrays used in a pop up slideshow?

I've created a program where you can choose a set of images by checking checkboxes. The image URL's and the alt-texts are stored in two arrays. When clicking av button on the HTML-page you open a new window that calls on the arrays with window.opener.
When closing the new window I would like to empty the arrays. Otherwise the pictures chosen in the first round are displayed in the slideshow when opening it the second time. I understand you can empty arrays by this method: array.length= 0;
But where do I add the code? I'm quite lost. I'm pasting the code, perhaps someone can give me a hand.
var imgUrlList = [], imgTextList = [], //These arrays need to be emptied
windVar = null;
function init() {
var tags, i, openWindow;
tags = document.getElementsByClassName("unmarkedImg");
openWindow = document.getElementById("slideShowBtn");
openWindow.onclick = savePicsForSlideshow;
for (i = 0; i < tags.length; i++) {
tags[i].parentNode.onmouseover = showLargePict;
tags[i].parentNode.onmouseout = hideLargePict;
}
}
window.onload = init;
function showLargePict() {
var largePictTagDiv = this.getElementsByClassName("innerBox")[0];
var largePictTagParentDiv = largePictTagDiv.parentNode;
var imgTag = largePictTagParentDiv.getElementsByTagName('img')[0];
var checkBoxlargePict = largePictTagDiv.getElementsByTagName('input')[0];
if (checkBoxlargePict.checked)
imgTag.className = "markedImg";
else imgTag.className = "unmarkedImg";
largePictTagDiv.style.visibility = "visible";
} // End showLargePict
function hideLargePict() {
var largePictTag;
largePictTag = this.getElementsByClassName("innerBox")[0];
largePictTag.style.visibility = "hidden";
}
function savePicsForSlideshow() {
var innerBoxes = document.getElementsByClassName("innerBox");
for (i = 0; i < innerBoxes.length; i++) {
checkBoxlargePict = innerBoxes[i].getElementsByTagName('input')[0];
if (checkBoxlargePict.checked) {
var imgTagSrc = innerBoxes[i].getElementsByTagName('img')[0].src;
imgUrlList.push(imgTagSrc);
var spanTagText = innerBoxes[i].getElementsByTagName('span')[0].innerHTML;
imgTextList.push(spanTagText);
}
}
if (imgTextList.length > 0) {
newWindow(500, 600, "slideshow.htm");
}
}
function newWindow(width, height, filename) {
var windowProperties;
windowProperties = "top=100,left=100,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + width + ",height=" + height;
if (windVar != null) if (windVar.closed == false) windVar.close();
windVar = window.open(filename, "", windowProperties);
}
Please excuse my programming and English grammar shortcomings. I'm new to javascript.
//Henrik, Göteborg, Sweden.
At the beginning of the savePicsForSlideshow function, empty out each array.
imgUrlList.length = 0;
imgTextList.length = 0;
You can check if thw window is close with the property closed of the object window
if(window.closed)
{
array.length = 0;
}

Faulty Logic in this image color equalization algorithm

Somewhere in my code, I seem to be doing something wrong and I cannot tell which part is going awry. I've printed to console the values I'm getting from the various arrays and it seems to match up. Then when I run the equalization function (a la Wikipedia-Histogram Equalization) my output image is close to total black. I was trying to interpret this guy's php into javascript just to test some stuff out and figured I did a decent job. But I'm not an expert.
The pertinent parts:
function imageLoaded(ev) {
element = document.getElementById("canvas1");
c = element.getContext("2d");
im = ev.target; // the image
// read the width and height of the canvas
width = element.width;
height = element.height;
// stamp the image on the left of the canvas:
c.drawImage(im, 0, 0);
// get all canvas pixel data
imageData = c.getImageData(0, 0, width, height);
w2 = width / 2;
var reds = new Array();
var greens = new Array();
var blues = new Array();
var freqR = new Array();
var freqG = new Array();
var freqB = new Array();
if (imageData){
buildHistograms(reds, greens,blues);
buildFrequencies(reds, greens, blues, freqR, freqG, freqB);
}
var alpha = 255/(w2*height);
// run through the image
for (y = 0; y < height; y++) {
inpos = y * width * 4; // *4 for 4 ints per pixel
outpos = inpos + w2 * 4;
for (x = 0; x < w2; x++) {
//reads pixel data(of img c)to each channel of rgb
r = imageData.data[inpos++];
g = imageData.data[inpos++];
b = imageData.data[inpos++];
a = imageData.data[inpos++];
//using histogram eqalization formula:
adjR = freqR[r]*alpha;
adjG = freqG[g]*alpha;
adjB = freqB[b]*alpha;
//assigns pixel data of output image
imageData.data[outpos++] = adjR;
imageData.data[outpos++] = adjG;
imageData.data[outpos++] = adjB;
imageData.data[outpos++] = a;
}
}
// put pixel data on canvas
c.putImageData(imageData, 0,0);
}
im = new Image();
im.onload = imageLoaded;
im.src = "Lenna.png";
function buildHistograms(reds,greens,blues){
//run through image building histogram
for (y=0; y < height; y++){
inpos = y * width *4;
for (x=0; x < w2; x++){
rd = imageData.data[inpos++];
g = imageData.data[inpos++];
b = imageData.data[inpos++];
a = imageData.data[inpos++];
// Add counts to our histogram arrays for each color.
reds.push(rd);
greens.push(g);
blues.push(b);
}
}
// Sort them by keys into order
reds.sort(function(a,b){return a-b});
greens.sort(function(a,b){return a-b});
blues.sort(function(a,b){return a-b});
}
function buildFrequencies(reds, greens, blues, freqR, freqG, freqB){
// Build frequency charts for all colors: takes REDS GREENS BLUES from buildHistograms and places them on top of each other accordingly
for(i=0; i<=255; i++){
sumR=0;
sumG=0;
sumB=0;
for(j=0; j<= i; j++){
if (reds[j]){sumR+=reds[j];}
if (greens[j]){sumG+=greens[j];}
if (blues[j]){sumB+=blues[j];}
}
freqR[i] = sumR;
freqG[i] = sumG;
freqB[i] = sumB;
}
}
Any help is appreciated, Thanks.
Looks like my build frequencies section was all wrong. I modified it in this way:
var len = reds.length;
for (j=0; j < len; j++) {
var rCurrVal = reds[j];
var gCurrVal = greens[j];
var bCurrVal = blues[j];
if (freqR.hasOwnProperty(rCurrVal)) {
freqR[rCurrVal] += 1;
} else {
freqR[rCurrVal] = 1;
}
if (freqG.hasOwnProperty(gCurrVal)) {
freqG[gCurrVal] += 1;
} else {
freqG[gCurrVal] = 1;
}
if (freqB.hasOwnProperty(bCurrVal)) {
freqB[bCurrVal] += 1;
} else {
freqB[bCurrVal] = 1;
}
}
for (i=0; i<255; i++){
if ($.inArray(i,reds)===-1){freqR[i]=0;}
if ($.inArray(i,greens)=== -1){freqG[i]=0;}
if ($.inArray(i,blues)=== -1){freqB[i]=0;}
if (i>0){
freqR[i]+=freqR[i-1];
freqG[i]+=freqG[i-1];
freqB[i]+=freqB[i-1];
}
}

Categories

Resources