app.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. window.addEventListener('load', function () {
  2. let countUser = document.querySelector('.count-user'),
  3. countComp = document.querySelector('.count-comp'),
  4. userField = document.querySelector('.user-field'),
  5. compField = document.querySelector('.comp-field'),
  6. sound = document.querySelector('.sound'),
  7. res = document.querySelector('.result'),
  8. play = document.querySelector('.play'),
  9. fields = document.querySelectorAll('.field'),
  10. userStep, compStep, countU = 0, countC = 0, blocked = false;
  11. function choiceUser(e) { //осознанный выбор пользователя
  12. if (blocked) return;
  13. let target = e.target;
  14. if (target.classList.contains('field')) {
  15. userStep = target.dataset.field;
  16. fields.forEach(item => item.classList.remove('active', 'error'));
  17. target.classList.add('active');
  18. choiceComp();
  19. }
  20. }
  21. function choiceComp() { //рандомный выбор компьютера
  22. blocked = true;
  23. let rand = Math.floor(Math.random() * 3);
  24. compField.classList.add('blink');
  25. let compFields = compField.querySelectorAll('.field');
  26. setTimeout(() => {
  27. compField.classList.remove('blink');
  28. compStep = compFields[rand].dataset.field;
  29. compFields[rand].classList.add('active');
  30. winner();
  31. },3000);
  32. }
  33. function winner() { //кто одержал победу
  34. blocked = false;
  35. let comb = userStep + compStep;
  36. switch (comb) {
  37. case 'rr':
  38. case 'ss':
  39. case 'pp':
  40. res.innerText = 'Ничья!';
  41. sound.setAttribute('src', 'audio/draw.mp3');
  42. sound.play();
  43. break;
  44. case 'rs':
  45. case 'sp':
  46. case 'pr':
  47. res.innerText = 'Победили вы!';
  48. sound.setAttribute('src', 'audio/win.mp3');
  49. sound.play();
  50. countU++;
  51. countUser.innerText = countU;
  52. compField.querySelector('[data-field='+compStep+']').classList.add('error');
  53. break;
  54. case 'sr':
  55. case 'ps':
  56. case 'rp':
  57. res.innerText = 'Победил компьютер!';
  58. sound.setAttribute('src', 'audio/loss.mp3');
  59. sound.play();
  60. countC++;
  61. countComp.innerText = countC;
  62. userField.querySelector('[data-field=' + userStep + ']').classList.add('error');
  63. break;
  64. }
  65. }
  66. function playGame() {
  67. countU = countC = 0;
  68. res.innerText = 'Сделайте выбор';
  69. countUser.innerText = '0';
  70. countComp.innerText = '0';
  71. fields.forEach(item => item.classList.remove('active', 'error'));
  72. }
  73. play.addEventListener('click', playGame);
  74. userField.addEventListener('click', choiceUser);
  75. });