GameJS

mail@pastecode.io avatar
unknown
javascript
2 years ago
1.4 kB
2
Indexable
Never
const availableElements = ["apple", "pear", "plum", "cherry"];
const openToWin = 3;

function shuffle(arr) {
    let j, x, i;
    for (i = arr.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = arr[i];
        arr[i] = arr[j];
        arr[j] = x;
    }
    return arr;
}

function generateSequence(winItem, finishRound) {
	if (finishRound > availableElements.length * (openToWin - 1) + 1 || finishRound < openToWin) {
  	console.log("error: finishRound");
  }
  console.log("Available items: ", availableElements);
  console.log("Win item: " + winItem);
  console.log("Finish round: " + finishRound);

  let elementsWithoutWinItems = availableElements.filter(x => x !== winItem);
  let sequence = [];
  for (let i = 0; i < openToWin - 1; i++) {
    sequence = sequence.concat(elementsWithoutWinItems);
  }
  sequence = shuffle(sequence);
  
  let firstPart = sequence.slice(0, finishRound - 3);
  let lastPart = sequence.slice(firstPart.length, sequence.length + 1);
  
  firstPart.push(winItem, winItem);
  firstPart = shuffle(firstPart);
  firstPart.push(winItem);
  lastPart = shuffle(lastPart.concat(elementsWithoutWinItems));
  
  return firstPart.concat(lastPart)
}

// TEST
let result = generateSequence("plum", 7);
console.log("\nRESULTS:");
for (let i = 0; i < result.length; i++) {
    console.log(i + 1, result[i])
}