cant get the reset button to reset the pot - javascript

for some reason i cant get my reset button to reset the pot i have this as my html code. ive been working at it and cant seem to figure it out im pretty sure im just missing something really important
<button id="reset" onClick="reset()"> Reset </button>
and this as my java for the reset button factor
var pot = 100;
function pull() {
var slot1 = 0;
var slot2 = 0;
var slot3 = 0;
/*generate 3 random numbers, assign to corresponding img1,
img2,img3, swap images in table */
for (var i = 1; i <= 3; i++) {
var fruit = Math.floor((Math.random() * 3) + 1);
document.getElementById(i).src = "img" + fruit + ".gif";
//assign each of the 3 random numbers to a slot value
if (i == 1) {
slot1 = fruit;
}
else if (i == 2) {
slot2 = fruit;
}
else {
slot3 = fruit;
}
}
//add 25 to the pot if the result is 3 of a kind
if (slot1 == slot2 && slot2 == slot3){
pot = pot + 25;
document.getElementById("awnser").innerHTML =
"Jackpot, 3 of a kind! You win $25.00, <br> Pot: $" + pot;
}
//add 10 to pot if the result is a pair
else if (slot1 == slot2 || slot2 == slot3 || slot1 == slot3){
pot = pot + 10;
document.getElementById("awnser").innerHTML = "A pair! You win $10.00.
<br> pot: $" + pot;
}
else {
pot = pot - 120;
if (pot <= 0) {
document.getElementById("awnser").innerHTML = "pot is empty, you are
out of cash."
document.getElementById("stop").disabled = true;
function reset(){
pot = pot + 100;
document.getElementById("reset").reset;
}
}
else {
document.getElementById("awnser").innerHTML = "No match! You loose
$20.00. <br> Pot: $" + pot;
}
}
}

Related

If statement with || is not doing anything

