반응형
up & down 게임은 임의로 선택된 하나의 숫자를 찾는 게임이다.
찾는 방법은 플레이어가 선택한 숫자가 정답에 대해 Up, Down을 알려줘 정답을 추론하는 게임이다.
어떻게 만들지 한번 생각해보자.
이 게임은 매 판마다 랜덤된 숫자가 하나 존재한다. App에서 props로 숫자 하나를 전달해 주면 될 것 같다.
그리고 게임에서 사용자가 정하는 숫자에 따라 up, down을 표시 주는데, 사용자 입력값은 매회 변한다. 그러니 state를 사용해 보겠다. 입력 방법은 input을 통해 숫자를 입력 받으면 될 것 같다.
App -> UpAndDown
props : answerNum
UpAndDown
state : playerNum
제작
yarn create react-app uad-game
cd uad-game
yarn start
import './App.css';
import UpAndDown from './UpAndDown';
import { useState } from 'react';
function App() {
const [answerNum,setAnswerNum] = useState(null);
const onClick = () => setAnswerNum(parseInt(Math.random() * 999 % 100));
return (
<div className='container'>
<UpAndDown answerNum={answerNum}></UpAndDown>
<button onClick={onClick}><h1>Start</h1></button>
</div>
);
}
export default App;
import React, { useRef, useState } from 'react';
const UpAndDown = ({ answerNum }) => {
const [playerNum, setPlayerNum] = useState();
const [trialCount, setTrialCount] = useState(0);
const inputValue = useRef(0);
const onSubmit = (e) => {
e.preventDefault();
setTrialCount(trialCount + 1);
setPlayerNum(inputValue.current.value);
inputValue.current.value = '';
};
return (
<div>
{
answerNum === null ? <h1>게임 시작 버튼을 눌러주세요</h1> :
<form onSubmit={onSubmit}>
<input ref={inputValue} type='number' placeholder='정답에 가까운 숫자 입력'></input>
<button type='submit'>제출</button>
<div>
{answerNum > playerNum ? <h1>Up</h1> : (answerNum == playerNum ? <h1>정답</h1> : <h1>Down</h1>)}
<h2>횟수{trialCount}</h2>
</div>
</form>
}
</div>
);
};
export default UpAndDown;
결과
gif 캡쳐
submit 시 input값에 접근하기 위해 useRef를 사용하였고, 나머지 부분은 큰 어려움은 없었다.
반응형
'WEB > HTML CSS JS' 카테고리의 다른 글
[Python] tkinter 공부 (0) | 2023.03.05 |
---|---|
[React.js] 숫자 맞추기 게임 baseball(숫자 야구) (0) | 2023.02.24 |
리눅스 서버 putty로 접속해서 nodejs, npm, yarn 설치하기 (1) | 2023.02.17 |
AutoSet10 사용해서 웹 서버 만들어 index.html 접속하기 (0) | 2023.02.16 |
[React Router v6] 3. Link, NavLink (0) | 2023.02.13 |