Adding user/computer score to a Tweet - javascript

Problem: When a user clicks the twitter icon, it brings up a tweet box, but doesn't add the values of the USER_SCORE/COMPUTER_SCORE variables. Right now I have only been testing the USER_SCORE alone.
I figured I could create a text node with the value in it, and append it to the box, however that isn't working, and am unsure on what else would really work.
Desired Result: I want to add the values of the USER_SCORE/COMPUTER_SCORES to the tweet box, when the twitter button is clicked.
JSBIN: http://jsbin.com/gabenafula/edit?html,js,output
JavaScript:
window.onload = function() {
//vars scope may change in the future.
var CHOICE_ROCK = document.querySelector('#rock'),
CHOICE_PAPER = document.querySelector('#paper'),
CHOICE_SCISSORS = document.querySelector('#scissors'),
WINNER_TXT = document.querySelector('#winner'),
BUTTONS = document.querySelectorAll('input'),
COMP_IMG = document.querySelector('#compChoice'),
USER_SCORE_EL = document.querySelector('#user-score'),
COMP_SCORE_EL = document.querySelector('#computer-score'),
PLAYER_CHOICE = document.querySelector('#player-choice'),
TWEET = document.querySelector('#tweet'),
USER_SCORE = 0,
COMPUTER_SCORE = 0,
GAME_SCORE = { USER_SCORE: 0, COMPUTER_SCORE: 0}, // add pt to each per win, stringify to local Storage
key = 'scores';
CHOICE_ROCK.addEventListener('click', USER_CHOICE, false);
CHOICE_PAPER.addEventListener('click', USER_CHOICE, false);
CHOICE_SCISSORS.addEventListener('click', USER_CHOICE, false);
//tweet your score
TWEET.addEventListener('click', function() {
var scoreValue = document.createTextNode(USER_SCORE.value);
window.open('https://twitter.com/intent/tweet?text=').appendChild(scoreValue);
}, false );
// Return user choice value;
function USER_CHOICE(e) {
var compChoice = COMPUTER_CHOICE();
var el = e.target;
if (el === CHOICE_ROCK) {
console.log('USER CHOICE: ROCK');
console.log('COMPS CHOICE: ' + compChoice);
console.log(USER_SCORE);
console.log(COMPUTER_SCORE);
ROCK('rock', compChoice);
PLAYER_CHOICE_STYLE('ROCK!');
USER_SCORE_EL.innerHTML = 'Your Score : ' + USER_SCORE;
COMP_SCORE_EL.innerHTML = 'Computer Score : ' + COMPUTER_SCORE;
} else if (el === CHOICE_PAPER) {
console.log('USER CHOICE: PAPER');
console.log('COMPS CHOICE: ' + compChoice);
console.log(USER_SCORE);
console.log(COMPUTER_SCORE);
PAPER('paper', compChoice);
PLAYER_CHOICE_STYLE('PAPER!');
USER_SCORE_EL.innerHTML = 'Your Score : ' + USER_SCORE;
COMP_SCORE_EL.innerHTML = 'Computer Score : ' + COMPUTER_SCORE;
} else if (el === CHOICE_SCISSORS) {
console.log('USER CHOICE: SCISSORS');
console.log('COMPS CHOICE: ' + compChoice);
console.log(USER_SCORE);
console.log(COMPUTER_SCORE);
SCISSORS('scissors', compChoice);
PLAYER_CHOICE_STYLE('SCISSORS!');
USER_SCORE_EL.innerHTML = 'Your Score : ' + USER_SCORE;
COMP_SCORE_EL.innerHTML = 'Computer Score : ' + COMPUTER_SCORE;
}
e.stopPropagation();
}
// Return value of computer choice
function COMPUTER_CHOICE() {
var num = Math.floor(Math.random() * 3) + 1;
console.log('COMP CHOICE number: ' + num);
if (num === 1) {
COMP_IMG.setAttribute('src', 'http://i.imgur.com/OHt2rjH.png');
COMP_IMG.style.border = '1px solid black';
return 'rock';
} else if (num === 2) {
COMP_IMG.setAttribute('src', 'http://i.imgur.com/H86s3q4.png');
COMP_IMG.style.border = '1px solid black';
return 'paper';
} else if (num === 3) {
COMP_IMG.setAttribute('src', 'http://i.imgur.com/rAkxkWc.png');
COMP_IMG.style.border = '1px solid black';
return 'scissors';
}
}
// Break up into functions
// compare values of user choice and computer chocie
function ROCK(USER_CHOICE, COMPUTER_CHOICE) {
if (USER_CHOICE === CHOICE_ROCK.id && COMPUTER_CHOICE === 'scissors') {
//user wins
USER_SCORE ++;
WINNER_TXT.style.color = 'green';
WINNER_TXT.innerHTML = 'YOU WIN!';
} else if (USER_CHOICE === CHOICE_ROCK.id && COMPUTER_CHOICE === 'paper') {
//comp wins
COMPUTER_SCORE ++;
WINNER_TXT.style.color = 'red';
WINNER_TXT.innerHTML = 'COMPUTER WINS!';
} else if (USER_CHOICE === CHOICE_ROCK.id && COMPUTER_CHOICE === 'rock') {
WINNER_TXT.style.color = 'blue';
WINNER_TXT.innerHTML = 'ITS A TIE!!!!!';
}
}
function PAPER(USER_CHOICE, COMPUTER_CHOICE) {
//Paper
if (USER_CHOICE === CHOICE_PAPER.id && COMPUTER_CHOICE === 'rock') {
//user wins
USER_SCORE ++;
WINNER_TXT.style.color = 'green';
WINNER_TXT.innerHTML = 'YOU WIN!';
} else if (USER_CHOICE === CHOICE_PAPER.id && COMPUTER_CHOICE === 'scissors') {
//comp wins
COMPUTER_SCORE ++;
WINNER_TXT.style.color = 'red';
WINNER_TXT.innerHTML = 'COMPUTER WINS!';
} else if (USER_CHOICE === CHOICE_PAPER.id && COMPUTER_CHOICE === 'paper') {
WINNER_TXT.style.color = 'blue';
WINNER_TXT.innerHTML = 'ITS A TIE!!!!!';
}
}
function SCISSORS(USER_CHOICE, COMPUTER_CHOICE) {
//scissors
if (USER_CHOICE === CHOICE_SCISSORS.id && COMPUTER_CHOICE === 'paper') {
//user wins
USER_SCORE ++;
WINNER_TXT.style.color = 'green';
WINNER_TXT.innerHTML = 'YOU WIN!';
} else if (USER_CHOICE === CHOICE_SCISSORS.id && COMPUTER_CHOICE === 'rock') {
//comp wins
COMPUTER_SCORE ++;
WINNER_TXT.style.color = 'red';
WINNER_TXT.innerHTML = 'COMPUTER WINS!';
} else if (USER_CHOICE === CHOICE_SCISSORS.id && COMPUTER_CHOICE === 'scissors') {
WINNER_TXT.style.color = 'blue';
WINNER_TXT.innerHTML = 'ITS A TIE!!!!!';
}
}
function PLAYER_CHOICE_STYLE(choice) {
PLAYER_CHOICE.innerHTML = 'You chose: ' + choice;
PLAYER_CHOICE.style.fontWeight = 'bold';
PLAYER_CHOICE.style.backgroundColor = '#555';
PLAYER_CHOICE.style.color = 'white';
PLAYER_CHOICE.style.borderBottom = '3px solid #444';
PLAYER_CHOICE.style.borderRadius = '30px';
PLAYER_CHOICE.style.padding ='10px';
}
// Add Local Storage
// function RENDER_SCORES() {
//
// }
//
// //Store scores
// function STORE_SCORE(LOCAL_STORAGE, key) {
// var score = JSON.stringify(LOCAL_STORAGE);
// LOCAL_STORAGE.setItem(key, score);
// }
//fetch scores
// function fetch(key, callback) {
// var LOCAL_STORAGE = JSON.pase(LOCAL_STORAGE.getItem(key));
// callback(LOCAL_STORAGE);
// }
//
// function render(data) {
// if (data !== null && data.hasOwnProperty('forEach')) {
// data.forEach(function(current){
// RENDER_SCORES(current);
// });
// }
// }
};
HTML:
<div class="container">
<div class="header"><h1>ROCK, PAPER, OR SCISSORS!</h1></div>
<div><span id="winner"></span></div>
<div>Computer's choice:</div>
<div><img id="compChoice" src="" alt="computers choice"></div>
<div id="player-choice"></div>
<div class="inner-container">
<div class="row">
<div class='items'>
<img class="rps" id="rock-img" src="https://cdn0.iconfinder.com/data/icons/rock-paper-scissors-emoji/792/rock-paper-scissors-emoji-cartoon-027-128.png" width="200" height="300">
<div><input type="submit" value="Rock" id="rock"></div>
</div>
<div class='items'>
<img class="rps" src="https://cdn0.iconfinder.com/data/icons/rock-paper-scissors-emoji/792/rock-paper-scissors-emoji-cartoon-019-256.png" width="200" height="300">
<div><input type="submit" value="Paper" id="paper"></div>
</div>
<div class='items'>
<img class="rps" src="https://cdn0.iconfinder.com/data/icons/rock-paper-scissors-emoji/792/rock-paper-scissors-emoji-cartoon-014-512.png" width="200" height="300">
<div><input type="submit" value="Scissors" id="scissors"></div>
</div>
</div>
</div>
<div id="scoreboard">
<div><h2 id='user-score'>Your Score:</h2></div>
<div><h2 id='computer-score'>Computer Score:</h2></div>
<img src="https://cdn4.iconfinder.com/data/icons/social-media-icons-the-circle-set/48/twitter_circle-128.png" id="tweet">
</div>
<div class="footer">
<span>© Zack 2016</span>
</div>
</div>

