Why is my small scale A* pathing script skipping everything? - javascript

I'm writing an A* pathing script for a game set on a 7x7 grid of tiles with the player always in the middle (tile 24). Zeros are added as a visual and it's actually one array, not a 7x7 2D array.
[00,01,02,03,04,05,06]
[07,08,09,10,11,12,13]
[14,15,16,17,18,19,20]
[21,22,23,24,25,26,27]
[28,29,30,31,32,33,34]
[35,36,37,38,39,40,41]
[42,43,44,45,46,47,48]
The game is server-driven so the player uses relative coordinates. What that means is, if the player moves, tile[0] changes. The short version of that is the player will always move from tile 24, which is the center tile. The grid is hard coded in, but if I post it publicly I'll change the code a little; no problem.
The function should take a destination and find a good path from tile 24 to that square but what it actually does it return "undefined".
If I input 24 I want the game to output an array like this
[18,12,6]
Here's the code:
z = 0;
function pathTo(goal){
var createPath = function (goal){
var createNode = function(i){
this.id = i;
this.g = Infinity;
this.f = Infinity;
this.parent = null;
this.open = null;
};
this.nodes = Array(49);
for(i=0;i<this.nodes.length;i++){
this.nodes[i] = new createNode(i);
}
this.start = this.nodes[24];
this.start.g = 0;
this.currentNodeId = 24;
this.goal = this.nodes[goal];
this.bestPath = null;
};//end createPath
var getBestNeighbor = function(nodeId){
z++
if(z>50){throw z}debugger;
console.log(nodeId);
var getG = function(parentG){
//here you can check the map for water, sand, and ruins penalties
/*
default = 1
path = .9
water = 3
*/
return (parentG + 1);
};
var closeNode = function (node){
node.open = false;
};//end closeNode
var getF = function(startId,endId,g){
if(g>9){
throw g;
}
var startX = startId % 7;
var startY = (startId - startX) / 7;
var endX = endId % 7;
var endY = (endId - endX) / 7;
var h = Math.sqrt( Math.pow((startX - endX) , 2 ) + Math.pow(( startY - endY ), 2 ) );
console.log("Start.id:"+startId+"H:"+h+" Start.id.g:"+g);
return (h + g);
};//end getF
var tracePath = function(tracedNode){
path.bestPath = [];
while(tracedNode != path.start){
path.bestPath.unshift(tracedNode.id);
tracedNode = tracedNode.parent;
}
return path.bestPath;
};//end tracePath
var getNeighborNodeId = function(x,y,currentId){return currentId + (y*7) + x;};//end getNeighborNodeId
if(path.bestPath === null){
var neighborNode = {};
var bestNode = {f: Infinity};
if(nodeId == path.goal.id){//may need to pass path
return tracePath(path.nodes[nodeId]);
}else{
for(x=-1;x<=1;x++){
for(y=-1;y<=1;y++){
var nnId = getNeighborNodeId(x,y,nodeId);
if(nnId==24){debugger}
if( ( (x!=0) && (y!=0) ) ||( (nnId>=0) && (nnId<=48))){
var neighborNode = path.nodes[nnId];
if(neighborNode.open === null){ neighborNode.open = true; }
if(neighborNode.open === true ){//don't check closed neighbors
if(typeof neighborNode === "object"){
neighborNode.parent = path.nodes[nodeId]
debugger;
neighborNode.g = getG(neighborNode.parent.g);
neighborNode.f = getF(neighborNode.id , path.goal.id , neighborNode.g);
if( neighborNode.f < bestNode.f){
bestNode = neighborNode;
}//endif
}//endif
}//endif Note: if the node isn't null or true, it's false.
}
}//endfor
}//endfor - Note: Here we should have the best neighbor
if(bestNode.f == Infinity){
closeNode(path.nodes[nodeId]);//need escape for no possible path
return;
}else{
//bestNode.parent = path.nodes[nodeId];
path.currentNodeId = bestNode.id;
getBestNeighbor(bestNode.id);
}//endelse
}//endelse
}//endif
};//end getBestNeighbor
var path = new createPath(goal);
while(path.bestPath === null){
getBestNeighbor(path.currentNodeId);
}//end while
return path.bestPath;
}//end pathTo
console.log(pathTo(41)); //testing with 6
and a JSFiddle link: https://jsfiddle.net/jb4xtf3h/
It's my first time not just slapping globals everywhere, so it may have a scope issue I'm not familiar with.
Most likely my issue is in the getNeighborId function; I don't think I have anything declaring a good node's parent.
The problem is that it goes NW three times instead of NE three times. That probably means I have a mistake in the getBestNeighbor function where I'm reading a -1 as a 1.
Also I don't think I'm escaping the recursive function correctly.
For some reason, when I put in 41 it gets really confused. This either has to do with how I set G and H which are classically used in A* to record distance traveled on this path and the estimated distance remaining. Specifically the G number is wrong because it's taking bad steps for some reason.

Here is the working code. I didn't implement walls or anything but I do show where you would do that. All you need to do is close all the nodes that are walls before you begin pathing and you can assign movement penalties if you want the AI to "know" to avoid water or sand.
I actually can't pin down a single problem but a major one was the way the statement:
if( ( (x!=0) && (y!=0) ) ||( (nnId>=0) && (nnId<=48))){
was changed to:
if( ( !(x==0 && y==0) && ( nnId>=0 && nnId<=48))){
The intent of this line was to prevent searching the tile you are standing on x,y = (0,0) and also to make sure that the neighbor you want to look at is on the grid (7x7 grid has 49 squares numbered 0-48)
What I was trying to say is "IF X & Y ARE BOTH NOT ZERO" apparently that actually makes it the same as an or statement so if either square was 0 it skipped it and tiles that needed that space were having problems since there were several directions that weren't working.
I hope that helps somebody if they need a nice simple pathing script I tried really hard to make the code readable and I'm not the strongest coder in the world but a working A* script in 100 lines that I think is fairly easy to follow. If you are reading this and you're not familiar with A* pathing what you might need to know is
H is your heuristic value it's an estimation of the remaining distance form a tile. In this code it's under the path object path.nodes[array#].h
G is the distance you've moved so far to get to that square path.nodes[array#].g.
F just adds h+g for the total value. This pseudocode on Wikipedia helped me write it.
var z = 0;
function pathTo(goal){
var createPath = function (goal){
var createNode = function(i){
this.id = i;
this.g = Infinity;
this.f = Infinity;
this.parent = null;
this.open = null;
};
this.nodes = Array(49);
for(i=0;i<this.nodes.length;i++){
this.nodes[i] = new createNode(i);
}
this.start = this.nodes[24];
this.start.g = 0;
this.currentNodeId = 24;
this.goal = this.nodes[goal];
this.bestPath = null;
};//end createPath
var path = new createPath(goal);
var getBestNeighbor = function(nodeId){
var getG = function(parentG){
//here you can check the map for water, sand, and ruins penalties
/*
default = 1
path = .9
water = 3
*/
return (parentG + 1);
};
var closeNode = function (node){
node.open = false;
};//end closeNode
var getF = function(startId,endId,g){
var startX = startId % 7;
var startY = (startId - startX) / 7;
var endX = endId % 7;
var endY = (endId - endX) / 7;
var h = Math.sqrt( Math.pow((startX - endX) , 2 ) + Math.pow(( startY - endY ), 2 ) );
return (h + g);
};//end getF
var tracePath = function(tracedNode){
path.bestPath = [];
while(tracedNode != path.start){
path.bestPath.unshift(tracedNode.id);
tracedNode = tracedNode.parent;
}
return path.bestPath;
};//end tracePath
var getNeighborNodeId = function(x,y,currentId){return currentId + (y*7) + x;};//end getNeighborNodeId
debugger;
z++
if(z>50){throw z}
if(path.bestPath === null){
var neighborNode = {};
var bestNode = {f: Infinity};
if(nodeId == path.goal.id){//may need to pass path
return tracePath(path.nodes[nodeId]);
}else{
for(y=-1;y<=1;y++){
for(x=-1;x<=1;x++){
var nnId = getNeighborNodeId(x,y,nodeId);
if( ( !(x==0 && y==0) && ( nnId>=0 && nnId<=48))){
var neighborNode = path.nodes[nnId];
if(path.nodes[nodeId].parent!=neighborNode){
if(neighborNode.open === null){ neighborNode.open = true; }
if(neighborNode.open === true ){//don't check closed neighbors
if(typeof neighborNode === "object"){
neighborNode.parent = path.nodes[nodeId]
neighborNode.g = getG(neighborNode.parent.g);
neighborNode.f = getF(neighborNode.id , path.goal.id , neighborNode.g);
if( neighborNode.f < bestNode.f){
bestNode = neighborNode;
}//endif
}//endif
}
}//endif Note: if the node isn't null or true, it's false.
}
}//endfor
}//endfor - Note: Here we should have the best neighbor
if(bestNode.f >= 50){
closeNode(path.nodes[nodeId]);//need escape for no possible path
return;
}else{
path.currentNodeId = bestNode.id;
getBestNeighbor(bestNode.id);
}//endelse
}//endelse
}//endif
};//end getBestNeighbor
while(path.bestPath === null){
getBestNeighbor(path.currentNodeId);
}//end while
return path.bestPath;
}//end pathTo
myPath = pathTo(41); //testing with 6
console.log("path2:"+myPath);

Related

How to reduce number of computations during d3.js transition?

So right now, I'm trying to implement a search bar function into my d3.js plot. Right now it doesn't do anything, but that's not the issue at the moment. The problem is that when I type/delete something from the bar, there's visible lag/choppiness in the characters appearing/disappearing. I believe the issue is stemming from my plot. I have 140+ dots moving around the screen, and their position is being interpolated. So from the beginning to the end of the transition, my code has to compute 140 positions thousands of times over.
I've looked into trying to reduce the cardinality of the d3.interpolateNumber function, but it appears that there isn't a third argument to change the number of terms like in a linspace command. Right now I have an array of 1000 numbers for my function to run through, but I don't know how to pass the array to my other functions.
Below are the pertinent functions for this issue. The commented line in tweenPatch is the original code I had that made my code run, but gave my plot computational issues. Variables arr, curr, and step were my attempt to fix the situation, but I haven't been able to figure out how to pass the array into displayPatch().
function tweenPatch() {
var patch = d3.interpolateNumber(1, 26);
var arr = [];
var curr = 1;
var step = (26 - 1) / (1000 - 1);
for (var i = 0; i < 1000; i++) {
arr.push(curr + (step * i));
}
return arr.forEach(function(d) {
console.log(arr[d]);
displayPatch(arr[d]);
});
//return function(t) { displayPatch(t); };
}
function displayPatch(patch) {
dots.data(interpolateData(patch), function(d) { return d.name; }).call(position).sort(order);
var inter = Math.floor(patch);
var seas = 8;
var patc = 1;
if (inter > 24) {
seas = 9;
patc = inter - 24;
} else {
patc = inter;
}
label.text("Patch " + seas + "." + patc);
}
function interpolateValues(values, number) {
old = Math.floor(number);
upd = Math.ceil(number);
var old_data = values.filter(function(d) {return d.internal == old;});
var new_data = values.filter(function(d) {return d.internal == upd;});
var oobj = old_data[0];
var nobj = new_data[0];
var onum = oobj[Object.keys(oobj)[4]];
var nnum = nobj[Object.keys(nobj)[4]];
var difint = number - old;
var difdis = 0;
var newnum = nnum;
if (nnum > onum) {
difdis = nnum - onum;
newnum = ((difint) * difdis) + onum;
} else if (onum > nnum) {
difdis = onum - nnum;
newnum = onum - ((difint) * difdis);
}
return newnum;
}
I believe switching my SVG to a canvas may help things, but since I have no knowledge of canvas I'd rather leave that as a last resort.

javascript check if element rect hitting another with same class

I want to put like 30 of <img class="anger"> elements with random size and random position inside the <div> container, but none of the .anger hitting one another.
Is it possible?
This is my code so far:
function loadAngers() {
var wrp = '#angerContainer'; //the container
var rectAvatar = $('#picAvatar')[0].getBoundingClientRect(); //rect of user avatar
var rectWrapper = $(wrp)[0].getBoundingClientRect(); //rect of container
listCoorditaes = [[
rectAvatar.width,
(rectAvatar.left+rectAvatar.right)/2,
(rectAvatar.top+rectAvatar.bottom)/2
]];
$(wrp).find('.anger').remove();
for (var i=0; i<listAnger.length; i++) {
var verb = listAnger[i].replace('assets/img/verb/','').replace('.png','').replace('-',' ');
var anger = $('<img src="'+listAnger[i]+'" class="anger hvr-'+getRandom(listAnim)+'" data-verb="'+verb+'" style="position:absolute">');
var paddingX = 100;
var paddingY = 200;
var wideX = rectWrapper.width - paddingX;
var wideY = rectWrapper.height - paddingY - rectAvatar.top;
var width = Math.round(30 + Math.random() * 70);
var left;
var top;
var x;
var y;
var tubrukan;
var coba = 0;
do { //find the best coordinate
tubrukan = false;
coba++;
x = Math.round(Math.random() * wideX) + paddingX/2;
y = Math.round(Math.random() * wideY) + paddingY/2 + rectAvatar.top;
left = x - width/2;
top = y - width/2;
for (var j=0; j<=i; j++) {
var cekW = listCoorditaes[j][0];
var cekX = listCoorditaes[j][1];
var cekY = listCoorditaes[j][2];
var difX = Math.abs( x - cekX );
var difY = Math.abs( y - cekY );
if (difX < cekW && difY < cekW) {
tubrukan = true;
break;
}
}
}
while(tubrukan && coba<3); //as I give up for eternal loop, I limit the loop with 3 tries.
listCoorditaes.push([width,x,y]);
anger.css('width',width+'px');
anger.css('left',left);
anger.css('top',top);
anger.appendTo(wrp);
}
}
This is the current result:
As we can see, the elements still overlap the other because I limit the loop. If I remove the limit, browser will endure endless loop and become not responding.
Do you have another better way to achieve it?
UPDATE:
My bad, I set the container height only 800px, that's why it can't contain all those <img> without overlapping, thus eternal loop happen. I made it to 2000px to see if it works. But the problem is still takes uncertain number of loops to find the best coordinate, so I still put limit to the loop thus overlap still happen several times.

Creating a slider between two numbers

So I've been working on re-producing the slider found here https://www.skylight.io/ ( Scroll down to find the price slider ).
So far Ive managed to create something similiar, but some numbers are hard coded, making it difficult to change and not very re-usable.
I've been researching around and I think I need to use Math.log() and Math.exp() together to achieve something like in the link above but I'm not sure.
Heres a jsfiddle of what I have so far https://jsfiddle.net/7wrvpb34/.
I feel that its the maths part of this problem that is halting me I think, so any help would be greatly appreciated.
Javascript code below:
var slider = document.getElementById("slider")
var sliderFill = document.getElementById("slider-fill")
var knob = document.getElementById("knob")
var mouseDown;
var mousePos = {x:0};
var knobPosition;
var minPrice = 20;
var price = 0;
var minRequests = 50;
var requests = 50 + ",000";
var incrementSpeed = 2;
var incrementModifier = 20;
var incrementValue = 1;
var minMillionCount = 1;
var millionCount = 1;
var previousRequestAmount = 0;
document.getElementById("price").innerHTML = price;
document.getElementById("requests").innerHTML = requests;
highlightTable(1);
document.addEventListener('mousemove', function(e) {
if(mouseDown) {
updateSlider(e);
}
})
function updateSlider(event) {
mousePos.x = event.clientX - slider.getBoundingClientRect().left;
mousePos.x -= knob.offsetWidth / 2;
console.log(mousePos.x);
if(mousePos.x < 0) {
knob.style.left = "0px";
sliderFill.style.width = "0px";
price = 0;
requests = 50 + ",000";
document.getElementById("price").innerHTML = price;
document.getElementById("requests").innerHTML = requests;
return
}
if(mousePos.x > slider.offsetWidth - 20) {
return
}
sliderFill.style.width = mousePos.x + 10 + "px";
knob.style.left = mousePos.x + "px";
//Increase requests by using X position of mouse
incrementSpeed = mousePos.x / incrementModifier;
requests = minRequests + (mousePos.x * incrementSpeed);
//Round to nearest 1
requests = Math.round(requests / incrementValue) * incrementValue;
if (requests >= 1000){
var m = requests/ 1000;
m = Math.round(m / 1) * 1;
//Problem, lower the modifier depending on requests
incrementModifier = 20 * 0.95;
document.getElementById("requests").innerHTML = m + " million";
//Adjust Prices
if(( requests >= 1000) && (requests < 10000)) {
var numOfMillions = requests / 100;
//Round to closest 10.
//10 * number of millions
var rounded = Math.round(numOfMillions / 10) * 10;
price = minPrice + rounded;
highlightTable(3);
}
//Adjust Prices
if(requests >= 10000) {
var numOfMillions = requests / 1000;
var rounded = Math.round(numOfMillions / 1) * 1;
var basePrice = minPrice * 6;
price = basePrice + rounded;
highlightTable(4);
}
} else {
incrementModifier = 20;
document.getElementById("requests").innerHTML = requests + ",000"
if(requests < 100) {
highlightTable(1);
price = 0;
} else {
highlightTable(2);
price = 20;
}
}
previousRequestAmount = requests;
document.getElementById("price").innerHTML = price;
}
knob.addEventListener('mousedown', function() {
mouseDown = true;
});
document.addEventListener('mouseup', function() {
mouseDown = false;
});
function highlightTable(rowNum) {
var table = document.getElementById("payment-table")
for(var i = 0; i < table.rows.length; ++i) {
var row = table.rows[i]
if(i == rowNum) {
row.style.background = "grey"
} else {
row.style.background = "white";
}
}
}
Thank you for your time.
If you want it to be reusable you need to create a mathematical function that assigns a result to the number of requests. I will give you a very easy example.
If you want a different result for 1,10,100,100,10000 etc
var d = Math.log10(requests);
if(d<1){
doSomething();
}else if(d<2){
doSomethingElse();
} //etc
This way if you want to change the specific values that create certain results, all you need to do is change the function.
This only works if your tiers of requests follow a math function, if they don't you need to hard code it.
However if say they don't follow a math function, but you know how you would like them to change based on a value then you can do this.
var changingValue = 4;
if(requests < 400*changingValue){
doSomthing();
}else if(requests <= 400*changingValue*changingValue){
doSomethingElse();
}else{// the requests is greater than any of the above
doTheOtherThing();
}
Edit:
For the second one you need to make sure that each condition if always larger than the other from top to bottom.
The description "increasingly increasing" matches an arbitrary number of functions. I assume you also want it to be continuous, since you already have a non-continuous solution.
TL;DR
Use an exponential function.
Generic approach
Assuming imin and imax are the minimal and maximal values of the slider (i for input) and omin and omax are the minimal and maximal values to be displayed, the simplest thing I can think of would be a multiplication by something based on the input value:
f(x)
{
return omin + (omax - omin) * g((x - imin) / (imax - imin));
}
This will pass 0 to g if x == imin and 1 if x == imax.
The return value r of g(y) should be
r == 0 for y == 0
r == 1 for y == 1
0 < r < y for 0 < y < 1
The simplest function that I can think of that fulfills this is an exponential function with exponent > 1.
An exponent of 1 would be a linear function.
An exponent of 2 would be make the middle of the slider display one fourth of the maximum price instead of half of it.
But you really need to find that exponent yourself, based on your needs.

Detecting if two divs are too close or collide/overlap

I'm trying to detect if two given div's are too close or collide/overlap .
I have the below codepen which tries to generate 20 random div's and only append them to body if their position isn't too close to other existing div.
That's the idea but it doesn't work as expected where i get div's that get through with close/overlapping positions to existing divs. (run it multiple times if first time is perfect and you should come across it).
http://codepen.io/anon/pen/fHLzj
Can anyone see the mistake and way to make it work?
This is somewhat hard to explain and get..but here goes:
check every div against every div by running for loop.
x,y,h,w
x is top-left corner's distance from left.
y is top-left corner's distance from top.
h is div's height.
w is div's width.
Point to consider... you don't really need to check every div..consider this
there are 10 divs...
First you will check 1st against 9.
Second one against 8.
.............
Eight one against 2.
Ninth one against 1.
And don't the last one.
Also it's a good idea to assign values and check for collisions in data, before assigning them to dom. Dom should be just for rendering final result.
I'll assume you want to keep none of the two colliding divs.
Preview
http://jsfiddle.net/techsin/m4fSf/6/
as expected code is huge
var
div={},
number=10,
size=20,
m = ele('main');
mw= parseFloat(getComputedStyle(m).getPropertyValue("width"))-size,
mh= parseFloat(getComputedStyle(m).getPropertyValue("height"))-size,
f=true,
nn;
var i
for (i = 0; i < number; i++) {
div[i] = {};
var t = true, newX, newY, nn;
if (i!=0){
while (t) {
newX = rand(mw);
newY = rand(mh);
for (nn = 0; nn < i; nn++) {
if (!(((newX > div[nn].x + size+5) || (newY > div[nn].y + size+5)) ||
((newX + size+5 < div[nn].x) || (newY + size+5 < div[nn].y)))) {
break;
}
if (nn == i-1) t = false;
}}} else {
newX = rand(mw);
newY = rand(mh);
}
console.log(newX);
div[i].x = newX;
div[i].y = newY;
}
for (i = 0; i < number; i++) {
render(div[i]);
}
console.log(div);
function render(x){
var d=document.createElement('div');
d.style.position='absolute';
d.style.left=(x.x+'px');
d.style.top=(x.y+'px');
m.appendChild(d);
}
function rand(x) { return Math.random()*x;}
function ele(x){return document.getElementById(x);}
this code is from my collision site...ill try and put it in the code above, but this what's needed to avoid collisions and close gaps.
if (xpost+30>xx.left && xx.left>xpost && xx.top+30>ypost && xx.top<ypost+30) { xspeed = -speed; }
if (xpost<xx.left+30 && xx.left<xpost && xx.top+30>ypost && xx.top<ypost+30) { xspeed = speed; }
if (ypost+30>xx.top && xx.top>ypost && xx.left+30>xpost && xx.left<xpost+30) { yspeed = -speed; }
if (ypost<xx.top+30 && xx.top<ypost && xx.left+30>xpost && xx.left<xpost+30) { yspeed = speed; }
How about using one of these libraries to detect the collisions for you?
http://sourceforge.net/projects/jquerycollision/
http://gamequeryjs.com/
I changed the collision logic. It detects if an object is close to another object by comparing the distance between the objects. I wrapped the logic in a do-while loop as well, so that it will keep attempting to find a position to place the square and you'll have exactly 20 squares.
This works:
var positions = []; //stroe positions of appended divs
var divsize = 20;
var topGap = 40; // gap from top
var leftGap = 80; //gap from left
function generateRandomPositionedDiv(){
for(var c = 0; c < 20; c++){
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('<div/>').css({
'width':divsize+'px',
'height':divsize+'px',
'background-color': color
});
var posLeft;
var posTop;
var checkObj;
var collide = false;
posLeft = Math.floor((Math.random() * ($(document).width() - divsize)));//.toFixed();
posTop = Math.floor((Math.random() * ($(document).height() - divsize)));//.toFixed();
checkObj = {x: posLeft, y: posTop};
collide = checkForCollisions(checkObj);
if(!collide) {
positions.push({x: posLeft, y: posTop});
$newdiv.css({
'position':'absolute',
'left':posLeft+'px',
'top':posTop+'px'
});
$('body').append($newdiv);
}
}
}
/*function getPositions(box) {
var $box = $(box);
var pos = $box.position();
var width = $box.width();
var height = $box.height();
return [ [ pos.left, pos.left + width + leftGap ], [ pos.top, pos.top + height + topGap ] ];
}*/
function comparePositions(obj1, obj2) {
if(Math.abs(obj1.x - obj2.x) <= (divsize + leftGap) && Math.abs(obj1.y - obj2.y) <= (divsize + topGap)) {
return true;
} else {
return false;
}
}
function checkForCollisions(posObj){
for(var i = 0; i < positions.length; i++){
var match = comparePositions(positions[i], posObj);
if (match) {
//return true if two positions are close or overlapping
return match;
}
}
}
generateRandomPositionedDiv();

Javascript - Distance (in pixels) - Decision

I have a simple javascript animation, where two cowboys (iamges) 'race' each other based on a random interval number.
What I can't find out how to do is for the script to take a decision on who is the winner, meaning if a cowboy reaches a pre-defined distance first, the script will know and will show an alert on who won.
Here is a screen shot to show an example:
This is the code I have so far: http://pastebin.com/Cmt4N8c9
Can give me some directions?
Thanks,
Brian
In your move() function you should do something like
if (x >= dest_x) {
alert('player 1 won');
} else if (x2 >= dest_x2) {
alert('player 2 won');
} else {
... continue the loop ...
}
You'd most likely put that behind
document.getElementById("cowboy").style.top = y+'px';
document.getElementById("cowboy").style.left = x+'px';
document.getElementById("cowboytwo").style.top = y2+'px';
document.getElementById("cowboytwo").style.left = x2+'px';
You might want to check your code on duplicate variables too, by the way.
AFAIK dest_x and dest_x2 are both the same for example.
Simple move
/* Y is not relevant since you only move it on X axis */
var position1 = 100;
var position2 = 100;
var dest = 800; //Or any given value
function move() {
var step1 = Math.floor(1 + (10 * Math.random() ) );
var step2 = Math.floor(1 + (10 * Math.random() ) );
position1 += step1;
position2 += step2;
document.getElementById("cowboy").style.left = position1+'px';
document.getElementById("cowboytwo").style.left = position2+'px';
if(position1 < dest && position2 < dest) {
window.setTimeout('move()',100);
} else {
//We have the winner
if(position1 > dest) alert("Winner is Cowboy1");
if(position2 > dest) alert("Winner is Cowboy2");
//Its also possible that both of them pass target value at the same step
}
}

Categories

Resources