웹프로그래밍/HTML CSS JavaScript

[JavaScript] Math 객체

아잠만_ 2024. 5. 10. 16:54

Math객체

랜덤 객체

0.0 <= Math.random() < 1.0

Math.floor(Math.random() * (최대값-최소값+1)+최소값)

Math.round(Math.random() * (최대값-최소값)+최소값)

parseInt(Math.random() * (최대값-최소값)+최소값)


<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css"> 
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
const rand = parseInt(Math.random()*100+1);
let count = 0;
function proc1() {
	let num = document.querySelector('#num').value;
	let result ="";
	let tryNum = `${num} `;
	if(rand==num){
		result = `정답!! <br> ${count} 번만에 맞추셨습니다`;
		tryNum = `<span style="color:red">${num}</span> `;
	}else if(rand>num){
		result = "힌트 : 더 큰 수를 입력하세요";
	}else{
		result = "힌트 : 더 작은 수를 입력하세요";
	}
	document.querySelector('#hint').innerHTML=result;
	document.querySelector('#result1').innerHTML+=tryNum;
	count++;
	
}
</script>
</head>
<body>

	<div class="box">
		<h3>랜덤수 발생, 맞추기<br>1부터 100사이 숫자 입력</h3>
		<input id="num">
		<input type="button" value="추측" onclick="proc1()"> <br> <br>
		<h4 id="hint"></h4>
		시도 숫자
		<div id="result1"></div>
	</div>
</body>
</html>

문제

1. 가위 바위 보 게임을 할 수 있는 프로그램을 작성하시오. (컴퓨터는 랜덤, 사용자는 prompt로 입력 받아서 처리)

2. 로또 번호를 생성하는 프로그램을 작성하시오. (1번 ~ 45번 중 6개의 번호를 추첨)

 

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
	function proc2() {
		let my = "";
		let comNo = parseInt(Math.random() * 2);
		const rps = [ "가위", "바위", "보" ];
		let com = rps[comNo];

		while (true) {
			my = prompt(" 가위 바위 보를 입력해주세요");
			if (my != "가위" && my != "바위" && my != "보") {
				alert("잘못된 입력입니다.");
			} else {
				break;
			}
		}

		if (my == com) {
			res = "비겼습니다.";
		} else if ((my == "가위" && com == "보") || (my == "바위" && com == "가위")
				|| (my == "보" && com == "바위")) {
			res = "이겼습니다!";
		} else {
			res = "졌습니다";
		}

		disp = ` 사용자 : ${my} <br>`
		disp += ` 컴퓨터 : ${com} <br><br>`
		disp += `결과 : ${res} <br>`;
		document.getElementById('result2').innerHTML = disp;
	}
	function proc3() {
		let arr = [];
		while(arr.length<6){
			let r = parseInt(Math.random()*45+1);
			if(arr.indexOf(r)==-1){
				arr.push(r)
			}
		}
		
		arr.sort(function(a, b) {
	        return a - b; // 숫자 오름차순 정렬
	    });
		
		document.getElementById('result3').innerHTML = arr;
	}
</script>
</head>
<body>
	<div class="box">
		<h3>
			가위바위보
		</h3>
<input type="button" value="확인"
			onclick="proc2()"> <br> <br>
		<div id="result2"></div>
	</div>
	<div class="box">
		<h3>
			로또생성<br>
			(1~45번 중 6개의 번호 추첨)
		</h3>
<input type="button" value="확인"
			onclick="proc3()"> <br> <br>
		<div id="result3"></div>
	</div>
</body>
</html>