Monday 15 August 2011

Exiting out of a function in Javascript. Simple rock, paper, scissors game -



Exiting out of a function in Javascript. Simple rock, paper, scissors game -

how stop function executing if userchoice null or word apart rock,paper or scissors. i've tried utilize homecoming couldn't work. help appreciated. thanks

js fiddle link = http://jsfiddle.net/renay/d9bea2ra/1/

var userchoice = prompt('do take rock, paper or scissors?'); var compchoice = math.random(); if (compchoice <= 0.34) { compchoice = 'rock'; } else if (compchoice <= 0.67) { compchoice = 'paper'; } else { compchoice = 'scissors'; } function compare() { if (userchoice == compchoice) { console.log( 'the result tie!'); } else if ((userchoice == 'rock' && compchoice == 'scissors') || (userchoice == 'paper' && compchoice == 'rock') || (userchoice == 'scissors' && compchoice == 'paper') ) { console.log( 'you win!'); } else { console.log('you lose!'); } if (userchoice === null) { console.log('please select option'); } else if (userchoice !== 'rock'&&'paper'&&'scissors') { console.log('please select rock, paper or scissors'); } } console.log('your selection = ' + userchoice); console.log('computer selection = ' + compchoice); compare();

the status in if statement wrong. should be:

if (userchoice !== 'rock' && userchoice !== 'paper' && userchoice !== 'scissors')

an look of form e1 && e2 && e3 && ... evaluates lastly en sub-expression if of them truthy. test equivalent to:

if (userchoice !== 'scissors')

you should set check before displaying result of game, , homecoming function then. should be:

function compare() { if (userchoice === null) { console.log('please select option'); return; } else if (userchoice !== 'rock' && userchoice !== 'paper' && userchoice !== 'scissors') { console.log('please select rock, paper or scissors'); return; } if (userchoice == compchoice) { console.log( 'the result tie!'); } else if ((userchoice == 'rock' && compchoice == 'scissors') || (userchoice == 'paper' && compchoice == 'rock') || (userchoice == 'scissors' && compchoice == 'paper') ) { console.log( 'you win!'); } else { console.log('you lose!'); } }

javascript

No comments:

Post a Comment