I'm a super noob, and I'm trying to make a Caesar cipher in p5js, so far I manage to code the UI, but now I'm stuck and don't really know how to move forward can someone please help?
I know I need to use for loops, but I can't figure out how?
I really appreciate all the help
Thanks
let inp;
let button;
let alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
function setup() {
createCanvas(600, 600);
// Type here your plain or encryted message
inp = createInput();
inp.position(20, 30);
inp.size(550, 200);
// Encrypted / Decrypted message
inp = createInput();
inp.position(20, 340);
inp.size(550, 200);
// Key
inp = createInput();
inp.position(20, 280);
inp.size(200, 20);
button = createButton("Encrypt");
button.position(370, 260);
button.size(100, 50);
// button.mousePressed(encrypt);
button = createButton("Decrypt");
button.position(475, 260);
button.size(100, 50);
// button.mousePressed(decrypt);
noStroke();
// button.mousePressed(drawName);
}
function draw() {
background(0)
text("Type here your plain or encryted message", 20, 20);
text("Encrypted / Decrypted message", 20, 330);
text("Key", 20, 270);
fill(255)
}
Here's a link to the completed version: https://editor.p5js.org/Samathingamajig/sketches/7P5e__R8M
But I'll actually explain what I did so that you gain something from this.
function encrypt():
initial text = (get initial text)
output = "" // empty string
offset (aka seed) = (get the seed, make sure its an integer) mod 26
for each character in initial:
if character is in the alphabet:
index = (find the index of the character in the alphabet)
outputIndex = (index + offset + 26 /* this 26 isn't needed, but it's there to make the decrypt be a simple copy + paste, you'll see */ ) mod 26 /* force between 0 and 25, inclusive */
output += outputIndex to character
else:
output += initial character
(set the output text field to the output)
function decrypt():
initial text = (get initial text)
output = "" // empty string
offset (aka seed) = (get the seed, make sure its an integer)
for each character in initial:
if character is in the alphabet:
index = (find the index of the character in the alphabet)
outputIndex = (index - offset + 26 /* when subtracting the offset, the character could be a negative index */ ) mod 26 /* force between 0 and 25, inclusive */
output += outputIndex to character
else:
output += initial character
(set the output text field to the output)
Some other changes I made to your code that are required for this are:
indexOf()
, includes()
, alphabet[i]
, etc. with a string and the definition looks cleaner