Difference between revisions of "Qubot Script"

From QuData
Jump to navigation Jump to search
(Removed redirect to Qubot Script/ru)
Tag: Removed redirect
 
(11 intermediate revisions by the same user not shown)
Line 5: Line 5:
 
'''''Qubot Script''''' - is a programming language used to perform logical and mathematical operations while solving bot tasks
 
'''''Qubot Script''''' - is a programming language used to perform logical and mathematical operations while solving bot tasks
  
<span id="объявление-слотов-переменных"></span>
+
<span id="variable-slot-declaration"></span>
 
== Slots ==
 
== Slots ==
  
Line 17: Line 17:
 
A slot named '''a''' is declared and the value '''7''' is assigned to it
 
A slot named '''a''' is declared and the value '''7''' is assigned to it
  
<span id="типы-слотов"></span>
+
<span id="slot-types"></span>
  
 
== Local variables ==
 
== Local variables ==
  
В отличие от слотов локальные переменные сохраняются только внутри скрипта, где они объявлены. <br>
+
Unlike slots, local variables are stored only within the script where they are declared. <br>
Объявление происходит путем добавления перед именем служебного слова '''local''':
+
The declaration is made by adding the keyword '''local''' before the name:
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
local b = 8    // локальная переменная
+
local b = 8    // local variable
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Если локальная переменная объявлена внутри фигурных скобок '''{}''', то и ее значение доступно только там:
+
If a local variable is declared inside curly braces '''{}''', then its value is only available there:
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
local b = 8    // локальная переменная текущего скрипта
+
local b = 8    // local variable of the current script
  
 
if (b == 8)
 
if (b == 8)
 
{
 
{
   local c = 9 // локальная переменная блока оператора 'if'
+
   local c = 9 // local variable of 'if' statement block
   print(c)    // выведет 9
+
   print(c)    // will output 9
 
}
 
}
  
print(b)      // выведет 8  
+
print(b)      // will output 8
print(c)      // выдаст ошибку, т.к. тут уже переменная 'с' недоступна
+
print(c)      // will give an error, because the variable 'с' is unavailable here
 
</syntaxhighlight>
 
</syntaxhighlight>
  
<span id="типы-слотов"></span>
+
<span id="slot-types"></span>
  
== Типы переменных ==
+
== Variable types ==
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
sInt = 7                            // целочисленный
+
sInt = 7                            // Integer
sFloat = 7.3                        // вещественный
+
sFloat = 7.3                        // Float
sStr = "hello"                      // строковый
+
sStr = "hello"                      // String
sArr = [7, 7.3, "hello", sStr]      // массив
+
sArr = [7, 7.3, "hello", sStr]      // Array
sDic = { n: 1, s: "Wine"  }          // словарь
+
sDic = { n: 1, s: "Wine"  }          // Dictionary
sBool = true                        // бинарный
+
sBool = true                        // Boolean
sRegExp = /[abc]/                    // регулярное выражение
+
sRegExp = /[abc]/                    // Regular expression
sNone = none                        // неопределенное значение
+
sNone = none                        // Undefined value
 
</syntaxhighlight>
 
</syntaxhighlight>
  
<span id="логические-операции"></span>
+
<span id="logical-operations"></span>
  
== Логические операции ==
+
== Logical operations ==
  
* '''and''' - логическое ‘И’
+
* '''and''' - logical  ‘AND’
* '''or''' - логическое ‘ИЛИ’
+
* '''or''' - logical ‘OR’
* '''not''' - отрицание ‘НЕТ’
+
* '''not''' - negation ‘NO’
  
  
Например:
+
For example:
  
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Line 75: Line 75:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
<span id="арифметические-операции"></span>
+
<span id="arithmetic-operations"></span>
  
== Арифметические операции ==
+
== Arithmetic operations ==
  
* '''+''' - сложение
+
* '''+''' - addition
* '''-''' - вычитание
+
* '''-''' - subtraction
* '''*''' - умножение
+
* '''*''' - multiplication
* '''/''' - деление
+
* '''/''' - division
  
Например:
+
For example:
  
 
<syntaxhighlight lang="js">res = 2+3-4*5+(1.5-0.2/2)</syntaxhighlight>
 
<syntaxhighlight lang="js">res = 2+3-4*5+(1.5-0.2/2)</syntaxhighlight>
  
== Комментарии ==
+
== Comments ==
  
Комментарии используются для документирования фрагментов скрипта.
+
Comments are used to document script fragments.
Могут быть многострочыми и однострочными:
+
They can be multi-line and single-line:
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
 
/*
 
/*
Пример
+
Example of
     многострочного
+
     multi-line
         комментария
+
         comment
 
*/
 
*/
  
a = 2253 // пример однострочного комментария
+
a = 2253 // example of single-line comment
  
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Также разрешается и питоновский стиль комментария:
+
Python style comments are also allowed:
 
<syntaxhighlight lang="python">
 
<syntaxhighlight lang="python">
a = 2253 # пример однострочного комментария
+
a = 2253 # example of single-line comment
 
</syntaxhighlight>
 
</syntaxhighlight>
  
  
  
<span id="работа-с-массивами"></span>
+
<span id="working-with-arrays"></span>
  
<span id="работа-со-словарем-объектом"></span>
+
<span id="working-with-dictionary-object"></span>
  
== Работа со словарем (объектом) ==
+
== Working with a dictionary (object) ==
  
