2014-10-01 1 views
-2

Я делаю текстовую приключенческую игру. Мне удалось заставить все остальное работать, хотя я хотел бы немного упростить код, если это возможно. В любом случае, мне нужна моя игра, чтобы принять имя пользователя и ввести его в историю. Я знаю, как получить имя в истории, используя подсказку для захвата имени, но использование этого параметра не будет хорошо сочетаться с игрой.(javascript) Вставка имени пользователя из ввода и в переменную объекта

Это чисто html и javascript игра.

Любой совет поможет.

<!DOCTYPE html> 
    <html> 

<head> 
      <meta charset="utf-8" /> 
      <title>Nuclear Christmas</title> 

      <link href="image/favicon.ico" rel="shortcut icon" type="image/x-icon" /> 
      <link rel="stylesheet" type="text/css" href="ncTheme.css" /> 
      <link href='http://fonts.googleapis.com/css?family=Covered+By+Your+Grace' rel='stylesheet' type='text/css'> 
     </head> 
     <body> 
      <h1 class="headFont">How Far Would You Go for That Christmas Spirit?</h1> 
      <table> 
       <tr><!-- text field --> 
        <td id="textCell"> 
         <p id ="dialogue"><!--the game's dialogue will appear in the paragraph tag--></p> 
        </td> 
        <!-- text field --> 

        <!--this section holds img id: "image", which will be used to display the game's images--> 
        <td id="imageCell" width="400" rowspan="2"> 
        <img id="image" src="image/start/png" alt="Image failed to load."> 
        </td> 
        <!--this section holds img id: "image", which will be used to display the game's images--> 
       </tr> 
       <tr> 
        <!--this section houses the input box and the submit button.--> 
        <td id="inputCell"> 
        <!--background music--> 
        <audio id="music" autoplay loop> 
         <source src="audio/Silent night-warped.mp3" type="audio/mpeg"> 
          Your browser does not support the audio element. 
        </audio> 
         <button onclick="document.getElementById('music').muted=!document.getElementById('music').muted"><img id="mute" src ="image/Mobile-Speaker-icon.png"><!--allows music to stop and play when pressed--></button> 
        <!--background music--> 
        <input id="inputText" type="text"> <!-- text box --> 
        <input id="submitInput" type="submit" value="Submit" onClick="advance()"> <!-- the submit button --> 
        <!--this section houses the input box and the submit button.--> 
        </td> 
       </tr> 
      </table> 

    </body> 

    <script type="application/javascript"> 
    //the options object variable holds the text information. 
     var userName; 

     var options = new Object(); 
      options.scene0 = "In the early hours of January 3rd, the United States was plunged in to war against an enemy state. Invading forces made landfall on the U.S east coast and pushed towards the capital. Both sides fought a long fight, each suffering causalities in the thousands, yet neither side were willing to wave the white flag. In the coming months, both countries threatened each other with the possibility of a nuclear strike but neither were willing to pull the trigger. Unfortunately, those threats came to fruition on August 13th when the opposing side launched the first of many strikes against the U.S. The eastern seaboard was lit up like a Christmas tree. And it was unclear if a portion of the population survived. [START]"; //main screen 
      ////////////////////////////////////////////////////////// 
      options.inputName = "[CONTINUE]" //adding name to story 
      ////////////////////////////////////////////////////////// 
      options.scene1 = "Fast forward three years to find that the U.S is being occupied by the enemy. Some people are receiving aid from their new leader while others are joining the resistance. INSERT-NAME, on the other hand, is not remotely interested in fighting. What you care about is the date on the calendar. See, it's Christmas Eve, and you do not have everything set up. You know that your guests will be here by morning and that gives you just enough time to finish decorating. [CONTINUE]"; //introduction of story and objectives 
      ////////////////////////////////////////////////////////// 
      options.branch1 = "Thinking about the things you need. You ponder if getting snow will set off the decorations or maybe a gift will be enough to distract the guests. What should you do first? Find [snow] or get a [TV]"; //choices for users to choose from 
      ////////////////////////////////////////////////////////// 
      options.scene2 = "Though it’s below freezing, you know that the environment is way too dry to produce snow, so you improvise. Searching the surrounding area, you snatch up the most amount of paper you can carry and take it back to camp. You rip each piece and scatter it around your campsite. [CONTINUE]"; //result of the snow option 
      ////////////////////////////////////////////////////////// 
      options.sceneII = "You head into town and search the deserted buildings. It takes you around 2 hours to locate the television. It takes you some time, but you manage to secure the TV on your person. From that put on, you struggle to get it back to camp. [CONTINUE]"; //result of the TV option 
      ////////////////////////////////////////////////////////// 
      options.scene3 = "Stopping to inspect your work, you realize that more could be done; however, you aren’t quite sure if you’re willing to go through the extra trouble. [CONTINUE]"; //user examines situation in this scene 
      ////////////////////////////////////////////////////////// 
      options.branch2 = "I could use the rest of today to scavenge or sleep on today’s accomplishments. Gosh, I don’t know. Should I do more? [YES] or [NO]"; // second set of choices for user to choose from 
      ////////////////////////////////////////////////////////// 
      options.scene4 = "You head deep into town to find Walmart and get something extra for the home. When you get there, you search the aisles and find several things that could come in use but you don’t see that creepy Santa statue that your grandma use to put out on Christmas. Though, you manage to locate some tree ornaments. Don’t know how you’ll use them but you’ll improvise something. [CONTINUE]"; //results of choosing yes 
      ////////////////////////////////////////////////////////// 
      options.sceneIV = "You decide that the extra stuff isn’t needed, so you retire to your bed, promising yourself that you’ll properly clean tomorrow. The next day, you wake up and read the time on your watch, “DAMN!” You realize that your guests are due to arrive at any moment. This causes you to panic and try to tidy up the place as best you can. Unfortunately, you break a couple of items in the process. [CONTINUE]"; // results of choosing no 
      ////////////////////////////////////////////////////////// 
      options.scene5 = "You get back home before your self-enforced curfew and set out to arrange the final decorations. It only takes you a couple of minutes to strategically place the Christmas ornaments around your room *satisfied sigh* “, time to let the Christmas spirit take over.” You say. [CONTINUE]"; //proceeding scene for the yes choice 
      ////////////////////////////////////////////////////////// 
      options.end1 = "You prop up the guests and place Christmas hats on their heads and scarves around their necks. Sabrina looks upset, Todd looks bored, and Ted is looking the other way. 'Hey, guys. Uh, merry Christmas!' You say in your most cheerful voice. The only reaction you get is the slumping of Ted’s head. DAMN IT, no one appreciates the hard work you put into decorating. THE END"; // user suffers a bad Christmas/BAD ENDING 
      ////////////////////////////////////////////////////////// 
      options.end2 = "The next day, you prop up your guests and dress them in their Christmas attire. Sabrina is relaxing on the couch, Todd is drinking your homemade eggnog, and Ted is trying to sneak a peek at the gifts 'So nice to see you all. Merry Christmas!' You say in a cheery tone. Surprisingly, everyone seems to be enjoying themselves. You think to yourself, 'totally doing this next year.' THE END."; // user experiences a good Christmas/GOOD ENDING 

    //the options object variable holds the text information. 

    //the visuals object variable holds the images. 
     var visuals = new Object(); 
      visuals.scene0 = "image/start.png"; 
      visuals.inputName = "image/diary_scene.png"; 
      visuals.scene1 = "image/cityscape.png"; 
      visuals.branch1 = "image/list1.jpg"; 
      visuals.scene2 = "image/snow_scene.png" 
      visuals.sceneII = "image/tv_scene.png"; 
      visuals.scene3 = "image/camp_scene.png"; 
      visuals.branch2 = "image/more.png"; 
      visuals.scene4 = "image/ornament_scene.png"; 
      visuals.sceneIV = "image/alright.png"; 
      visuals.scene5 = "image/good_scene.png"; 
      visuals.end1 = "image/end1.png"; 
      visuals.end2 = "image/end2.png"; 
    //the visuals object variable holds the images. 
    } 
    //var state holds the each game state. 
     var state = "SC0"; 
     advance(); 
    /*--------------------------------------------------------------------*/ 

     function advance(){ 
      //Game progression is controlled here. 
       if(state == "SC0") checkDialogue(options.scene0,visuals.scene0,"start",null,"INP",null); 
      else if(state == "INP") checkDialogue(options.inputName,visuals.inputName,"continue",null,"SC1",null); 
      else if(state == "SC1") checkDialogue(options.scene1,visuals.scene1,"continue",null,"B1",null); 
      else if(state == "B1") checkDialogue(options.branch1,visuals.branch1,"snow","tv","SC2","SCII"); 
      else if(state == "SC2") checkDialogue(options.scene2,visuals.scene2,"continue",null,"SC3",null); 
      else if(state == "SCII") checkDialogue(options.sceneII,visuals.sceneII,"continue",null,"SC3",null); 
      else if(state == "SC3") checkDialogue(options.scene3,visuals.scene3,"continue",null,"B2",null); 
      else if(state == "B2") checkDialogue(options.branch2,visuals.branch2,"yes","no","SC4","SCIV"); 
      else if(state == "SC4") checkDialogue(options.scene4,visuals.scene4,"continue",null,"SC5",null); 
      else if(state == "SCIV") checkDialogue(options.sceneIV,visuals.sceneIV,"continue",null,"E1",null); 
      else if(state == "SC5") checkDialogue(options.scene5,visuals.scene5,"continue",null,"E2",null); 
      else if(state == "E1") checkDialogue(options.end1,visuals.end1,null,null,null,null); 
      else if(state == "E2") checkDialogue(options.end1,visuals.end1,null,null,null,null); 
     } 
     // 

     function checkDialogue(output,images,answer1,answer2,state1,state2,userName){ 
      outT("dialogue",output); 
      document.getElementById("image").src = images; 

       if(analyzeInput(answer1)) progress(state1); 
      else if(analyzeInput(answer2)) progress(state2); 
      else if(analyzeInput("restart")) progress("SC0"); //Resets the game to the beginning 
      else document.getElementById("inputText").value = ""; 
     } 
    // 
     function progress(statex){ 
      state = statex; 
      document.getElementById("inputText").value = ""; 
      advance(); 
     } 
    //used professor's code for letter conversion on 9/26/2014 
     function analyzeInput(answer){ 
      if(answer != null){ 
       var a = document.getElementById("inputText").value.toUpperCase(); 
       var b = answer.toUpperCase(); 
       var c = a.indexOf(b) >= 0; 
       /*debugger*/console.log("a = "+a+" b = "+b+" c = "+c);/*debugger*/ 
       return c == true; 
      }else return false; 
     } 
      function outT(myId,myTEXT){ 
      document.getElementById(myId).innerHTML = myTEXT; 
     } 
    </script> 

</html> 
+0

Вы можете использовать любое решение для хранения данных, предлагаемое текущими браузерами, например localStorage или простые куки. – nicolas

ответ

0

Вы можете использовать тег. Попробуйте что-то вроде этого: input id="input1" placeholder="typehere" Это позволит пользователю вводить текст прямо на страницу без необходимости использовать всплывающие подсказки. Вы также можете указать тип материала, который они могут ввести во входную область, добавив аргумент type="example" к вашему тегу ввода. Вы можете использовать приведенные здесь аргументы: http://www.w3schools.com/tags/att_input_type.asp На этой странице также говорится о вводе ввода, который вы могли бы использовать, или вы могли бы использовать кнопку с функцией javascript.

Смежные вопросы