Skip to content
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

[자동차 경주] BoRamSon 미션 제출합니다. #743

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
51 changes: 49 additions & 2 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,52 @@
import Car from './Car.js';
class App {
async play() {}
async play() {
try {
const carNames = await this.inputCarNames();
const round = await this.inputRound();

const cars = carNames.map((name) => new Car(name));

console.log('\n실행 결과');
for (let i = 0; i < round; i++) {
cars.forEach((car) => car.move());
this.printStatus(cars);
console.log();
}

const winners = this.getWinners(cars);
this.printWinners(winners);
} catch (error) {
console.error(error.message);
}
}

async inputCarNames() {
const input = await Console.readLineAsync(
'경주할 자동차 이름을 입력하세요.\n'
);
return input.split(',').map((name) => name.trim());
}

async inputRound() {
const input = await Console.readLineAsync('시도할 횟수는 몇 회인가요?\n');
return Number(input);
}

printStatus(cars) {
cars.forEach((car) => {
console.log(`${car.name} : ${'-'.repeat(car.position)}`);
});
}

getWinners(cars) {
const maxPosition = Math.max(...cars.map((car) => car.position));
return cars.filter((car) => car.position === maxPosition).map((car) => car.name);
}

printWinners(winners) {
console.log(`최종 우승자 : ${winners.join(', ')}`);
}
}

export default App;
export default App;
20 changes: 20 additions & 0 deletions src/Car.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export default class Car {
constructor(name) {
this.validateName(name);
this.name = name;
this.position = 0;
}

validateName(name) {
if (name.length === 0 || name.length > 5) {
throw new Error('[ERROR] 자동차 이름은 1자 이상, 5자 이하만 가능합니다.');
}
}

move() {
const randomNumber = Random.pickNumberInRange(0, 9);
if (randomNumber >= 4) {
this.position++;
}
}
}