I'm trying to create a little text based rpg to put in practice what i learned of javascript. I tried two approaches, one is working and the other one isn't it, and I want to know why.
In the first one, I created an object "monster" with a method that sets all the properties of each monster (hit points, attack points, etc). The problem with this it's i have to write the properties one by one, and it makes the code too long for my taste.
/* Write JavaScript here */
/* Write JavaScript here */
$(document).ready(function() {
var hero = {
hitPoints: 13,
armorClass: 10,
attackBonus: 1,
weaponDamage: 7,
heroStats: function() {
return "Hero" + "<br/>" +
"Hit Points: " + this.hitPoints + "<br/>" +
"Armor Class: " + this.armorClass + "<br/>" +
"Attack Bonus: " + this.attackBonus + "<br/>" +
"Weapon Damage: " + this.weaponDamage;
},
alive: true
};
var monster = {
name: "",
hitPoints: 0,
armorClass: 0,
attackBonus: 0,
weaponDamage: 0,
monsterStats: function() {
return this.name + "<br/>" +
"Hit Points: " + this.hitPoints + "<br/>" +
"Armor Class: " + this.armorClass + "<br/>" +
"Attack Bonus: " + this.attackBonus + "<br/>" +
"Weapon Damage: " + this.weaponDamage;
},
monsterSelected: false,
selectMonster: function() {
if (this.monsterSelected === false) {
switch (Math.floor(Math.random() * 2) + 1) {
case 1:
this.name = "Werewolf";
this.hitPoints = 20;
this.armorClass = 8;
this.attackBonus = 4;
this.weaponDamage = 3;
this.monsterSelected = true;
break;
case 2:
this.name = "Goblin";
this.hitPoints = 15;
this.armorClass = 10;
this.attackBonus = 4;
this.weaponDamage = 3;
this.monsterSelected = true;
break;
}
}
},
alive: true
};
monster.selectMonster();
$(".hero_info").html(hero.heroStats());
$(".monster_info").html(monster.monsterStats());
$("button").click(function() {
battle(monster);
});
function battle(actualmonster) {
if (actualmonster.alive === false) {
actualmonster.monsterSelected = false;
actualmonster.selectMonster();
$(".monster_info").html(actualmonster.monsterStats());
$(".battle_info").html("");
actualmonster.alive = true;
} else {
var d20 = Math.floor(Math.random() * 20) + 1;
var d_wp = Math.floor(Math.random() * hero.weaponDamage) + 1;
if (d20 + hero.attackBonus > actualmonster.armorClass) {
$(".battle_info").html("You attack!: d20+" + hero.attackBonus + ": " + (d20 + hero.attackBonus) + " vs AC " + actualmonster.armorClass + "<br/>" + "You hit!: d" + hero.weaponDamage + ": " + d_wp);
actualmonster.hitPoints = actualmonster.hitPoints - d_wp;
$(".monster_info").html(actualmonster.monsterStats());
} else {
$(".battle_info").html("You miss!: d20+" + hero.attackBonus + ": " + (d20 + hero.attackBonus) + " vs AC " + actualmonster.armorClass);
}
if (actualmonster.hitPoints <= 0) {
actualmonster.hitPoints = 0;
$(".monster_info").html(actualmonster.monsterStats());
$(".battle_info").html("You killed the monster!");
actualmonster.alive = false;
} else {
var d20_m = Math.floor(Math.random() * 20) + 1;
var d_wp_m = Math.floor(Math.random() * monster.weaponDamage) + 1;
if (d20_m + actualmonster.attackBonus > hero.armorClass) {
$(".battle_info").append("<br/>Monster attacks you!: d20+" + actualmonster.attackBonus + ": " + (d20_m + actualmonster.attackBonus) + " vs AC " + hero.armorClass + "<br/>" + "Monster hits you!: d" + actualmonster.weaponDamage + ": " + d_wp_m);
hero.hitPoints = hero.hitPoints - d_wp_m;
$(".hero_info").html(hero.heroStats());
} else {
$(".battle_info").append("<br/>Monster miss!: d20+" + hero.attackBonus + ": " + (d20_m + monster.attackBonus) + " vs AC " + hero.armorClass);
}
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p class="monster_info"></p>
<p class="battle_info"></p>
<p class="hero_info"></p>
<button type="button">Attack</button>
</body>
In the second one, instead of creating and object "monster", i make a constructor, so i could define the monsters in a shorter and simplier way (for example: var phantom = new monster (prop1, prop2, prop3...)). The issue comes when i tried select a random monster for each battle. I tried a lot of things, but the problem remains the same: if a create a random function to select the monsters, this works every time a click the attack button, making a mess. This is driven me crazy, and i have no idea what to do. Any suggestions? Thanks in advance.
$(document).ready(function() {
var hero = {
hitPoints: 13,
armorClass: 10,
attackBonus: 1,
weaponDamage: 7,
heroStats: function() {
return "Hero" + "<br/>" +
"Hit Points: " + this.hitPoints + "<br/>" +
"Armor Class: " + this.armorClass + "<br/>" +
"Attack Bonus: " + this.attackBonus + "<br/>" +
"Weapon Damage: " + this.weaponDamage;
},
alive: true
};
function monster(name, hitpoints, armorclass, attackbonus, weapondamage) {
this.name = name;
this.hitPoints = hitpoints;
this.armorClass = armorclass;
this.attackBonus = attackbonus;
this.weaponDamage = weapondamage;
this.monsterStats = function() {
return this.name + "<br/>" +
"Hit Points: " + this.hitPoints + "<br/>" +
"Armor Class: " + this.armorClass + "<br/>" +
"Attack Bonus: " + this.attackBonus + "<br/>" +
"Weapon Damage: " + this.weaponDamage;
},
this.selected = false;
this.alive = true;
}
function selectMonster() {
var werewolf = new monster("Werewolf", 5, 4, 4, 3);
var goblin = new monster("Goblin", 15, 4, 4, 3);
switch (Math.floor(Math.random() * 2) + 1) {
case 1:
if (werewolf.selected === false) {
werewolf.selected = false;
return werewolf;
}
break;
case 2:
if (goblin.selected === false) {
goblin.selected = false;
return goblin;
}
break;
}
}
$(".hero_info").html(hero.heroStats());
$(".monster_info").html(selectMonster().monsterStats());
$("button").click(function() {
battle(selectMonster());
});
function battle(actualmonster) {
if (actualmonster.alive === false) {
actualmonster.selected = false;
actualmonster.selectMonster();
$(".monster_info").html(actualmonster.monsterStats());
$(".battle_info").html("");
actualmonster.alive = true;
} else {
var d20 = Math.floor(Math.random() * 20) + 1;
var d_wp = Math.floor(Math.random() * hero.weaponDamage) + 1;
if (d20 + hero.attackBonus > actualmonster.armorClass) {
$(".battle_info").html("You attack!: d20+" + hero.attackBonus + ": " + (d20 + hero.attackBonus) + " vs AC " + actualmonster.armorClass + "<br/>" + "You hit!: d" + hero.weaponDamage + ": " + d_wp);
actualmonster.hitPoints = actualmonster.hitPoints - d_wp;
$(".monster_info").html(actualmonster.monsterStats());
} else {
$(".battle_info").html("You miss!: d20+" + hero.attackBonus + ": " + (d20 + hero.attackBonus) + " vs AC " + actualmonster.armorClass);
}
if (actualmonster.hitPoints <= 0) {
actualmonster.hitPoints = 0;
$(".monster_info").html(actualmonster.monsterStats());
$(".battle_info").html("You killed the monster!");
actualmonster.alive = false;
} else {
var d20_m = Math.floor(Math.random() * 20) + 1;
var d_wp_m = Math.floor(Math.random() * hero.weaponDamage) + 1;
if (d20_m + actualmonster.attackBonus > hero.armorClass) {
$(".battle_info").append("<br/>Monster attacks you!: d20+" + actualmonster.attackBonus + ": " + (d20_m + actualmonster.attackBonus) + " vs AC " + hero.armorClass + "<br/>" + "Monster hits you!: d" + actualmonster.weaponDamage + ": " + d_wp_m);
hero.hitPoints = hero.hitPoints - d_wp_m;
$(".hero_info").html(hero.heroStats());
} else {
$(".battle_info").append("<br/>Monster miss!: d20+" + hero.attackBonus + ": " + (d20_m + actualmonster.attackBonus) + " vs AC " + hero.armorClass);
}
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="monster_info"></p>
<p class="battle_info"></p>
<p class="hero_info"></p>
<button type="button">Attack</button>
The second approach is good but you're using it weird. selectMonster will randomly generate monster with some random logic and a call to new monster. But then you call selectMonster() a few times for no apparent reason.
Your code should look like:
var current_monster = selectMonster(); // note that you already have function named monster
$(".monster_info").html(current_monster.monsterStats());
$("button").click(function() {
battle(current_monster);
});
You can also go all the way with prototyping to define your monsters:
function Monster(name, hp, attack) {
this.name = name;
this.hp = hp;
this.attack = attack;
this.alive = true;
// etc
}
Monster.prototype.monsterStats = function() {
return this.name + "<br/>" +
"Hit Points: " + this.hitPoints + "<br/>" +
"Armor Class: " + this.armorClass + "<br/>" +
"Attack Bonus: " + this.attackBonus + "<br/>" +
"Weapon Damage: " + this.weaponDamage;
}
function Werewolf() {
Monster.call(this, "werewolf", 5, 4); // call parent
}
Werewolf.prototype = new Monster();
function Goblin() {
Monster.call(this, "goblin", 15, 3); // call parent
}
Goblin.prototype = new Monster();
var goblin = new Goblin();
console.log(goblin.hp); // 15
console.log(goblin.monsterStats()); // goblin <br /> etc..
In your monster constructor, you're doing stuff in your return statement that you probably don't want to be. When you have something like return x + 1, foo = 3, bar = false the expressions are evaluated left to right and the last one is returned. That is, you're retuning the state of this.alive instead of returning the this expected in the constructor.
Try refactoring your code to explicitly return the monster object you want to be created by the constructor, and see if you still have problems there. Generally, you want your return to stand on its own, to avoid confusion around syntax.
Related
I am creating a dynamic list with JS
var obj = JSON.parse(Agent212);
var i;
var serie = "Agent212";
for (i = 0; i < obj.strips.length; i++) {
if (obj.strips[i].Collectie == "0") {
document.write("<li><a onclick='newPage(" + obj.strips[i].Nummer + "," + serie + ")' style = 'color:orange'>" + obj.strips[i].Nummer + " - " + obj.strips[i].Titel + "</a></li>");
}
else if (obj.strips[i].Collectie == "2") {
document.write("<li><a onclick='newPage(" + obj.strips[i].Nummer + "," + serie + ")' style = 'color:red'>" + obj.strips[i].Nummer + " - " + obj.strips[i].Titel + "</a></li>");
}
else {
document.write("<li><a class='ToHide' onclick='newPage(" + obj.strips[i].Nummer + "," + serie + ")'><strike>" + obj.strips[i].Nummer + " - " + obj.strips[i].Titel + "</strike></a></li>");
}
}
when I click on an item in the list, I create a childpage
function newPage(StripNum, SerieNaam) {
var obj = JSON.parse(SerieNaam);
var i;
var x = StripNum;
for (i = 0; i < obj.strips.length; i++) {
if (obj.strips[i].Nummer == x) {
if (obj.strips[i].Collectie == 0) {
var myWindow = window.open();
myWindow.document.writeln('<html>');
myWindow.document.writeln('<head>');
myWindow.document.writeln('<meta name="viewport" content="width=device-width, initial-scale=1">');
myWindow.document.writeln('<link rel="stylesheet" href="./css/W3CSS.css">');
myWindow.document.writeln('<scr' + 'ipt>');
myWindow.document.writeln('function windowClose(){');
myWindow.document.writeln('window.close();}'); **
myWindow.document.writeln('function ToevoegenVerzameling(){'); **
myWindow.document.writeln('window.alert("toegevoegd aan verzameling");');
myWindow.document.writeln('window.close();');
myWindow.document.writeln('}');
myWindow.document.writeln('</scr' + 'ipt>');
myWindow.document.writeln('</head>');
myWindow.document.writeln('<body>');
myWindow.document.writeln('<div class="w3-container w3-display-topmiddle">');
myWindow.document.writeln('<div class="w3-card-16 w3-round-xlarge" style="width:100%">');
myWindow.document.writeln('<a onclick="windowClose();"><center><img src="' + obj.strips[i].Link + obj.strips[i].Nummer + '.jpg"></center></a>');
myWindow.document.writeln('<div class="w3-container w3-margin-top">');
myWindow.document.writeln('<center><B>Nummer: </B><I>' + obj.strips[i].Nummer + '</I></center>');
myWindow.document.writeln('<center><B>Titel: </B><I>' + obj.strips[i].Titel + '</I></center>');
myWindow.document.writeln('<center><button onclick="ToevoegenVerzameling()" class="w3-btn w3-light-grey w3-border w3-border-black w3-round-xlarge w3-margin-top w3-margin-bottom" style="width:100%"><h2><b>Toevoegen</b></h2></button></center>');
myWindow.document.writeln('</div>');
myWindow.document.writeln('</div>');
myWindow.document.writeln('</div>');
myWindow.document.writeln('</body>');
myWindow.document.writeln('</html>');
}
all of the above does work, but know I want to ad a replace function to ToevoegenVerzameling().
I've tried with adding this piece of code.
myWindow.document.writeln('if (window.opener != null && !window.opener.closed){');
myWindow.document.writeln('var str = "<li><a onclick='
newPage(" + obj.strips[i].Nummer + ", " + serie + ")
' style = '
color: orange '>" + obj.strips[i].Nummer + " - " + obj.strips[i].Titel +"</a></li>";');
myWindow.document.writeln('str.replace("<a onclick='
newPage(", " < a class = 'ToHide'
onclick = 'newPage(");'); myWindow.document.writeln('str.replace("style = '
color: orange '>", "><\strike>");'); myWindow.document.writeln('str.replace("</a>", "</strike></a>");}');
But I can't get it to work, Were am I making a mistake in this?
Description: A complex structure of HTML elements (rectangles) displayed on the screen, no overlaps, each rectangle having a distinct HTML id attribute (hence pickable by Selenium IWebDriver and C# code).
Target: I need programatically with Selenium and C# to create and trigger mousewheel event (via IJavaScriptExecutor or some other methods) on a selected rectangle element.
Q: How this can be done? Thank you
This is my implementation after investigating
//wheelTicks: negative for zoomin, positive to zoomout
public object zoomElementById(string elemId, int wheelTicks=1)
{
object response = null;
string myJavaScript =
// Callback (place in first!) used to notify the caller that the async callee is ready
" var callback = arguments[arguments.length - 1]; " +
" var maxIntervals = arguments[1]; " +
//ms
" var intervalDuration = 150; " +
" console.log('javascripting...', callback, arguments); " +
"var d = new Date(); " +
"var n = d.getTime(); " +
" var myZoomCenterElement = document.getElementById('" + elemId + "'); " +
// some debug output in the console
" console.log(myZoomCenterElement); " +
// *** THE CORE OF THE SOLUTION *** Creates proper WheelEvent object and triggers WheelEvent(Zoom)
" var box = myZoomCenterElement.getBoundingClientRect(); " +
" var boxMiddleX = Math.round((box.right + box.left )/2); " +
" var boxMiddleY = Math.round((box.bottom + box.top )/2); " +
" var myWheelableElement = document.getElementsByClassName('svg-tree-view')[0]; " +
" var wheelEventInitDict = { " +
" 'deltaX' : 0.0, " +
" 'deltaY' : -200.0, " +
" 'deltaZ' : 0.0, " +
" 'deltaMode' : 0, " +
" 'clientX' : boxMiddleX, " +
" 'clientY' : boxMiddleY " +
" }; " +
" var myWheelEvent = new WheelEvent('wheel', wheelEventInitDict); " +
" console.log(wheelEventInitDict, boxMiddleX, boxMiddleY, myWheelEvent); " +
" var myIntervalCounter = 0; " +
" var myInterval = setInterval(function(){ " +
" myWheelableElement.dispatchEvent(myWheelEvent); " +
" myIntervalCounter++; " +
" if (myIntervalCounter > maxIntervals) clearInterval(myInterval); " +
" }, intervalDuration); " +
" var sthToReturn = 'Returning: Nothing requested!'; " +
" var asyncAwaitInMiliSeconds = Math.ceil( 1.2 * intervalDuration * maxIntervals ); " +
// Triggers the callback (to indicate async ready)
" setTimeout( function(){ " +
" console.log((new Date()).getTime()-n); " +
" callback(sthToReturn); " +
" }, asyncAwaitInMiliSeconds); " +
""
;
_driver.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0, 0, 20));
IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
try
{
// addititonal args(optional) to be sent to the javascript func are put after the first arg
return response = js.ExecuteAsyncScript(myJavaScript, elemId, wheelTicks);
}
catch(UnhandledAlertException e)
{
Console.WriteLine("Error Occured! \n {0}", e.ToString() );
return null;
}
}
I'm trying to make a script that will notify you if someone gets inline on Whatsapp web and I have this script:
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
// I want it to repeat onlineCheck() after 1 second
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + "Notification sent");
}
}
}
and I want to replace // I don't know what to put here with something that will run the function onlineCheck()
how should I do that
I first had this script:
var onlineCheck1 = window.setInterval(function(){
var x = document.querySelector('[title="online"]');
var name = $('#main>header>div.chat-body>div.chat-main>.chat-title>span').text()
var d = new Date();
if (x == null) {
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + name + " " + "was" + " " + "offline");
} else {
if (x.innerText === "online") {
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + name + " " + "was" + " " + "////online///");
} else {
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours())
+ ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds())
+ " " + name + " " + "was" + " " + "offline");
}
} ,1000);
but I want it to not do any thing with console log I just want it to repeat itself till it finds the element with the title="online"
Note: I'm using chrome's console to run the script and you can try it yourself if you want.
Invoke the function itself. This is called Recursion. You must be careful to prevent onlineCheck()calls itself infinitely
function onlineCheck()
{
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null)
{
onlineCheck();
}
else
{
if (y.innerText === 'online')
{
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
You can simply call the function as below
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
onlineCheck();
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
You need recursion technique.
While using this technique, the recursive function should need a termination condition to end the process (otherwise the process will infinitely iterates which will eventually cause Maximum call stack size exceeded error)
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
// Be sure to add a termination condition
onlineCheck()
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
As others have pointed out, you could just call the function directly: onlineCheck();. However, the loop condition (document.querySelector('[title="online"]') != null) won't have changed if you do that, so it'll go into an infinite loop/recursion.
Here's another way:
function onlineCheck() {
var y = document.querySelector('[title="online"]');
var d = new Date();
if (y == null) {
setTimeout(onlineCheck, 10);
} else {
if (y.innerText === 'online') {
new Notification("contact is online");
console.log(d.toLocaleDateString() + "|" + addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getSeconds()) + " " + "Notification sent");
}
}
}
This re-schedules onlineCheck to be called after 10 milliseconds, giving the page a chance to update before checking again. You may want to increase this number to, say, 1000; this way it'll check once every second instead of spinning in place, going "are we done yet? how about now? how about now? and now? now? now?".
Here is my code :
//Player Loadout
//Version 1.0 by Madi Magdy
function Player(name,sex,side) {
this.name = name;
this.sex = sex;
this.side = side;
}
//var newPlayer = new Player(prompt("Please enter your name"),prompt("Please enter your sex"),prompt("Please enter your nationality"));
//console.log("Hello " + newPlayer.name + "!");
function Class(classType,mainWeapon,sideWeapon) {
this.classType = classType;
this.mainWeapon = mainWeapon;
this.sideWeapon = sideWeapon;
}
assaultClass = new Class("Assault","M416","M9");
engineerClass = new Class("Engineer","AK5C","P226");
reconClass = new Class("Recon","SRR61","Deagle44");
supportClass = new Class("Support","M249","M1911");
classChooser = function(playerChoice) {
if (playerChoice === assaultClass.classType) {
console.log("You chose the " + assaultClass.classType + " " + "class! Your default weapons are " + assaultClass.mainWeapon + " " + "and " + assaultClass.sideWeapon);
}
else if (playerChoice === engineerClass.classType) {
console.log("You chose the " + engineerClass.classType + " " + "class! Your default weapons are " + engineerClass.mainWeapon + " " + "and " + engineerClass.sideWeapon);
}
else if (playerChoice === reconClass.classType) {
console.log("You chose the " + reconClass.classType + " " + "class! Your default weapons are " + reconClass.mainWeapon + " " + "and " + reconClass.sideWeapon);
}
else if (playerChoice === supportClass.classType) {
console.log("You chose the " + supportClass.classType + " " + "class! Your default weapons are " + supportClass.mainWeapon + " " + "and " + supportClass.sideWeapon);
}
};
classChooser(prompt("Please choose your class! Type in Assault or Engineer or Recon or Support!"));
classWeapons = function(weapon,attach,camo) {
this.weapon = weapon;
this.attach = attach;
this.camo = camo;
};
yourClassWeapons = new classWeapons(prompt("Choose your weapon"),prompt("Choose your weapon attachment"),prompt("Choose your camouflage color"));
var classChosen = function(yourChosenClass) {
if (yourChosenClass === assaultClass.classType) {
console.log("Your weapons are listed as follows");
console.log(yourClassWeapons);
}
else {
console.log("NOPE");
}
};
classChosen(classChooser()); //I also tried classChosen(classChooser);
I enter the string "Assault" when prompted and when I try to pass the classChooser function as an argument in my classChosen function, the statement after the if never executes but the else does. What mistake do I have?
The main problem is that you are not passing to classChosen what you think you are passing. The way it is, the variable yourChosenClass is undefined, which is why it isn't equal to assaultClass.classType.
You need to either store the value that the player chose, or return it from classChooser. Also, it would be much better for your code if the prompt for classChooser was part of the function instead of being passed as a parameter. So it could be something like this:
classChooser = function() {
var playerChoice = prompt("Please choose your class! Type in Assault or Engineer or Recon or Support!");
if (playerChoice === assaultClass.classType) {
console.log("You chose the " + assaultClass.classType + " " + "class! Your default weapons are " + assaultClass.mainWeapon + " " + "and " + assaultClass.sideWeapon);
}
else if (playerChoice === engineerClass.classType) {
console.log("You chose the " + engineerClass.classType + " " + "class! Your default weapons are " + engineerClass.mainWeapon + " " + "and " + engineerClass.sideWeapon);
}
else if (playerChoice === reconClass.classType) {
console.log("You chose the " + reconClass.classType + " " + "class! Your default weapons are " + reconClass.mainWeapon + " " + "and " + reconClass.sideWeapon);
}
else if (playerChoice === supportClass.classType) {
console.log("You chose the " + supportClass.classType + " " + "class! Your default weapons are " + supportClass.mainWeapon + " " + "and " + supportClass.sideWeapon);
}
return playerChoice;
};
classChosen(classChooser());
// or...
// var playerChosenClass = classChooser();
// classChosen(playerChosenClass);
Additionally, choosing the weapon can be refactored in a similar way:
weaponChooser = function() {
var weapon = prompt("Choose your weapon");
var attachment = prompt("Choose your weapon attachment");
var camo = prompt("Choose your camouflage color");
return new classWeapons(weapon, attachment, camo);
}
yourClassWeapons = weaponChooser();
Your classChooser function returns undefined, so in
classChosen(classChooser());
You pass in an argument parameter as undefined. That is else statement gets executed.
To make this work, you need to
classChooser = function(playerChoice) {
var returnType;
if (playerChoice === assaultClass.classType) {
console.log("You chose the " + assaultClass.classType + " " + "class! Your default weapons are " + assaultClass.mainWeapon + " " + "and " + assaultClass.sideWeapon);
return assaultClass.classType;
}
else if (playerChoice === engineerClass.classType) {
console.log("You chose the " + engineerClass.classType + " " + "class! Your default weapons are " + engineerClass.mainWeapon + " " + "and " + engineerClass.sideWeapon);
returnType = engineerClass.classType;
}
else if (playerChoice === reconClass.classType) {
console.log("You chose the " + reconClass.classType + " " + "class! Your default weapons are " + reconClass.mainWeapon + " " + "and " + reconClass.sideWeapon);
returnType = reconClass.classType;
}
else if (playerChoice === supportClass.classType) {
console.log("You chose the " + supportClass.classType + " " + "class! Your default weapons are " + supportClass.mainWeapon + " " + "and " + supportClass.sideWeapon);
returnType = supportClass.classType;
}
return returnType;
};
classChoosen(classChooser(prompt("Please choose your class! Type in Assault or Engineer or Recon or Support!")));
I have a tree structure where the elements can be dragged and dropped into another element. My objective is when a element or node from a tree is dragged and dropped to the external element I want a line to be drawn from the element of the tree to the external location.
I have the code separate for dragging and dropping. I tried to integrate the code into my tree structure and getting this error. I did see similar errors but could not get an exact idea about what exactly the error is. Here is the code that is giving me the error.
end: function(item, hover, placeholder, helper) {
if (placeholder.parent().length) {
var tree = $('#tree1').aciTree('api');
if (tree.isItem(item)) {
var id = tree.getId(item);
var label = tree.getLabel(item);
if (this._instance.jQuery.hasClass('any')) {
this._instance.jQuery.find('li:not(.aciSortablePlaceholder)').remove();
}
var item = $('<li id="item-' + id + '">' + label + '</li>');
var sourceId = id;
var destinationId = sourceId;
drawLine(sourceId, destinationId);
//This is how the function is called
placeholder.after(item).detach();
}
else {
placeholder.detach();
}
}
helper.detach();
}});
function drawLine(eTarget, eSource) {
setTimeout(function () {
var $source = eSource;
var $target = eTarget;
var originX = $source.offset().left + $source.width() + 20 + 4;
// In the $source.offset() I am getting the error.
var originY = $source.offset().top + (($source.height() + 20 + 4) / 2);
var endingX = $target.offset().left;
var endingY = $target.offset().top + (($target.height() + 20 + 4) / 2);
var space = 20;
var color = "black";
var a = "M" + originX + " " + originY + " L" + (originX + space) + " " + originY; // beginning
var b = "M" + (originX + space) + " " + originY + " L" + (endingX - space) + " " + endingY; // diagonal line
var c = "M" + (endingX - space) + " " + endingY + " L" + endingX + " " + endingY; // ending
var all = a + " " + b + " " + c;
console.log("New Line ----------------------------");
console.log("originX: " + originX + " | originY: " + originY + " | endingX: " + endingX + " | endingY: " + endingY + " | space: " + space + " | color: " + color );
console.log(all);
myLines[myLines.length] = svg
.path(all)
.attr({
"stroke": color,
"stroke-width": 1,
"stroke-dasharray": "-"
});
}, 1000);
PS: I am using firefox. The eTarget and eSource and getting the values as supplied.