Text based rpg javascript practice project - javascript

I was told making a game would be a good way to learn how to use javascript properly so I have started a game in which thus far the player is prompted to create a hero, and then assign attributes to it based on its hero type(magerouge, necromancer, warlock, or shaman) however when I get to the point of assigning attributes it always says the user picked a necromancer no matter what class he actually chose. So in short something is wrong with my function called "defaultAssign". I hope i am posting this question properly, if i am posting incorrectly please let me know so I can try to fix it, this is my first question. Here is my code:
var heroArray = [];
var yourHero ="";
var hero = {
characterType:"",
Damage:0,
Health:0,
Mana:0,
ManaRegenRate:0,
HealthRegenRate:0,
SpecialSkills:[]
};
var mainMenu = function(){
var nameCheck = prompt("What is your Character's Name?").toUpperCase() ;
for( var i = 0;i <= heroArray.length ; i++){
if (nameCheck === heroArray[i]){
alert("We have found your hero change this string later");
runGame(heroArray[i]);
}
else{
alert("You Must Create a Champion");
var heroName = prompt("What Will You Name Your Sorcerer!").toUpperCase;
characterCreator(heroName);
/*use a loop with a regular expression here to check if the name is avalible, if it is countinue, if not
prompt the user for another name
*/
}
/* run "gameSave" for particular hero
Run the main Game function and print to the console:
"Ah yes "+yourHerosNameHere+"," +hisOrHer+" tale echoes far and wide. We last spoke of his journey to"
+insertCurrentCityHere+" where "+heOrShe+" "mostRecentAction"."
*/
}
}
var characterCreator = function(yourHero){
yourHero = Object.create(hero);
yourHero.characterType = prompt("Choose your Character Type:\n"+
"MageRouge\n"+
"Warlock\n"+
"Shaman\n"+
"Necromancer").toUpperCase;
defaultAssign(yourHero.characterType)
}
function defaultAssign(playersType){
for (var j = 0 ; j <= 3 ; j++){
if (playersType === "MAGEROUGE"){
yourHero.Damage=25;
yourHero.Health=50;
yourHero.Mana=15;
yourHero.ManaRegenRate=1;
yourHero.HealthRegenRate=0.4;
yourHero.SpecialSkills=[["pickpocket",],["sneak",],["lockpick",]];
alert("Ahha a powerful Magerouge, choose your skills emphasis wisely,"
+" it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
if(playersType === "WARLOCK"){
yourHero.Damage=50;
yourHero.Health=50;
yourHero.Mana=25;
yourHero.ManaRegenRate=0.6;
yourHero.HealthRegenRate=0.3;
yourHero.SpecialSkills=[["summonDemon",0],["bindDemon",0],["portal",0],["illusion",0]];
alert("Ahha a powerful Warlock, choose your skills emphasis wisely,"
+"it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
if(playersType === "SHAMAN"){
yourHero.Damage=40;
yourHero.Health=50;
yourHero.Mana=30;
yourHero.ManaRegenRate=0;
yourHero.HealthRegenRate=0.6;
yourHero.SpecialSkills=[["weatherControl",0],["heal",0],["astralProjection",0]]
alert("Ahha a powerful Shaman choose your skills emphasis wisely,"
+"it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
else if(playersType === "NECROMANCER") {
yourHero.Damage=60;
yourHero.Health=50;
yourHero.Mana=20;
yourHero.ManaRegenRate=0.8;
yourHero.HealthRegenRate=0.4;
yourHero.SpecialSkills=[["raiseDead",0],["petrify",0],["soulSap",0]];
alert("Ahha a powerful Necromancer choose your skills emphasis wisely,"
+"it could determine your Destiny...");
skillAssigner(yourHero);
break;
}
}
}
/*
create an array of hometowns for the main character to choose from
*/
function skillAssigner(yourHero){
for (var s = 0;s<3;s++){
var p = 0;
while( p < 10 ){
var n = prompt("How many points will you spend on "+yourHero.SpecialSkills[s]+"?");
yourHero.SpecialSkills[s][1] = n;
p +=n;
}
}
}
mainMenu();

Get rid of the else on the line where it checks if the player's type is a Necromancer. It is not necessary.
The for loop is not necessary inside the function defaultAssign (and with its removal, nor are the breaks.)
Finally, toUpperCase is a function so you must invoke it with parentheses, toUpperCase().
Resolving these issues gets your code to work.
You should work on formatting your code (or get an editor that does it for you) to increase its readability-- this will help you find errors.

Related

discord.js How to fix variables coming back as undefined

I have scanned through the extensive list of questions asking similar things, but none of them have been able to solve this problem in this context.
Essentially, I'm attempting to build a blackjack command for a bot in discord.js, and so far, the flow looks like this: it takes the names and id's of all of the players and then passes them into the function that handles each game. First, three functions are defined. One that finds the value of a hand (the total of the cards) and one that adds a new card. A RichEmbed is created that will be edited many times, and the first time it is created in a game, it will give each person their hand, evaluate it, and then put it in the embed.
The problem is: the variables storing players' hands and hand values come back as undefined during initialization, even though I have tested that they can be output from the same place in the code, and that the functions that give them their data also work. What is causing them to be undefined, and why is it only those two variables? The others work just fine.
My code:
async function bj(players_id, players_names) {
var pc = players_id.length; //player count
var turn; //whose turn is it? based on id
var disp; //text to be shown in embed; game status.
var hands = []; //each player's hand
var handValues = []; //the sum of the cards in a hand
var cards = ["A", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]; //all possible cards
var ing = []; //is player in game? / have they busted?
turn = players_id[0];
var disp_dir = "React with �� to hit and ✋ to stand.";
disp = `Currently ${message.member.guild.members.get(turn).displayName}'s turn.\n${disp_dir}`;
function addCard() {return(cards[Math.floor(Math.random() * cards.length)])}; //simply grabs a card from the list of cards
function findHandValue(handValue, currentCards) { //takes two inputs, one is the current hand value, the other is a list of card values. finds the total value of the hand and returns it.
var val = 0;
for (i = 0; i < currentCards.length; i++) {
card = currentCards[i];
if (card == "A") {
if (handValue > 21) {val += 1;} else {val += 11;};
} else if (card == "J" || card == "Q" || card == "K") {
val += 10;
} else {val += card;};
};
return(val);
};
function makeEmbed(first) { //constructs the embed that will be used to show the game. param. first tells whether it is the first time the embed is being constrcuted in a game.
var bjg = new Discord.RichEmbed()
.setTitle("Blackjack Game")
.setDescription(`Initiated by ${players_names[0]}`)
.addField("Status", `${disp}`)
.setThumbnail("https://cdn.discordapp.com/attachments/563578266984775681/657323254813425674/cards.jpg")
.setColor("DC134C")
.setFooter("Valkyrie", client.avatarURL)
.setTimestamp();
if (first == true) {
for (i = 0; i < pc; i++) { //should be creating each player's hand
ing.push(true); //this one works
hands.push([addCard(), addCard()]); //but for some reason, this one returns undefined
handValues.push(findHandValue(0, hands[i])); //and this one
bjg.addField(`${players_names[i]}'s Hand`, `${hands[i]}\n\nValue: ${handValues[i]}`); //spits out undefined in almost every place, including the player_name[i]
var bjs = message.channel.send(bjg);
return(bjs);
};
};
};
var bjs = await makeEmbed(true); //and this stuff works fine
await bjs.react("��");
await bjs.react("✋");
};
if (args[0] == "quick") {
message.reply("You've started a game of solo blackjack against a bot!");
await bj([message.author.id], [message.member.displayName]);
Apologies that that is lengthy, but all of it is necessary to show what it's doing and to help pinpoint the error's origin.
Finally, this is the result
Extra Note
After extremely extensive debugging, I've found that the problem is coming from the line
handValues.push(findHandValue(0, hands[i]));, and the problem is that it changes i by +2, which only raises more questions. A small band-aid fix was to set another variable to i at the start and then reset i to the other one after the line.

Javascript - Clone a div after user input on quantity

I'm trying to clone a div after a user puts in the amount of divs to be cloned. User will put in a number (say 3) and the function will create three group-container divs. The prompt works, but nothing happens after that. Seems pretty simple but it's evading me. Is my logic incorrect? Obviously my programming skills are very new.
I create a function that has the input (groupInput)
Create a for loop to reiterate the following instruction
The for loop will clone group-container as many times as i<groupInput
function addGroup() {
var groupInput = prompt("How many groups? 1-100");
for(i=0; i<groupInput; i++){
var group = document.getElementById("group-container");
var clone = group.cloneNode(true);
group.parentNode.appendChild(clone);
}
}
Any suggestions would be much appreciated.
Updated
Thanks for the suggestions, I get I should use class for this now.
I did get it to work with the ID in jsfiddle (not sure why it's not in my html), but now with the class it's not: https://jsfiddle.net/waynebunch/c5sw5dxu/. getElementsByClassName is valid right?
You should put the group declaration outside of the for loop so the clone remains the same throughout the loop.
Fiddle
function addGroup() {
var groupInput = prompt("How many groups? 1-100");
var group = document.getElementById("group-container");
for(i=0; i<groupInput; i++){
var clone = group.cloneNode(true);
group.parentNode.appendChild(clone);
}
}
The prompt() method probably returns the correct number, but with type set to String. Instead try
parseInt(groupInput)
To convert the value to a number, which should allow the for loop to execute properly.
Something like the below might work once you get your quantity in from a prompt or text input.
var doc = document;
var input = prompt("Please enter your qty", "0");
if (input != null) {
for (i = 0; i < input; i++) {
var elem = doc.createElement('div');
elem.className = 'group-container';
}
}

Multiple conditions using for loop

I'm beginning programming with codecademy and I tried to write a "search for word" program, but I don't know how to write a condition in if using a for loop to check all the letters in a search word, no matter the length.
I know the for loop gives me true or false, but I would like it to generate as many text[j] === myWord[j-i] conditions to my code as there are letters.
Is there something wrong with my syntax or should I use other command that I don't know of?
var text = "Within the field of literary criticism, text also refers to the original information content of a particular piece of writing; that is, the text of a work is that primal symbolic arrangement of letters as originally composed, apart from later alterations, deterioration, commentary, translations, paratext, etc. Therefore, when literary criticism is concerned with the determination of a text, it is concerned with the distinguishing of the original information content from whatever has been added to or subtracted from that content as it appears in a given textual document (that is, a physical representation of text).";
var myWord = "literary";
var hits = [];
for (var i=0; i < text.length; i++) {
if (for (var j=i; j<(i + myWord.length); j++){
text[j]===myWord[j-i]
})
hits.push(text[i])
}
}
if (hits.length === 0) {
console.log("Your name wasn't found!");
}
else {
console.log(hits);
}
You should move the if condition inside the inner loop like below
for (var i = 0; i < text.length; i++) {
for (var j = i; j < (i + myWord.length); j++){
if(text[j]===myWord[j-i])
hits.push(text[i]);
}
}
}

String control in loops

I have a big question.
I have many Strings in my Programm and want to check these Strings on there values.
I wrote a Loop for it, but insted of the Definition of an String he is creating a new value. It's basicly really difficult to discribe, also because i am basicly German.
But i can give you my current code, so maybee you will see what I mean:
{
var Loch1G = $('#m1-Rundenanalyse-Datum').val(); //In the strings just the number is changing
var Loch2G = $('#m1-Rundenanalyse-Turnier').val();
x=1
while (x <= 2) {
if ("Loch" + x + "G" == ""){ //Next String is genrated (x=x+1)
alert("Eingabe war leer");
}
x=x+1
}
}
How can I solve this?
I'd suggest using an array to store the values you want to check:
var lochs = [];
lochs.push($('#m1-Rundenanalyse-Datum').val());
lochs.push($('#m1-Rundenanalyse-Turnier').val());
for (var i = 0, len = lochs.length; i < len; i++){
if (lochs[i] == ''){
alert("Eingabe war leer");
}
}
JS Fiddle demos: passes (no alert), fails (alert)
This suggestion is based on my presumption that you're trying to create the names of the vars you want to check, which won't work, whereas this approach lets you store all values (however many) in the same array and then iterate over that array to find any values that are equal to an empty string.
If you really want to stick with your current approach, you could do the following:
{
window.Loch1G = $('#m1-Rundenanalyse-Datum').val(); //In the strings just the number is changing
window.Loch2G = $('#m1-Rundenanalyse-Turnier').val();
var x=1;
while (x <= 2) {
if (window["Loch" + x + "G"] == ""){ //Next String is genrated (x=x+1)
alert("Eingabe war leer");
}
x=x+1;
}
}
But I can't think why you'd want to; plus the use of global variables is poor practice as it explicitly makes those variables available to every closure within the document, which allows them to be easily, and accidentally, overwritten.
In a reasonably up-to-date browser, that implements Array.prototype.every, you could dispense with the explicit iteration:
var lochs = [];
lochs.push($('#m1-Rundenanalyse-Datum').val());
lochs.push($('#m1-Rundenanalyse-Turnier').val());
if (!lochs.every(function(a){ return a !== ''; })) {
alert("Eingabe war leer");
}
JS Fiddle demos: passes (no alert), fails (alerts).

How can i know its valid in JS?

I am developing an Adobe interactive form with LiveCycle LC designer with JavaScript.
// Identify required fields (it may be a free text field, drop-down, check box, i mean there 3 kinds possibilties) and make yellow colored them
var myArrayYellow = new Array();
var yellowFields;
yellowFields = my_required_fields_list_string.rawValue
myArrayYellow = yellowFields.split(" ");
for (var i = 0; i < myArrayYellow.length; i++) {
===> Here at this point, i want to check the existence of [i] field in the form that its a valid field/objetc or not? bcz, i have chances of getting non-existing fields in the my_required_fields_list_string, hence prior to assigning yellow color to them, i want to check their validity on the form or not? Pls. let me know the JS for this // if its true/found, then only assign yellow color as below
xfa.resolveNode("MY_ADOBE_FORM.." + myArrayYellow [i]).ui.oneOfChild.border.fill.color.value = "255,255,254"
};
For some other purpose, some expert gave me a JS as below, i tried to tune it as per my above requirement, but its not working
function findNodes(vNode){
if (vNode.className === "field"){
if (vNode.isPropertySpecified("name") === true){
var myStateName = new RegExp(vNode.name);
var returnValue = GFL.search(myStateName);
if (returnValue != -1) {
this.ui.oneOfChild.border.fill.color.value = "192,192,192";
this.access = "readOnly";
} else {
this.ui.oneOfChild.border.fill.color.value = "255,255,255"; //whatever colour is open access
this.access = "open";
}
}
}
for (var a=0;a<vNode.nodes.length;a++) {
findNodes(vNode.nodes.item(a));
}
}
findNodes(xfa.form);
if I understand your problem, you need to check if xfa.resolveNode returns something and handle it from there.
var node;
if ( (node=xfa.resolveNode("MY_ADOBE_FORM.." + myArrayYellow[i]) )!==null){
node.ui.oneOfChild.border.fill.color.value = "255,255,254"
}
If I understand correctly, you are trying to check if all of your values in the array are valid before preforming operations on them. Just check and make sure they are not null.
EDIT: You should probably check for empty string as well.
for (var i = 0; i < myArrayYellow.length; i++) {
if (!(myArrayYellow[i] == null || myArrayYellow[i] == "")){
//Do Stuff
}
}

Categories