No results display when running JavaScript - javascript

I am stumped. I am not receiving any errors or undefined errors when running this code just a blank return and then a new command line. I've run it about 100 times in the command prompt and still nothing. I figured after 100 times it should display the "Congratulations message". Can anyone take a look and see what I am missing? Thank you in advance.
//Player Class
function Player(name, weapons) {
this.playerName = name;
this.playerHealth = 10;
this.playerStrength = 2;
this.playerWeapons = weapons;
}
Player.prototype.applyDamage = function(damage) {
this.playerHealth = this.playerHealth - damage;
console.log(this.playerName + " " + "has sustained " + " " + this.playerHealth + " " + "amount of damage.");
}
Player.prototype.isAlive = function() {
if(this.playerHealth > 0)
return true;
else
return false;
}
Player.prototype.attacksWith = function() {
var random = Math.floor(Math.random() * 8);
return (this.weapon[random]);
}
//Minion Class
function Minion(minion, health, strength) {
this.minionName = 'Minion';
this.minionHealth = 5;
this.minionStrength = 2;
}
Minion.prototype.applyDamage = function(damage) {
this.minionHealth = this.minionHealth - damage;
console.log(this.minionName + " " + "has sustained " + " " + this.minionHealth + " " + "amount of damage.");
}
Minion.prototype.isAlive = function() {
if(this.minionHealth > 0)
return true;
else
return false;
}
Minion.prototype.attack = function(playerName) {
playerName.applyDamage(this.minionHealth);
}
//Weapons Class
function Weapons(weapon) {
this.weaponName = weapon;
this.weapondamage = Math.floor(Math.random() * 5) + 1;
}
var weaponsCache = [];
for (var i = 0; i < 8; i++) {
var axe = new Weapons("skullCracker");
var hxfx = new Weapons("Hexaflexagon");
var blade = new Weapons("Balmung");
var mario = new Weapons("cappy");
var fire = new Weapons("Fire Breath");
var staff = new Weapons("Magic Staff");
var hrp = new Weapons("Harpe");
var CobaltWep = new Weapons("Cobalt Rifle");
var w = new Weapons([i]);
weaponsCache[i] = w;
}
var player = [];
var i = 0;
while (i < 8) {
var m = new Player();
player[i] = m;
i++;
}
//Game Class
function Game(players, minions) {
this.players = [];
this.minions = [];
}
function attack(player, minion) {
while (playerName.isAlive() && minionName.isAlive()) {
actualDamage = player.strength * this.damage();
minion.applyDamage(actualDamage);
if (minion.isAlive())
minion.attack(player);
else
break;
}
}
function createMinions() {
var i = 0;
while (i > 20) {
var m = new Minion();
minion[i] = m;
i++;
}
}
function createPlayers() {
var player = []; {
var ph = new Player("Prophetic Hamster", weaponsCache);
var mm = new Player("Mighty Mathematician", weaponsCache);
var sieg = new Player ("Siegfried", weaponsCache);
var bd = new Player ("Blue Dragon", weaponsCache);
var ip = new Player("Iron Professor", weaponsCache)
}
Game.prototype.play = function() {
console.log("Simulating Battle...");
createMinion();
createPlayer();
var i = 0,
count = 0;
while (i < 20) {
if (minions[i].isAlive())
count++;
}
if (count == 20) {
i = 0;
var flag = 0;
while (i < 8) {
if (players[i].isAlive())
flag++;
}
while (count == 20 && flag > 0) {
var randomPlayer, randomMinion;
randomPlayer = Math.floor(Math.random() * 8);
randomMinion = math.floor(Math.random() * 20);
weapon = player.attackWith();
attack(minions);
attack(players);
}
count = 0;
i = 0;
while (i > 20) {
if (minions[i].isAlive())
count++;
}
flag = 0;
i = 0;
while (i < 8) {
if (players[i].isAlive())
flag++;
}
if (flag > count)
console.log("Congratulations!! You have defeated Scarlet Byte");
}
}
}

Related

How do i run animation two, only after animation one has completed?

I understand this question has been answered already, but most of them are in jquery. At the moment function one and function two run at the same time. But how do I alter this code so function two only runs after function one has completed its journey to the top of the screen and back down again?
<html>
<head>
<title>JavaScript Animation</title>
</head>
<body>
<script>
function start() {
animation();
animationone();
}
function animation() {
obj = document.getElementById("jbtext");
obj.style.position = "absolute";
obj.style.bottom = "0px";
w = document.body.clientHeight;
goUp = true;
animateText();
}
var obj, w, goUp;
function animateText() {
var pos = parseInt(obj.style.bottom, 10);
(goUp) ? pos++ : pos--;
obj.style.bottom = pos + "px";
if (pos < 0) {
goUp = true;
}
if (pos > w) {
goUp = false;
}
if (pos < 0) {
return;
}
setTimeout(animateText, 10);
}
document.addEventListener("DOMContentLoaded", start, false);
function animationone() {
obja = document.getElementById("jbtexta");
obja.style.position = "absolute";
obja.style.left = "10px";
obja.style.bottom = "10px";
wtwo = document.body.clientWidth;
goRight = true;
animatesecond();
}
var obja, wtwo, goRight;
function animatesecond() {
var position = parseInt(obja.style.left, 10);
(goRight) ? position++ : position--;
obja.style.left = position + "px";
if (position > wtwo) {
goRight = false;
}
if (position < 0) {
goRight = true;
}
if (position < 0) {
return;
}
setTimeout(animatesecond, 10);
}
</script>
<p id="jbtext"> first function</p>
<p id="jbtexta"> second function</p>
</body>
</html>
You can use promises in javascript. Promises are a block of code that will run asynchronously and return at a later point in time. It "returns" by calling the resolve method which is an argument of the Promise constructor. You can then chain promises together to accomplish what you need.
function animationOne() {
return new Promise(function(resolve) {
// ... do your logic for the first animation here here.
resolve(); // <-- call this when your animation is finished.
})
}
function animationTwo() {
return new Promise(function(resolve) {
// ... do your logic for animation two here.
resolve(); // <-- call this when your animation is finished.
})
}
animationOne().then(function() {
animationTwo();
})
This is just another way of Peter LaBanca's answer.
I do not enjoy using Promises. Instead, I use async and await
function runFirst() {
//animation
}
async function waitThenRun() {
await runFirst();
//second animation
}
waitThenRun();
I just don't enjoy the idea of Promise. The code above runs waitThenRun(). That function then runs runFirst(), but waits until it has been finished to run the rest of the function. Having setTimeout or other ways of delaying code in runFirst means you should use Promise. (Pure JS)
MDN
How about the following script AnimationOneAndTwo? The script uses setInterval to “run” the animations. To use it create an instance using the factory method createInstance. Then when the condition or conditions to end the first animation are true call on the next method of the instance to start the second animation. Then when the condition or conditions to end the second animation are true call on the end method of the instance. The following snippet includes the definition for AnimationOneAndTwo and its application to your situation. For more details on how I created the function please refer to “How to Run One Animation after Another: A Reply to a Question at Stack Overflow”.
<html>
<head>
<title>JavaScript Animation</title>
</head>
<body>
<script>
/***
* AnimationOneAndTwo
* Copyright 2019 John Frederick Chionglo (jfchionglo#yahoo.ca)
***/
function AnimationOneAndTwo(parms) {
this.id = parms.id;
}
AnimationOneAndTwo.objs = [];
AnimationOneAndTwo.createProcessLogic = function(parms) {
var obj;
obj = new AnimationOneAndTwo({id: parms.id});
AnimationOneAndTwo.objs[parms.id] = obj;
if ("animationStepOne" in parms) {}
else {
throw new RangeError("animationStepOne not found in parms.");
}
obj["animationStepOne"] = parms.animationStepOne;
if ("animationStepTwo" in parms) {}
else {
throw new RangeError("animationStepTwo not found in parms.");
}
obj["animationStepTwo"] = parms.animationStepTwo;
if ("speed" in parms) {
obj.msf_0 = parms.speed;
}
return obj;
};
with (AnimationOneAndTwo) {
prototype.ap = window;
prototype.dc = window.document;
prototype.np = 6;
prototype.nt = 4;
prototype.ni = 7;
prototype.no = 3;
prototype.nn = 1;
prototype.nr = 1; (function(ia, pa) {
var str, j;
for (j=0; j<ia.length; j++) {
str = ' prototype.' + 'iE_in_' + ia[j] + ' = function() {\n';
str += ' this.s_in_' + ia[j] + ' = ( this.m_' + pa[j] + ' < 1 ? true : false );\n';
str += '};\n';
eval(str);
}
})([1], [0]);
(function(ia, pa) {
var str, j;
for (j=0; j<ia.length; j++) {
str = ' prototype.' + 'iE_in_' + ia[j] + ' = function() {\n';
str += ' this.s_in_' + ia[j] + ' = ( this.m_' + pa[j] + ' < 1 ? false : true );\n';
str += '};\n';
eval(str);
}
})([0,2,3,4,5,6], [0,2,0,2,5,4]);
(function(ia, pa) {
var str, j;
for (j=0; j<ia.length; j++) {
str = ' prototype.' + 'fE_in_' + ia[j] + ' = function() {\n';
str += ' this.m_' + pa[j] + ' -= 1;\n';
str += '};\n';
eval(str);
}
})([3,4,5,6], [0,2,5,4]);
(function(oa, pa, ka) {
var str, j;
for (j=0; j<oa.length; j++) {
str = ' prototype.' + 'fE_ou_' + oa[j] + ' = function() {\n';
str += ' this.m_' + pa[j] + ' += 1;\n';
str += '};\n';
eval(str);
}
})([0,1,2], [1,3,2]);
(function(ta, ia) {
var str, j, k, h;
for (j=0; j<ta.length; j++) {
str = ' prototype.' + 'iE_T_' + ta[j] + ' = function() {\n';
for (h=0; h<ia[j].length; h++) {
k = ia[j][h];
str += ' this.iE_in_' + k + '();\n';
}
if (ia[j].length<1) {
str += ' this.s_t_' + ta[j] + ' = true;\n';
} else {
str += ' this.s_t_' + ta[j] + ' = this.s_in_' + ia[j][0];
for (k=1; k<ia[j].length; k++)
str += ' && this.s_in_' + ia[j][k];
}
str += ';\n';
str += '};\n';
eval(str);
}
})([0,1,2,3], [[0], [1, 2], [3, 6], [4, 5]]);
(function(ta, ia, oa) {
var str, j, k, h;
for (j=0; j<ta.length; j++) {
str = ' prototype.' + 'fE_T_' + ta[j] + ' = function() {\n';
for (h=0; h<ia[j].length; h++) {
k = ia[j][h];
str += ' this.fE_in_' + k + '();\n';
}
for (h=0; h<oa[j].length; h++) {
k = oa[j][h];
str += ' this.fE_ou_' + k + '();\n';
}
str += '};\n';
eval(str);
}
})([0,1,2,3], [[], [], [3, 6], [4, 5]], [[], [], [2], []]);
(function(parms) {
var str, j, k, h, i;
var ta = parms.ta;
var pad = parms.pad;
var pat = parms.pat;
var tar = parms.tar;
var tad = parms.tad;
var tav = parms.tav;
for (i=0; i<ta.length; i++) {
j = ta[i];
str = ' prototype.' + ' pEv_T_' + j + ' = function() {\n';
str += ' this.fE_T_' + j + '();\n';
for (h=0; h<tar[j].length; h++) {
k = tar[j][h];
str += ' this.iE_T_' + k + '();\n';
}
str += ' };\n';
eval(str);
}
})({
ta: [0,1,2,3],
tar: [[0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3], [1, 3]]
});
prototype.pEv_T_0 = function() {
this.fE_T_0();
this.iE_T_0();
this.iE_T_1();
this.iE_T_2();
this.animationStepOne();
};
prototype.pEv_T_1 = function() {
this.fE_T_1();
this.iE_T_0();
this.iE_T_1();
this.iE_T_2();
this.iE_T_3();
this.animationStepTwo();
};
prototype.ipn = function() {
this.iE_T_0();
this.iE_T_1();
this.iE_T_2();
this.iE_T_3();
};
prototype.im = function() {
var j, h, pa;
for (j=0; j<this.np; j++) {
eval('this.m_' + j + ' = 0');
}
pa = [1,2,3];
for (h=0; h<pa.length; h++) {
j = pa[h];
eval('this.m_' + j + ' = ' + 0);
}
pa = [0,4,5];
for (h=0; h<pa.length; h++) {
j = pa[h];
eval('this.m_' + j + ' = ' + 1);
}
};
prototype.ai_0 = undefined;
prototype.msf_0 = 10;
prototype.mss_0 = 1500;
prototype.ms_0 = prototype.msf_0;
prototype.sp_0 = function() {
if (this.ai_0) { this.ap.clearInterval(this.ai_0); this.ai_0 = undefined; }
};
prototype.st_0 = function() {
if (this.ai_0) { this.sp_0(); }
this.ai_0 = this.ap.setInterval('AnimationOneAndTwo.objs[' + this.id + '].rn_0()', this.ms_0);
};
prototype.rn_0 = function() {
var t;
var et = [];
if (this.s_t_0) {
this.pEv_T_0();
} else if (this.s_t_1) {
this.pEv_T_1();
} else {
if (this.ai_0) {
this.sp_0();
}
}
};
prototype.start = function() {
with (this) {
if (ai_0) { sp_0(); }
im();
ipn();
st_0();
}
};
prototype.next = function() {
if (this.s_t_2) {
this.pEv_T_2();
} else if (this.s_t_3) {
this.pEv_T_3();
}
};
prototype.end = function() {
if (this.s_t_2) {
this.pEv_T_2();
}
if (this.s_t_3) {
this.pEv_T_3();
}
};
}
var aotobj;
function start() {
animation();
animationone();
aotobj = AnimationOneAndTwo.createProcessLogic({
id: 12345
, animationStepOne: animateText
, animationStepTwo: animatesecond
});
aotobj.start();
}
function animation() {
obj = document.getElementById("jbtext");
obj.style.position = "absolute";
obj.style.bottom = "0px";
w = document.body.clientHeight;
goUp = true;
// animateText();
}
var obj, w, goUp;
function animateText() {
var pos = parseInt(obj.style.bottom, 10);
(goUp) ? pos++ : pos--;
obj.style.bottom = pos + "px";
if (pos < 0) {
goUp = true;
}
if (pos > w) {
goUp = false;
}
if (pos < 0) {
aotobj.next();
return;
}
// setTimeout(animateText, 10);
}
document.addEventListener("DOMContentLoaded", start, false);
function animationone() {
obja = document.getElementById("jbtexta");
obja.style.position = "absolute";
obja.style.left = "10px";
obja.style.bottom = "10px";
wtwo = document.body.clientWidth;
goRight = true;
// animatesecond();
}
var obja, wtwo, goRight;
function animatesecond() {
var position = parseInt(obja.style.left, 10);
(goRight) ? position++ : position--;
obja.style.left = position + "px";
if (position > wtwo) {
goRight = false;
}
if (position < 0) {
goRight = true;
}
if (position < 0) {
// AnimationOneAndTwo.objs[12345].end();
aotobj.end();
return;
}
// setTimeout(animatesecond, 10);
}
</script>
<p id="jbtext"> first function</p>
<p id="jbtexta"> second function</p>
</body>
</html>

