jeudi 18 février 2016

JavaScript - Choose your own adventure game - Best way to get started

I'm learning JavaScript and fairly new to programming.

As an exercise, I'm trying to create a "choose your own adventure" game with straight JavaScript. No jQuery or other libraries for now. Here's my code:

var choice;

function getId(element) {
    choice = element.id;
}

function choiceChange () {
    choice = "c";
}

function currentValueChoice () {
    alert(choice);
}

function choiceAlert () {
    switch(choice) {
            case "a":
                    alert("You chose a")
                    break;
            default:
                    alert("You chose b")

    }
}

http://ift.tt/20GCeFC

I have 2 main buttons that represent 2 different choices. They both have onclick events for 2 functions. The getId function captures the id of the button that is clicked and then stores it in a variable (choice) and then choiceAlert runs to alert me on that choice (switch statement). The alert will ideally be replaced with an action other than an alert.

The other 2 buttons are to verify the value of choice at certain times when I was putting this together.

Should I even be using the onclick event in the html? I think that should be done in the JavaScript itself.

Honestly, I feel like I'm making things difficult for myself here and will run into problems as I get deeper into other choices and what to do with them. I'd like to start this out the right way.

Do some more experienced JavaScript developers have a better way to code the type of game I'm trying to make? Or can you offer some pointers as to what I'm doing wrong or what I can improve upon?

Aucun commentaire:

Enregistrer un commentaire