2016-04-14 2 views
1

Это простая игра-палач, я сделал клавиатуру алфавита кнопками, поэтому onclick следует вызвать функцию checkLetter на проверить, выбрана ли буква, выбранная в слово, которое нужно угадать или не эта часть, он не запускается и как удалить букву на кнопке, когда пользователь щелкнул по ней, чтобы помешать ему снова выбрать ее ?!
это мой код начинается с HTML затем Javascript Hangman игра, сравнивающая букву, которую пользователь выбрал с буквами в слове, чтобы быть догадками

var B 
 
    ,L 
 
    ,placeholder 
 
    ,correctGuesses 
 
    ,wrongGuesses 
 
    ,wordToGuess 
 
    ,wordLength 
 
    ,words=[] 
 
    ,wrongletter=true; 
 

 
    function newGame() 
 
    { 
 
     //initialize all the variables 
 
     placeholder=""; 
 
     correctGuesses=0; 
 
     wrongGuesses=0; 
 
     wordToGuess=getWord(); 
 
     wordLength=wordToGuess.length; 
 
     
 
     //make a loop that replaces underscores with the word to be guessed 
 
     for(var i=0;i<wordLength;i++) 
 
     { 
 
     \t placeholder+="_ "; 
 
     } 
 
     document.getElementById("placeforword").innerHTML=placeholder; 
 
     
 
     //loop to make a keyboard of buttons 
 
     //B hold the buttons 
 
    B = ''; 
 
    //L hold letters 
 
    L; 
 
    //this loop to get the letters by charcode 
 
    for (var i = 65; 90 >= i; i++) {// A-65, Z-90 
 
     L = String.fromCharCode(i); 
 
     B += '<button id="B2" onclick="getLetter(\''+L+'\');">' + L + '</button>'; 
 
    } 
 
    document.getElementById("box1").innerHTML = B; 
 
    drawCanvas(); 
 
    } 
 
    function getLetter(x) 
 
    { 
 
     checkLetter(x); 
 
    } 
 
    function checkLetter(letter) 
 
    { 
 
    \t document.getElementById("placeforword").innerHTML=placeholder; 
 
     placeholder=placeholder.split(""); 
 
       for(var i=0;i<wordLength;i++) 
 
      { 
 
      \t if(wordToGuess.charAt(i)===letter.toLowerCase()) 
 
      \t { 
 
       placeholder[i]=letter; 
 
       wrongletter=false; 
 
       correctGuesses++; 
 
      \t } 
 
      \t if(correctGuesses===wordLength) 
 
      \t { 
 
      \t \t //if all letters have been guessed that mean u guessed all the correct letters and u win 
 
      \t \t //call the drawCanvas 
 
      \t \t drawCanvas(); 
 
    
 
      \t } 
 
      } 
 
      \t //if ur guess was wrong 
 
    \t if(wrongGuess) 
 
    \t { 
 
    \t \t badGuesses++; 
 
    \t \t drawCanvas();//this function to draw the body of the victim 
 
    \t } 
 
    \t document.getElementById("placeforword").innerHTML=placeholder.join(""); 
 
     
 
    } 
 
function getWord() 
 
{ 
 
\t var a=["bad","happy","anyotherwords"]; 
 
\t //choose a random word 
 
\t return a[parseInt(Math.random()*a.length)]; 
 
}
<html> 
 

 
<head> 
 
    <title>New Game</title> 
 
    <style type="text/css"> 
 
    #B1 { 
 
     background-color: #4CAF50; 
 
     color: white; 
 
     font-size: 24px; 
 
    } 
 
    #box2 { 
 
     width: 350px; 
 
     height: 350px; 
 
     padding: 10px; 
 
     background-color: blue; 
 
     text-align: center; 
 
    } 
 
    </style> 
 
</head> 
 

 
<body> 
 
    <div id="container" style="width:100%;"> 
 
    <div id="left" style="float:left;width:50%;"> 
 
     <div id="newgame"> 
 
     <button onclick="newGame()" id="B1">New Game</button> 
 
     <br> 
 
     <br> 
 
     </div> 
 
     <!--<div id="newgame1"></div>--> 
 
     <div id="box1"></div> 
 
     <div> 
 
     <p id="placeforword"></p> 
 
     </div> 
 
     <div id="box2"> 
 
     <h1>Letters u Guessed</h1> 
 
     </div> 
 
    </div> 
 
    <div id="right" style="float:right;width:50%;"> 
 
     <div> 
 
     <canvas id="stage" width="643" height="643" style="border:5px solid #000000;"></canvas> 
 
     </div> 
 
    </div> 
 
    </div> 
 

 

+2

Пожалуйста, используйте знаки препинания. Я понимаю, что английский язык не является первым языком многих пользователей, но ваш вопрос почти не читается. –

ответ

0

Ваш идентификатор кнопки должен быть уникальным. Таким образом изменить цикл, который создает кнопку для

for (var i = 65; 90 >= i; i++) {// A-65, Z-90 
    L = String.fromCharCode(i); 
    B += '<button id="'+L+'" onclick="getLetter(\''+L+'\');">' + L + '</button>'; 
} 

И в getLetter() функции можно отключить кнопку,

function getLetter(x) 
{ 
    checkLetter(x); 
    document.getElementById(x).disabled = true; 
} 
+0

Это не сработало, только одна буква заменена подчеркиванием, и кнопка не отключена – emma

+0

что-то не так с остальной частью моего кода? !! – emma

+0

В моем коде была небольшая ошибка с меткой '' 'на'

0

Переработанный с кодом. Изменения комментируются самим фрагментом.

Мои комментарии размещены между ///////// и \\\\\\\\\\\ для удобства понимания.

Функция drawCanvas() была закомментирована, потому что она не определена.

var B 
 
    ,L 
 
    ,placeholder 
 
    ,correctGuesses 
 
    ,wrongGuesses 
 
    ,wordToGuess 
 
    ,wordLength 
 
    ,words=[] 
 
    ,wrongletter=true; 
 

 
    function newGame() 
 
    { 
 
     //initialize all the variables 
 
     placeholder=[]; /////////initialize placeholder as an array\\\\\\\\\\\ 
 
     correctGuesses=0; 
 
     wrongGuesses=0; 
 
     wordToGuess=getWord(); 
 
     wordLength=wordToGuess.length; 
 
     
 
     //make a loop that replaces underscores with the word to be guessed 
 
     for(var i=0;i<wordLength;i++) 
 
     { 
 
     \t placeholder[i] = "_ "; /////////instead of concatinating string add '_' to placeholder array\\\\\\\\\\\ 
 
     } 
 
     document.getElementById("placeforword").innerHTML=placeholder.join(""); 
 
     
 
     //loop to make a keyboard of buttons 
 
     //B hold the buttons 
 
    B = ''; 
 
    //L hold letters 
 
    L; 
 
    //this loop to get the letters by charcode 
 
    for (var i = 65; 90 >= i; i++) {// A-65, Z-90 
 
     L = String.fromCharCode(i); 
 
     B += '<button id="'+L+'" onclick="getLetter(\''+L+'\');">' + L + '</button>'; /////////button id should be unique. So give each button with letter as id \\\\\\\\\\\ 
 
    } 
 
    document.getElementById("box1").innerHTML = B; 
 
    //drawCanvas(); 
 
    } 
 
    function getLetter(x) 
 
    { 
 
     document.getElementById(x).disabled = true; /////////disable button that clicked\\\\\\\\\\\ 
 
     checkLetter(x); 
 
    } 
 
    function checkLetter(letter) 
 
    { 
 
     wrongletter=true; 
 
    \t document.getElementById("placeforword").innerHTML=placeholder; 
 
//  placeholder=placeholder.split(""); /////////no need this since the placeholder is now an array\\\\\\\\\\\ 
 
       for(var i=0;i<wordLength;i++) 
 
      { 
 
      \t if(wordToGuess.charAt(i)===letter.toLowerCase()) 
 
      \t { 
 
       placeholder[i]=letter; 
 
       wrongletter=false; 
 
       correctGuesses++; 
 
      \t } 
 
      \t if(correctGuesses===wordLength) 
 
      \t { 
 
      \t \t //if all letters have been guessed that mean u guessed all the correct letters and u win 
 
      \t \t //call the drawCanvas 
 
      \t \t //drawCanvas(); 
 
    
 
      \t } 
 
      } 
 
      \t //if ur guess was wrong 
 
    \t if(wrongletter) /////////I think you mistakenly gave the variable name here\\\\\\\\\\\ 
 
    \t { 
 
    \t \t wrongGuesses++; /////////I think you mistakenly gave the variable name here\\\\\\\\\\\ 
 
    \t \t //drawCanvas();//this function to draw the body of the victim 
 
    \t } 
 
    \t document.getElementById("placeforword").innerHTML=placeholder.join(""); 
 
     
 
    } 
 
function getWord() 
 
{ 
 
\t var a=["bad","happy","anyotherwords"]; 
 
\t //choose a random word 
 
\t return a[parseInt(Math.random()*a.length)]; 
 
}
<html> 
 

 
<head> 
 
    <title>New Game</title> 
 
    <style type="text/css"> 
 
    #B1 { 
 
     background-color: #4CAF50; 
 
     color: white; 
 
     font-size: 24px; 
 
    } 
 
    #box2 { 
 
     width: 350px; 
 
     height: 350px; 
 
     padding: 10px; 
 
     background-color: blue; 
 
     text-align: center; 
 
    } 
 
    </style> 
 
</head> 
 

 
<body> 
 
    <div id="container" style="width:100%;"> 
 
    <div id="left" style="float:left;width:50%;"> 
 
     <div id="newgame"> 
 
     <button onclick="newGame()" id="B1">New Game</button> 
 
     <br> 
 
     <br> 
 
     </div> 
 
     <!--<div id="newgame1"></div>--> 
 
     <div id="box1"></div> 
 
     <div> 
 
     <p id="placeforword"></p> 
 
     </div> 
 
     <div id="box2"> 
 
     <h1>Letters u Guessed</h1> 
 
     </div> 
 
    </div> 
 
    <div id="right" style="float:right;width:50%;"> 
 
     <div> 
 
     <canvas id="stage" width="643" height="643" style="border:5px solid #000000;"></canvas> 
 
     </div> 
 
    </div> 
 
    </div>

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