2016-03-09 2 views
0

Сегодня я попытался сделать текстовые приключения появляться на «холсте», как то, что я сделал для MadLibs, но я не могу показаться, что это кажется одной строкой за раз , или найти способ позволить пользователю щелкнуть что-то, чтобы появилась следующая строка. Другая проблема заключается в том, что делать, когда появляется опция, поэтому, если кто-то читает это и знает, как я могу решить эту проблему: посмотрите, что я сделал до сих пор в my website.Как сделать JavaScript запускать по одной строке за один раз

На данный момент у меня есть функция, которая запускает последовательность предупреждений (по одной для каждой строки истории) в порядке, а затем подтверждает и выводит подсказки для решения, которое может сделать пользователь. Это не очень удобно, и я хочу, чтобы текст появлялся с использованием чего-то типа .innerHTML, но я не знаю, как его работать.

See here for the code behind the function.

function theElderwood1() { 
 
    alert("THE ELDERWOOD: EPISODE I by Kiran Evans"); 
 
    var conf = confirm("Play this game?"); 
 
    if (conf === false) { 
 
    return; 
 
    } else { 
 
    alert("Let's go!"); 
 
    }; 
 
    alert("It was a dark and stormy night, when a mouse stirred in the woods. You check your watch, it's nearly midnight... and you are lost."); 
 
    alert("You came here for a stroll, but that was at 5pm and the Sun was still up. Now everything is pitch black and the only light is coming from the Moon and stars."); 
 
    var torchSearch = confirm("Do you want to search your bag for a torch?"); 
 
    if (torchSearch === true) { 
 
    alert("You search your bag and find a torch, with very low battery power."); 
 
    alert("You shine the torch ahead of you, and notice that the path forks into two."); 
 
    } else { 
 
    alert("You don't search your bag, and have to deal with the lack of natural light."); 
 
    alert("After walking a little while, you can just about make out that the path forks into two.") 
 
    }; 
 
    var pathChoice = prompt("Do you want to take the left or right fork? (Type 'L' or 'R')"); 
 
    if (pathChoice.toUpperCase() === 'L') { 
 
    alert("You take the left path, and continue walking."); 
 
    alert("You eventually come across a stream."); 
 
    if (torchSearch === true) { 
 
     alert("You shine the torch into it and see that the stream is running very fast, and is too deep to wade through."); 
 
    } else { 
 
     alert("You cannot tell how fast or how deep it is, so you try to wade through."); 
 
     alert("Half way across, you sink into the stream which has become a river and cannot escape. You get swept under and cannot breathe."); 
 
     alert("You drowned."); 
 
     return; 
 
    }; 
 
    alert("You decide to turn back and take the right path."); 
 
    } else { 
 
    alert("You take the right path, and continue walking."); 
 
    }; 
 
    alert("Down the right path, you come across a small construction of sticks and twigs."); 
 
    var wigwamSearch = confirm("Do you want to look inside?"); 
 
    if (wigwamSearch === true) { 
 
    if (torchSearch === true) { 
 
     alert("You shine your torch into it, and a small goblin-like creature lashes out at you."); 
 
     alert("Hitting it with the torch, you manage to fight it off and it hobbles back into its lair."); 
 
    } else { 
 
     alert("You poke your head inside to get a better look and can just about make out a pair of glowing red eyes right in your face."); 
 
     alert("Whatever the creature is, you can hear it breathing and it begins to shriek."); 
 
     alert("The creature screams, lashes out and attacks you. You have nothing to fight it with, so have to use your fists."); 
 
     alert("You manage to fight it off eventually, but not without some extreme injuries. You are bleeding heavily from your neck, where the creature has bitten you."); 
 
     alert("The scent of your blood attracts more of the creatures."); 
 
     var run = confirm("Do you want to run?"); 
 
     if (run === true) { 
 
     alert("You get back on your feet and start running..."); 
 
     alert("...but it's not enough. The creatures outnumber you, though you can't see how many there are."); 
 
     alert("They overpower you and devour you. You died."); 
 
     return; 
 
     } else { 
 
     alert("You sit back and await your approaching doom."); 
 
     alert("The creatures surround you and tear you to pieces. You died."); 
 
     return; 
 
     }; 
 
    }; 
 
    } else { 
 
    alert("You decide not to look inside the structure and continue walking."); 
 
    }; 
 
    alert("Your legs begin to feel tired, so you check your watch. It is now 30 minutes into the morning. You know you must find a way out of the woods soon as you are feeling tired and hungry."); 
 
    alert("You hear rustling behind you and spin round..."); 
 
    if (torchSearch === true) { 
 
    alert("You point your torch at the noise and a fleck of white catches your eye in the blackness of the night."); 
 
    alert("You move your torch about and more patches of white appear until they start to form the shapes of creatures."); 
 
    alert("One of the creatures emerges from the darkness onto the path from where you just came."); 
 
    alert("It is small, not much higher than your waist, and has bright red eyes. Its skin is inexplicably pale and scarred in several places."); 
 
    alert("More creatures step out into the torchlight and slowly begin hobbling towards you."); 
 
    var runFrom = confirm("Do you want to run?"); 
 
    if (runFrom === true) { 
 
     alert("You turn away from them and begin to pick up your pace, going from a walk to a jog and eventually into a sprint."); 
 
     alert("Despite your incredible speed, you can hear the creatures close behind at all times."); 
 
     alert("You feel the ground under your feet change from soft soil to hard rock."); 
 
     var checkSurroundings = confirm("The creatures are still hot on your heels. Do you want to pause to check out your surroundings?"); 
 
     if (checkSurroundings === true) { 
 
     alert("You slow down, shining your torch around and notice a cliff edge up ahead. You notice how you are now on top of a cliff, in an open space."); 
 
     alert("You quickly change direction and begin running parallel to the cliff edge."); 
 
     } else { 
 
     alert("You pick up the pace, set on the path ahead...."); 
 
     alert("...which suddenly disappears from underneath you."); 
 
     alert("You are falling..."); 
 
     alert("...for ever..."); 
 
     alert("...until you hit the floor."); 
 
     alert("You died."); 
 
     return; 
 
     }; 
 
    } else { 
 
     alert("You stay put, observing the creatures as they approach. Keeping the torchlight fixed on them, your hands begin to shake as you notice the closer ones gnashing their teeth."); 
 
     alert("Frozen in fear, you begin to sweat as the first creature reaches you and sniffs you."); 
 
     alert("The creature jumps onto you, knocking you to the ground and licks your face."); 
 
     alert("The others surround you and the one on top of you bites your neck."); 
 
     alert("You scream in pain as the creatures eat you alive."); 
 
     return; 
 
    }; 
 
    } else { 
 
    alert("You cannot make out anything behind you, dismissing it as your imagination."); 
 
    alert("You feel the ground under your feet change from soft soil to hard rock."); 
 
    alert("You pick up the pace, set on the path ahead...."); 
 
    alert("...which suddenly disappears from underneath you."); 
 
    alert("You are falling..."); 
 
    alert("...for ever..."); 
 
    alert("...until you hit the floor."); 
 
    alert("You died."); 
 
    return; 
 
    }; 
 
    alert("The cliff eventually becomes a road and you hear the creatures behind you scream with anger as you reach a lamp post and are safely in the light."); 
 
    alert("You can see the lights of a town ahead of you, and head for them."); 
 
    alert("You check your watch. The time is now 1am. You're feeling extremely fatigued and don't know if you can make it to the next town."); 
 
    var sit = confirm("There is a bench beside the road. Do you want to sit down, and rest?"); 
 
    if (sit === true) { 
 
    alert("With the creatures well out of reach, you take a seat on the bench and close your eyes."); 
 
    } else { 
 
    alert("You decide to soldier on until you reach the town."); 
 
    alert("Unfortunately, you overestimated the capacity of your own stamina and collapse in the middle of the road and black out."); 
 
    }; 
 
    alert("END OF EPISODE I."); 
 
    var restart = confirm("Do you want to restart?"); 
 
    if (restart === true) { 
 
    theElderwood1(); 
 
    return; 
 
    } else { 
 
    scoreCount += 1; 
 
    score(1, 'theElderwood2'); 
 
    alert("UNLOCKED! The Elderwood: Episode II"); 
 
    return; 
 
    }; 
 
};

