微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

p5js中的Caesar Cipher

如何解决p5js中的Caesar Cipher

我是一个超级菜鸟,我正在尝试在p5js中创建一个Caesar密码,到目前为止,我设法编写了UI,但是现在我被卡住了,真不知道该如何前进请帮忙吗?

我知道我需要使用循环,但是我不知道该怎么做? 我非常感谢所有帮助
谢谢

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,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",330);
  text("Key",270);
  fill(255)
}

解决方法

以下是完整版本的链接: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]等,并且定义看起来更简洁

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。