Javascript to create a cipher?
Jan 12, 2021
Hi all, I would like to create an encoding Storyline in which the user specifies the Caesar cipher (+N) to encode a word. For example, typing MARK in a +2 cipher work output OCTM. Does that make sense? I was hoping to use JS to pull apart the input variable and encode it, but I can't seem to make it work.
Here's the JS that I am currently using:
var player = GetPlayer();
var str = player.GetVar("TextEntry");
var amount = player.Getvar("Cipher");
var output = '';
for (var i = 0; i < str.length; i ++) {
var c = str[i];
if (c.match(/[a-z]/i)) {
var code = str.charCodeAt(i);
if ((code >= 65) && (code <= 90))
c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
else if ((code >= 97) && (code <= 122))
c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
};
output += c;
};
player.SetVar("returned",output);
player.SetVar("YouTyped",str);
2 Replies
I found this online. I modified it a little bit to work in storyline.
var player = GetPlayer();
var cipherText = player.GetVar("TextEntry");
var cipherOffset = player.GetVar("Cipher");
var alphabet = "abcdefghijklmnopqrstuvwxyz";
var fullAlphabet = alphabet + alphabet + alphabet;
cipherOffset = (cipherOffset % alphabet.length);
var cipherFinish = '';
for(i=0; i<cipherText.length; i++){
var letter = cipherText[i];
var upper = (letter == letter.toUpperCase());
letter = letter.toLowerCase();
var index = alphabet.indexOf(letter);
if(index == -1){
cipherFinish += letter;
} else {
index = ((index + cipherOffset) + alphabet.length);
var nextLetter = fullAlphabet[index];
if(upper) nextLetter = nextLetter.toUpperCase();
cipherFinish += nextLetter;
}
}
player.SetVar("returned",cipherFinish);
player.SetVar("YouTyped",cipherText);
Thank you so much!