diff --git a/src/app.js b/src/app.js index ad9a93a..12cad2c 100644 --- a/src/app.js +++ b/src/app.js @@ -1 +1,29 @@ +/* eslint-disable no-console */ 'use strict'; + +const readline = require('readline'); +const { generateRandomNumber } = require('./generateRandomNumber.js'); +const { calculateBullsAndCows } = require('./calculateBullsAndCows.js'); +const { getInput } = require('./getInput.js'); + +(async() => { + const currentNumber = generateRandomNumber(); + + while (true) { + const userInput = await getInput(); + + if (userInput.length !== 4) { + console.log('The number must consist of 4 characters'); + } + + const result = calculateBullsAndCows(currentNumber, userInput); + + console.log(`Result: Bulls: ${result.bulls}, Cows: ${result.cows}`); + + if (result.bulls === 4) { + console.log('Congratulations! You guessed the number.'); + + readline.close(); + } + } +})(); diff --git a/src/calculateBullsAndCows.js b/src/calculateBullsAndCows.js new file mode 100644 index 0000000..dabb518 --- /dev/null +++ b/src/calculateBullsAndCows.js @@ -0,0 +1,21 @@ +'use strict'; + +function calculateBullsAndCows(hiddenNumber, guessNumber) { + let bulls = 0; + let cows = 0; + + for (const num in hiddenNumber) { + if (hiddenNumber[num] === guessNumber[num]) { + bulls++; + } else if (hiddenNumber.includes(guessNumber[num])) { + cows++; + } + } + + return { + bulls, + cows, + }; +} + +module.exports = { calculateBullsAndCows }; diff --git a/src/generateRandomNumber.js b/src/generateRandomNumber.js new file mode 100644 index 0000000..e126fd8 --- /dev/null +++ b/src/generateRandomNumber.js @@ -0,0 +1,17 @@ +'use strict'; + +function generateRandomNumber() { + const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + let number = ''; + + for (let i = 0; i < 4; i++) { + const randomIndex = Math.floor(Math.random() * digits.length); + const digit = digits.splice(randomIndex, 1)[0]; + + number += digit; + } + + return number; +} + +module.exports = { generateRandomNumber }; diff --git a/src/getInput.js b/src/getInput.js new file mode 100644 index 0000000..763e67b --- /dev/null +++ b/src/getInput.js @@ -0,0 +1,18 @@ +'use strict'; + +const readline = require('readline'); + +function getInput() { + return new Promise((resolve) => { + const terminal = readline.createInterface({ + input: process.stdin, + output: process.stdout, + }); + + terminal.question('Please, guess a number. ', (guessNumber) => { + resolve(guessNumber); + }); + }); +} + +module.exports = { getInput };