#javascript #html #random
Вопрос:
Я сделал простую игру «камень-ножницы-бумага», используя HTML JavaScript, CSS и RandoJs Для случайных выборов, Но у меня возникли некоторые проблемы с логикой
var rock = document.getElementById("rock"); // Getting User pickable Rock Element
var paper = document.getElementById("paper"); // Getting User Pickable Paper Element
var scissor = document.getElementById("scissor"); // Getting User Pickable Scissor Element
let robotPick = ["rock", "paper", "scissor"]; // What Robot Can Pick
// Getting Human Score Element For Changing Scores
var humanScore = document.getElementById("humanScore");
var robotScore = document.getElementById("robotScore");
var message = document.getElementById("message"); // Getting message Element
// Adding Event Listeners To Pickable Elements
window.addEventListener("load", function(e) {
rock.addEventListener("click", function(e) { checkWin("rock"); });
paper.addEventListener("click", function(e) { checkWin("paper"); });
scissor.addEventListener("click", function(e) { checkWin("scissor"); });
});
function checkWin(pick) {
let humanPick = pick;
let picks = rando(robotPick).index; // What Robot Will Pick is Generated Randomly using RandoJS
let whoWon; // This Will Contain Who Won
// Main Logic
if (humanPick === "rock" || robotPick[picks] === "rock") whoWon = "tie";
if (humanPick === "rock" || robotPick[picks] === "paper") whoWon = "robot";
if (humanPick === "rock" || robotPick[picks] === "scissor") whoWon = "human";
if (humanPick === "paper" || robotPick[picks] === "paper") whoWon = "tie";
if (humanPick === "paper" || robotPick[picks] === "scissor") whoWon = "robot";
if (humanPick === "paper" || robotPick[picks] === "rock") whoWon = "human";
if (humanPick === "scissor" || robotPick[picks] === "scissor") whoWon = "tie";
if (humanPick === "scissor" || robotPick[picks] === "rock") whoWon = "robot";
if (humanPick === "scissor" || robotPick[picks] === "paper") whoWon = "human";
// Checking Who Won!
if (whoWon === "human") {
let x = parseInt(humanScore.innerHTML);
message.innerHTML = "Robot Chose " robotPick[picks];
x ; humanScore.innerHTML = x;
}
if (whoWon === "robot") {
let x = parseInt(robotScore.innerHTML);
message.innerHTML = "Robot Chose " robotPick[picks];
x ; robotScore.innerHTML = x;
}
if (whoWon === "tie") {
let x = parseInt(robotScore.innerHTML);
message.innerHTML = "Robot Chose " robotPick[picks];
x ; robotScore.innerHTML = x;
}
}
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rock, Paper amp; Scissors</title>
<style>*{transition:all 0.2s ease;-webkit-transition:all 0.2s ease}body{position:absolute;font-family:sans-serif;transform:translate(-50%, -50%);background:#252525;left:50%;top:50%;user-select:none}.body i{font-size:4em;margin:5px}.score{font-size:1.5em;text-align:center;margin-top:2em}p{margin:20px 0;padding:0;color:#ffd900;font-size:0.9em}#hands{text-align:center}#hands i{margin:10px;font-size:3em;color:#ffd900;cursor:pointer}#hands i:hover{transform:scale(1.3)}.humanScore{color:#48ff00}.robotScore{color:#00ccff}</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
</head>
<body>
<div id="hands">
<i id="rock" class="fas fa-hand-rock"></i>
<i id="paper" class="fas fa-hand-paper"></i>
<i id="scissor" class="fas fa-hand-peace"></i>
</div>
<div class="score">
<span class="humanScore"><i class="fas fa-user-alt"></i> <span id="humanScore">0</span></span>
amp;nbsp;amp;nbsp;
<span class="robotScore"><i class="fas fa-robot"></i> <span id="robotScore">0</span></span>
<p id="message">Choose First</p>
</div>
<script src="https://randojs.com/2.0.0.js"></script>
Когда есть связь, она не работает, и я использую RandoJs для случайного выбора выбора робота. Есть ли другой способ сделать это ?
Я указал, что я сделал внутри кода, используя комментарии
А также я использую шрифт Awesome 5 Для Иконок!
Комментарии:
1. пожалуйста, дважды проверьте свой код, условная ветвь для связи увеличивает переменную, содержащую оценку робота, а затем присваивает ее robotScore, т. Е.. вы инструктируете машину, чтобы она дала роботу точку на галстуке … и посмотрите также ответ Криллвуда 🙂
Ответ №1:
Вы выполняете ИЛИ проверяет ( ||
) вместо И проверяет ( amp;amp;
), измените на:
if (humanPick === "rock" amp;amp; robotPick[picks] === "rock") whoWon = "tie";
if (humanPick === "rock" amp;amp; robotPick[picks] === "paper") whoWon = "robot";
if (humanPick === "rock" amp;amp; robotPick[picks] === "scissor") whoWon = "human";
if (humanPick === "paper" amp;amp; robotPick[picks] === "paper") whoWon = "tie";
if (humanPick === "paper" amp;amp; robotPick[picks] === "scissor") whoWon = "robot";
if (humanPick === "paper" amp;amp; robotPick[picks] === "rock") whoWon = "human";
if (humanPick === "scissor" amp;amp; robotPick[picks] === "scissor") whoWon = "tie";
if (humanPick === "scissor" amp;amp; robotPick[picks] === "rock") whoWon = "robot";
if (humanPick === "scissor" amp;amp; robotPick[picks] === "paper") whoWon = "human";
Комментарии:
1. Рад помочь 🙂
Ответ №2:
Ваша проблема исходит от оператора ||
, которого вы используете, потому if(A || B)
что означает if A is true OR B is true then
aka. вам нужно, чтобы только одно из утверждений было истинным, чтобы ввести утверждение if. Где как if(A amp;amp; B)
означает if A is true AND B is true then
, что оба утверждения должны быть истинными, чтобы соответствовать утверждению if.
В основном переключайтесь на ||
с. amp;amp;
Надеюсь, вы понимаете разницу между ||
и amp;amp;
Ответ №3:
Логика, как указывалось, требует логического AND
, а не OR
и когда есть ничья, либо оба должны набрать очко, либо ни один из них не должен забивать, последнее более уместно.
var rock = document.getElementById("rock"); // Getting User pickable Rock Element
var paper = document.getElementById("paper"); // Getting User Pickable Paper Element
var scissor = document.getElementById("scissor"); // Getting User Pickable Scissor Element
let robotPick = ["rock", "paper", "scissor"]; // What Robot Can Pick
// Getting Human Score Element For Changing Scores
var humanScore = document.getElementById("humanScore");
var robotScore = document.getElementById("robotScore");
var message = document.getElementById("message"); // Getting message Element
// Adding Event Listeners To Pickable Elements
window.addEventListener("load", function(e) {
rock.addEventListener("click", function(e) { checkWin("rock"); });
paper.addEventListener("click", function(e) { checkWin("paper"); });
scissor.addEventListener("click", function(e) { checkWin("scissor"); });
});
function checkWin(pick) {
let humanPick = pick;
let picks = rando(robotPick).index; // What Robot Will Pick is Generated Randomly using RandoJS
let whoWon; // This Will Contain Who Won
// Main Logic
if (humanPick === "rock" amp;amp; robotPick[picks] === "rock") whoWon = "tie";
if (humanPick === "rock" amp;amp; robotPick[picks] === "paper") whoWon = "robot";
if (humanPick === "rock" amp;amp; robotPick[picks] === "scissor") whoWon = "human";
if (humanPick === "paper" amp;amp; robotPick[picks] === "paper") whoWon = "tie";
if (humanPick === "paper" amp;amp; robotPick[picks] === "scissor") whoWon = "robot";
if (humanPick === "paper" amp;amp; robotPick[picks] === "rock") whoWon = "human";
if (humanPick === "scissor" amp;amp; robotPick[picks] === "scissor") whoWon = "tie";
if (humanPick === "scissor" amp;amp; robotPick[picks] === "rock") whoWon = "robot";
if (humanPick === "scissor" amp;amp; robotPick[picks] === "paper") whoWon = "human";
// Checking Who Won!
if (whoWon === "human") {
let x = parseInt(humanScore.innerHTML);
message.innerHTML = "Robot Chose " robotPick[picks] ' - you win!';
x ; humanScore.innerHTML = x;
}
if (whoWon === "robot") {
let x = parseInt(robotScore.innerHTML);
message.innerHTML = "Robot Chose " robotPick[picks] ' - Robot wins!';
x ; robotScore.innerHTML = x;
}
if (whoWon === "tie") {
let x = parseInt(robotScore.innerHTML);
let y = parseInt(humanScore.innerHTML);
message.innerHTML = "You both Chose " pick;
robotScore.innerHTML = x;
humanScore.innerHTML = y;
}
}
*{transition:all 0.2s ease;-webkit-transition:all 0.2s ease}body{position:absolute;font-family:sans-serif;transform:translate(-50%, -50%);background:#252525;left:50%;top:50%;user-select:none}.body i{font-size:4em;margin:5px}.score{font-size:1.5em;text-align:center;margin-top:2em}p{margin:20px 0;padding:0;color:#ffd900;font-size:0.9em}#hands{text-align:center}#hands i{margin:10px;font-size:3em;color:#ffd900;cursor:pointer}#hands i:hover{transform:scale(1.3)}.humanScore{color:#48ff00}.robotScore{color:#00ccff}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
<div id="hands">
<i id="rock" class="fas fa-hand-rock"></i>
<i id="paper" class="fas fa-hand-paper"></i>
<i id="scissor" class="fas fa-hand-peace"></i>
</div>
<div class="score">
<span class="humanScore"><i class="fas fa-user-alt"></i> <span id="humanScore">0</span></span>
amp;nbsp;amp;nbsp;
<span class="robotScore"><i class="fas fa-robot"></i> <span id="robotScore">0</span></span>
<p id="message">Choose First</p>
</div>
<script src="https://randojs.com/2.0.0.js"></script>
—обновление—
После странного рабочего дня я немного поиграл с кодом, когда вернулся, так как почувствовал, что существует более совершенное решение, чем то, которое я опубликовал ранее. Цель всегда состоит в том, чтобы попытаться написать чистую разметку и код, поэтому я смиренно предлагаю здесь бред дегенерата в надежде, что это имеет смысл…
document.addEventListener('DOMContentLoaded',()=>{
const q=(e,n=document)=>n.querySelector(e);
let i=0;
function checkWin( e ) {
let humanScore = q('.score .human span');
let robotScore = q('.score .robot span');
let message = q('#message');
const mt_rand=(a,b)=>Math.floor(Math.random()*(b-a 1) a);
const announce=(m,c)=>message.innerHTML=[ 'Robot picked ' c, m ].join(' - ');
const lookup={
'Rock':'r',
'Paper':'p',
'Scissors':'s'
};
const options=Object.keys( lookup );
const matrix=[
/* player chooses Rock */
['r','r',0], //draw
['r','p',0], //lose
['r','s',1], //win
/* Player chooses Paper */
['p','p',0], //draw
['p','r',1], //win
['p','s',0], //lose
/* Player chooses Scissors */
['s','s',0], //draw
['s','r',0], //lose
['s','p',1] //win
];
let pick=e.target.dataset.id;
let rp=mt_rand( 0, options.length - 1 );
matrix.some( a=>{
let robot=lookup[ options[ rp ] ];
let human=lookup[ pick ];
if( a[0]==human amp;amp; a[1]==robot ){
let msg=a[2] ? 'You win!' : 'Robot wins!';
if( human == robot )msg='It was a draw!';
// find current score for both - cast as number
let hs=Number( humanScore.dataset.score );
let rs=Number( robotScore.dataset.score );
//update both player amp; robot scores
if( human!=robot ){
i ;
// update total count
q('div[data-total]').dataset.total=i;
// scores
humanScore.dataset.score = a[2] ? hs a[2] : hs 0;
robotScore.dataset.score = !a[2] ? rs ( 1 - a[2] ) : rs 0;
// percentages
humanScore.dataset.pc=( ( Number( humanScore.dataset.score ) / i ) * 100 ).toFixed(0);
robotScore.dataset.pc=( ( Number( robotScore.dataset.score ) / i ) * 100 ).toFixed(0);
}
announce( msg, options[ rp ].toLowerCase() );
return true;
}
});
}
// Adding Event Listeners To Pickable Elements
document.querySelectorAll('#hands > i').forEach( n => n.addEventListener( 'click', checkWin ) );
});
*{transition:all 0.2s ease;-webkit-transition:all 0.2s ease}
body{position:absolute;font-family:sans-serif;transform:translate(-50%, -50%);background:#252525;left:50%;top:50%;user-select:none}
.body i{font-size:4em;margin:5px}
.score{font-size:1.5em;text-align:center;margin-top:2em}
p{margin:20px 0;padding:0;color:#ffd900;font-size:0.9em}
#hands{text-align:center}
#hands i{margin:10px;font-size:3em;color:#ffd900;cursor:pointer}
#hands i:hover{transform:scale(1.3)}
.human{color:#48ff00}
.robot{color:#00ccff}
[data-score]:after{ content:" (" attr( data-pc )"%)";font-size:0.75rem; }
[data-score]:before{content:attr(data-score)}
.score > span,
.score > span span{margin:0 0.5rem;display:inline-block;}
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
<div id='hands'>
<i data-id='Rock' class='fas fa-hand-rock'></i>
<i data-id='Paper' class='fas fa-hand-paper'></i>
<i data-id='Scissors' class='fas fa-hand-peace'></i>
</div>
<div class='score' data-total=0>
<span class='human'>
<i class='fas fa-user-alt'></i>
<span data-score=0 data-pc=0></span>
</span>
<span class='robot'>
<i class='fas fa-robot'></i>
<span data-score=0 data-pc=0></span>
</span>
<p id='message'>You choose first</p>
</div>