JS Game Results Not What I Expect - javascript

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;
})

Related

Farm Clicker game - Gold's value is increasing more than necessary

I'm trying to make a Farm Clicker game myself with Javascript. (In other words, as you click the Add Gold button, the user earns 1 gold and can obtain passive gold by buying some animals according to the number of gold he has.) But there is a problem with the program: If I save 50 gold and buy a goat, the gold suddenly increases more than necessary. The problem is most likely in the section that says setInterval, but I still couldn't find the exact solution.
HTML
<head>
<title>Farm clicker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content"></div>
<script src="script.js"></script>
</body>
JS
// global variables
const myContent = document.getElementById("content");
var gold=0;
let animals = {};
var goldToAdd = 0;
// global functions
function addGoldButton() {
let myButton = document.createElement("button");
myButton.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
addGoldButton();
function addGold(goldToAdd) {
console.trace();
if (gold == 0) {
gold = goldToAdd;
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
goldCounter.innerHTML = "Gold: " + gold;
myContent.appendChild(goldCounter);
} else
{
gold += goldToAdd;
document.getElementById("goldCounter").innerHTML = "Gold: " + gold;
}
// check for events on current gold level
checkGold();
goldToAdd=0;
}
function checkGold(){
if (gold >= 50 && document.getElementById("goatBuyButton") == null) {
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", ()=>buyAnimal("goat"));
myContent.appendChild(buttonBar);
buttonBar.appendChild(buyButton);
}
if (gold >= 90 && document.getElementById("pigBuyButton") == null) {
let buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", ()=>buyAnimal("pig"));
buttonBar.appendChild(buyButton);
}
if (gold >= 120 && document.getElementById("cowBuyButton") == null){
buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Cow (120g)";
buyButton.addEventListener("click", ()=>buyAnimal("cow"));
buttonBar.appendChild(buyButton);
}
function buyAnimal(animal) {
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id = "itemBar";
myContent.appendChild(itemBar);
}
switch (animal) {
case "":
//do something, don't and forget the break;
case "goat":
if (gold >= 50) {
addGold(-50);
if (animals.goats == null) {
animals.goats = 1;
let myElement = document.createElement("div");
myElement.id = "goats";
myElement.innerHTML = "Goat Quantity: " + animals.goats;
itemBar.appendChild(myElement);
} else {
animals.goats += 1;
document.getElementById("goats").innerHTML = "Goat Quantity: " + animals.goats;
}
}
break;
case "pig":
if (gold >= 90) {
addGold(-90);
if (animals.pigs == null) {
animals.pigs = 1;
let myElement = document.createElement("div");
myElement.id = "pigs";
myElement.innerHTML = "Pig Quantity: " + animals.pigs;
itemBar.appendChild(myElement);
} else {
animals.pigs += 1;
document.getElementById("pigs").innerHTML = "Pig Quantity: " + animals.pigs;
}
}
break;
case "cow":
if (gold >= 120) {
addGold(-120);
if (animals.cows == null) {
animals.cows = 1;
let myElement = document.createElement("div");
myElement.id = "cows";
myElement.innerHTML = "Cow Quantity: " + animals.cows;
itemBar.appendChild(myElement);
} else {
animals.cows += 1;
document.getElementById("cows").innerHTML = "Cow Quantity: " + animals.cows;
}
}
break;
default:
console.log("no animal found");
}
}
function passiveGold() {
if (animals.goats > 0) {
goldToAdd += animals.goats*5; //50=>5 10=>1
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs*10; //90=>10 9=>1
}
if (animals.cows > 0) {
goldToAdd += animals.cows*15; //120=>15 8=>1
}
addGold(goldToAdd);
}
setInterval(passiveGold, 10000);
}
So here the problem is in the passiveGold Function.It runs in to a infinite loop because after you are buying an animal the animal count is obviously greater than 0.So the if condition will be evaluated to true always inside the passiveGold function and as a result of that it runs into a infinite loop.
function passiveGold() {
if (animals.goats > 0) {
goldToAdd += animals.goats*5; //50=>5 10=>1
return;
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs*10; //90=>10 9=>1
return;
}
if (animals.cows > 0) {
goldToAdd += animals.cows*15; //120=>15 8=>1
return;
}
addGold(goldToAdd);
}
So here i just did a small modification by adding return statements into every if condition code blocks.So that after executing once it will return to the main function.
// global variables
const myContent = document.getElementById("content");
var gold=0;
let animals = {};
var goldToAdd = 0;
// global functions
function addGoldButton() {
let myButton = document.createElement("button");
myButton.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
addGoldButton();
function addGold(goldToAdd) {
console.trace();
if (gold == 0) {
gold = goldToAdd;
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
goldCounter.innerHTML = "Gold: " + gold;
myContent.appendChild(goldCounter);
} else
{
gold += goldToAdd;
document.getElementById("goldCounter").innerHTML = "Gold: " + gold;
}
// check for events on current gold level
checkGold();
goldToAdd=0;
}
function checkGold(){
if (gold >= 50 && document.getElementById("goatBuyButton") == null) {
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", ()=>buyAnimal("goat"));
myContent.appendChild(buttonBar);
buttonBar.appendChild(buyButton);
}
if (gold >= 90 && document.getElementById("pigBuyButton") == null) {
let buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", ()=>buyAnimal("pig"));
buttonBar.appendChild(buyButton);
}
if (gold >= 120 && document.getElementById("cowBuyButton") == null){
buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Cow (120g)";
buyButton.addEventListener("click", ()=>buyAnimal("cow"));
buttonBar.appendChild(buyButton);
}
function buyAnimal(animal) {
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id = "itemBar";
myContent.appendChild(itemBar);
}
switch (animal) {
case "":
//do something, don't and forget the break;
case "goat":
if (gold >= 50) {
addGold(-50);
if (animals.goats == null) {
animals.goats = 1;
let myElement = document.createElement("div");
myElement.id = "goats";
myElement.innerHTML = "Goat Quantity: " + animals.goats;
itemBar.appendChild(myElement);
} else {
animals.goats += 1;
document.getElementById("goats").innerHTML = "Goat Quantity: " + animals.goats;
}
}
break;
case "pig":
if (gold >= 90) {
addGold(-90);
if (animals.pigs == null) {
animals.pigs = 1;
let myElement = document.createElement("div");
myElement.id = "pigs";
myElement.innerHTML = "Pig Quantity: " + animals.pigs;
itemBar.appendChild(myElement);
} else {
animals.pigs += 1;
document.getElementById("pigs").innerHTML = "Pig Quantity: " + animals.pigs;
}
}
break;
case "cow":
if (gold >= 120) {
addGold(-120);
if (animals.cows == null) {
animals.cows = 1;
let myElement = document.createElement("div");
myElement.id = "cows";
myElement.innerHTML = "Cow Quantity: " + animals.cows;
itemBar.appendChild(myElement);
} else {
animals.cows += 1;
document.getElementById("cows").innerHTML = "Cow Quantity: " + animals.cows;
}
}
break;
default:
console.log("no animal found");
}
}
function passiveGold() {
if (animals.goats > 0) {
goldToAdd += animals.goats*5; //50=>5 10=>1
return;
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs*10; //90=>10 9=>1
return;
}
if (animals.cows > 0) {
goldToAdd += animals.cows*15; //120=>15 8=>1
return;
}
addGold(goldToAdd);
}
setInterval(passiveGold, 10000);
}
<head>
<title>Farm clicker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content"></div>
<script src="script.js"></script>
</body>
Hope I solved your problem.And if you need anything to be clarified let me know.
There are two main issues with the gold incrementation here. There's a brace out of place leading to (I think) the setInterval be created several times (each time checkGold is called, in fact). Secondly, the goldToAdd amount is not zero at the start of passiveGold. I've also edited addGold so that two gold counters don't turn up when you hit 0 gold. Snippet below:
const myContent = document.getElementById("content");
var gold=0;
let animals = {};
var goldToAdd = 0;
// global functions
function addGoldButton() {
let myButton = document.createElement("button");
myButton.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
myContent.appendChild(myButton);
}
addGoldButton();
function addGold(goldToAdd) {
if(document.getElementById("goldCounter") == null) {
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
myContent.appendChild(goldCounter);
}
gold += goldToAdd;
document.getElementById("goldCounter").innerHTML = "Gold: " + gold;
checkGold();
}
function checkGold(){
if (gold >= 50 && document.getElementById("goatBuyButton") == null) {
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", ()=>buyAnimal("goat"));
myContent.appendChild(buttonBar);
buttonBar.appendChild(buyButton);
}
if (gold >= 90 && document.getElementById("pigBuyButton") == null) {
let buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", ()=>buyAnimal("pig"));
buttonBar.appendChild(buyButton);
}
if (gold >= 120 && document.getElementById("cowBuyButton") == null){
buttonBar = document.getElementById("buttonBar");
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Cow (120g)";
buyButton.addEventListener("click", ()=>buyAnimal("cow"));
buttonBar.appendChild(buyButton);
}
}
function buyAnimal(animal) {
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id = "itemBar";
myContent.appendChild(itemBar);
}
switch (animal) {
case "":
//do something, don't and forget the break;
case "goat":
if (gold >= 50) {
addGold(-50);
if (animals.goats == null) {
animals.goats = 1;
let myElement = document.createElement("div");
myElement.id = "goats";
myElement.innerHTML = "Goat Quantity: " + animals.goats;
itemBar.appendChild(myElement);
} else {
animals.goats += 1;
document.getElementById("goats").innerHTML = "Goat Quantity: " + animals.goats;
}
}
break;
case "pig":
if (gold >= 90) {
addGold(-90);
if (animals.pigs == null) {
animals.pigs = 1;
let myElement = document.createElement("div");
myElement.id = "pigs";
myElement.innerHTML = "Pig Quantity: " + animals.pigs;
itemBar.appendChild(myElement);
} else {
animals.pigs += 1;
document.getElementById("pigs").innerHTML = "Pig Quantity: " + animals.pigs;
}
}
break;
case "cow":
if (gold >= 120) {
addGold(-120);
if (animals.cows == null) {
animals.cows = 1;
let myElement = document.createElement("div");
myElement.id = "cows";
myElement.innerHTML = "Cow Quantity: " + animals.cows;
itemBar.appendChild(myElement);
} else {
animals.cows += 1;
document.getElementById("cows").innerHTML = "Cow Quantity: " + animals.cows;
}
}
break;
default:
console.log("no animal found");
}
}
function passiveGold() {
goldToAdd = 0;
if (animals.goats > 0) {
goldToAdd += animals.goats*5; //50=>5 10=>1
}
if (animals.pigs > 0) {
goldToAdd += animals.pigs*10; //90=>10 9=>1
}
if (animals.cows > 0) {
goldToAdd += animals.cows*15; //120=>15 8=>1
}
addGold(goldToAdd);
}
setInterval(passiveGold, 10000);
<div id="content"></div>
I've refactored your code and broke it down and remade it. i've made the logic simpler and more like an actual game loop demo
<head>
<title>Farm clicker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content"></div>
</body>
// global state
let game_state = {
gold: 50,
animals: {
goats: 0,
pigs: 0,
cows: 0
},
}
// global variables
const content = document.getElementById("content");
let passiveGoldInterval = null;
// helper functions
function addGold(value){
game_state.gold += value;
updateUI();
}
function buyAnimal(animal){
switch(animal){
case 'goat':
if(game_state.gold >= 50){
addGold(-50);
game_state.animals.goats++;
}
break;
case 'pig':
if(game_state.gold >= 90){
addGold(-90);
game_state.animals.pigs++;
}
break;
case 'cow':
if(game_state.gold >= 120){
addGold(-120);
game_state.animals.cows++;
}
break;
default: // do nothing
}
updateUI();
}
// background function
function passiveGold(){
addGold(game_state.animals.goats * 5); // add gold for goats
addGold(game_state.animals.pigs * 10); // add gold for pigs
addGold(game_state.animals.cows * 15); // add gold for cows
}
// game state management (init)
function init(){
passiveGoldInterval = setInterval(passiveGold, 10000); // calss this function every 10 seconds
updateUI();
}
function updateUI(){
if (!(document.getElementById("addButton"))) {
let myButton = document.createElement("button");
myButton.id = "addButton";
myButton.addEventListener("click", ()=>addGold(1)); // add one
myButton.innerHTML = "Add Gold!";
content.appendChild(myButton);
}
if (!(document.getElementById("goldCounter"))) {
let goldCounter = document.createElement("h2");
goldCounter.id = "goldCounter";
goldCounter.innerHTML = "Gold: " + game_state.gold;
content.appendChild(goldCounter);
} else
{
document.getElementById("goldCounter").innerHTML = "Gold: " + game_state.gold;
}
let itemBar = document.getElementById('itemBar');
if (itemBar == null) {
itemBar = document.createElement("div");
itemBar.id = "itemBar";
content.appendChild(itemBar);
}
// animals (display counts)
if (game_state.animals.goats >= 1 && !(document.getElementById("goats"))) {
let myElement1 = document.createElement("div");
myElement1.id = "goats";
myElement1.innerHTML = "Goat Quantity: " + game_state.animals.goats;
document.getElementById('itemBar').appendChild(myElement1);
} else if(document.getElementById("goats")) {
document.getElementById("goats").innerHTML = "Goat Quantity: " + game_state.animals.goats;
}
if (game_state.animals.pigs >= 1 && !(document.getElementById("pigs"))) {
let myElement2 = document.createElement("div");
myElement2.id = "pigs";
myElement2.innerHTML = "Pig Quantity: " + game_state.animals.pigs;
document.getElementById('itemBar').appendChild(myElement2);
} else if(document.getElementById("pigs")) {
document.getElementById("pigs").innerHTML = "Pig Quantity: " + game_state.animals.pigs;
}
if (game_state.animals.cows >= 1 && !(document.getElementById("cows"))) {
let myElement3 = document.createElement("div");
myElement3.id = "cows";
myElement3.innerHTML = "Cow Quantity: " + game_state.animals.cows;
document.getElementById('itemBar').appendChild(myElement3);
} else if(document.getElementById("cows")) {
document.getElementById("cows").innerHTML = "Cow Quantity: " + game_state.animals.cows;
}
// display buttons if match
// button container
if(!(document.getElementById("buttonBar"))){
let buttonBar = document.createElement("div");
buttonBar.id = "buttonBar";
content.appendChild(buttonBar);
}
// goats buy
if(game_state.gold >= 50){
if(!(document.getElementById("goatBuyButton"))){
let buyButton = document.createElement("button");
buyButton.id = "goatBuyButton";
buyButton.innerHTML = "Buy Goat (50g)";
buyButton.addEventListener("click", () => buyAnimal("goat"));
content.appendChild(buyButton);
}
} else {
if(document.getElementById("goatBuyButton")){
document.getElementById("goatBuyButton").remove();
}
}
// pigs buy
if(game_state.gold >= 90){
if(!(document.getElementById("pigBuyButton"))){
let buyButton = document.createElement("button");
buyButton.id = "pigBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", () => buyAnimal("pig"));
content.appendChild(buyButton);
}
} else {
if(document.getElementById("pigBuyButton")){
document.getElementById("pigBuyButton").remove();
}
}
// cows buy
if(game_state.gold >= 120){
if(!(document.getElementById("cowBuyButton"))){
let buyButton = document.createElement("button");
buyButton.id = "cowBuyButton";
buyButton.innerHTML = "Buy Pig (90g)";
buyButton.addEventListener("click", () => buyAnimal("cow"));
content.appendChild(buyButton);
}
} else {
if(document.getElementById("cowBuyButton")){
document.getElementById("cowBuyButton").remove();
}
}
}
init();

