R_random.html ->보여지는 화면
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Random Game</title>
<style>
h1{
margin-left: 80px;
}
body {
background-color: black;
color: white;
width : 50%;
max-width: 800px;
min-width : 480px;
margin : 0 auto; //중앙 정렬을 하겠다는 뜻
}
</style>
</head>
<body>
<h1>랜덤 숫자 맞추기</h1>
<p>1부터 100까지 랜덤 숫자를 맞춰주세요. 총 10번의 기회가 있습니다.</p>
<div class="form">
<label for="guessField">Enter a guess: </label>
<input type="text" id="guessText" class="guessField">
<input type="submit" value="Summit guess" class="submitButton">
</div>
<div class="resultField">
<p class ="inputNumber"></p>
<p class ="result"></p>
<p class = "hint"></p>
</div>
<script src = "Random1.js">
</script>
</html>
Random.js -> 자바스크립트 파일
let randomNumber = Math.floor(Math.random() * 100)+1;
const inputNumber = document.querySelector(".inputNumber");
const result = document.querySelector(".result");
const hint = document.querySelector(".hint");
const guessField = document.querySelector(".guessField");
const submitButton = document.querySelector(".submitButton");
let count =1;
let resetButton;
function checkGuess() {
let userGuess =Number(guessField.value);
if( count ===1){
inputNumber.textContent='Previous : ';
}
inputNumber.textContent += userGuess+ ' ';
if(userGuess === randomNumber){
result.textContent ="축하드립니다 정답을 맞추셨습니다.";
result.style.backgroundColor ='green';
hint.textContent = '';
setGameOver();
} else if(count ===10){
result.textContent ="게임이 종료되었습니다."
result.style.backgroundColor ='red';
hint.textContent = '';
setGameOver();
} else{
result.textContent ='틀리셨습니다 다시 입력해주세요';
result.style.backgroundColor ='red';
if(randomNumber > userGuess){
hint.textContent = '입력 하신 숫자가 너무 작습니다';
}
else if(randomNumber < userGuess){
hint.textContent = '입력하신 숫자가 너무 큽니다.';
}
}
count++;
guessField.value ='';
guessField.focus();
}
submitButton.addEventListener('click', checkGuess);
function setGameOver(){
guessField.disabled = true;
submitButton.disabled =true;
resetButton = document.createElement('button');
resetButton.textContent ='게임 다시 시작';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
count =1;
const resetField = document.querySelectorAll('.resultField p');
for(let i =0; i<resetField.length ; i++){
resetField[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
submitButton.disabled = false;
guessField.value ='';
guessField.focus();
inputNumber.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random()*100)+1;
}
참고 ->https://developer.mozilla.org/ko/docs/Learn/JavaScript/First_steps/A_first_splash