Using text box info as variable in Javascript? - javascript

So, I'm making a rock,paper,scissors game using Javascript and I'm having some trouble starting. I need to have a text box and submit button, then the user input of "rock", "paper", "scissors" will be played against the computer's random choice. How would I have the computer take what's entered into the text field and run it against the computers choice? I'm a novice and in need of a nudge in the right direction, because I'm not sure how to start this problem.
Thanks
Edit:
So, a friend sent me some code and I added onto some of it and it looks like it would work(at least to me), but I'm not sure what to set the variable "player" equal to in order to equal the textbox information.
var player =
var choices = ["rock","paper","scissors"];
var computer = choices[Math.floor(Math.random()*3)];
var win = "Your "+player+" beats "+computer+". You win.";
var lose = "Your "+player+" loses to "+computer+". You lose.";
var draw = "A draw: "+player+" on "+computer+".";
if(player === "rock"){
if(computer === "scissors"){
result = win;
alert="win";
}
else if(computer === "paper"){
result = lose;
alert="lose";
}
else if(computer === "rock"){
result = draw;
alert="draw";
}
}
else if(player === "paper"){
if(computer === "rock"){
result = win;
alert="win";
}
else if(computer === "scissors"){
result = lose;
alert="lose";
}
else if(computer === "paper"){
result = draw;
alert="draw";
}
}
else if(player === "scissors"){
if(computer === "paper"){
result = win;
alert="win";
}
else if(computer === "rock"){
result = lose;
alert="lose";
}
else if(computer === "scissors"){
result = draw;
alert="draw";
}
}
</script>
</head>
<body>
<form>
<input type="text" id="rockTextInput" size="100" placeholder="Rock, Paper, or Scissors" >
<input type="button" id="Button" value="Play Hand">
</form>
</body>
</html>

The computer's choice could be generated like this:
...
var plays = ["rock", "paper", "scissors"];
var rand = Math.round(Math.random() * 2);
alert("Computer played: " + plays[rand]);
//Check to see the winner
...
Hope that helps give you a start.

Due to the limited number of possibilities, a way to do it is with a look-up table. You'd have to use further JavaScript to link it to your HTML. For that you'll probably want to use document.getElementById with an <input>'s value and output to some other Element.
/*
Usage:
play(player_choice)
player_choice String, 'rock', 'paper' or 'scissors'
returns Object with properties
player String, player's choice
ai String, ai's choice
result Integer, 0 - lose, 1 - draw, 2 - win
resultText String, description of result
*/
var play = (function () {
var options = ['rock', 'paper', 'scissors'],
result_table = {
'rock': {
'rock': 1,
'paper': 0,
'scissors': 2
},
'paper': {
'rock': 2,
'paper': 1,
'scissors': 0
},
'scissors': {
'rock': 0,
'paper': 2,
'scissors': 1
}
},
result_text = ['AI wins', 'Draw', 'Player wins'];
return function (player_choice) {
var ai_choice;
player_choice = player_choice.toLowerCase();
if (!result_table.hasOwnProperty(player_choice)) {
throw '[' + player_choice + '] not a valid choice.';
}
ai_choice = options[Math.floor(Math.random() * options.length)];
return {
'player': player_choice,
'ai': ai_choice,
'result': result_table[player_choice][ai_choice],
'resultText': result_text[result_table[player_choice][ai_choice]]
};
};
}());

Related

im a new learner and cant figure out why my code is not working