Change the tweet your score section to the following:
//tweet your score
TWEET.addEventListener('click', function() {
var message = "Your score was " + USER_SCORE + ". The computers score was " + COMPUTER_SCORE;
window.open('https://twitter.com/intent/tweet?text=' + message);
}, false );

Related

why is my rock,paper game not running correctly

I'm learning front end and this project for a rock paper game is killing me, I'm not getting any errors and the logic seems correct to me but I'm not getting any output. I think my buttons are wrong and maybe I'm but I honestly have no clue id really appreciate it if somebody could help me out I have been stuck on this for hours.
<script>
const score=document.querySelector("score");
const buttons=document.querySelectorAll("buttons");
const computer=document.querySelector("computer");
const player=document.querySelector("player");
const rock=document.getElementById("rock");
const paper=document.getElementById("paper");
const scisscors=document.getElementById("scisscors");
function computerplayer(){
let computer=Math.floor(Math.random() * 3);
let random=['rock',"paper",'sisscors']
if(computer>3){
return 'rock'
}
if(computer<2){
return 'paper'
}
else{
return 'sisscors'
}
}
function game(choice,computer){
if(choice=='rock'&& computer=='sisscors'){
pscore++
score();
console.log( 'u win');
}
if(choice== 'rock'&& computer==="rock"){
console.log("it be a tie")
}
if(choice=="rock"&& computer=="paper"){
cscore++
score();
console.log("u lose");
}
if(choice== 'sisscors'&& computer=='rock'){
console.log( "u lost")
cscore++
score();
}
if(choice=='sisscors'&& computer=='paper'){
console.log('you win')
pscore++
score();
}
if(choice=='paper'&& computer=='rock'){
console.log("you win")
pscore++
score();
}
if(choice=='paper'&& computer=='sisscors'){
console.log("lost")
cscore++
score();
}
}
function score(){
if(pscore==3){
console.log("end game win")
}
if(cscore==3){
console.log("end game loser")
}
}
buttons.addEventListener('click', function(){
game('rock')
})
buttons.addEventListener('click', function(){
game('paper')
})
buttons.addEventListener('click', function(){
game('sisscors')
})
</script>
Thanks
First of all this code won't return 3 or greater number
let computer = Math.floor(Math.random() * 3);
then computerplayer() will only return 'paper' and 'sisscors' and you should change computerplayer() function.
Next you should change your buttons event listennr to these:
rock.addEventListener('click', function () {
game('rock', computerplayer())
})
paper.addEventListener('click', function () {
game('paper', computerplayer())
})
rock.addEventListener('click', function () {
game('sisscors', computerplayer())
})
Since you have to change many more things, then I mentioned a complete code here:
<script>
window.addEventListener('load', () => {
let pscore = 0;
let cscore = 0;
const result = document.querySelector(".result");
const player = document.querySelector(".pscore");
const computer = document.querySelector(".cscore");
const rock = document.getElementById("rock");
const paper = document.getElementById("paper");
const scissors = document.getElementById("scissors");
rock.addEventListener('click', function () {
game('rock', computerplayer())
})
paper.addEventListener('click', function () {
game('paper', computerplayer())
})
scissors.addEventListener('click', function () {
game('scissors', computerplayer())
})
function computerplayer() {
let random = Math.floor(Math.random() * 3);
if (random == 0)
return 'rock'
else if (random == 1)
return 'paper'
else if (random == 2)
return 'scissors'
}
function game(choice, computerAction) {
if (choice == 'rock' && computerAction == 'scissors') {
pscore++
score();
console.log('u win');
} else if (choice == 'rock' && computerAction === "rock") {
console.log("it be a tie")
} else if (choice == "rock" && computerAction == "paper") {
cscore++
score();
console.log("u lose");
} else if (choice == 'scissors' && computerAction == 'rock') {
console.log("u lost")
cscore++
score();
} else if (choice == 'scissors' && computerAction == 'paper') {
console.log('you win')
pscore++
score();
} else if (choice == 'scissors' && computerAction === "scissors") {
console.log("it be a tie")
} else if (choice == 'paper' && computerAction == 'rock') {
console.log("you win")
pscore++
score();
} else if (choice == 'paper' && computerAction == 'scissors') {
console.log("lost")
cscore++
score();
} else if (choice == 'paper' && computerAction === "paper") {
console.log("it be a tie")
}
function score() {
console.log(pscore, cscore)
player.innerHTML = pscore;
computer.innerHTML = cscore;
if (pscore == 3) {
console.log("end game win")
result.innerHTML = 'You won.';
} else if (cscore == 3) {
console.log("end game loser")
result.innerHTML = 'Computer won.';
}
if (pscore == 3 || cscore == 3) {
rock.style.display = 'none';
paper.style.display = 'none';
scissors.style.display = 'none';
}
}
}
});
</script>
<body>
Computer:<span class="cscore"></span>
<br />
Player: <span class="pscore"></span><br />
<br />
<input type="button" id="rock" value="Rock" />
<input type="button" id="paper" value="Paper" />
<input type="button" id="scissors" value="scissors" />
<span class="result"></span>
</body>

