0

I have a rock paper sciccors game so ill put the js code below

var r = 0;
var p = 0;
var s = 0;
var num = 0;

function random() {
  var num = Math.floor(Math.random() * 3);
  console.log(`${num}`);
}

function rockcho() {
  let r = 1;
  let p = 0;
  let s = 0;

};

function papercho() {
  let p = 1;
  let r = 0;
  let s = 0;
};

function scissorscho() {
  let s = 1;
  let p = 0;
  let r = 0;
}

function play() {
  if (r = 0, p = 0, s = 0) {
    nothing();
  };
  //this is for rock//
  if (r = 1) {
    if (num = 2) {
      win();
      let rock = 0;
    };
    if (num = 1) {
      lose();
    }
    if (num = 0) {
      draw();
    }
  }
}

function win() {
  alert("you win! :) click to play again");
};

function lose() {
  alert("you lost :( click to play again");
};

function draw() {
  alert("it was a draw! click to play again");
};

function nothing() {
  alert("please click a button to play.")
};

the win alert and the lose alert are going off at the same time. someone please help.

I tried rewriting the code and it didnt work, I cant figure out how to fix the alert bug its going off whenever i press a button when its not supposed to.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • where in your code are you calling all those functions? `random, rockcho, papercho, scissorscho, play`? – Chris G Apr 27 '23 at 16:26
  • The code only seems to *define* functions, it never *invokes* any of them. Can you update this to an example which demonstrates the problem? – David Apr 27 '23 at 16:26
  • Additionally... This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? – David Apr 27 '23 at 16:27
  • 1
    `let rock = 0;` does nothing useful. The variable is local to that `if` block, and you never access it after the assignment. – Barmar Apr 27 '23 at 16:29
  • 1
    `if (r = 1)` you need to use `==` for comparison, `=` is assignment. All your `if` statements make this mistake. – Barmar Apr 27 '23 at 16:30
  • `if (num = 2) {` you are not asking if num ==2, you are giving num a new value here – Chris G Apr 27 '23 at 16:30
  • `if (r = 0, p = 0, s = 0)` this is not how you test multiple conditions, you have to connect them with `&&` or `||`. It should be `if (r == 0 && p == 0 && s == 0)` – Barmar Apr 27 '23 at 16:30
  • The `=` instead of `==` problem is why you're getting multiple alerts. When you assign instead of comparing, both of them succeed. – Barmar Apr 27 '23 at 16:32

1 Answers1

0

i fix your wrong code look at mine._.

 function play() {
if (r == 0 && p == 0 && s == 0) {
  nothing();
}

//this is for rock//
if (r == 1) {
  if (num == 2) {
    win();
    let rock = 0;
  }

  if (num == 1) {
    lose();
  }
  if (num == 0) {
    draw();
  }
 }
}
paliz
  • 347
  • 2
  • 5