Объявление словаря:
+
Dictionary declaration:
  
 
<syntaxhighlight lang="js">dic = { n: 1, s: "Wine"  } </syntaxhighlight>
 
<syntaxhighlight lang="js">dic = { n: 1, s: "Wine"  } </syntaxhighlight>
  
Доступ к значениям словаря:
+
Accessing dictionary values:
  
<syntaxhighlight lang="js">a = dic.n            // доступ к полю с именем "n" через точку  
+
<syntaxhighlight lang="js">a = dic.n            // access to field named "n" through dot  
a = dic["n"]          // доступ к полю с именем "n" через оператор доступа
+
a = dic["n"]          // access a field named "n" via an access statement
dic["food"] = "milk"  // добавление в словарь пары ключ-значение
+
dic["food"] = "milk"  // add a key-value pair to a dictionary
 
</syntaxhighlight>
 
</syntaxhighlight>
  
== Работа с массивами ==
+
== Working with arrays ==
  
Объявление массива:
+
Array declaration:
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
arr = [1,2,3]        // создает массив с тремя элементами со значениями 1,2,3
+
arr = [1,2,3]        // create an array with three elements with values 1,2,3
  
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Доступ к элементам массива:
+
Accessing array elements:
  
<syntaxhighlight lang="js">first  = arr[0]      // получить первый элемент массива
+
<syntaxhighlight lang="js">first  = arr[0]      // get the first element of array
last  = arr[-1]      // получить последний элемент массива
+
last  = arr[-1]      // get the last element of an array
last  = arr[-2]      // получить предпоследний элемент массива
+
last  = arr[-2]      // get the penultimate element of an array
arr[0] = 7            // изменить значение первого элемента</syntaxhighlight>
+
arr[0] = 7            // change the value of the first element</syntaxhighlight>
Функции работы с массивом:
+
Array Functions:
  
'''''push(val1,val2...)''''' - добавить в конец массива элементы со значениями '''val1, val2...'''
+
'''''push(val1,val2...)''''' - add elements with values '''val1, val2...''' to the end of the array
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
arr.push(4) // добавить значение '4' в конец массива
+
arr.push(4) // add the value '4' to the end of the array
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''unshift(val1,val2...)''''' - добавить в начало массива элементы со значениями '''val1, val2...'''
+
'''''unshift(val1,val2...)''''' - add elements with values '''val1, val2...''' to the beginning of the array
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
arr.unshift(0) // добавить значение '0' в начало
+
arr.unshift(0) // add the value '0' to the beginning
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''pop()''''' - удалить последний элемент массива и вернуть его значение
+
'''''pop()''''' - remove the last element of an array and return its value
  
'''''shift()''''' - удалить первый элемент массива и вернуть его значение
+
'''''shift()''''' - remove the first element of an array and return its value
  
'''''slice(start,end)''''' - возвращает часть массива начиная с позиции '''start''' и если указана переменная '''end''', то до нее не включая
+
'''''slice(start,end)''''' - return a part of the array starting from the position '''start''' and if the variable '''end'''is specified, then up to it
  
'''''splice(start, deleteCount)''''' - удаляет '''deleteCount''' элементов начиная с позиции '''start'''
+
'''''splice(start, deleteCount)''''' - delete '''deleteCount''' elements from the position '''start'''
  
'''''clear()''''' - очистить массив
+
'''''clear()''''' - clear the array
  
Функции работы с массивом словарей:
+
Dictionary array functions:
  
'''''find(EXPR)''''' - ищет элементы массива, удовлетворяющие условию '''EXPR'''. Найденные элементы возвращаются в виде массива<br>
+
'''''find(EXPR)''''' - search for array elements that satisfy the '''EXPR''' condition. Found elements are returned as an array.<br>
Например:
+
For example:
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
arr = [                            // массив из трех объектов с продуктами
+
arr = [                            // array of three objects with products
 
   {title: "Wine", price: 120},
 
   {title: "Wine", price: 120},
 
   {title: "Cheese", price: 100},
 
   {title: "Cheese", price: 100},
Line 175: Line 175:
 
]  
 
]  
  
local res = arr.find(price > 80)  // найти все объекты у которых поле 'price' больше 80 и вернуть их в массиве
+
local res = arr.find(price > 80)  // find all objects whose 'price' field is higher than 80 and return them in an array
print('найдено $res.length:')     // выведет количество найденных объектов
+
print('found $res.length:')       // display the number of found objects
print(res)                         // выведет объекты, удовлетворяющие условию
+
print(res)                       // display objects that satisfy the condition
 
</syntaxhighlight>
 
</syntaxhighlight>
  
  
'''''total(EXPR)''''' - применить выражение '''EXPR''' к каждому элементу массива и суммировать все значения<br>
+
'''''total(EXPR)''''' - apply the expression '''EXPR''' to each element of the array and sum all the values.<br>
Например посчитаем сумму товаров в корзине:
+
For example, let's calculate the amount of items in the cart:
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
arr = [                                // массив из трех объектов с продуктами
+
arr = [                                // array of three objects with products
 
   {title: "Wine", price: 120, amount: 3},
 
   {title: "Wine", price: 120, amount: 3},
 
   {title: "Pizza", price: 100, amount: 2},
 
   {title: "Pizza", price: 100, amount: 2},
Line 190: Line 190:
 
]  
 
]  
  
