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();
Related
The first function getComputerChoice() returns a random - rock, paper, or scissor. However, in the playRound function when the computer' choice and user's choice are compared, it shows incorrect answers for a few of them. For example, when I choose rock and computer chooses paper, I win, which is wrong.
I tried using if else and switch statements but faced the same problem. It would be great if someone could help me out.
let computerSelection = getComputerChoice();
let playerSelection = prompt("rock, paper, or scissor?").toLowerCase();
function getComputerChoice(){
const randomNumber = Math.floor(Math.random()*3);
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissor";
} return choice;
}
function playRound(playerSelection, computerSelection){
let result = '';
if(computerSelection === playerSelection){
result = "It's a tie";
} else if(computerSelection === 'paper' && playerSelection === 'rock'){
result = "you lose";
} else if(computerSelection === 'scissor' && playerSelection === 'rock'){
result = "you win";
} else if ((computerSelection === 'rock') && (playerSelection === 'paper')){
result = "You win";
} else if((computerSelection === 'scissor') && (playerSelection === 'paper')){
result = "you lose";
} else if ((computerSelection === 'paper') && (playerSelection === 'scissor') ){
result = "You win";
} else if((computerSelection === 'rock') && (playerSelection === 'scissor')){
result = "You lose";
}
return result;
};
alert("The computer chose: " + getComputerChoice());
alert("That means " + playRound(playerSelection, computerSelection));
In your first statement, you choose the computer selection. But in your second to last statement, you call getComputerChoice() which makes a DIFFERENT selection. Change the next to the last line to
alert("The computer chose: " + computerSelection);
Try adding this debug line that I have put in, and then look at the console in the browser. You will see what the computer really chose
function getComputerChoice(){
const randomNumber = Math.floor(Math.random()*3);
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissor";
}
// debug line
console.log('randomly chose', choice);
return choice;
}
ChatGPT?
This code will run but it has a couple of problems:
In the getComputerChoice function, the variable choice is declared without const, let, or var. This means that it's a global variable and could cause issues in the future.
The line alert("The computer chose: " + getComputerChoice()); is calling the getComputerChoice function twice, but it should only be called once and stored in the computerSelection variable.
The result of the playRound function is not being logged to the console or displayed in any other way, it's only being returned.
To resolve these problems, you could modify the code as follows:
let computerSelection = getComputerChoice();
let playerSelection = prompt("rock, paper, or scissor?").toLowerCase();
function getComputerChoice(){
let choice = '';
const randomNumber = Math.floor(Math.random() * 3);
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissor";
}
return choice;
}
function playRound(playerSelection, computerSelection){
let result = '';
if(computerSelection === playerSelection){
result = "It's a tie";
} else if(computerSelection === 'paper' && playerSelection === 'rock'){
result = "you lose";
} else if(computerSelection === 'scissor' && playerSelection === 'rock'){
result = "you win";
} else if ((computerSelection === 'rock') && (playerSelection === 'paper')){
result = "You win";
} else if((computerSelection === 'scissor') && (playerSelection === 'paper')){
result = "you lose";
} else if ((computerSelection === 'paper') && (playerSelection === 'scissor') ){
result = "You win";
} else if((computerSelection === 'rock') && (playerSelection === 'scissor')){
result = "You lose";
}
return result;
};
console.log("The computer chose: " + computerSelection);
console.log("That means " + playRound(playerSelection, computerSelection));
Your Code is not consistent : here is the answer:
let computerSelection = getComputerChoice();
let playerSelection = prompt("rock, paper, or scissor?").toLowerCase();
function getComputerChoice(){
const randomNumber = Math.floor(Math.random() * 3);
let choice;
if(randomNumber === 0){
choice = "rock";
} else if(randomNumber === 1){
choice = "paper";
} else if(randomNumber === 2){
choice = "scissors";
}
return choice;
}
function playRound(playerSelection, computerSelection){
let result = '';
if(computerSelection === playerSelection){
result = "It's a tie";
} else if(computerSelection === 'paper' && playerSelection === 'rock'){
result = "You lose";
} else if(computerSelection === 'scissors' && playerSelection === 'rock'){
result = "You win";
} else if ((computerSelection === 'rock') && (playerSelection === 'paper')){
result = "You win";
} else if((computerSelection === 'scissors') && (playerSelection === 'paper')){
result = "You lose";
} else if ((computerSelection === 'paper') && (playerSelection === 'scissors') ){
result = "You lose";
} else if((computerSelection === 'rock') && (playerSelection === 'scissors')){
result = "You win";
}
return result;
};
let result = playRound(playerSelection, computerSelection);
alert("The computer chose: " + computerSelection);
alert("That means " + result);
Note:
scissor has been corrected to scissors.
Consistent use of capitalization for "You win" and "You lose".
The result ofplayRound() function has been stored in a variable
result before using it in the alert
.
const playerText = document.querySelector("#playerText");
const computerText = document.querySelector("#computerText");
const resultText = document.querySelector("#resultText");
const choiceBtns = document.querySelectorAll(".choiceBtn");
let player;
let computer;
let playerScore = 0;
let computerScore = 0;
let ifresult = "";
choiceBtns.forEach(button => button.addEventListener("click", () => {
player = button.textContent;
computerSelection();
playerText.textContent = "Player: " + player;
computerText.textContent = "Computer: " + computer;
resultText.textContent = "Result: " + result();
}));
function computerSelection(){
const randNum = Math.floor(Math.random() * 3) + 1;
switch(randNum){
case 1:
computer = "rock";
break;
case 2:
computer = "paper";
break;
case 3:
computer = "scissors";
break;
}
}
function result() {
if ((player === "paper" && computer === "rock") ||
(player === "scissors" && computer === "paper") ||
(player === "rock" && computer === "scissors")) {
playerScore += 1;
return ("You win! ");
}
if (playerScore == 2) {
return ("Winner winner chicken dinner! You won the game!");
}
else if (player == computer) {
return ("Draw!");
}
else {
computerScore += 1;
display ("you lose");
if (computerScore == 5) {
return ("You lost the game. ");
}
}
}
Everything in this function works except this final if statement in the else bracket.
if (computerScore == 5) {
return ("You lost the game. ");
I am getting the error,
"unreachable code detected ts(7027)".
If I delete the "return ("You lose!");" how would i display i lost the game? The second return "return ("You lost the game.");" returns that statement if i lose 5 times. Thanks for the help
In your final else statement, you're returning a value before the if condition is run.
return ("You lose!");
if (computerScore == 5) { // this code is unreachable
You need to remove this return.
} else {
computerScore += 1;
if (computerScore == 5) {
return ("You lost the game.");
}
}
Avoid such mistakes by adding a good extension into your VS Code. Image below demonstrates how my plugin detected the mistake. I am using Tabnine.
2. Be careful when returning values to close the if statement and then start new one.
3. There are some logic issues that makes this function a bit hard to read and unscalable.
4. Using your params I have cleaned and fixed it. I think your level of programming will fit into this solution. Since you are learning then it's OK to write longer code and with time your skill will come.
5. You can test this game, change the function values under the script.
// DEFINE VARIABLES
let player = undefined
let computer = undefined
let playerScore = 0
let computerScore = 0
let returnText = undefined
const theGame = (player, computer) => {
// PLAYER HAS PAPER
if (player === 'paper' && computer === 'rock') {
playerScore++
returnText = 'You win!'
checkScore(playerScore, computerScore)
return returnText
} else if (player === 'paper' && computer === 'paper') {
returnText = 'Draw!'
return returnText
} else if (player === 'paper' && computer === 'scissors') {
computerScore++
returnText = 'You lose!'
checkScore(playerScore, computerScore)
return returnText
}
// PLAYER HAS ROCK
if (player === 'rock' && computer === 'rock') {
returnText = 'Draw!'
return returnText
} else if (player === 'rock' && computer === 'paper') {
computerScore++
returnText = 'You lose!'
checkScore(playerScore, computerScore)
return returnText
} else if (player === 'rock' && computer === 'scissors') {
playerScore++
returnText = 'You win!'
checkScore(playerScore, computerScore)
return returnText
}
// PLAYER HAS SCISSORS
if (player === 'scissors' && computer === 'rock') {
computerScore++
returnText = 'You lose!'
checkScore(playerScore, computerScore)
return returnText
} else if (player === 'scissors' && computer === 'paper') {
playerScore++
returnText = 'You win!'
checkScore(playerScore, computerScore)
return returnText
} else if (player === 'scissors' && computer === 'scissors') {
returnText = 'Draw!'
return returnText
}
}
// CHECK SCRORE FUNCTION
const checkScore = (playerScore, computerScore) => {
let winningScore = 3
let result = undefined
if (playerScore === winningScore) {
result = 'Winner winner chicken dinner! You won the game!'
} else if (computerScore === winningScore) {
result = 'Winner winner chicken dinner! You won the game!'
} else {
// For testing
console.log('Player score: ', playerScore, 'Computer score: ', computerScore)
return playerScore, computerScore
}
// For testing
console.log(result)
return result
}
// TESTING
theGame('paper', 'rock')
Everything you put after a return statement will not be executed.
If the last else statement is reached, the function will return “You lose!” and its execution will stop.
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!");
}
}
How do i stop the function from executing if the userChoice is null or a word apart from rock,paper or scissors.
I've tried to use return but i couldn't get it to work.
Any help is appreciated.
Thanks
JS Fiddle Link = http://jsfiddle.net/Renay/d9bea2ra/1/
var userChoice = prompt('Do you choose 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 is a 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 an option');
} else if (userChoice !== 'rock'&&'paper'&&'scissors') {
console.log('Please select rock, paper or scissors');
}
}
console.log('Your choice = ' + userChoice);
console.log('Computer Choice = ' + compChoice);
compare();
The condition in your if statement is wrong. It should be:
if (userChoice !== 'rock' && userChoice !== 'paper' && userChoice !== 'scissors')
An expression of the form e1 && e2 && e3 && ... evaluates to last eN sub-expression if all of them truthy. So your test was equivalent to:
if (userChoice !== 'scissors')
You should put that check before displaying the result of the game, and return from the function then. So it should be:
function compare() {
if (userChoice === null) {
console.log('Please select an 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 is a tie!');
} else if ((userChoice == 'rock' && compChoice == 'scissors') || (userChoice == 'paper' && compChoice == 'rock') || (userChoice == 'scissors' && compChoice == 'paper') ) {
console.log( 'You win!');
} else {
console.log('You lose!');
}
}
Just do return;
function compare() {
if(!userChoice)
return;
// (...) more code
}
A return call exits the function. But note that you can only use return inside a function
If i understand correctly, you want to return to the beginning of the code. You should wrap the entire thing in a function, then call that function again:
function rockPaperScissors() {
var userChoice = prompt('Do you choose 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 is a 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 an option');
rockPaperScissors();
} else if (userChoice !== 'rock' && userChoice !== 'paper' && userChoice !== 'scissors') { // fixed
console.log('Please select rock, paper or scissors');
rockPaperScissors();
}
}
console.log('Your choice = ' + userChoice);
console.log('Computer Choice = ' + compChoice);
compare();
}
rockPaperScissors();
You also had an error with checking if it isn't one of rock, paper, or scissors, so i fixed that. (It seems Barmar got to it before me.)
I updated each if/else part of your function to exit when it match if/else condition with return false. In addition I changed the if (userChoice === null) check to if (userChoice === "") because it looks like that prompt('Do you choose rock, paper or scissors?'); returns an empty string when the user doesn't enter any value. Fiddle Also, I just updated the beginning of the function to work accordingly to **Barmar'**s suggestion (he got it right first time around).
function compare() {
if (userChoice === "") {
console.log('Please select an option');
return false;
} else if ((userChoice !== 'rock') && (userChoice !=='paper') && (userChoice !=='scissors')) {
console.log('Please select rock, paper or scissors');
return false;
}
if (userChoice == compChoice) {
console.log('The result is a tie!');
return false;
} else if ((userChoice == 'rock' && compChoice == 'scissors') || (userChoice == 'paper' && compChoice == 'rock') || (userChoice == 'scissors' && compChoice == 'paper')) {
console.log('You win!');
return false;
} else {
console.log('You lose!');
return false;
}
}
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.