JS - Error: "Cannot read property of undefined"

I'm attempting to make a genetic algorithm simulation in JavaScript using the P5.JS library, but i'm experiencing some issues. Here's what i have so far:
//var popS = 2;
var popu;
//var balls = [];
var target;
function setup() {
createCanvas(800, 300);
popu = new Population();
target = createVector(width - 15, height / 2);
}
function draw() {
background(50);
popu.run();
var ballsC = 0;
for (var a = 0; a < popu.balls.length; a++) {
if (popu.balls[a].done == true){
ballsC ++;
}
}
if (ballsC >= popu.popS) {
//popu = new Population();
popu.evaluate();
//popu.selection();
}
fill(255, 0, 30);
noStroke();
ellipse(target.x, target.y, 20, 20);
}
function DNA() {
this.genes = [];
this.changes = 7;//random(2, 50);
for (var a = 0; a < this.changes; a++) {
this.genes[a] = random(0, 15);
}
this.crossover = function (pB) {
var newdna = new DNA();
var mid = floor(random(0, this.genes.length));
for (var a = 0; a < this.genes.length; a++) {
if (a < mid) {
newdna.genes[a] = this.genes[a];
}else {
newdna.genes[a] = pB.genes[a];
}
}
return newdna;
}
}
function Population() {
this.balls = [];
this.popS = 50;
this.maxfit = 0;
this.matingpool = [];
for (var a = 0; a < this.popS; a++) {
this.balls[a] = new Ball();
}
this.evaluate = function() {
for (var a = 0; a < this.balls.length; a++) {
this.balls[a].calcF();
if (this.balls[a].fitness > this.maxfit) {
this.maxfit = this.balls[a].fitness;
}
}
this.matingpool = [];
for (var b = 0; b < this.balls.length; b++) {
var n = this.balls[b].fitness * 100;
for (var c = 0; c < n; c++) {
this.matingpool.push(this.balls[c]);
}
}
this.selection();
}
this.selection = function () {
var newBalls = [];
for (var a = 0; a < this.balls.length; a++) {
var parentA = this.matingpool[floor(random(0, this.matingpool.length))];
var parentB = this.matingpool[floor(random(0, this.matingpool.length))];
var child = parentA.dna.crossover(parentB.dna);
newBalls[a] = new Ball(child);
}
this.balls = newBalls;
}
this.run = function() {
for (var a = 0; a < this.balls.length; a++) {
this.balls[a].update();
this.balls[a].checkCol();
this.balls[a].show();
}
}
}
function Ball(dna) {
this.pos = createVector(10, height / 2);
this.speed = createVector(2, 2.5);
this.mul = -1;
this.time = 0;
this.a = 0;
if (dna) {
this.dna = dna;
} else {
this.dna = new DNA();
}
this.done = false;
this.fitness = 0;
this.reached;
this.update = function() {
if (this.done == false) {
if (this.time >= this.dna.genes[this.a]) {
this.a++;
this.time = 0;
this.mul *= -1;
}
this.speed.set(2, 2.5 * this.mul);
this.pos.add(this.speed);
}
}
this.show = function() {
this.time += 0.1;
fill(255, 70);
noStroke();
ellipse(this.pos.x, this.pos.y, 10, 10);
}
this.checkCol = function() {
if (this.pos.y > height || this.pos.y < 0 || this.pos.x > width) {
//print("col");
this.done = true;
}
if (dist(this.pos.x, this.pos.y, target.x, target.y) <= (10 / 2) + (20 / 2)) {
//print("done!");
this.done = true;
this.reached = true;
}
}
this.calcF = function() {
var a = dist(this.pos.x, this.pos.y, target.x, target.y);
var b = this.dna.genes.length;
var c = 0;
if (this.reached){
c = 1;
}
this.fitness = map(map(a, 0, width, 1, 0) + map(b, 2, 50, 1, 0) + c, 0, 3, 0, 1);
}
}
This is the most essential part of the code:
var popu;
function setup() {
createCanvas(800, 300);
popu = new Population();
}
function draw() {
background(50);
//popu = new Population();
popu.evaluate();
//popu.selection();
}
function DNA() {
this.genes = [];
this.changes = 7; //random(2, 50);
for (var a = 0; a < this.changes; a++) {
this.genes[a] = random(0, 15);
}
this.crossover = function(pB) {
var newdna = new DNA();
var mid = floor(random(0, this.genes.length));
for (var a = 0; a < this.genes.length; a++) {
if (a < mid) {
newdna.genes[a] = this.genes[a];
} else {
newdna.genes[a] = pB.genes[a];
}
}
return newdna;
}
}
function Population() {
this.balls = [];
this.popS = 50;
this.maxfit = 0;
this.matingpool = [];
for (var a = 0; a < this.popS; a++) {
this.balls[a] = new Ball();
}
this.evaluate = function() {
this.matingpool = [];
for (var b = 0; b < this.balls.length; b++) {
var n = this.balls[b].fitness * 100;
for (var c = 0; c < n; c++) {
this.matingpool.push(this.balls[c]);
}
}
this.selection();
}
this.selection = function() {
var newBalls = [];
for (var a = 0; a < this.balls.length; a++) {
var parentA = this.matingpool[floor(random(0, this.matingpool.length))];
var parentB = this.matingpool[floor(random(0, this.matingpool.length))];
var child = parentA.dna.crossover(parentB.dna);
newBalls[a] = new Ball(child);
}
this.balls = newBalls;
}
}
function Ball(dna) {
this.pos = createVector(10, height / 2);
this.speed = createVector(2, 2.5);
this.mul = -1;
this.time = 0;
this.a = 0;
if (dna) {
this.dna = dna;
} else {
this.dna = new DNA();
}
this.done = false;
this.fitness = 0;
this.reached;
}
So whenever it gets to here:
this.selection = function () {
var newBalls = [];
for (var a = 0; a < this.balls.length; a++) {
var parentA = random(this.matingpool);
var parentB = random(this.matingpool);
var child = parentA.dna.crossover(parentB.dna);
newBalls[a] = new Ball(child);
}
this.balls = newBalls;
}
i get the error: "Cannot read property 'dna' of undefined", why on earth is this happening?? When i use the debugger in chrome i can clearly see that matingpool has 2000 elements but when i try to get a random one it returns "undefined".
var parentA = random(this.matingpool);
var parentB = random(this.matingpool);
The weird thing is that parentB works, but parentA dosn't.
Any help is much appreciated. Entire code running here: http://codepen.io/felipe_mare/pen/bgOYMN
If it helps, i sometimes get the error: "Cannot read property '0' of undefined" instead, at line 138
this.update = function() {
if (this.done == false) {
//line 138
if (this.time >= this.dna.genes[this.a]) {
//line 138
this.a++;
this.time = 0;
this.mul *= -1;
}
this.speed.set(2, 2.5 * this.mul);
this.pos.add(this.speed);
}
}
In the future, please please please try to narrow your questions down to an MCVE. I understand that this was a complicated problem to debug, but you'll have much better luck if you try to narrow your problem down to a minimal (under 20 lines) example. Most of the time, you'll end up finding your error in the process of creating the MCVE.
But your problem is actually when you create the matingpool array, here:
this.matingpool = [];
for (var b = 0; b < this.balls.length; b++) {
var n = this.balls[b].fitness * 100;
for (var c = 0; c < n; c++) {
this.matingpool.push(this.balls[c]);
}
}
If I add a print statement inside the inner for loop, like this:
this.matingpool = [];
for (var b = 0; b < this.balls.length; b++) {
var n = this.balls[b].fitness * 100;
for (var c = 0; c < n; c++) {
console.log("pushing: " + this.balls[c]);
this.matingpool.push(this.balls[c]);
}
}
Then I see that you're pushing undefined into the array a bunch of times:
(1178) pushing: [object Object]
(3) pushing: undefined
(482) pushing: [object Object]
(3) pushing: undefined
(216) pushing: [object Object]
Then you choose randomly from this array, which is why your error shows up in random places in your code.
You're going to have to debug this further to figure out why that's happening- it seems weird that you're looping based on a fitness instead of an array length, but I don't really understand the code well enough to be sure. In any case, hopefully this gets you on the right track.

