Math.random() (JavaScript)

Math.random()

0이상 1 미만의 실수 형태의 난수를 반환한다.

 

원하는 범위 난수 생성

만약 1과 3 사이의 난수를 생성하고 싶으면

let a = parseInt(Math.random()*3) + 1
// parseInt(Math.random()*3)는 0, 1, 2 숫자를 랜덤으로 반환 그래서 +1 필요

min이상 max미만 사이의 생성하는 함수

function getRandomArbitrary(min, max){
	return Math.random() * (max - min) + min;
}

min이상 max미만의 정수를 생성하는 함수

function getRandomInt(min, max){
	min = Math.ceil(min);          //Math.ceil : 소수점 올림
	max = Math.floor(max);         //Math.floor : 소수점 내림
  return Math.floor(Math.random() * (max - min)) + min;
}

min이상 max이하의 정수를 생성하는 함수

function getRandomIntInclusive(min, max){
	min = Math.ceil(min);
	max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

 

 

관련 예제)

가위, 바위, 보 게임

rock-paper-scissors.html

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Test026.html</title>
  <link rel="stylesheet" type="text/css" href="css/rock-paper-scissors.css">
  <script type="text/javascript" src="js/rock-paper-scissors.js"></script>
</head>
<body>

  <div class="title">
    <h1>가위! 바위! 보!!</h1>
  </div>

  <div class="contents">
    <form>
      <div class="input">
        <p>입력(가위, 바위, 보)</p>

        <div id="userInput">
          <input type="text" class="txt" id="txtUser">
          <button type="button" class="btn" onclick="startGame()">게임 결과 확인</button>
        </div>
      </div>

      <div class="result">
        <p id="resultTxt">결과</p>
        <textarea name="textarea" id="txtResult" cols="35" rows="2" readonly="readonly"></textarea>
      </div>
    </form>
  </div>
</body>
</html>

rock-paper-scissors.css

@font-face {
  font-family: 'SuncheonB';
  src: url('<https://cdn.jsdelivr.net/gh/projectnoonnu/noonfonts_2202-2@1.0/SuncheonB.woff>') format('woff');
  font-weight: normal;
  font-style: normal;
}

* {
  font-family: SuncheonB, 나눔 고딕;
}

body {
  font-family: SuncheonB, 나눔 고딕;
  background-color: #262559;
  color: #F26BDC;
}
.title {
  display: flex;
  font-size: 20px;
  flex-direction: column;
  align-items: center;
}

.contents {
  font-size: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 30px;
}

#resultTxt {
  margin-top : 100px;
}

rock-paper-scissors.js

function startGame() {
  let strArr = ["가위", "바위", "보"];
  
  // 결과 출력할 문자열
  let msg = "";

  // 0~2 사이의 난수 발생
  let randNum = parseInt(Math.random() * 3) + 1;

  // 입력 받은 문자열 변수에 저장
  let strUser = document.getElementById("txtUser").value;
  let userNum = 0;

  // 입력 받은 문자열 숫자로 변환
  switch (strUser) {
    case "가위":
      userNum = 1;
      break;
    
    case "바위":
      userNum = 2;
      break;
    
    case "보":
      userNum = 3;
      break;
    
    default:
      alert("올바른 값을 입력하세요.");
      return;
  }
  
  // 출력 문자열
  msg += "사용자 : " + strUser + ", 컴퓨터 : " + strArr[randNum-1] + "\\n";

  // 가위바위보 연산
  if (randNum==userNum){
    msg += " → 비겼습니다.";
  } 
  else if (userNum%3 == (randNum+2)%3) {
    msg += " → 컴퓨터가 이겼습니다.";
  }
  else {
    msg += " → 당신이 이겼습니다.";
  }
  
  document.getElementById("txtResult").value = msg;
}

 

 

 


https://www.instagram.com/p/BjBtugRFz8L/?utm_source=ig_web_copy_link

부족하거나 잘못된 내용이 있을 경우 댓글 달아주시면 감사하겠습니다.

이 글에 부족한 부분이 존재할 경우 추후에 수정될 수 있습니다.