Domanda

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:

enter image description here

This is the code I have so far: http://pastebin.com/Cmt4N8c9

Can give me some directions?

Thanks, Brian

È stato utile?

Soluzione

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.

Altri suggerimenti

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
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top