getting html input value inside javascript class

i am new to javascript and im making a BMI calculator. im making a class in javascript to produce the calculations. currently users could input their height (in feet and inches) and weight. when i run a method within my class. it keeps saying this.feet = null instead of grabbing the value from the input. my javascript code is below. result() is in my html for the submit button.
function calculator(feet,inches,weight) {
this.feet = feet.value;
this.inches = inches.value;
this.weight = weight.value;
this.validateInput = function() {
var errors = [];
if(isNaN(this.feet) || this.feet < 0) {
errors.push("Feet");
}
else {
return this.feet
};
if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) {
errors.push("Inches")
}
else {
return this.inches;
};
if(isNaN(this.weight) || this.weight < 0) {
errors.push("Weight");
}
else {
return this.weight
}
};
this.inchesConverter = function() {
this.feet = parseFloat(feet);
this.inches = parseFloat(inches);
return parseInt(this.feet*12+this.inches);
};
this.bmi = function() {
var height = this.inchesConverter();
var validater = this.validateInput();
for(r = 0; r < errors.length; r++){
if(errors.length > 0) {
return errors[r] + " must be a valid positive number.";
}
else {
parseFloat((validateWeight * 703) / (Math.pow(height, 2))).toFixed(1);
}
}
};
};
var getWeight = document.getElementById('txtWeight');
var getFeet = document.getElementById('txtHeightFeet');
var getInches = document.getElementById('txtHeightInches');
var test = new calculator(getFeet, getInches, getWeight);
function result() {
document.getElementById("lblBMI").innerHTML(test.bmi());
}
Instead of assigning feet.value to this.feet try assigning feet.getAttribute('value')
If you console.log(feet) does it show the proper DOM element?
There is no need to declare the variables with "this."
function calculator(paraFeet,paraInches,paraWeight) {
var feet = paraFeet.value;
var inches = paraInches.value;
var weight = paraWeight.value;
...
you can now remove "this." from every of these variables inside your function
Every browser has JavaScript console on which you can debug your code.
I have some fun to fix it here or there but also you should try it yourself.
Anyway here it is:
function calculator(weight, feet, inches) {
this.weight = weight;
this.feet = feet;
this.inches = inches;
this.validateInput = function() {
var errors = [];
if (!this.validNumber(this.weight, 1000)) {
errors.push("Invalid weight.");
}
if (!this.validNumber(this.feet, 10)) {
errors.push("Invalid hight in feet.");
}
if (!this.validNumber(this.inches, 11)) {
errors.push("Invalid hight in inches.")
}
return errors;
};
this.validNumber = function(num, max) {
if (num.length > 0 && !isNaN(num)) {
var number = parseInt(num);
return number > 0 && number < max + 1;
}
return false;
}
this.displayErrors = function(errors) {
var html = "";
for (error of errors)
html += error + "<br/>";
return html;
};
this.inchesConverter = function() {
var feet = parseInt(this.feet);
var inches = parseInt(this.inches);
return feet * 12 + inches;
};
this.bmi = function() {
var errors = this.validateInput();
if (errors.length > 0) {
return this.displayErrors(errors);
}
var height = this.inchesConverter();
return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1);
};
};
function result() {
var getWeight = document.getElementById('txtWeight').value;
var getFeet = document.getElementById('txtHeightFeet').value;
var getInches = document.getElementById('txtHeightInches').value;
var test = new calculator(getWeight, getFeet, getInches);
document.getElementById("lblBMI").innerHTML = test.bmi();
return false;
}
<span>
<label>Weight</label>
<input id="txtWeight">
</span>
<span>
<label>HeightFeet</label>
<input id="txtHeightFeet">
</span>
<span>
<label>HeightInches</label>
<input id="txtHeightInches">
</span>
<button id='run' onClick="return result();">Calculate</button>
<div id="lblBMI"></div>
Figured out what my issue was. The problem arose from my for loop. Working code is posted below!
function calculator(feet,inches,weight) {
this.feet = feet.value;
this.inches = inches.value;
this.weight = weight.value;
this.validateInput = function() {
var errors = [];
if(isNaN(this.feet) || this.feet < 0 || this.feet == "") {
errors.push("feet");
};
if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) {
errors.push("inches")
};
if(isNaN(this.weight) || this.weight < 0 || this.weight == "") {
errors.push("weight");
};
return errors;
console.log(errors);
};
this.inchesConverter = function() {
var parseFeet = parseFloat(this.feet);
var parseInches = parseFloat(this.inches);
return parseInt(parseFeet*12+parseInches);
};
this.bmi = function() {
var height = this.inchesConverter();
var errors = this.validateInput();
if(errors.length > 0) {
for(r = 0; r < errors.length; r++){
return "Please enter a correct number for " + errors[r];
};
}
else {
return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1);
};
};
};
function result(){
var getWeight = document.getElementById('txtWeight');
var getFeet = document.getElementById('txtHeightFeet');
var getInches = document.getElementById('txtHeightInches');
var test = new calculator(getFeet, getInches, getWeight);
document.getElementById("lblBMI").innerHTML = test.bmi();
};

