Изменение значения объекта с помощью события onClick - PullRequest
0 голосов
/ 15 марта 2020

Извините, что спросил это снова, но я хотел добавить больше кода для контекста.

Я делаю игру «Ножницы из каменной бумаги» и хочу менять кнопку playerChoice при нажатии кнопки.

Я хочу добавить событие onclick для каждой кнопки и запустить функцию, которая установит свойство playerChoice, чтобы оно ссылалось на индекс gameOptions.


<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>Lapis, Papyrus Scalpellus</h1>

<h2>Make a Choice</h2>
<button id="Lapis">Lapis</button>
<button id="Papyrus">Papyrus</button>
<button id=Scalpellus>Scalpellus</button>
<h2>Game Results</h2>

<script src="script.js"></script>

</body>
</html>


const gameOptions = ["Lapis", "Papyrus", "Scalpellus"];

const newChoice = randomChoice();

console.log(newChoice);

const humanPlayer = {
  playerChoice: gameOptions[0],
};

const computerPlayer = {
  playerChoice: randomChoice(),
};

document.querySelector("#Lapis").onclick = function() {
  humanPlayer.playerChoice = gameOptions[0];
};

document.querySelector("#Papyrus").onclick = function() {
  humanPlayer.playerChoice = gameOptions[1];
};
document.querySelector("#Scalpellus").onclick = function() {
  humanPlayer.playerChoice = gameOptions[2];
};

console.log(humanPlayer);

//Random Choice
function randomChoice() {
  const theChoice = gameOptions[Math.floor(Math.random() * 3)];
  return theChoice;
}

//Players 

function resultText(innerText){
  const paragraph = document.createElement('p');
  paragraph.innerText = innerText;
  document.body.appendChild(paragraph);
}


//Outcomes
function fight(){
  if(computerPlayer.playerChoice === humanPlayer.playerChoice){
     resultText("Its a Tie!20. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
  }else if (computerPlayer.playerChoice === "Lapis"){
    if(humanPlayer.playerChoice === "Papyrus"){
     resultText("Human Player Wins!6. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
    }else if( humanPlayer.playerChoice === "Scalpellus"){
       resultText("Computer Player Wins!5 You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }
  }else if(computerPlayer.playerChoice === "Papyrus"){
    if ( humanPlayer.playerChoice === "Lapis"){
      resultText("Compter Player Wins!4. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }else if( humanPlayer.playerChoice === "Scalpellus"){
      resultText("Human Player Wins!3. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }
  }else if(computerPlayer.playerChoice === "Scalpellus"){
    if ( humanPlayer.playerChoice === "Lapis"){
      resultText("Human Player Wins!2. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);

    }else if( humanPlayer.playerChoice === "Papyrus"){
      resultText("Computer Player Wins!1. You chose " + humanPlayer.playerChoice + " and the computer chose " + computerPlayer.playerChoice);
    }
  }
}

fight()

1 Ответ

1 голос
/ 15 марта 2020

Вы можете использовать следующее, чтобы сохранить ваш код простым:

var btns = document.querySelectorAll("button");
for (var i = 0; i < btns.length; i++){
  btns[i].addEventListener("click", btnHandler);
}

И тогда ваша функция-обработчик будет вызываться при каждом нажатии кнопки без необходимости повторения вашего кода:

function btnHandler(el){
  switch (el.getAttribute("id")){
    case "Papyrus":
    ...
    default: break;
  }
}

Он также позволяет вам передавать сам элемент кнопки, так что вы можете просто извлечь атрибут ID при необходимости, вместо того, чтобы передавать параметр для каждого отдельного экземпляра через отдельные вызовы. Для проверки условия выигрыша вы можете исключить несколько операторов «если», просто посмотрев, равны ли они, а если нет, сравнить только человеческий выбор с выбором компьютера, который победит, и таким образом установить результат. Его можно оптимизировать и дальше, но я думаю, что вы хотели бы кое-что из этого узнать, поэтому я также прокомментировал скрипку.

Для этого примера я также переместил функцию fight () в обработчик кнопок, чтобы у игрока будет выбор, и выбор компьютера будет активирован только в этот момент. В исходном коде было несколько экземпляров, которые вызывали функции и устанавливают переменные, но не использовали их и т. Д. c, а также несколько синтаксических ошибок.

См. Прикрепленную скрипту: https://jsfiddle.net/s0toz3L8/2/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...