2015-04-23 2 views
0

Итак, я создаю эту основанную на тексте RPG в JavaScript и после того, как создаю имя и введите y в подсказку, программа замерзает. Может кто-нибудь, пожалуйста, помогите мне? Проблема заключается в том, что я подтверждаю имя и меняю значение переменной settingTheName на другое число и передает его функции uiPrompt, которая просто замерзает. Я понятия не имею, почему это происходит.Программа Javascript замерзает при определенном нажатии клавиши. Зачем?

<!doctype html> 
<html> 
<head> 
<title>Random RPG</title> 
</head> 
<body> 
<p id="text"></p> 
<input id="prompt"/> 
<button id='butoon' onclick="uiPrompt(options,functions)">Enter</button> 
<script> 

var settingTheName = 0; 

//used for ui to determine in certain prompts which commands are acceptable 
var options; 
//the input that the player puts in the ui box 
var playerInput; 
var functions= { 
     newGame: function() { 
       document.getElementById('text').innerHTML = 'Welcome to the world of Aldania, a magical and mystical world where anything can happen! Aldania is filled with adventure so grab a sword, some Mountain Dew, Doritos, and click the link below to download some free ram! Just Kidding! We are going to create a new character for you! Lets start with his name.'; 
      settingTheName = 1; 
     }, 
     loadGame: function() { 
       document.getElementById('text').innerHTML = 'Welcome to the world of Aldania, a magical and mystical world where anything can happen! Aldania is filled with adventure so grab a sword, some Mountain Dew, Doritos, and click the link below to download some free ram! Just kidding! Just create a fucking character aoadBSIHBIYCBSIY the game.'; 
     }, 
     setName: function() { 
      playerInput = document.getElementById("prompt").value; 
      document.getElementById('text').innerHTML = 'Are you sure you want your character to be named ' +playerInput+ '? Press Y for yes and N for No.'; 
      options= { 
       createTheChar: ['y', 'yes'], 
       newGame: ['n', 'no'] 
      }; 
     }, 
     creeteTheChar: function() { 
      for (var j=0; j < 7; ++j) { 
       if (j=0) { 
        document.getElementById('text').innerHTML = 'Do you prefer to channel your power with your faith in God or the Devil?'; 
       } else if (j=1) { 
        document.getElementById('text').innerHTML = 'Whats your favorite element? Fire, Cold, Lightning, or Poison?'; 
       } else if (j=2) { 
        document.getElementById('text').innerHTML = 'Are you more of a guy who is very defensive or more ferocious?'; 
       } else if (j=3) { 
        document.getElementById('text').innerHTML = 'Would you like to run around yelling incantations and throwing magic missiles or unleash the power of the mind upon your foes?'; 
       } else if (j=4) { 
        document.getElementById('text').innerHTML = 'When keeping undercover, do you use the shadows to your advantage or speedily sneak around?'; 
       } else if (j=5) { 
        document.getElementById('text').innerHTML = 'Are you the happy go lucky type of guy or do you prefer to meticulously calculate your plans?'; 
       } else if (j=6) { 
        document.getElementById('text').innerHTML = 'Do you wanna play a super silly character?'; 

       }    
      } 
     } 
}; 

//handles user input 
function uiPrompt() { 
    playerInput = document.getElementById("prompt").value; 
    if (settingTheName == 1) { 
     document.getElementById('text').innerHTML = 'Are you sure you want your character to be named ' +playerInput+ '? Press Y for yes and N for No.'; 
     options= { 
      creeteTheChar: ['y', 'yes'], 
      newGame: ['n', 'no'] 
     }; 
     settingTheName = 2; 
    } else { 
     for (functionName in options) { 
      // check if playerInput is in options[functionName] array 
      if (options[functionName].indexOf(playerInput) >= 0) { 
        functions[functionName]() // call function 
       break 
      } 
     } 
    } 
} 

//start menu at the beginning of the game 
function startMenu() { 
    options= { 
     newGame: ['n', 'new game', 'game'], 
     loadGame: ['l', 'load game', 'game'] 
    }; 
    document.getElementById('text').innerHTML = 'RANDOM RPG: Where everything is random as f***! \n (N)ew Game \n (L)oad Game'; 
} 

startMenu(); 
</script> 
</body> 
</html> 
+1

Вашей 'Функция creeteTheChar' устанавливает J для каждого из значений 0-6 вместо сравнения его с каждым из этих значений. –

ответ

1

Ваша функция «creeteTheChar» нужно использовать == вместо того, чтобы просто = при проверке, если переменная равна значению. В противном случае вы устанавливаете значение каждый раз. Это приводит к бесконечной остановке вашей функции, поскольку j всегда будет меньше 7.

Вы также хотите увеличить j после каждой итерации, а не раньше. Поэтому вместо ++ j вы выполняете j ++. Если вы этого не сделаете, j == 0 никогда не будет правдой. Кроме того, функция creeteTheChar не ждет ввода какого-либо пользователя, прежде чем перейти к следующей итерации в цикле. Поэтому он заканчивает тем, что заканчивает цикл, и «Хочешь играть супер глупым персонажем?» отображается.

Не обескураживайте вас, но вы хотите, чтобы ваш код был более динамичным, если вы намереваетесь иметь много вариантов. В противном случае вы окажетесь с горными процедурами, которые невозможно контролировать и отслеживать ошибки. Чтобы сделать это правильно, вы захотите использовать классы.

В любом случае, вот функция creeteTheChar правильно оценить значение J:

creeteTheChar: function() { 
     console.log('creating character'); 
     for (var j=0; j < 7; j++) { 
      if (j==0) { 
       document.getElementById('text').innerHTML = 'Do you prefer to channel your power with your faith in God or the Devil?'; 
      } else if (j==1) { 
       document.getElementById('text').innerHTML = 'Whats your favorite element? Fire, Cold, Lightning, or Poison?'; 
      } else if (j==2) { 
       document.getElementById('text').innerHTML = 'Are you more of a guy who is very defensive or more ferocious?'; 
      } else if (j==3) { 
       document.getElementById('text').innerHTML = 'Would you like to run around yelling incantations and throwing magic missiles or unleash the power of the mind upon your foes?'; 
      } else if (j==4) { 
       document.getElementById('text').innerHTML = 'When keeping undercover, do you use the shadows to your advantage or speedily sneak around?'; 
      } else if (j==5) { 
       document.getElementById('text').innerHTML = 'Are you the happy go lucky type of guy or do you prefer to meticulously calculate your plans?'; 
      } else if (j==6) { 
       document.getElementById('text').innerHTML = 'Do you wanna play a super silly character?'; 

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