Advertisement
vladovip

JS FUND MIDEX_Memory Game

May 7th, 2022
890
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function memoryGame(inputArr) {
  2.  
  3.   let numbers = inputArr.shift().trim().split(" ");
  4.   let moves = 0;
  5.  
  6.   while (numbers.length > 1 && inputArr[0].toLowerCase() !== "end") {
  7.     let [index1, index2] = inputArr.shift().split(" ");
  8.     index1 = Number(index1);
  9.     index2 = Number(index2);
  10.     moves++;
  11.  
  12.     if (
  13.       index1 < 0 ||
  14.       index1 >= numbers.length ||
  15.       index1 === index2 ||
  16.       index2 < 0 ||
  17.       index2 >= numbers.length
  18.     ) {
  19.       let index = Math.trunc(numbers.length / 2);
  20.  
  21.       let symbol = "-" + moves + "a";
  22.  
  23.       numbers.splice(index, 0, symbol, symbol);
  24.  
  25.       console.log("Invalid input! Adding additional elements to the board");
  26.     } else {
  27.       let num1 = numbers[index1];
  28.  
  29.       let num2 = numbers[index2];
  30.  
  31.       if (num1 === num2) {
  32.         numbers.splice(index1, 1);
  33.         index2 = numbers.indexOf(num2);
  34.         numbers.splice(index2, 1);
  35.         console.log(`Congrats! You have found matching elements - ${num1}!`);
  36.       } else if (num1 !== num2) {
  37.         console.log("Try again!");
  38.       }
  39.     }
  40.   }
  41.  
  42.   if (numbers.length === 0 || numbers.length === 1) {
  43.     console.log(`You have won in ${moves} turns!`);
  44.   } else {
  45.     console.log(`Sorry you lose :(`);
  46.  
  47.     console.log(`${numbers.join(" ")}`);
  48.   }
  49. }
  50.  
  51.  
  52. memoryGame(["1 1 2 2 3 3 4 4 5 5", "1 0", "-1 0", "1 0", "1 0", "1 0", "end"]);
  53.  
  54. console.log(`--------`);
  55.  
  56. memoryGame(["a 2 4 a 2 4", "0 3", "0 2", "0 1", "0 1", "end"]);
  57.  
  58. console.log(`-------`);
  59.  
  60. memoryGame(["a 2 4 a 2 4", "4 0", "0 2", "0 1", "0 1", "end"]);
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement