다시 묻게되어 미안하지만 컨텍스트에 대한 코드를 더 추가하고 싶었습니다.
가위 바위 보 게임을 만들고 있는데 버튼을 눌렀을 때 playerChoice 키를 바꾸고 싶습니다.
각 버튼에 onclick 이벤트를 추가하고 gameOptions 인덱스를 참조하도록 playerChoice 속성을 설정하는 함수를 실행하고 싶습니다.
<!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()
다음을 사용하여 코드를 단순하게 유지할 수 있습니다.
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 속성 만 가져올 수 있습니다. 승리 조건 확인의 경우 단순히 동일한 지 확인하여 여러 "if"문을 제거 할 수 있으며 그렇지 않은 경우 인간의 선택을 이길 수있는 컴퓨터 선택과 비교하고 그에 따라 결과를 설정합니다. 더 최적화 할 수 있지만 이것에서 뭔가를 배우고 싶어서 바이올린에 대해서도 언급했습니다.
이 예제에서는 플레이어가 선택할 수 있도록 fight () 함수를 버튼 핸들러로 옮겼으며 컴퓨터의 선택도 해당 지점에서만 트리거됩니다. 원래 코드에는 함수를 호출하고 변수를 설정했지만 사용하지 않은 몇 가지 인스턴스와 몇 가지 구문 오류가있었습니다.
첨부 된 바이올린 참조 : https://jsfiddle.net/s0toz3L8/2/
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다