-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[이재빈] up and down 구현 #10
Open
JaeBeen95
wants to merge
18
commits into
whatever-mentoring:main
Choose a base branch
from
JaeBeen95:mission-1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
0b82aa0
프로젝트 시작
JaeBeen95 898b50b
요구사항 정리
JaeBeen95 23b4a1a
1. 랜덤 숫자 생성
JaeBeen95 31adf2a
2. 랜덤 숫자 저장(시도 저장)
JaeBeen95 7fbb543
3. 사용자 입력 받기 구현
JaeBeen95 8304ee3
4. 사용자 입력에 대한 유효성 검사 및 통과 못할 시 다시 입력하도록 구현
JaeBeen95 85f131c
refactor: 불필요한 검증 코드 제거
JaeBeen95 a2b188c
5. 사용자 이전 입력 값 저장 & 불필요한 else 분기문 제거
JaeBeen95 5f6c39f
6. 5회 초과 시 게임 종료
JaeBeen95 3fbdc43
refactor: 불필요한 else문 제거
JaeBeen95 1b54ea4
refactor: 게임 실행 함수 분기 및 재실행 여부 의사코드 작성
JaeBeen95 de97f31
refactor: 상태 초기화 함수 작성
JaeBeen95 1f12eb4
7. 게임 재실행 구현
JaeBeen95 ba2400e
refactor: 게임 결과를 보여주는 로직 분리
JaeBeen95 6198f2e
refactor: 게임 힌트를 보여주는 로직 분리
JaeBeen95 1341a2f
refactor: 랜덤 숫자를 구하는 부분을 함수로 분리
JaeBeen95 232b9da
refactor: 어색한 비교 부분 변경
JaeBeen95 efe496b
refactor: validation 로직 error를 throw하는 방식으로 변경
JaeBeen95 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
1. 1 이상 50 이하의 랜덤한 숫자를 만든다. | ||
|
||
2. 랜덤 숫자를 저장한다. | ||
|
||
3. 사용자로부터 숫자를 입력 받는다. | ||
|
||
- 검증을 통과한 사용자의 입력 값이 들어온다면 랜덤 숫자와 비교한다. | ||
|
||
4. 검사를 통과하지 못하면 다시 입력하도록 하게 한다. | ||
|
||
- 1에서 50까지의 숫자만 입력 받고, 공백이나 소수도 허용하지 않도록 유효성 검사를 함 | ||
|
||
5. 사용자의 이전 입력 값은 저장한다. | ||
|
||
- 매 시도마다 "이전 추측: 저장된 입력 값들" 형태로 출력 | ||
|
||
6. 시도가 5회 초과되면 초과됐다는 메시지와 함께 게임을 종료하고 다시 시작할지 묻는다. | ||
|
||
7. 결과 중 정답일 경우 게임을 종료하고 게임을 다시 시작할지 여부를 묻는다. | ||
|
||
- yes면 게임 다시 진행, no면 전체 게임을 종료한다. (yes 혹은 no 이외의 대답이 돌아올 경우 yes 혹은 no로만 대답할 수 있다는 메시지와 함께 다시 입력하도록 하게 함) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,6 +16,6 @@ | |
"devDependencies": { | ||
"esbuild": "^0.21.1", | ||
"eslint": "^8.57.0", | ||
"prettier": "^3.2.5" | ||
"prettier": "^3.4.2" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
import { readLineAsync } from "./input.js"; | ||
|
||
const getRandomNumber = (startNum, endNum) => { | ||
const randomNumber = Math.floor(Math.random() * endNum) + startNum; | ||
|
||
return randomNumber; | ||
}; | ||
|
||
const gameState = { | ||
randomNumber: getRandomNumber(1, 50), | ||
attempts: 0, | ||
userInput: [], | ||
}; | ||
|
||
const resetGameState = () => { | ||
gameState.randomNumber = getRandomNumber(1, 50); | ||
gameState.attempts = 0; | ||
gameState.userInput = []; | ||
}; | ||
|
||
const validateInputValue = (inputValue) => { | ||
const inputNumber = Number(inputValue); | ||
const isNotNumber = Number.isNaN(inputNumber); | ||
const isNotInteger = !Number.isInteger(inputNumber); | ||
const isOutOfRange = inputNumber < 1 || inputNumber > 50; | ||
|
||
if (isNotNumber || isNotInteger || isOutOfRange) { | ||
throw new Error("1에서 50사이의 정수 값만 입력해주세요"); | ||
} | ||
|
||
return inputNumber; | ||
}; | ||
|
||
const handleGameResult = ({ isCorrect, randomNumber, attempts }) => { | ||
if (isCorrect) { | ||
console.log(`정답! ${attempts}번 만에 숫자를 맞추셨습니다.`); | ||
return true; | ||
} | ||
|
||
if (attempts >= 5) { | ||
console.log(`5회 초과! 숫자를 맞추지 못했습니다. (정답: ${randomNumber})`); | ||
return true; | ||
} | ||
|
||
return false; | ||
}; | ||
|
||
const displayHint = (userNumber, randomNumber, userGuesses) => { | ||
console.log(userNumber > randomNumber ? "다운" : "업"); | ||
console.log(`이전 추측: ${userGuesses.join(", ")}`); | ||
}; | ||
|
||
async function play() { | ||
console.log("컴퓨터가 1~50 사이의 숫자를 선택했습니다. 숫자를 맞춰보세요."); | ||
|
||
while (true) { | ||
try { | ||
const inputValue = await readLineAsync("숫자 입력: "); | ||
const validNumber = validateInputValue(inputValue); | ||
const isCorrect = validNumber === gameState.randomNumber; | ||
|
||
gameState.attempts++; | ||
gameState.userInput.push(validNumber); | ||
|
||
const gameFinished = handleGameResult({ | ||
isCorrect, | ||
randomNumber: gameState.randomNumber, | ||
attempts: gameState.attempts, | ||
}); | ||
|
||
if (gameFinished) break; | ||
|
||
displayHint({ | ||
userNumber: validNumber, | ||
randomNumber: gameState.randomNumber, | ||
userGuesses: gameState.userInput, | ||
}); | ||
} catch (error) { | ||
console.log(error.message); | ||
continue; | ||
} | ||
} | ||
} | ||
|
||
async function askToPlayAgain() { | ||
while (true) { | ||
const answer = await readLineAsync("게임을 다시 시작하시겠습니까? (yes/no): "); | ||
const lowerAnswer = answer.toLowerCase(); | ||
|
||
if (lowerAnswer === "yes") { | ||
return true; | ||
} | ||
if (lowerAnswer === "no") { | ||
return false; | ||
} | ||
|
||
console.log("yes 또는 no만 입력해주세요."); | ||
} | ||
} | ||
|
||
async function upAndDownGame() { | ||
do { | ||
resetGameState(); | ||
await play(); | ||
} while (await askToPlayAgain()); | ||
|
||
console.log("게임을 종료합니다."); | ||
} | ||
|
||
upAndDownGame(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import readline from "readline"; | ||
|
||
export function readLineAsync(query) { | ||
return new Promise((resolve, reject) => { | ||
if (arguments.length !== 1) { | ||
reject(new Error("arguments must be 1")); | ||
} | ||
|
||
if (typeof query !== "string") { | ||
reject(new Error("query must be string")); | ||
} | ||
|
||
const rl = readline.createInterface({ | ||
input: process.stdin, | ||
output: process.stdout, | ||
}); | ||
|
||
rl.question(query, (input) => { | ||
rl.close(); | ||
resolve(input); | ||
}); | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
문자열이 들어오더라도 잘 방어될 수 있도록 꼼꼼하게 작성되었네요 👍