Как вы можете видеть, это очень просто и не очень удобно все эти всплывающие окна. Любая помощь/советы по этому поводу будут очень признательны! Благодаря!

+0

Добро пожаловать в So - пожалуйста, включите ваш код в вопрос, а не ссылку –

+0

Извините, я так делаю сейчас. – Sabrewolf

+0

Это довольно длинный, но я надеюсь, что я объяснил проблему ... – Sabrewolf

ответ

0

Вот глобальный взгляд на то, что вам нужно, надеюсь, что это поможет!

  1. Если вы плохо знаете HTML, сделайте несколько руководств по нему. Не бойтесь этого, HTML - это даже не язык программирования, а язык разметки, сделанный для организации данных, намного проще, чем Javascript. Вы также захотите изучить CSS, как только увидите, как выглядит чистый чистый HTML-код.

  2. Вам нужно где-то написать на странице HTML. A <p> тег где-то внутри <body> будет в порядке. Дайте ему идентификатор, чтобы вы могли легко получить его позже: <p id="story"></p>

  3. Для того, чтобы найти, где писать, нужен ваш Javascript. Используйте document.getElementById(id).

  4. Что вы редактируете на странице, это текст, я бы не рекомендовал использовать .innerHTML, даже если это может показаться проще. Вы хотите создать текстовый узел, который вы можете сделать с помощью document.createTextNode(text).

  5. Как только у вас есть свой текстовый узел и знаете, где его разместить, просто используйте element.appendChild(otherElement). «element» - это элемент, полученный от getElementById, тогда как «otherElement» должен быть созданным текстовым узлом.

  6. Добавление текста в порядке, но вы также должны удалить его в какой-то момент! Конечно, было бы неплохо сделать скроллер в красивой панели с цветом папируса, но для начала изучите, как использовать element.removeChild, чтобы удалить текст предыдущей строки. Здесь есть несколько шагов, но я не знаю, как много вы знаете о javascript, так что, возможно, с вами все будет в порядке, или, может быть, это будет еще один вопрос StackOverflow?

  7. После того, как все это работает нормально, вы хотите, чтобы заменить confirm() звонки с <button> с, а может быть, чтобы добавить текстовую зону <input> задавать вопросы игроку, но это выходит за рамки данного вопроса ,

Удачи вам!

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