mirror of
https://github.com/google/blockly.git
synced 2026-01-05 08:00:09 +01:00
New initial commit with .svn directories and their contents ignored.
This commit is contained in:
214
generators/javascript.js
Normal file
214
generators/javascript.js
Normal file
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* 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 Helper functions for generating JavaScript for blocks.
|
||||
* @author fraser@google.com (Neil Fraser)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.JavaScript');
|
||||
|
||||
goog.require('Blockly.Generator');
|
||||
|
||||
|
||||
Blockly.JavaScript = new Blockly.Generator('JavaScript');
|
||||
|
||||
/**
|
||||
* List of illegal variable names.
|
||||
* This is not intended to be a security feature. Blockly is 100% client-side,
|
||||
* so bypassing this list is trivial. This is intended to prevent users from
|
||||
* accidentally clobbering a built-in object or function.
|
||||
* @private
|
||||
*/
|
||||
Blockly.JavaScript.addReservedWords(
|
||||
'Blockly,' + // In case JS is evaled in the current window.
|
||||
// https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words
|
||||
'break,case,catch,continue,debugger,default,delete,do,else,finally,for,function,if,in,instanceof,new,return,switch,this,throw,try,typeof,var,void,while,with,' +
|
||||
'class,enum,export,extends,import,super,implements,interface,let,package,private,protected,public,static,yield,' +
|
||||
'const,null,true,false,' +
|
||||
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects
|
||||
'Array,ArrayBuffer,Boolean,Date,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Error,eval,EvalError,Float32Array,Float64Array,Function,Infinity,Int16Array,Int32Array,Int8Array,isFinite,isNaN,Iterator,JSON,Math,NaN,Number,Object,parseFloat,parseInt,RangeError,ReferenceError,RegExp,StopIteration,String,SyntaxError,TypeError,Uint16Array,Uint32Array,Uint8Array,Uint8ClampedArray,undefined,uneval,URIError,' +
|
||||
// https://developer.mozilla.org/en/DOM/window
|
||||
'applicationCache,closed,Components,content,_content,controllers,crypto,defaultStatus,dialogArguments,directories,document,frameElement,frames,fullScreen,globalStorage,history,innerHeight,innerWidth,length,location,locationbar,localStorage,menubar,messageManager,mozAnimationStartTime,mozInnerScreenX,mozInnerScreenY,mozPaintCount,name,navigator,opener,outerHeight,outerWidth,pageXOffset,pageYOffset,parent,performance,personalbar,pkcs11,returnValue,screen,screenX,screenY,scrollbars,scrollMaxX,scrollMaxY,scrollX,scrollY,self,sessionStorage,sidebar,status,statusbar,toolbar,top,URL,window,' +
|
||||
'addEventListener,alert,atob,back,blur,btoa,captureEvents,clearImmediate,clearInterval,clearTimeout,close,confirm,disableExternalCapture,dispatchEvent,dump,enableExternalCapture,escape,find,focus,forward,GeckoActiveXObject,getAttention,getAttentionWithCycleCount,getComputedStyle,getSelection,home,matchMedia,maximize,minimize,moveBy,moveTo,mozRequestAnimationFrame,open,openDialog,postMessage,print,prompt,QueryInterface,releaseEvents,removeEventListener,resizeBy,resizeTo,restore,routeEvent,scroll,scrollBy,scrollByLines,scrollByPages,scrollTo,setCursor,setImmediate,setInterval,setResizable,setTimeout,showModalDialog,sizeToContent,stop,unescape,updateCommands,XPCNativeWrapper,XPCSafeJSObjectWrapper,' +
|
||||
'onabort,onbeforeunload,onblur,onchange,onclick,onclose,oncontextmenu,ondevicemotion,ondeviceorientation,ondragdrop,onerror,onfocus,onhashchange,onkeydown,onkeypress,onkeyup,onload,onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmozbeforepaint,onpaint,onpopstate,onreset,onresize,onscroll,onselect,onsubmit,onunload,onpageshow,onpagehide,' +
|
||||
'Image,Option,Worker,' +
|
||||
// https://developer.mozilla.org/en/Gecko_DOM_Reference
|
||||
'Event,Range,File,FileReader,Blob,BlobBuilder,' +
|
||||
'Attr,CDATASection,CharacterData,Comment,console,DocumentFragment,DocumentType,DomConfiguration,DOMError,DOMErrorHandler,DOMException,DOMImplementation,DOMImplementationList,DOMImplementationRegistry,DOMImplementationSource,DOMLocator,DOMObject,DOMString,DOMStringList,DOMTimeStamp,DOMUserData,Entity,EntityReference,MediaQueryList,MediaQueryListListener,NameList,NamedNodeMap,Node,NodeFilter,NodeIterator,NodeList,Notation,Plugin,PluginArray,ProcessingInstruction,SharedWorker,Text,TimeRanges,Treewalker,TypeInfo,UserDataHandler,Worker,WorkerGlobalScope,' +
|
||||
'HTMLDocument,HTMLElement,HTMLAnchorElement,HTMLAppletElement,HTMLAudioElement,HTMLAreaElement,HTMLBaseElement,HTMLBaseFontElement,HTMLBodyElement,HTMLBRElement,HTMLButtonElement,HTMLCanvasElement,HTMLDirectoryElement,HTMLDivElement,HTMLDListElement,HTMLEmbedElement,HTMLFieldSetElement,HTMLFontElement,HTMLFormElement,HTMLFrameElement,HTMLFrameSetElement,HTMLHeadElement,HTMLHeadingElement,HTMLHtmlElement,HTMLHRElement,HTMLIFrameElement,HTMLImageElement,HTMLInputElement,HTMLKeygenElement,HTMLLabelElement,HTMLLIElement,HTMLLinkElement,HTMLMapElement,HTMLMenuElement,HTMLMetaElement,HTMLModElement,HTMLObjectElement,HTMLOListElement,HTMLOptGroupElement,HTMLOptionElement,HTMLOutputElement,HTMLParagraphElement,HTMLParamElement,HTMLPreElement,HTMLQuoteElement,HTMLScriptElement,HTMLSelectElement,HTMLSourceElement,HTMLSpanElement,HTMLStyleElement,HTMLTableElement,HTMLTableCaptionElement,HTMLTableCellElement,HTMLTableDataCellElement,HTMLTableHeaderCellElement,HTMLTableColElement,HTMLTableRowElement,HTMLTableSectionElement,HTMLTextAreaElement,HTMLTimeElement,HTMLTitleElement,HTMLTrackElement,HTMLUListElement,HTMLUnknownElement,HTMLVideoElement,' +
|
||||
'HTMLCanvasElement,CanvasRenderingContext2D,CanvasGradient,CanvasPattern,TextMetrics,ImageData,CanvasPixelArray,HTMLAudioElement,HTMLVideoElement,NotifyAudioAvailableEvent,HTMLCollection,HTMLAllCollection,HTMLFormControlsCollection,HTMLOptionsCollection,HTMLPropertiesCollection,DOMTokenList,DOMSettableTokenList,DOMStringMap,RadioNodeList,' +
|
||||
'SVGDocument,SVGElement,SVGAElement,SVGAltGlyphElement,SVGAltGlyphDefElement,SVGAltGlyphItemElement,SVGAnimationElement,SVGAnimateElement,SVGAnimateColorElement,SVGAnimateMotionElement,SVGAnimateTransformElement,SVGSetElement,SVGCircleElement,SVGClipPathElement,SVGColorProfileElement,SVGCursorElement,SVGDefsElement,SVGDescElement,SVGEllipseElement,SVGFilterElement,SVGFilterPrimitiveStandardAttributes,SVGFEBlendElement,SVGFEColorMatrixElement,SVGFEComponentTransferElement,SVGFECompositeElement,SVGFEConvolveMatrixElement,SVGFEDiffuseLightingElement,SVGFEDisplacementMapElement,SVGFEDistantLightElement,SVGFEFloodElement,SVGFEGaussianBlurElement,SVGFEImageElement,SVGFEMergeElement,SVGFEMergeNodeElement,SVGFEMorphologyElement,SVGFEOffsetElement,SVGFEPointLightElement,SVGFESpecularLightingElement,SVGFESpotLightElement,SVGFETileElement,SVGFETurbulenceElement,SVGComponentTransferFunctionElement,SVGFEFuncRElement,SVGFEFuncGElement,SVGFEFuncBElement,SVGFEFuncAElement,SVGFontElement,SVGFontFaceElement,SVGFontFaceFormatElement,SVGFontFaceNameElement,SVGFontFaceSrcElement,SVGFontFaceUriElement,SVGForeignObjectElement,SVGGElement,SVGGlyphElement,SVGGlyphRefElement,SVGGradientElement,SVGLinearGradientElement,SVGRadialGradientElement,SVGHKernElement,SVGImageElement,SVGLineElement,SVGMarkerElement,SVGMaskElement,SVGMetadataElement,SVGMissingGlyphElement,SVGMPathElement,SVGPathElement,SVGPatternElement,SVGPolylineElement,SVGPolygonElement,SVGRectElement,SVGScriptElement,SVGStopElement,SVGStyleElement,SVGSVGElement,SVGSwitchElement,SVGSymbolElement,SVGTextElement,SVGTextPathElement,SVGTitleElement,SVGTRefElement,SVGTSpanElement,SVGUseElement,SVGViewElement,SVGVKernElement,' +
|
||||
'SVGAngle,SVGColor,SVGICCColor,SVGElementInstance,SVGElementInstanceList,SVGLength,SVGLengthList,SVGMatrix,SVGNumber,SVGNumberList,SVGPaint,SVGPoint,SVGPointList,SVGPreserveAspectRatio,SVGRect,SVGStringList,SVGTransform,SVGTransformList,' +
|
||||
'SVGAnimatedAngle,SVGAnimatedBoolean,SVGAnimatedEnumeration,SVGAnimatedInteger,SVGAnimatedLength,SVGAnimatedLengthList,SVGAnimatedNumber,SVGAnimatedNumberList,SVGAnimatedPreserveAspectRatio,SVGAnimatedRect,SVGAnimatedString,SVGAnimatedTransformList,' +
|
||||
'SVGPathSegList,SVGPathSeg,SVGPathSegArcAbs,SVGPathSegArcRel,SVGPathSegClosePath,SVGPathSegCurvetoCubicAbs,SVGPathSegCurvetoCubicRel,SVGPathSegCurvetoCubicSmoothAbs,SVGPathSegCurvetoCubicSmoothRel,SVGPathSegCurvetoQuadraticAbs,SVGPathSegCurvetoQuadraticRel,SVGPathSegCurvetoQuadraticSmoothAbs,SVGPathSegCurvetoQuadraticSmoothRel,SVGPathSegLinetoAbs,SVGPathSegLinetoHorizontalAbs,SVGPathSegLinetoHorizontalRel,SVGPathSegLinetoRel,SVGPathSegLinetoVerticalAbs,SVGPathSegLinetoVerticalRel,SVGPathSegMovetoAbs,SVGPathSegMovetoRel,ElementTimeControl,TimeEvent,SVGAnimatedPathData,' +
|
||||
'SVGAnimatedPoints,SVGColorProfileRule,SVGCSSRule,SVGExternalResourcesRequired,SVGFitToViewBox,SVGLangSpace,SVGLocatable,SVGRenderingIntent,SVGStylable,SVGTests,SVGTextContentElement,SVGTextPositioningElement,SVGTransformable,SVGUnitTypes,SVGURIReference,SVGViewSpec,SVGZoomAndPan');
|
||||
|
||||
/**
|
||||
* Order of operation ENUMs.
|
||||
* https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence
|
||||
*/
|
||||
Blockly.JavaScript.ORDER_ATOMIC = 0; // 0 "" ...
|
||||
Blockly.JavaScript.ORDER_MEMBER = 1; // . []
|
||||
Blockly.JavaScript.ORDER_NEW = 1; // new
|
||||
Blockly.JavaScript.ORDER_FUNCTION_CALL = 2; // ()
|
||||
Blockly.JavaScript.ORDER_INCREMENT = 3; // ++
|
||||
Blockly.JavaScript.ORDER_DECREMENT = 3; // --
|
||||
Blockly.JavaScript.ORDER_LOGICAL_NOT = 4; // !
|
||||
Blockly.JavaScript.ORDER_BITWISE_NOT = 4; // ~
|
||||
Blockly.JavaScript.ORDER_UNARY_PLUS = 4; // +
|
||||
Blockly.JavaScript.ORDER_UNARY_NEGATION = 4; // -
|
||||
Blockly.JavaScript.ORDER_TYPEOF = 4; // typeof
|
||||
Blockly.JavaScript.ORDER_VOID = 4; // void
|
||||
Blockly.JavaScript.ORDER_DELETE = 4; // delete
|
||||
Blockly.JavaScript.ORDER_MULTIPLICATION = 5; // *
|
||||
Blockly.JavaScript.ORDER_DIVISION = 5; // /
|
||||
Blockly.JavaScript.ORDER_MODULUS = 5; // %
|
||||
Blockly.JavaScript.ORDER_ADDITION = 6; // +
|
||||
Blockly.JavaScript.ORDER_SUBTRACTION = 6; // -
|
||||
Blockly.JavaScript.ORDER_BITWISE_SHIFT = 7; // << >> >>>
|
||||
Blockly.JavaScript.ORDER_RELATIONAL = 8; // < <= > >=
|
||||
Blockly.JavaScript.ORDER_IN = 8; // in
|
||||
Blockly.JavaScript.ORDER_INSTANCEOF = 8; // instanceof
|
||||
Blockly.JavaScript.ORDER_EQUALITY = 9; // == != === !==
|
||||
Blockly.JavaScript.ORDER_BITWISE_AND = 10; // &
|
||||
Blockly.JavaScript.ORDER_BITWISE_XOR = 11; // ^
|
||||
Blockly.JavaScript.ORDER_BITWISE_OR = 12; // |
|
||||
Blockly.JavaScript.ORDER_LOGICAL_AND = 13; // &&
|
||||
Blockly.JavaScript.ORDER_LOGICAL_OR = 14; // ||
|
||||
Blockly.JavaScript.ORDER_CONDITIONAL = 15; // ?:
|
||||
Blockly.JavaScript.ORDER_ASSIGNMENT = 16; // = += -= *= /= %= <<= >>= ...
|
||||
Blockly.JavaScript.ORDER_COMMA = 17; // ,
|
||||
Blockly.JavaScript.ORDER_NONE = 99; // (...)
|
||||
|
||||
/**
|
||||
* Arbitrary code to inject into locations that risk causing infinite loops.
|
||||
* Any instances of '%1' will be replaced by the block ID that failed.
|
||||
* E.g. ' checkTimeout(%1);\n'
|
||||
* @type ?string
|
||||
*/
|
||||
Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
|
||||
|
||||
/**
|
||||
* Initialise the database of variable names.
|
||||
*/
|
||||
Blockly.JavaScript.init = function() {
|
||||
// Create a dictionary of definitions to be printed before the code.
|
||||
Blockly.JavaScript.definitions_ = Object.create(null);
|
||||
|
||||
if (Blockly.Variables) {
|
||||
if (!Blockly.JavaScript.variableDB_) {
|
||||
Blockly.JavaScript.variableDB_ =
|
||||
new Blockly.Names(Blockly.JavaScript.RESERVED_WORDS_);
|
||||
} else {
|
||||
Blockly.JavaScript.variableDB_.reset();
|
||||
}
|
||||
|
||||
var defvars = [];
|
||||
var variables = Blockly.Variables.allVariables();
|
||||
for (var x = 0; x < variables.length; x++) {
|
||||
defvars[x] = 'var ' +
|
||||
Blockly.JavaScript.variableDB_.getName(variables[x],
|
||||
Blockly.Variables.NAME_TYPE) + ';';
|
||||
}
|
||||
Blockly.JavaScript.definitions_['variables'] = defvars.join('\n');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Prepend the generated code with the variable definitions.
|
||||
* @param {string} code Generated code.
|
||||
* @return {string} Completed code.
|
||||
*/
|
||||
Blockly.JavaScript.finish = function(code) {
|
||||
// Convert the definitions dictionary into a list.
|
||||
var definitions = [];
|
||||
for (var name in Blockly.JavaScript.definitions_) {
|
||||
definitions.push(Blockly.JavaScript.definitions_[name]);
|
||||
}
|
||||
return definitions.join('\n\n') + '\n\n\n' + code;
|
||||
};
|
||||
|
||||
/**
|
||||
* Naked values are top-level blocks with outputs that aren't plugged into
|
||||
* anything. A trailing semicolon is needed to make this legal.
|
||||
* @param {string} line Line of generated code.
|
||||
* @return {string} Legal line of code.
|
||||
*/
|
||||
Blockly.JavaScript.scrubNakedValue = function(line) {
|
||||
return line + ';\n';
|
||||
};
|
||||
|
||||
/**
|
||||
* Encode a string as a properly escaped JavaScript string, complete with
|
||||
* quotes.
|
||||
* @param {string} string Text to encode.
|
||||
* @return {string} JavaScript string.
|
||||
* @private
|
||||
*/
|
||||
Blockly.JavaScript.quote_ = function(string) {
|
||||
// TODO: This is a quick hack. Replace with goog.string.quote
|
||||
string = string.replace(/\\/g, '\\\\')
|
||||
.replace(/\n/g, '\\\n')
|
||||
.replace(/'/g, '\\\'');
|
||||
return '\'' + string + '\'';
|
||||
};
|
||||
|
||||
/**
|
||||
* Common tasks for generating JavaScript from blocks.
|
||||
* Handles comments for the specified block and any connected value blocks.
|
||||
* Calls any statements following this block.
|
||||
* @param {!Blockly.Block} block The current block.
|
||||
* @param {string} code The JavaScript code created for this block.
|
||||
* @return {string} JavaScript code with comments and subsequent blocks added.
|
||||
* @this {Blockly.CodeGenerator}
|
||||
* @private
|
||||
*/
|
||||
Blockly.JavaScript.scrub_ = function(block, code) {
|
||||
if (code === null) {
|
||||
// Block has handled code generation itself.
|
||||
return '';
|
||||
}
|
||||
var commentCode = '';
|
||||
// Only collect comments for blocks that aren't inline.
|
||||
if (!block.outputConnection || !block.outputConnection.targetConnection) {
|
||||
// Collect comment for this block.
|
||||
var comment = block.getCommentText();
|
||||
if (comment) {
|
||||
commentCode += this.prefixLines(comment, '// ') + '\n';
|
||||
}
|
||||
// Collect comments for all value arguments.
|
||||
// Don't collect comments for nested statements.
|
||||
for (var x = 0; x < block.inputList.length; x++) {
|
||||
if (block.inputList[x].type == Blockly.INPUT_VALUE) {
|
||||
var childBlock = block.inputList[x].connection.targetBlock();
|
||||
if (childBlock) {
|
||||
var comment = this.allNestedComments(childBlock);
|
||||
if (comment) {
|
||||
commentCode += this.prefixLines(comment, '// ');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
|
||||
var nextCode = this.blockToCode(nextBlock);
|
||||
return commentCode + code + nextCode;
|
||||
};
|
||||
119
generators/javascript/colour.js
Normal file
119
generators/javascript/colour.js
Normal file
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* 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 JavaScript for colour blocks.
|
||||
* @author fraser@google.com (Neil Fraser)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.JavaScript.colour');
|
||||
|
||||
goog.require('Blockly.JavaScript');
|
||||
|
||||
|
||||
Blockly.JavaScript['colour_picker'] = function(block) {
|
||||
// Colour picker.
|
||||
var code = '\'' + block.getTitleValue('COLOUR') + '\'';
|
||||
return [code, Blockly.JavaScript.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['colour_random'] = function(block) {
|
||||
// Generate a random colour.
|
||||
if (!Blockly.JavaScript.definitions_['colour_random']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'colour_random', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.colour_random.functionName = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '() {');
|
||||
func.push(' var num = Math.floor(Math.random() * Math.pow(2, 24));');
|
||||
func.push(' return \'#\' + (\'00000\' + num.toString(16)).substr(-6);');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['colour_random'] = func.join('\n');
|
||||
}
|
||||
var code = Blockly.JavaScript.colour_random.functionName + '()';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['colour_rgb'] = function(block) {
|
||||
// Compose a colour from RGB components expressed as percentages.
|
||||
var red = Blockly.JavaScript.valueToCode(block, 'RED',
|
||||
Blockly.JavaScript.ORDER_COMMA) || 0;
|
||||
var green = Blockly.JavaScript.valueToCode(block, 'GREEN',
|
||||
Blockly.JavaScript.ORDER_COMMA) || 0;
|
||||
var blue = Blockly.JavaScript.valueToCode(block, 'BLUE',
|
||||
Blockly.JavaScript.ORDER_COMMA) || 0;
|
||||
|
||||
if (!Blockly.JavaScript.definitions_['colour_rgb']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'colour_rgb', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.colour_rgb.functionName = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(r, g, b) {');
|
||||
func.push(' r = Math.max(Math.min(Number(r), 100), 0) * 2.55;');
|
||||
func.push(' g = Math.max(Math.min(Number(g), 100), 0) * 2.55;');
|
||||
func.push(' b = Math.max(Math.min(Number(b), 100), 0) * 2.55;');
|
||||
func.push(' r = (\'0\' + (Math.round(r) || 0).toString(16)).slice(-2);');
|
||||
func.push(' g = (\'0\' + (Math.round(g) || 0).toString(16)).slice(-2);');
|
||||
func.push(' b = (\'0\' + (Math.round(b) || 0).toString(16)).slice(-2);');
|
||||
func.push(' return \'#\' + r + g + b;');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['colour_rgb'] = func.join('\n');
|
||||
}
|
||||
var code = Blockly.JavaScript.colour_rgb.functionName +
|
||||
'(' + red + ', ' + green + ', ' + blue + ')';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['colour_blend'] = function(block) {
|
||||
// Blend two colours together.
|
||||
var c1 = Blockly.JavaScript.valueToCode(block, 'COLOUR1',
|
||||
Blockly.JavaScript.ORDER_COMMA) || '\'#000000\'';
|
||||
var c2 = Blockly.JavaScript.valueToCode(block, 'COLOUR2',
|
||||
Blockly.JavaScript.ORDER_COMMA) || '\'#000000\'';
|
||||
var ratio = Blockly.JavaScript.valueToCode(block, 'RATIO',
|
||||
Blockly.JavaScript.ORDER_COMMA) || 0.5;
|
||||
|
||||
if (!Blockly.JavaScript.definitions_['colour_blend']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'colour_blend', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.colour_blend.functionName = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(c1, c2, ratio) {');
|
||||
func.push(' ratio = Math.max(Math.min(Number(ratio), 1), 0);');
|
||||
func.push(' var r1 = parseInt(c1.substring(1, 3), 16);');
|
||||
func.push(' var g1 = parseInt(c1.substring(3, 5), 16);');
|
||||
func.push(' var b1 = parseInt(c1.substring(5, 7), 16);');
|
||||
func.push(' var r2 = parseInt(c2.substring(1, 3), 16);');
|
||||
func.push(' var g2 = parseInt(c2.substring(3, 5), 16);');
|
||||
func.push(' var b2 = parseInt(c2.substring(5, 7), 16);');
|
||||
func.push(' var r = Math.round(r1 * (1 - ratio) + r2 * ratio);');
|
||||
func.push(' var g = Math.round(g1 * (1 - ratio) + g2 * ratio);');
|
||||
func.push(' var b = Math.round(b1 * (1 - ratio) + b2 * ratio);');
|
||||
func.push(' r = (\'0\' + (r || 0).toString(16)).slice(-2);');
|
||||
func.push(' g = (\'0\' + (g || 0).toString(16)).slice(-2);');
|
||||
func.push(' b = (\'0\' + (b || 0).toString(16)).slice(-2);');
|
||||
func.push(' return \'#\' + r + g + b;');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['colour_blend'] = func.join('\n');
|
||||
}
|
||||
var code = Blockly.JavaScript.colour_blend.functionName +
|
||||
'(' + c1 + ', ' + c2 + ', ' + ratio + ')';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
323
generators/javascript/lists.js
Normal file
323
generators/javascript/lists.js
Normal file
@@ -0,0 +1,323 @@
|
||||
/**
|
||||
* 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 JavaScript for list blocks.
|
||||
* @author fraser@google.com (Neil Fraser)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.JavaScript.lists');
|
||||
|
||||
goog.require('Blockly.JavaScript');
|
||||
|
||||
|
||||
Blockly.JavaScript['lists_create_empty'] = function(block) {
|
||||
// Create an empty list.
|
||||
return ['[]', Blockly.JavaScript.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['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.JavaScript.valueToCode(block, 'ADD' + n,
|
||||
Blockly.JavaScript.ORDER_COMMA) || 'null';
|
||||
}
|
||||
code = '[' + code.join(', ') + ']';
|
||||
return [code, Blockly.JavaScript.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['lists_repeat'] = function(block) {
|
||||
// Create a list with one element repeated.
|
||||
if (!Blockly.JavaScript.definitions_['lists_repeat']) {
|
||||
// Function copied from Closure's goog.array.repeat.
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'lists_repeat', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.lists_repeat.repeat = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(value, n) {');
|
||||
func.push(' var array = [];');
|
||||
func.push(' for (var i = 0; i < n; i++) {');
|
||||
func.push(' array[i] = value;');
|
||||
func.push(' }');
|
||||
func.push(' return array;');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['lists_repeat'] = func.join('\n');
|
||||
}
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'ITEM',
|
||||
Blockly.JavaScript.ORDER_COMMA) || 'null';
|
||||
var argument1 = Blockly.JavaScript.valueToCode(block, 'NUM',
|
||||
Blockly.JavaScript.ORDER_COMMA) || '0';
|
||||
var code = Blockly.JavaScript.lists_repeat.repeat +
|
||||
'(' + argument0 + ', ' + argument1 + ')';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['lists_length'] = function(block) {
|
||||
// List length.
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
|
||||
Blockly.JavaScript.ORDER_FUNCTION_CALL) || '\'\'';
|
||||
return [argument0 + '.length', Blockly.JavaScript.ORDER_MEMBER];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['lists_isEmpty'] = function(block) {
|
||||
// Is the list empty?
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '[]';
|
||||
return ['!' + argument0 + '.length', Blockly.JavaScript.ORDER_LOGICAL_NOT];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['lists_indexOf'] = function(block) {
|
||||
// Find an item in the list.
|
||||
var operator = block.getTitleValue('END') == 'FIRST' ?
|
||||
'indexOf' : 'lastIndexOf';
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'FIND',
|
||||
Blockly.JavaScript.ORDER_NONE) || '\'\'';
|
||||
var argument1 = Blockly.JavaScript.valueToCode(block, 'VALUE',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '[]';
|
||||
var code = argument1 + '.' + operator + '(' + argument0 + ') + 1';
|
||||
return [code, Blockly.JavaScript.ORDER_MEMBER];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['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.JavaScript.valueToCode(block, 'AT',
|
||||
Blockly.JavaScript.ORDER_UNARY_NEGATION) || '1';
|
||||
var list = Blockly.JavaScript.valueToCode(block, 'VALUE',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '[]';
|
||||
|
||||
if (where == 'FIRST') {
|
||||
if (mode == 'GET') {
|
||||
var code = list + '[0]';
|
||||
return [code, Blockly.JavaScript.ORDER_MEMBER];
|
||||
} else if (mode == 'GET_REMOVE') {
|
||||
var code = list + '.shift()';
|
||||
return [code, Blockly.JavaScript.ORDER_MEMBER];
|
||||
} else if (mode == 'REMOVE') {
|
||||
return list + '.shift();\n';
|
||||
}
|
||||
} else if (where == 'LAST') {
|
||||
if (mode == 'GET') {
|
||||
var code = list + '.slice(-1)[0]';
|
||||
return [code, Blockly.JavaScript.ORDER_MEMBER];
|
||||
} else if (mode == 'GET_REMOVE') {
|
||||
var code = list + '.pop()';
|
||||
return [code, Blockly.JavaScript.ORDER_MEMBER];
|
||||
} else if (mode == 'REMOVE') {
|
||||
return list + '.pop();\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 = parseFloat(at) - 1;
|
||||
} else {
|
||||
// If the index is dynamic, decrement it in code.
|
||||
at += ' - 1';
|
||||
}
|
||||
if (mode == 'GET') {
|
||||
var code = list + '[' + at + ']';
|
||||
return [code, Blockly.JavaScript.ORDER_MEMBER];
|
||||
} else if (mode == 'GET_REMOVE') {
|
||||
var code = list + '.splice(' + at + ', 1)[0]';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
} else if (mode == 'REMOVE') {
|
||||
return list + '.splice(' + at + ', 1);\n';
|
||||
}
|
||||
} else if (where == 'FROM_END') {
|
||||
if (mode == 'GET') {
|
||||
var code = list + '.slice(-' + at + ')[0]';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
} else if (mode == 'GET_REMOVE' || mode == 'REMOVE') {
|
||||
if (!Blockly.JavaScript.definitions_['lists_remove_from_end']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'lists_remove_from_end', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.lists_getIndex.lists_remove_from_end = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(list, x) {');
|
||||
func.push(' x = list.length - x;');
|
||||
func.push(' return list.splice(x, 1)[0];');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['lists_remove_from_end'] =
|
||||
func.join('\n');
|
||||
}
|
||||
code = Blockly.JavaScript.lists_getIndex.lists_remove_from_end +
|
||||
'(' + list + ', ' + at + ')';
|
||||
if (mode == 'GET_REMOVE') {
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
} else if (mode == 'REMOVE') {
|
||||
return code + ';\n';
|
||||
}
|
||||
}
|
||||
} else if (where == 'RANDOM') {
|
||||
if (!Blockly.JavaScript.definitions_['lists_get_random_item']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'lists_get_random_item', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.lists_getIndex.random = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(list, remove) {');
|
||||
func.push(' var x = Math.floor(Math.random() * list.length);');
|
||||
func.push(' if (remove) {');
|
||||
func.push(' return list.splice(x, 1)[0];');
|
||||
func.push(' } else {');
|
||||
func.push(' return list[x];');
|
||||
func.push(' }');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['lists_get_random_item'] =
|
||||
func.join('\n');
|
||||
}
|
||||
code = Blockly.JavaScript.lists_getIndex.random +
|
||||
'(' + list + ', ' + (mode != 'GET') + ')';
|
||||
if (mode == 'GET' || mode == 'GET_REMOVE') {
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
} else if (mode == 'REMOVE') {
|
||||
return code + ';\n';
|
||||
}
|
||||
}
|
||||
throw 'Unhandled combination (lists_getIndex).';
|
||||
};
|
||||
|
||||
Blockly.JavaScript['lists_setIndex'] = function(block) {
|
||||
// Set element at index.
|
||||
// Note: Until February 2013 this block did not have MODE or WHERE inputs.
|
||||
var list = Blockly.JavaScript.valueToCode(block, 'LIST',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '[]';
|
||||
var mode = block.getTitleValue('MODE') || 'GET';
|
||||
var where = block.getTitleValue('WHERE') || 'FROM_START';
|
||||
var at = Blockly.JavaScript.valueToCode(block, 'AT',
|
||||
Blockly.JavaScript.ORDER_NONE) || '1';
|
||||
var value = Blockly.JavaScript.valueToCode(block, 'TO',
|
||||
Blockly.JavaScript.ORDER_ASSIGNMENT) || 'null';
|
||||
// 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.JavaScript.variableDB_.getDistinctName(
|
||||
'tmp_list', Blockly.Variables.NAME_TYPE);
|
||||
var code = 'var ' + listVar + ' = ' + list + ';\n';
|
||||
list = listVar;
|
||||
return code;
|
||||
}
|
||||
if (where == 'FIRST') {
|
||||
if (mode == 'SET') {
|
||||
return list + '[0] = ' + value + ';\n';
|
||||
} else if (mode == 'INSERT') {
|
||||
return list + '.unshift(' + value + ');\n';
|
||||
}
|
||||
} else if (where == 'LAST') {
|
||||
if (mode == 'SET') {
|
||||
var code = cacheList();
|
||||
code += list + '[' + list + '.length - 1] = ' + value + ';\n';
|
||||
return code;
|
||||
} else if (mode == 'INSERT') {
|
||||
return list + '.push(' + 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 = parseFloat(at) - 1;
|
||||
} else {
|
||||
// If the index is dynamic, decrement it in code.
|
||||
at += ' - 1';
|
||||
}
|
||||
if (mode == 'SET') {
|
||||
return list + '[' + at + '] = ' + value + ';\n';
|
||||
} else if (mode == 'INSERT') {
|
||||
return list + '.splice(' + at + ', 0, ' + value + ');\n';
|
||||
}
|
||||
} else if (where == 'FROM_END') {
|
||||
var code = cacheList();
|
||||
if (mode == 'SET') {
|
||||
code += list + '[' + list + '.length - ' + at + '] = ' + value + ';\n';
|
||||
return code;
|
||||
} else if (mode == 'INSERT') {
|
||||
code += list + '.splice(' + list + '.length - ' + at + ', 0, ' + value +
|
||||
');\n';
|
||||
return code;
|
||||
}
|
||||
} else if (where == 'RANDOM') {
|
||||
var code = cacheList();
|
||||
var xVar = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'tmp_x', Blockly.Variables.NAME_TYPE);
|
||||
code += 'var ' + xVar + ' = Math.floor(Math.random() * ' + list +
|
||||
'.length);\n';
|
||||
if (mode == 'SET') {
|
||||
code += list + '[' + xVar + '] = ' + value + ';\n';
|
||||
return code;
|
||||
} else if (mode == 'INSERT') {
|
||||
code += list + '.splice(' + xVar + ', 0, ' + value + ');\n';
|
||||
return code;
|
||||
}
|
||||
}
|
||||
throw 'Unhandled combination (lists_setIndex).';
|
||||
};
|
||||
|
||||
Blockly.JavaScript['lists_getSublist'] = function(block) {
|
||||
// Get sublist.
|
||||
var list = Blockly.JavaScript.valueToCode(block, 'LIST',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '[]';
|
||||
var where1 = block.getTitleValue('WHERE1');
|
||||
var where2 = block.getTitleValue('WHERE2');
|
||||
var at1 = Blockly.JavaScript.valueToCode(block, 'AT1',
|
||||
Blockly.JavaScript.ORDER_NONE) || '1';
|
||||
var at2 = Blockly.JavaScript.valueToCode(block, 'AT2',
|
||||
Blockly.JavaScript.ORDER_NONE) || '1';
|
||||
if (where1 == 'FIRST' && where2 == 'LAST') {
|
||||
var code = list + '.concat()';
|
||||
} else {
|
||||
if (!Blockly.JavaScript.definitions_['lists_get_sublist']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'lists_get_sublist', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.lists_getSublist.func = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName +
|
||||
'(list, where1, at1, where2, at2) {');
|
||||
func.push(' function getAt(where, at) {');
|
||||
func.push(' if (where == \'FROM_START\') {');
|
||||
func.push(' at--;');
|
||||
func.push(' } else if (where == \'FROM_END\') {');
|
||||
func.push(' at = list.length - at;');
|
||||
func.push(' } else if (where == \'FIRST\') {');
|
||||
func.push(' at = 0;');
|
||||
func.push(' } else if (where == \'LAST\') {');
|
||||
func.push(' at = list.length - 1;');
|
||||
func.push(' } else {');
|
||||
func.push(' throw \'Unhandled option (lists_getSublist).\';');
|
||||
func.push(' }');
|
||||
func.push(' return at;');
|
||||
func.push(' }');
|
||||
func.push(' at1 = getAt(where1, at1);');
|
||||
func.push(' at2 = getAt(where2, at2) + 1;');
|
||||
func.push(' return list.slice(at1, at2);');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['lists_get_sublist'] =
|
||||
func.join('\n');
|
||||
}
|
||||
var code = Blockly.JavaScript.lists_getSublist.func + '(' + list + ', \'' +
|
||||
where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')';
|
||||
}
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
125
generators/javascript/logic.js
Normal file
125
generators/javascript/logic.js
Normal file
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* 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 JavaScript for logic blocks.
|
||||
* @author q.neutron@gmail.com (Quynh Neutron)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.JavaScript.logic');
|
||||
|
||||
goog.require('Blockly.JavaScript');
|
||||
|
||||
|
||||
Blockly.JavaScript['controls_if'] = function(block) {
|
||||
// If/elseif/else condition.
|
||||
var n = 0;
|
||||
var argument = Blockly.JavaScript.valueToCode(block, 'IF' + n,
|
||||
Blockly.JavaScript.ORDER_NONE) || 'false';
|
||||
var branch = Blockly.JavaScript.statementToCode(block, 'DO' + n);
|
||||
var code = 'if (' + argument + ') {\n' + branch + '}';
|
||||
for (n = 1; n <= block.elseifCount_; n++) {
|
||||
argument = Blockly.JavaScript.valueToCode(block, 'IF' + n,
|
||||
Blockly.JavaScript.ORDER_NONE) || 'false';
|
||||
branch = Blockly.JavaScript.statementToCode(block, 'DO' + n);
|
||||
code += ' else if (' + argument + ') {\n' + branch + '}';
|
||||
}
|
||||
if (block.elseCount_) {
|
||||
branch = Blockly.JavaScript.statementToCode(block, 'ELSE');
|
||||
code += ' else {\n' + branch + '}\n';
|
||||
}
|
||||
return code + '\n';
|
||||
};
|
||||
|
||||
Blockly.JavaScript['logic_compare'] = function(block) {
|
||||
// Comparison operator.
|
||||
var OPERATORS = {
|
||||
EQ: '==',
|
||||
NEQ: '!=',
|
||||
LT: '<',
|
||||
LTE: '<=',
|
||||
GT: '>',
|
||||
GTE: '>='
|
||||
};
|
||||
var operator = OPERATORS[block.getTitleValue('OP')];
|
||||
var order = (operator == '==' || operator == '!=') ?
|
||||
Blockly.JavaScript.ORDER_EQUALITY : Blockly.JavaScript.ORDER_RELATIONAL;
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'A', order) || '0';
|
||||
var argument1 = Blockly.JavaScript.valueToCode(block, 'B', order) || '0';
|
||||
var code = argument0 + ' ' + operator + ' ' + argument1;
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['logic_operation'] = function(block) {
|
||||
// Operations 'and', 'or'.
|
||||
var operator = (block.getTitleValue('OP') == 'AND') ? '&&' : '||';
|
||||
var order = (operator == '&&') ? Blockly.JavaScript.ORDER_LOGICAL_AND :
|
||||
Blockly.JavaScript.ORDER_LOGICAL_OR;
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'A', order);
|
||||
var argument1 = Blockly.JavaScript.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 == '&&') ? 'true' : 'false';
|
||||
if (!argument0) {
|
||||
argument0 = defaultArgument;
|
||||
}
|
||||
if (!argument1) {
|
||||
argument1 = defaultArgument;
|
||||
}
|
||||
}
|
||||
var code = argument0 + ' ' + operator + ' ' + argument1;
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['logic_negate'] = function(block) {
|
||||
// Negation.
|
||||
var order = Blockly.JavaScript.ORDER_LOGICAL_NOT;
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'BOOL', order) ||
|
||||
'true';
|
||||
var code = '!' + argument0;
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['logic_boolean'] = function(block) {
|
||||
// Boolean values true and false.
|
||||
var code = (block.getTitleValue('BOOL') == 'TRUE') ? 'true' : 'false';
|
||||
return [code, Blockly.JavaScript.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['logic_null'] = function(block) {
|
||||
// Null data type.
|
||||
return ['null', Blockly.JavaScript.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['logic_ternary'] = function(block) {
|
||||
// Ternary operator.
|
||||
var value_if = Blockly.JavaScript.valueToCode(block, 'IF',
|
||||
Blockly.JavaScript.ORDER_CONDITIONAL) || 'false';
|
||||
var value_then = Blockly.JavaScript.valueToCode(block, 'THEN',
|
||||
Blockly.JavaScript.ORDER_CONDITIONAL) || 'null';
|
||||
var value_else = Blockly.JavaScript.valueToCode(block, 'ELSE',
|
||||
Blockly.JavaScript.ORDER_CONDITIONAL) || 'null';
|
||||
var code = value_if + ' ? ' + value_then + ' : ' + value_else
|
||||
return [code, Blockly.JavaScript.ORDER_CONDITIONAL];
|
||||
};
|
||||
200
generators/javascript/loops.js
Normal file
200
generators/javascript/loops.js
Normal file
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* 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 JavaScript for loop blocks.
|
||||
* @author fraser@google.com (Neil Fraser)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.JavaScript.loops');
|
||||
|
||||
goog.require('Blockly.JavaScript');
|
||||
|
||||
|
||||
Blockly.JavaScript['controls_repeat'] = function(block) {
|
||||
// Repeat n times (internal number).
|
||||
var repeats = Number(block.getTitleValue('TIMES'));
|
||||
var branch = Blockly.JavaScript.statementToCode(block, 'DO');
|
||||
if (Blockly.JavaScript.INFINITE_LOOP_TRAP) {
|
||||
branch = Blockly.JavaScript.INFINITE_LOOP_TRAP.replace(/%1/g,
|
||||
'\'' + block.id + '\'') + branch;
|
||||
}
|
||||
var loopVar = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'count', Blockly.Variables.NAME_TYPE);
|
||||
var code = 'for (var ' + loopVar + ' = 0; ' +
|
||||
loopVar + ' < ' + repeats + '; ' +
|
||||
loopVar + '++) {\n' +
|
||||
branch + '}\n';
|
||||
return code;
|
||||
};
|
||||
|
||||
Blockly.JavaScript['controls_repeat_ext'] = function(block) {
|
||||
// Repeat n times (external number).
|
||||
var repeats = Blockly.JavaScript.valueToCode(block, 'TIMES',
|
||||
Blockly.JavaScript.ORDER_ASSIGNMENT) || '0';
|
||||
var branch = Blockly.JavaScript.statementToCode(block, 'DO');
|
||||
if (Blockly.JavaScript.INFINITE_LOOP_TRAP) {
|
||||
branch = Blockly.JavaScript.INFINITE_LOOP_TRAP.replace(/%1/g,
|
||||
'\'' + block.id + '\'') + branch;
|
||||
}
|
||||
var code = '';
|
||||
var loopVar = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'count', Blockly.Variables.NAME_TYPE);
|
||||
var endVar = repeats;
|
||||
if (!repeats.match(/^\w+$/) && !Blockly.isNumber(repeats)) {
|
||||
var endVar = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'repeat_end', Blockly.Variables.NAME_TYPE);
|
||||
code += 'var ' + endVar + ' = ' + repeats + ';\n';
|
||||
}
|
||||
code += 'for (var ' + loopVar + ' = 0; ' +
|
||||
loopVar + ' < ' + endVar + '; ' +
|
||||
loopVar + '++) {\n' +
|
||||
branch + '}\n';
|
||||
return code;
|
||||
};
|
||||
|
||||
Blockly.JavaScript['controls_whileUntil'] = function(block) {
|
||||
// Do while/until loop.
|
||||
var until = block.getTitleValue('MODE') == 'UNTIL';
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'BOOL',
|
||||
until ? Blockly.JavaScript.ORDER_LOGICAL_NOT :
|
||||
Blockly.JavaScript.ORDER_NONE) || 'false';
|
||||
var branch = Blockly.JavaScript.statementToCode(block, 'DO');
|
||||
if (Blockly.JavaScript.INFINITE_LOOP_TRAP) {
|
||||
branch = Blockly.JavaScript.INFINITE_LOOP_TRAP.replace(/%1/g,
|
||||
'\'' + block.id + '\'') + branch;
|
||||
}
|
||||
if (until) {
|
||||
argument0 = '!' + argument0;
|
||||
}
|
||||
return 'while (' + argument0 + ') {\n' + branch + '}\n';
|
||||
};
|
||||
|
||||
Blockly.JavaScript['controls_for'] = function(block) {
|
||||
// For loop.
|
||||
var variable0 = Blockly.JavaScript.variableDB_.getName(
|
||||
block.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'FROM',
|
||||
Blockly.JavaScript.ORDER_ASSIGNMENT) || '0';
|
||||
var argument1 = Blockly.JavaScript.valueToCode(block, 'TO',
|
||||
Blockly.JavaScript.ORDER_ASSIGNMENT) || '0';
|
||||
var increment = Blockly.JavaScript.valueToCode(block, 'BY',
|
||||
Blockly.JavaScript.ORDER_ASSIGNMENT) || '1';
|
||||
var branch = Blockly.JavaScript.statementToCode(block, 'DO');
|
||||
if (Blockly.JavaScript.INFINITE_LOOP_TRAP) {
|
||||
branch = Blockly.JavaScript.INFINITE_LOOP_TRAP.replace(/%1/g,
|
||||
'\'' + block.id + '\'') + branch;
|
||||
}
|
||||
var code;
|
||||
if (Blockly.isNumber(argument0) && Blockly.isNumber(argument1) &&
|
||||
Blockly.isNumber(increment)) {
|
||||
// All arguments are simple numbers.
|
||||
var up = parseFloat(argument0) <= parseFloat(argument1);
|
||||
code = 'for (' + variable0 + ' = ' + argument0 + '; ' +
|
||||
variable0 + (up ? ' <= ' : ' >= ') + argument1 + '; ' +
|
||||
variable0;
|
||||
var step = Math.abs(parseFloat(increment));
|
||||
if (step == 1) {
|
||||
code += up ? '++' : '--';
|
||||
} else {
|
||||
code += (up ? ' += ' : ' -= ') + step;
|
||||
}
|
||||
code += ') {\n' + branch + '}\n';
|
||||
} else {
|
||||
code = '';
|
||||
// Cache non-trivial values to variables to prevent repeated look-ups.
|
||||
var startVar = argument0;
|
||||
if (!argument0.match(/^\w+$/) && !Blockly.isNumber(argument0)) {
|
||||
var startVar = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
variable0 + '_start', Blockly.Variables.NAME_TYPE);
|
||||
code += 'var ' + startVar + ' = ' + argument0 + ';\n';
|
||||
}
|
||||
var endVar = argument1;
|
||||
if (!argument1.match(/^\w+$/) && !Blockly.isNumber(argument1)) {
|
||||
var endVar = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
variable0 + '_end', Blockly.Variables.NAME_TYPE);
|
||||
code += 'var ' + endVar + ' = ' + argument1 + ';\n';
|
||||
}
|
||||
// Determine loop direction at start, in case one of the bounds
|
||||
// changes during loop execution.
|
||||
var incVar = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
variable0 + '_inc', Blockly.Variables.NAME_TYPE);
|
||||
code += 'var ' + incVar + ' = ';
|
||||
if (Blockly.isNumber(increment)) {
|
||||
code += Math.abs(increment) + ';\n';
|
||||
} else {
|
||||
code += 'Math.abs(' + increment + ');\n';
|
||||
}
|
||||
code += 'if (' + startVar + ' > ' + endVar + ') {\n';
|
||||
code += ' ' + incVar + ' = -' + incVar +';\n';
|
||||
code += '}\n';
|
||||
code += 'for (' + variable0 + ' = ' + startVar + ';\n' +
|
||||
' ' + incVar + ' >= 0 ? ' +
|
||||
variable0 + ' <= ' + endVar + ' : ' +
|
||||
variable0 + ' >= ' + endVar + ';\n' +
|
||||
' ' + variable0 + ' += ' + incVar + ') {\n' +
|
||||
branch + '}\n';
|
||||
}
|
||||
return code;
|
||||
};
|
||||
|
||||
Blockly.JavaScript['controls_forEach'] = function(block) {
|
||||
// For each loop.
|
||||
var variable0 = Blockly.JavaScript.variableDB_.getName(
|
||||
block.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'LIST',
|
||||
Blockly.JavaScript.ORDER_ASSIGNMENT) || '[]';
|
||||
var branch = Blockly.JavaScript.statementToCode(block, 'DO');
|
||||
if (Blockly.JavaScript.INFINITE_LOOP_TRAP) {
|
||||
branch = Blockly.JavaScript.INFINITE_LOOP_TRAP.replace(/%1/g,
|
||||
'\'' + block.id + '\'') + branch;
|
||||
}
|
||||
var code;
|
||||
var indexVar = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
variable0 + '_index', Blockly.Variables.NAME_TYPE);
|
||||
if (argument0.match(/^\w+$/)) {
|
||||
branch = ' ' + variable0 + ' = ' + argument0 + '[' + indexVar + '];\n' +
|
||||
branch;
|
||||
code = 'for (var ' + indexVar + ' in ' + argument0 + ') {\n' +
|
||||
branch + '}\n';
|
||||
} else {
|
||||
// The list appears to be more complicated than a simple variable.
|
||||
// Cache it to a variable to prevent repeated look-ups.
|
||||
var listVar = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
variable0 + '_list', Blockly.Variables.NAME_TYPE);
|
||||
branch = ' ' + variable0 + ' = ' + listVar + '[' + indexVar + '];\n' +
|
||||
branch;
|
||||
code = 'var ' + listVar + ' = ' + argument0 + ';\n' +
|
||||
'for (var ' + indexVar + ' in ' + listVar + ') {\n' +
|
||||
branch + '}\n';
|
||||
}
|
||||
return code;
|
||||
};
|
||||
|
||||
Blockly.JavaScript['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.';
|
||||
};
|
||||
443
generators/javascript/math.js
Normal file
443
generators/javascript/math.js
Normal file
@@ -0,0 +1,443 @@
|
||||
/**
|
||||
* 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 JavaScript for math blocks.
|
||||
* @author q.neutron@gmail.com (Quynh Neutron)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.JavaScript.math');
|
||||
|
||||
goog.require('Blockly.JavaScript');
|
||||
|
||||
|
||||
Blockly.JavaScript['math_number'] = function(block) {
|
||||
// Numeric value.
|
||||
var code = parseFloat(block.getTitleValue('NUM'));
|
||||
return [code, Blockly.JavaScript.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['math_arithmetic'] = function(block) {
|
||||
// Basic arithmetic operators, and power.
|
||||
var OPERATORS = {
|
||||
ADD: [' + ', Blockly.JavaScript.ORDER_ADDITION],
|
||||
MINUS: [' - ', Blockly.JavaScript.ORDER_SUBTRACTION],
|
||||
MULTIPLY: [' * ', Blockly.JavaScript.ORDER_MULTIPLICATION],
|
||||
DIVIDE: [' / ', Blockly.JavaScript.ORDER_DIVISION],
|
||||
POWER: [null, Blockly.JavaScript.ORDER_COMMA] // Handle power separately.
|
||||
};
|
||||
var tuple = OPERATORS[block.getTitleValue('OP')];
|
||||
var operator = tuple[0];
|
||||
var order = tuple[1];
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'A', order) || '0';
|
||||
var argument1 = Blockly.JavaScript.valueToCode(block, 'B', order) || '0';
|
||||
var code;
|
||||
// Power in JavaScript requires a special case since it has no operator.
|
||||
if (!operator) {
|
||||
code = 'Math.pow(' + argument0 + ', ' + argument1 + ')';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
}
|
||||
code = argument0 + operator + argument1;
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['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.
|
||||
arg = Blockly.JavaScript.valueToCode(block, 'NUM',
|
||||
Blockly.JavaScript.ORDER_UNARY_NEGATION) || '0';
|
||||
if (arg[0] == '-') {
|
||||
// --3 is not legal in JS.
|
||||
arg = ' ' + arg;
|
||||
}
|
||||
code = '-' + arg;
|
||||
return [code, Blockly.JavaScript.ORDER_UNARY_NEGATION];
|
||||
}
|
||||
if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') {
|
||||
arg = Blockly.JavaScript.valueToCode(block, 'NUM',
|
||||
Blockly.JavaScript.ORDER_DIVISION) || '0';
|
||||
} else {
|
||||
arg = Blockly.JavaScript.valueToCode(block, 'NUM',
|
||||
Blockly.JavaScript.ORDER_NONE) || '0';
|
||||
}
|
||||
// First, handle cases which generate values that don't need parentheses
|
||||
// wrapping the code.
|
||||
switch (operator) {
|
||||
case 'ABS':
|
||||
code = 'Math.abs(' + arg + ')';
|
||||
break;
|
||||
case 'ROOT':
|
||||
code = 'Math.sqrt(' + arg + ')';
|
||||
break;
|
||||
case 'LN':
|
||||
code = 'Math.log(' + arg + ')';
|
||||
break;
|
||||
case 'EXP':
|
||||
code = 'Math.exp(' + arg + ')';
|
||||
break;
|
||||
case 'POW10':
|
||||
code = 'Math.pow(10,' + arg + ')';
|
||||
break;
|
||||
case 'ROUND':
|
||||
code = 'Math.round(' + arg + ')';
|
||||
break;
|
||||
case 'ROUNDUP':
|
||||
code = 'Math.ceil(' + arg + ')';
|
||||
break;
|
||||
case 'ROUNDDOWN':
|
||||
code = 'Math.floor(' + arg + ')';
|
||||
break;
|
||||
case 'SIN':
|
||||
code = 'Math.sin(' + arg + ' / 180 * Math.PI)';
|
||||
break;
|
||||
case 'COS':
|
||||
code = 'Math.cos(' + arg + ' / 180 * Math.PI)';
|
||||
break;
|
||||
case 'TAN':
|
||||
code = 'Math.tan(' + arg + ' / 180 * Math.PI)';
|
||||
break;
|
||||
}
|
||||
if (code) {
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
}
|
||||
// Second, handle cases which generate values that may need parentheses
|
||||
// wrapping the code.
|
||||
switch (operator) {
|
||||
case 'LOG10':
|
||||
code = 'Math.log(' + arg + ') / Math.log(10)';
|
||||
break;
|
||||
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.JavaScript.ORDER_DIVISION];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['math_constant'] = function(block) {
|
||||
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
|
||||
var CONSTANTS = {
|
||||
PI: ['Math.PI', Blockly.JavaScript.ORDER_MEMBER],
|
||||
E: ['Math.E', Blockly.JavaScript.ORDER_MEMBER],
|
||||
GOLDEN_RATIO: ['(1 + Math.sqrt(5)) / 2', Blockly.JavaScript.ORDER_DIVISION],
|
||||
SQRT2: ['Math.SQRT2', Blockly.JavaScript.ORDER_MEMBER],
|
||||
SQRT1_2: ['Math.SQRT1_2', Blockly.JavaScript.ORDER_MEMBER],
|
||||
INFINITY: ['Infinity', Blockly.JavaScript.ORDER_ATOMIC]
|
||||
};
|
||||
return CONSTANTS[block.getTitleValue('CONSTANT')];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['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.JavaScript.valueToCode(block, 'NUMBER_TO_CHECK',
|
||||
Blockly.JavaScript.ORDER_MODULUS) || '0';
|
||||
var dropdown_property = block.getTitleValue('PROPERTY');
|
||||
var code;
|
||||
if (dropdown_property == 'PRIME') {
|
||||
// Prime is a special case as it is not a one-liner test.
|
||||
if (!Blockly.JavaScript.definitions_['isPrime']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'isPrime', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.logic_prime= functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(n) {');
|
||||
func.push(' // http://en.wikipedia.org/wiki/Primality_test#Naive_methods');
|
||||
func.push(' if (n == 2 || n == 3) {');
|
||||
func.push(' return true;');
|
||||
func.push(' }');
|
||||
func.push(' // False if n is NaN, negative, is 1, or not whole.');
|
||||
func.push(' // And false if n is divisible by 2 or 3.');
|
||||
func.push(' if (isNaN(n) || n <= 1 || n % 1 != 0 || n % 2 == 0 ||' +
|
||||
' n % 3 == 0) {');
|
||||
func.push(' return false;');
|
||||
func.push(' }');
|
||||
func.push(' // Check all the numbers of form 6k +/- 1, up to sqrt(n).');
|
||||
func.push(' for (var x = 6; x <= Math.sqrt(n) + 1; x += 6) {');
|
||||
func.push(' if (n % (x - 1) == 0 || n % (x + 1) == 0) {');
|
||||
func.push(' return false;');
|
||||
func.push(' }');
|
||||
func.push(' }');
|
||||
func.push(' return true;');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['isPrime'] = func.join('\n');
|
||||
}
|
||||
code = Blockly.JavaScript.logic_prime + '(' + number_to_check + ')';
|
||||
return [code, Blockly.JavaScript.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.JavaScript.valueToCode(block, 'DIVISOR',
|
||||
Blockly.JavaScript.ORDER_MODULUS) || '0';
|
||||
code = number_to_check + ' % ' + divisor + ' == 0';
|
||||
break;
|
||||
}
|
||||
return [code, Blockly.JavaScript.ORDER_EQUALITY];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['math_change'] = function(block) {
|
||||
// Add to a variable in place.
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'DELTA',
|
||||
Blockly.JavaScript.ORDER_ADDITION) || '0';
|
||||
var varName = Blockly.JavaScript.variableDB_.getName(
|
||||
block.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
|
||||
return varName + ' = (typeof ' + varName + ' == \'number\' ? ' + varName +
|
||||
' : 0) + ' + argument0 + ';\n';
|
||||
};
|
||||
|
||||
// Rounding functions have a single operand.
|
||||
Blockly.JavaScript['math_round'] = Blockly.JavaScript['math_single'];
|
||||
// Trigonometry functions have a single operand.
|
||||
Blockly.JavaScript['math_trig'] = Blockly.JavaScript['math_single'];
|
||||
|
||||
Blockly.JavaScript['math_on_list'] = function(block) {
|
||||
// Math functions for lists.
|
||||
var func = block.getTitleValue('OP');
|
||||
var list, code;
|
||||
switch (func) {
|
||||
case 'SUM':
|
||||
list = Blockly.JavaScript.valueToCode(block, 'LIST',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '[]';
|
||||
code = list + '.reduce(function(x, y) {return x + y;})';
|
||||
break;
|
||||
case 'MIN':
|
||||
list = Blockly.JavaScript.valueToCode(block, 'LIST',
|
||||
Blockly.JavaScript.ORDER_COMMA) || '[]';
|
||||
code = 'Math.min.apply(null, ' + list + ')';
|
||||
break;
|
||||
case 'MAX':
|
||||
list = Blockly.JavaScript.valueToCode(block, 'LIST',
|
||||
Blockly.JavaScript.ORDER_COMMA) || '[]';
|
||||
code = 'Math.max.apply(null, ' + list + ')';
|
||||
break;
|
||||
case 'AVERAGE':
|
||||
// math_median([null,null,1,3]) == 2.0.
|
||||
if (!Blockly.JavaScript.definitions_['math_mean']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'math_mean', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.math_on_list.math_mean = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(myList) {');
|
||||
func.push(' return myList.reduce(function(x, y) {return x + y;}) / ' +
|
||||
'myList.length;');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['math_mean'] = func.join('\n');
|
||||
}
|
||||
list = Blockly.JavaScript.valueToCode(block, 'LIST',
|
||||
Blockly.JavaScript.ORDER_NONE) || '[]';
|
||||
code = Blockly.JavaScript.math_on_list.math_mean + '(' + list + ')';
|
||||
break;
|
||||
case 'MEDIAN':
|
||||
// math_median([null,null,1,3]) == 2.0.
|
||||
if (!Blockly.JavaScript.definitions_['math_median']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'math_median', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.math_on_list.math_median = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(myList) {');
|
||||
func.push(' var localList = myList.filter(function (x) ' +
|
||||
'{return typeof x == \'number\';});');
|
||||
func.push(' if (!localList.length) return null;');
|
||||
func.push(' localList.sort(function(a, b) {return b - a;});');
|
||||
func.push(' if (localList.length % 2 == 0) {');
|
||||
func.push(' return (localList[localList.length / 2 - 1] + ' +
|
||||
'localList[localList.length / 2]) / 2;');
|
||||
func.push(' } else {');
|
||||
func.push(' return localList[(localList.length - 1) / 2];');
|
||||
func.push(' }');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['math_median'] = func.join('\n');
|
||||
}
|
||||
list = Blockly.JavaScript.valueToCode(block, 'LIST',
|
||||
Blockly.JavaScript.ORDER_NONE) || '[]';
|
||||
code = Blockly.JavaScript.math_on_list.math_median + '(' + list + ')';
|
||||
break;
|
||||
case 'MODE':
|
||||
if (!Blockly.JavaScript.definitions_['math_modes']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'math_modes', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.math_on_list.math_modes = functionName;
|
||||
// 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].
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(values) {');
|
||||
func.push(' var modes = [];');
|
||||
func.push(' var counts = [];');
|
||||
func.push(' var maxCount = 0;');
|
||||
func.push(' for (var i = 0; i < values.length; i++) {');
|
||||
func.push(' var value = values[i];');
|
||||
func.push(' var found = false;');
|
||||
func.push(' var thisCount;');
|
||||
func.push(' for (var j = 0; j < counts.length; j++) {');
|
||||
func.push(' if (counts[j][0] === value) {');
|
||||
func.push(' thisCount = ++counts[j][1];');
|
||||
func.push(' found = true;');
|
||||
func.push(' break;');
|
||||
func.push(' }');
|
||||
func.push(' }');
|
||||
func.push(' if (!found) {');
|
||||
func.push(' counts.push([value, 1]);');
|
||||
func.push(' thisCount = 1;');
|
||||
func.push(' }');
|
||||
func.push(' maxCount = Math.max(thisCount, maxCount);');
|
||||
func.push(' }');
|
||||
func.push(' for (var j = 0; j < counts.length; j++) {');
|
||||
func.push(' if (counts[j][1] == maxCount) {');
|
||||
func.push(' modes.push(counts[j][0]);');
|
||||
func.push(' }');
|
||||
func.push(' }');
|
||||
func.push(' return modes;');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['math_modes'] = func.join('\n');
|
||||
}
|
||||
list = Blockly.JavaScript.valueToCode(block, 'LIST',
|
||||
Blockly.JavaScript.ORDER_NONE) || '[]';
|
||||
code = Blockly.JavaScript.math_on_list.math_modes + '(' + list + ')';
|
||||
break;
|
||||
case 'STD_DEV':
|
||||
if (!Blockly.JavaScript.definitions_['math_standard_deviation']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'math_standard_deviation', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.math_on_list.math_standard_deviation = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(numbers) {');
|
||||
func.push(' var n = numbers.length;');
|
||||
func.push(' if (!n) return null;');
|
||||
func.push(' var mean = numbers.reduce(function(x, y) ' +
|
||||
'{return x + y;}) / n;');
|
||||
func.push(' var variance = 0;');
|
||||
func.push(' for (var j = 0; j < n; j++) {');
|
||||
func.push(' variance += Math.pow(numbers[j] - mean, 2);');
|
||||
func.push(' }');
|
||||
func.push(' variance = variance / n;');
|
||||
func.push(' return Math.sqrt(variance);');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['math_standard_deviation'] =
|
||||
func.join('\n');
|
||||
}
|
||||
list = Blockly.JavaScript.valueToCode(block, 'LIST',
|
||||
Blockly.JavaScript.ORDER_NONE) || '[]';
|
||||
code = Blockly.JavaScript.math_on_list.math_standard_deviation +
|
||||
'(' + list + ')';
|
||||
break;
|
||||
case 'RANDOM':
|
||||
if (!Blockly.JavaScript.definitions_['math_random_item']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'math_random_item', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.math_on_list.math_random_item = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(list) {');
|
||||
func.push(' var x = Math.floor(Math.random() * list.length);');
|
||||
func.push(' return list[x];');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['math_random_item'] = func.join('\n');
|
||||
}
|
||||
list = Blockly.JavaScript.valueToCode(block, 'LIST',
|
||||
Blockly.JavaScript.ORDER_NONE) || '[]';
|
||||
code = Blockly.JavaScript.math_on_list.math_random_item +
|
||||
'(' + list + ')';
|
||||
break;
|
||||
default:
|
||||
throw 'Unknown operator: ' + func;
|
||||
}
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['math_modulo'] = function(block) {
|
||||
// Remainder computation.
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'DIVIDEND',
|
||||
Blockly.JavaScript.ORDER_MODULUS) || '0';
|
||||
var argument1 = Blockly.JavaScript.valueToCode(block, 'DIVISOR',
|
||||
Blockly.JavaScript.ORDER_MODULUS) || '0';
|
||||
var code = argument0 + ' % ' + argument1;
|
||||
return [code, Blockly.JavaScript.ORDER_MODULUS];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['math_constrain'] = function(block) {
|
||||
// Constrain a number between two limits.
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
|
||||
Blockly.JavaScript.ORDER_COMMA) || '0';
|
||||
var argument1 = Blockly.JavaScript.valueToCode(block, 'LOW',
|
||||
Blockly.JavaScript.ORDER_COMMA) || '0';
|
||||
var argument2 = Blockly.JavaScript.valueToCode(block, 'HIGH',
|
||||
Blockly.JavaScript.ORDER_COMMA) || 'Infinity';
|
||||
var code = 'Math.min(Math.max(' + argument0 + ', ' + argument1 + '), ' +
|
||||
argument2 + ')';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['math_random_int'] = function(block) {
|
||||
// Random integer between [X] and [Y].
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'FROM',
|
||||
Blockly.JavaScript.ORDER_COMMA) || '0';
|
||||
var argument1 = Blockly.JavaScript.valueToCode(block, 'TO',
|
||||
Blockly.JavaScript.ORDER_COMMA) || '0';
|
||||
if (!Blockly.JavaScript.definitions_['math_random_int']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'math_random_int', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.math_random_int.random_function = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(a, b) {');
|
||||
func.push(' if (a > b) {');
|
||||
func.push(' // Swap a and b to ensure a is smaller.');
|
||||
func.push(' var c = a;');
|
||||
func.push(' a = b;');
|
||||
func.push(' b = c;');
|
||||
func.push(' }');
|
||||
func.push(' return Math.floor(Math.random() * (b - a + 1) + a);');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['math_random_int'] = func.join('\n');
|
||||
}
|
||||
var code = Blockly.JavaScript.math_random_int.random_function +
|
||||
'(' + argument0 + ', ' + argument1 + ')';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['math_random_float'] = function(block) {
|
||||
// Random fraction between 0 and 1.
|
||||
return ['Math.random()', Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
102
generators/javascript/procedures.js
Normal file
102
generators/javascript/procedures.js
Normal file
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* 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 JavaScript for procedure blocks.
|
||||
* @author fraser@google.com (Neil Fraser)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.JavaScript.procedures');
|
||||
|
||||
goog.require('Blockly.JavaScript');
|
||||
|
||||
|
||||
Blockly.JavaScript['procedures_defreturn'] = function(block) {
|
||||
// Define a procedure with a return value.
|
||||
var funcName = Blockly.JavaScript.variableDB_.getName(
|
||||
block.getTitleValue('NAME'), Blockly.Procedures.NAME_TYPE);
|
||||
var branch = Blockly.JavaScript.statementToCode(block, 'STACK');
|
||||
if (Blockly.JavaScript.INFINITE_LOOP_TRAP) {
|
||||
branch = Blockly.JavaScript.INFINITE_LOOP_TRAP.replace(/%1/g,
|
||||
'\'' + block.id + '\'') + branch;
|
||||
}
|
||||
var returnValue = Blockly.JavaScript.valueToCode(block, 'RETURN',
|
||||
Blockly.JavaScript.ORDER_NONE) || '';
|
||||
if (returnValue) {
|
||||
returnValue = ' return ' + returnValue + ';\n';
|
||||
}
|
||||
var args = [];
|
||||
for (var x = 0; x < block.arguments_.length; x++) {
|
||||
args[x] = Blockly.JavaScript.variableDB_.getName(block.arguments_[x],
|
||||
Blockly.Variables.NAME_TYPE);
|
||||
}
|
||||
var code = 'function ' + funcName + '(' + args.join(', ') + ') {\n' +
|
||||
branch + returnValue + '}';
|
||||
code = Blockly.JavaScript.scrub_(block, code);
|
||||
Blockly.JavaScript.definitions_[funcName] = code;
|
||||
return null;
|
||||
};
|
||||
|
||||
// Defining a procedure without a return value uses the same generator as
|
||||
// a procedure with a return value.
|
||||
Blockly.JavaScript['procedures_defnoreturn'] =
|
||||
Blockly.JavaScript['procedures_defreturn'];
|
||||
|
||||
Blockly.JavaScript['procedures_callreturn'] = function(block) {
|
||||
// Call a procedure with a return value.
|
||||
var funcName = Blockly.JavaScript.variableDB_.getName(
|
||||
block.getTitleValue('NAME'), Blockly.Procedures.NAME_TYPE);
|
||||
var args = [];
|
||||
for (var x = 0; x < block.arguments_.length; x++) {
|
||||
args[x] = Blockly.JavaScript.valueToCode(block, 'ARG' + x,
|
||||
Blockly.JavaScript.ORDER_COMMA) || 'null';
|
||||
}
|
||||
var code = funcName + '(' + args.join(', ') + ')';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['procedures_callnoreturn'] = function(block) {
|
||||
// Call a procedure with no return value.
|
||||
var funcName = Blockly.JavaScript.variableDB_.getName(
|
||||
block.getTitleValue('NAME'), Blockly.Procedures.NAME_TYPE);
|
||||
var args = [];
|
||||
for (var x = 0; x < block.arguments_.length; x++) {
|
||||
args[x] = Blockly.JavaScript.valueToCode(block, 'ARG' + x,
|
||||
Blockly.JavaScript.ORDER_COMMA) || 'null';
|
||||
}
|
||||
var code = funcName + '(' + args.join(', ') + ');\n';
|
||||
return code;
|
||||
};
|
||||
|
||||
Blockly.JavaScript['procedures_ifreturn'] = function(block) {
|
||||
// Conditionally return value from a procedure.
|
||||
var condition = Blockly.JavaScript.valueToCode(block, 'CONDITION',
|
||||
Blockly.JavaScript.ORDER_NONE) || 'false';
|
||||
var code = 'if (' + condition + ') {\n';
|
||||
if (block.hasReturnValue_) {
|
||||
var value = Blockly.JavaScript.valueToCode(block, 'VALUE',
|
||||
Blockly.JavaScript.ORDER_NONE) || 'null';
|
||||
code += ' return ' + value + ';\n';
|
||||
} else {
|
||||
code += ' return;\n';
|
||||
}
|
||||
code += '}\n';
|
||||
return code;
|
||||
};
|
||||
260
generators/javascript/text.js
Normal file
260
generators/javascript/text.js
Normal file
@@ -0,0 +1,260 @@
|
||||
/**
|
||||
* 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 JavaScript for text blocks.
|
||||
* @author fraser@google.com (Neil Fraser)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.JavaScript.text');
|
||||
|
||||
goog.require('Blockly.JavaScript');
|
||||
|
||||
|
||||
Blockly.JavaScript['text'] = function(block) {
|
||||
// Text value.
|
||||
var code = Blockly.JavaScript.quote_(block.getTitleValue('TEXT'));
|
||||
return [code, Blockly.JavaScript.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['text_join'] = function(block) {
|
||||
// Create a string made up of any number of elements of any type.
|
||||
var code;
|
||||
if (block.itemCount_ == 0) {
|
||||
return ['\'\'', Blockly.JavaScript.ORDER_ATOMIC];
|
||||
} else if (block.itemCount_ == 1) {
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'ADD0',
|
||||
Blockly.JavaScript.ORDER_NONE) || '\'\'';
|
||||
code = 'String(' + argument0 + ')';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
} else if (block.itemCount_ == 2) {
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'ADD0',
|
||||
Blockly.JavaScript.ORDER_NONE) || '\'\'';
|
||||
var argument1 = Blockly.JavaScript.valueToCode(block, 'ADD1',
|
||||
Blockly.JavaScript.ORDER_NONE) || '\'\'';
|
||||
code = 'String(' + argument0 + ') + String(' + argument1 + ')';
|
||||
return [code, Blockly.JavaScript.ORDER_ADDITION];
|
||||
} else {
|
||||
code = new Array(block.itemCount_);
|
||||
for (var n = 0; n < block.itemCount_; n++) {
|
||||
code[n] = Blockly.JavaScript.valueToCode(block, 'ADD' + n,
|
||||
Blockly.JavaScript.ORDER_COMMA) || '\'\'';
|
||||
}
|
||||
code = '[' + code.join(',') + '].join(\'\')';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
}
|
||||
};
|
||||
|
||||
Blockly.JavaScript['text_append'] = function(block) {
|
||||
// Append to a variable in place.
|
||||
var varName = Blockly.JavaScript.variableDB_.getName(
|
||||
block.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'TEXT',
|
||||
Blockly.JavaScript.ORDER_NONE) || '\'\'';
|
||||
return varName + ' = String(' + varName + ') + String(' + argument0 + ');\n';
|
||||
};
|
||||
|
||||
Blockly.JavaScript['text_length'] = function(block) {
|
||||
// String length.
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
|
||||
Blockly.JavaScript.ORDER_FUNCTION_CALL) || '\'\'';
|
||||
return [argument0 + '.length', Blockly.JavaScript.ORDER_MEMBER];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['text_isEmpty'] = function(block) {
|
||||
// Is the string null?
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '\'\'';
|
||||
return ['!' + argument0, Blockly.JavaScript.ORDER_LOGICAL_NOT];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['text_indexOf'] = function(block) {
|
||||
// Search the text for a substring.
|
||||
var operator = block.getTitleValue('END') == 'FIRST' ?
|
||||
'indexOf' : 'lastIndexOf';
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'FIND',
|
||||
Blockly.JavaScript.ORDER_NONE) || '\'\'';
|
||||
var argument1 = Blockly.JavaScript.valueToCode(block, 'VALUE',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '\'\'';
|
||||
var code = argument1 + '.' + operator + '(' + argument0 + ') + 1';
|
||||
return [code, Blockly.JavaScript.ORDER_MEMBER];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['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.JavaScript.valueToCode(block, 'AT',
|
||||
Blockly.JavaScript.ORDER_UNARY_NEGATION) || '1';
|
||||
var text = Blockly.JavaScript.valueToCode(block, 'VALUE',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '\'\'';
|
||||
switch (where) {
|
||||
case 'FIRST':
|
||||
var code = text + '.charAt(0)';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
case 'LAST':
|
||||
var code = text + '.slice(-1)';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
case 'FROM_START':
|
||||
// Blockly uses one-based indicies.
|
||||
if (Blockly.isNumber(at)) {
|
||||
// If the index is a naked number, decrement it right now.
|
||||
at = parseFloat(at) - 1;
|
||||
} else {
|
||||
// If the index is dynamic, decrement it in code.
|
||||
at += ' - 1';
|
||||
}
|
||||
var code = text + '.charAt(' + at + ')';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
case 'FROM_END':
|
||||
var code = text + '.slice(-' + at + ').charAt(0)';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
case 'RANDOM':
|
||||
if (!Blockly.JavaScript.definitions_['text_random_letter']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'text_random_letter', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.text_charAt.text_random_letter = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(text) {');
|
||||
func.push(' var x = Math.floor(Math.random() * text.length);');
|
||||
func.push(' return text[x];');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['text_random_letter'] = func.join('\n');
|
||||
}
|
||||
code = Blockly.JavaScript.text_charAt.text_random_letter +
|
||||
'(' + text + ')';
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
}
|
||||
throw 'Unhandled option (text_charAt).';
|
||||
};
|
||||
|
||||
Blockly.JavaScript['text_getSubstring'] = function(block) {
|
||||
// Get substring.
|
||||
var text = Blockly.JavaScript.valueToCode(block, 'STRING',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '[]';
|
||||
var where1 = block.getTitleValue('WHERE1');
|
||||
var where2 = block.getTitleValue('WHERE2');
|
||||
var at1 = Blockly.JavaScript.valueToCode(block, 'AT1',
|
||||
Blockly.JavaScript.ORDER_NONE) || '1';
|
||||
var at2 = Blockly.JavaScript.valueToCode(block, 'AT2',
|
||||
Blockly.JavaScript.ORDER_NONE) || '1';
|
||||
if (where1 == 'FIRST' && where2 == 'LAST') {
|
||||
var code = text;
|
||||
} else {
|
||||
if (!Blockly.JavaScript.definitions_['text_get_substring']) {
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'text_get_substring', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.text_getSubstring.func = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName +
|
||||
'(text, where1, at1, where2, at2) {');
|
||||
func.push(' function getAt(where, at) {');
|
||||
func.push(' if (where == \'FROM_START\') {');
|
||||
func.push(' at--;');
|
||||
func.push(' } else if (where == \'FROM_END\') {');
|
||||
func.push(' at = text.length - at;');
|
||||
func.push(' } else if (where == \'FIRST\') {');
|
||||
func.push(' at = 0;');
|
||||
func.push(' } else if (where == \'LAST\') {');
|
||||
func.push(' at = text.length - 1;');
|
||||
func.push(' } else {');
|
||||
func.push(' throw \'Unhandled option (text_getSubstring).\';');
|
||||
func.push(' }');
|
||||
func.push(' return at;');
|
||||
func.push(' }');
|
||||
func.push(' at1 = getAt(where1, at1);');
|
||||
func.push(' at2 = getAt(where2, at2) + 1;');
|
||||
func.push(' return text.slice(at1, at2);');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['text_get_substring'] =
|
||||
func.join('\n');
|
||||
}
|
||||
var code = Blockly.JavaScript.text_getSubstring.func + '(' + text + ', \'' +
|
||||
where1 + '\', ' + at1 + ', \'' + where2 + '\', ' + at2 + ')';
|
||||
}
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['text_changeCase'] = function(block) {
|
||||
// Change capitalization.
|
||||
var OPERATORS = {
|
||||
UPPERCASE: '.toUpperCase()',
|
||||
LOWERCASE: '.toLowerCase()',
|
||||
TITLECASE: null
|
||||
};
|
||||
var operator = OPERATORS[block.getTitleValue('CASE')];
|
||||
var code;
|
||||
if (operator) {
|
||||
// Upper and lower case are functions built into JavaScript.
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'TEXT',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '\'\'';
|
||||
code = argument0 + operator;
|
||||
} else {
|
||||
if (!Blockly.JavaScript.definitions_['text_toTitleCase']) {
|
||||
// Title case is not a native JavaScript function. Define one.
|
||||
var functionName = Blockly.JavaScript.variableDB_.getDistinctName(
|
||||
'text_toTitleCase', Blockly.Generator.NAME_TYPE);
|
||||
Blockly.JavaScript.text_changeCase.toTitleCase = functionName;
|
||||
var func = [];
|
||||
func.push('function ' + functionName + '(str) {');
|
||||
func.push(' return str.replace(/\\S+/g,');
|
||||
func.push(' function(txt) {return txt[0].toUpperCase() + ' +
|
||||
'txt.substring(1).toLowerCase();});');
|
||||
func.push('}');
|
||||
Blockly.JavaScript.definitions_['text_toTitleCase'] = func.join('\n');
|
||||
}
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'TEXT',
|
||||
Blockly.JavaScript.ORDER_NONE) || '\'\'';
|
||||
code = Blockly.JavaScript.text_changeCase.toTitleCase +
|
||||
'(' + argument0 + ')';
|
||||
}
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['text_trim'] = function(block) {
|
||||
// Trim spaces.
|
||||
var OPERATORS = {
|
||||
LEFT: '.trimLeft()',
|
||||
RIGHT: '.trimRight()',
|
||||
BOTH: '.trim()'
|
||||
};
|
||||
var operator = OPERATORS[block.getTitleValue('MODE')];
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'TEXT',
|
||||
Blockly.JavaScript.ORDER_MEMBER) || '\'\'';
|
||||
return [argument0 + operator, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['text_print'] = function(block) {
|
||||
// Print statement.
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'TEXT',
|
||||
Blockly.JavaScript.ORDER_NONE) || '\'\'';
|
||||
return 'window.alert(' + argument0 + ');\n';
|
||||
};
|
||||
|
||||
Blockly.JavaScript['text_prompt'] = function(block) {
|
||||
// Prompt function.
|
||||
var msg = Blockly.JavaScript.quote_(block.getTitleValue('TEXT'));
|
||||
var code = 'window.prompt(' + msg + ')';
|
||||
var toNumber = block.getTitleValue('TYPE') == 'NUMBER';
|
||||
if (toNumber) {
|
||||
code = 'parseFloat(' + code + ')';
|
||||
}
|
||||
return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL];
|
||||
};
|
||||
45
generators/javascript/variables.js
Normal file
45
generators/javascript/variables.js
Normal 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 JavaScript for variable blocks.
|
||||
* @author fraser@google.com (Neil Fraser)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.JavaScript.variables');
|
||||
|
||||
goog.require('Blockly.JavaScript');
|
||||
|
||||
|
||||
Blockly.JavaScript['variables_get'] = function(block) {
|
||||
// Variable getter.
|
||||
var code = Blockly.JavaScript.variableDB_.getName(block.getTitleValue('VAR'),
|
||||
Blockly.Variables.NAME_TYPE);
|
||||
return [code, Blockly.JavaScript.ORDER_ATOMIC];
|
||||
};
|
||||
|
||||
Blockly.JavaScript['variables_set'] = function(block) {
|
||||
// Variable setter.
|
||||
var argument0 = Blockly.JavaScript.valueToCode(block, 'VALUE',
|
||||
Blockly.JavaScript.ORDER_ASSIGNMENT) || '0';
|
||||
var varName = Blockly.JavaScript.variableDB_.getName(
|
||||
block.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
|
||||
return varName + ' = ' + argument0 + ';\n';
|
||||
};
|
||||
237
generators/python.js
Normal file
237
generators/python.js
Normal file
@@ -0,0 +1,237 @@
|
||||
/**
|
||||
* 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 Helper functions for generating Python for blocks.
|
||||
* @author fraser@google.com (Neil Fraser)
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
goog.provide('Blockly.Python');
|
||||
|
||||
goog.require('Blockly.Generator');
|
||||
|
||||
|
||||
Blockly.Python = new Blockly.Generator('Python');
|
||||
|
||||
/**
|
||||
* List of illegal variable names.
|
||||
* This is not intended to be a security feature. Blockly is 100% client-side,
|
||||
* so bypassing this list is trivial. This is intended to prevent users from
|
||||
* accidentally clobbering a built-in object or function.
|
||||
* @private
|
||||
*/
|
||||
Blockly.Python.addReservedWords(
|
||||
// import keyword
|
||||
// print ','.join(keyword.kwlist)
|
||||
// http://docs.python.org/reference/lexical_analysis.html#keywords
|
||||
'and,as,assert,break,class,continue,def,del,elif,else,except,exec,finally,for,from,global,if,import,in,is,lambda,not,or,pass,print,raise,return,try,while,with,yield,' +
|
||||
//http://docs.python.org/library/constants.html
|
||||
'True,False,None,NotImplemented,Ellipsis,__debug__,quit,exit,copyright,license,credits,' +
|
||||
// http://docs.python.org/library/functions.html
|
||||
'abs,divmod,input,open,staticmethod,all,enumerate,int,ord,str,any,eval,isinstance,pow,sum,basestring,execfile,issubclass,print,super,bin,file,iter,property,tuple,bool,filter,len,range,type,bytearray,float,list,raw_input,unichr,callable,format,locals,reduce,unicode,chr,frozenset,long,reload,vars,classmethod,getattr,map,repr,xrange,cmp,globals,max,reversed,zip,compile,hasattr,memoryview,round,__import__,complex,hash,min,set,apply,delattr,help,next,setattr,buffer,dict,hex,object,slice,coerce,dir,id,oct,sorted,intern');
|
||||
|
||||
/**
|
||||
* Order of operation ENUMs.
|
||||
* http://docs.python.org/reference/expressions.html#summary
|
||||
*/
|
||||
Blockly.Python.ORDER_ATOMIC = 0; // 0 "" ...
|
||||
Blockly.Python.ORDER_COLLECTION = 1; // tuples, lists, dictionaries
|
||||
Blockly.Python.ORDER_STRING_CONVERSION = 1; // `expression...`
|
||||
Blockly.Python.ORDER_MEMBER = 2; // . []
|
||||
Blockly.Python.ORDER_FUNCTION_CALL = 2; // ()
|
||||
Blockly.Python.ORDER_EXPONENTIATION = 3; // **
|
||||
Blockly.Python.ORDER_UNARY_SIGN = 4; // + -
|
||||
Blockly.Python.ORDER_BITWISE_NOT = 4; // ~
|
||||
Blockly.Python.ORDER_MULTIPLICATIVE = 5; // * / // %
|
||||
Blockly.Python.ORDER_ADDITIVE = 6; // + -
|
||||
Blockly.Python.ORDER_BITWISE_SHIFT = 7; // << >>
|
||||
Blockly.Python.ORDER_BITWISE_AND = 8; // &
|
||||
Blockly.Python.ORDER_BITWISE_XOR = 9; // ^
|
||||
Blockly.Python.ORDER_BITWISE_OR = 10; // |
|
||||
Blockly.Python.ORDER_RELATIONAL = 11; // in, not in, is, is not,
|
||||
// <, <=, >, >=, <>, !=, ==
|
||||
Blockly.Python.ORDER_LOGICAL_NOT = 12; // not
|
||||
Blockly.Python.ORDER_LOGICAL_AND = 13; // and
|
||||
Blockly.Python.ORDER_LOGICAL_OR = 14; // or
|
||||
Blockly.Python.ORDER_CONDITIONAL = 15; // if else
|
||||
Blockly.Python.ORDER_LAMBDA = 16; // lambda
|
||||
Blockly.Python.ORDER_NONE = 99; // (...)
|
||||
|
||||
/**
|
||||
* Arbitrary code to inject into locations that risk causing infinite loops.
|
||||
* Any instances of '%1' will be replaced by the block ID that failed.
|
||||
* E.g. ' checkTimeout(%1)\n'
|
||||
* @type ?string
|
||||
*/
|
||||
Blockly.Python.INFINITE_LOOP_TRAP = null;
|
||||
|
||||
/**
|
||||
* This is used as a placeholder in functions defined using
|
||||
* Blockly.Python.provideFunction_. It must not be legal code that could
|
||||
* legitimately appear in a function definition (or comment), and it must
|
||||
* not confuse the regular expression parser.
|
||||
*/
|
||||
Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ = '{{{}}}';
|
||||
Blockly.Python.FUNCTION_NAME_PLACEHOLDER_REGEXP_ =
|
||||
new RegExp(Blockly.Python.FUNCTION_NAME_PLACEHOLDER_, 'g');
|
||||
|
||||
/**
|
||||
* Initialise the database of variable names.
|
||||
*/
|
||||
Blockly.Python.init = function() {
|
||||
// Create a dictionary of definitions to be printed before the code.
|
||||
Blockly.Python.definitions_ = Object.create(null);
|
||||
// Create a dictionary mapping desired function names in definitions_
|
||||
// to actual function names (to avoid collisions with user functions).
|
||||
Blockly.Python.functionNames_ = Object.create(null);
|
||||
|
||||
if (Blockly.Variables) {
|
||||
if (!Blockly.Python.variableDB_) {
|
||||
Blockly.Python.variableDB_ =
|
||||
new Blockly.Names(Blockly.Python.RESERVED_WORDS_);
|
||||
} else {
|
||||
Blockly.Python.variableDB_.reset();
|
||||
}
|
||||
|
||||
var defvars = [];
|
||||
var variables = Blockly.Variables.allVariables();
|
||||
for (var x = 0; x < variables.length; x++) {
|
||||
defvars[x] = Blockly.Python.variableDB_.getName(variables[x],
|
||||
Blockly.Variables.NAME_TYPE) + ' = None';
|
||||
}
|
||||
Blockly.Python.definitions_['variables'] = defvars.join('\n');
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Prepend the generated code with the variable definitions.
|
||||
* @param {string} code Generated code.
|
||||
* @return {string} Completed code.
|
||||
*/
|
||||
Blockly.Python.finish = function(code) {
|
||||
// Convert the definitions dictionary into a list.
|
||||
var imports = [];
|
||||
var definitions = [];
|
||||
for (var name in Blockly.Python.definitions_) {
|
||||
var def = Blockly.Python.definitions_[name];
|
||||
if (def.match(/^(from\s+\S+\s+)?import\s+\S+/)) {
|
||||
imports.push(def);
|
||||
} else {
|
||||
definitions.push(def);
|
||||
}
|
||||
}
|
||||
var allDefs = imports.join('\n') + '\n\n' + definitions.join('\n\n');
|
||||
return allDefs.replace(/\n\n+/g, '\n\n').replace(/\n*$/, '\n\n\n') + code;
|
||||
};
|
||||
|
||||
/**
|
||||
* Naked values are top-level blocks with outputs that aren't plugged into
|
||||
* anything.
|
||||
* @param {string} line Line of generated code.
|
||||
* @return {string} Legal line of code.
|
||||
*/
|
||||
Blockly.Python.scrubNakedValue = function(line) {
|
||||
return line + '\n';
|
||||
};
|
||||
|
||||
/**
|
||||
* Encode a string as a properly escaped Python string, complete with quotes.
|
||||
* @param {string} string Text to encode.
|
||||
* @return {string} Python string.
|
||||
* @private
|
||||
*/
|
||||
Blockly.Python.quote_ = function(string) {
|
||||
// TODO: This is a quick hack. Replace with goog.string.quote
|
||||
string = string.replace(/\\/g, '\\\\')
|
||||
.replace(/\n/g, '\\\n')
|
||||
.replace(/\%/g, '\\%')
|
||||
.replace(/'/g, '\\\'');
|
||||
return '\'' + string + '\'';
|
||||
};
|
||||
|
||||
/**
|
||||
* Common tasks for generating Python from blocks.
|
||||
* Handles comments for the specified block and any connected value blocks.
|
||||
* Calls any statements following this block.
|
||||
* @param {!Blockly.Block} block The current block.
|
||||
* @param {string} code The Python code created for this block.
|
||||
* @return {string} Python code with comments and subsequent blocks added.
|
||||
* @this {Blockly.CodeGenerator}
|
||||
* @private
|
||||
*/
|
||||
Blockly.Python.scrub_ = function(block, code) {
|
||||
if (code === null) {
|
||||
// Block has handled code generation itself.
|
||||
return '';
|
||||
}
|
||||
var commentCode = '';
|
||||
// Only collect comments for blocks that aren't inline.
|
||||
if (!block.outputConnection || !block.outputConnection.targetConnection) {
|
||||
// Collect comment for this block.
|
||||
var comment = block.getCommentText();
|
||||
if (comment) {
|
||||
commentCode += this.prefixLines(comment, '# ') + '\n';
|
||||
}
|
||||
// Collect comments for all value arguments.
|
||||
// Don't collect comments for nested statements.
|
||||
for (var x = 0; x < block.inputList.length; x++) {
|
||||
if (block.inputList[x].type == Blockly.INPUT_VALUE) {
|
||||
var childBlock = block.inputList[x].connection.targetBlock();
|
||||
if (childBlock) {
|
||||
var comment = this.allNestedComments(childBlock);
|
||||
if (comment) {
|
||||
commentCode += this.prefixLines(comment, '# ');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
|
||||
var nextCode = this.blockToCode(nextBlock);
|
||||
return commentCode + code + nextCode;
|
||||
};
|
||||
|
||||
/**
|
||||
* Define a function to be included in the generated code.
|
||||
* The first time this is called with a given desiredName, the code is
|
||||
* saved and an actual name is generated. Subsequent calls with the
|
||||
* same desiredName have no effect but have the same return value.
|
||||
*
|
||||
* It is up to the caller to make sure the same desiredName is not
|
||||
* used for different code values.
|
||||
*
|
||||
* The code gets output when Blockly.Python.finish() is called.
|
||||
*
|
||||
* @param {string} desiredName The desired name of the function (e.g., isPrime).
|
||||
* @param {code} A list of Python statements.
|
||||
* @return {string} The actual name of the new function. This may differ
|
||||
* from desiredName if the former has already been taken by the user.
|
||||
* @private
|
||||
*/
|
||||
Blockly.Python.provideFunction_ = function(desiredName, code) {
|
||||
if (!Blockly.Python.definitions_[desiredName]) {
|
||||
var functionName = Blockly.Python.variableDB_.getDistinctName(
|
||||
desiredName, Blockly.Generator.NAME_TYPE);
|
||||
Blockly.Python.functionNames_[desiredName] = functionName;
|
||||
Blockly.Python.definitions_[desiredName] = code.join('\n').replace(
|
||||
Blockly.Python.FUNCTION_NAME_PLACEHOLDER_REGEXP_, functionName);
|
||||
}
|
||||
return Blockly.Python.functionNames_[desiredName];
|
||||
};
|
||||
85
generators/python/colour.js
Normal file
85
generators/python/colour.js
Normal 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
312
generators/python/lists.js
Normal 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
123
generators/python/logic.js
Normal 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
227
generators/python/loops.js
Normal 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
371
generators/python/math.js
Normal 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];
|
||||
};
|
||||
117
generators/python/procedures.js
Normal file
117
generators/python/procedures.js
Normal 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
252
generators/python/text.js
Normal 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];
|
||||
};
|
||||
45
generators/python/variables.js
Normal file
45
generators/python/variables.js
Normal 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';
|
||||
};
|
||||
Reference in New Issue
Block a user