I've been looking on how to make a simple coin flip script using JavaScript, and I've seen videos of people that seem to over-complicate things using 20 different elements or whatever you call them. What I set out to do is create a "magic 8 ball" kind of script but only using simple commands. I have it working so that I have a text box, then next to it is a button when pressed it will execute a function.
My problem:T
Instead of returning a number when using Math.floor(Math.random() * 4), I want to return the words like "yes" "no" "maybe" etc. Additionally, I was wondering what the () do in Math.random().
My code is below. The first statement works if nothing is typed in it says "please enter a question" but the rest doesn't.
function checkFunction() {
if (question.value == '') {
document.getElementById("fortune").innerHTML = "Please Enter A Question";
} else {
Math.floor(Math.random(data) * 4);
if (data == 0) {
document.getElementById("fortune").innerHTML = "Maybe";
} else if (data == 1) {
document.getElementById("fortune").innerHTML = "Try Again";
} else if (data == 2) {
document.getElementById("fortune").innerHTML = "Yes";
} else if (data == 3) {
document.getElementById("fortune").innerHTML = "No";
} else {
return "Invalid";
}
}
}
I don't care if it's long, I just want it to be simple. I don't want to have to define a bunch of variables and mess around with calling them up because I'm just trying to take it a step at a time. I'm basically trying to figure out the maximum potential of an if statement before moving on and learning new things.
I was wondering what the () do in Math.random().
Math.random() is a function and it takes no parameters. The () means it's a function. You are passing data to the function but the function will not use it because it is parameterless.
If you don't like to have that return:
function checkFunction() {
var arr = ['Maybe','Try Again','Yes','No'],
index = Math.floor(Math.random() * 5); //0 to 4
document.getElementById('fortune').innerHTML = (question.value=='')? 'Please Enter A Question' : (index<arr.length)? arr[index] : 'Invalid';
}
If you like to have the return use this:
function checkFunction() {
var arr = ['Maybe','Try Again','Yes','No'],
index = Math.floor(Math.random() * 5); //0 to 4
var tmp = (question.value=='')? 'Please Enter A Question' : (index<arr.length)? arr[index] : false;
if (tmp===false){
return 'Invalid';
}else{
document.getElementById('fortune').innerHTML = tmp;
}
}
Math.floor(Math.random(data) * 4);
ignores the parameter data because Math.random doesn't take a parameter. The expression statement evaluates to an integer value in range [0, 4). After execution data is still undefined (or whatever it was before).
You could use an integer random number generator function such as:
function randomInt( low, high) {
var range = high - low + 1;
return low + Math.floor( range * Math.random());
}
to return an integer in the inclusive range [low, high] when called.
Related
Today, i start my very first game application with javascripp for studing purpuse. It's a gambit game that you set the bet, chose Odd or Even then Call. It's just a simply game but i get the problem with sumerize the score.
The idea is: I create a callback function to proceed the data, it took value of odd button and even button then comparing to a random number of a variable, then if the result is win, your money will be raised otherwise it's reduced. Here is my js code:
var even = document.getElementById('even')
var odd = document.getElementById('odd')
var call = document.getElementById('submit_btn')
var result = document.getElementById('result')
var score = document.getElementById('capital')
function process(choice,money,capital=1000) {
console.log(capital)
call.addEventListener('click',function () {
let luck = Math.floor(Math.random()*2)
if (choice == luck) {
capital += parseInt(money) ;
result.innerHTML = 'win+ '+money;
} else {
capital -= money;
result.innerHTML = 'lose- '+money;
}
score.innerHTML = 'Capital: '+capital
console.log(capital)
if(capital<1){
alert('Game Over')
}
})
}
even.addEventListener('click',function () {
let bet = parseInt(document.getElementById('bets').value)
if(Number.isInteger(bet) == true){
process(1,bet)
console.log(bet)
}else{
alert('You must bet first!!!')
}
})
odd.addEventListener('click',function () {
let bet = parseInt(document.getElementById('bets').value)
if(Number.isInteger(bet) == true){
process(0,bet)
console.log(bet)
}else{
alert('You must bet first!!!')
}
})
here is my application.
My problem is it works correctly when I just bet and call but when I change the bet option the money will be reset. How could I save the result then use it when another even occur. Thank you very much
In process(choice,money,capital=1000) you defined a default value 1000 to capital.
Therefore every time you click odd / even, it call process(0,bet) / process(1,bet), the capital reset to 1000. Because you didn't provide any value as third parameter.
I notice you add event listener in every process function, it may cause memory issue. You just need to bind once in this situation.
I will probably write like this:
// use IIFE to prevent pollution of global variable
(function(){
var even = document.getElementById('even')
var odd = document.getElementById('odd')
var call = document.getElementById('submit_btn')
var result = document.getElementById('result')
var score = document.getElementById('capital')
var bet = document.getElementById('bets');
// define variables here to keep their value.
var capital = 1000;
var money = NaN;
var choice = NaN;
function process(){
if(Number.isNaN(money) && Number.isNaN(choice)) return;
let luck = Math.floor(Math.random()*2)
if (choice == luck) {
capital += parseInt(money) ;
result.innerHTML = 'win+ '+money;
} else {
capital -= money;
result.innerHTML = 'lose- '+money;
}
score.innerHTML = 'Capital: '+capital
console.log(capital)
if(capital<1){
alert('Game Over')
}
}
function chageBet(choice){
if(Number.isInteger(parseInt(bet.value)) == true){
choice = choice;
money = bet.value;
console.log(bet)
} else{
alert('You must bet first!!!')
}
}
// just bind event once
call.addEventListener('click', process)
even.addEventListener('click', chageBet.bind(null, 1))
odd.addEventListener('click', chageBet.bind(null, 0))
})();
And maybe it's better to provide a reset function to reset the capital/money/choice variables.
Update:
Try to explain how variables change their values.
Round 1
choice is NaN; money is NaN; capital is 1000;
User set bet to 10
Click even button
execute changeBet(1)
choice become 1; money become 10;
Click call button
execute process()
(assume)vwin -> capital become 1000 + 10 = 1010
Round 2
choice is 1; money is 10; capital is 1010
User set bet to 200
Click odd button
execute changeBet(0)
choice become 0; money become 200;
Click call button
execute process()
lose -> capital become 1010 - 200 = 810
Every click event on button will execute the function that assigned in their addEventListener, and function changes the values of variables.
Please let me know if I am not clear enough.
I have these If statements based off of a Math.random() function and it works for the most part but sometimes nothing evaluates to true
I've tried changing the numbers that the Boolean statements compare too and I've tried changing the number that Math.random is multiplied by
var dodge = {
dodgeValue: function() {
return Math.floor(Math.random() * 10) + 1
},
roll: function() {
console.log('ROLL AFTER DODGE?'); //DELETE THIS
if (this.dodgeValue() <= 5) {
console.log('Ball Rolls to Person One');
dodgeBall.ball.position = 'on ground';
dodgeBall.personOne.ball();
}
if (this.dodgeValue() >= 5) {
console.log('Ball Rolls to Person Two');
dodgeBall.ball.position = 'on ground';
dodgeBall.personTwo.ball();
}
},
This is one of the two parts that have the same problem the other one when copied and pasted was really jumbled so I left it out but if anyone had any ideas on why this is happening or how to fix it that would be great.
You're generating two random numbers. A new one each time you write this.dodgeValue().
Additionally, if the value is exactly 5 then both branches will run - this probably isn't intended behaviour.
You should do something like let dodge = this.dodgeValue(); and then use if( dodge <= 5). Additionally, you should use else rather than an "if A then ... if not A then ..."
That's because you call dodgeValue twice, which calls random twice.
Ignoring the fact that random numbers in computers are actually psudeorandom for a second, let's look at what happens when you call dodgeValue twice to get two random numbers like you have.
You could conceivably get the following numbers from this code:
4
6 8
6 2
In the first case, the first if will be true and execute, since 4 <= 5.
The first if will be false, but the second if will be true, since 6 > 5 (first if is false) and 8 >= 5 (second if is true).
Now, what happens in that third case? Both if's will be false, since 6 > 5 (first if is false) and 2 < 5 (second if is false).
If that is how you intend for it to work (which I'm assuming not), keep your code as is. If not, you have 2 options depending on your needs.
If you need to store the output of dodgeValue for later, you can use a variable:
var dodge = {
dodgeValue: function() {
return Math.floor(Math.random() * 10) + 1
},
roll: function() {
console.log('ROLL AFTER DODGE?'); //DELETE THIS
var val = this.dodgeValue();
if (val <= 5) {
console.log('Ball Rolls to Person One');
dodgeBall.ball.position = 'on ground';
dodgeBall.personOne.ball();
}
if (val >= 5) {
console.log('Ball Rolls to Person Two');
dodgeBall.ball.position = 'on ground';
dodgeBall.personTwo.ball();
}
},
If you just need them to be opposites of each other, then just use an else clause instead.
var dodge = {
dodgeValue: function() {
return Math.floor(Math.random() * 10) + 1
},
roll: function() {
console.log('ROLL AFTER DODGE?'); //DELETE THIS
if (this.dodgeValue() <= 5) {
console.log('Ball Rolls to Person One');
dodgeBall.ball.position = 'on ground';
dodgeBall.personOne.ball();
} else {
console.log('Ball Rolls to Person Two');
dodgeBall.ball.position = 'on ground';
dodgeBall.personTwo.ball();
}
},
This is part of a javascript to validate a form. This checks to see if it is empty.
if (form.redoarr.value == "") {
alert("Has to be higher");
form.redoarr.focus();
return false;
}
I want to make sure that the 4 digit number entered begins with a 2 digit number under 75. It also has to end in a 2 digit number under 40. How can I use substr to extract the first two digits and make sure they are under 75 and the last two digits and make sure they are under 40. I don't need anything complicated as it's for a single in house user on a private form. I can't just use < 7641 as 1849 is not okay (for instance).
Notwithstanding the usual caveats about never validating a form only in JavaScript (rather than using a server-side language), REGEX is a good fit for this:
let
err,
val = form.redoarr.value
;
if (!val)
err = 'No value entered';
else if (!/^([0-6][0-9]|7[0-4])([0-3][0-9])$/.test(val))
err = 'Value must be four digits, with the first two under 75 and the last two under 40';
if (err) {
form.redoarr.focus();
alert(err);
return false;
}
REGEX is cleaner as you don't need to create any variables. However here's how you'd do it via substring:
let
nums_1 = val.substr(0, 2),
nums_2 = val.substr(2)
;
I hope this solution helps
var value = form.redoarr.value;
var re = /^\d{4}$/;
var error = '';
var first_two_digits = '';
var last_two_digits = '';
if ( !re.test(value) ) {
error = 'Value must be four numbers';
}
first_two_digits = value.substr(0, 2);
last_two_digits = value.substr(2);
if (Number(first_two_digits) >= 75 || Number(last_two_digits) >= 40) {
error = 'Invalid number provided';
}
if (error) {
alert(error);
return false;
}
Working on "Higher, Lower" function in codeacademy.
can someone please explain why we are using the same argument to invoke the same function inside of the guessMyNumber function?
I was under the impression that I needed to decrement or increment the argument.
Please see the code below.
function guessNumber(number) {
// Prompt the user for a number
guess = prompt("Guess a number between 1 and 100");
// Convert their guess to a number using +
guess = +guess;
// Define base case
if (guess == number) {
return console.log("You got it! The number was " + number);
}
// Define recursive case with a function call
if (guess < number) {
console.log("Higher");
guessNumber(number);
} else {
console.log("Lower");
guessNumber(number);
}
}
// Call the function guessNumber() with an integer for an argument
guessNumber(5);
What is the best practice when counting the number of times an action has been carried out in javascript? for example I have a prompt that asks for a number
var playerGuess = prompt("What is your guess ");
What i would like to do is after 3 attempts end the game with another prompt.
What I am having difficulty with is actually counting the number of inputs
Thanks
I have tried creating a function do count the number of times an input has been made
var guessCount = playerGuess.count;
function limit(playerGuess){
if (guessCount >= 3){
alert("game over");
} else{
alert("carry on");
}
}
totally wrong i know but having a go
Like so:
// Global var to hold number of guesses
var guessCount = 0;
// Function to get the guess
function getGuess() {
// Get a new guess
var guess = prompt('What is your guess ');
// Process guess here, eg:
if (...whatever tests you want to make...) {
// Good guess
alert('Good guess: ' + guess);
} else {
// Bad guess
guessCount += 1;
// Fail out if too many guesses have been tried
if (guessCount >= 3) {
alert('Game over');
return;
}
}
};
Cheers!
You should evaluate the answer you get each time.
If the answer is valid, take the count in another variable and when the count reaches the desired amount take no inputs.
var attempts = 0;
function ask_question(){
if(attempts > 3)
{
// you have played enough!
return;
}
else
{
var playerGuess = prompt("What is your guess ");
if(parseInt(playerGuess) != NaN && playerGuess != '')
{
attempts++;
// do whatever you would like to do with playerGuess
}
}
}
You could do this with a while loop and a variable to store the current iteration. Consider the following, which gives you three chances to guess the "secret" number:
var secretNumber = 42,
youWon = false,
i = 0;
while (i < 3) {
var playerGuess = prompt("What is your guess?");
if (playerGuess == secretNumber){
youWon = true;
break;
}
i++;
}
if (youWon) {
alert("You got it!");
} else {
alert("Sorry, you have no more tries left.");
}
This code loops over and over, incrementing i each time. It asks the question, and checks the answer. If the answer is right, it sets the youWon flag and breaks out of the loop, ending it early. Otherwise, the loop ends naturally after 3 iterations. After the loop is done, the youWon flag is checked to determine if the loop ended because the right answer was given, or if it ended because the number of tries was exhausted.