some context,
I'm making a game wherein you have to guess a randomly generated number between 1 and 1 million. I'm trying to make it so that if the user inputs something that is not a number, above 1 million, or below zero, it will display an error warning. The last else if statement is supposed to do this, but is not doing so. I've tried several revisions, including individual else if statements for each forbidden case, but they aren't working.
<script type = "text/javascript">
var randomNumber = Math.floor(Math.random() * 1000000 + 1);
var count = 0;
var x = 1000000
console.log(randomNumber)
document.getElementById("submitguess").onclick = function(){
var userGuess = document.getElementById("guessField").value;
console.log(userGuess)
if(userGuess == randomNumber)
{
if (count < 10) {
document.getElementById('higherOrLower').innerHTML = '<div class="powerupstyling"><a class="facethebossstyling">YOU BEAT THE GAME. CONGRATS !</a></div>'
}
else if (count > 10) {
document.getElementById('higherOrLower').innerHTML = "<center>grats you got it in " + count + " tries. Unfortunately, you didn't quite beat the game. Aim for 10 tries or lower.</center>"
}
}
else if (userGuess > randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go lower</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
else if (userGuess < randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go higher</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
else if (userGuess >= 1000000 || userGuess =< 0 || userGuess == "") {
alert('input a valid number !')
}
}
</script
You have to write the last else if before you check if the userGuess is higher or lower than the randomNumber.
That's because when userGuess is below 0 or over 1.000.000 it will always be catched by the else ifs that check if the userGuess is lower or higher than randomNumber. Therefore the last else if will never be reached.
The correct order would be:
Check if the user guessed right.
Check if the input is wrong.
Check if the user guessed too high.
Check if the user guessed too low.
But you did:
Check if the user guessed right.
Check if the user guessed too high.
Check if the user guessed too low.
Check if the input is wrong.
Do the following:
<script type = "text/javascript">
var randomNumber = Math.floor(Math.random() * 1000000 + 1);
var count = 0;
var x = 1000000
console.log(randomNumber)
document.getElementById("submitguess").onclick = function(){
var userGuess = document.getElementById("guessField").value;
console.log(userGuess)
if(userGuess == randomNumber)
{
if (count < 10) {
document.getElementById('higherOrLower').innerHTML = '<div class="powerupstyling"><a class="facethebossstyling">YOU BEAT THE GAME. CONGRATS !</a></div>'
}
else if (count > 10) {
document.getElementById('higherOrLower').innerHTML = "<center>grats you got it in " + count + " tries. Unfortunately, you didn't quite beat the game. Aim for 10 tries or lower.</center>"
}
}
else if (userGuess >= 1000000 || userGuess <= 0 || userGuess == "") {
alert('input a valid number !')
}
else if (userGuess > randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go lower</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
else if (userGuess < randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go higher</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
}
</script
There are a couple problems with your conditionals.
else if (userGuess > randomNumber)
{ ... }
This will handle all numbers, even those greater than 1,000,000.
else if (userGuess < randomNumber)
{ ... }
This will handle all numbers, even those less than 0.
Therefore, your last conditional will only ever catch a blank input (which would probably be better expressed as a cast to string or bool).
Also, as pointed out in the comments to your question, the correct less than or equal syntax is <=.
You do:
else if (userGuess >= 1000000 || userGuess =< 0 || userGuess == "") {
But it's like this:
else if (userGuess >= 1000000 || userGuess <= 0 || userGuess == "") {
<script type = "text/javascript">
var randomNumber = Math.floor(Math.random() * 1000000 + 1);
var count = 0;
var x = 1000000
console.log(randomNumber)
document.getElementById("submitguess").onclick = function(){
var userGuess = document.getElementById("guessField").value;
console.log(userGuess)
if(userGuess == randomNumber)
{
if (count < 10) {
document.getElementById('higherOrLower').innerHTML = '<div class="powerupstyling"><a class="facethebossstyling">YOU BEAT THE GAME. CONGRATS !</a></div>'
}
else if (count > 10) {
document.getElementById('higherOrLower').innerHTML = "<center>grats you got it in " + count + " tries. Unfortunately, you didn't quite beat the game. Aim for 10 tries or lower.</center>"
}
}
else if (userGuess > randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go lower</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
else if (userGuess < randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go higher</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
else if (userGuess >= 1000000 || userGuess <= 0 || userGuess == "") {
alert('input a valid number !')
}
}
</script

can not display the dialog when load both file .js or .html?

I am having trouble with this problem. When I coded this very simple javascript code from head first javasript book, they said to me that I must saved it as the name battle.js and run it, but after that, they said to me that I must run it as the name battle.html. Here is the code
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = promt("Ready, aim, fire! (enter a number from 0-6):")
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3/guesses);
alert(stats);
As they described, it must appear a dialog and we can enter something into that, but when I ran it, nothing appeared.
I just a newbie with javascript, could you please give me some ideas ? Thank you very much.
Your code has typing mistake. replace promt to prompt
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = prompt("Ready, aim, fire! (enter a number from 0-6):")
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3 / guesses);
alert(stats);

Rock Paper Scissors Javascript Game Add Choice Limit

I've created a Javascript-based Rock Paper Scissors game and it's pretty good so far. However, I want to create an option for "best out of 3" or "best out of 5". Please could some of you awesome JS people have a look at my code and see how I could implement the best of "x" scenario. Basically, I guess it comes down to the number of clicks.
Anyway, the code speaks for itself and here is a live example of the code:
Rock Paper Scissors Live Github Example
And the code:
(function(){
/*
* Rock, paper, scissors
*
* The classic game recreated in Javascript for playing in the browser.
*
*/
// create the choices
var choices = [
'rock',
'paper',
'scissors'
];
var CHOICES_LENGTH = choices.length;
// create the text for winning or drawing
var USER_WINS = "You win!";
var COMP_WINS = "Computer wins";
var DRAW = "Draw"
var MEH = '<i class="fa fa-meh-o" aria-hidden="true"></i>';
var SMILE = '<i class="fa fa-smile-o" aria-hidden="true"></i>';
var FROWN = '<i class="fa fa-frown-o" aria-hidden="true"></i>';
var score = 0;
var computer_score = 0;
var gameType;
var clicks = 0;
// score elements
var userScore = getById('score');
var compScore = getById('computerScore');
userScore.textContent = score;
compScore.textContent = computer_score;
// get the game area and get access to all the buttons
var game = getById('game');
var userChoices = game.getElementsByTagName('button');
var comp = getById('computer');
var compChoices = comp.getElementsByTagName('div');
// get the results element and hide it initially
var results = getById('results');
hide(results);
var gameOver = getById('gameOver');
hide(gameOver);
// get the intro element and the buttons for choosing a game type
var intro = getById('intro');
var bestOf3 = getById('bestOf3');
var bestOf5 = getById('bestOf5');
// start the best of 3 game
bestOf3.onclick = function() {
enableGame();
gameType = 3;
}
bestOf5.onclick = function() {
enableGame();
gameType = 5;
}
function enableGame() {
enable(userChoices);
hide(intro);
}
// add an onclick event to each button and disable them initially
for(var i = 0; i < userChoices.length; i++) {
userChoices[i].onclick = selection;
userChoices[i].disabled = true;
}
function computerSelection() {
var randomIndex = Math.floor(Math.random() * CHOICES_LENGTH);
var compChoice = choices[randomIndex];
return compChoice;
}
function selection() {
// get the user and computer choice
var chosen = this.id;
var comp = computerSelection();
// get the users chosen item
var chosenItem = getById(chosen);
// prepare the chosenCompItem so we can assign it to a dynamic id
var chosenCompItem;
if(comp === 'rock') {
chosenCompItem = getById('computerRock');
}
else if(comp === 'paper') {
chosenCompItem = getById('computerPaper');
}
else if(comp === 'scissors') {
chosenCompItem = getById('computerScissors');
}
// show results and disable all choices so no more can
// be made while waiting for the pop up to fade out
show(results);
reappear(results);
disable(userChoices);
disable(compChoices);
// make the selected item stand out from the rest
chosenItem.classList.add('selected');
chosenCompItem.classList.add('selected');
// decide who wins
if(chosen === comp) {
results.textContent = DRAW;
// ugly repetive code. what can I do???
timeout();
results.innerHTML += MEH;
}
else if(chosen === 'rock' && comp === 'scissors') {
results.textContent = USER_WINS;
score += 1;
userScore.textContent = score;
timeout();
results.innerHTML += SMILE;
}
else if(chosen === 'paper' && comp === 'rock') {
results.textContent = USER_WINS;
score += 1;
userScore.textContent = score;
timeout();
results.innerHTML += SMILE;
}
else if(chosen === 'scissors' && comp === 'paper') {
results.textContent = USER_WINS;
score += 1;
userScore.textContent = score;
timeout();
results.innerHTML += SMILE;
}
else {
results.textContent = COMP_WINS;
computer_score +=1;
compScore.textContent = computer_score;
timeout();
results.innerHTML += FROWN;
}
console.log(clicks);
}
// utilities
function getById(id) {
return document.getElementById(id);
}
function hide(element) {
element.style.display = 'none';
}
function show(element) {
element.style.display = 'block';
}
function disappear(element) {
element.className = 'disappear';
}
function reappear(element) {
element.className = 'reappear';
}
function disable(elements) {
for(var i = 0; i < elements.length; i++) {
elements[i].disabled = true;
elements[i].classList.add('unselected');
}
}
function enable(elements) {
for(var i = 0; i < elements.length; i++) {
elements[i].disabled = false;
elements[i].classList.add('default');
elements[i].classList.remove('selected', 'unselected');
}
}
function timeout() {
setTimeout(function(){
disappear(results);
enable(userChoices);
enable(compChoices);
}, 2000)
}
})();
The code has massive room for improvement but the main thing here is, how do I make it so the user gets only 3 or 5 plays??
Hope this all makes sense.
Thanks
Assuming your definition of best of "N" is the same as mine, my code should work.
My definition of "best of N" is:
To win, one person must win N/2 rounds, with N/2 being rounded up to the nearest whole number.
You could use this code:
if(userScore + compScore === gameType) { gameOver(); }
And use a simple if statement to see who won.
Hope this helped!

Add Variables In If Statement From Values Determined by Radio Buttons

I have a short survey that gives a final value based on the selections you make. The problem is, only the first radio group, "people" is being added at the end... the other four (org + focal + location + carry) are being ignored. Would someone please help me figure out what is wrong with my code? Thanks!
var score = 0;
var people = 0;
var org = 0;
var focal = 0;
var location = 0;
var carry = 0;
//PEOPLE
if ($('input:radio:checked').val() === "Obama") {
people = -25;
}else if ($('input:radio:checked').val() === "Clinton"){
people = -15;
}else if($('input:radio:checked').val() === "Bush"){
people = 25;
}else if($('input:radio:checked').val() === "Romney"){
people = 0;
}else if($('input:radio:checked').val() === "Windsor"){
people = 25;
}else if($('input:radio:checked').val() === "Putin"){
people = -25;
};
//ORG
if ($('input:radio:checked').val() === "Christian") {
org = 20;
}else if ($('input:radio:checked').val() === "Boy Scouts"){
org = 10;
}else if($('input:radio:checked').val() === "Freemason"){
org = 30;
}else if($('input:radio:checked').val() === "KGB"){
org = -20;
}else if($('input:radio:checked').val() === "Islam"){
org = -30;
}else if($('input:radio:checked').val() === "Satanic Cult"){
org = -50;
};
//FOCAL
if ($('input:radio:checked').val() === "Financial") {
focal = 15;
}else if ($('input:radio:checked').val() === "Industry"){
focal = 20;
}else if($('input:radio:checked').val() === "Medical"){
focal = 5;
}else if($('input:radio:checked').val() === "Technology"){
focal = 30;
}else if($('input:radio:checked').val() === "War"){
focal = -30;
}else if($('input:radio:checked').val() === "Spy"){
focal = -20;
};
//LOCATION
if ($('input:radio:checked').val() === "United Kingdom") {
location = 5;
}else if ($('input:radio:checked').val() === "U.S.A."){
location = -15;
}else if($('input:radio:checked').val() === "China"){
location = 0;
}else if($('input:radio:checked').val() === "Germany"){
location = 20;
}else if($('input:radio:checked').val() === "Russia"){
location = -40;
}else if($('input:radio:checked').val() === "Mexico"){
location = -60;
};
//CARRY
if ($('input:radio:checked').val() === "Tune") {
var carry = 15;
}else if ($('input:radio:checked').val() === "Weight"){
var carry = 25;
}else if($('input:radio:checked').val() === "Stick"){
var carry = 0;
}else if($('input:radio:checked').val() === "Grudge"){
var carry = -25;
}else if($('input:radio:checked').val() === "Ebola"){
var carry = -80;
}else if($('input:radio:checked').val() === "Reset"){
var carry = -100;
};
var score = (people + org + focal + location + carry);
if(score>50){
$('.result').html('You Win!');
}else{
$('.result').html('You Lose!');
}
$('p').html("Your score is " + score + ".");
The problem is your radio selector, it will always return the very first checked radio value across all the groups instead of targeting specific groups.
The solution is to use the radio group name in the selector like $('input[name="people"]:radio:checked').val().
To add to that, you can simplify the code by using a value map like
var pmap = {
Obama: -25,
Clinton: -15,
Bush: 25,
Romney: 0,
Windsor: 25,
Putin: -25
};
var people = pmap[$('input[name="people"]:radio:checked').val()] || 0;
Create similar value maps for the other groups also.

Javascript Check variable.Then gain ++ per second

I have a problem i want to check a variable.If its 0 then gain ++ after 1.5s.If its 10 then gain ++ after .4s.Its complicated.It doesnt really work.My code so far:
if(road == 1){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1400);}
else if(road == 2){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1300);}
else if(road == 3){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1200);}
else if(road == 4){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1100);}
else if(road == 5){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},1000);}
else if(road == 6){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},900);}
else if(road == 7){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},800);}
else if(road == 8){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},600);}
else if(road == 9){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},400);}
else if(road == 10){setInterval(function(){stamina = stamina+1;document.getElementById("stamina").innerHTML = stamina;},200);}
else{setInterval(function(){stamina++;document.getElementById("stamina").innerHTML = stamina;},1500);}
And the code to build a road is this:
function build_road() {
if ((wood + tavern) >= 29 && stone > 4 && road < 10) {
road++;
document.getElementById("road_count").innerHTML = road;
wood = (wood + tavern) - 20;
stone = stone - 5;
document.getElementById("wood").innerHTML = wood;
document.getElementById("stone").innerHTML = stone;
exp = exp + 20;
var x = document.getElementById("PROGRESS");
x.setAttribute("value", exp);
x.setAttribute("max", max);
if (exp == 100) {
exp = 0;
level++;
document.getElementById("level").innerHTML = level;
}
alert("Congratulations,You've create a Road,Now you gain stamina slightly faster.");
}
else {
alert("You need: 30Wood,5Stone .Maximum 10 Roads.")
}
}
Make reusable functions (it's often a good practice, when you a difficulties with a piece of code, to break it into small functions):
var staminaIncreaseTimer = null;
function configureStaminaIncrease(delay) {
if (staminaIncreaseTimer !== null)
clearInterval(staminaIncreaseTimer);
staminaIncreaseTimer = setInterval(function () {
increaseStamina();
}, delay);
}
function increaseStamina() {
stamina += 1;
document.getElementById("stamina").innerHTML = stamina;
}
Solution with an array (suggested by Jay Harris)
var roadIndex = road-1;
var ROAD_DELAYS = [1400, 1300, 1200, /*...*/];
var DEFAULT_DELAY = 1500;
if (roadIndex < ROAD_DELAYS.length) {
configureStaminaIncrease(ROAD_DELAYS[roadIndex]);
} else {
configureStaminaIncrease(DEFAULT_DELAY);
}
Solution with a switch instead of you if-elseif mess:
switch (road) {
case 1:
configureStaminaIncrease(1400);
break;
case 2:
configureStaminaIncrease(1300);
break;
case 3:
configureStaminaIncrease(1200);
break;
//and so on...
default:
configureStaminaIncrease(1500);
}

Categories

Resources