local res = arr.total(price * amount)  // для каждого элемента массива умножаем цену на количество и складываем результат
+
local res = arr.total(price * amount)  // for each element of the array, multiply the price by the quantity and add the result
print("К оплате: $res грн.")           // выведет сумму товаров: "К оплате: 680 грн."
+
print("To pay: $res UAH")               // display the cost of goods: "To pay: 680 UAH"
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''count(EXPR)''''' - найти количество элементов массива для которых истинно выражение '''EXPR'''
+
'''''count(EXPR)''''' - find the number of array elements for which the expression '''EXPR''' is true
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
arr = [                                // массив из трех объектов с продуктами
+
arr = [                                // array of three objects with products
 
   {title: "Wine", price: 120, amount: 3},
 
   {title: "Wine", price: 120, amount: 3},
 
   {title: "Pizza", price: 100, amount: 2},
 
   {title: "Pizza", price: 100, amount: 2},
Line 202: Line 202:
 
]  
 
]  
  
local res = arr.count(price < 100)                           // для каждого элемента массива умножаем цену на количество и складываем результат
+
local res = arr.count(price < 100)   // for each element of the array, multiply the price by the quantity and add the result
print("Количество товаров, дешевле 100 грн: $res")           // выведет количество товаров: "Количество товаров, дешевле 100 грн: 1"
+
print("The quantity of goods that is cheaper than 100 UAH: $res") // display the number of goods: "The quantity of goods that is cheaper than 100 UAH: 1"
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''sort(KEY)''''' - отсортировать массив
+
'''''sort(KEY)''''' - sort array
  
Поддерживаются только массивы, в которых все значения одного типа: число или строка для sort() и словарь для sort(key)
+
Only arrays are supported where all values are of the same type: a number or string for sort() and a dictionary for sort(key)
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
list = [1, 3, 2] // массив чисел
+
list = [1, 3, 2] // array of numbers
str  = ["a", "hi", "banana"] // массив строк
+
str  = ["a", "hi", "banana"] // string array
arr  = [        // массив из словарей с продуктами
+
arr  = [        // array of dictionaries with products
 
   {title: "Wine", price: 120, amount: 3},
 
   {title: "Wine", price: 120, amount: 3},
 
   {title: "Pizza", price: 100, amount: 2},
 
   {title: "Pizza", price: 100, amount: 2},
 
]  
 
]  
  
list.sort()       // отсортировать массив по возрастанию
+
list.sort()       // sort array in ascending order
  str.sort()        // отсортировать массив по возрастанию
+
  str.sort()        // sort array in ascending order
  arr.sort(price)  // отсортировать массив объектов по ключу 'price'
+
  arr.sort(price)  // sort array of objects by key 'price'
 
// TODO
 
// TODO
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''reverse()''''' - перевернуть массив
+
'''''reverse()''''' - flip array
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
list = [1, 3, 2]  // массив
+
list = [1, 3, 2]  // array
  
 
list.reverse()    // [2, 3, 1]
 
list.reverse()    // [2, 3, 1]
Line 232: Line 232:
  
  
<span id="работа-со-строками"></span>
+
<span id="working-with-strings"></span>
  
== Работа со строками ==
+
== Working with strings ==
  
Объявление строковых слотов:
+
Declaration of string slots:
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
str = "hello"          // используя двойные кавычки
+
str = "hello"          // using double quotes
str = 'hello'          // используя одинарные кавычки</syntaxhighlight>
+
str = 'hello'          // using single quotes</syntaxhighlight>
  
Операции со строками:
+
String operations:
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
 
base = 'http://imgs/'
 
base = 'http://imgs/'
url = base + 'img1.png' // сложение строк
+
url = base + 'img1.png' // string addition
 
</syntaxhighlight>
 
</syntaxhighlight>
<span id="функции-перехода"></span>
+
<span id="transition-function"></span>
  
Подстановка слотов в строки:
+
Substitution of slots in strings:
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
 
a = 5
 
a = 5
str = "a = $a"          // вместо $a будет подставлено значение слота a
+
str = "a = $a"          // instead of $a the value of slot a will be substituted
print(str)              // выведет: "a = 5"
+
print(str)              // will output: "a = 5"
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Вставка выражений в строки:
+
Inserting expressions into strings:
  
Выражения можно вставлять в строки, обрамляя их фигурными скобками:
+
Expressions can be inserted into strings by framing them with curly braces:
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
str = "2 + 3 = {2+3}"  // вычислит выражение и вставит результат в строку
+
str = "2 + 3 = {2+3}"  // evaluate the expression and insert the result into a string
print(str)              // выведет: "2 + 3 = 5"
+
print(str)              // will output: "2 + 3 = 5"
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Экранирование спецсимволов '$','{','}' происходит путем добавления наклонной черты '\'
+
Shielding special characters '$','{','}' is done by adding a slash '\'
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
str = "price: 4.99\$ \{sale\}"  // вычислит выражение и вставит результат в строку
+
str = "price: 4.99\$ \{sale\}"  // evaluate the expression and insert the result into a string
print(str)                      // выведет: "price: 4.99$ {sale}"
+
print(str)                      // will output: "price: 4.99$ {sale}"
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Функции работы со строками:
+
String Functions:
  
'''''length''''' - получить длинну строки
+
'''''length''''' - get string length
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
 
str = "hello"
 
str = "hello"
len = str.length          // вернет 5 - число символов строки "hello"
+
len = str.length          // return 5 - the number of characters in the string "hello"
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''substring(start,end)''''' - получить подстроку начиная с позиции '''start''' и до позиции '''end''' не включая
+
'''''substring(start,end)''''' - get a substring starting from position '''start''' up to '''end''' position, not including it
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
 
