Скрипт позволяет создать викторину "угадай номер". Числа,по умолчанию, от 1 до 10. ----------------------------------------------------------------- Пример использования скрипта:
----------------------------------------------------------------- Код скрипта:
Вставьте следующий код между тегами <BODY></BODY>
<form name="quiz_form" id="quiz_form" action="#" onsubmit="return guess_num();"> <label for="Guess">I'm thinking of a number. Can you guess it?</label><br /> <input type="text" name="Guess" id="Guess" size="5" /> <input type="submit" value="Guess!" /> </form> <script type="text/javascript">if (document.getElementById && document.createTextNode) {
/* Maximum number */ var m_num = 10; /* Number of guesses the viewer has */ var num_chances = 3; /* Message displayed after a correct guess */ var you_win = "Correct! You Win!"; /* Message displayed after after all guesses have been used */ var you_lose = "Sorry! You lose!"; /* Message displayed if user guesses too low */ var need_higher = "I\'m looking for a higher number."; /* Message displayed if user guesses too high */ var need_lower = "I\'m looking for a lower number.";
var c = 1; var ran_num = Math.floor(Math.random()*(m_num)); ran_num += 1;
function num_reset() { c = 1; ran_num = Math.floor(Math.random()*(m_num)); ran_num += 1; }
function guess_num() {
var user_guess = document.getElementById("Guess").value; user_guess *= 1;
var to_match = /\d+/; var is_num = to_match.test(user_guess);
if (!is_num) { window.alert("Guesses must be numeric."); return false; }
if ( (user_guess < 1) || (user_guess > m_num) ) { window.alert("Guesses must be between 1 and "+m_num+"."); return false; }
if (c<=num_chances) {
var chances_left = num_chances-c; var sing_plural = "guesses"
if (user_guess == ran_num) { window.alert(you_win); num_reset(); return false; } else {
if (c == num_chances) { window.alert(you_lose+"\n\nI was looking for the number "+ran_num+"!"); num_reset(); return false; } else { var which_way = (user_guess < ran_num) ? need_higher : need_lower; if (chances_left == 1) { sing_plural = "guess"; } window.alert(which_way+" You have "+chances_left+" "+sing_plural+" left!"); c+=1; return false; } } } else { return false; }
}
}
</script>
|