p5js 中的凯撒密码

Caesar Cipher in p5js

我是一个超级菜鸟,我正在尝试在 p5js 中制作凯撒密码,到目前为止我设法编写了 UI,但现在我被卡住了,我真的不知道如何前进,有人可以帮忙吗?

我知道我需要使用 for 循环,但我不知道如何使用? 我非常感谢所有的帮助
谢谢

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)
}

这是完整版本的 link:https://editor.p5js.org/Samathingamajig/sketches/7P5e__R8M

但实际上我会解释我做了什么,以便您从中有所收获。

凯撒密码的工作原理:

  1. 从种子值和旋转文本的整数开始
  2. 要加密,对于每个字母,将种子添加到字母中。即 A + 2 = C,B + 5 = G,等等
  3. 要解密,对于每个字母,从字母中减去种子。即 C - 2 = A,G - 5 = B,等等

伪代码:

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)

您的代码的一些其他更改:

我对您的代码所做的一些其他更改是:

  • 拥有所有按钮的全局数组和所有输入的全局数组。您一直覆盖该值,因此一次只有一个引用,因此您无法访问加密和解密函数中的值
  • 更改了创建输入(文本字段)的顺序,以便它们是垂直定义的,这有利于我们推送到数组时
  • 将字母表变量设为字符串而不是数组,您仍然可以使用字符串执行 indexOf()includes()alphabet[i] 等,并且定义看起来更清晰