Ok, I'm still a beginner at JavaScript, but I'm trying to write a rock-paper-scissors type game. Everything is working pretty well, except that every time that I run the "reload" function the output is whatever is the first "if" statement of the second if/else statement. By this I mean that the output "Both sides reload." would come back every time if the code were to be arranged how it is below. Also I already know that the randomizer works. Any help will be greatly appreciated. Thanks.
var reload = function() {
var random = function() {
var randomizer = Math.random() * 100
if (randomizer <= 33) {
var compDecision = 1
}
else if (randomizer > 67) {
var compDecision = 2
}
else if (33 < randomizer && randomizer <= 67) {
var compDecision = 3
}}
if (compDecision = 1) {
confirm("Both sides reload.")
}
else if (compDecision = 2) {
confirm("You reload and the enemy takes up defensive positions.")
}
else if (compDecision = 3) {
confirm("The enemy takes you out as you reload.")
}}
First of all use = for assignments, and == for logical compare operation.
Then you should declare var compDecision as a empty or default var and then assign to it a value without using var again. I would recommended using semi-colons ; to end your statements, unlike JavaScript, they are not optional for other languages.
Here is your working code, check the differences conclude the solution:
var reload = function () {
var compDecision = 0;
var random2 = function () {
var randomizer = Math.random() * 100
if (randomizer <= 33) {
compDecision = 1;
} else if (randomizer > 67) {
compDecision = 2;
} else {
compDecision = 3;
}
}
random2();
if (compDecision == 1) {
alert("Both sides reload.");
} else if (compDecision == 2) {
alert("You reload and the enemy takes up defensive positions.");
} else if (compDecision == 3) {
alert("The enemy takes you out as you reload.");
}
}
reload();
Tested here : http://jsfiddle.net/urahara/6rtt0w62/
Related
In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();
Given these 9 words, display on the page the word corresponding to their chosen number
1.mercury
2.venus
3.earth
4.mars
5.jupiter
6.saturn
7.uranus
8.neptune
9.pluto
Im not sure what I'm missing here Ive done a lot of trial an error and nothing seems to work.
I've tried using numEntry as my comparison for all the if statements and it hasn't worked. When I made var numEntry = true; only Mercury would display. When I made var numEntry = 1,2,3,4,5,6,7,8,9 only pluto would show. I then tried to create a variable for each number and use each once in a comparison like below but every planet shows up instead of the corresponding number to planet.
var numberOfPlanet = prompt("Please enter a number between 1 and 9");
function thePlanets(){
var numOne = 1;
var numTwo = 2;
var numThree = 3;
var numFour = 4;
var numFive = 5;
var numSix = 6;
var numSeven = 7;
var numEight = 8;
var numNine = 9;
//do I need to define numberEntry if I use it in my comparisons below? what do I define it as after the = //// I tried defining as true but only mercury will appear, i tried inserting numbers 1 through 9 but only pluto worked//
if(numOne = 1 ){
document.write("mercury");
}
if(numTwo = 2 ){
document.write("venus");
}
if(numThree = 3 ){
document.write("earth");
}
if(numFour = 4 ){
document.write("mars");
}
if(numFive = 5 ){
document.write("jupiter");
}
if(numSix = 6 ){
document.write("saturn");
}
if(numSeven = 7 ){
document.write("uranus");
}
if(numEight = 8 ){
document.write("neptune");
}
if(numNine = 9 ){
document.write("pluto");
}
}
thePlanets();
I just need a number to correspond with the right planet when the user enters that number eg. ( user enters 1 and it displays mercury)
Some notes:
Use numberOfPlanet as the function argument to compare with (it becomes num inside the function).
Convert numberOfPlanet to Number as prompt() returns string.
Use === (strong comparison) instead of = (assignment).
Use else if instead of next if if you need only one variant from some so that the comparing stops when the right result is found.
var numberOfPlanet = Number(prompt("Please enter a number between 1 and 9"));
function thePlanets(num){
if(num === 1){
document.write("mercury");
}
else if(num === 2){
document.write("venus");
}
else if(num === 3){
document.write("earth");
}
else if(num === 4){
document.write("mars");
}
else if(num === 5){
document.write("jupiter");
}
else if(num === 6){
document.write("saturn");
}
else if(num === 7){
document.write("uranus");
}
else if(num === 8){
document.write("neptune");
}
else if(num === 9){
document.write("pluto");
}
}
thePlanets(numberOfPlanet);
I'm still pretty new to JavaScript and need to be pointed in the right direction on a tiny project that is just for practice.
Very sorry if I'm not posting incorrectly, this is my first post on Stack Overflow and any help is appreciated.
I've tried accomplishing my goal a few different ways and haven't gotten there.
attack.addEventListener("click", function(){
hit();
});
function hit(){
if (bossHealth.textContent > 0 && playerFocus.textContent >=2) {
playerFocus.textContent -= 2;
bossHealth.textContent -= 3;
console.log("attack");
}
else if (bossHealth.textContent >= 0 && playerFocus.textContent < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
};
strong.addEventListener("click", function(){
bigHit();
});
function bigHit(){
if(bossHealth.textContent > 0 && playerFocus.textContent >= 5){
playerFocus.textContent -= 6;
bossHealth.textContent -= 6;
console.log("strong attack");
}
else if (playerFocus <5){
alert("Strong attack costs 5 focus, if you do not have enough focus try regenerating for a turn");
}
else (bossHealth.textContent <= 0){
bossHealth.textContent = "Dead";
alert("You've killed the bad guy and saved the world!!!");
}
};
easy.addEventListener("click", function(){
reset();
});
function reset(){
playerHealth.textContent = 10;
playerFocus.textContent = 10;
bossHealth.textContent = 10;
};
hard.addEventListener("click", function(){
hardMode();
});
function hardMode(){
playerHealth.textContent = 10;
playerFocus.textContent = 10;
bossHealth.textContent = 15;
};
With function hit I don't get the alert in my else if statement
with function bigHit I also don't get my alert for the else if statement and neither part of the else statement works.
also subtraction works in my functions, but when trying to add another function that uses addition in the same way it adds the number to the end of the string instead of performing math
You really shouldn't depend on what is in the DOM for logic. You should try with local variables then update the DOM based on those variables.
var boss = {}
var player = {}
function reset(){
player.health = 10;
player.focus = 10;
boss.health = 10;
update()
};
function hit(){
if (boss.health > 0 && player.focus >=2) {
player.focus -= 2;
boss.health -= 3;
console.log("attack");
} else if (boss.health > 0 && player.focus < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
update()
}
function update() {
playerFocus.textContent = player.focus
playerHealth.textContent = player.health
bossHealth.textContent = boss.health
}
Your issue is caused by textContent automatically turning your numbers into strings, by managing the data using your own variables this doesn't affect your code's logic.
Alternatively you could parse the strings as numbers using new Number(playerFocus.textContent), parseFloat(playerFocus.textContent), or +playerFocus.textContent but your code will become very hard to read very quickly.
Hope this enough to help you to make more edits to your code.
It looks like your playerFocus variable is a DOM node? Based on that assumption, your condition is missing a check for its textContent:
if (bossHealth.textContent > 0 && playerFocus.textContent >= 5){
// ...
}
else if (playerFocus.textContent <5){
// ...
In JavaScript, else blocks cannot have conditions, so if you want to conditionally check whether bossHealth.textContent <= 0 at the end of your bigHit function, you will need to change it to an else if (bossHealth.textContent <= 0) { ... } block instead.
I'm adding on to #LoganMurphy's comment and my own. In order to use the value of bossHealth it needs to be an integer. Change your code to look something like this:
function hit(){
if (parseInt(bossHealth.textContent) > 0 && parseInt(playerFocus.textContent) >=2) {
playerFocus.textContent -= 2;
bossHealth.textContent -= 3;
console.log("attack");
}
else if (parseInt(bossHealth.textContent) >= 0 && parseInt(playerFocus.textContent) < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
};
https://www.w3schools.com/jsref/jsref_parseint.asp
I tried solving a Problem I found online. I successfully solved the problem, but there's one small error that I couldn't solve.
The Problem
Write a guessing game where the user has to guess a secret number.
After every guess the program tells the user whether their number was
too large or too small. At the end the number of tries needed should
be printed.
Here's my code:
// Generate a random number between 1 and 100
var num = Math.floor(Math.random() * (100)) + 1;
var running = true;
while(running) {
var tries = 1;
var input = prompt("Take a guess");
if (input == num) {
console.log("Correct!");
console.log("Number of tries: " + tries);
running = false;
}else if (input > num) {
console.log("Too big");
}else if (input < num) {
console.log("Too small");
}
tries++;
}
Bug
Even if the user takes more than 1 try, the program still says,
Number of tries: 1
Please explain what am I doing wrong.
Thank You.
You reinitialize tires on each iteration of your while loop:
while(running) {
var tries = 1;
...
}
Try initializing outside of your loop.
var num = Math.floor(Math.random() * (100)) + 1;
var running = true;
var tries = 1;
while(running) {
var input = prompt("Take a guess");
if (input == num) {
console.log("Correct!");
console.log("Number of tries: " + tries);
running = false;
}else if (input > num) {
console.log("Too big");
}else if (input < num) {
console.log("Too small");
}
tries++;
}
Your variable tries decalres inside the while body. So, any loop iteration, this variable gets the value 1. To solve this issue, you should declare & initialize the variable outside to the loop:
// Generate a random number between 1 and 100
var num = Math.floor(Math.random() * 100) + 1;
var running = true;
var tries = 1;
while (running) {
var input = prompt("Take a guess");
if (input == num) {
console.log("Correct!");
console.log("Number of tries: " + tries);
running = false;
} else if (input > num) {
console.log("Too big");
} else if (input < num) {
console.log("Too small");
}
tries++;
}
Note: Do not use console.log(), use alert() instead. The console is for debugging, not for notify user messages.
I can see your problem. If you put a variable inside while function it will be reset each time meaning that it will be 1 each time.
If you put it outside it run just fine. Also, I believe that promt returns a string not a number that is why I would recommend you either to convert a number to string or a promt to number.
Here is the working code:
var num = Math.floor(Math.random() * (100)) + 1;
var running = true;
var tries = 1;
while(running) {
var input = parseFloat(prompt("Take a guess"));
if (input == num) {
console.log("Correct!");
console.log("Number of tries: " + tries);
running = false;
}else if (input > num) {
console.log("Too big");
}else if (input < num) {
console.log("Too small");
}
tries++;
}
I'm trying to solve a problem similar to the popular fizzbuzz or pingpong question. I already figured out how to write this portion of the code, however I also need to make a counter in which the user inputs their number and the page gives back 1 to the number they input, as well as the fizzbuzz/popcorn numbers. I think the code is something along the lines of
for (i = 1; i <= 20; i++) {...}
But I don't know how to combine this with my other code
var pingpong = function(number) {
if (number % 15 === 0) {
return 'pingpong';
} else if (number % 5 === 0) {
return 'pong';
} else if (number % 3 === 0) {
return 'ping';
} else {
return false;
}
};
Sorry, I know this is a super beginner question, but I'm just starting out and am having a hard time figuring out how everything works together.
You are close. To read more about JavaScripts loops.
var pingpong = function(number) {
if (number % 15 === 0) {
return 'pingpong';
} else if (number % 5 === 0) {
return 'pong';
} else if (number % 3 === 0) {
return 'ping';
} else {
return false;
}
};
for (var i = 1; i <= 20; i++) {
var num = pingpong(i);
// Just show it on the screen
document.body.innerHTML += i + ': ' + num + '<br />';
}