Кодирование и декодирование облачных данных

Материал из Letopisi.Ru — «Время вернуться домой»
Перейти к: навигация, поиск

Кодирование облачных переменных - процесс перекодировки списка или строки в цифровой формат облачных пероеменных.


Содержание

Быстрый способ

Необходимые переменные и списки

Метод требует следующих переменных:

  • (z)
  • i
  • i2
  • i3
  • ☁ data
  • C

Кроме того, потребуется список "users". В этом примере проект будет запоминать участников, которые посетили этот проект, но этот список можно потом поменять на другой.

Кодирование

The encoding process takes each item in a list, separates them with a particular number, and converts each letter into a number with a fixed amount of digits.

В процесс кодирования каждый элемент списка разделяется числом разделителем, а каждая буква конвертируется в число из определенного числа цифр. В качестве разделителя используется код 00. При кодировании каждая буква каждого элемента списка добавляется как число. Число представляет букву в переменной z, которая содержит все все возможные буквы. Например, буква b находится в переменной z на позиции 12 и код представляющий b 12, соответственно для буквы e код 15


when gf clicked
set [z v] to [0123456789abcdefghijklmnopqrstuvwxyz?] 

define encode
set [i v] to [0]
set [C v] to []
repeat (length of [users v])
    change [i v] by (1)
    set [i2 v] to [0]
    repeat (length of (item (i) of [users v]))
        change [i2 v] by (1)
        set [i3 v] to [0]
        repeat until <<(letter (i2) of (item (i) of [users v])) = (letter (i3) of (z))> or <not <(i3) < (length of (z))>>> //если буква не входит в переменную "z" то цикл не завершится, поэтому условия, что все завершается после проверки последней буквы в переменной z 
            change [i3 v] by (1)
        end
        if <(length of (i3)) < (length of (length of (z)))> then // Если число цифр в  i3 меньше максимального, то добавляется нужное число нулей 
            repeat until <not <(length of (i3)) < (length of (length of (z)))>>
                set [i3 v] to (join [0] (i3))
            end
        end
        set [C v] to (join (C) (i3))
    end
    repeat (length of (length of (z)))
        set [C v] to (join (C) [0])
    end
end
set [☁ data v] to (C)

Декодирование

Декодирование берет данные в цифрах и превращает их в буквы

define decode
set [i v] to [0]
set [i3 v] to []
set [C v] to (☁ data)// чтобы не слишком часто обращаться к облачным данным
delete (all v) of [users v]
if <not <((length of (C)) mod (length of (length of (z)))) = [0]>> then
    repeat until <((length of (C)) mod (length of (length of (z)))) = [0]>
        set [C v] to (join [0] (C))
    end
end
repeat ((length of (C)) / (length of (length of (z))))
    set [i2 v] to []
    repeat (length of (length of (z)))
        set [i2 v] to (join (i2) (letter ((i) + (length of (i2))) of (C)))
    end
    if <(i2) = [0]> then// 000 = 0 is true, so no matter how long the 0 is it'll be true here
        add (i3) to [users v]
        set [i3 v] to []
    else
        set [i3 v] to (join (i3) (letter (i2) of (z)))
    end
    change [i v] by (length of (length of (z)))
end

Углубленный метод

Необходимые переменные и списки

Большинство необходимых переменных задаются скриптом

define Create Vars
set [Characters v] to [� !"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~0123456789]
set [p1 v] to [1] //This variable is the ID that will be given to the character
repeat (length of (Characters))
  set (letter (p1) of (Characters)) to (join([floor v] of ((p1)/(10)))(round((p1) mod (10))))//This edited block creates a variable with the name of a specific character, with that character's 2 digit number ID inside the variable
  change [p1 v] by (1)

Дополнительные переменные

  • Characters
  • p1
  • p2
  • p3
  • p4
  • ☁ data

Lists include:

  • CloudList
  • bypass
  • hold

Кодирование

The encoding process works in the same way as the above method, although this method uses a faster way of encoding characters to their 2 digit ID number that includes another edited block:

define Encode
delete (all v) of [bypass v]
set [p1 v] to [1]
repeat (length of [CloudList v])
  set [p2 v] to [1]
  set [p3 v] to (item (p1) of [CloudList v])//sets a variable to the item of the cloud list we are currently encoding
  repeat (length of (p3))
    set [p4 v] to (join ((letter (p2) of (p3)) of [Sprite1 v])[1])//This edited block is used to pull the data out of those variables you set with "Create Vars" replace Sprite1 with the sprite that ran the Create Vars custom block
    add (letter (1) of (p4)) to [bypass v]
    add (letter (2) of (p4)) to [bypass v]//Adds the 2 digit ID of the character to the list
    change [p2 v] by (1)//changes to the next character in the item of the cloud list so it can encode it
  end
  add [0] to [bypass v]
  add [0] to [bypass v]//These 0s tell the decoder to make a new item
  change [p1 v] by (1)//changes to the next item in the cloud list so it can encode it
end
set [☁ data v] to (bypass)//The bypass list is used to bypass the 10240 character limit of the join block, it also prevents cloud flooding (setting a cloud variable more than 3 times a second)

Decoding

The decoding script for this method will look very similar to the script for the easier version. Luckily, there are no edited blocks in this script!

define Decode
set [p1 v] to [1]
set [p2 v] to [2]
delete (all v) of [CloudList v]
delete (all v) of [hold v] //This list collects the data for one item of the Cloudlist, it is then added to the CloudList and the process is repeated
repeat ((length of (☁ data)) / (2))//Since we encoded each character into a 2 digit number, they must be decoded in sets of 2 digits
    set [p3 v] to (join (letter (p1) of (☁ data)) (letter (p2) of (☁ data)))//Uses two variables (p1 and p2) for speed, since using another variable is faster than using (p1+1)
    change [p1 v] by (2)
    change [p2 v] by (2)
    if <(p3) = [0]> then//Doesn't need to be 00, because according to scratch, 00 = 0 even when they are read as strings
        add (hold) to [CloudList v]//adds decoded data to the cloud list in one item
        delete (all v) of [hold v]//deletes and repeats
    else
        add (letter (p3) of (Characters)) to [hold v]//collects decoded data
    end
end

See Also

Персональные инструменты
Инструменты
Акция час кода 2018

организаторы проекта