SKGreyHound

Memory Game

Jan 10th, 2021
676
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. function memoryGame(input) {
  2.  
  3. let sequence = input.shift().split(' ');
  4. let command = input.shift();
  5. let turns = 0;
  6.  
  7. while (command !== 'end') {
  8. let [index1, index2] = command.split(' ').map(Number);
  9. turns++;
  10.  
  11. if (sequence[index1] === sequence[index2]) {
  12. console.log(`Congrats! You have found matching elements - ${sequence[index1]}!`);
  13. sequence = removeElements(index1, index2);
  14. } else {
  15. if (index1 < 0 || index1 > sequence.length || index2 < 0 || index2 > sequence.length) {
  16. console.log("Invalid input! Adding additional elements to the board");
  17. let index = Math.trunc(sequence.length / 2);
  18. sequence.splice(index, 0, `-${turns}a`, `-${turns}a`);
  19. } else {
  20. console.log("Try again!");
  21. }
  22. }
  23. if (sequence.length === 0) {
  24. console.log(`You have won in ${turns} turns!`);
  25. break;
  26. }
  27. command = input.shift();
  28. }
  29. if (sequence.length > 0) {
  30. console.log("Sorry you lose :(");
  31. console.log(sequence.join(' '));
  32. }
  33.  
  34.  
  35. function removeElements(index1, index2) {
  36. const num1 = sequence[index1];
  37. const num2 = sequence[index2];
  38. if (num1 === num2) {
  39. sequence.splice(index1, 1);
  40. index2 = sequence.indexOf(num2);
  41. sequence.splice(index2, 1);
  42. }
  43. return sequence;
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment