관리 메뉴

샐님은 개발중

야구게임 - 랜덤함수, append , join 등 본문

자바스크립트/인프런강의-렛츠기릿 자바스크립트

야구게임 - 랜덤함수, append , join 등

샐님 2023. 7. 4. 20:15
728x90
반응형
<html>

<head>
    <meta charset="utf-8">
    <title>숫자야구</title>
</head>

<body>
    <form id="form">
        <input type="text" id="input">
        <button>확인</button>
    </form>
    <div id="logs"></div>
    <script>
        const $input = document.querySelector('#input');
        const $form = document.querySelector('#form');
        const $logs = document.querySelector('#logs');

        const numbers = []; // [1, 2, 3, 4, 5, 6, 7, 8, 9]
        for (let n = 0; n < 9; n += 1) {
            numbers.push(n + 1);
        }
        const answer = []; // [3, 1, 4, 6]
        for (let n = 0; n < 4; n += 1) { // 네 번 반복
            const index = Math.floor(Math.random() * numbers.length); // 0~8 정수 
            answer.push(numbers[index]);
            numbers.splice(index, 1);
        }
        console.log(answer);

        const tries = [];

        function checkInput(input) { // 3146,   314,  3144
            if (input.length !== 4) { // 길이는 4가 아닌가
                return alert('4자리 숫자를 입력해 주세요.');
            }
            if (new Set(input).size !== 4) { // 중복된 숫자가 있는가
                return alert('중복되지 않게 입력해 주세요.');
            }
            if (tries.includes(input)) { // 이미 시도한 값은 아닌가
                return alert('이미 시도한 값입니다.');
            }
            return true;
        } // 검사하는 코드

        $form.addEventListener('submit', (event) => {
            event.preventDefault();
            const value = $input.value;
            $input.value = '';
            if (!checkInput(value)) {
                return;
            }
            // 입력값 문제없음
            if (answer.join('') === value) { // [3, 1, 4, 6] -> '3146'
                $logs.textContent = '홈런!';
                return;
            }
            if (tries.length >= 9) {
                const message = document.createTextNode(`패배! 정답은 ${answer.join('')}`);
                $logs.appendChild(message);
                return;
            }
            // 몇 스트라이크 몇 볼인지 검사
            let strike = 0;
            let ball = 0;
            // answer: 3146,  value: 1347
            for (let i = 0; i < answer.length; i++) {
                const index = value.indexOf(answer[i]);
                console.log("index", index)
                if (index > -1) { // 일치하는 숫자 발견
                    if (index === i) { // 자릿수도 같음
                        strike += 1;
                    } else { // 숫자만 같음
                        ball += 1;
                    }
                }
            }
            $logs.append(`${value}: ${strike} 스트라이크 ${ball} 볼`, document.createElement('br'));
            tries.push(value);
        });
    </script>
</body>

</html>

 

2. foreach 

  // 몇 스트라이크 몇 볼인지 검사
            let strike = 0;
            let ball = 0;
            // answer: 3146,  value: 1347
            // for (let i = 0; i < answer.length; i++) {
            //     const index = value.indexOf(answer[i]);
            //     console.log("index", index)
            //     if (index > -1) { // 일치하는 숫자 발견
            //         if (index === i) { // 자릿수도 같음
            //             strike += 1;
            //         } else { // 숫자만 같음
            //             ball += 1;
            //         }
            //     }
            // }
            // for -> foreach 로 바꾸기
            answer.forEach((el, index) => {
                const indx = value.Indexof(el);
                if (indx > -1) {
                    if (indx == index) {
                        strike += 1;
                    } else {
                        ball += 1;
                    }
                }

            });

3. map - 반복문 역할과 각 값을 바꿀수 있다. 새로운 배열을 만들어 준다.

           - 기존배열은 변경안함.

       answer.map((el, indx) => {
                return el * 2;
            })

 

4. foreach 또는 map 을 쓰는 이유

   - 원하는 배열을 만들고 값을 여달아 쓸 수 있다.

728x90
반응형