React/webgame

03 숫자야구 코드

aloha2jh 2024. 4. 5. 02:15

 

const React = require('react');
const { useState, useRef } = React;
const Try = require('./Try');
/* 
1. 랜덤숫자4개 9이하로 출력해주는 함수 
//4개를 어떻게 안겹치게 하지?

2. 사용자가 값 입력시, 체크해서 돌려주기
체크1) 맞는 숫자가 있는지 몇개인지
체크2) 자리수까지 맞는 숫자가 있는지 몇개인지

3. 화면에 데이터 쌓이게

숫자야구
[ ][ ][ ][ ] 
--------------
1,2,3,4 : 0 - 스트라이크  1 - 볼  /8번의 기회가 남음
2,4,6,7 : 

*/
const BaseBall = () => {
    const getNums = () => {
        const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        const fourNums = [];
        for (i = 0; i < 4; i++) {
            const chosen = nums.splice(Math.floor(Math.random() * (9 - i)), 1)[0];
            fourNums.push(chosen)
        }
        return fourNums;
    }

    const [inputVal, setInputVal] = useState('');
    const [result, setResult] = useState(''); //사용자한테 결과값 알려줌.-홈런일때.
    const [chances, setChances] = useState(9); //남은기회
    const [desc, setDesc] = useState([]); //[ {tries:"1234", result:},{} ]
    const [answer, setAnswer] = useState(getNums()); //[{strike:1, ball:0}, ]
    const inputRef = useRef(null);

    const onSubmitForm = (e) => {
        e.preventDefault();
        setInputVal('');
        if (inputVal !== '' & chances !== 0) {
            const homerun = inputVal === answer.join('') ? true : false;
            if (homerun) {
                setResult('홈런입니다.');
                reset();
            } else {
                let strike = 0;
                let ball = 0;
                for (let i = 0; i < 4; i++) {
                    if (answer[i] == inputVal[i]) {
                        strike++;
                    }
                    for (let j = 0; j < 4; j++) {
                        if (answer[i] == inputVal[j]) {
                            ball++;
                        }
                    }
                }
                console.log(strike + '//' + ball)

                const newDesc = {
                    tries: inputVal,
                    result: `${strike}스트라이크 ${ball}볼`
                };
                setDesc(prevDesc => [...prevDesc, newDesc]);
                setResult('');
            }

            if (!homerun) {
                setChances(prevChances => prevChances - 1);
            }
            setInputVal('');

            if (chances == 1) {
                setResult(`답은 ${answer} 였습니다.`);
            }
        } else {
            reset();
            setResult('')
        }
    }
    const reset = () => {
        setChances(9);
        setAnswer(getNums());
        setDesc([]);
    }
    const onChangeVal = (e) => {
        setInputVal(e.currentTarget.value);
    }

    return (
        <>
            <div class="number-baseball">
                <form onSubmit={onSubmitForm}>
                    <ul>
                        <li>
                            <h4>숫자야구</h4>
                            <p>[ ] [ ] [ ] [ ] </p>
                            <input
                                ref={inputRef}
                                value={inputVal}
                                onChange={onChangeVal}
                            />
                            <button>입력</button>
                        </li>
                        <li>
                            <h5>테스트용:</h5>
                            <p>answer: {answer}</p>
                        </li>
                        <li>
                            <h5>사용자 확인:</h5>
                            <p>{result}</p>
                            <ul>
                                <li>남은 기회 : {chances}</li>
                                {
                                    desc.map((item, i) => (
                                        <li key={i + item.tries}>
                                            {i + 1}차 시도 - 입력값: {item.tries} 결과:{item.result}
                                        </li>
                                    ))
                                }
                            </ul>
                        </li>
                    </ul>
                </form>
            </div>
        </>
    )
}

module.exports = BaseBall;