str = "http://server/im.png"
 
str = "http://server/im.png"
substr = str.substring(7,13)  // вернет строку "server"
+
substr = str.substring(7,13)  // return the string "server"
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''search(pattern)''''' - найти позицию первого вхождения '''pattern''', иначе вернуть -1. Аргумент '''pattern''' может быть как строкой
+
'''''search(pattern)''''' - find the position of the first occurrence of '''pattern''', otherwise return -1. Argument '''pattern''' can be either a string
так и регулярным выражением:
+
or a regular expression:
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
 
str = "apple orange juice"
 
str = "apple orange juice"
res = str.search('orange')          // вернет позицию строки 'orange': 6
+
res = str.search('orange')          // return the position of the string 'orange': 6
res = str.search(/(orange|juice)/)  // вернет позицию строки 'orange' или 'juice'
+
res = str.search(/(orange|juice)/)  // return the position of the string 'orange' or 'juice'
res = str.search('pizza')          // не найдет 'pizza' и вернет -1
+
res = str.search('pizza')          // will not find 'pizza' and will return -1
 
</syntaxhighlight>
 
</syntaxhighlight>
  
  
<span id="условный-оператор"></span>
+
<span id="conditional-operator"></span>
  
== Условный оператор ==
+
== Conditional operator ==
Оператор '''if''' используется, если необходимо ветвление логики в зависимости от условия
+
The '''if''' statement is used to branch the logic depending on the condition
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 311: Line 311:
 
     res = 'a less or equal 7'
 
     res = 'a less or equal 7'
 
}</syntaxhighlight>
 
}</syntaxhighlight>
В данном примере проверяется условие <code>a &gt; 7</code> и если оно истинно, то выполняется первый блок скрипта, окруженный фигурными скобками, иначе выполняется блок после служебного слова '''else'''
+
In this example, the condition <code>a &gt; 7</code> is checked and if it is true, then the first block of the script is executed, that is surrounded by curly braces, otherwise the block after the keyword '''else''' is executed
  
<span id="цикл-while"></span>
+
<span id="while-loop"></span>
  
== Цикл '''while''' ==
+
== '''While''' loop ==
  
Оператор цикла проверяет условие и пока оно истинно, выполняет код окруженный фигурными скобками
+
The loop statement checks the condition and while it is true, executes the code surrounded by curly braces
  
 
<syntaxhighlight lang="js">a = 7
 
<syntaxhighlight lang="js">a = 7
Line 324: Line 324:
 
     a = a - 1
 
     a = a - 1
 
}</syntaxhighlight>
 
}</syntaxhighlight>
В данном примере скрипт <code>a = a - 1</code> будет выполнятся до тех пор пока значение слота <code>a</code> не станет равным нулю
+
In this example, the script <code>a = a - 1</code> will be executed until the value of the slot <code>a</code> becomes zero
  
<span id="итератор-for"></span>
+
<span id="iterator-for"></span>
== Итератор '''for''' ==
+
== Iterator '''for''' ==
  
Итератор используется для перебора всех значений массива, либо ключей из словаря
+
An iterator is used to loop through all values of an array, or keys from a dictionary
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 342: Line 342:
 
1
 
1
 
</syntaxhighlight>
 
</syntaxhighlight>
В данном примере цикл последовательно перебирает значения массива и заносит их во временную переменную '''val''' соответственно для каждого элемента массива выполняется окруженный фигурными скобками скрипт '''print(val)''' выводящий значение в отладочное окно
+
In this example, the loop sequentially iterates through the values of the array and puts them into the temporary variable '''val''',  respectively, for each element of the array, the script  '''print(val)''', surrounded by curly braces, is executed, displaying the value in the debug window
  
Иногда удобно в цикле иметь и индекс массива, для этого перед переменной значения добавляем имя переменной индекса:
+
Sometimes it is convenient to have an array index in the loop. For this we add the name of the index variable before the value variable:
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 358: Line 358:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Для перебора ключей и значений словаря используется аналогичная конструкция:
+
To iterate over the keys and values of a dictionary, a similar construction is used:
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
 
arr = {pizza: 100, milk: 20, wine: 120}
 
arr = {pizza: 100, milk: 20, wine: 120}
Line 371: Line 371:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
<span id="оператор-switch"></span>
+
<span id="operator-switch"></span>
  
== Оператор выбора '''switch''' ==
+
== '''Switch''' case operator ==
  
Конструкция '''switch''' заменяет собой сразу несколько '''if'''. Она представляет собой более наглядный способ сравнить выражение сразу с несколькими вариантами.
+
The '''switch''' construct replaces several '''ifs''' at once. It is a more visual way to compare an expression against several options at once.
Имеет один или более блок '''case''' и необязательный блок '''default'''.
+
It has one or more '''case''' block and optional '''default''' block.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 388: Line 388:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Переменная проверяется на строгое соответствие значению справа от '''case''' и если оно совпадает, то выполняется код до тех пор пока не встретится
+
The variable is checked for a strict match to the value to the right of '''case''' and if it matches, then the code is executed until it meets '''break''' operator.
оператор '''break'''
 
  
Если ни одно из '''case''' не подошло, выполняется код справа от '''default'''
+
If none of the '''case''' matches, the code to the right of '''default''' is executed.
  
<span id="оператор-in"></span>
+
<span id="operator-in"></span>
  
== Оператор '''in''' ==
+
== '''In''' operator ==
  
Оператор '''in''' проверяет есть ли значение в массиве либо является ключём в словаре.
+
The '''in''' operator checks whether the value is in an array or is a key in a dictionary.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
sArr = [7, 7.3, "hello"]            // массив
+
sArr = [7, 7.3, "hello"]            // array
print("hello" in sArr)              // вернет true, т.к. значение "hello" присутствует в массиве sArr  
+
print("hello" in sArr)              // return true, because the value "hello" is present in the array sArr  
sDic = { price: 100, food: "Wine"}  // словарь
+
sDic = { price: 100, food: "Wine"}  // dictionary
print("food" in sDic)                // вернет true, т.к. ключ "food" присутствует в словаре sDic
+
print("food" in sDic)                // return true, because the key "food" is present in the dictionary sDic
  
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Переменная проверяется на строгое соответствие значению справа от '''case''' и если оно совпадает, то выполняется код до тех пор пока не встретится
+
The variable is checked for a strict match to the value to the right of '''case''' and if it matches, then the code is executed until it meets '''break''' operator.
оператор '''break'''
 
  
Если ни одно из '''case''' не подошло, выполняется код справа от '''default'''
+
If none of the '''case''' matches, the code to the right of '''default''' is executed.
  
<span id="оператор-button"></span>
+
<span id="operator-button"></span>
  
== Оператор '''button''' ==
+
== '''Button''' operator ==
  
 
'''''button(caption){ SCRIPT }'''''<br>
 
'''''button(caption){ SCRIPT }'''''<br>
Данный оператор добавляет в интерфейс кнопку с текстом '''caption''' в текущее сообщение. После нажатия на кнопку выполняется логика '''SCRIPT'''.
+
This operator adds a button to the interface with the text '''caption''' in the current message. After pressing the button, the '''SCRIPT''' logic is executed.
Если '''caption''' - объект, то он должен состоять из двухбуквенных ключей (идентификаторов языка: en, ru,…) со строковыми значения на этих языках.
+
If '''caption''' is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
button('click me')      // текст в кнопке
+
button('click me')      // button text
 
{
 
{
     // скрипт, который выполнится после нажатия
+
     // script that is executed after clicking
 
     print('button was clicked!')
 
     print('button was clicked!')
 
     step('STATE_AFTER_CLICK')
 
     step('STATE_AFTER_CLICK')
Line 429: Line 427:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
При нажатии на кнопку скрипт будет выполнен в контексте локальных переменных на момент добавления данной кнопки, а также в контексте
+
When the button is clicked, the script will be executed in the context of local variables at the time the button was added, as well as in the context of the slot values at the moment the button was clicked!
значений слотов на момент нажатия на кнопку!
 
  
<span id="функции-перехода"></span>
+
<span id="transition-function"></span>
  
== Функции перехода ==
+
== Transition functions ==
  
'''''run(state)''''' - выполнить логику шага '''state'''
+
'''''run(state)''''' - execute '''state''' step logic
  
'''''step(state)''''' - установка шага перехода по умолчанию в значение '''state'''
+
'''''step(state)''''' - set default transition step to '''state'''
  
'''''goto(state)''''' - мгновенный переход в шаг '''state'''
+
'''''goto(state)''''' - instant jump to '''state''' step
  
<span id="функции-работы-с-контентом"></span>
+
<span id="content-functions"></span>
  
== Функции работы с контентом ==
+
== Content functions ==
  
'''''text(obj)''''' - вывести в текущее сообщение текст. Если '''obj''' - это сторока, то она выводится не зависимо от текущего языка. Если '''obj''' - объект, то он должен состоять из двухбуквенных ключей (идентификаторов языка: en, ru,…) со строковыми значения на этих языках.
+
'''''text(obj)''''' - display text in current message. If '''obj''' is a string, then it is output regardless of the current language. If '''obj''' is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 453: Line 450:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''images()''''' - создать новую строку картинок. Каждый последующий вызов image будет добавляться в эту строку, пока снова не будет вызван images().
+
'''''images()''''' - create a new line of images. Every following call to image will be added to this line until images() is called again.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 461: Line 458:
 
image(URL + "owl_b.png") </syntaxhighlight>
 
image(URL + "owl_b.png") </syntaxhighlight>
  
'''''image(url, width)''''' - вывести в текущее сообщение картинку. Если '''url''' - это строка, то он используется не зависимо от текущего языка. Если '''url''' - объект, то он должен состоять из двухбуквенных ключей (идентификаторов языка: en, ru,…) со строковыми значения на этих языках.. Необязательный параметр '''width''' указывает насколько в процентах нужно сжать изображение
+
'''''image(url, width)''''' - add an image to the current message. If '''url''' is a string, then it is used regardless of the current language. If '''url''' is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages. The optional parameter '''width''' specifies how much to compress the image as a percentage.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 469: Line 466:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''buttons()''''' - создать новую строку кнопок. Каждый последующий вызов button будет добавляться в эту строку, пока снова не будет вызван buttons().
+
'''''buttons()''''' - create a new row of buttons. Every following call to button will be added to this line until buttons() is called again.  
  
'''''get_check()''''' - получить массив значений кнопок типа check (1 - нажата, 0 - отжата)
+
'''''get_check()''''' - get an array of button values of the check type (1 - pressed, 0 - released)
  
'''''set_check(list)''''' - задать значения кнопок типа check из массива list.
+
'''''set_check(list)''''' - set the values of check type buttons from the list array.
  
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
Line 480: Line 477:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
'''''get_radio()''''' - получить массив значений кнопок типа radio (1 - нажата, 0 - отжата). Единица будет одна.
+
'''''get_radio()''''' - get an array of radio button values (1 - pressed, 0 - released). The unit will be one.
  
'''''set_radio(list)''''' - задать значения кнопок типа radio из массива list.
+
'''''set_radio(list)''''' - set the values of radio type buttons from the list array.
  
<span id="отладчные-функции"></span>
+
<span id="debug-functions"></span>
  
== Отладчные функции ==
+
== Debugging functions ==
  
'''''print(args)''''' - вывод информации в окно отладки
+
'''''print(args)''''' - display information in the debug window
  
<span id="округление"></span>
+
<span id="rounding"></span>
  
== Округление ==
+
== Rounding ==
  
'''''floor(val)''''' - округление чисел в меньшую сторону:
+
'''''floor(val)''''' - round numbers down:
  
 
<syntaxhighlight lang="js">floor(5.8)    //  5
 
<syntaxhighlight lang="js">floor(5.8)    //  5
 
floor(-6.1)  // -7</syntaxhighlight>
 
floor(-6.1)  // -7</syntaxhighlight>
'''''trunc(val)''''' - отбрасывание дробной части:
+
'''''trunc(val)''''' - discard the fractional part:
  
 
<syntaxhighlight lang="js">trunc(5.51)  //  5
 
<syntaxhighlight lang="js">trunc(5.51)  //  5
 
trunc(-6.99)  // -6</syntaxhighlight>
 
trunc(-6.99)  // -6</syntaxhighlight>
'''''ceil(val)''''' - округление чисел в большую сторону:
+
'''''ceil(val)''''' - round numbers up:
  
 
<syntaxhighlight lang="js">ceil(5.15)    // 6</syntaxhighlight>
 
<syntaxhighlight lang="js">ceil(5.15)    // 6</syntaxhighlight>
'''''round(val, num)''''' - округление '''val''' до '''num''' чисел после запятой:
+
'''''round(val, num)''''' - round '''val''' to '''num''' numbers after the decimal point:
  
 
<syntaxhighlight lang="js">round(3.14159265, 2)  // 3.14</syntaxhighlight>
 
<syntaxhighlight lang="js">round(3.14159265, 2)  // 3.14</syntaxhighlight>
  
<span id="случайные-числа"></span>
+
<span id="random-numbers"></span>
== Случайные числа ==
+
== Random numbers ==
  
'''''randint(min,max)''''' - возвращает целое случайное число в диапазоне [min,max].
+
'''''randint(min,max)''''' - return an integer random number in the range [min,max].
  
'''''random()''''' - возвращает случайное вещественное число в диапазоне [0,1].
+
'''''random()''''' - return an integer random number in the range [0,1].
  
<span id="дата-и-время"></span>
+
<span id="date-and-time"></span>
== Дата и время ==
+
== Date and time ==
  
'''''date(format)''''' - возвращает текущую дату и время в указанном формате. По умолчанию аргумент '''format''' принимает значение: '''%d/%m/%Y %H:%M:%S'''
+
'''''date(format)''''' - return the current date and time in the specified format. By default, the '''format''' argument takes the value: '''%d/%m/%Y %H:%M:%S'''
  
Поддерживаемые коды форматирования:
+
Supported format codes:
  
* '''%y''' - год без столетия ('22')
+
* '''%y''' - year without a century ('22')
* '''%Y''' - год ('2022')
+
* '''%Y''' - year ('2022')
* '''%m''' - месяц
+
* '''%m''' - month
* '''%d''' - день
+
* '''%d''' - day
* '''%H''' - часы
+
* '''%H''' - hours 
* '''%M''' - минуты
+
* '''%M''' - minutes
* '''%S''' - секунды
+
* '''%S''' - seconds
  
Например:
+
For example:
 
<syntaxhighlight lang="js">
 
<syntaxhighlight lang="js">
date()  // 17/05/2022 18:16:31 т.е. сейчас
+
date()  // 17/05/2022 18:16:31 it means now
 
date('%Y.%m.%d %H:%M:%S')  // 2022.05.17 18:16:31
 
date('%Y.%m.%d %H:%M:%S')  // 2022.05.17 18:16:31
 
</syntaxhighlight>
 
</syntaxhighlight>

Latest revision as of 17:04, 1 July 2022

Qubot Script

Qubot Script - is a programming language used to perform logical and mathematical operations while solving bot tasks

Slots

Slot - is a variable whose value is available in all states of the bot. Also, the value of the slot is saved if the bot is closed and then the work is continued after a while.

A slot is declared for the first time when values are assigned to it.
For example:

a = 7

A slot named a is declared and the value 7 is assigned to it

Local variables

Unlike slots, local variables are stored only within the script where they are declared.
The declaration is made by adding the keyword local before the name:

local b = 8    // local variable

If a local variable is declared inside curly braces {}, then its value is only available there:

local b = 8    // local variable of the current script

if (b == 8)
{
   local c = 9 // local variable of 'if' statement block
   print(c)    // will output 9
}

print(b)       // will output 8
print(c)       // will give an error, because the variable 'с' is unavailable here

Variable types

sInt = 7                             // Integer
sFloat = 7.3                         // Float 
sStr = "hello"                       // String
sArr = [7, 7.3, "hello", sStr]       // Array
sDic = { n: 1, s: "Wine"  }          // Dictionary
sBool = true                         // Boolean
sRegExp = /[abc]/                    // Regular expression
sNone = none                         // Undefined value

Logical operations

  • and - logical ‘AND’
  • or - logical ‘OR’
  • not - negation ‘NO’


For example:

a = true
b = false
c = true
res = not((a and b) or c)

Arithmetic operations

  • + - addition
  • - - subtraction
  • * - multiplication
  • / - division

For example:

res = 2+3-4*5+(1.5-0.2/2)

Comments

Comments are used to document script fragments. They can be multi-line and single-line:

/*
Example of
    multi-line
        comment
*/

a = 2253 // example of single-line comment

Python style comments are also allowed:

a = 2253 # example of single-line comment


Working with a dictionary (object)

Dictionary declaration:

dic = { n: 1, s: "Wine"  }

Accessing dictionary values:

a = dic.n             // access to field named "n" through dot  
a = dic["n"]          // access a field named "n" via an access statement
dic["food"] = "milk"  // add a key-value pair to a dictionary

Working with arrays

Array declaration:

arr = [1,2,3]         // create an array with three elements with values 1,2,3

Accessing array elements:

first  = arr[0]       // get the first element of array
last   = arr[-1]      // get the last element of an array
last   = arr[-2]      // get the penultimate element of an array
arr[0] = 7            // change the value of the first element

Array Functions:

push(val1,val2...) - add elements with values val1, val2... to the end of the array

arr.push(4) // add the value '4' to the end of the array

unshift(val1,val2...) - add elements with values val1, val2... to the beginning of the array

arr.unshift(0) // add the value '0' to the beginning

pop() - remove the last element of an array and return its value

shift() - remove the first element of an array and return its value

slice(start,end) - return a part of the array starting from the position start and if the variable endis specified, then up to it

splice(start, deleteCount) - delete deleteCount elements from the position start

clear() - clear the array

Dictionary array functions:

find(EXPR) - search for array elements that satisfy the EXPR condition. Found elements are returned as an array.
For example:

arr = [                            // array of three objects with products
  {title: "Wine", price: 120},
  {title: "Cheese", price: 100},
  {title: "Cola", price: 40},
] 

local res = arr.find(price > 80)   // find all objects whose 'price' field is higher than 80 and return them in an array
print('found $res.length:')       // display the number of found objects
print(res)                       // display objects that satisfy the condition


total(EXPR) - apply the expression EXPR to each element of the array and sum all the values.
For example, let's calculate the amount of items in the cart:

arr = [                                 // array of three objects with products
  {title: "Wine", price: 120, amount: 3},
  {title: "Pizza", price: 100, amount: 2},
  {title: "Cola", price: 40, amount: 3},
] 

local res = arr.total(price * amount)   // for each element of the array, multiply the price by the quantity and add the result
print("To pay: $res UAH")               // display the cost of goods: "To pay: 680 UAH"

count(EXPR) - find the number of array elements for which the expression EXPR is true

arr = [                                 // array of three objects with products
  {title: "Wine", price: 120, amount: 3},
  {title: "Pizza", price: 100, amount: 2},
  {title: "Cola", price: 40, amount: 3},
] 

local res = arr.count(price < 100)    // for each element of the array, multiply the price by the quantity and add the result
print("The quantity of goods that is cheaper than 100 UAH: $res")  // display the number of goods: "The quantity of goods that is cheaper than 100 UAH: 1"

sort(KEY) - sort array

Only arrays are supported where all values are of the same type: a number or string for sort() and a dictionary for sort(key)

list = [1, 3, 2] // array of numbers
str  = ["a", "hi", "banana"] // string array
arr  = [         // array of dictionaries with products
  {title: "Wine", price: 120, amount: 3},
  {title: "Pizza", price: 100, amount: 2},
] 

list.sort()        // sort array in ascending order
 str.sort()        // sort array in ascending order
 arr.sort(price)   // sort array of objects by key 'price'
// TODO

reverse() - flip array

list = [1, 3, 2]  // array 

list.reverse()    // [2, 3, 1]


Working with strings

Declaration of string slots:

str = "hello"           // using double quotes
str = 'hello'           // using single quotes

String operations:

base = 'http://imgs/'
url = base + 'img1.png' // string addition

Substitution of slots in strings:

a = 5
str = "a = $a"          // instead of $a the value of slot a will be substituted
print(str)              // will output: "a = 5"

Inserting expressions into strings:

Expressions can be inserted into strings by framing them with curly braces:

str = "2 + 3 = {2+3}"   // evaluate the expression and insert the result into a string
print(str)              // will output: "2 + 3 = 5"

Shielding special characters '$','{','}' is done by adding a slash '\'

str = "price: 4.99\$ \{sale\}"   // evaluate the expression and insert the result into a string
print(str)                       // will output: "price: 4.99$ {sale}"

String Functions:

length - get string length

str = "hello"
len = str.length           // return 5 - the number of characters in the string "hello"

substring(start,end) - get a substring starting from position start up to end position, not including it

str = "http://server/im.png"
substr = str.substring(7,13)  // return the string "server"

search(pattern) - find the position of the first occurrence of pattern, otherwise return -1. Argument pattern can be either a string or a regular expression:

str = "apple orange juice"
res = str.search('orange')          // return the position of the string 'orange': 6
res = str.search(/(orange|juice)/)  // return the position of the string 'orange' or 'juice'
res = str.search('pizza')           // will not find 'pizza' and will return -1


Conditional operator

The if statement is used to branch the logic depending on the condition

a = 9
if (a > 7) 
{
    res = 'a more than 7'
}
else
{
    res = 'a less or equal 7'
}

In this example, the condition a > 7 is checked and if it is true, then the first block of the script is executed, that is surrounded by curly braces, otherwise the block after the keyword else is executed

While loop

The loop statement checks the condition and while it is true, executes the code surrounded by curly braces

a = 7
while (a > 0) 
{
    a = a - 1
}

In this example, the script a = a - 1 will be executed until the value of the slot a becomes zero

Iterator for

An iterator is used to loop through all values of an array, or keys from a dictionary

arr = [3,2,1]
for(val in arr)
{
    print(val)
}
output:
3
2
1

In this example, the loop sequentially iterates through the values of the array and puts them into the temporary variable val, respectively, for each element of the array, the script print(val), surrounded by curly braces, is executed, displaying the value in the debug window

Sometimes it is convenient to have an array index in the loop. For this we add the name of the index variable before the value variable:

arr = [3,2,1]
for(i, val in arr)
{
    print("$i: $val")
}
output:
0: 3
1: 2
2: 1

To iterate over the keys and values of a dictionary, a similar construction is used:

arr = {pizza: 100, milk: 20, wine: 120}
for(key, val in arr)
{
    print("$key: $val")
}
output:
pizza: 100
milk: 20
wine: 120

Switch case operator

The switch construct replaces several ifs at once. It is a more visual way to compare an expression against several options at once. It has one or more case block and optional default block.

a = 'one'
switch(a)
{
   case 'one': print('one'); break;
   case 'two': print('two'); break;
   default: print('def')
}

The variable is checked for a strict match to the value to the right of case and if it matches, then the code is executed until it meets break operator.

If none of the case matches, the code to the right of default is executed.

In operator

The in operator checks whether the value is in an array or is a key in a dictionary.

sArr = [7, 7.3, "hello"]             // array
print("hello" in sArr)               // return true, because the value "hello" is present in the array sArr 
sDic = { price: 100, food: "Wine"}   // dictionary
print("food" in sDic)                // return true, because the key "food" is present in the dictionary sDic

The variable is checked for a strict match to the value to the right of case and if it matches, then the code is executed until it meets break operator.

If none of the case matches, the code to the right of default is executed.

Button operator

button(caption){ SCRIPT }
This operator adds a button to the interface with the text caption in the current message. After pressing the button, the SCRIPT logic is executed. If caption is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages.

button('click me')      // button text
{
    // script that is executed after clicking 
    print('button was clicked!')
    step('STATE_AFTER_CLICK')
}

When the button is clicked, the script will be executed in the context of local variables at the time the button was added, as well as in the context of the slot values at the moment the button was clicked!

Transition functions

run(state) - execute state step logic

step(state) - set default transition step to state

goto(state) - instant jump to state step

Content functions

text(obj) - display text in current message. If obj is a string, then it is output regardless of the current language. If obj is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages.

text("Hi world!")     
text({ en: "Hi world!", ru: "Привет мир!", es: "¡Hola mundo!"})

images() - create a new line of images. Every following call to image will be added to this line until images() is called again.

URL = "https://qudata.com/qubot/im/"  
images()     
image(URL + "owl_a.png")     
image(URL + "owl_b.png")

image(url, width) - add an image to the current message. If url is a string, then it is used regardless of the current language. If url is an object, then it must consist of two-letter keys (language identifiers: en, ru,…) with string values in these languages. The optional parameter width specifies how much to compress the image as a percentage.

URL = "https://qudata.com/qubot/im/"     
image(URL + "owl_a.png")  
image({ en: URL + "en.png", ru: URL + "ru.png"})

buttons() - create a new row of buttons. Every following call to button will be added to this line until buttons() is called again.

get_check() - get an array of button values of the check type (1 - pressed, 0 - released)

set_check(list) - set the values of check type buttons from the list array.

CHECK = [0,1,0]
set_check(CHECK)

get_radio() - get an array of radio button values (1 - pressed, 0 - released). The unit will be one.

set_radio(list) - set the values of radio type buttons from the list array.

Debugging functions

print(args) - display information in the debug window

Rounding

floor(val) - round numbers down:

floor(5.8)    //  5
floor(-6.1)   // -7

trunc(val) - discard the fractional part:

trunc(5.51)   //  5
trunc(-6.99)  // -6

ceil(val) - round numbers up:

ceil(5.15)    // 6

round(val, num) - round val to num numbers after the decimal point:

round(3.14159265, 2)  // 3.14

Random numbers

randint(min,max) - return an integer random number in the range [min,max].

random() - return an integer random number in the range [0,1].

Date and time

date(format) - return the current date and time in the specified format. By default, the format argument takes the value: %d/%m/%Y %H:%M:%S

Supported format codes:

  • %y - year without a century ('22')
  • %Y - year ('2022')
  • %m - month
  • %d - day
  • %H - hours
  • %M - minutes
  • %S - seconds

For example:

date()  // 17/05/2022 18:16:31 it means now
date('%Y.%m.%d %H:%M:%S')  // 2022.05.17 18:16:31