Class select system


#1

I am trying to create a simple class select system for an RPG project i'm working on, it works by taking an input from the user in number form then translating that into a selected class, yet i keep getting the error "class1 in not defined", i am stumped as to how this is happening, feedback is much appreciated; below is my code, i have mad relevant parts bold.

console.log("Choose your class:")
console.log("1. Mage")
console.log("2. Archer")
console.log("3. Warrior")
console.log("4. Rogue")
console.log("5. Paladin")

var classSelect = function(class1) {
var classAsk = prompt("What class would you like to play as? (type the number e.g 4)");
}
classSelect(classAsk)

if(class1 === "1") {
    var classSelect = "mage";
            
} else if(player_class === "2") {
    var classSelect = "archer";
            
} if(player_class === "3") {
    var classSelect = "warrior";
    
} if(player_class === "4") {
    var classSelect = "rogue";
   
} else {
    var classSelect = "paladin";
}

var classConfirm = function(user_confirm) {
    var user_confirm = prompt("You have selected the" + classSelect + " " + "are you sure?");
}
if (user_confirm = "yes") {
    console.log("Let's go");
} else {
    classConfirm(user_confirm);
}

classConfirm(user_confirm)

#2

Hi @chiefcrypto,

Your code seems to be way too wrong. Using wrong data structures for the right thing. Using unnamed variables. Bad if-else ladder.

var classSelect = function(class1) {
var classAsk = prompt("What class would you like to play as? (type the number e.g 4)");
}
classSelect(classAsk)

is unnecessary. You can simply do it as:

var classAsk = prompt("What class would you like to play as? (type the number e.g 4)");

or:

// if you really need a function
var classSelect = function() {
    return prompt("What class would you like to play as? (type the number e.g 4)");
}
var class1 = classSelect();

Then change the really long if-else ladder to something easier to maintain and manipulate:

var classes = ["mage", "archer", "warrior", "rogue", "paladin"];
var userClass = classes[class1 - 1]; // classSelect is already a function; so choose userClass name

even if you haven't learnt arrays yet, you'll end up coding like this only once you do. If you want it to be if-else, then do:

var userClass;
if(class1 === "1") 
    userClass = "mage";            
else if(class1  === "2")  // player_class isn't defined
    userClass = "archer";            
else if(class1  === "3")  // player_class isn't defined
    userClass = "warrior";
else if(class1  === "4")  // player_class isn't defined
    userClass = "rogue";
else userClass = "paladin";

Similarly, change the last classConfirm things. I really advise you to dry run your code, and plan your code before starting to code, not vice-versa.