I have an assignment for my web design class & we were given a basic code that we need to modify to do more. As soon as I add an if, else if statement, the javascript stops working. I can't figure out where I'm going wrong. If someone could steer me in the right direction, I'd really appreciate it.
Here's the original code (with notes one what we need to do):
<!DOCTYPE html>
<!-- Finish the logic of the Rock Paper Scissors game below.
See the comments for instructions. -->
<html>
<head>
<title>RPS</title>
<script>
function rps() {
userChoice = prompt("Rock, paper or scissors?");
userPick.innerHTML = userChoice;
computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice < 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
computerPick.innerHTML = computerChoice;
result = compare(userChoice, computerChoice);
if (result == 1) {
// set the outcome entity to say that "Player Wins!"
// also increment the user's score.
} else if (result == -1) {
// set the outcome entity to say that "Computer Wins!"
// also increment the computer's score.
} else {
// set the outcome entity to say "Tie"
}
}
function compare(choice1, choice2) {
// return 0 if choices are equal,
// 1 if choice1 wins,
// -1 if choice2 wins
}
</script>
</head>
<body>
<h2>RockPaperScissors</h2>
<p id="outcome">-</p> <b> computer picks: </b>
<p id="computerPick">-</p> <b> player picks: </b>
<p id="userPick">-</p>
<!-- create p blocks to store the computer's score (number of wins)
and the user's score. These will have to be modified by the rps function
-->
<button type="button" onclick="rps()">Go</button>
</body>
</html>
This is how I changed the function compare method:
function compare(choice1, choice2) {
// return 0 if choices are equal,
// 1 if choice1 wins,
// -1 if choice2 wins
if (choice1 == "paper" && choice2 == "rock" ||
choice1 == "rock" && choice2 == "scissors" ||
choice1 == "scissors" && choice2 == "paper") {
return == 1;
}
else if (choice1 == "paper" && choice2 == "scissors" ||
choice1 == "rock" && choice2 == "paper" ||
choice1 == "scissors" && choice2 == "rock") {
return == -1;
}
else {
return == 0;
}
}
Remove the == from your returns. They should just be like...
return 1;
== is used for comparison.
Change your compare function to
function compare(choice1, choice2) {
// return 0 if choices are equal,
// 1 if choice1 wins,
// -1 if choice2 wins
if (choice1=="paper" && choice2=="rock"||choice1=="rock"
&& choice2=="scissors"||choice1=="scissors" && choice2=="paper"){
return 1;}
else if (choice1=="paper" &&
choice2=="scissors"||choice1=="rock" && choice2=="paper"||choice1=="scissors" &&
choice2=="rock"){
return -1;}
else {
return 0;}
}
return 1
not
return == 1
Return is a keyword not a variable. = is the assignment operator, which puts the value on the right side of the operator into the variable on the left side. And == is the equality operator.
Related
I'm making a rock paper scissors games where the counter should add 1 if user wins, add 0.5 if it's a tie, and remains the same if user lost. But in the alert and what's shown in the console doesn't match. Sometimes its shown in the alert that I win and in the console its shown I lose or its a tie. And the counter doesn't add up correctly.
In the image above it's shown 3 wins, 1 tie, and 1 lose. It should show I've won 3.5 games but it shows 5.5. And there is only 5 games played so it should be impossible to win 5.5.
Here is the code:
let winCounter = 0;
// playRound function will play a game of rock, paper, scissors and returns the result
function playRound(playerSelection, computerSelection) {
let getPlayerInsensitive = playerSelection.toLowerCase();
if (getPlayerInsensitive === "rock" && computerSelection === "Rock") {
winCounter+=0.5;
return "It's a tie, both are Rock";
} else if (getPlayerInsensitive === "rock" && computerSelection === "Paper") {
winCounter = winCounter;
return "You Lose! Paper beats Rock";
} else if (getPlayerInsensitive === "rock" && computerSelection === "Scissors") {
winCounter+=1;
return "You win! Rock beats Scissors";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Rock") {
winCounter+=1;
return "You win! Paper beats Rock";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Paper") {
winCounter+=0.5;
return "It's a tie! Both are Paper";
} else if (getPlayerInsensitive === "paper" && computerSelection === "Scissors") {
winCounter = winCounter;
return "You lose! Scissors beats Paper";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Rock") {
winCounter = winCounter;
return "You lose! Rock beats Scissors";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Scissors") {
winCounter=0.5;
return "It's a tie! Both are Scissors";
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Paper") {
winCounter+=1;
return "You win! Scissors beat Paper";
} else {
return "Check your spelling!";
}
}
// game function returns the winner after five rounds
function game() {
for (let i = 0; i < 5; i++) {
let getSelect = prompt("Choose Rock, Paper, or Scissors", "");
if (getSelect === null || getSelect === "") {
alert("You clicked Cancel!");
}
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
//outputs the winner of 5 games
if (i === 4) {
alert("You've played 5 games");
if (winCounter >= 3) {
alert(`You've won ${winCounter} out of 5 games. You win!`);
return `You've won ${winCounter} out of 5 games. You win!`;
} else if (winCounter === 2.5) {
alert(`You've won 2.5 out of 5 games. It's a tie!`);
return `You've won 2.5 out of 5 games. It's a tie!`;
} else if (winCounter < 2.5) {
alert(`You've won ${winCounter} out of 5 games. You lost!`);
return `You've won ${winCounter} out of 5 games. You lost!`;
}
}
}
}
console.log(game());
And here is the fiddle: https://jsfiddle.net/JaredDev/o62hr7as/125/
Why does it show different results in alert and console.log
It's because you called the computerPlay function twice, thus could returns different selection each time it is called,
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
you could change it to this, so it is called only once
const result = playRound(getSelect, computerPlay())
alert(result);
if (i < 5) {
console.log(result)
}
also why the score could be more than it should have, its because playRound function also called twice each turn
Caling code with random behaviour and side-effects twice
This piece of code produces an unintended result because the function computerPlay has random behaviour and the function playRound has has side-effects (modifies the winCounter).
alert(playRound(getSelect, computerPlay()));
if (i < 5) {
console.log(playRound(getSelect, computerPlay()));
}
You could correct this part of the problem by calling the function only once and assigning its result to a variable:
const result = playRound(getSelect, computerPlay());
alert(result);
if (i < 5) {
console.log(result);
}
Typo
You also have a typo:
} else if (getPlayerInsensitive === "scissors" && computerSelection === "Scissors") {
winCounter=0.5;
return "It's a tie! Both are Scissors";
This should say += not just =:
winCounter+=0.5;
i'm learning javascript and currently making a rock, paper, scissor game using only javascript. the game will have 1 round mode and 3 rounds mode but as i finished to code the 1 round mode i found out having problem display result, whoever win the game it display "the game is tie" and can't find where s the mistake, can anybody help me?
// Player choice
var getPlayerChoice = function() {
var playerChoice = prompt("Choose rock, paper, or scissors");
while (playerChoice !== 'rock' && playerChoice !== 'paper' && playerChoice !== 'scissors') {
if (playerChoice === null) {
break;
}
playerChoice = prompt("Invalid ! you have to choose rock, paper, or scissors");
}
return playerChoice;
}
// Computer Choice
var getComputerChoice = function () {
var randomNum = Math.random();
if ( randomNum < 0.3333 ) {
return "rock";
} else if ( randomNum > 0.3333 && randomNum < 0.6666 ) {
return "scissors";
} else {
return "paper";
}
}
// Winner Function
var getWinner = function (playerChoice, computerChoice) {
if (computerChoice === playerChoice) {
return "The Game is Tie";
} else if (computerChoice === "paper") {
if (playerChoice === "scissors") {
return "player win";
} else if (playerChoice === "rock") {
return "computer win";
}
} else if (computerChoice === "rock") {
if (playerChoice === "scissors") {
return "computer win";
} else if (playerChoice === "paper") {
return "player win";
}
} else if (computerChoice === "scissors") {
if (playerChoice === "rock") {
return "player win";
} else if (playerChoice === "paper") {
return "computer win";
}
}
}
// Single game mode
var singleRound = function() {
var playerChoice = getPlayerChoice();
if (playerChoice === null) {
return;
}
var computerChoice = getComputerChoice();
var winner = getWinner(playerChoice, computerChoice);
var message = " You chose: " + playerChoice + "\n Computer chose: " + computerChoice;
if (winner === "player") {
alert(message + "\nYou won!");
} else if (winner === "computer") {
alert(message + "\nYou lost!");
} else {
alert(message + "\nThe Game is Tie");
}
return winner;
}
var mode = prompt("Welcome!\n \nplease insert 1 for single round mode\n2 for 3 rounds mode");
if (mode === '1') {
singleRound();
} else if (mode === '2') {
threeRoundsMode();
}
Your getWinner() function returns player win or computer win, but your code that calls it is looking for return values of player or computer.
Because the code never gets what it's looking for it defaults to `'The Game is Tie'
This is happening because of a mistake in the singleRound() function. if (winner === "player") { should be if (winner === "player win") { and similarly the if (winner === "computer") { should say if (winner === "computer win") { so that the text being compared matches. Right now, it is comparing "player" and "player win", then "computer" and "computer win" so then the else clause is reached regardless of actual game outcome.
Not printing the winner in Rock,Paper,Scissor game. For some reason I cannot get my function DeclareWinner to return any of the strings I have created.
After I did a short test where I put a string outside of my if/else statements I managed to get a print. It seems that my returns are stuck in the local scope and does therefore not get printed.
var weapon = "rock"
function Userchoice(weapon){
if (weapon === "rock" || weapon === "paper" || weapon === "scissor") {
return weapon
}
else {
return "Invalid Choice";
}
}
function Computerchoice(){
var Number = Math.floor(Math.random() * 3);
if (Number === 0) {
return "rock";
}
else if (Number === 1) {
return "paper";
}
else if (Number === 2) {
return "scissor";
}
}
function DeclareWinner(Userchoice, Computerchoice){
if (Userchoice === Computerchoice){
return "Tiebreak";
}
else if (Userchoice === "rock" && Computerchoice === "scissor"){
return "User wins";
}
else if (Userchoice === "rock" && Computerchoice === "paper"){
return "Computer wins";
}
else if (Userchoice === "paper" && Computerchoice === "rock"){
return "User wins";
}
else if (Userchoice === "paper" && Computerchoice === "scissor"){
return "Computer wins";
}
else if (Userchoice === "scissor" && Computerchoice === "rock"){
return "Computer wins";
}
else if (Userchoice === "scissor" && Computerchoice === "paper"){
return "User wins";
}
}
console.log(Userchoice(weapon));
console.log(Computerchoice());
console.log(DeclareWinner(Userchoice, Computerchoice));
The expectation of console.log(DeclareWinner(Userchoice, Computerchoice)); is to print who is the winner.
(ps. I know there are several other rock paper scissor games who are more technical, I just wanted to try and create my own without specific guidance)
Thanks in advance.
You are not passing the correct arguments to your function. Userchoice and Computerchoice are both references to the corresponding functions and do not represent the (string) results of your previous function calls as you might expect.
You can easily verify this by adding a console.log(Userchoice), which prints:
function Userchoice(weapon){if(weapon==="rock"||weapon==="paper"||weapon==="scissor"){return weapon;}else{return"Invalid Choice";}}
You want to store the results of the function calls before printing and pass them to DeclareWinner.
Relevant part:
// Your unchanged code
// ...
let userchoice = Userchoice(weapon);
let computerchoice = Computerchoice();
console.log(userchoice);
console.log(computerchoice);
console.log(DeclareWinner(userchoice, computerchoice));
As a side note: Variable and method names usually start with a lower case letter.
So I am trying to create this Rock, Paper, Scissors program to run on a telnet server. Except It's not allowing me to enter the words "Rock","Paper", or "Scissors".
First CPUhand is showing up as undefined and is not setting to one of the options in my if statements.
Second whenever I enter a single character in the command prompt, It gives me my "Invalid, try again!" else statement and skips to the next line.
Is anyone able to figure out why my if statements for CPUhand are not working or why I can't enter more than a single character in command prompt?
Screenshot1 Screenshot2
"use strict";
const
net = require('net'),
server = net.createServer(function(connection) { //create server
let randomNum = randomNumber(1, 3);
let CPUhand
if(randomNum == 1){
CPUhand == "Rock";
} else if(randomNum == 2){
CPUhand == "Paper";
} else if(randomNum == 3){
CPUhand == "Scissors";
}
connection.write("Enter: Rock, Paper, or Scissors!\r\n");
connection.on('data', function(chunk) { //collect data from user
let USERhand = chunk.toString();
if(CPUhand === "Rock" && USERhand === "Scissors" || USERhand === "Rock" && CPUhand === "Scissors"){
connection.write("Rock beats Scissors!\r\n");
}
else if(CPUhand === "Paper" && USERhand === "Rock" || USERhand === "Paper" && CPUhand === "Rock"){
connection.write("Paper beats Rock!\r\n");
}
else if(CPUhand === "Scissors" && USERhand === "Paper" || USERhand === "Scissors" && CPUhand === "Paper"){
connection.write("Scissors beats Paper!\r\n");
}
else if(CPUhand === USERhand){
connection.write("Draw!\r\n");
}
else{
connection.write("Invalid! Try Again! \r\n");
}
});
}); server.listen(5432); //bind port
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
1) Typo in block:
if(randomNum == 1){
CPUhand == "Rock";
} else ...
Should be:
if(randomNum == 1){
CPUhand = "Rock";
} else ...
2) In user input you have also line break symbol:
let USERhand = chunk.toString();
Replace with:
let USERhand = chunk.toString().trim();
I've been practicing a game with JavaScript, and was wondering how to prevent the console from printing when a user makes an ill defined choice?
Here is the code:
var user = prompt("Do you choose rock, paper or scissors?");
var computer = Math.random();
if (computer < 0.34) {
computer = "rock";
}
else if (computer <= 0.67) {
computer = "paper";
}
else {
computer = "scissors";
}
console.log("Computer Chooses: " + computer);
console.log("User Chooses: " + user);
var compare = function (computer, user) {
if (computer === "rock") {
if (user === "scissors") {
return "Computer wins by choosing rock!";
}
}
else if (computer === "scissors") {
if (user === "paper") {
return "Computer wins by choosing scissors!";
}
}
else if (computer === "paper") {
if (user === "rock") {
return "Computer wins by choosing paper!"
}
}
if (computer === user) {
return ("It is a tie!")
}
else if (user === "paper") {
if (computer === "rock") {
return ("You win by choosing paper!")
}
}
else if (user === "rock") {
if (computer === "scissors") {
return ("You win by choosing scissors!")
}
}
else if (user === "scissors") {
if (computer === "paper") {
return ("You win by choosing scissors!")
}
}
***if (user !== "rock" && user !== "paper" && user !== "scissors") {
confirm(user + " is an invalid entry.");
}***
};
compare(computer, user);
At the end I snipped the bit of code that gives the user an indication that he has put in the wrong characters. What I am wondering is:
How do I keep anything from displaying to the console once someone has put in the wrong input?
One option would be to keep asking the user for a valid input until a valid input is given:
while (user != "rock" && user != "paper" && user != "scissors") {
user = prompt("Do you choose rock, paper or scissors?")
if (user == null) {
break;
}
};
if (user != null) {
...
}
http://jsfiddle.net/2w3pt5yy/3/
make the validation of user input at the beginning . if user passes only show the code else show error.
var user = prompt("Do you choose rock, paper or scissors?");
if(user !== "rock" && user !== "paper" && user!== "scissors") {
confirm(user + " is an invalid entry.");
} else {
// code for process
}
You can add this code on top of your js code
var console = {};
console.log = function(){};
You have more if statements than is necessary; you can simplify the logic.
var getComputerMove = function () {
// equivalent of Math.floor
// aka it grabs the integer component of `Math.random() * 3`
// either 0, 1, or 2
return (Math.random() * 3) | 0;
}
var playRockPaperScissors = function () {
var moves = [ "rock", "paper", "scissors" ]
, user = ""
, computer = getComputerMove();
// while `user` is not in the `moves` array
// `Array.indexOf` returns -1 if an element is not in the array
// prompt the user for his move
while (moves.indexOf(user.toLowerCase()) == -1) {
user = prompt("Rock, paper, or scissors?");
}
// this is where you can save yourself all that typing and think out
// the possible movesets:
// item: rock < paper < scissors < rock
// index: 0 < 1 < 2 < 0
// so, the computer wins if its choice is greater than the user's,
// or if the computer chose "rock" and the user chose scissors
// we can translate this to
// user < computer || (computer == 0 && user == 2)
var userIndex = moves.indexOf(user.toLowerCase());
// uncomment, if you want to see the moves
// console.log("user:", user, "computer:", moves[computer]);
if (userIndex < computer || (userIndex == 2 && computer == 0) {
alert("Computer wins!");
} else {
alert("User wins!");
}
}