How to switch two letters in a string

var dkey = ""
function changekey(decryptionkey){
dkey = decryptionkey
var Ranint = Math.floor(Math.random() * 25) + 1
var Ranint2 = Math.floor(Math.random() * 25) + 1
if(Ranint===Ranint2){
Ranint2+=1
if(Ranint2>25){
Ranint2-=3
}
}
key = key.replace(key.charAt(Ranint),key.charAt(Ranint2))
}
changekey(key)
alert(key)
Say Ranint = 1 and Ranint2 = 2 then key would be
"BBCDEFGHIJKLMNOPQRSTUVWXYZ"
My question is how I would change the code for the key to result in
"BACDEFGHIJKLMNOPQRSTUVWXYZ"
String.prototype.setCharAt = function(index,chr) {
if(index > this.length-1) return str;
return this.substr(0,index) + chr + this.substr(index+1);
}
var dkey = "";
function changekey(decryptionkey){
dkey = decryptionkey;
var Ranint = Math.floor(Math.random() * 25) + 1;
var Ranint2 = Math.floor(Math.random() * 25) + 1;
if(Ranint===Ranint2){
Ranint2+=1;
if(Ranint2>25){
Ranint2-=3;
}
}
var firstChar = dkey.charAt(Ranint);
var secondChar = dkey.charAt(Ranint2);
dkey = dkey.setCharAt(Ranint2, firstChar);
dkey = dkey.setCharAt(Ranint, secondChar);
return dkey;
}
alert(changekey("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
The DEMO
This is just an alternative could be worth to consider, to find the right one:
var myStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function switchChar(str)
{
var randomA = getExclusiveRandom(str);
var randomB = getExclusiveRandom(str, randomA);
var replaceA = str[randomA];
var replaceB = str[randomB];
str = str.split("");
str[randomA] = "["+replaceB+"]";
str[randomB] = "["+replaceA+"]";
return str.join("");
}
function getExclusiveRandom(str, exclude)
{
var res = Math.floor(Math.random() * str.length) + 1;
if(!exclude)
{
return res;
}
else
{
if(res === exclude)
{
res = getExclusiveRandom(str, exclude);
}
return res;
}
}
console.info(switchChar(myStr));

how to I get rid of undefined(s) and the other problems in my code?

I've tried this a thousand different ways in a thousand different times and my JS code won't come out the way I want it. When I run it in the Mozilla scratchpad, I get "userHand is undefined" and the second printHand shows as undefined, too. Could someone show me where are the errors in my blackjack game?
function Card (s, n) {
var suit = s;
var number = n;
this.getNumber = function () {
return number;
};
this.getSuit = function () {
return suit;
};
this.getValue = function () {
if (number > 10) {
return 10;
} else if (number === 1) {
return 11;
} else {
return number;
}
};
}
var cardNames = {1:"Ace", 2:"2", 3:"3", 4:"4", 5:"5", 6:"6", 7:"7", 8:"8", 9:"9", 10:"10", 11:"Joker", 12:"Queen", 13:"King"};
var suitNames = {1:"Clubs", 2:"Diamonds", 3:"Hearts", 4:"Spades"};
var deal = function () {
var s = Math.floor(Math.random() * 4 + 1);
var n = Math.floor(Math.random() * 13 + 1);
return new Card(s, n);
};
function Hand(){
var cards = [];
cards.push(deal());
cards.push(deal());
this.getHand = function () {
return cards;
};
this.score = function () {
var score;
for (i = 0; i < cards.length; i++) {
score = score + cards[i].getValue();
}
for (i = 0; i < cards.length; i++) {
if (score > 21 && cards[i].getValue() === 11) {
score = score - 10;
}
} return score;
};
this.printHand = function () {
for (i = 0; i < cards.length; i++) {
var hand;
if (i === 0) {
hand = cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
} else {
hand = hand + " and a " + cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
}
} alert(hand);
};
this.hitMe = function () {
cards.push(deal());
};
}
var playAsDealer = function () {
var playDealer = new Hand();
while (playDealer.score() < 17) {
playDealer.hitMe();
}
this.printHand = function () {
return playDealer.printHand();
};
this.score = function () {
return playDealer.score();
};
};
var playAsUser = function () {
var playUser = new Hand();
this.printHand = function () {
return playUser.printHand();
};
this.score = function () {
return playUser.score();
};
var decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
for (i = 0; decision !== false; i++) {
playUser.hitMe();
decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
}
};
var declareWinner = function (userHand, dealerHand) {
if ((userHand.score < dealerHand.score) || userHand.score > 21) {
return "You lose.";
} else if (userHand.score > dealerHand.score) {
return "You win.";
} else {
return "You tied.";
}
};
var playGame = function () {
var user = playAsUser();
var dealer = playAsDealer();
declareWinner(user, dealer);
console.log("User got " + user.printHand());
console.log("Dealer got " + dealer.printHand());
};
playGame();
You aren't returning nothing on printHand()
I just added the return statement and worked. See this fiddle
this.printHand = function () {
for (i = 0; i < cards.length; i++) {
var hand;
if (i === 0) {
hand = cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
} else {
hand = hand + " and a " + cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
}
}
//alert(hand); //remove this alert
return hand; // <----- solution
};

Categories