JS Game Results Not What I Expect

I'm fairly new to JS and I'm currently trying to make my first simple game. The premise is that the player must choose and submit a bet. They then chose one of three cups and win if the ball is in the chosen cup.
It's mostly functioning as I hoped to except the outcome for how much money they gain.
The player starts with $40 and when its a loss it correctly subtracts the bet amount. When the player wins however it does not add the bet amount but instead puts it beside the previous amount.
For example, if the player has $40 and bets $5 and wins it will change their total to $405.
I have noticed that this does not happen for the first bet if the player wins but then does not work again on subsequent guesses.
I can not figure what is causing this behavior and any help would be greatly appreciated.
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Hobo Balls</title>
<link rel="stylesheet" href="hobo.css">
</head>
<body>
<div class="header">
<h1>Hobo Balls</h1>
<h2>Instructions</h2>
</div>
<div class="cups">
<div id="cup1-image">
<img src="/Cup1.png">
</div>
<div id="cup2-image">
<img src="/Cup2.png">
</div>
<div id="cup3-image">
<img src="/Cup3.png">
</div>
</div>
<br>
<div>
<label for="bet">Place Your Bet</label>
<input name="bet" id="bet" type="number" min="1" max="400" value="0"/>
<input id="enter-bet" type="submit"/>
<p id="show-bet"></p>
</div>
<div class="result">
<h3>You are a ???</h3>
<p id="win-or-lose"></p>
</div>
<p id="cash"></p>
<script type="text/javascript" src="/hoboscript.js"></script>
</body>
</html>
JS
let cup1;
let cup2;
let cup3;
let playerGuess;
let playerBet;
let playerCash = 40;
let outcome;
//Player enters bet amount
document.getElementById("enter-bet").addEventListener("click", function () {
playerBet = document.getElementById("bet").value;
document.getElementById("show-bet").innerHTML = "You bet $" + playerBet;
});
//Determine ball position
const ballPlacement = () => {
const ballResult = Math.floor(Math.random() * 3);
console.log(ballResult);
if (ballResult === 0) {
cup1 = 'ball';
cup2 = 'crab';
cup3 = 'hobo';
} else if (ballResult === 1) {
cup1 = 'crab';
cup2 = 'ball';
cup3 = 'hobo';
} else { (ballResult === 2); {
cup1 = 'hobo';
cup2 = 'crab';
cup3 = 'ball';
}
}
};
//Determine if guess iscorrect and display result
const playerWin = () => {
//correct Guess
if (playerGuess === 'cup1' && cup1 === 'ball') {
outcome = 'win'; document.querySelector("h3").innerHTML = "You are a Winner"; document.getElementById('cup1-image').innerHTML = '<img src="/ball.jpg">';
} else if (playerGuess === 'cup2' && cup2 === 'ball') {
outcome = 'win'; document.querySelector("h3").innerHTML = "You are a Winner"; document.getElementById('cup2-image').innerHTML = '<img src="/ball.jpg">';
} else if (playerGuess === 'cup3' && cup3 === 'ball') {
outcome = 'win'; document.querySelector("h3").innerHTML = "You are a Winner"; document.getElementById('cup3-image').innerHTML = '<img src="/ball.jpg">';
//incorrect guess
} else if (playerGuess === 'cup1' && cup1 === 'crab') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup1-image').innerHTML = '<img src="/crab.jpg">';
} else if (playerGuess === 'cup1' && cup1 === 'hobo') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup1-image').innerHTML = '<img src="/hobo.jpg">';
} else if (playerGuess === 'cup2' && cup2 === 'crab') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup2-image').innerHTML = '<img src="/crab.jpg">';
} else if (playerGuess === 'cup2' && cup2 === 'hobo') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup2-image').innerHTML = '<img src="/hobo.jpg">';
} else if (playerGuess === 'cup3' && cup3 === 'crab') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup3-image').innerHTML = '<img src="/crab.jpg">';
} else if (playerGuess === 'cup3' && cup3 === 'hobo') {
outcome = 'lose'; document.querySelector("h3").innerHTML = "You are a Loser"; document.getElementById('cup3-image').innerHTML = '<img src="/hobo.jpg">';
}
};
//Player selects cup, previous functions are called
document.getElementById("cup1-image").addEventListener("click", function () {
playerGuess = 'cup1';
ballPlacement();
playerWin();
if (outcome === 'win') {
playerCash = playerCash + playerBet;
} else if (outcome === 'lose') {
playerCash = playerCash - playerBet;
}
document.getElementById('win-or-lose').innerHTML = outcome;
document.getElementById("cash").innerHTML = "You have $" + playerCash + " remaining";
});
document.getElementById("cup2-image").addEventListener("click", function () {
playerGuess = 'cup2';
ballPlacement();
playerWin();
if (outcome === 'win') {
playerCash = playerCash + playerBet;
} else if (outcome === 'lose') {
playerCash = playerCash - playerBet;
}
document.getElementById('win-or-lose').innerHTML = outcome;
document.getElementById("cash").innerHTML = "You have $" + playerCash + " remaining";
});
document.getElementById("cup3-image").addEventListener("click", function () {
playerGuess = 'cup3';
ballPlacement();
playerWin();
if (outcome === 'win') {
playerCash = playerCash + playerBet;
} else if (outcome === 'lose') {
playerCash = playerCash - playerBet;
}
document.getElementById('win-or-lose').innerHTML = outcome;
document.getElementById("cash").innerHTML = "You have $" + playerCash + " remaining";
});
Here in your code:
document.getElementById("enter-bet").addEventListener("click", function () {
playerBet = document.getElementById("bet").value;
document.getElementById("show-bet").innerHTML = "You bet $" + playerBet;
});
The variable playerBet is being assigned a string value, change the statement to:
playerBet = parseInt(document.getElementById("bet").value;
Use valueAsNumber instead of value for number inputs:
//Player enters bet amount
document.getElementById("enter-bet").addEventListener("click", function () {
playerBet = document.getElementById("bet").valueAsNumber;
document.getElementById("show-bet").innerHTML = "You bet $" + playerBet;
})

Rock paper scissors Javascript

I'm trying to build an RPS game with Javascript, using a click event as input.
I can get the program to see Watson's input and clock the number of games I've lost, but I can't get the program to recognize my input.
What steps have I missed out? Please check out the following link for all the code including HTML.
https://codepen.io/szewah/pen/daMKbK
var rockPaperScissors = ['Rock', 'Paper', 'Scissors'];
//gueses
var computerGuess = rockPaperScissors[Math.floor(Math.random()*rockPaperScissors.length)];
var myGuess = function (input) {
if (input === 'Rock' || input === 'Paper' || input === "Scissors") {
return input;
} else {
console.log('That\'s not a valid choice. Try again.');
};
};
// results
var wins =0;
var losses = 0;
var ties = 0;
//returns information to the DOM
var userChoiceText = document.getElementById('userchoice-text');
var computerChoiceText = document.getElementById('userchoice-text');
var winsText = document.getElementById('wins-text');
var lossesText = document.getElementById('losses-text');
var tiesText = document.getElementById('ties-text');
//adds event listener
document.getElementById('rock-btn').addEventListener('click', runGame);
document.getElementById('paper-btn').addEventListener('click', runGame);
document.getElementById('scissors-btn').addEventListener('click', runGame);
//function to run after event listener is triggered
function runGame () {
if ((myGuess === 'Rock' && computerGuess === 'Scissors') ||
(myGuess === 'Scissors' && computerGuess === 'Paper') ||
(myGuess === 'Paper' && computerGuess === 'Rock')) {
wins++;
console.log('I win!')
} else if (myGuess === computerGuess) {
ties++;
console.log('It\'s a tie!')
} else {
losses++;
console.log('Watson won!')
}
userChoiceText.textContent = 'You chose ' + myGuess + '.';
computerChoiceText.textContent = 'Watson chose ' + computerGuess + '.';
winsText.textContent = 'Wins: ' + wins + '.';
tiesText.textContent = 'Ties: ' + ties + '.';
lossesText.textContent = 'Losses: ' + losses + '.';
};
// array for choices of rock, paper, scissors
var rockPaperScissors = ['Rock', 'Paper', 'Scissors'];
function myGuessFn(input) {
if (input === 'Rock' || input === 'Paper' || input === 'Scissors') {
return input;
} else {
console.log('That\'s not a valid choice. Try again.');
};
};
// results
var wins = 0;
var losses = 0;
var ties = 0;
//returns information to the DOM
var userChoiceText = document.getElementById('userchoice-text');
var computerChoiceText = document.getElementById('computerchoice-text');
var winsText = document.getElementById('wins-text');
var lossesText = document.getElementById('losses-text');
var tiesText = document.getElementById('ties-text');
//adds event listener
document.getElementById('rock-btn').addEventListener('click', runGame);
document.getElementById('paper-btn').addEventListener('click', runGame);
document.getElementById('scissors-btn').addEventListener('click', runGame);
//function to run after event listener is triggered
function runGame(event) {
var myGuess = myGuessFn(event.target.innerHTML);
var computerGuess = rockPaperScissors[Math.floor(Math.random() * rockPaperScissors.length)];
if ((myGuess === 'Rock' && computerGuess === 'Scissors') ||
(myGuess === 'Scissors' && computerGuess === 'Paper') ||
(myGuess === 'Paper' && computerGuess === 'Rock')) {
wins++;
console.log('I win!')
} else if (myGuess === computerGuess) {
ties++;
console.log('It\'s a tie!')
} else {
losses++;
console.log('Watson won!')
}
userChoiceText.textContent = 'You chose ' + myGuess + '.';
computerChoiceText.textContent = 'Watson chose ' + computerGuess + '.';
winsText.textContent = 'Wins: ' + wins + '.';
tiesText.textContent = 'Ties: ' + ties + '.';
lossesText.textContent = 'Losses: ' + losses + '.';
};
#rock-btn,
#paper-btn,
#scissors-btn {
cursor: pointer;
}
<div class="container">
<h1>Press Rock Paper Scissors to play</h1>
<div class="choices">
<div id="rock-btn">Rock</div>
<div id="paper-btn">Paper</div>
<div id="scissors-btn">Scissors</div>
</div>
<hr>
<div class="resultChoice">
<p id="userchoice-text"></p>
<br>
<p id="computerchoice-text"></p>
</div>
<hr>
<div class="results">
<p id="wins-text"></p>
<p id="losses-text"></p>
<p id="ties-text"></p>
</div>
</div>

