Last active
April 2, 2019 18:55
-
-
Save Ampa1R/5e990d7a7efec75e67a44e34c40d6c52 to your computer and use it in GitHub Desktop.
Bulls and Cows
This file contains hidden or 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
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <meta charset="utf-8"> | |
| <title>Bulls and Cows JavaScript</title> | |
| <script src="lib.js" defer></script> | |
| <script src="main.js" defer></script> | |
| <style> | |
| *{ | |
| box-sizing: content-box; | |
| } | |
| .app{ | |
| font-family: sans-serif; | |
| display: flex; | |
| flex-direction: column; | |
| align-items: center; | |
| } | |
| input { | |
| padding: 10px 15px; | |
| border-style: solid; | |
| } | |
| input:disabled { | |
| border-color: #ccc; | |
| } | |
| button { | |
| border-style: solid; | |
| cursor: pointer; | |
| padding: 10px 15px; | |
| } | |
| button:disabled { | |
| cursor: auto; | |
| } | |
| .guess { | |
| margin: 10px 0; | |
| } | |
| .result { | |
| margin-top: 40px; | |
| font-size: 2em; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="app"> | |
| <h1>Bulls'n'Cows</h1> | |
| <div class="guess"> | |
| <input type="text" placeholder="Число" class="guess__value" disabled> | |
| <button class="guess__add" disabled>Проверить</button> | |
| </div> | |
| <div class="additional"> | |
| <button class="additional__concede" disabled>Сдаюсь</button> | |
| <button class="additional__new">Новая игра</button> | |
| </div> | |
| <div class="result"> | |
| ... | |
| </div> | |
| </div> | |
| </body> | |
| </html> |
This file contains hidden or 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
| class BullsAndCows { | |
| generateNumber() { | |
| this.needle = ""; // пустая переменная, в которой дальше будет храниться загаданное число | |
| while( this.needle.length < 4 || this.isNumberHaveDuplicates(this.needle)) { // пока длина сгенерированного числа меньш 4 и вЧислеЕстьПовторения | |
| this.needle = Math.round(Math.random() * 10000) + ""; // генерируем число и превращаем его в string | |
| } | |
| return this.needle; // возвращаем сгенерированное число | |
| } | |
| guessNumber(n) { | |
| // пользователь вводит число | |
| if( isNaN( n / 1 ) ) return 'Only digits are allowed'; // Если при делении на 1 получается Not a Number | |
| if(n.length !== 4) return 'Enter 4 digits'; | |
| if( this.isNumberHaveDuplicates(n) ) return 'Enter a number without duplicate digits'; | |
| let bulls = 0; | |
| let cows = 0; | |
| n.split('').forEach( (num, pos) => { // превращаем число в массив вида [1, 2, 3, 4] и перебираем элементы | |
| if(this.needle.indexOf(num) === pos) // если число присутствует в массиве и стоит на том же месте | |
| bulls++; | |
| else if(this.needle.includes(num)) // если число присутвует в массиве | |
| cows++; | |
| }); | |
| return {bulls: bulls, cows: cows}; | |
| } | |
| isNumberHaveDuplicates(input) { | |
| if(typeof input === 'number') // если int, превращаем в string | |
| input = input + ''; | |
| if(typeof input === 'string') // если string, превращаем в массив вида [1, 2, 3, 4] | |
| input = input.split(''); | |
| if(typeof input !== 'object') // если не массив, то возвращаем ошибку | |
| return console.error('Incorrect data'); | |
| // создаем новый массив путём перебора старого: если индекс первого найденного в массиве числа не совпадает | |
| // с его настоящим индексом, значит в массиве есть повторения и длина нового массива не будет равна исходной | |
| const res = input.filter( (val, pos) => input.indexOf(val) == pos); | |
| return res.length !== input.length; | |
| } | |
| } |
This file contains hidden or 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
| (function() { | |
| const game = new BullsAndCows; | |
| let num = null; | |
| const input = document.querySelector('.guess__value'); | |
| const guessButton = document.querySelector('.guess__add'); | |
| const result = document.querySelector('.result'); | |
| const newGameButton = document.querySelector('.additional__new'); | |
| const concedeButton = document.querySelector('.additional__concede'); | |
| guessButton.addEventListener('click', function(e) { | |
| e.preventDefault(); | |
| const val = input.value; | |
| const guessRes = game.guessNumber(val); | |
| console.log(guessRes); | |
| if(typeof guessRes === 'object' && guessRes.bulls >= 0 && guessRes.cows >= 0) { | |
| if(guessRes.bulls === 4) { | |
| input.setAttribute('disabled', true); | |
| guessButton.setAttribute('disabled', true); | |
| concedeButton.setAttribute('disabled', true); | |
| newGameButton.removeAttribute('disabled'); | |
| result.innerHTML = 'You\'re right!'; | |
| } | |
| else | |
| result.innerHTML = `Bulls: ${guessRes.bulls} | Cows: ${guessRes.cows}`; | |
| } | |
| else if(typeof guessRes === 'string') | |
| result.innerHTML = guessRes; | |
| else | |
| result.innerHTML = 'Error'; | |
| }); | |
| newGameButton.addEventListener('click', function(e) { | |
| num = game.generateNumber(); | |
| console.log(num); | |
| newGameButton.setAttribute('disabled', true); | |
| input.removeAttribute('disabled'); | |
| guessButton.removeAttribute('disabled'); | |
| concedeButton.removeAttribute('disabled'); | |
| result.innerHTML = 'New game started'; | |
| }); | |
| concedeButton.addEventListener('click', function(e) { | |
| input.setAttribute('disabled', true); | |
| guessButton.setAttribute('disabled', true); | |
| concedeButton.setAttribute('disabled', true); | |
| newGameButton.removeAttribute('disabled'); | |
| result.innerHTML = `Number was ${num}`; | |
| }); | |
| // TODO: add history | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment