Skip to content
Empty file added docs/README.md
Empty file.
51 changes: 50 additions & 1 deletion src/App.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,54 @@
import { MissionUtils } from "@woowacourse/mission-utils";
import Computer from "./Computer/Computer.js";
import UserInput from "./UserInput/UserInput.js";

class App {
async play() {}
constructor() {
this.computer = new Computer();
this.userInput = new UserInput();
}

async play() {
MissionUtils.Console.print("숫자 야구 게임을 시작합니다.");

while (true) {
const userInput = await this.userInput.inputUser();
const result = this.compareNum(userInput);

MissionUtils.Console.print(result);

if (result === '3스트라이크') {
MissionUtils.Console.print("3개의 숫자를 모두 맞히셨습니다! 게임 종료");
if (!(await this.userInput.restartOption())) {
break;
}
this.computer = new Computer();
}
}
}

compareNum(userInput) {
let strike = 0;
let ball = 0;

for (let i = 0; i < 3; i++) {
if (userInput[i] === this.computer.number[i]) {
strike++;
} else if (this.computer.number.includes(userInput[i])) {
ball++;
}
}

if (strike > 0 && ball > 0) {
return `${ball}볼 ${strike}스트라이크`;
} else if (strike > 0) {
return `${strike}스트라이크`;
} else if (ball > 0) {
return `${ball}볼`;
} else {
return "낫싱";
}
}
}

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

class Computer {
constructor() {
this.number = this.getRandomNum();
}

getRandomNum() {
const number = [];
while (number.length < 3) {
const randomNum = MissionUtils.Random.pickNumberInRange(1, 9);
if (!number.includes(randomNum)) {
number.push(randomNum);
}
}
return number;
}
}

export default Computer;
8 changes: 8 additions & 0 deletions src/Constant/Constant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const MESSAGE = {
START: "숫자 야구 게임을 시작합니다.",
INPUT: "숫자를 입력해주세요 : ",
END: "3개의 숫자를 모두 맞히셨습니다! 게임 종료",
REPLAY: "게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.",
ERROR: "[ERROR] 잘못된 입력입니다."
};

29 changes: 29 additions & 0 deletions src/UserInput/UserInput.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { MissionUtils } from "@woowacourse/mission-utils";
import { MESSAGE } from "../Constant/Constant";

class UserInput {
async inputUser() {
const userInput = await MissionUtils.Console.readLineAsync(MESSAGE.INPUT);
if (!this.isValidInput(userInput)) {
throw new Error(MESSAGE.ERROR);
}
return userInput.split('').map(Number);
}

isValidInput(userInput) {
return new Set(userInput).size === 3 && /^[1-9]{3}$/.test(userInput);
}

async restartOption() {
const option = await MissionUtils.Console.readLineAsync(MESSAGE.REPLAY);
if (option === '1') {
return true;
} else if (option === '2') {
return false;
} else {
throw new Error(MESSAGE.ERROR);
}
}
}

export default UserInput;