JSLint keeps telling me that my functions are out of scope. It isn't making any sense

1=rock
2=paper
3=scissor
When I am using JSLint to check my code for errors, it is throwing a whole bunch of messages at me saying that some of my functions are out of scope. I have already spent 2 hours fiddling with the code trying to get it to work, but to no avail. Maybe someone can take a look at it with fresh eyes. Thanks.
var computerchoice = 0;
var humanchoice = 0;
var computerscore = 0;
var humanscore = 0;
var roundnumber = 0;
var tiescore = 0;
var winner;
var loser;
function SwitchToGameScreen() {
document.getElementById("startscreen").style.display = "none";
document.getElementById("gamescreen").style.display = "block";
}
function resetgame() {
document.getElementById("humanrock").style.border = "none";
document.getElementById("humanpaper").style.border = "none";
document.getElementById("humanscissor").style.border = "none";
document.getElementById("computerrock").style.border = "none";
document.getElementById("computerpaper").style.border = "none";
document.getElementById("computerscissor").style.border = "none";
}
function human_chooses_rock() {
humanchoice = 1;
document.getElementById("rock").style.border = "thick solid #0000FF";
document.getElementById("humanchoice").innerHTML = "Rock";
EvaluateRound;
}
function human_chooses_paper() {
humanchoice = 2;
document.getElementById("paper").style.border = "thick solid #0000FF";
document.getElementById("humanchoice").innerHTML = "Paper";
EvaluateRound;
}
function human_chooses_scissor() {
humanchoice = 3;
document.getElementById("scissor").style.border = "thick solid #0000FF";
document.getElementById("humanchoice").innerHTML = "Scissor";
EvaluateRound;
}
function EvaluateRound() {
roundnumber = roundnumber + 1;
computerchoice = Math.floor(Math.random() * 6) + 1;
if (humanchoice === 1 && computerchoice === 1) {
tiescore = tiescore + 1;
winner = "nobody";
UpdateStats();
}
if (humanchoice === 1 && computerchoice === 2) {
computerscore = computerscore + 1;
winner = "Computer";
UpdateStats();
}
if (humanchoice === 1 && computerchoice === 2) {
humanscore = humanscore + 1;
winner = "Human";
UpdateStats();
}
if (humanchoice === 2 && computerchoice === 1) {
humanscore = humanscore + 1;
winner = "Human";
UpdateStats();
}
if (humanchoice === 2 && computerchoice === 2) {
tiescore = tiescore + 1;
winner = "nobody";
UpdateStats();
}
if (humanchoice === 2 && computerchoice === 3) {
computerscore = computerscore + 1;
winner = "Computer";
UpdateStats();
}
if (humanchoice === 3 && computerchoice === 1) {
computerscore = computerscore + 1;
winner = "Computer";
UpdateStats();
}
if (humanchoice === 3 && computerchoice === 2) {
humanscore = humanscore + 1;
winner = "Human";
UpdateStats();
}
if (humanchoice === 3 && computerchoice === 3) {
tiescore = tiescore + 1;
winner = "nobody";
UpdateStats();
}
if (roundnumber === 10) {
document.getElementById("gamescreen").style.display = "none";
document.getElementById("finishscreen").style.display = "block";
UpdateStats();
}
if (computerchoice === 1) {
document.getElementById("computerrock").style.border = "thick solid #0000FF";
}
if (computerchoice === 2) {
document.getElementById("computerpaper").style.border = "thick solid #0000FF";
}
if (computerchoice === 3) {
document.getElementById("computerscissor").style.border = "thick solid #0000FF";
}
}
function UpdateStats() {
document.getElementById("humanscore").innerHTML = humanscore;
document.getElementById("computerscore").innerHTML = computerscore;
document.getElementById("tiescore").innerHTML = tiescore;
document.getElementById("roundnumber").innerHTML = roundnumber;
document.getElementById("computerchoice").innerHTML = computerchoice;
document.getElementById("winner").innerHTML = winner;
} document.getElementById("hidestartscreenshowgamescreen").addEventListener("click", SwitchToGameScreen);
document.getElementById("rock").addEventListener("click",human_chooses_rock);
document.getElementById("paper").addEventListener("click",human_chooses_paper);
document.getElementById("scissor").addEventListener("click",human_chooses_scissor);
document.getElementById("rock").addEventListener("click", resetgame);
document.getElementById("paper").addEventListener("click", resetgame);
document.getElementById("scissor").addEventListener("click", resetgame);

