New initial commit with .svn directories and their contents ignored.

This commit is contained in:
ellen.spertus
2013-10-30 14:46:03 -07:00
commit a8acffd81c
754 changed files with 85941 additions and 0 deletions

View File

@@ -0,0 +1,85 @@
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for colour blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Python.colour');
goog.require('Blockly.Python');
Blockly.Python['colour_picker'] = function(block) {
// Colour picker.
var code = '\'' + block.getTitleValue('COLOUR') + '\'';
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['colour_random'] = function(block) {
// Generate a random colour.
Blockly.Python.definitions_['import_random'] = 'import random';
var code = '\'#%06x\' % random.randint(0, 2**24 - 1)';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['colour_rgb'] = function(block) {
// Compose a colour from RGB components.
var functionName = Blockly.Python.provideFunction_(
'colour_rgb',
[ 'def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(r, g, b):',
' r = round(min(100, max(0, r)) * 2.55)',
' g = round(min(100, max(0, g)) * 2.55)',
' b = round(min(100, max(0, b)) * 2.55)',
' return \'#%02x%02x%02x\' % (r, g, b)']);
var r = Blockly.Python.valueToCode(block, 'RED',
Blockly.Python.ORDER_NONE) || 0;
var g = Blockly.Python.valueToCode(block, 'GREEN',
Blockly.Python.ORDER_NONE) || 0;
var b = Blockly.Python.valueToCode(block, 'BLUE',
Blockly.Python.ORDER_NONE) || 0;
var code = functionName + '(' + r + ', ' + g + ', ' + b + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['colour_blend'] = function(block) {
// Blend two colours together.
var functionName = Blockly.Python.provideFunction_(
'colour_blend',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
'(colour1, colour2, ratio):',
' r1, r2 = int(colour1[1:3], 16), int(colour2[1:3], 16)',
' g1, g2 = int(colour1[3:5], 16), int(colour2[3:5], 16)',
' b1, b2 = int(colour1[5:7], 16), int(colour2[5:7], 16)',
' ratio = min(1, max(0, ratio))',
' r = round(r1 * (1 - ratio) + r2 * ratio)',
' g = round(g1 * (1 - ratio) + g2 * ratio)',
' b = round(b1 * (1 - ratio) + b2 * ratio)',
' return \'#%02x%02x%02x\' % (r, g, b)']);
var colour1 = Blockly.Python.valueToCode(block, 'COLOUR1',
Blockly.Python.ORDER_NONE) || '\'#000000\'';
var colour2 = Blockly.Python.valueToCode(block, 'COLOUR2',
Blockly.Python.ORDER_NONE) || '\'#000000\'';
var ratio = Blockly.Python.valueToCode(block, 'RATIO',
Blockly.Python.ORDER_NONE) || 0;
var code = functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};

312
generators/python/lists.js Normal file
View File

@@ -0,0 +1,312 @@
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for list blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.lists');
goog.require('Blockly.Python');
Blockly.Python['lists_create_empty'] = function(block) {
// Create an empty list.
return ['[]', Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['lists_create_with'] = function(block) {
// Create a list with any number of elements of any type.
var code = new Array(block.itemCount_);
for (var n = 0; n < block.itemCount_; n++) {
code[n] = Blockly.Python.valueToCode(block, 'ADD' + n,
Blockly.Python.ORDER_NONE) || 'None';
}
code = '[' + code.join(', ') + ']';
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['lists_repeat'] = function(block) {
// Create a list with one element repeated.
var argument0 = Blockly.Python.valueToCode(block, 'ITEM',
Blockly.Python.ORDER_NONE) || 'None';
var argument1 = Blockly.Python.valueToCode(block, 'NUM',
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
var code = '[' + argument0 + '] * ' + argument1;
return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
};
Blockly.Python['lists_length'] = function(block) {
// List length.
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '[]';
return ['len(' + argument0 + ')', Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['lists_isEmpty'] = function(block) {
// Is the list empty?
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '[]';
var code = 'not len(' + argument0 + ')';
return [code, Blockly.Python.ORDER_LOGICAL_NOT];
};
Blockly.Python['lists_indexOf'] = function(block) {
// Find an item in the list.
var argument0 = Blockly.Python.valueToCode(block, 'FIND',
Blockly.Python.ORDER_NONE) || '[]';
var argument1 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var code;
if (block.getTitleValue('END') == 'FIRST') {
var functionName = Blockly.Python.provideFunction_(
'first_index',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList, elem):',
' try: theIndex = myList.index(elem) + 1',
' except: theIndex = 0',
' return theIndex']);
code = functionName + '(' + argument1 + ', ' + argument0 + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else {
var functionName = Blockly.Python.provideFunction_(
'last_index',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList, elem):',
' try: theIndex = len(myList) - myList[::-1].index(elem)',
' except: theIndex = 0',
' return theIndex']);
code = functionName + '(' + argument1 + ', ' + argument0 + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
};
Blockly.Python['lists_getIndex'] = function(block) {
// Get element at index.
// Note: Until January 2013 this block did not have MODE or WHERE inputs.
var mode = block.getTitleValue('MODE') || 'GET';
var where = block.getTitleValue('WHERE') || 'FROM_START';
var at = Blockly.Python.valueToCode(block, 'AT',
Blockly.Python.ORDER_UNARY_SIGN) || '1';
var list = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_MEMBER) || '[]';
if (where == 'FIRST') {
if (mode == 'GET') {
var code = list + '[0]';
return [code, Blockly.Python.ORDER_MEMBER];
} else {
var code = list + '.pop(0)';
if (mode == 'GET_REMOVE') {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return code + '\n';
}
}
} else if (where == 'LAST') {
if (mode == 'GET') {
var code = list + '[-1]';
return [code, Blockly.Python.ORDER_MEMBER];
} else {
var code = list + '.pop()';
if (mode == 'GET_REMOVE') {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return code + '\n';
}
}
} else if (where == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at)) {
// If the index is a naked number, decrement it right now.
at = parseInt(at, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at = 'int(' + at + ' - 1)';
}
if (mode == 'GET') {
var code = list + '[' + at + ']';
return [code, Blockly.Python.ORDER_MEMBER];
} else {
var code = list + '.pop(' + at + ')';
if (mode == 'GET_REMOVE') {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return code + '\n';
}
}
} else if (where == 'FROM_END') {
if (mode == 'GET') {
var code = list + '[-' + at + ']';
return [code, Blockly.Python.ORDER_MEMBER];
} else {
var code = list + '.pop(-' + at + ')';
if (mode == 'GET_REMOVE') {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return code + '\n';
}
}
} else if (where == 'RANDOM') {
Blockly.Python.definitions_['import_random'] = 'import random';
if (mode == 'GET') {
code = 'random.choice(' + list + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else {
var functionName = Blockly.Python.provideFunction_(
'lists_remove_random_item',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
' x = int(random.random() * len(myList))',
' return myList.pop(x)']);
code = functionName + '(' + list + ')';
if (mode == 'GET_REMOVE') {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (mode == 'REMOVE') {
return code + '\n';
}
}
}
throw 'Unhandled combination (lists_getIndex).';
};
Blockly.Python['lists_setIndex'] = function(block) {
// Set element at index.
// Note: Until February 2013 this block did not have MODE or WHERE inputs.
var list = Blockly.Python.valueToCode(block, 'LIST',
Blockly.Python.ORDER_MEMBER) || '[]';
var mode = block.getTitleValue('MODE') || 'GET';
var where = block.getTitleValue('WHERE') || 'FROM_START';
var at = Blockly.Python.valueToCode(block, 'AT',
Blockly.Python.ORDER_NONE) || '1';
var value = Blockly.Python.valueToCode(block, 'TO',
Blockly.Python.ORDER_NONE) || 'None';
// Cache non-trivial values to variables to prevent repeated look-ups.
// Closure, which accesses and modifies 'list'.
function cacheList() {
if (list.match(/^\w+$/)) {
return '';
}
var listVar = Blockly.Python.variableDB_.getDistinctName(
'tmp_list', Blockly.Variables.NAME_TYPE);
var code = listVar + ' = ' + list + '\n';
list = listVar;
return code;
}
if (where == 'FIRST') {
if (mode == 'SET') {
return list + '[0] = ' + value + '\n';
} else if (mode == 'INSERT') {
return list + '.insert(0, ' + value + ')\n';
}
} else if (where == 'LAST') {
if (mode == 'SET') {
return list + '[-1] = ' + value + '\n';
} else if (mode == 'INSERT') {
return list + '.append(' + value + ')\n';
}
} else if (where == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at)) {
// If the index is a naked number, decrement it right now.
at = parseInt(at, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at = 'int(' + at + ' - 1)';
}
if (mode == 'SET') {
return list + '[' + at + '] = ' + value + '\n';
} else if (mode == 'INSERT') {
return list + '.insert(' + at + ', ' + value + ')\n';
}
} else if (where == 'FROM_END') {
if (mode == 'SET') {
return list + '[-' + at + '] = ' + value + '\n';
} else if (mode == 'INSERT') {
return list + '.insert(-' + at + ', ' + value + ')\n';
}
} else if (where == 'RANDOM') {
Blockly.Python.definitions_['import_random'] = 'import random';
var code = cacheList();
var xVar = Blockly.Python.variableDB_.getDistinctName(
'tmp_x', Blockly.Variables.NAME_TYPE);
code += xVar + ' = int(random.random() * len(' + list + '))\n';
if (mode == 'SET') {
code += list + '[' + xVar + '] = ' + value + '\n';
return code;
} else if (mode == 'INSERT') {
code += list + '.insert(' + xVar + ', ' + value + ')\n';
return code;
}
}
throw 'Unhandled combination (lists_setIndex).';
};
Blockly.Python['lists_getSublist'] = function(block) {
// Get sublist.
var list = Blockly.Python.valueToCode(block, 'LIST',
Blockly.Python.ORDER_MEMBER) || '[]';
var where1 = block.getTitleValue('WHERE1');
var where2 = block.getTitleValue('WHERE2');
var at1 = Blockly.Python.valueToCode(block, 'AT1',
Blockly.Python.ORDER_ADDITIVE) || '1';
var at2 = Blockly.Python.valueToCode(block, 'AT2',
Blockly.Python.ORDER_ADDITIVE) || '1';
if (where1 == 'FIRST' || (where1 == 'FROM_START' && at1 == '1')) {
at1 = '';
} else if (where1 == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at1)) {
// If the index is a naked number, decrement it right now.
at1 = parseInt(at1, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at1 = 'int(' + at1 + ' - 1)';
}
} else if (where1 == 'FROM_END') {
if (Blockly.isNumber(at1)) {
at1 = -parseInt(at1, 10);
} else {
at1 = '-int(' + at1 + ')';
}
}
if (where2 == 'LAST' || (where2 == 'FROM_END' && at2 == '1')) {
at2 = '';
} else if (where1 == 'FROM_START') {
if (Blockly.isNumber(at2)) {
at2 = parseInt(at2, 10);
} else {
at2 = 'int(' + at2 + ')';
}
} else if (where1 == 'FROM_END') {
if (Blockly.isNumber(at2)) {
// If the index is a naked number, increment it right now.
// Add special case for -0.
at2 = 1 - parseInt(at2, 10);
if (at2 == 0) {
at2 = '';
}
} else {
// If the index is dynamic, increment it in code.
Blockly.Python.definitions_['import_sys'] = 'import sys';
at2 = 'int(1 - ' + at2 + ') or sys.maxsize';
}
}
var code = list + '[' + at1 + ' : ' + at2 + ']';
return [code, Blockly.Python.ORDER_MEMBER];
};

123
generators/python/logic.js Normal file
View File

@@ -0,0 +1,123 @@
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for logic blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.logic');
goog.require('Blockly.Python');
Blockly.Python['controls_if'] = function(block) {
// If/elseif/else condition.
var n = 0;
var argument = Blockly.Python.valueToCode(block, 'IF' + n,
Blockly.Python.ORDER_NONE) || 'False';
var branch = Blockly.Python.statementToCode(block, 'DO' + n) || ' pass\n';
var code = 'if ' + argument + ':\n' + branch;
for (n = 1; n <= block.elseifCount_; n++) {
argument = Blockly.Python.valueToCode(block, 'IF' + n,
Blockly.Python.ORDER_NONE) || 'False';
branch = Blockly.Python.statementToCode(block, 'DO' + n) || ' pass\n';
code += 'elif ' + argument + ':\n' + branch;
}
if (block.elseCount_) {
branch = Blockly.Python.statementToCode(block, 'ELSE') || ' pass\n';
code += 'else:\n' + branch;
}
return code;
};
Blockly.Python['logic_compare'] = function(block) {
// Comparison operator.
var OPERATORS = {
EQ: '==',
NEQ: '!=',
LT: '<',
LTE: '<=',
GT: '>',
GTE: '>='
};
var operator = OPERATORS[block.getTitleValue('OP')];
var order = Blockly.Python.ORDER_RELATIONAL;
var argument0 = Blockly.Python.valueToCode(block, 'A', order) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'B', order) || '0';
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.Python['logic_operation'] = function(block) {
// Operations 'and', 'or'.
var operator = (block.getTitleValue('OP') == 'AND') ? 'and' : 'or';
var order = (operator == 'and') ? Blockly.Python.ORDER_LOGICAL_AND :
Blockly.Python.ORDER_LOGICAL_OR;
var argument0 = Blockly.Python.valueToCode(block, 'A', order);
var argument1 = Blockly.Python.valueToCode(block, 'B', order);
if (!argument0 && !argument1) {
// If there are no arguments, then the return value is false.
argument0 = 'False';
argument1 = 'False';
} else {
// Single missing arguments have no effect on the return value.
var defaultArgument = (operator == 'and') ? 'True' : 'False';
if (!argument0) {
argument0 = defaultArgument;
}
if (!argument1) {
argument1 = defaultArgument;
}
}
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.Python['logic_negate'] = function(block) {
// Negation.
var argument0 = Blockly.Python.valueToCode(block, 'BOOL',
Blockly.Python.ORDER_LOGICAL_NOT) || 'True';
var code = 'not ' + argument0;
return [code, Blockly.Python.ORDER_LOGICAL_NOT];
};
Blockly.Python['logic_boolean'] = function(block) {
// Boolean values true and false.
var code = (block.getTitleValue('BOOL') == 'TRUE') ? 'True' : 'False';
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['logic_null'] = function(block) {
// Null data type.
return ['None', Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['logic_ternary'] = function(block) {
// Ternary operator.
var value_if = Blockly.Python.valueToCode(block, 'IF',
Blockly.Python.ORDER_CONDITIONAL) || 'False';
var value_then = Blockly.Python.valueToCode(block, 'THEN',
Blockly.Python.ORDER_CONDITIONAL) || 'None';
var value_else = Blockly.Python.valueToCode(block, 'ELSE',
Blockly.Python.ORDER_CONDITIONAL) || 'None';
var code = value_then + ' if ' + value_if + ' else ' + value_else
return [code, Blockly.Python.ORDER_CONDITIONAL];
};

227
generators/python/loops.js Normal file
View File

@@ -0,0 +1,227 @@
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for loop blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.loops');
goog.require('Blockly.Python');
Blockly.Python['controls_repeat'] = function(block) {
// Repeat n times (internal number).
var repeats = parseInt(block.getTitleValue('TIMES'), 10);
var branch = Blockly.Python.statementToCode(block, 'DO') || ' pass\n';
if (Blockly.Python.INFINITE_LOOP_TRAP) {
branch = Blockly.Python.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + block.id + '\'') + branch;
}
var loopVar = Blockly.Python.variableDB_.getDistinctName(
'count', Blockly.Variables.NAME_TYPE);
var code = 'for ' + loopVar + ' in range(' + repeats + '):\n' + branch;
return code;
};
Blockly.Python['controls_repeat_ext'] = function(block) {
// Repeat n times (external number).
var repeats = Blockly.Python.valueToCode(block, 'TIMES',
Blockly.Python.ORDER_NONE) || '0';
if (Blockly.isNumber(repeats)) {
repeats = parseInt(repeats, 10);
} else {
repeats = 'int(' + repeats + ')';
}
var branch = Blockly.Python.statementToCode(block, 'DO') || ' pass\n';
if (Blockly.Python.INFINITE_LOOP_TRAP) {
branch = Blockly.Python.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + block.id + '\'') + branch;
}
var loopVar = Blockly.Python.variableDB_.getDistinctName(
'count', Blockly.Variables.NAME_TYPE);
var code = 'for ' + loopVar + ' in range(' + repeats + '):\n' + branch;
return code;
};
Blockly.Python['controls_whileUntil'] = function(block) {
// Do while/until loop.
var until = block.getTitleValue('MODE') == 'UNTIL';
var argument0 = Blockly.Python.valueToCode(block, 'BOOL',
until ? Blockly.Python.ORDER_LOGICAL_NOT :
Blockly.Python.ORDER_NONE) || 'False';
var branch = Blockly.Python.statementToCode(block, 'DO') || ' pass\n';
if (Blockly.Python.INFINITE_LOOP_TRAP) {
branch = Blockly.Python.INFINITE_LOOP_TRAP.replace(/%1/g,
'"' + block.id + '"') + branch;
}
if (block.getTitleValue('MODE') == 'UNTIL') {
if (!argument0.match(/^\w+$/)) {
argument0 = '(' + argument0 + ')';
}
argument0 = 'not ' + argument0;
}
return 'while ' + argument0 + ':\n' + branch;
};
Blockly.Python['controls_for'] = function(block) {
// For loop.
var variable0 = Blockly.Python.variableDB_.getName(
block.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Python.valueToCode(block, 'FROM',
Blockly.Python.ORDER_NONE) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'TO',
Blockly.Python.ORDER_NONE) || '0';
var increment = Blockly.Python.valueToCode(block, 'BY',
Blockly.Python.ORDER_NONE) || '1';
var branch = Blockly.Python.statementToCode(block, 'DO') || ' pass\n';
if (Blockly.Python.INFINITE_LOOP_TRAP) {
branch = Blockly.Python.INFINITE_LOOP_TRAP.replace(/%1/g,
'"' + block.id + '"') + branch;
}
var code = '';
var range;
// Helper functions.
var defineUpRange = function() {
return Blockly.Python.provideFunction_(
'upRange',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
'(start, stop, step):',
' while start <= stop:',
' yield start',
' start += abs(step)']);
};
var defineDownRange = function() {
return Blockly.Python.provideFunction_(
'downRange',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
'(start, stop, step):',
' while start >= stop:',
' yield start',
' start -= abs(step)']);
};
// Arguments are legal Python code (numbers or strings returned by scrub()).
var generateUpDownRange = function(start, end, inc) {
return '(' + start + ' <= ' + end + ') and ' +
defineUpRange() + '(' + start + ', ' + end + ', ' + inc + ') or ' +
defineDownRange() + '(' + start + ', ' + end + ', ' + inc + ')';
};
if (Blockly.isNumber(argument0) && Blockly.isNumber(argument1) &&
Blockly.isNumber(increment)) {
// All parameters are simple numbers.
argument0 = parseFloat(argument0);
argument1 = parseFloat(argument1);
increment = Math.abs(parseFloat(increment));
if (argument0 % 1 === 0 && argument1 % 1 === 0 && increment % 1 === 0) {
// All parameters are integers.
if (argument0 <= argument1) {
// Count up.
argument1++;
if (argument0 == 0 && increment == 1) {
// If starting index is 0, omit it.
range = argument1;
} else {
range = argument0 + ', ' + argument1;
}
// If increment isn't 1, it must be explicit.
if (increment != 1) {
range += ', ' + increment;
}
} else {
// Count down.
argument1--;
range = argument0 + ', ' + argument1 + ', -' + increment;
}
range = 'range(' + range + ')';
} else {
// At least one of the parameters is not an integer.
if (argument0 < argument1) {
range = defineUpRange();
} else {
range = defineDownRange();
}
range += '(' + argument0 + ', ' + argument1 + ', ' + increment + ')';
}
} else {
// Cache non-trivial values to variables to prevent repeated look-ups.
var scrub = function(arg, suffix) {
if (Blockly.isNumber(arg)) {
// Simple number.
arg = parseFloat(arg);
} else if (arg.match(/^\w+$/)) {
// Variable.
arg = 'float(' + arg + ')';
} else {
// It's complicated.
var varName = Blockly.Python.variableDB_.getDistinctName(
variable0 + suffix, Blockly.Variables.NAME_TYPE);
code += varName + ' = float(' + arg + ')\n';
arg = varName;
}
return arg;
};
var startVar = scrub(argument0, '_start');
var endVar = scrub(argument1, '_end');
var incVar = scrub(increment, '_inc');
if (typeof startVar == 'number' && typeof endVar == 'number') {
if (startVar < endVar) {
range = defineUpRange(startVar, endVar, increment);
} else {
range = defineDownRange(startVar, endVar, increment);
}
} else {
// We cannot determine direction statically.
range = generateUpDownRange(startVar, endVar, increment);
}
}
code += 'for ' + variable0 + ' in ' + range + ':\n' + branch;
return code;
};
Blockly.Python['controls_forEach'] = function(block) {
// For each loop.
var variable0 = Blockly.Python.variableDB_.getName(
block.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Python.valueToCode(block, 'LIST',
Blockly.Python.ORDER_RELATIONAL) || '[]';
var branch = Blockly.Python.statementToCode(block, 'DO') || ' pass\n';
if (Blockly.Python.INFINITE_LOOP_TRAP) {
branch = Blockly.Python.INFINITE_LOOP_TRAP.replace(/%1/g,
'"' + block.id + '"') + branch;
}
var code = 'for ' + variable0 + ' in ' + argument0 + ':\n' + branch;
return code;
};
Blockly.Python['controls_flow_statements'] = function(block) {
// Flow statements: continue, break.
switch (block.getTitleValue('FLOW')) {
case 'BREAK':
return 'break\n';
case 'CONTINUE':
return 'continue\n';
}
throw 'Unknown flow statement.';
};

371
generators/python/math.js Normal file
View File

@@ -0,0 +1,371 @@
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for math blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.math');
goog.require('Blockly.Python');
// If any new block imports any library, add that library name here.
Blockly.Python.addReservedWords('math,random');
Blockly.Python['math_number'] = function(block) {
// Numeric value.
var code = parseFloat(block.getTitleValue('NUM'));
var order = code < 0 ? Blockly.Python.ORDER_UNARY_SIGN :
Blockly.Python.ORDER_ATOMIC;
return [code, order];
};
Blockly.Python['math_arithmetic'] = function(block) {
// Basic arithmetic operators, and power.
var OPERATORS = {
ADD: [' + ', Blockly.Python.ORDER_ADDITIVE],
MINUS: [' - ', Blockly.Python.ORDER_ADDITIVE],
MULTIPLY: [' * ', Blockly.Python.ORDER_MULTIPLICATIVE],
DIVIDE: [' / ', Blockly.Python.ORDER_MULTIPLICATIVE],
POWER: [' ** ', Blockly.Python.ORDER_EXPONENTIATION]
};
var tuple = OPERATORS[block.getTitleValue('OP')];
var operator = tuple[0];
var order = tuple[1];
var argument0 = Blockly.Python.valueToCode(block, 'A', order) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'B', order) || '0';
var code = argument0 + operator + argument1;
return [code, order];
// In case of 'DIVIDE', division between integers returns different results
// in Python 2 and 3. However, is not an issue since Blockly does not
// guarantee identical results in all languages. To do otherwise would
// require every operator to be wrapped in a function call. This would kill
// legibility of the generated code. See:
// http://code.google.com/p/blockly/wiki/Language
};
Blockly.Python['math_single'] = function(block) {
// Math operators with single operand.
var operator = block.getTitleValue('OP');
var code;
var arg;
if (operator == 'NEG') {
// Negation is a special case given its different operator precedence.
var code = Blockly.Python.valueToCode(block, 'NUM',
Blockly.Python.ORDER_UNARY_SIGN) || '0';
return ['-' + code, Blockly.Python.ORDER_UNARY_SIGN];
}
Blockly.Python.definitions_['import_math'] = 'import math';
if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') {
arg = Blockly.Python.valueToCode(block, 'NUM',
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
} else {
arg = Blockly.Python.valueToCode(block, 'NUM',
Blockly.Python.ORDER_NONE) || '0';
}
// First, handle cases which generate values that don't need parentheses
// wrapping the code.
switch (operator) {
case 'ABS':
code = 'math.fabs(' + arg + ')';
break;
case 'ROOT':
code = 'math.sqrt(' + arg + ')';
break;
case 'LN':
code = 'math.log(' + arg + ')';
break;
case 'LOG10':
code = 'math.log10(' + arg + ')';
break;
case 'EXP':
code = 'math.exp(' + arg + ')';
break;
case 'POW10':
code = 'math.pow(10,' + arg + ')';
break;
case 'ROUND':
code = 'round(' + arg + ')';
break;
case 'ROUNDUP':
code = 'math.ceil(' + arg + ')';
break;
case 'ROUNDDOWN':
code = 'math.floor(' + arg + ')';
break;
case 'SIN':
code = 'math.sin(' + arg + ' / 180.0 * math.pi)';
break;
case 'COS':
code = 'math.cos(' + arg + ' / 180.0 * math.pi)';
break;
case 'TAN':
code = 'math.tan(' + arg + ' / 180.0 * math.pi)';
break;
}
if (code) {
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
// Second, handle cases which generate values that may need parentheses
// wrapping the code.
switch (operator) {
case 'ASIN':
code = 'math.asin(' + arg + ') / math.pi * 180';
break;
case 'ACOS':
code = 'math.acos(' + arg + ') / math.pi * 180';
break;
case 'ATAN':
code = 'math.atan(' + arg + ') / math.pi * 180';
break;
default:
throw 'Unknown math operator: ' + operator;
}
return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
};
Blockly.Python['math_constant'] = function(block) {
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
var CONSTANTS = {
PI: ['math.pi', Blockly.Python.ORDER_MEMBER],
E: ['math.e', Blockly.Python.ORDER_MEMBER],
GOLDEN_RATIO: ['(1 + math.sqrt(5)) / 2', Blockly.Python.ORDER_MULTIPLICATIVE],
SQRT2: ['math.sqrt(2)', Blockly.Python.ORDER_MEMBER],
SQRT1_2: ['math.sqrt(1.0 / 2)', Blockly.Python.ORDER_MEMBER],
INFINITY: ['float(\'inf\')', Blockly.Python.ORDER_ATOMIC]
};
var constant = block.getTitleValue('CONSTANT');
if (constant != 'INFINITY') {
Blockly.Python.definitions_['import_math'] = 'import math';
}
return CONSTANTS[constant];
};
Blockly.Python['math_number_property'] = function(block) {
// Check if a number is even, odd, prime, whole, positive, or negative
// or if it is divisible by certain number. Returns true or false.
var number_to_check = Blockly.Python.valueToCode(block, 'NUMBER_TO_CHECK',
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
var dropdown_property = block.getTitleValue('PROPERTY');
var code;
if (dropdown_property == 'PRIME') {
Blockly.Python.definitions_['import_math'] = 'import math';
var functionName = Blockly.Python.provideFunction_(
'isPrime',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(n):',
' # http://en.wikipedia.org/wiki/Primality_test#Naive_methods',
' # If n is not a number but a string, try parsing it.',
' if type(n) not in (int, float, long):',
' try:',
' n = float(n)',
' except:',
' return False',
' if n == 2 or n == 3:',
' return True',
' # False if n is negative, is 1, or not whole,' +
' or if n is divisible by 2 or 3.',
' if n <= 1 or n % 1 != 0 or n % 2 == 0 or n % 3 == 0:',
' return False',
' # Check all the numbers of form 6k +/- 1, up to sqrt(n).',
' for x in range(6, int(math.sqrt(n)) + 2, 6):',
' if n % (x - 1) == 0 or n % (x + 1) == 0:',
' return False',
' return True']);
code = functionName + '(' + number_to_check + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
switch (dropdown_property) {
case 'EVEN':
code = number_to_check + ' % 2 == 0';
break;
case 'ODD':
code = number_to_check + ' % 2 == 1';
break;
case 'WHOLE':
code = number_to_check + ' % 1 == 0';
break;
case 'POSITIVE':
code = number_to_check + ' > 0';
break;
case 'NEGATIVE':
code = number_to_check + ' < 0';
break;
case 'DIVISIBLE_BY':
var divisor = Blockly.Python.valueToCode(block, 'DIVISOR',
Blockly.Python.ORDER_MULTIPLICATIVE);
// If 'divisor' is some code that evals to 0, Python will raise an error.
if (!divisor || divisor == '0') {
return ['False', Blockly.Python.ORDER_ATOMIC];
}
code = number_to_check + ' % ' + divisor + ' == 0';
break;
}
return [code, Blockly.Python.ORDER_RELATIONAL];
};
Blockly.Python['math_change'] = function(block) {
// Add to a variable in place.
var argument0 = Blockly.Python.valueToCode(block, 'DELTA',
Blockly.Python.ORDER_ADDITIVE) || '0';
var varName = Blockly.Python.variableDB_.getName(block.getTitleValue('VAR'),
Blockly.Variables.NAME_TYPE);
return varName + ' = (' + varName + ' if type(' + varName +
') in (int, float, long) else 0) + ' + argument0 + '\n';
};
// Rounding functions have a single operand.
Blockly.Python['math_round'] = Blockly.Python['math_single'];
// Trigonometry functions have a single operand.
Blockly.Python['math_trig'] = Blockly.Python['math_single'];
Blockly.Python['math_on_list'] = function(block) {
// Math functions for lists.
var func = block.getTitleValue('OP');
var list = Blockly.Python.valueToCode(block, 'LIST',
Blockly.Python.ORDER_NONE) || '[]';
var code;
switch (func) {
case 'SUM':
code = 'sum(' + list + ')';
break;
case 'MIN':
code = 'min(' + list + ')';
break;
case 'MAX':
code = 'max(' + list + ')';
break;
case 'AVERAGE':
var functionName = Blockly.Python.provideFunction_(
'math_mean',
// This operation excludes null and values that are not int or float:',
// math_mean([null, null, "aString", 1, 9]) == 5.0.',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
' localList = [e for e in myList if type(e) in (int, float, long)]',
' if not localList: return',
' return float(sum(localList)) / len(localList)']);
code = functionName + '(' + list + ')';
break;
case 'MEDIAN':
var functionName = Blockly.Python.provideFunction_(
'math_median',
// This operation excludes null values:
// math_median([null, null, 1, 3]) == 2.0.
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
' localList = sorted([e for e in myList ' +
'if type(e) in (int, float, long)])',
' if not localList: return',
' if len(localList) % 2 == 0:',
' return (localList[len(localList) / 2 - 1] + ' +
'localList[len(localList) / 2]) / 2.0',
' else:',
' return localList[(len(localList) - 1) / 2]']);
code = functionName + '(' + list + ')';
break;
case 'MODE':
var functionName = Blockly.Python.provideFunction_(
'math_modes',
// As a list of numbers can contain more than one mode,
// the returned result is provided as an array.
// Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1].
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(some_list):',
' modes = []',
' # Using a lists of [item, count] to keep count rather than dict',
' # to avoid "unhashable" errors when the counted item is ' +
'itself a list or dict.',
' counts = []',
' maxCount = 1',
' for item in some_list:',
' found = False',
' for count in counts:',
' if count[0] == item:',
' count[1] += 1',
' maxCount = max(maxCount, count[1])',
' found = True',
' if not found:',
' counts.append([item, 1])',
' for counted_item, item_count in counts:',
' if item_count == maxCount:',
' modes.append(counted_item)',
' return modes']);
code = functionName + '(' + list + ')';
break;
case 'STD_DEV':
Blockly.Python.definitions_['import_math'] = 'import math';
var functionName = Blockly.Python.provideFunction_(
'math_standard_deviation',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(numbers):',
' n = len(numbers)',
' if n == 0: return',
' mean = float(sum(numbers)) / n',
' variance = sum((x - mean) ** 2 for x in numbers) / n',
' return math.sqrt(variance)']);
code = functionName + '(' + list + ')';
break;
case 'RANDOM':
Blockly.Python.definitions_['import_random'] = 'import random';
code = 'random.choice(' + list + ')';
break;
default:
throw 'Unknown operator: ' + func;
}
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['math_modulo'] = function(block) {
// Remainder computation.
var argument0 = Blockly.Python.valueToCode(block, 'DIVIDEND',
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'DIVISOR',
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
var code = argument0 + ' % ' + argument1;
return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
};
Blockly.Python['math_constrain'] = function(block) {
// Constrain a number between two limits.
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'LOW',
Blockly.Python.ORDER_NONE) || '0';
var argument2 = Blockly.Python.valueToCode(block, 'HIGH',
Blockly.Python.ORDER_NONE) || 'float(\'inf\')';
var code = 'min(max(' + argument0 + ', ' + argument1 + '), ' +
argument2 + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['math_random_int'] = function(block) {
// Random integer between [X] and [Y].
Blockly.Python.definitions_['import_random'] = 'import random';
var argument0 = Blockly.Python.valueToCode(block, 'FROM',
Blockly.Python.ORDER_NONE) || '0';
var argument1 = Blockly.Python.valueToCode(block, 'TO',
Blockly.Python.ORDER_NONE) || '0';
var code = 'random.randint(' + argument0 + ', ' + argument1 + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['math_random_float'] = function(block) {
// Random fraction between 0 and 1.
Blockly.Python.definitions_['import_random'] = 'import random';
return ['random.random()', Blockly.Python.ORDER_FUNCTION_CALL];
};

View File

@@ -0,0 +1,117 @@
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for procedure blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Python.procedures');
goog.require('Blockly.Python');
Blockly.Python['procedures_defreturn'] = function(block) {
// Define a procedure with a return value.
// First, add a 'global' statement for every variable that is assigned.
var globals = Blockly.Variables.allVariables(block);
for (var i = globals.length - 1; i >= 0; i--) {
var varName = globals[i];
if (block.arguments_.indexOf(varName) == -1) {
globals[i] = Blockly.Python.variableDB_.getName(varName,
Blockly.Variables.NAME_TYPE);
} else {
// This variable is actually a parameter name. Do not include it in
// the list of globals, thus allowing it be of local scope.
globals.splice(i, 1);
}
}
globals = globals.length ? ' global ' + globals.join(', ') + '\n' : '';
var funcName = Blockly.Python.variableDB_.getName(block.getTitleValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var branch = Blockly.Python.statementToCode(block, 'STACK');
if (Blockly.Python.INFINITE_LOOP_TRAP) {
branch = Blockly.Python.INFINITE_LOOP_TRAP.replace(/%1/g,
'"' + block.id + '"') + branch;
}
var returnValue = Blockly.Python.valueToCode(block, 'RETURN',
Blockly.Python.ORDER_NONE) || '';
if (returnValue) {
returnValue = ' return ' + returnValue + '\n';
} else if (!branch) {
branch = ' pass';
}
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.Python.variableDB_.getName(block.arguments_[x],
Blockly.Variables.NAME_TYPE);
}
var code = 'def ' + funcName + '(' + args.join(', ') + '):\n' +
globals + branch + returnValue;
code = Blockly.Python.scrub_(block, code);
Blockly.Python.definitions_[funcName] = code;
return null;
};
// Defining a procedure without a return value uses the same generator as
// a procedure with a return value.
Blockly.Python['procedures_defnoreturn'] =
Blockly.Python['procedures_defreturn'];
Blockly.Python['procedures_callreturn'] = function(block) {
// Call a procedure with a return value.
var funcName = Blockly.Python.variableDB_.getName(block.getTitleValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.Python.valueToCode(block, 'ARG' + x,
Blockly.Python.ORDER_NONE) || 'None';
}
var code = funcName + '(' + args.join(', ') + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['procedures_callnoreturn'] = function(block) {
// Call a procedure with no return value.
var funcName = Blockly.Python.variableDB_.getName(block.getTitleValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < block.arguments_.length; x++) {
args[x] = Blockly.Python.valueToCode(block, 'ARG' + x,
Blockly.Python.ORDER_NONE) || 'None';
}
var code = funcName + '(' + args.join(', ') + ')\n';
return code;
};
Blockly.Python['procedures_ifreturn'] = function(block) {
// Conditionally return value from a procedure.
var condition = Blockly.Python.valueToCode(block, 'CONDITION',
Blockly.Python.ORDER_NONE) || 'False';
var code = 'if ' + condition + ':\n';
if (block.hasReturnValue_) {
var value = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || 'None';
code += ' return ' + value + '\n';
} else {
code += ' return\n';
}
return code;
};

252
generators/python/text.js Normal file
View File

@@ -0,0 +1,252 @@
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for text blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.text');
goog.require('Blockly.Python');
Blockly.Python['text'] = function(block) {
// Text value.
var code = Blockly.Python.quote_(block.getTitleValue('TEXT'));
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['text_join'] = function(block) {
// Create a string made up of any number of elements of any type.
//Should we allow joining by '-' or ',' or any other characters?
var code;
if (block.itemCount_ == 0) {
return ['\'\'', Blockly.Python.ORDER_ATOMIC];
} else if (block.itemCount_ == 1) {
var argument0 = Blockly.Python.valueToCode(block, 'ADD0',
Blockly.Python.ORDER_NONE) || '\'\'';
code = 'str(' + argument0 + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
} else if (block.itemCount_ == 2) {
var argument0 = Blockly.Python.valueToCode(block, 'ADD0',
Blockly.Python.ORDER_NONE) || '\'\'';
var argument1 = Blockly.Python.valueToCode(block, 'ADD1',
Blockly.Python.ORDER_NONE) || '\'\'';
var code = 'str(' + argument0 + ') + str(' + argument1 + ')';
return [code, Blockly.Python.ORDER_UNARY_SIGN];
} else {
var code = [];
for (var n = 0; n < block.itemCount_; n++) {
code[n] = Blockly.Python.valueToCode(block, 'ADD' + n,
Blockly.Python.ORDER_NONE) || '\'\'';
}
var tempVar = Blockly.Python.variableDB_.getDistinctName('temp_value',
Blockly.Variables.NAME_TYPE);
code = '\'\'.join([str(' + tempVar + ') for ' + tempVar + ' in [' +
code.join(', ') + ']])';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
};
Blockly.Python['text_append'] = function(block) {
// Append to a variable in place.
var varName = Blockly.Python.variableDB_.getName(block.getTitleValue('VAR'),
Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_NONE) || '\'\'';
return varName + ' = str(' + varName + ') + str(' + argument0 + ')\n';
};
Blockly.Python['text_length'] = function(block) {
// String length.
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '\'\'';
return ['len(' + argument0 + ')', Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['text_isEmpty'] = function(block) {
// Is the string null?
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '\'\'';
var code = 'not len(' + argument0 + ')';
return [code, Blockly.Python.ORDER_LOGICAL_NOT];
};
Blockly.Python['text_indexOf'] = function(block) {
// Search the text for a substring.
// Should we allow for non-case sensitive???
var operator = block.getTitleValue('END') == 'FIRST' ? 'find' : 'rfind';
var argument0 = Blockly.Python.valueToCode(block, 'FIND',
Blockly.Python.ORDER_NONE) || '\'\'';
var argument1 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var code = argument1 + '.' + operator + '(' + argument0 + ') + 1';
return [code, Blockly.Python.ORDER_MEMBER];
};
Blockly.Python['text_charAt'] = function(block) {
// Get letter at index.
// Note: Until January 2013 this block did not have the WHERE input.
var where = block.getTitleValue('WHERE') || 'FROM_START';
var at = Blockly.Python.valueToCode(block, 'AT',
Blockly.Python.ORDER_UNARY_SIGN) || '1';
var text = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_MEMBER) || '\'\'';
switch (where) {
case 'FIRST':
var code = text + '[0]';
return [code, Blockly.Python.ORDER_MEMBER];
case 'LAST':
var code = text + '[-1]';
return [code, Blockly.Python.ORDER_MEMBER];
case 'FROM_START':
// Blockly uses one-based indicies.
if (Blockly.isNumber(at)) {
// If the index is a naked number, decrement it right now.
at = parseInt(at, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at = 'int(' + at + ' - 1)';
}
var code = text + '[' + at + ']';
return [code, Blockly.Python.ORDER_MEMBER];
case 'FROM_END':
var code = text + '[-' + at + ']';
return [code, Blockly.Python.ORDER_MEMBER];
case 'RANDOM':
Blockly.Python.definitions_['import_random'] = 'import random';
var functionName = Blockly.Python.provideFunction_(
'text_random_letter',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(text):',
' x = int(random.random() * len(text))',
' return text[x];']);
code = functionName + '(' + text + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
throw 'Unhandled option (text_charAt).';
};
Blockly.Python['text_getSubstring'] = function(block) {
// Get substring.
var text = Blockly.Python.valueToCode(block, 'STRING',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var where1 = block.getTitleValue('WHERE1');
var where2 = block.getTitleValue('WHERE2');
var at1 = Blockly.Python.valueToCode(block, 'AT1',
Blockly.Python.ORDER_ADDITIVE) || '1';
var at2 = Blockly.Python.valueToCode(block, 'AT2',
Blockly.Python.ORDER_ADDITIVE) || '1';
if (where1 == 'FIRST' || (where1 == 'FROM_START' && at1 == '1')) {
at1 = '';
} else if (where1 == 'FROM_START') {
// Blockly uses one-based indicies.
if (Blockly.isNumber(at1)) {
// If the index is a naked number, decrement it right now.
at1 = parseInt(at1, 10) - 1;
} else {
// If the index is dynamic, decrement it in code.
at1 = 'int(' + at1 + ' - 1)';
}
} else if (where1 == 'FROM_END') {
if (Blockly.isNumber(at1)) {
at1 = -parseInt(at1, 10);
} else {
at1 = '-int(' + at1 + ')';
}
}
if (where2 == 'LAST' || (where2 == 'FROM_END' && at2 == '1')) {
at2 = '';
} else if (where1 == 'FROM_START') {
if (Blockly.isNumber(at2)) {
at2 = parseInt(at2, 10);
} else {
at2 = 'int(' + at2 + ')';
}
} else if (where1 == 'FROM_END') {
if (Blockly.isNumber(at2)) {
// If the index is a naked number, increment it right now.
at2 = 1 - parseInt(at2, 10);
if (at2 == 0) {
at2 = '';
}
} else {
// If the index is dynamic, increment it in code.
// Add special case for -0.
Blockly.Python.definitions_['import_sys'] = 'import sys';
at2 = 'int(1 - ' + at2 + ') or sys.maxsize';
}
}
var code = text + '[' + at1 + ' : ' + at2 + ']';
return [code, Blockly.Python.ORDER_MEMBER];
};
Blockly.Python['text_changeCase'] = function(block) {
// Change capitalization.
var OPERATORS = {
UPPERCASE: '.upper()',
LOWERCASE: '.lower()',
TITLECASE: '.title()'
};
var operator = OPERATORS[block.getTitleValue('CASE')];
var argument0 = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var code = argument0 + operator;
return [code, Blockly.Python.ORDER_MEMBER];
};
Blockly.Python['text_trim'] = function(block) {
// Trim spaces.
var OPERATORS = {
LEFT: '.lstrip()',
RIGHT: '.rstrip()',
BOTH: '.strip()'
};
var operator = OPERATORS[block.getTitleValue('MODE')];
var argument0 = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_MEMBER) || '\'\'';
var code = argument0 + operator;
return [code, Blockly.Python.ORDER_MEMBER];
};
Blockly.Python['text_print'] = function(block) {
// Print statement.
var argument0 = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_NONE) || '\'\'';
return 'print(' + argument0 + ')\n';
};
Blockly.Python['text_prompt'] = function(block) {
// Prompt function.
var functionName = Blockly.Python.provideFunction_(
'text_prompt',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(msg):',
' try:',
' return raw_input(msg)',
' except NameError:',
' return input(msg)']);
var msg = Blockly.Python.quote_(block.getTitleValue('TEXT'));
var code = functionName + '(' + msg + ')';
var toNumber = block.getTitleValue('TYPE') == 'NUMBER';
if (toNumber) {
code = 'float(' + code + ')';
}
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};

View File

@@ -0,0 +1,45 @@
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Python for variable blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Python.variables');
goog.require('Blockly.Python');
Blockly.Python['variables_get'] = function(block) {
// Variable getter.
var code = Blockly.Python.variableDB_.getName(block.getTitleValue('VAR'),
Blockly.Variables.NAME_TYPE);
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['variables_set'] = function(block) {
// Variable setter.
var argument0 = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '0';
var varName = Blockly.Python.variableDB_.getName(block.getTitleValue('VAR'),
Blockly.Variables.NAME_TYPE);
return varName + ' = ' + argument0 + '\n';
};