(note this is similar to but not the same as the question I asked moments ago - the solution to that question was to add the brackets when calling Math.Random)
At the bottom of the code below, I'm dealing out two hands of blackjack myhand and yourhand and then logging the hands to the console
"I scored a "+myHand.score()+" and you scored a "+ yourHand.score());
However, the result I'm getting is
I scored NaN and you scored a NaN
Originally, the getValue method in the Card constructor was passed a parameter called card but the instructions for building the Hand constructor said to call getValue without passing a parameter
this.card1.getValue();
so I changed the getValue method to take the var number (which is in the Card constructor)
anyways, to make a long story short, whatever i do, it's printing out
I scored NaN and you scored a NaN
and I'm not sure exactly where I'm going wrong.
// Make your card constructor again here, but make sure to use private
// variables!
function Card(num, suit){
var number = num;
var suits = suit;
this.getSuit = function(){
return suits;
};
this.getNumber = function(){
return number;
};
this.getValue = function(number){
if (number > 10){
return 10;
}else if (number === 1){
return 11;
}else{
return number;
}
};
}
function Hand(){
this.card1 = deal();
this.card2 = deal();
this.score = function(){
var score1 = this.card1.getValue();
var score2 = this.card2.getValue();
return score1 + score2;
};
}
// Make a deal function here. It should return a new card with a suit
// that is a random number from 1 to 4, and a number that is a random
// number between 1 and 13
var deal = function(){
var suit = Math.floor(Math.random() * 4 + 1);
var number = Math.floor(Math.random() * 13 + 1);
return new Card(number, suit);
};
// examples of the deal function in action
var myHand = new Hand();
var yourHand = new Hand();
console.log("I scored a "+myHand.score()+" and you scored a "+ yourHand.score());
Your getValue function is wrong. It should be:
this.getValue = function() {
if( this.number>10) return 10;
if( this.number==1) return 11;
return this.number;
}
A hint that something was wrong is that you are calling this.card1.getValue() with no arguments, whereas you defined this.getValue(number) with an argument.
When you address card.getValue() it requires some input
this.getValue = function(number){
if (number > 10){
return 10;
}else if (number === 1){
return 11;
}else{
return number;
}
};
The function doest not return anything, resulting in a NaN.
To solve this, use this.number instead
Your get value function accepts a number argument
this.getValue = function(number)
But you aren't passing in the value here:
var score1 = this.card1.getValue();
var score2 = this.card2.getValue();
Related
I am very new to JavaScript and I'm sure this question has been answered quite a bit, but when I search my question I don't seem to find an answer (or one that I actually understand :D)
Currently, I'm trying to create a tool to help kids with there multiplication facts and I'm having trouble getting the program to generate new random numbers.
var r1 = Math.floor(Math.random() * 13);
var r2 = Math.floor(Math.random() * 13);
function start() {
println("Welcome to the multipilcation helper! ");
var num = readLine("Pick a number you want to practice or type 'random'!");
var ques = readLine("How many questions do you want?");
if (num == "random") {
for (var i = 0; i < ques; i++) {
var answer = r1 * r2;
println(r1 + "*" + r2);
var check = readLine("what is the answer");
if (check == answer) {
println("thats correct!");
} else {
println("thats wrong! ");
}
}
}
}
The problem is that my variables seem to pick a random number as soon as the script starts and stick with it instead of giving me a new random number.
Can anyone help me out and tell me how to get a new random number every time the variable is called?
Simply create yourself a method like the one below and use it like r() to get a new random number every call.
function r() {
return Math.floor(Math.random() * 13);
}
console.log(r());
console.log(r());
console.log(r());
In your loop you should be reassigning the random numbers so that they are reassigned every iteration of the loop. Otherwise they stay static to the value you give them at the top.
Also, you should use triple equals in Javascript when checking for equality as it is best practice.
function start() {
console.log("Welcome to the multipilcation helper! ");
var num = prompt("Pick a number you want to practice or type 'random'!");
var ques = prompt("How many questions do you want?");
if (num == "random") {
for (var i = 0; i < ques; i++) {
var r1 = Math.floor(Math.random() * 13);
var r2 = Math.floor(Math.random() * 13);
var answer = r1 * r2;
console.log(r1 + "*" + r2);
var check = prompt("what is the answer");
if (check == answer) {
console.log("thats correct!");
} else {
console.log("thats wrong! ");
}
}
}
}
start()
You random numbers are being static at the moment. They need to be called again. Move your r1 and r2 assignments inside the for.
I don't have enough reputation to comment, but will update the answer
if you explain it with more details.
You need to put the random call in a function in order for it to create a new number each time. When you assign it directly to a variable as you have, it only runs once and stores that value in the variable.
// pick a number between 0 and 13
var random = function() {
return Math.floor(Math.random() * 13);
}
function start(){
for(var i = 0; i < 15; i++){
// call random function for each number and store in a var
var number1 = random();
var number2 = random();
var answer = number1 * number2;
console.log('equation:', number1 + '*' + number2);
console.log('answer:', answer);
}
}
// call the start function
start()
I'm just writing a very simple function in javascript to calculate a factorial. I understand that in javascript you can assign a function to a variable.
So I have tried this on an online compiler (https://repl.it/languages/javascript) and this is what my code looks like
var mynum = prompt("Enter a number", "<enter a number>");
var answer;
if (isNaN(mynum)){
console.log(mynum +" is not a number");
}
else{
console.log("You entered "+mynum);
answer = function (mynum){
var i = mynum-1;
var temp = mynum;
while(i>0){
temp = temp*i;
i--;
}
return temp;
};
console.log("the factorial of "+mynum+" is "+answer);
}
But when I run this the output keeps including the whole function as "answer"
You entered 23
the factorial of 23 is function (mynum) {var _loopStart = Date.now(),_loopIt = 0;
var i = mynum - 1;
var temp = mynum;setTimeout(function () {_loopStart = Infinity;});
while (i > 0) {if (++_loopIt > 5000 && Date.now() - _loopStart > 150) throw new RangeError("Potential infinite loop. You can disable this from settings.");
temp = temp * i;
i--;
}
return temp;
}
However i don't have this issue when i create the function and then call it separately (something like answer = function(mynum).
Can anyone please let me know why this is happening?
Thanks!
Assigning a function to a variable is different from assigning its evaluation.
In your case, you have two solutions available :
Make an effective call to your assigned function at logging time:
console.log("the factorial of "+mynum+" is "+answer(mynum));
Make an effective call to your assigned function at assignation time:
answer = (function (mynum){
var i = mynum-1;
var temp = mynum;
while(i > 0) {
temp = temp*i;
i--;
}
return temp;
}(mynum));
Both solutions are quite equivalent for your specific situation.
Why?
Because declaring a function like so:
var func = function () {
console.log("Hello!");
};
Or like so:
function func () {
console.log("Hello!");
};
Has little difference
As pointed out, you have to call it as a function.
var mynum = prompt("Enter a number", "<enter a number>");
var answer;
if (isNaN(mynum)){
console.log(mynum +" is not a number");
}
else{
console.log("You entered "+mynum);
answer = function (mynum){
var i = mynum-1;
var temp = mynum;
while(i>0){
temp = temp*i;
i--;
}
return temp;
};
console.log("the factorial of "+mynum+" is "+answer (mynum));
}
Alternatively, you could use IIEF(mmediately invoked function expression):
var mynum = prompt("Enter a number", "<enter a number>");
var answer;
if (isNaN(mynum)){
console.log(mynum +" is not a number");
}
else{
console.log("You entered "+mynum);
answer = (function (mynum){
var i = mynum-1;
var temp = mynum;
while(i>0){
temp = temp*i;
i--;
}
return temp;
})(mynum);
console.log("the factorial of "+mynum+" is "+answer);
}
Note that I've added a parenthesis around your function and passed in arguments. That's how you can immediately invoke functions.
When you return a function in javascript such as answer(). You must call it as such.
console.log("the factorial of "+mynum+" is "+answer(mynum));
You need to use the function that you wrote by calling it i.e
function add (a,b) {
return a + b;
}
add(1,2);
This is my current assignment :
Add a method that will increase the value of one of the numeric properties.
Add a method that will decrease the value of the same numeric property.
Create a for loop after creating an instance of the character. The loop will iterate 100 times.
Inside the loop call one of the methods based on a random number from zero to 3. Using a switch statement, if the value is 0 then call the method that losses; 1 don’t call anything; 2 call the method that gains.
Here is my current coding. I know I'm doing something wrong. I just can't figure out what I am doing wrong with the switch statement.
var BR = "<br />";
function person(name, sandwiches) {
this.name = name;
this.sandwiches = sandwiches;
function jump() {
var text = " leaps over an obstacle.";
return fname + text;
}
function run() {
var text = " runs as fast as they can";
return fname + text;
}
function dodge() {
var attack = math.random();
var att = math.round(attack);
var defense = math.random();
var def = math.round(defense);
if(att > def) {
return "You missed";
}
else {
return "You dodged";
}
}
function date() {
var today = new Date();
return today.toDateString();
}
function shout() {
var word = "Oh no";
return word.toUpperCase();
}
this.addSandwich = function (sandwiches) {
sandwiches = sandwiches + 1;
return sandwiches;
};
this.loseSandwich = function (sandwiches) {
sandwiches = sandwiches - 1;
return sandwiches;
};
}
var character = new person("Jerry", 1);
for(i=0; i < 100; i++) {
var random = Math.floor(Math.random() * 3);
switch(random) {
case 0:
character.loseSandwich(character.sandwiches);
console.log(sandwiches);
break;
case 1:
break;
case 2:
character.addSandwich(character.sandwiches);
break;
}
}
document.write("Name: " + character.name + BR);
document.write("Sandwiches: " + character.sandwiches + BR);
Math.floor(Math.random() * 3) is not what you want.
You want something like Math.random() % 3 to get 0, 1, or 2 every single time
Not sure if this is your problem, but it is at least one of them;
In a few places you have a lowercase math, for example:
function dodge() {
var attack = math.random();
JavaScript is case-sensitive, and it should be Math.random() not math.random()
Another issue is that these functions:
this.addSandwich = function (sandwiches) {
sandwiches = sandwiches + 1;
return sandwiches;
};
do not change the number of sandwiches. You get in a value of sandwiches, add or subtract 1, then return that changed number, but never use the returned result.
You are only changing the value of the variable that was passed in, not changing the number of sandwiches on the instance of the person.
Note that this.sandwiches (the variable on the instance of a person) is not the same variable as sandwiches (the function argument)
I dont think there is any reason to pass the number of sandwiches into those functions, and they could just do:
this.addSandwich = function () {
this.sandwiches = this.sandwiches + 1;
};
or more simply:
this.addSandwich = function () {
this.sandwiches++;
};
Another problem here:
character.loseSandwich(character.sandwiches);
console.log(sandwiches);
The console.log statement is trying to log sandwiches but that is not a variable at that point. You probably wanted console.log(character.sandwiches); However this wouldn't cause an exception, it would just always log undefined.
I am making a quick game where a player damages a enemy npc. I have a function below that does the calculation for the damage, but I can't get the console log to say i'm doing "X" amount of damage. What am I doing wrong? Instead, it just pulls up the function statement, but I want it to give me the functions value!
var damage = function() {
return Math.floor(Math.random() * 5 + 1);
};
I'm calling my function in another code properly, but when I try to console log the damage in that other code, I get a error.
function attackButton() {
darkwarrior.hp = darkwarrior.hp - damage();
console.log(darkwarrior.hp);
console.log(damage);
If you run console.log(damage()); you will get the "X" amount of damage instead of the function statement. So you could change attackButton() function to be:
function attackButton() {
var damageDealt = damage();
darkwarrior.hp = darkwarrior.hp - damageDealt;
console.log(darkwarrior.hp);
console.log(damageDealt);
I'm not sure to understand, you want to log the result? If so, you can do that:
var damage = function() {
return Math.floor(Math.random() * 5 + 1);
};
console.log(damage());
EDIT:
you forgot the (). + the value will not be the same if you don't put it in a variable:
function attackButton() {
var amount = damage()
darkwarrior.hp = darkwarrior.hp - amount;
console.log(darkwarrior.hp);
console.log(amount);
}
you just have to use an expression to assign the value to a variable. Then log it. Then return it.
var damage = function() {
var num = Math.floor(Math.random() * 5 + 1);
console.log(num);
return num;
};
damage();
Something like this should work for you.
function NPC(startingLife, name) {
this.hp = startingLife;
this.name = name
}
NPC.prototype.takeDamage = function(amount) {
this.hp = Math.max(this.hp - amount, 0);
if (this.hp == 0) {
console.log(this.name + " Dies");
}
return this.hp;
};
function damage() {
return Math.floor(Math.random() * 5 + 1);
}
var darkwarrior = new NPC(4, 'Dark Warrior');
function attackButton() {
var amount = damage();
darkwarrior.takeDamage(amount);
console.log("Dark Warrior took " + amount + " points of damage");
}
document.querySelector('#attack-button').addEventListener("click", attackButton);
<button id="attack-button">ATTACK!</button>
You are just returning the value instead of printing it. You should instead replace return with console.log(
I have a strange problem. I have to implement a function count(s) which inverts the getNumberSequence function that I have already create. (i.e: count(getNumberSequence(x)) == x, for all integers x > 0). I have my function and I have also the logic to resolve the problem but I don't know how to do it. In my case I want to call the previous string of ordered numbers, split them and call the last number. The problem is, how can I call the return of another method? Here are my codes:
function getNumberSequence(number) {
var result = "";
if (number <= 0) {
return result;
} else {
var first = true;
for (i = 1; i <= number; i++) {
if (first) {
first = false;
} else {
result += ", ";
}
result += i;
}
}
return result
}
Basically I need the variable result in this case to call it in the other function.
function count(s) {
var d = s. split(', ');
return d[-1];
}
I know that the second code is wrong but I don't know how to fix it. I have implemented a test that is:
test( "Count", function() {
for (i = 1; i<10000; i = i + 10) {
equal(count(getNumberSequence(i)) , i, "count(getNumberSequence(" +i + ")) should return " + i);
}
I know that the answer could be stupid but I started javascript yesterday for the first time. Hope you can help me. Thanks to everyone
If I understand you correctly you want to pass a number, say 10, into the first function and have that return a string of numbers up to 10 and then for count to read that string and return 10 (as an integer) again? This will do the trick. It takes the string, splits it, and pops out the last number converting it to an integer before it returns it.
function count(seq) {
return parseInt(seq.split(', ').pop(), 10);
}
I could rewrite it like this:
function count(seq) {
// create an array
var arr = seq.split(', ');
// grab the last element (a string)
var lastElement = arr.pop();
// convert the string to an integer
var convertedInteger = parseInt(lastElement, 10);
// return the integer
return convertedInteger;
}
If you wanted to use reverse and grab the first element, do this:
function count(seq) {
return parseInt(seq.split(', ').reverse()[0], 10);
}
Or use shift which does the same thing:
function count(seq) {
return parseInt(seq.split(', ').reverse().shift(), 10);
}
DEMO