showing variable value in <p> paragraph using getElementById.innerHTML in Javascript

I'm trying to write a Blackjack code using Javascript, and showing the result in an HTML page. I have written the logic already, but I can't get to show the results in paragraph by ID, using getElementById.innerHTML. I don't know how to make it right. Could you please help me with this? I'm running out of time :(. here's the code:
<!DOCTYPE html>
<html>
<title>Welcome to Blackjack</title>
<!--<link href="style.css" rel="stylesheet" type="text/css">
<!-- <script src="bj.js"></script> -->
<head>
<script>
var PlayerScore = 0;
var DealerScore = 0;
var Winner = "Nobody";
var AskAgain = true;
function random(maxValue)
{
return Math.floor(Math.random() * maxValue) + 1;
}
function pickSuit()
{
suit = random(4);
if(suit == 1)
return "Spades";
if(suit == 2)
return "Clubs";
if(suit == 3)
return "Diamonds";
return "Hearts";
}
function cardName(card)
{
if(card == 1)
return "Ace";
if(card == 11)
return "Jack";
if(card == 12)
return "Queen";
if(card == 13)
return "King";
return ("" + card);
}
function cardValue(card)
{
if(card == 1)
return 11;
if(card > 10)
return 10;
return card;
}
function PickACard(strWho)
{
card = random(13);
suit = pickSuit();
alert(strWho + " picked the " + cardName(card) + " of " + suit);
return cardValue(card);
}
function Dealer()
{
while(DealerScore < 17)
{
DealerScore = DealerScore + PickACard("Dealer");
}
}
function User()
{
PlayerScore = PlayerScore + PickACard("You");
}
function LookAtHands(Winner)
{
if(DealerScore > 21)
{
alert("House busts! You win!");
Winner = "You";
}
else
if((PlayerScore > DealerScore) && (PlayerScore <= 21))
{
alert("You win!");
Winner = "You";
}
else
if(PlayerScore == DealerScore)
{
alert("Push!");
Winner = "Tie";
}
else
{
alert("House wins!");
Winner = "House";
}
}
Dealer();
alert("Dealer's score is: " + DealerScore);
document.getElementById('DealerScore').innerHTML = DealerScore;
User();
alert("Your score is: " + PlayerScore);
document.getElementById("DealerScore").innerHTML = "Dealer's score is: " + DealerScore;
while (AskAgain == true )
{
var answer = confirm("Do you want to draw a card?")
if (answer == true)
{
User();
alert("Your score is: " + PlayerScore);
document.getElementById("PlayerScore").innerHTML = "Your score is: " + PlayerScore;
if (PlayerScore < 21)
{AskAgain = true;}
else
{AskAgain = false;}
}
else
{
AskAgain = false;
}
}
LookAtHands();
</script>
</head>
<body>
<div><p>Welcome to our Blackjack Table!</p>
<p id="PlayerScore">Your Score is: </p>
<p id="DealerScore">Dealer's Score is: </p>
</div>
</body>
</html>
As #nnnnnn has mentioned that your html tags are not even loaded when your JS has executed and hence the issue. Try something like below to correct the issue:
<!DOCTYPE html>
<html>
<title>Welcome to Blackjack</title>
<!--<link href="style.css" rel="stylesheet" type="text/css">
<!-- <script src="bj.js"></script> -->
<head>
<script>
var PlayerScore = 0;
var DealerScore = 0;
var Winner = "Nobody";
var AskAgain = true;
function random(maxValue)
{
return Math.floor(Math.random() * maxValue) + 1;
}
function pickSuit()
{
suit = random(4);
if(suit == 1)
return "Spades";
if(suit == 2)
return "Clubs";
if(suit == 3)
return "Diamonds";
return "Hearts";
}
function cardName(card)
{
if(card == 1)
return "Ace";
if(card == 11)
return "Jack";
if(card == 12)
return "Queen";
if(card == 13)
return "King";
return ("" + card);
}
function cardValue(card)
{
if(card == 1)
return 11;
if(card > 10)
return 10;
return card;
}
function PickACard(strWho)
{
card = random(13);
suit = pickSuit();
alert(strWho + " picked the " + cardName(card) + " of " + suit);
return cardValue(card);
}
function Dealer()
{
while(DealerScore < 17)
{
DealerScore = DealerScore + PickACard("Dealer");
}
}
function User()
{
PlayerScore = PlayerScore + PickACard("You");
}
function LookAtHands(Winner)
{
if(DealerScore > 21)
{
alert("House busts! You win!");
Winner = "You";
}
else
if((PlayerScore > DealerScore) && (PlayerScore <= 21))
{
alert("You win!");
Winner = "You";
}
else
if(PlayerScore == DealerScore)
{
alert("Push!");
Winner = "Tie";
}
else
{
alert("House wins!");
Winner = "House";
}
}
</script>
</head>
<body>
<div><p>Welcome to our Blackjack Table!</p>
<p id="PlayerScore">Your Score is: </p>
<p id="DealerScore">Dealer's Score is: </p>
</div>
<script>
Dealer();
alert("Dealer's score is: " + DealerScore);
document.getElementById('DealerScore').innerHTML = DealerScore;
User();
alert("Your score is: " + PlayerScore);
document.getElementById("DealerScore").innerHTML = "Dealer's score is: " + DealerScore;
while (AskAgain == true )
{
var answer = confirm("Do you want to draw a card?")
if (answer == true)
{
User();
alert("Your score is: " + PlayerScore);
document.getElementById("PlayerScore").innerHTML = "Your score is: " + PlayerScore;
if (PlayerScore < 21)
{AskAgain = true;}
else
{AskAgain = false;}
}
else
{
AskAgain = false;
}
}
LookAtHands();
</script>
</body>
</html>
your script is loading before the document that has the elements in it. Enclose your script in:
window.onload=function() {
//all of your JavaScript code
}

Categories

Resources