I have just recently got into coding and have chosen to learn JavaScript as my first language. I have written up code for a Rock, Paper, Scissors game but the wrong outputs come out when I run it? for example I would put my answer as scissors and the computer would choose rock and the game will come out as a tie.
const getUserChoice = userInput => {
if (userInput === 'rock' || userInput === 'paper' || userInput === 'scissors') {
return userInput
} else {
return 'Error!'
}
}
var getComputerChoice = () => {
const randomNumber = Math.floor(Math.random() * 3);
switch (randomNumber) {
case 0:
return 'rock'
break;
case 1:
return 'paper'
break;
case 2:
return 'scissors'
break;
}
};
const determineWinner = (userChoice, computerChoice) => {
if (userChoice === computerChoice) {
return 'its a tie!';
};
if (userChoice === 'rock') {
if (computerChoice === 'paper') {
return 'computer won';
} else {
return 'user won';
}
}
if (userChoice === 'paper') {
if (computerChoice === 'scissors') {
return 'computer won';
} else {
return 'user won'
}
}
if (userChoice === 'scissors') {
if (computerChoice === 'rock') {
return 'computer won';
} else {
return 'user won'
}
}
};
const playGame = () => {
console.log(`player chose ${getUserChoice('scissors')}`);
console.log(`computer chose ${getComputerChoice()}`);
console.log(determineWinner(getUserChoice("scissors"), getComputerChoice()));
}
playGame();
Maybe there are more issues, but here are some of them:
Each time you execute getComputerChoice you get a different value because a random value is picked inside:
console.log(`player chose ${getUserChoice('scissors')}`);
console.log(`computer chose ${getComputerChoice()}`);
console.log(determineWinner(getUserChoice("scissors"), getComputerChoice()));
So you must instead call and store in variables:
let playerChose = getUserChoice('scissors');
let computerChose = getComputerChoice();
let winner = determineWinner(playerChose, computerChose);
console.log(`player chose ${playerChose}`);
console.log(`computer chose ${computerChose}`);
console.log(winner);
You can do it without variables, but be sure not invoking getComputerChoice several times.
Also userInput should be between parenthesis at:
const getUserChoice = (userInput) => {
Every time you call getComputerChoice you'll get a different value, you could save the values in a variable with the const keyword.
const playGame = () => {
// It would be nice if you request this to the user, with prompt
const userChoice = getUserChoice('scissors');
// Save the random value
const computerChoice = getComputerChoice();
console.log(`player chose ${userChoice}`);
console.log(`computer chose ${computerChoice}`);
// This will work
console.log(determineWinner(userChoice, computerChoice));
}
playGame();
More on prompt here

Ties are still running win messages?

I've been messing around with a rock, paper scissors project that codecademy gets you to try, I'm pretty happy with it but I have one problem! When the result is a tie, it logs the tie message (perfect!) but also logs the win message linked with the result!
How do I get it to ONLY log the tie message?
Here's the code:
const getUserChoice = userInput => {
userInput = userInput.toLowerCase();
if (userInput === "rock" || userInput === "paper" || userInput === "scissors" || userInput === "gun") {
return userInput;
} else {
console.log(`Sorry! But ${userInput} is an illegal weapon in the bloodythirsty sport of Rock, Paper, Scissors!`)
}
}
const getComputerChoice = () => {
const ranNum = Math.floor(Math.random() * 3);
switch (ranNum) {
case 0:
return "rock";
case 1:
return "paper";
case 2:
return "scissors";
}
};
const determineWinner = (getUserChoice, getComputerChoice) => {
if (getComputerChoice === getUserChoice) {
console.log("It seems it's a tie! You've matched wits!");
}
if (getUserChoice === "rock") {
if (getComputerChoice === "paper") {
return "The computer wins! It has gift wrapped your weapon.";
} else {
return "You beat the computer! They immediately begin crafting bigger scissors.";
}
}
if (getUserChoice === "paper") {
if (getComputerChoice === "scissors") {
return "The computer wins! They claim arts and crafts time as a reward."
} else {
return "You beat the computer! Their puny stone was no match for your paper aeroplane to the eye!"
}
}
if (getUserChoice === "scissors") {
if (getComputerChoice === "rock") {
return "The computer wins! You won't be cutting straight lines any time soon..."
} else {
return "You beat the computer! You cause emotional damage by destroying their robot child's drawing. You're a monster."
}
}
if (getUserChoice === "gun") {
if (getComputerChoice === "rock" || getComputerChoice === "paper" || getComputerChoice === "scissors") {
return "You win. But at what cost?"
}
}
if (getUserChoice === undefined) {
return "Come back when you're ready to take this game seriously."
}
}
//Enter your choice below in getUserChoice brackets
const playGame = () => {
let userChoice = getUserChoice("rock");
let computerChoice = getComputerChoice();
if (userChoice !== undefined) {
console.log(`You have chosen ${userChoice} as your weapon.`);
}
if (userChoice !== undefined) {
console.log(`The computer has brought ${computerChoice} to a ${userChoice} fight.`);
}
console.log(determineWinner(userChoice, computerChoice))
}
playGame();
Instead of logging the tie message, you should return it, leaving the logging to the caller:
if (getComputerChoice === getUserChoice) {
return "It seems it's a tie! You've matched wits!";
}

How to fix undefined variable in javascript

For some reason my function is not returning a 1 or 2 even though it's specifically setup to do so. What am I doing wrong? I'm looking at the chrome dev tools and it's telling me that var processed is undefined.
I'm quite stumped on this. I've been reading if it's because a variable could be used as a parameter but I'm not sure if this is the case
var processChoices = function (player, computer){
switch (player) {
case player == 'rock':
if (computer == 'paper'){
var winner = 2;
} else if (computer == 'scissors'){
var winner = 1;
}
break;
case player == 'paper':
if (computer == 'scissors'){
var winner = 2;
} else if (computer == 'rock'){
var winner = 1;
}
break;
case player == 'scissors':
if (computer == 'rock'){
var winner = 2;
} else if (computer == 'paper'){
var winner = 1;
}
break;
default:
if (computer == player){
var winner = console.log('We have a tie, go again!');
}
break;
}
return winner
}
var determineWinner = function (){
var computer = computerPlay();
var player = playerChoice();
var processed = processChoices(player, computer);
if (processed == 1){
playerCount += 1;
} else {
computerCount += 1;
}
var message = (processed == 2) ? `The computer wins! ${computer} beats ${player}!` : `The player wins! ${player} beats ${computer}!`;
console.log(message);
}
I'm expecting the output of var processed to be 1 or 2. It's coming back as undefined.
It looks like you're not using the switch statement correctly. Your case statements need to just be the value that you want to match. See below.
It's would also be good to declare the variable winner once.
var processChoices = function(player, computer) {
var winner = 0;
switch (player) {
case 'rock':
if (computer == 'paper') {
winner = 2;
} else if (computer == 'scissors') {
winner = 1;
}
break;
case 'paper':
if (computer == 'scissors') {
winner = 2;
} else if (computer == 'rock') {
winner = 1;
}
break;
case 'scissors':
if (computer == 'rock') {
winner = 2;
} else if (computer == 'paper') {
winner = 1;
}
break;
default:
if (computer == player) {
console.log('We have a tie, go again!');
}
break;
}
return winner
}
var computer = "rock";
var player = "paper";
console.log("Player chose:", player, "Computer chose:", computer);
console.log("The winner is...", processChoices(player, computer));
First off the switch format is wrong.
switch (player) {
case player == 'rock': // wrong
case 'rock': // correct
Second you need to check all states of computer or else check at the end
var processChoices = function (player, computer){
let winner = 0;
switch (player) {
case 'rock':
if (computer === 'paper'){
winner = 2;
} else if (computer === 'scissors'){
winner = 1;
}
break;
case 'paper':
if (computer === 'scissors'){
winner = 2;
} else if (computer === 'rock'){
winner = 1;
}
break;
case 'scissors':
if (computer === 'rock'){
winner = 2;
} else if (computer === 'paper'){
winner = 1;
}
break;
}
if (winner === 0) {
console.log('We have a tie, go again!');
}
return winner
}
ps:
use const and let. Don't use `var'
use === not ==
Also the entire thing can be a lot smaller
const winnerTable = {
rock: {
rock: 0,
paper: 2,
scissors: 1,
},
paper: {
rock: 1,
paper: 0,
scissors: 2,
},
scissors: {
rock: 2,
paper: 1,
scissors: 0,
},
};
var processChoices = function (player, computer){
return winnerTable[player][computer];
};
well I guess it's in var determineWinner u called
var processed = processChoices(player, computer);
and processChoices is a var not a function with parameters
=>delete (player, computer);

Use of logical and comparison operators in conditions (javascript)

I want the user to input his answer in a rock-paper-scissors game in the following line of code.
userChoice = prompt("Do you choose rock, paper or scissors?");
However, in case the user writes something other than exactly "rock", "paper" or "scissors", he is supposed to choose again, which I tried to do with this piece of code:
while (userChoice !== "rock" || "paper" || "scissors") {
userChoice = prompt("Invalid choice. Please change your answer.");
};
The problem I have is that the program keeps recognizing the given input as invalid, even if it is "rock", "paper" or "scissors".
While typing this, I managed to find a solution on my own.
while (userChoice !== "rock" && userChoice !== "paper" && userChoice !== "scissors") {
userChoice = prompt("Invalid choice. Please change your answer.");
};
That way does make sense and the first condition probably didn't work because even if you type a correct answer (e.g. "paper"), it still doesn't equal the other two answers (in this case "rock" and "scissors"), which is why the program kept saying the answer has been invalid, right? Or is it a syntax error?
Now (with the working condition), the choice of the user has to be neither "rock" nor "paper" nor "scissors" and thus it works properly.
Also, is there possibly an easier and shorter way of writing that condition?
Note: I hope it's fine that parts of the solution are already included as they could help other coders.
Two examples
One with an array and Array.prototype.indexOf():
var userChoice;
while (!~['rock', 'paper', 'scissors'].indexOf(userChoice)) {
userChoice = prompt("Invalid choice. Please change your answer.");
};
And another with an object and the in operator:
The in operator returns true if the specified property is in the specified object.
var userChoice;
while (!(userChoice in {rock: 1, paper: 1, scissors: 1})) {
userChoice = prompt("Invalid choice. Please change your answer.");
};
Use indexOf
while (["rock", "paper", "scissors"].indexOf(userChoice) > -1) {
Your first attempt
while (userChoice !== "rock" || "paper" || "scissors") {
is technically an infinite loop because
|| "paper"
for example, technically evaluates to true or a truthy value
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Rock Papper Scissors Game</title>
</head>
<body>
<h1>Play Rock Papper Scissors?</h1>
<button id="start">Play?</button>
<script>
function rpsGame() {
var computerChoice = Math.random(),
userChoice = prompt('Do you choose rock, paper, or scissors');
function getComputerChoice() {
if (computerChoice <= 0.33) {
computerChoice = 'rock';
} else if (computerChoice <= 0.66 && computerChoice >= 0.33) {
computerChoice = 'paper';
} else {
computerChoice = 'scissors';
}
}
function playAgain() {
var restart = prompt('Would you like to play again, yes or no?').toLowerCase();
switch(restart) {
case 'yes':
rpsGame();
break;
default:
alert('Okay, see you later!');
}
}
function compare() {
var choice1 = userChoice.toLowerCase(),
choice2 = computerChoice,
tie = "The computer chose " + choice2 + ", and you chose " + choice1 + ". The result is a tie!",
win = "The computer chose " + choice2 + ", and you chose " + choice1 + ". You win!",
lose = "The computer chose " + choice2 + ", and you chose " + choice1 + ". The computer wins!";
switch (choice1) {
case "":
alert("You didn't enter anything. Maybe we can play later!");
break;
case 'rock':
if (choice2 === 'scissors') {
alert(win);
} else if (choice2 === 'rock') {
alert(tie);
} else {
alert(lose);
}
playAgain();
break;
case 'paper':
if (choice2 === 'rock') {
alert(win);
} else if (choice2 === 'paper') {
alert(tie);
} else {
alert(lose);
}
playAgain();
break;
case 'scissors':
if (choice2 === 'paper') {
alert(win);
} else if (choice2 === 'scissors') {
alert(tie);
} else {
alert(lose);
}
playAgain();
break;
default:
alert(choice1.substring(0,1).toUpperCase() + choice1.substring(1, choice1.length).toLowerCase() + " is an invalid choice. Please change your answer.");
rpsGame();
}
}
getComputerChoice();
compare();
}
document.getElementById('start').addEventListener('click', rpsGame);
</script>
</body>
</html>

Sending a string/result from JS to HTML-page

I'm working on a simple rock, paper, scissors game of HTML + JS.
Here are the full codes (CSS, JS, HTML): http://jsfiddle.net/fJw4R/
(too long to past here I thought). Here you can see it with pictures: http://shinebrightmedia.se/rps/rockpaperscissors.html
As you can see, the .math-module works, and when you choose rock, paper or scissor the computer randomizes a choice.
However, I now would like to have a textstring underneath the computer/monitor, and I'm wondering what the easiest way to do that. I want it to either say YOU WIN! or YOU LOSE!
I started on a function looking like this:
function theWinnerIs(userChoice, computerChoice) {
if (userChoice === computerChoice ) {
return 'No winner, it is a draw';
}
if ((userChoice === 'rock') && (computerChoice === 'scissor')) {
return 'human';
}
if ((userChoice === 'rock') && (computerChoice === 'paper')) {
return 'computer';
}
if ((userChoice === 'paper') && (computerChoice === 'scissor')) {
return 'computer';
}
if ((userChoice === 'paper') && (computerChoice === 'rock')) {
return 'human';
}
if ((userChoice === 'scissor') && (computerChoice === 'rock')) {
return 'computer';
}
if ((userChoice === 'scissor') && (computerChoice === 'paper')) {
return 'human';
}
}
What is the easiest way to send the return to the index-file? ie. YOU WIN! or YOU LOSE!
Thanks for any help.
No need to use this block of ifs - here's very compact alternative:
var choices = { rock: -1, paper: 0, scissors: 1 };
var score = choices[userChoice] - choices[computerChoice];
score = score - (score/2|0) * 3;
... which will give you -1 if user loses the round, 1 if they win, 0 in case of draw.
Now you can just send the output to any prepared container by filling its innerHTML property:
var results = {
'-1': 'YOU LOSE',
'1': 'YOU WIN',
'0': 'IT\'S A DRAW'
};
var resultContainer = document.getElementById('result');
resultContainer.innerHTML = results[score];
Here's a small demo to illustrate both those concepts.
From what I understand, you would like to display some text depending on the outcome of your "theWinnerIs" method. I would suggest you create a div on your page and set its content with JavaScript. There are numerous ways to accomplish your goal, however.
So you want to add a div to your page, something like <div id="output"></div>. You can then update the text here with the following
var outputElement = document.getElementById("output");
outputElement.innerHTML = theWinnerIs(userChoice, computerChoice);
Here's an updated version of your code for perspective, though raina77ow's solution is much nicer.

Categories

Resources