Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
d831b0b
docs: readme 작성
BoeunHan Oct 22, 2023
0f94e34
feat: 랜덤 숫자 세자리 지정
BoeunHan Oct 22, 2023
f17380f
feat: 사용자 입력
BoeunHan Oct 22, 2023
12f237b
feat: 컴퓨터 응답 출력
BoeunHan Oct 22, 2023
29736f2
feat: 볼 스트라이크 계산
BoeunHan Oct 25, 2023
d7353c3
feat: 스트라이크 볼 메세지 출력
BoeunHan Oct 25, 2023
2890ef2
feat: 게임 재시작 쿼리 메세지
BoeunHan Oct 25, 2023
0fc67db
feat: 게임 재시작 시 numbers 초기화
BoeunHan Oct 25, 2023
e6d07f5
feat: 배열 초기화 함수 분리
BoeunHan Oct 25, 2023
aab592a
feat: 사용자 입력 예외 발생
BoeunHan Oct 25, 2023
f898cb5
feat: 쿼리 분리
BoeunHan Oct 25, 2023
cd10f7d
style: 변수 naming 수정
BoeunHan Oct 25, 2023
ce33efd
fix: App.play() 함수 await 추가
BoeunHan Oct 25, 2023
c9ba2be
style: 변수 naming 수정
BoeunHan Oct 25, 2023
d4aac0f
style: QUIT 상수
BoeunHan Oct 25, 2023
ff32a2e
style: STRIKE 상수
BoeunHan Oct 25, 2023
cd951be
style: returnMessage 반환값 통일
BoeunHan Oct 25, 2023
bd94bdb
feat: 숫자 입력, 재시작 입력 함수 분리
BoeunHan Oct 25, 2023
9e171e7
feat: calculateBallStrike reduce로 변경
BoeunHan Oct 25, 2023
41e3cc8
style: property value shorthand convention
BoeunHan Oct 25, 2023
f39bd22
style: 문자열 작은따옴표 사용
BoeunHan Oct 25, 2023
6ab159f
style: reduce 객체 복사 후 수정
BoeunHan Oct 25, 2023
d0f3cbd
style: ++를 +=1로 변경
BoeunHan Oct 25, 2023
20bb592
style: if문 중괄호 추가
BoeunHan Oct 25, 2023
c0d686b
style: 조건문 결합
BoeunHan Oct 25, 2023
f15170f
style: 변수명, 함수명 변경
BoeunHan Oct 25, 2023
1df1359
style: string 배열 변환 - spread에서 split으로 변경
BoeunHan Oct 25, 2023
f3884ec
style: 상수 추가
BoeunHan Oct 25, 2023
5ae3f53
style: soft tab 변경
BoeunHan Oct 25, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
- ✅랜덤 숫자 세자리 지정하기
- ✅사용자 입력받기
- ✅컴퓨터 응답 출력하기
- ✅잘못된 값 입력 시 에러 발생하기
- ✅랜덤 숫자와 사용자 입력 비교하기
- ✅게임 종료 시 재시작/종료 입력받기
11 changes: 10 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import Computer from './Computer.js';
import User from './User.js';

class App {
async play() {}
constructor() {
this.computer = new Computer();
this.user = new User();
}
async play() {
await this.computer.playGame(this.user);
}
}

export default App;
72 changes: 72 additions & 0 deletions src/Computer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { MissionUtils } from '@woowacourse/mission-utils';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import { Console, Random } from '@woowacourse/mission-utils';

이렇게 선언하면 이후에 MissionUtils.Random()Random()로 줄여서 쓸 수 있어요!


export default class Computer {
static REPLAY_CODE = '1';
static QUIT_CODE = '2';
static NUM_SIZE = 3;
static MODE_SIZE = 1;

constructor() {
this.numbers = [];
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

airbnb 스타일 가이드에 따르면 구문의 앞과 블록의 뒤에는 빈 행을 두는 것이 좋다고 해요.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

미처 확인하지 못한 컨벤션이네요..알려주셔서 감사합니다!

pickRandomNumbers() {
this.clearNumbers();
while (this.numbers.length < Computer.NUM_SIZE) {
const number = MissionUtils.Random.pickNumberInRange(1, 9);
if (!this.numbers.includes(number)) {
this.numbers.push(number);
}
}
}
async playGame(user) {
MissionUtils.Console.print('숫자 야구 게임을 시작합니다.');
while (true) {
this.pickRandomNumbers();
while (true) {
const input = await user.getUserNumber();
const result = this.getMessage(input);
MissionUtils.Console.print(result.result);
if (result.success) {
MissionUtils.Console.print(
'3개의 숫자를 모두 맞히셨습니다! 게임 종료'
);
break;
}
}
Comment on lines +23 to +35

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

playGame()에 모든 기능을 넣기 보다는 내부에 있는 while문과 if문을 새로운 함수로 만들어 사용하는게 좋을 것 같아 제안합니다!! :D
기능별로 나누어 함수를 만드는 게 나중에 리팩토링하고 테스트를 진행할 때 좋을 것 같아요.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2주차 때는 좀더 코드를 기능별로 분리해보겠습니다. 조언 감사합니다!

const input = await user.getUserReplay();
if (input === Computer.QUIT_CODE) break;
}
}
getMessage(expectedNumbers) {
const ballStrike = this.calculateBallStrike(expectedNumbers);
const result = this.getResultString(ballStrike);
return {
result,
success: ballStrike.strike === Computer.NUM_SIZE,
};
}
calculateBallStrike(expectedNumbers) {
return expectedNumbers
.split('')
.map(Number)
.reduce(
(res, cur, idx) => {
const newRes = { ...res };
if (this.numbers[idx] === cur) newRes.strike += 1;
else if (this.numbers.includes(cur)) newRes.ball += 1;
return newRes;
},
{ ball: 0, strike: 0 }
);
}
getResultString({ ball, strike }) {
if (ball === 0 && strike === 0) return '낫싱';
else if (ball === 0) return `${strike}스트라이크`;
else if (strike === 0) return `${ball}볼`;
else return `${ball}볼 ${strike}스트라이크`;
Comment on lines +64 to +66

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

앞의 if문에 return이 있으니
뒤에서부터는 else if 대신 if를 써도 될 것 같습니다!

}

clearNumbers() {
this.numbers = [];
}
}
34 changes: 34 additions & 0 deletions src/User.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { MissionUtils } from '@woowacourse/mission-utils';
import Computer from './Computer';
export default class User {
async getUserNumber() {
const input = await MissionUtils.Console.readLineAsync(
'숫자를 입력해주세요 : '
);

if (
input.length !== Computer.NUM_SIZE ||
input.includes('0') ||
Number.isNaN(input)
) {
throw new Error('[ERROR] 숫자가 잘못된 형식입니다.');
}

return input;
}

async getUserReplay() {
const input = await MissionUtils.Console.readLineAsync(
'게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.\n'
);
if (
input.length !== Computer.MODE_SIZE ||
(input !== Computer.REPLAY_CODE && input !== Computer.QUIT_CODE) ||
Number.isNaN(input)
) {
throw new Error('[ERROR] 숫자가 잘못된 형식입니다.');
}

return input;
}
}