How can I modify my HTML file with node.js?

require('dotenv').config()
var ComfyJS = require("comfy.js");
var firstplayer = document.getElementById("firstcharactername");
var maxPlayer = 0;
var totalAmount = 0;
var playerOne = "player1";
var playerTwo = "player2";
var playerOneScore = 0;
var playerTwoScore = 0;
var playerOneHealth = 50;
var playerTwoHealth = 50;
var playerOneTurnNumber = 1;
var playerTwoTurnNumber = 0;
function randomFunc(min, max)
{
return Math.floor(Math.random() * max) + min;
}
ComfyJS.onCommand = ( user, command, message, flags, extra ) => {
function rpsPicker()
{
var randomnumberRPS = randomFunc(1,3);
if(randomnumberRPS === 1)
{
ComfyJS.Say("#" + user + " Rock");
}
else if(randomnumberRPS === 2)
{
ComfyJS.Say("#" + user + " Paper");
}
else if(randomnumberRPS === 3)
{
ComfyJS.Say("#" + user + " Scissors");
}
}
function headtailPicker()
{
var randomnumberHeadTail = randomFunc(1,2);
if(randomnumberHeadTail === 1)
{
ComfyJS.Say("#" + user + " Heads");
}
else
{
ComfyJS.Say("#" + user + " Tail");
}
}
///////////////////////////////////////////////COMMANDS/////////////////////////////////////////////////
if( command === "roll1" && user === playerOne)
{
var randomNumber1 = randomFunc(2,11);
ComfyJS.Say("#"+user + " You've rolled two dices equals to " + randomNumber1+".");
playerOneScore += randomNumber1;
ComfyJS.Say("#"+user + "'s total amount is "+ playerOneScore);
}
else if(command === "roll2" && user === playerTwo)
{
var randomNumber2 = randomFunc(2,11);
ComfyJS.Say("#"+user + " You've rolled two dices equals to " + randomNumber2+".");
playerTwoScore += randomNumber2;
ComfyJS.Say("#"+user + "'s total amount is "+ playerTwoScore);
}
else if(command === "compare")
{
if(playerOneScore > playerTwoScore)
{
ComfyJS.Say(playerOne+" won.")
}
else
{
ComfyJS.Say(playerTwo+" won.")
}
}
else if (command === "joingame")
{
maxPlayer += 1;
if(maxPlayer === 1)
{
playerOne = user;
ComfyJS.Say("#"+user + " has joined the game " + ".");
firstplayer.innerText = user;
}
else if(maxPlayer === 2)
{
playerTwo = user;
ComfyJS.Say("#"+user + " has joined the game " + ".");
}
else if(maxPlayer > 2)
{
ComfyJS.Say("Max player limit!")
}
}
else if(command === "resetgame" && flags.broadcaster == true)
{
totalAmount = 0;
maxPlayer = 0;
playerOne = "player1";
playerTwo = "player2";
playerOneScore = 0;
playerTwoScore = 0;
}
else if (command === "rps")
{
rpsPicker();
}
else if (command === "flipcoin")
{
headtailPicker();
}
///////////////////////////////////////////////COMBAT GAME//////////////////////////////////////////////////////
else if( command === "attack1" && user === playerOne)
{
if (playerOneTurnNumber > 0)
{
var randomNumberAttack1 = randomFunc(5,12);
ComfyJS.Say("/me " + "#"+user + " hits "+ randomNumberAttack1 + " damage to his opponent.");
playerTwoHealth -= randomNumberAttack1;
ComfyJS.Say("/me " + "#"+playerTwo + "'s remaining health is " + playerTwoHealth);
playerOneTurnNumber -= 1;
}
else
{
ComfyJS.Say("/me It's not your turn.");
}
}
else if( command === "attack2" && user === playerTwo)
{
if (playerTwoTurnNumber > 0)
{
var randomNumberAttack2 = randomFunc(5,12);
ComfyJS.Say("/me " + "#"+user + " hits "+ randomNumberAttack2 + " damage to his opponent.");
playerOneHealth -= randomNumberAttack2;
ComfyJS.Say("/me " + "#"+playerOne + "'s remaining health is " + playerOneHealth);
playerTwoTurnNumber -= 1;
}
else
{
ComfyJS.Say("/me It's not your turn.");
}
}
else if( command === "endturn1" && user === playerOne)
{
ComfyJS.Say("/me " + playerOne + " ends his turn.");
playerTwoTurnNumber += 1;
}
else if( command === "endturn2" && user === playerTwo)
{
ComfyJS.Say("/me " + playerTwo + " ends his turn.");
playerOneTurnNumber += 1;
}
}
///////////////////////////////////////////WELCOMER/////////////////////////////////////////////////
ComfyJS.onJoin = ( user, self, extra ) =>
{
console.log(user);
ComfyJS.Say("#"+user+" Welcome!");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
ComfyJS.onChat = ( user, message, flags, self, extra ) =>
{
console.log( user, message, extra.userColor, flags.broadcaster);
}
ComfyJS.Init( process.env.TWITCHUSER, process.env.OAUTH, "shiftyshifterr" );
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/comfy.js#latest/dist/comfy.min.js"></script>
<h1>TEST GAME</h1>
<div class="character-container">
<div class="first-character-container">
<p id="firstcharactername" class="first-character-name"></p>
<img src="firstplayer.gif" alt="firstplayer">
</div>
<div>
<img src="secondplayer.gif" alt="secondplayer">
<p id="secondcharactername" class="second-character-name"></p>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
I'm using node.js to build a twitch bot.
But when I try to modify my HTML via that javascript file I get an error like:
ReferenceError: the document is not defined
I've searched for it and found out that node.js is server sided so I can not use document.getElementById with it.
But I want to modify my HTML file by using that node.js javascript file.
Is there any way to do that and how?
What i'my trying to do here is that when they type joingame command user name will be written in p tag in my HTML file.
I'm pretty new to developing so sorry if I messed up with a question.
As you have correctly identified, you cannot reach document from server-side, because that only exists in the browser. You will need to parse the HTML if you want to work with it on Node JS, server-side.
You will need to install it like
npm install --save node-html-parser
and then you will be able to do something like
import { parse } from 'node-html-parser';
//Some code
var document = parse(yourhtml);
In this example -
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))
https://expressjs.com/en/starter/hello-world.html
if you notice the res.send - you are sending the html there
If you post your nodejs snippets, we can work further.
document.getElementById interacts with your "HTML document" on runtime. If you need to edit your "HTML file" contents you need something like this:
var fs = require('fs');
fs.readFile('index.txt', 'utf-8', function(err, data) {
if (err) throw err;
var newValue = 'new content';
fs.writeFile('index.txt', newValue, 'utf-8', function(err, data) {
if (err) throw err;
console.log('Done!');
})
})
Source

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>

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
}

Adding user/computer score to a Tweet

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 );

Categories

Resources