├── .eslintignore ├── .eslintrc.json ├── .gitignore ├── .npmignore ├── API.md ├── LICENCE ├── README-CN.md ├── README.md ├── bin └── ssc.js ├── package.json ├── scripts └── gendoc.js ├── src ├── code │ ├── argType.js │ ├── blockType.js │ ├── blocks │ │ ├── control.js │ │ ├── data.js │ │ ├── events.js │ │ ├── index.js │ │ ├── looks.js │ │ ├── motion.js │ │ ├── operators.js │ │ ├── sensing.js │ │ └── sound.js │ ├── generator.js │ ├── grammar.ne │ ├── index.js │ ├── inputType.js │ ├── parser.js │ └── uid.js ├── index.js ├── index.node.js ├── playground │ ├── default.sb3 │ ├── index.html │ └── playground.js └── project │ ├── emptyAudio.js │ ├── emptySvg.js │ ├── parser.js │ └── schema.js ├── test └── test │ └── test.js ├── webpack.config.js └── yarn.lock /.eslintignore: -------------------------------------------------------------------------------- 1 | dist/* 2 | node_modules/* -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "es6": true, 4 | "node": true 5 | }, 6 | "extends": [ 7 | "standard" 8 | ], 9 | "globals": { 10 | "Atomics": "readonly", 11 | "SharedArrayBuffer": "readonly" 12 | }, 13 | "rules": { 14 | "indent": [2, 4] 15 | } 16 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | /dist 3 | /playground 4 | /.vscode 5 | railroad.html 6 | yarn-error.log -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | test/ 3 | build/ 4 | playground/ 5 | railroad.html 6 | yarn-error.log 7 | src/code/nearley/index.ne 8 | .eslintrc.json 9 | .gitignore 10 | yarn-error.log -------------------------------------------------------------------------------- /API.md: -------------------------------------------------------------------------------- 1 | # ScratchScript Core Block API Reference 2 | Generated by [scripts/gendoc.js](scripts/gendoc.js) 3 | Package Version: 0.1.10 4 | Generate Date: 7/22/2020, 4:31:42 PM 5 | ## Index 6 | 1. [Motion](#Motion) 7 | 2. [Looks](#Looks) 8 | 3. [Sound](#Sound) 9 | 4. [Events](#Events) 10 | 5. [Control](#Control) 11 | 6. [Sensing](#Sensing) 12 | 7. [Operators](#Operators) 13 | 8. [Data](#Data) 14 | ## Motion 15 | [Return To Index](#Index) 16 | ID: `motion` 17 | ### `walkStep(STEPS: Number): void` 18 | Reference to `motion_movesteps`. 19 | ### `turnRight(DEGREES: Number): void` 20 | Reference to `motion_turnright`. 21 | ### `turnLeft(DEGREES: Number): void` 22 | Reference to `motion_turnleft`. 23 | ### `goTo(TO: Menu): void` 24 | Reference to `motion_goto`. 25 | ### `goToPos(X: Number, Y: Number): void` 26 | Reference to `motion_gotoxy`. 27 | ### `glideTo(SECS: Number, TO: Menu): void` 28 | Reference to `motion_glideto`. 29 | ### `glideToPos(SECS: Number, X: Number, Y: Number): void` 30 | Reference to `motion_glidesecstoxy`. 31 | ### `setDirection(DIRECTION: Menu): void` 32 | Reference to `motion_pointindirection`. 33 | ### `towards(TOWARDS: Menu): void` 34 | Reference to `motion_pointtowards`. 35 | ### `changeX(DX: Number): void` 36 | Reference to `motion_changexby`. 37 | ### `setX(X: Number): void` 38 | Reference to `motion_setx`. 39 | ### `changeY(DY: Number): void` 40 | Reference to `motion_changeyby`. 41 | ### `setY(Y: Number): void` 42 | Reference to `motion_sety`. 43 | ### `ifOnEdgeBounce(): void` 44 | Reference to `motion_ifonedgebounce`. 45 | ### `setRotationStyle(Y: Number): void` 46 | Reference to `motion_setrotationstyle`. 47 | ### `x(): any` 48 | Reference to `motion_xposition`. 49 | ### `y(): any` 50 | Reference to `motion_yposition`. 51 | ### `direction(): any` 52 | Reference to `motion_direction`. 53 | ## Looks 54 | [Return To Index](#Index) 55 | ID: `looks` 56 | ### `sayFor(MESSAGE: String, SECS: Number): void` 57 | Reference to `looks_sayforsecs`. 58 | ### `say(MESSAGE: String): void` 59 | Reference to `looks_say`. 60 | ### `thinkFor(MESSAGE: String, SECS: Number): void` 61 | Reference to `looks_thinkforsecs`. 62 | ### `think(MESSAGE: String): void` 63 | Reference to `looks_think`. 64 | ### `switchCostume(COSTUME: Menu): void` 65 | Reference to `looks_switchcostumeto`. 66 | ### `nextCostume(): void` 67 | Reference to `looks_nextcostume`. 68 | ### `switchbackdropto(BACKDROP: Menu): void` 69 | Reference to `looks_switchbackdropto`. 70 | ### `nextBackdrop(): void` 71 | Reference to `looks_nextbackdrop`. 72 | ### `addSize(CHANGE: Number): void` 73 | Reference to `looks_changesizeby`. 74 | ### `setSize(SIZE: Number): void` 75 | Reference to `looks_setsizeto`. 76 | ### `clearGraphicEffects(): void` 77 | Reference to `looks_cleargraphiceffects`. 78 | ### `show(NUM: Menu): void` 79 | Reference to `looks_show`. 80 | ### `hide(NUM: Menu): void` 81 | Reference to `looks_hide`. 82 | ### `gotofrontback(NUM: Number): void` 83 | Reference to `looks_gotofrontback`. 84 | ### `goforwardbackwardlayers(NUM: Menu): void` 85 | Reference to `looks_goforwardbackwardlayers`. 86 | ### `costumenumbername(): void` 87 | Reference to `looks_costumenumbername`. 88 | ### `backdropnumbername(): any` 89 | Reference to `looks_backdropnumbername`. 90 | ### `size(): any` 91 | Reference to `looks_size`. 92 | ### `setColorEffect(VALUE: Number): void` 93 | Set color effect to a number. 94 | ### `changeColorEffect(CHANGE: Number): void` 95 | Change color effect by a number. 96 | ### `setFisheyeEffect(VALUE: Number): void` 97 | Set fisheye effect to a number. 98 | ### `changeFisheyeEffect(CHANGE: Number): void` 99 | Change fisheye effect by a number. 100 | ### `setWhirlEffect(VALUE: Number): void` 101 | Set whirl effect to a number. 102 | ### `changeWhirlEffect(CHANGE: Number): void` 103 | Change whirl effect by a number. 104 | ### `setPixelateEffect(VALUE: Number): void` 105 | Set pixelate effect to a number. 106 | ### `changePixelateEffect(CHANGE: Number): void` 107 | Change pixelate effect by a number. 108 | ### `setMosaicEffect(VALUE: Number): void` 109 | Set mosaic effect to a number. 110 | ### `changeMosaicEffect(CHANGE: Number): void` 111 | Change mosaic effect by a number. 112 | ### `setBrightnessEffect(VALUE: Number): void` 113 | Set brightness effect to a number. 114 | ### `changeBrightnessEffect(CHANGE: Number): void` 115 | Change brightness effect by a number. 116 | ## Sound 117 | [Return To Index](#Index) 118 | ID: `sound` 119 | ### `playUntilDone(SOUND_MENU: Menu): void` 120 | Reference to `sound_playuntildone`. 121 | ### `play(SOUND_MENU: Menu): void` 122 | Reference to `sound_play`. 123 | ### `stopAllSounds(): void` 124 | Reference to `sound_stopallsounds`. 125 | ### `changeeffectby(EFFECT: Menu, VALUE: Number): void` 126 | Reference to `sound_changeeffectby`. 127 | ### `setEffect(EFFECT: Menu, VALUE: Number): void` 128 | Reference to `sound_seteffectto`. 129 | ### `clearEffects(): void` 130 | Reference to `sound_cleareffects`. 131 | ### `addVolume(VOLUME: Number): void` 132 | Reference to `sound_changevolumeby`. 133 | ### `setVolume(VOLUME: Number): void` 134 | Reference to `sound_setvolumeto`. 135 | ### `volume(): any` 136 | Reference to `sound_volume`. 137 | ## Events 138 | [Return To Index](#Index) 139 | ID: `events` 140 | ### `flagClicked(): any` 141 | Reference to `event_whenflagclicked`. 142 | ### `keyPressed(KEY_OPTION: Menu): any` 143 | Reference to `event_whenkeypressed`. 144 | ### `clicked(): any` 145 | Reference to `event_whenthisspriteclicked`. 146 | ### `backdropSwitchesTo(BROADCAST_INPUT: Broadcast): any` 147 | Reference to `event_whenbackdropswitchesto`. 148 | ### `greaterThan(VALUE: Number): any` 149 | Reference to `event_whengreaterthan`. 150 | ### `broadcastReceived(BROADCAST_OPTION: Broadcast): any` 151 | Reference to `event_whenbroadcastreceived`. 152 | ### `broadcast(BROADCAST_INPUT: Broadcast): void` 153 | Reference to `event_broadcast`. 154 | ### `broadcastAndWait(BROADCAST_INPUT: Broadcast): void` 155 | Reference to `event_broadcastandwait`. 156 | ## Control 157 | [Return To Index](#Index) 158 | ID: `control` 159 | ### `wait(DURATION: PositiveNumber): void` 160 | Reference to `control_wait`. 161 | ### `repeat(TIMES: Integer) { 1 }: void` 162 | Reference to `control_repeat`. 163 | ### `forever() { 1 }: void` 164 | Reference to `control_forever`. 165 | ### `if(CONDITION: Boolean) { 1 }: void` 166 | Reference to `control_if`. 167 | ### `ifelse(CONDITION: Boolean) { 2 }: void` 168 | Reference to `control_if_else`. 169 | ### `waitUntil(CONDITION: Boolean): void` 170 | Reference to `control_wait_until`. 171 | ### `repeatUntil(CONDITION: Boolean) { 1 }: void` 172 | Reference to `control_repeat_until`. 173 | ### `forEach(VARIABLE: Variable, VALUE: Integer): void` 174 | Reference to `control_for_each`. 175 | ### `stop(STOP_OPTION: Menu): void` 176 | Reference to `control_stop`. 177 | ### `startAsClone(): any` 178 | Reference to `control_start_as_clone`. 179 | ### `cloneSelf(): void` 180 | Reference to `control_create_clone_of`. 181 | ### `clone(CLONE_OPTION: Menu): void` 182 | Reference to `control_create_clone_of`. 183 | ### `deleteThisClone(): void` 184 | Reference to `control_delete_this_clone`. 185 | ### `getCounter(): void` 186 | Reference to `control_get_counter`. 187 | ### `incrCounter(): void` 188 | Reference to `control_incr_counter`. 189 | ### `clearCounter(): void` 190 | Reference to `control_clear_counter`. 191 | ### `allAtOnce() { 1 }: void` 192 | Reference to `control_all_at_once`. 193 | ## Sensing 194 | [Return To Index](#Index) 195 | ID: `sensing` 196 | ### `isTouching(TOUCHINGOBJECTMENU: Menu): any` 197 | Reference to `sensing_touchingobject`. 198 | ### `isTouchingColor(COLOR: Color): any` 199 | Reference to `sensing_touchingcolor`. 200 | ### `isColorTouchingColor(COLOR: Color, COLOR2: Color): any` 201 | Reference to `sensing_coloristouchingcolor`. 202 | ### `distanceTo(DISTANCETOMENU: Menu): any` 203 | Reference to `sensing_distanceto`. 204 | ### `askAndWait(QUESTION: String): void` 205 | Reference to `sensing_askandwait`. 206 | ### `answer(): any` 207 | Reference to `sensing_answer`. 208 | ### `isKeyPressed(KEY_OPTION: Menu): any` 209 | Reference to `sensing_keypressed`. 210 | ### `isMouseDown(): any` 211 | Reference to `sensing_mousedown`. 212 | ### `mouseX(): any` 213 | Reference to `sensing_mousex`. 214 | ### `mouseY(): any` 215 | Reference to `sensing_mousey`. 216 | ### `setDragMode(DRAG_MODE: Menu): void` 217 | Reference to `sensing_setdragmode`. 218 | ### `loudness(): any` 219 | Reference to `sensing_loudness`. 220 | ### `timer(): any` 221 | Reference to `sensing_timer`. 222 | ### `resetTimer(): void` 223 | Reference to `sensing_resettimer`. 224 | ### `ofStage(PROPERTY: String): void` 225 | Reference to `sensing_of`. 226 | ### `of(OBJECT: Menu, PROPERTY: String): void` 227 | Reference to `sensing_of`. 228 | ### `current(CURRENTMENU: Menu): void` 229 | Reference to `sensing_current`. 230 | ### `dayssince2000(): any` 231 | Reference to `sensing_dayssince2000`. 232 | ### `username(): any` 233 | Reference to `sensing_username`. 234 | ## Operators 235 | [Return To Index](#Index) 236 | ID: `math` 237 | ### `add(NUM1: Number, NUM2: Number): any` 238 | Reference to `operator_add`. 239 | ### `subtract(NUM1: Number, NUM2: Number): any` 240 | Reference to `operator_subtract`. 241 | ### `multiply(NUM1: Number, NUM2: Number): any` 242 | Reference to `operator_multiply`. 243 | ### `divide(NUM1: Number, NUM2: Number): any` 244 | Reference to `operator_divide`. 245 | ### `random(FROM: Number, TO: Number): any` 246 | Reference to `operator_random`. 247 | ### `gt(OPERAND1: String, OPERAND2: String): any` 248 | Reference to `operator_gt`. 249 | ### `lt(OPERAND1: String, OPERAND2: String): any` 250 | Reference to `operator_lt`. 251 | ### `equals(OPERAND1: String, OPERAND2: String): any` 252 | Reference to `operator_equals`. 253 | ### `and(OPERAND1: Boolean, OPERAND2: Boolean): any` 254 | Reference to `operator_and`. 255 | ### `or(OPERAND1: Boolean, OPERAND2: Boolean): any` 256 | Reference to `operator_or`. 257 | ### `not(OPERAND: Boolean): any` 258 | Reference to `operator_not`. 259 | ### `join(STRING1: String, STRING2: String): any` 260 | Reference to `operator_join`. 261 | ### `letterOf(LETTER: Integer, STRING: String): any` 262 | Reference to `operator_letter_of`. 263 | ### `length(STRING: String): any` 264 | Reference to `operator_length`. 265 | ### `contains(STRING1: String, STRING2: String): any` 266 | Reference to `operator_contains`. 267 | ### `mod(NUM1: Number, NUM2: Number): any` 268 | Reference to `operator_mod`. 269 | ### `round(NUM: Number): any` 270 | Reference to `operator_round`. 271 | ### `mathop(OPERATOR: Menu, NUM: Number): any` 272 | Reference to `operator_mathop`. 273 | ### `abs(NUM: Number): any` 274 | Reference to `operator_mathop`. 275 | ### `floor(NUM: Number): any` 276 | Reference to `operator_mathop`. 277 | ### `ceil(NUM: Number): any` 278 | Reference to `operator_mathop`. 279 | ### `sqrt(NUM: Number): any` 280 | Reference to `operator_mathop`. 281 | ### `sin(NUM: Number): any` 282 | Reference to `operator_mathop`. 283 | ### `cos(NUM: Number): any` 284 | Reference to `operator_mathop`. 285 | ### `tan(NUM: Number): any` 286 | Reference to `operator_mathop`. 287 | ### `atan(NUM: Number): any` 288 | Reference to `operator_mathop`. 289 | ### `ln(NUM: Number): any` 290 | Reference to `operator_mathop`. 291 | ### `log(NUM: Number): any` 292 | Reference to `operator_mathop`. 293 | ### `e(NUM: Number): any` 294 | Reference to `operator_mathop`. 295 | ### `powerOfTen(NUM: Number): any` 296 | Reference to `operator_mathop`. 297 | ## Data 298 | [Return To Index](#Index) 299 | ID: `data` 300 | ### `setVar(VARIABLE: Variable, VALUE: String): void` 301 | Reference to `data_setvariableto`. 302 | ### `addVar(VARIABLE: Variable, VALUE: String): void` 303 | Reference to `data_changevariableby`. 304 | ### `hideVar(VARIABLE: Variable): void` 305 | Reference to `data_hidevariable`. 306 | ### `showVar(VARIABLE: Variable): void` 307 | Reference to `data_showvariable`. 308 | ### `addItem(LIST: List, ITEM: String): void` 309 | Reference to `data_addtolist`. 310 | ### `deleteItem(LIST: List, INDEX: PositionInteger): void` 311 | Reference to `data_deleteoflist`. 312 | ### `deleteAll(LIST: List): void` 313 | Reference to `data_deletealloflist`. 314 | ### `insertItem(LIST: List, INDEX: PositionInteger, ITEM: String): void` 315 | Reference to `data_insertatlist`. 316 | ### `replaceItem(LIST: List, INDEX: PositionInteger, ITEM: String): void` 317 | Reference to `data_replaceitemoflist`. 318 | ### `itemOfList(LIST: List, INDEX: PositionInteger): any` 319 | Reference to `data_itemoflist`. 320 | ### `indexOfList(LIST: List, ITEM: String): any` 321 | Reference to `data_itemnumoflist`. 322 | ### `lengthOfList(LIST: List, ITEM: String): any` 323 | Reference to `data_lengthoflist`. 324 | ### `containsItem(LIST: List, ITEM: String): any` 325 | Reference to `data_listcontainsitem`. 326 | ### `hideList(LIST: List): void` 327 | Reference to `data_hidelist`. 328 | ### `showList(LIST: List): void` 329 | Reference to `data_showlist`. 330 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README-CN.md: -------------------------------------------------------------------------------- 1 | # ScratchScriptKit 2 | 3 | 一个简约的玩具脚本语言工具包,用于将 Scratch 工程规模化和代码化。 4 | 5 | Chinese 中文 [English](./README.md) 6 | 7 | ScratchScript 示例: 8 | ```lua 9 | var direction = 0; 10 | when events.flagClicked() { 11 | looks.sayFor('Hello ScratchScript!', 3); 12 | forever { 13 | direction = 1; 14 | repeat (10) { 15 | motion.changeY(5 * direction); 16 | } 17 | if (direction == 1) { 18 | direction = -1; 19 | } else { 20 | direction = 1; 21 | } 22 | } 23 | } 24 | ``` 25 | 26 | ## 项目描述文件 27 | 28 | 项目描述文件用于定义各个角色和舞台的初始属性,统一命名 `project.yaml` 或者 `project.json` ,支持 YAML 和 JSON 语法进行描述。 29 | 基本格式如下,JSON 则大同小异: 30 | 31 | ```yaml 32 | # 井号开头为注释 33 | # YAML 使用缩进表达层级关系,详情请搜索 YAML 查询文档 34 | 35 | # 作品描述对象,如无提供则会生成一个干净的空作品文件(只有纯白色无代码舞台) 36 | info: 37 | # 舞台对象,如无提供则会默认添加纯白色无代码舞台 38 | stage: 39 | # 代码属性 40 | code: 41 | # 相对于项目描述文件所在文件夹的代码文件位置,如无提供则无代码 42 | file: ./src/stage.ss 43 | # 当前舞台背景编号,如无提供则默认为 0 44 | costume: 0 45 | # 舞台播放声音的大小 46 | volume: 100 47 | # 舞台背景清单,如无提供则默认添加纯白色背景 48 | costumes: 49 | # 一个减号代表一个背景,按顺序依次编号,从 0 开始。 50 | - 51 | # 背景名称 52 | name: Stage 53 | # 相对于项目描述文件所在文件夹的图像文件位置,允许使用 PNG 图像或 SVG 图像 54 | file: ./asset/stage.png 55 | # 舞台音效清单,如无提供则不添加任何音效 56 | sounds: 57 | # 一个减号代表一个音效,按顺序依次编号,从 0 开始。 58 | - 59 | # 音效名称 60 | name: 流行音乐 61 | # 相对于项目描述文件所在文件夹的音效文件位置,允许使用 WAV 音频和 MP3 音频 62 | file: ./asset/pop.mp3 63 | # 角色清单,如无提供则没有任何角色 64 | sprites: 65 | - 66 | # 角色名称,不允许重复,如不提供或出现冲突则会自动生成一个新名称 67 | name: Cat 68 | # 代码属性 69 | code: 70 | # 相对于项目描述文件所在文件夹的代码文件位置,如无提供则无代码 71 | file: ./src/stage.ss 72 | # 角色播放声音的大小,100 为最大, 0 为无声 73 | volume: 100 74 | # 是否显示角色 75 | visible: true 76 | # 角色的横纵坐标,按照角色中心和舞台坐标系计算 77 | pos: 78 | x: 0 79 | y: 0 80 | # 角色当前的大小,100 为正常大小 81 | size: 100 82 | # 角色当前的旋转角度,90 为向右 83 | direction: 90 84 | # 旋转模式,可选值为 all around, don't rotate, left-right 85 | rotationstyle: all around 86 | # 当前角色造型编号,如无提供则默认为 0 87 | costume: 0 88 | # 角色造型清单,如无提供则默认添加透明造型 89 | costumes: 90 | # 一个减号代表一个造型,按顺序依次编号,从 0 开始。 91 | - 92 | # 造型名称 93 | name: Cat0 94 | # 相对于项目描述文件所在文件夹的图像文件位置,允许使用 PNG 图像或 SVG 图像 95 | file: ./asset/cat.png 96 | # 相对于图像左上角的图像旋转中心点位置,如不提供则默认为图像中心 97 | center: 98 | x: 0 99 | y: 0 100 | # 角色音效清单,如无提供则不添加任何音效 101 | sounds: 102 | # 一个减号代表一个音效,按顺序依次编号,从 0 开始。 103 | - 104 | # 音效名称 105 | name: Meow 106 | # 相对于项目描述文件所在文件夹的音效文件位置,允许使用 WAV 音频和 MP3 音频 107 | file: ./asset/meow.mp3 108 | 109 | ``` 110 | 111 | ## ScratchScript 112 | 113 | ScratchScriptKit 的重要组成部分,使用简单的语法对角色和舞台进行编程的脚本语言。 114 | (有人吐槽这是 Lua,其实的确参考了很多,不过还是和 Lua 有所不同的) 115 | 116 | ### 语法 117 | 118 | #### 数字 119 | 允许正常的正负整数或小数: 120 | 121 | ```javascript 122 | 0 1 20 -1 1.05 -3.14 123 | ``` 124 | 125 | 当然十六进制,二进制,八进制,也是完全可以的,在编译时将会转换成十进制数字: 126 | 127 | ```javascript 128 | 0xAAFFEE // Hex 129 | 07654321 // Oct 130 | 0b100101 // Bin 131 | ``` 132 | 133 | #### 字符串 134 | 使用单引号或双引号开头和结尾: 135 | ```javascript 136 | 'Single' "Double" 137 | ``` 138 | 你可以使用反斜杠(\)进行转义: 139 | 140 | |格式|转义为| 141 | |---|---| 142 | |`\n`|换行符| 143 | |`\\`|反斜杠| 144 | |`\'`|单引号| 145 | |`\"`|双引号| 146 | |`\uxxxx`|(x 为十六进制符号(`[0-9a-fA-f]`))十六进制的 Unicode 编码所对应的任意的 Unicode 字符| 147 | 148 | 注:其实反斜杠后面只要不是 u 都会转译成那个字符(雾) 149 | 150 | #### HEX 颜色值 151 | 152 | 使用井号开头 `#`,后跟 3, 4, 6, 8 个十六进制字符,颜色顺序如下: 153 | (注:R 代表红色,G 代表绿色,B 代表蓝色,A 代表不透明度) 154 | 155 | |格式|颜色顺序| 156 | |---|--------| 157 | |`#XXX`|`#RGB`| 158 | |`#XXXX`|`#RGBA`| 159 | |`#XXXXXX`|`#RRGGBB`| 160 | |`#XXXXXXXX`|`#RRGGBBAA`| 161 | 162 | ```css 163 | #F00 /* Black */ 164 | #F007 /* Half transparent red */ 165 | #FFFFFFFF /* White */ 166 | ``` 167 | 168 | #### 标识符 169 | 170 | 资深用户一条式:`[A-Za-z_][A-Za-z_0-9]*` 171 | 172 | 第一个字符必须为任意大小写字母(A-Z,a-z)或下划线(_), 173 | 之后可跟任意大小写字母,下划线和数字(0-9)进行组合: 174 | ``` 175 | identifier 176 | thisIsAnIdentifier666 177 | IDENTIFIER0 178 | nameWhateverUWant 179 | ``` 180 | 注:不得使用专用关键字作为标识符,下文有列出 181 | 182 | #### 关键字清单 183 | 184 | 请勿将下列关键字用于变量或函数定义。 185 | 186 | ``` 187 | atonce bool define false 188 | for forever if in let 189 | number null register 190 | repeat string true using 191 | var when while 192 | ``` 193 | 194 | #### 注释 195 | 196 | 在两个连续的斜杠后跟的当前行的所有内容都将被编译器忽略,: 197 | 198 | ```c 199 | // Line comment 200 | /* 201 | Block comment 202 | */ 203 | ``` 204 | 205 | #### 分隔符? 206 | 207 | 从例子里你可以看到每个函数执行的后面都加入了分号作为分割符,其实这并非必要,设定这个语法只是为了顺应其他程序员的习惯。 208 | 209 | ```js 210 | // This is okay! 211 | looks.sayFor('Hello ScratchScript!', 3) 212 | // Add semicolon if you want: 213 | looks.sayFor('Hello ScratchScript!', 3); 214 | ``` 215 | 216 | #### 空白 217 | 218 | ScratchScript 不像 Python 使用缩进表达层级关系,所以你大可放心在不造成歧义的情况下写成一行,但是为了可读性还是推荐多用换行和缩进来表达程序结构。 219 | 220 | ```lua 221 | // This still can be compiled! 222 | when events.flagClicked() { looks.sayFor('Hello ScratchScript!', 3); forever { direction = 1; repeat (10) { motion.changeY(5 * direction); } if (direction == 1) { direction = -1; } else { direction = 1; }}} 223 | ``` 224 | 225 | #### 运算符 226 | 227 | 虽然你可以直接通过执行模块的语法来进行运算,但是为了简单,ScratchScript 228 | 基本支持以下简化的算式: 229 | 230 | - 算术运算符 231 | - 加法 `+` 232 | - 减法 `-` 233 | - 乘法 `*` 234 | - 除法 `/` 235 | - 求余 `%` 236 | - 逻辑运算符 237 | - 等于 `==` 238 | - 大于 `>` 239 | - 小于 `<` 240 | - 不成立 `!` 241 | - 逻辑与 `&&` 242 | - 逻辑或 `||` 243 | - 字符串操作 244 | - 连接字符串 `..` 245 | 246 | 如果算式两侧均为常数,则编译器会进行预计算优化,部分数学函数模块也支持预计算优化。 247 | 248 | 运算优先级如下表(数字越高优先级越大): 249 | 250 | 1. 逻辑或 `||` 251 | 2. 逻辑与 `&&` 252 | 2. 大于 `>`, 小于 `<` 253 | 3. 等于 `==` 254 | 3. 连接字符串 `..` 255 | 5. 加减 `+`, `-` 256 | 6. 乘除,求余 `*`, `/`, `%` 257 | 7. 不成立 `!` 258 | 259 | 后续会尝试添加语法糖(自增,大于等于,不等于等)(懒) 260 | 261 | #### 定义变量/列表 262 | 263 | 类似 JavaScript,使用 `var` 开头将创建一个全局(舞台)变量,使用 `let` 开头将创建一个局部(仅角色)变量。 264 | 如果在舞台里使用 `let` 定义变量,则效果和 `var` 一样。后跟一个标识符作为名称,默认该变量为一个普通变量,初始值将决定该变量是普通变量还是列表。如果使用常量字面量或不提供初始值,则默认为普通变量,如果提供以 `[` 和 `]` 包裹的列表,则使用列表类型。 265 | 266 | 列表使用 `[` 和 `]` 包裹,使用逗号 `,` 区分每个项目,每个项目可以使用任意的字面量来表示。 267 | 268 | ```js 269 | var answer = "C" 270 | var answers = [ 271 | "Any type!", 272 | 123 273 | ] 274 | ``` 275 | 276 | 277 | #### 执行模块(函数): 278 | 279 | 执行一个函数的格式为 *类型*.*模块名称*(*参数*) 280 | 如果有多个参数,则使用英文逗号分隔开。 281 | 如果执行的模块是自定义模块,则不需要输入模块类型。 282 | ``` 283 | *Cateory*.*Identifier*(*arguments*); 284 | motion.moveSteps(5); 285 | customBlock('I\'m a custom block!'); 286 | ``` 287 | 288 | #### 触发事件 289 | ``` 290 | when *Cateory*.*Identifier*(*arguments*) { 291 | *Codes* 292 | } 293 | ``` 294 | 295 | #### 条件判断 296 | 对应 Scratch 的 `如果 < > 那么 { }` 模块,当判断参数为 `true` 时则执行内部代码。 297 | 如果在 `if` 和 `}` 之间添加了 `else`,则对应 Scratch 的 `如果 < > 那么 { } 否则 { }`。 298 | 当判断参数为 `true` 时则执行 `if` 和 `else` 之间的代码,否则则执行 `else` 和 `}` 之间的代码。 299 | 虽然 ScratchScript 不限制你使用非布尔值模块,但是为了确保稳健性,建议统一使用布尔值模块。 300 | ```lua 301 | if(*Condition*) { 302 | *Codes* 303 | } 304 | 305 | if(*Condition*) { 306 | *Codes* 307 | } else { 308 | *Codes* 309 | } 310 | ``` 311 | 312 | #### 多分支模块 313 | 314 | 虽然应该没有什么模块会用到多分支,但是因为 Scratch 原代码里有提到,为了兼容性则设计了这个语法。 315 | 在执行函数的下方使用多个 `in` 加一个常量值(通常为数字,代表分支的编号)用于分辨分支类型,如果达成模块要求则会进入该分支,之后将按模块的执行方式继续执行,直到到达结尾的 `}` 结束执行。 316 | 317 | ```lua 318 | *Cateory*.*Identifier*(*arguments*) 319 | in *String or Number* { 320 | *Code* 321 | } in *String or Number* { 322 | *Code* 323 | } 324 | ... 325 | 326 | // Example 327 | ext.switch(value) 328 | in 1 { 329 | looks.say("Hello!"); 330 | } in 2 { 331 | looks.say("Bye!"); 332 | } 333 | ``` 334 | 335 | #### 无限循环 336 | 对应 Scratch 的 `重复执行 { }` 模块,永久重复执行: 337 | ```lua 338 | forever { 339 | *Codes* 340 | } 341 | ``` 342 | 343 | #### 重复执行 344 | 对应 Scratch 的 `重复执行 ( ) 次 { }` 模块,参数为一个正整数,指定循环的次数: 345 | ```lua 346 | repeat (*Times*) { 347 | *Codes* 348 | } 349 | ``` 350 | 351 | #### 条件循环 352 | 353 | 对应 Scratch 的 `重复执行直到 < < > 不成立 > { }` 模块,参数为一个布尔值,当为 `true` 时进行循环。 354 | 目前暂时不限模块类型(懒),但是建议判断时使用布尔值类型的模块,保证生成的代码足够稳定。 355 | 356 | ```lua 357 | while (*Conditions*) { 358 | *Codes* 359 | } 360 | ``` 361 | 362 | #### 计次循环 363 | 364 | 对应 Scratch 的 `对于 [ ] 中的每个 [ ] { }` 模块,将左侧的变量中的值依次设置成 `1` 到右侧的计次数并在改变值后执行循环体。 365 | 虽然 ScratchScript 不限制你使用非数值模块,但是为了确保稳健性,建议统一使用数值模块或数字常量。 366 | ```lua 367 | for (*variable* in *times*) { 368 | *Codes* 369 | } 370 | // Will count from 1 to 10 371 | for (counter in 10) { 372 | looks.sayFor(counter, 1); 373 | } 374 | ``` 375 | 376 | #### 自定义模块(WIP) 377 | 378 | 使用 `define` 关键字作为开头,后跟一个普通的标识符并提供名称,如果需要不刷新舞台,则在 `define` 关键字前添加 `atonce` 关键字。 379 | 380 | ``` 381 | define *Identifier*(*arguments*) { 382 | *Codes* 383 | } 384 | // Will not update the stage! 385 | atonce define *Identifier*(*arguments*) { 386 | *Codes* 387 | } 388 | ``` 389 | 390 | 因为自定义模块存在类型(字符串/数字类型,布尔类型),如果仅声明了参数名称则使用字符串/数字类型作为参数类型。如果参数名后加冒号,再加入以下关键字即可指定参数类型: 391 | - `string` 字符串类型 392 | - `number` 数字类型 393 | - `bool` 布尔值类型 394 | 395 | ``` 396 | // This argument will become a string/number type input. 397 | define stringAndNumberArg1(str) { 398 | // ... 399 | } 400 | 401 | // This argument will become a string type input. 402 | define stringArg(str: string) { 403 | // ... 404 | } 405 | 406 | // This argument will become a number type input. 407 | define numberArg(str: number) { 408 | // ... 409 | } 410 | 411 | // This argument will become a boolean type input. 412 | define boolArg(arg: bool) { 413 | // ... 414 | } 415 | 416 | ``` 417 | 418 | #### 模块引用 419 | 420 | 使用 `using` 关键字后跟一个**静态**字符串,通过相对路径的方式指定模块的位置,其内的模块会被添加到现有代码内,嵌套引用的话只会引用同一个。 421 | 422 | ```C# 423 | using *FilePath* 424 | using './path/to/module.ss' 425 | ``` 426 | 427 | #### 注册扩展 428 | 429 | 使用 `register` 关键字后跟一个**静态**字符串指定拓展模块的文件位置,其内定义的扩展模块将可以在代码内使用,嵌套引用的话会报告编译错误。如果需要引用同名不同功能的模块,则在字符串后面再跟一个 `as` 和一个标识符代表这个模块的新 ID。同种模块的多次不同 ID 引用不会触发编译错误。 430 | 431 | 扩展文件的搜索方式不光有相对目录方式,如果相对目录无法找到模块,编译器还会根据环境变量 `SCRATCHSCRIPT_INCLUDE_DIR` 的相对目录里查询,如果仍然不存在则会报告编译错误。如果你的扩展定义文件格式为 `.js`,你可以选择不写文件后缀名。 432 | 433 | ```js 434 | register *FilePath* 435 | register './path/to/extension.js' 436 | // You can rename extension 437 | register './path/to/extension.js' as new_id 438 | // You can also register it with file path without .js extension name. 439 | // If your extension definition file's extention name is .js . 440 | register './path/to/extension' 441 | ``` 442 | 443 | ## ScratchScript 模块定义文件结构 444 | 445 | 为了能有一定的拓展性,支持外部扩展的非核心模块,这里提供了一个模块定义文件的结构说明文件格式,开发者可使用 `register` 语句进行引用。 446 | 447 | 该文件的本质是一个 JavaScript 脚本,核心模块也采用此模块定义文件结构来支持核心模块,如有需要可以在原代码参考。 448 | 449 | 首先模块的导出类型是一个对象,拥有三个对象: 450 | 451 | - `name` 字符串,可选,表述该扩展的名称。 452 | - `id` 字符串,必需,表述该扩展的 ID,将会作为函数名的一部分。 453 | - `doc` 字符串,可选,该参数的简短文档,用于脚本生成模块文档。 454 | - `description` 字符串,可选,表述该扩展的简单描述。 455 | - `blocks` 数组,必需,列出所有的模块列表,每个数组成员都是一个对象,格式如下: 456 | - `name` 模块的函数名称,将作为函数名后缀的一部分。 457 | - `doc` 字符串,可选,该参数的简短文档,用于脚本生成模块文档。 458 | - `opcode` 模块在 Scratch 里的模块 ID。 459 | - `preprocess` 函数,如果所有参数均为常量,那么此函数用于预计算处理,第一个参数为这个 AST 节点,返回一个新的常量 AST 节点对象替换该模块。 460 | - `type` 模块样式类型,默认值为 `1`,可选值如下: 461 | - `1` :普通模块,类似 `等待 ( ) 秒` 模块 462 | - `2` :返回值模块,类似 `回答` 模块 463 | - `3` :布尔值模块,类似 `鼠标是否按下` 模块 464 | - `4` :事件模块,类似 `当 🚩 被点击` 模块 465 | - `subn` 如果模块类型为多分支模块(类似 `如果 < > 那么`, `如果 < > 那么 否则 `),则此参数为分支的数量,默认为 `0`, 即没有分支。 466 | - `args` 模块的参数数组,每个数组成员都是一个对象,格式如下: 467 | - `name` 字符串,这个输入值在 Scratch 的键名。 468 | - `doc` 字符串,可选,该参数的简短文档,用于脚本生成模块文档。 469 | - `type` 参数的类型,默认值为 `10`,可选值如下: 470 | - `4` 数字 471 | - `5` 正数 472 | - `6` 正整数 473 | - `7` 整数 474 | - `8` 角度 475 | - `9` 颜色 476 | - `10` 字符串 477 | - `11` 广播菜单 478 | - `12` 变量菜单 479 | - `13` 列表菜单 480 | - `20` 枚举菜单 481 | - `30` 静态常量,此时该变量不作为参数的一部分参与。 482 | - `31` 菜单静态常量,此时该变量不作为参数的一部分参与。 483 | - `value` 任意,可选,如果类型为常量,则此处为该参数的常量值,无需按照 AST 对象结构定义。 484 | - `menu` 函数,如果类型为枚举菜单,则此参数用于处理用户输入并返回需要存储的真实值。 485 | - `menuOpcode` 字符串,在大多数情况下,菜单都属于独立的模块(只是因为 Shadow 所以拖不出来),所以这里如果提供,则作为这个菜单模块的模块 ID,否则将直接菜单值作为普通参数存储。 486 | 487 | ## 编译器开发 488 | 489 | ### 部署 490 | 491 | 推荐使用 Yarn 进行各种库的下载及构建工具的运行,NPM 也是可以的。 492 | 493 | ```bash 494 | > yarn 495 | > yarn start 496 | ``` 497 | 498 | 启动 webpack-dev-server 之后,访问 [http://localhost:8040/playground/](http://localhost:8040/playground/) 即可访问网页编辑器(仅供调试)。 499 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ScratchScriptKit 2 | 3 | [![Licence](https://img.shields.io/github/license/Steve-xmh/scratch-script?style=flat-square)](https://github.com/Steve-xmh/scratch-script/blob/master/LICENCE) 4 | [![Github](https://img.shields.io/github/repo-size/Steve-xmh/scratch-script?style=flat-square)](https://github.com/Steve-xmh/scratch-script) 5 | [![Github Package Version](https://img.shields.io/github/package-json/v/Steve-xmh/scratch-script?label=dev&style=flat-square)](https://github.com/Steve-xmh/scratch-script) 6 | [![Package Version](https://img.shields.io/npm/v/scratch-script?style=flat-square)](https://www.npmjs.com/package/scratch-script) 7 | [![NPM](https://img.shields.io/bundlephobia/min/scratch-script?style=flat-square)](https://www.npmjs.com/package/scratch-script) 8 | 9 | Code feature is in alpha statement, . But others (sprites or stage definition) are finished. 10 | 11 | A toolchain to make scratch project without drag any thing. 12 | 13 | ScratchScript Example: 14 | ```lua 15 | var direction = 0; 16 | when events.flagClicked() { 17 | looks.sayFor('Hello ScratchScript!', 3); 18 | forever { 19 | direction = 1; 20 | repeat (10) { 21 | motion.changeY(5 * direction); 22 | } 23 | if (direction == 1) { 24 | direction = -1; 25 | } else { 26 | direction = 1; 27 | } 28 | } 29 | } 30 | ``` 31 | 32 | [Chinese 中文](./README-CN.md) English 33 | [API Refenerce](./API.md) 34 | 35 | English document is in progress (:P) 36 | 37 | ## Installation 38 | 39 | ```shell 40 | > npm i scratch-script -g 41 | ``` 42 | 43 | ## Development 44 | 45 | We recommend you to use Yarn to setup the environment, npm also works. 46 | 47 | ```bash 48 | > yarn 49 | > yarn start 50 | ``` 51 | 52 | This will start webpack dev server, then you can access [http://localhost:8040/playground/](http://localhost:8040/playground/) to the playground (only for debug). 53 | 54 | ## Usage 55 | 56 | ```shell 57 | > ssc --help 58 | Usage: ssc [options] 59 | 60 | Options: 61 | -v, --version output the version number 62 | -o, --output specify an output project file path 63 | -h, --help display help for command 64 | ``` 65 | -------------------------------------------------------------------------------- /bin/ssc.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | 'use strict' 4 | 5 | const path = require('path') 6 | const prog = require('commander') 7 | const fs = require('fs') 8 | 9 | const version = require('../package.json').version 10 | 11 | const ss = require('../dist/node/ssc') 12 | 13 | prog.version(version, '-v, --version') 14 | .name('ssc') 15 | .arguments('') 16 | .option('-o, --output ', 'specify an output project file path') 17 | .action((dir, argv) => { 18 | const projectDir = path.resolve(process.cwd(), dir) 19 | const outputDir = argv.output 20 | ? path.resolve(process.cwd(), argv.output) 21 | : path.resolve(projectDir, path.basename(projectDir) + '.sb3') 22 | ss.complieInNodeJS({ 23 | projectDir 24 | }).then(complied => { 25 | return fs.promises.writeFile(outputDir, complied) 26 | }).catch(err => { 27 | console.log(err) 28 | }) 29 | }) 30 | 31 | prog.parse(process.argv) 32 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "scratch-script", 3 | "version": "0.1.10", 4 | "description": "[Alpha] An easy language to make huge scratch code more easily. ✨", 5 | "repository": "https://github.com/Steve-xmh/scratch-script", 6 | "main": "dist/node/ssc.js", 7 | "browser": "dist/web/ssc.js", 8 | "bin": { 9 | "ssc": "bin/ssc.js" 10 | }, 11 | "scripts": { 12 | "start": "webpack-dev-server", 13 | "build": "cross-env NODE_ENV=production webpack --progress --color", 14 | "test": "ava test/test/*.js", 15 | "gendoc": "node scripts/gendoc", 16 | "prepare": "npm run build && npm run gendoc && npm run test", 17 | "railroad": "nearley-railroad ./src/code/nearley/index.ne -o ./railroad.html" 18 | }, 19 | "keywords": [ 20 | "scratch", 21 | "compiler", 22 | "scratch-script", 23 | "language", 24 | "programming-language" 25 | ], 26 | "author": { 27 | "name": "Steve Xiao", 28 | "email": "776470918@qq.com", 29 | "url": "https://github.com/Steve-xmh" 30 | }, 31 | "maintainers": [ 32 | "Steve Xiao <776470918@qq.com> (https://github.com/Steve-xmh)", 33 | "Alex Cui (https://github.com/alexcui03)" 34 | ], 35 | "license": "AGPL-3.0-or-later", 36 | "dependencies": { 37 | "ajv": "^6.12.2", 38 | "commander": "^5.1.0", 39 | "jszip": "^3.4.0", 40 | "moo": "^0.5.1", 41 | "nearley": "^2.19.3", 42 | "yaml": "^1.9.2" 43 | }, 44 | "devDependencies": { 45 | "@babel/core": "^7.10.5", 46 | "@babel/plugin-transform-runtime": "^7.10.5", 47 | "@babel/preset-env": "^7.10.4", 48 | "arraybuffer-loader": "^1.0.8", 49 | "ava": "^3.4.0", 50 | "babel-loader": "^8.1.0", 51 | "babel-plugin-transform-runtime": "^6.23.0", 52 | "copy-webpack-plugin": "^6.0.3", 53 | "cross-env": "^7.0.2", 54 | "eslint": "^6.8.0", 55 | "eslint-config-standard": "^14.1.0", 56 | "eslint-plugin-import": "^2.20.1", 57 | "eslint-plugin-node": "^11.0.0", 58 | "eslint-plugin-promise": "^4.2.1", 59 | "eslint-plugin-standard": "^4.0.1", 60 | "lodash.defaultsdeep": "^4.6.1", 61 | "mkdirp": "^1.0.4", 62 | "nearley-loader": "^2.0.0", 63 | "raw-loader": "^4.0.1", 64 | "react": "^16.13.1", 65 | "react-dom": "^16.13.1", 66 | "rimraf": "^3.0.2", 67 | "scratch-gui": "^0.1.0-prerelease.20200720192905", 68 | "scratch-vm": "^0.2.0-prerelease.20200720182258", 69 | "webpack": "^4.43.0", 70 | "webpack-cli": "^3.3.12", 71 | "webpack-dev-server": "^3.11.0" 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /scripts/gendoc.js: -------------------------------------------------------------------------------- 1 | 2 | const path = require('path') 3 | const fs = require('fs') 4 | const fsp = fs.promises 5 | 6 | const ScratchScript = require('../dist/node/ssc').default 7 | const BlockStorage = ScratchScript.BlockStorage.createWithCoreBlocks() 8 | const InputType = ScratchScript.InputType 9 | const IntToType = {} 10 | 11 | for (const i in InputType) { 12 | IntToType[InputType[i]] = i 13 | } 14 | 15 | async function main () { 16 | const f = await fsp.open(path.resolve(__dirname, '../API.md'), 'w') 17 | await f.write('# ScratchScript Core Block API Reference\n') 18 | await f.write('Generated by [scripts/gendoc.js](scripts/gendoc.js) \n') 19 | await f.write(`Package Version: ${require('../package.json').version} \n`) 20 | await f.write(`Generate Date: ${new Date().toLocaleString('en-us')} \n`) 21 | const index = Object.keys(BlockStorage._coreBlocks) 22 | let i = 0 23 | await f.write('## Index\n') 24 | for (const cate of index) { 25 | const blocks = BlockStorage._coreBlocks[cate] 26 | await f.write(`${++i}. [${blocks.name || blocks.id}](#${blocks.name || blocks.id})\n`) 27 | } 28 | for (const cate of index) { 29 | const blocks = BlockStorage._coreBlocks[cate] 30 | await f.write(`## ${blocks.name || blocks.id}\n`) 31 | if ('doc' in blocks) await f.write(`${blocks.doc} \n`) 32 | await f.write('[Return To Index](#Index) \n') 33 | await f.write(`ID: \`${blocks.id}\` \n`) 34 | if ('blocks' in blocks) { 35 | for (const block of blocks.blocks) { 36 | await f.write(`### \`${block.name}(`) 37 | const args = ('args' in block) ? block.args.filter(v => v.type !== 30 && v.type !== 31) : [] 38 | if (args.length > 0) { 39 | await f.write(args.map(arg => { 40 | return arg.name + ': ' + IntToType[arg.type] 41 | }).join(', ')) 42 | } 43 | await f.write(`)${'subn' in block ? ` { ${block.subn} }` : ''}`) 44 | if (block.type === 1) { 45 | await f.write(': void') 46 | } else { 47 | await f.write(': any') 48 | } 49 | await f.write('`\n') 50 | if ('doc' in block) await f.write(`${block.doc} \n`) 51 | else await f.write(`Reference to \`${block.opcode}\`. \n`) 52 | } 53 | } 54 | } 55 | await f.close() 56 | } 57 | 58 | main() 59 | -------------------------------------------------------------------------------- /src/code/argType.js: -------------------------------------------------------------------------------- 1 | export default { 2 | /** 1 */ 3 | StringOrNumber: 1, 4 | /** 2 */ 5 | EnumMenu: 2, 6 | /** 3 */ 7 | VariableMenu: 3 8 | } 9 | -------------------------------------------------------------------------------- /src/code/blockType.js: -------------------------------------------------------------------------------- 1 | const BlockType = { 2 | /** 3 | * 1 4 | */ 5 | Block: 1, 6 | /** 7 | * 2 8 | */ 9 | ReporterBlock: 2, 10 | /** 11 | * 3 12 | */ 13 | BooleanReporter: 3, 14 | /** 15 | * 4 16 | */ 17 | EventBlock: 4 18 | } 19 | 20 | export default BlockType 21 | -------------------------------------------------------------------------------- /src/code/blocks/control.js: -------------------------------------------------------------------------------- 1 | 2 | import InputType from '../inputType' 3 | import BlockType from '../blockType' 4 | 5 | export default { 6 | name: 'Control', 7 | id: 'control', 8 | blocks: [{ 9 | name: 'wait', 10 | opcode: 'control_wait', 11 | type: BlockType.Block, 12 | args: [{ 13 | name: 'DURATION', 14 | type: InputType.PositiveNumber 15 | }] 16 | }, { 17 | name: 'repeat', 18 | opcode: 'control_repeat', 19 | type: BlockType.Block, 20 | subn: 1, 21 | args: [{ 22 | name: 'TIMES', 23 | type: InputType.Integer 24 | }] 25 | }, { 26 | name: 'forever', 27 | opcode: 'control_forever', 28 | type: BlockType.Block, 29 | subn: 1 30 | }, { 31 | name: 'if', 32 | opcode: 'control_if', 33 | type: BlockType.Block, 34 | subn: 1, 35 | args: [{ 36 | name: 'CONDITION', 37 | type: InputType.Boolean 38 | }] 39 | }, { 40 | name: 'ifelse', 41 | opcode: 'control_if_else', 42 | type: BlockType.Block, 43 | subn: 2, 44 | args: [{ 45 | name: 'CONDITION', 46 | type: InputType.Boolean 47 | }] 48 | }, { 49 | name: 'waitUntil', 50 | opcode: 'control_wait_until', 51 | type: BlockType.Block, 52 | args: [{ 53 | name: 'CONDITION', 54 | type: InputType.Boolean 55 | }] 56 | }, { 57 | name: 'repeatUntil', 58 | opcode: 'control_repeat_until', 59 | type: BlockType.Block, 60 | subn: 1, 61 | args: [{ 62 | name: 'CONDITION', 63 | type: InputType.Boolean 64 | }] 65 | }, { 66 | name: 'forEach', 67 | opcode: 'control_for_each', 68 | type: BlockType.Block, 69 | args: [{ 70 | name: 'VARIABLE', 71 | type: InputType.Variable 72 | }, { 73 | name: 'VALUE', 74 | type: InputType.Integer 75 | }] 76 | }, { 77 | name: 'stop', 78 | opcode: 'control_stop', 79 | type: BlockType.Block, 80 | args: [{ 81 | name: 'STOP_OPTION', 82 | type: InputType.Menu 83 | }] 84 | }, { 85 | name: 'startAsClone', 86 | opcode: 'control_start_as_clone', 87 | type: BlockType.EventBlock 88 | }, { 89 | name: 'cloneSelf', 90 | opcode: 'control_create_clone_of', 91 | type: BlockType.Block, 92 | args: [{ 93 | name: 'CLONE_OPTION', 94 | type: InputType.Constant, 95 | value: '_myself_', 96 | menuOpcode: 'control_create_clone_of_menu' 97 | }] 98 | }, { 99 | name: 'clone', 100 | opcode: 'control_create_clone_of', 101 | type: BlockType.Block, 102 | args: [{ 103 | name: 'CLONE_OPTION', 104 | type: InputType.Menu, 105 | menuOpcode: 'control_create_clone_of_menu' 106 | }] 107 | }, { 108 | name: 'deleteThisClone', 109 | opcode: 'control_delete_this_clone', 110 | type: BlockType.Block 111 | }, { 112 | name: 'getCounter', 113 | opcode: 'control_get_counter', 114 | type: BlockType.Block 115 | }, { 116 | name: 'incrCounter', 117 | opcode: 'control_incr_counter', 118 | type: BlockType.Block 119 | }, { 120 | name: 'clearCounter', 121 | opcode: 'control_clear_counter', 122 | type: BlockType.Block 123 | }, { 124 | name: 'allAtOnce', 125 | opcode: 'control_all_at_once', 126 | type: BlockType.Block, 127 | subn: 1 128 | }] 129 | } 130 | -------------------------------------------------------------------------------- /src/code/blocks/data.js: -------------------------------------------------------------------------------- 1 | 2 | import InputType from '../inputType' 3 | import BlockType from '../blockType' 4 | 5 | export default { 6 | name: 'Data', 7 | id: 'data', 8 | blocks: [{ 9 | name: 'setVar', 10 | opcode: 'data_setvariableto', 11 | type: BlockType.Block, 12 | args: [{ 13 | name: 'VARIABLE', 14 | type: InputType.Variable 15 | }, { 16 | name: 'VALUE', 17 | type: InputType.String 18 | }] 19 | }, { 20 | name: 'addVar', 21 | opcode: 'data_changevariableby', 22 | type: BlockType.Block, 23 | args: [{ 24 | name: 'VARIABLE', 25 | type: InputType.Variable 26 | }, { 27 | name: 'VALUE', 28 | type: InputType.String 29 | }] 30 | }, { 31 | name: 'hideVar', 32 | opcode: 'data_hidevariable', 33 | type: BlockType.Block, 34 | args: [{ 35 | name: 'VARIABLE', 36 | type: InputType.Variable 37 | }] 38 | }, { 39 | name: 'showVar', 40 | opcode: 'data_showvariable', 41 | type: BlockType.Block, 42 | args: [{ 43 | name: 'VARIABLE', 44 | type: InputType.Variable 45 | }] 46 | }, { 47 | name: 'addItem', 48 | opcode: 'data_addtolist', 49 | type: BlockType.Block, 50 | args: [{ 51 | name: 'LIST', 52 | type: InputType.List 53 | }, { 54 | name: 'ITEM', 55 | type: InputType.String 56 | }] 57 | }, { 58 | name: 'deleteItem', 59 | opcode: 'data_deleteoflist', 60 | type: BlockType.Block, 61 | args: [{ 62 | name: 'LIST', 63 | type: InputType.List 64 | }, { 65 | name: 'INDEX', 66 | type: InputType.PositionInteger 67 | }] 68 | }, { 69 | name: 'deleteAll', 70 | opcode: 'data_deletealloflist', 71 | type: BlockType.Block, 72 | args: [{ 73 | name: 'LIST', 74 | type: InputType.List 75 | }] 76 | }, { 77 | name: 'insertItem', 78 | opcode: 'data_insertatlist', 79 | type: BlockType.Block, 80 | args: [{ 81 | name: 'LIST', 82 | type: InputType.List 83 | }, { 84 | name: 'INDEX', 85 | type: InputType.PositionInteger 86 | }, { 87 | name: 'ITEM', 88 | type: InputType.String 89 | }] 90 | }, { 91 | name: 'replaceItem', 92 | opcode: 'data_replaceitemoflist', 93 | type: BlockType.Block, 94 | args: [{ 95 | name: 'LIST', 96 | type: InputType.List 97 | }, { 98 | name: 'INDEX', 99 | type: InputType.PositionInteger 100 | }, { 101 | name: 'ITEM', 102 | type: InputType.String 103 | }] 104 | }, { 105 | name: 'itemOfList', 106 | opcode: 'data_itemoflist', 107 | type: BlockType.ReporterBlock, 108 | args: [{ 109 | name: 'LIST', 110 | type: InputType.List 111 | }, { 112 | name: 'INDEX', 113 | type: InputType.PositionInteger 114 | }] 115 | }, { 116 | name: 'indexOfList', 117 | opcode: 'data_itemnumoflist', 118 | type: BlockType.ReporterBlock, 119 | args: [{ 120 | name: 'LIST', 121 | type: InputType.List 122 | }, { 123 | name: 'ITEM', 124 | type: InputType.String 125 | }] 126 | }, { 127 | name: 'lengthOfList', 128 | opcode: 'data_lengthoflist', 129 | type: BlockType.ReporterBlock, 130 | args: [{ 131 | name: 'LIST', 132 | type: InputType.List 133 | }, { 134 | name: 'ITEM', 135 | type: InputType.String 136 | }] 137 | }, { 138 | name: 'containsItem', 139 | opcode: 'data_listcontainsitem', 140 | type: BlockType.BooleanReporter, 141 | args: [{ 142 | name: 'LIST', 143 | type: InputType.List 144 | }, { 145 | name: 'ITEM', 146 | type: InputType.String 147 | }] 148 | }, { 149 | name: 'hideList', 150 | opcode: 'data_hidelist', 151 | type: BlockType.Block, 152 | args: [{ 153 | name: 'LIST', 154 | type: InputType.List 155 | }] 156 | }, { 157 | name: 'showList', 158 | opcode: 'data_showlist', 159 | type: BlockType.Block, 160 | args: [{ 161 | name: 'LIST', 162 | type: InputType.List 163 | }] 164 | }] 165 | } 166 | -------------------------------------------------------------------------------- /src/code/blocks/events.js: -------------------------------------------------------------------------------- 1 | 2 | import InputType from '../inputType' 3 | import BlockType from '../blockType' 4 | 5 | export default { 6 | name: 'Events', 7 | id: 'events', 8 | blocks: [{ 9 | name: 'flagClicked', 10 | opcode: 'event_whenflagclicked', 11 | type: BlockType.EventBlock 12 | }, { 13 | name: 'keyPressed', 14 | opcode: 'event_whenkeypressed', 15 | type: BlockType.EventBlock, 16 | args: [{ 17 | name: 'KEY_OPTION', 18 | type: InputType.Menu 19 | }] 20 | }, { 21 | name: 'clicked', 22 | opcode: 'event_whenthisspriteclicked', 23 | type: BlockType.EventBlock 24 | }, { 25 | name: 'backdropSwitchesTo', 26 | opcode: 'event_whenbackdropswitchesto', 27 | type: BlockType.EventBlock, 28 | args: [{ 29 | name: 'BROADCAST_INPUT', 30 | type: InputType.Broadcast 31 | }] 32 | }, { 33 | name: 'greaterThan', 34 | opcode: 'event_whengreaterthan', 35 | type: BlockType.EventBlock, 36 | args: [{ 37 | name: 'VALUE', 38 | type: InputType.Number 39 | }] 40 | }, { 41 | name: 'broadcastReceived', 42 | opcode: 'event_whenbroadcastreceived', 43 | type: BlockType.EventBlock, 44 | args: [{ 45 | name: 'BROADCAST_OPTION', 46 | type: InputType.Broadcast 47 | }] 48 | }, { 49 | name: 'broadcast', 50 | opcode: 'event_broadcast', 51 | type: BlockType.Block, 52 | args: [{ 53 | name: 'BROADCAST_INPUT', 54 | type: InputType.Broadcast 55 | }] 56 | }, { 57 | name: 'broadcastAndWait', 58 | opcode: 'event_broadcastandwait', 59 | type: BlockType.Block, 60 | args: [{ 61 | name: 'BROADCAST_INPUT', 62 | type: InputType.Broadcast 63 | }] 64 | }] 65 | } 66 | -------------------------------------------------------------------------------- /src/code/blocks/index.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @typedef {Object} ArgumentD 4 | * @property {number} type 5 | * @property {Object.} menu 6 | * @property {string} menuOpcode 7 | * 8 | * @typedef {Object} BlockD 9 | * @property {string} name 10 | * @property {string} opcode 11 | * @property {number} type 12 | * @property {number} subn 13 | * @property {Array.} args 14 | * @property {(node: import('../parser').Constant) => string} preprocess 15 | * 16 | * @typedef {Object} BlockDefinition 17 | * @property {string} name 18 | * @property {string} id 19 | * @property {string} description 20 | * @property {*} value 21 | * @property {Array.} blocks 22 | * 23 | * @typedef {Object.} BlockDefinitions 24 | * @returns {BlockStorage} 25 | */ 26 | 27 | import InputType from '../inputType' 28 | 29 | import MotionBlocks from './motion' 30 | import LooksBlocks from './looks' 31 | import SoundBlocks from './sound' 32 | import EventsBlocks from './events' 33 | import ControlBlocks from './control' 34 | import SensingBlocks from './sensing' 35 | import OperatorsBlocks from './operators' 36 | import DataBlocks from './data' 37 | 38 | class BlockStorage { 39 | constructor () { 40 | /** 41 | * @type {BlockDefinitions} 42 | * @private 43 | */ 44 | this._coreBlocks = {} 45 | this._blocks = {} 46 | } 47 | 48 | /** 49 | * @param {BlockDefinition} desc 50 | * @private 51 | */ 52 | _register (desc) { 53 | if (!desc || typeof desc.id !== 'string') { 54 | throw new Error(`Extention ${desc.id || desc.name} doesn't have a id or not exists`) 55 | } 56 | if (this._coreBlocks[desc.id] !== undefined) { 57 | throw new Error(`Extention ${desc.id} has been registered`) 58 | } 59 | this._coreBlocks[desc.id] = desc 60 | return this 61 | } 62 | 63 | /** 64 | * @param {BlockDefinition} desc 65 | * @param {string?} rename 66 | */ 67 | register (desc, rename = null) { 68 | const registerid = rename || desc.id 69 | if (!desc || typeof registerid !== 'string') { 70 | throw new Error(`Extention ${registerid || desc.name} doesn't have a id or not exists`) 71 | } 72 | if (this._blocks[registerid] !== undefined || this._coreBlocks[registerid] !== undefined) { 73 | throw new Error(`Extention ${registerid} has been registered`) 74 | } 75 | this._blocks[registerid] = desc 76 | return this 77 | } 78 | 79 | reset () { 80 | this._blocks = {} 81 | return this 82 | } 83 | 84 | /** 85 | * @param {string} blockiden 86 | * @param {number} argn 87 | * @returns {BlockD?} 88 | */ 89 | getBlock (blockiden, argn = 0) { 90 | const [id, name] = blockiden.split('.') 91 | if (this._blocks[id]) { 92 | return this._blocks[id].blocks.find(v => v.name === name && 93 | (v.args ? (v.args.filter(v => v.type !== InputType.Constant && v.type !== InputType.MenuConstant).length === argn) : (argn === 0)) 94 | ) || null 95 | } else if (this._coreBlocks[id]) { 96 | return this._coreBlocks[id].blocks.find(v => v.name === name && 97 | (v.args ? (v.args.filter(v => v.type !== InputType.Constant && v.type !== InputType.MenuConstant).length === argn) : (argn === 0)) 98 | ) || null 99 | } else { 100 | return null 101 | } 102 | } 103 | } 104 | 105 | BlockStorage.coreBlocks = { 106 | motion: MotionBlocks, 107 | looks: LooksBlocks, 108 | sound: SoundBlocks, 109 | events: EventsBlocks, 110 | control: ControlBlocks, 111 | sensing: SensingBlocks, 112 | operators: OperatorsBlocks, 113 | data: DataBlocks 114 | } 115 | 116 | const createWithCoreBlocks = function () { 117 | const storage = new BlockStorage() 118 | for (const key in BlockStorage.coreBlocks) { 119 | storage._register(BlockStorage.coreBlocks[key]) 120 | } 121 | return storage 122 | } 123 | 124 | export { 125 | BlockStorage as default, 126 | createWithCoreBlocks 127 | } 128 | -------------------------------------------------------------------------------- /src/code/blocks/looks.js: -------------------------------------------------------------------------------- 1 | 2 | import InputType from '../inputType' 3 | import BlockType from '../blockType' 4 | 5 | const effects = [ 6 | 'Color', 7 | 'Fisheye', 8 | 'Whirl', 9 | 'Pixelate', 10 | 'Mosaic', 11 | 'Brightness' 12 | ] 13 | 14 | const genEffectsBlocks = (effectName) => [{ 15 | name: `set${effectName}Effect`, 16 | opcode: 'looks_seteffectto', 17 | doc: `Set ${effectName.toLowerCase()} effect to a number.`, 18 | type: BlockType.Block, 19 | args: [{ 20 | name: 'VALUE', 21 | type: InputType.Number 22 | }, { 23 | name: 'EFFECT', 24 | type: InputType.MenuConstant, 25 | value: effectName.toUpperCase() 26 | }] 27 | }, { 28 | name: `change${effectName}Effect`, 29 | opcode: 'looks_changeeffectby', 30 | doc: `Change ${effectName.toLowerCase()} effect by a number.`, 31 | type: BlockType.Block, 32 | args: [{ 33 | name: 'CHANGE', 34 | type: InputType.Number 35 | }, { 36 | name: 'EFFECT', 37 | type: InputType.MenuConstant, 38 | value: effectName.toUpperCase() 39 | }] 40 | }] 41 | 42 | export default { 43 | name: 'Looks', 44 | id: 'looks', 45 | blocks: [{ 46 | name: 'sayFor', 47 | opcode: 'looks_sayforsecs', 48 | type: BlockType.Block, 49 | args: [{ 50 | name: 'MESSAGE', 51 | type: InputType.String 52 | }, { 53 | name: 'SECS', 54 | type: InputType.Number 55 | }] 56 | }, { 57 | name: 'say', 58 | opcode: 'looks_say', 59 | type: BlockType.Block, 60 | args: [{ 61 | name: 'MESSAGE', 62 | type: InputType.String 63 | }] 64 | }, { 65 | name: 'thinkFor', 66 | opcode: 'looks_thinkforsecs', 67 | type: BlockType.Block, 68 | args: [{ 69 | name: 'MESSAGE', 70 | type: InputType.String 71 | }, { 72 | name: 'SECS', 73 | type: InputType.Number 74 | }] 75 | }, { 76 | name: 'think', 77 | opcode: 'looks_think', 78 | type: BlockType.Block, 79 | args: [{ 80 | name: 'MESSAGE', 81 | type: InputType.String 82 | }] 83 | }, { 84 | name: 'switchCostume', 85 | opcode: 'looks_switchcostumeto', 86 | type: BlockType.Block, 87 | args: [{ 88 | name: 'COSTUME', 89 | type: InputType.Menu, 90 | menuOpcode: 'looks_costume' 91 | }] 92 | }, { 93 | name: 'nextCostume', 94 | opcode: 'looks_nextcostume', 95 | type: BlockType.Block 96 | }, { 97 | name: 'switchbackdropto', 98 | opcode: 'looks_switchbackdropto', 99 | type: BlockType.Block, 100 | args: [{ 101 | name: 'BACKDROP', 102 | type: InputType.Menu, 103 | menuOpcode: 'looks_backdrops' 104 | }] 105 | }, { 106 | name: 'nextBackdrop', 107 | opcode: 'looks_nextbackdrop', 108 | type: BlockType.Block 109 | }, { 110 | name: 'addSize', 111 | opcode: 'looks_changesizeby', 112 | type: BlockType.Block, 113 | args: [{ 114 | name: 'CHANGE', 115 | type: InputType.Number 116 | }] 117 | }, { 118 | name: 'setSize', 119 | opcode: 'looks_setsizeto', 120 | type: BlockType.Block, 121 | args: [{ 122 | name: 'SIZE', 123 | type: InputType.Number 124 | }] 125 | }, { 126 | name: 'clearGraphicEffects', 127 | opcode: 'looks_cleargraphiceffects', 128 | type: BlockType.Block 129 | }, { 130 | name: 'show', 131 | opcode: 'looks_show', 132 | type: BlockType.Block, 133 | args: [{ 134 | name: 'NUM', 135 | type: InputType.Menu, 136 | menu: i => i, 137 | menuOpcode: 'math_integer' 138 | }] 139 | }, { 140 | name: 'hide', 141 | opcode: 'looks_hide', 142 | type: BlockType.Block, 143 | args: [{ 144 | name: 'NUM', 145 | type: InputType.Menu, 146 | menu: i => i, 147 | menuOpcode: 'math_integer' 148 | }] 149 | }, { 150 | name: 'gotofrontback', 151 | opcode: 'looks_gotofrontback', 152 | type: BlockType.Block, 153 | args: [{ 154 | name: 'NUM', 155 | type: InputType.Number 156 | }] 157 | }, { 158 | name: 'goforwardbackwardlayers', 159 | opcode: 'looks_goforwardbackwardlayers', 160 | type: BlockType.Block, 161 | args: [{ 162 | name: 'NUM', 163 | type: InputType.Menu, 164 | menu: i => i, 165 | menuOpcode: 'math_integer' 166 | }] 167 | }, { 168 | name: 'costumenumbername', 169 | opcode: 'looks_costumenumbername', 170 | type: BlockType.Block, 171 | args: [] 172 | }, { 173 | name: 'backdropnumbername', 174 | opcode: 'looks_backdropnumbername', 175 | type: BlockType.ReporterBlock, 176 | args: [] 177 | }, { 178 | name: 'size', 179 | opcode: 'looks_size', 180 | type: BlockType.ReporterBlock, 181 | args: [] 182 | } 183 | ].concat(...effects.map(genEffectsBlocks)) 184 | } 185 | -------------------------------------------------------------------------------- /src/code/blocks/motion.js: -------------------------------------------------------------------------------- 1 | 2 | import InputType from '../inputType' 3 | import BlockType from '../blockType' 4 | 5 | export default { 6 | name: 'Motion', 7 | id: 'motion', 8 | blocks: [{ 9 | name: 'walkStep', 10 | opcode: 'motion_movesteps', 11 | type: BlockType.Block, 12 | args: [{ 13 | name: 'STEPS', 14 | type: InputType.Number 15 | }] 16 | }, { 17 | name: 'turnRight', 18 | opcode: 'motion_turnright', 19 | type: BlockType.Block, 20 | args: [{ 21 | name: 'DEGREES', 22 | type: InputType.Number 23 | }] 24 | }, { 25 | name: 'turnLeft', 26 | opcode: 'motion_turnleft', 27 | type: BlockType.Block, 28 | args: [{ 29 | name: 'DEGREES', 30 | type: InputType.Number 31 | }] 32 | }, { 33 | name: 'goTo', 34 | opcode: 'motion_goto', 35 | type: BlockType.Block, 36 | args: [{ 37 | name: 'TO', 38 | type: InputType.Menu, 39 | menuOpcode: 'motion_goto_menu' 40 | }] 41 | }, { 42 | name: 'goToPos', 43 | opcode: 'motion_gotoxy', 44 | type: BlockType.Block, 45 | args: [{ 46 | name: 'X', 47 | type: InputType.Number 48 | }, { 49 | name: 'Y', 50 | type: InputType.Number 51 | }] 52 | }, { 53 | name: 'glideTo', 54 | opcode: 'motion_glideto', 55 | type: BlockType.Block, 56 | args: [{ 57 | name: 'SECS', 58 | type: InputType.Number 59 | }, { 60 | name: 'TO', 61 | type: InputType.Menu, 62 | menuOpcode: 'motion_glideto_menu' 63 | }] 64 | }, { 65 | name: 'glideToPos', 66 | opcode: 'motion_glidesecstoxy', 67 | type: BlockType.Block, 68 | args: [{ 69 | name: 'SECS', 70 | type: InputType.Number 71 | }, { 72 | name: 'X', 73 | type: InputType.Number 74 | }, { 75 | name: 'Y', 76 | type: InputType.Number 77 | }] 78 | }, { 79 | name: 'setDirection', 80 | opcode: 'motion_pointindirection', 81 | type: BlockType.Block, 82 | args: [{ 83 | name: 'DIRECTION', 84 | type: InputType.Menu, 85 | menuOpcode: 'math_angle' 86 | }] 87 | }, { 88 | name: 'towards', 89 | opcode: 'motion_pointtowards', 90 | type: BlockType.Block, 91 | args: [{ 92 | name: 'TOWARDS', 93 | type: InputType.Menu, 94 | menuOpcode: 'motion_pointtowards_menu' 95 | }] 96 | }, { 97 | name: 'changeX', 98 | opcode: 'motion_changexby', 99 | type: BlockType.Block, 100 | args: [{ 101 | name: 'DX', 102 | type: InputType.Number 103 | }] 104 | }, { 105 | name: 'setX', 106 | opcode: 'motion_setx', 107 | type: BlockType.Block, 108 | args: [{ 109 | name: 'X', 110 | type: InputType.Number 111 | }] 112 | }, { 113 | name: 'changeY', 114 | opcode: 'motion_changeyby', 115 | type: BlockType.Block, 116 | args: [{ 117 | name: 'DY', 118 | type: InputType.Number 119 | }] 120 | }, { 121 | name: 'setY', 122 | opcode: 'motion_sety', 123 | type: BlockType.Block, 124 | args: [{ 125 | name: 'Y', 126 | type: InputType.Number 127 | }] 128 | }, { 129 | name: 'ifOnEdgeBounce', 130 | opcode: 'motion_ifonedgebounce', 131 | type: BlockType.Block, 132 | args: [] 133 | }, { 134 | name: 'setRotationStyle', 135 | opcode: 'motion_setrotationstyle', 136 | type: BlockType.Block, 137 | args: [{ 138 | name: 'Y', 139 | type: InputType.Number 140 | }] 141 | }, { 142 | name: 'x', 143 | opcode: 'motion_xposition', 144 | type: BlockType.ReporterBlock 145 | }, { 146 | name: 'y', 147 | opcode: 'motion_yposition', 148 | type: BlockType.ReporterBlock 149 | }, { 150 | name: 'direction', 151 | opcode: 'motion_direction', 152 | type: BlockType.ReporterBlock 153 | }] 154 | } 155 | -------------------------------------------------------------------------------- /src/code/blocks/operators.js: -------------------------------------------------------------------------------- 1 | 2 | import InputType from '../inputType' 3 | import BlockType from '../blockType' 4 | 5 | export default { 6 | name: 'Operators', 7 | id: 'math', 8 | blocks: [{ 9 | name: 'add', 10 | opcode: 'operator_add', 11 | type: BlockType.ReporterBlock, 12 | args: [{ 13 | name: 'NUM1', 14 | type: InputType.Number 15 | }, { 16 | name: 'NUM2', 17 | type: InputType.Number 18 | }] 19 | }, { 20 | name: 'subtract', 21 | opcode: 'operator_subtract', 22 | type: BlockType.ReporterBlock, 23 | args: [{ 24 | name: 'NUM1', 25 | type: InputType.Number 26 | }, { 27 | name: 'NUM2', 28 | type: InputType.Number 29 | }] 30 | }, { 31 | name: 'multiply', 32 | opcode: 'operator_multiply', 33 | type: BlockType.ReporterBlock, 34 | args: [{ 35 | name: 'NUM1', 36 | type: InputType.Number 37 | }, { 38 | name: 'NUM2', 39 | type: InputType.Number 40 | }] 41 | }, { 42 | name: 'divide', 43 | opcode: 'operator_divide', 44 | type: BlockType.ReporterBlock, 45 | args: [{ 46 | name: 'NUM1', 47 | type: InputType.Number 48 | }, { 49 | name: 'NUM2', 50 | type: InputType.Number 51 | }] 52 | }, { 53 | name: 'random', 54 | opcode: 'operator_random', 55 | type: BlockType.ReporterBlock, 56 | args: [{ 57 | name: 'FROM', 58 | type: InputType.Number 59 | }, { 60 | name: 'TO', 61 | type: InputType.Number 62 | }] 63 | }, { 64 | name: 'gt', 65 | opcode: 'operator_gt', 66 | type: BlockType.BooleanReporter, 67 | args: [{ 68 | name: 'OPERAND1', 69 | type: InputType.String 70 | }, { 71 | name: 'OPERAND2', 72 | type: InputType.String 73 | }] 74 | }, { 75 | name: 'lt', 76 | opcode: 'operator_lt', 77 | type: BlockType.BooleanReporter, 78 | args: [{ 79 | name: 'OPERAND1', 80 | type: InputType.String 81 | }, { 82 | name: 'OPERAND2', 83 | type: InputType.String 84 | }] 85 | }, { 86 | name: 'equals', 87 | opcode: 'operator_equals', 88 | type: BlockType.BooleanReporter, 89 | args: [{ 90 | name: 'OPERAND1', 91 | type: InputType.String 92 | }, { 93 | name: 'OPERAND2', 94 | type: InputType.String 95 | }] 96 | }, { 97 | name: 'and', 98 | opcode: 'operator_and', 99 | type: BlockType.BooleanReporter, 100 | args: [{ 101 | name: 'OPERAND1', 102 | type: InputType.Boolean 103 | }, { 104 | name: 'OPERAND2', 105 | type: InputType.Boolean 106 | }] 107 | }, { 108 | name: 'or', 109 | opcode: 'operator_or', 110 | type: BlockType.BooleanReporter, 111 | args: [{ 112 | name: 'OPERAND1', 113 | type: InputType.Boolean 114 | }, { 115 | name: 'OPERAND2', 116 | type: InputType.Boolean 117 | }] 118 | }, { 119 | name: 'not', 120 | opcode: 'operator_not', 121 | type: BlockType.BooleanReporter, 122 | args: [{ 123 | name: 'OPERAND', 124 | type: InputType.Boolean 125 | }] 126 | }, { 127 | name: 'join', 128 | opcode: 'operator_join', 129 | type: BlockType.ReporterBlock, 130 | args: [{ 131 | name: 'STRING1', 132 | type: InputType.String 133 | }, { 134 | name: 'STRING2', 135 | type: InputType.String 136 | }] 137 | }, { 138 | name: 'letterOf', 139 | opcode: 'operator_letter_of', 140 | type: BlockType.ReporterBlock, 141 | args: [{ 142 | name: 'LETTER', 143 | type: InputType.Integer 144 | }, { 145 | name: 'STRING', 146 | type: InputType.String 147 | }] 148 | }, { 149 | name: 'length', 150 | opcode: 'operator_length', 151 | type: BlockType.ReporterBlock, 152 | args: [{ 153 | name: 'STRING', 154 | type: InputType.String 155 | }] 156 | }, { 157 | name: 'contains', 158 | opcode: 'operator_contains', 159 | type: BlockType.BooleanReporter, 160 | args: [{ 161 | name: 'STRING1', 162 | type: InputType.String 163 | }, { 164 | name: 'STRING2', 165 | type: InputType.String 166 | }] 167 | }, { 168 | name: 'mod', 169 | opcode: 'operator_mod', 170 | type: BlockType.ReporterBlock, 171 | args: [{ 172 | name: 'NUM1', 173 | type: InputType.Number 174 | }, { 175 | name: 'NUM2', 176 | type: InputType.Number 177 | }] 178 | }, { 179 | name: 'round', 180 | opcode: 'operator_round', 181 | type: BlockType.ReporterBlock, 182 | args: [{ 183 | name: 'NUM', 184 | type: InputType.Number 185 | }] 186 | }, { 187 | name: 'mathop', 188 | opcode: 'operator_mathop', 189 | type: BlockType.ReporterBlock, 190 | args: [{ 191 | name: 'OPERATOR', 192 | type: InputType.Menu 193 | }, { 194 | name: 'NUM', 195 | type: InputType.Number 196 | }] 197 | }, { 198 | name: 'abs', 199 | opcode: 'operator_mathop', 200 | type: BlockType.ReporterBlock, 201 | args: [{ 202 | name: 'OPERATOR', 203 | type: InputType.MenuConstant, 204 | value: 'abs' 205 | }, { 206 | name: 'NUM', 207 | type: InputType.Number 208 | }] 209 | }, { 210 | name: 'floor', 211 | opcode: 'operator_mathop', 212 | type: BlockType.ReporterBlock, 213 | args: [{ 214 | name: 'OPERATOR', 215 | type: InputType.MenuConstant, 216 | value: 'floor' 217 | }, { 218 | name: 'NUM', 219 | type: InputType.Number 220 | }] 221 | }, { 222 | name: 'ceil', 223 | opcode: 'operator_mathop', 224 | type: BlockType.ReporterBlock, 225 | args: [{ 226 | name: 'OPERATOR', 227 | type: InputType.MenuConstant, 228 | value: 'ceiling' 229 | }, { 230 | name: 'NUM', 231 | type: InputType.Number 232 | }] 233 | }, { 234 | name: 'sqrt', 235 | opcode: 'operator_mathop', 236 | type: BlockType.ReporterBlock, 237 | args: [{ 238 | name: 'OPERATOR', 239 | type: InputType.MenuConstant, 240 | value: 'sqrt' 241 | }, { 242 | name: 'NUM', 243 | type: InputType.Number 244 | }] 245 | }, { 246 | name: 'sin', 247 | opcode: 'operator_mathop', 248 | type: BlockType.ReporterBlock, 249 | args: [{ 250 | name: 'OPERATOR', 251 | type: InputType.MenuConstant, 252 | value: 'sin' 253 | }, { 254 | name: 'NUM', 255 | type: InputType.Number 256 | }] 257 | }, { 258 | name: 'cos', 259 | opcode: 'operator_mathop', 260 | type: BlockType.ReporterBlock, 261 | args: [{ 262 | name: 'OPERATOR', 263 | type: InputType.MenuConstant, 264 | value: 'cos' 265 | }, { 266 | name: 'NUM', 267 | type: InputType.Number 268 | }] 269 | }, { 270 | name: 'tan', 271 | opcode: 'operator_mathop', 272 | type: BlockType.ReporterBlock, 273 | args: [{ 274 | name: 'OPERATOR', 275 | type: InputType.MenuConstant, 276 | value: 'tan' 277 | }, { 278 | name: 'NUM', 279 | type: InputType.Number 280 | }] 281 | }, { 282 | name: 'atan', 283 | opcode: 'operator_mathop', 284 | type: BlockType.ReporterBlock, 285 | args: [{ 286 | name: 'OPERATOR', 287 | type: InputType.MenuConstant, 288 | value: 'atan' 289 | }, { 290 | name: 'NUM', 291 | type: InputType.Number 292 | }] 293 | }, { 294 | name: 'ln', 295 | opcode: 'operator_mathop', 296 | type: BlockType.ReporterBlock, 297 | args: [{ 298 | name: 'OPERATOR', 299 | type: InputType.MenuConstant, 300 | value: 'ln' 301 | }, { 302 | name: 'NUM', 303 | type: InputType.Number 304 | }] 305 | }, { 306 | name: 'log', 307 | opcode: 'operator_mathop', 308 | type: BlockType.ReporterBlock, 309 | args: [{ 310 | name: 'OPERATOR', 311 | type: InputType.MenuConstant, 312 | value: 'log' 313 | }, { 314 | name: 'NUM', 315 | type: InputType.Number 316 | }] 317 | }, { 318 | name: 'e', 319 | opcode: 'operator_mathop', 320 | type: BlockType.ReporterBlock, 321 | args: [{ 322 | name: 'OPERATOR', 323 | type: InputType.MenuConstant, 324 | value: 'e ^' 325 | }, { 326 | name: 'NUM', 327 | type: InputType.Number 328 | }] 329 | }, { 330 | name: 'powerOfTen', 331 | opcode: 'operator_mathop', 332 | type: BlockType.ReporterBlock, 333 | args: [{ 334 | name: 'OPERATOR', 335 | type: InputType.MenuConstant, 336 | value: '10 ^' 337 | }, { 338 | name: 'NUM', 339 | type: InputType.Number 340 | }] 341 | }] 342 | } 343 | -------------------------------------------------------------------------------- /src/code/blocks/sensing.js: -------------------------------------------------------------------------------- 1 | 2 | import InputType from '../inputType' 3 | import BlockType from '../blockType' 4 | 5 | export default { 6 | name: 'Sensing', 7 | id: 'sensing', 8 | blocks: [{ 9 | name: 'isTouching', 10 | opcode: 'sensing_touchingobject', 11 | type: BlockType.BooleanReporter, 12 | args: [{ 13 | name: 'TOUCHINGOBJECTMENU', 14 | type: InputType.Menu, 15 | menuOpcode: 'sensing_touchingobjectmenu' 16 | }] 17 | }, { 18 | name: 'isTouchingColor', 19 | opcode: 'sensing_touchingcolor', 20 | type: BlockType.BooleanReporter, 21 | args: [{ 22 | name: 'COLOR', 23 | type: InputType.Color 24 | }] 25 | }, { 26 | name: 'isColorTouchingColor', 27 | opcode: 'sensing_coloristouchingcolor', 28 | type: BlockType.BooleanReporter, 29 | args: [{ 30 | name: 'COLOR', 31 | type: InputType.Color 32 | }, { 33 | name: 'COLOR2', 34 | type: InputType.Color 35 | }] 36 | }, { 37 | name: 'distanceTo', 38 | opcode: 'sensing_distanceto', 39 | type: BlockType.ReporterBlock, 40 | args: [{ 41 | name: 'DISTANCETOMENU', 42 | type: InputType.Menu, 43 | menuOpcode: 'sensing_distancetomenu' 44 | }] 45 | }, { 46 | name: 'askAndWait', 47 | opcode: 'sensing_askandwait', 48 | type: BlockType.Block, 49 | args: [{ 50 | name: 'QUESTION', 51 | type: InputType.String 52 | }] 53 | }, { 54 | name: 'answer', 55 | opcode: 'sensing_answer', 56 | type: BlockType.ReporterBlock 57 | }, { 58 | name: 'isKeyPressed', 59 | opcode: 'sensing_keypressed', 60 | type: BlockType.BooleanReporter, 61 | args: [{ 62 | name: 'KEY_OPTION', 63 | type: InputType.Menu, 64 | menuOpcode: 'sensing_keyoptions' 65 | }] 66 | }, { 67 | name: 'isMouseDown', 68 | opcode: 'sensing_mousedown', 69 | type: BlockType.BooleanReporter 70 | }, { 71 | name: 'mouseX', 72 | opcode: 'sensing_mousex', 73 | type: BlockType.ReporterBlock 74 | }, { 75 | name: 'mouseY', 76 | opcode: 'sensing_mousey', 77 | type: BlockType.ReporterBlock 78 | }, { 79 | name: 'setDragMode', 80 | opcode: 'sensing_setdragmode', 81 | type: BlockType.Block, 82 | args: [{ 83 | name: 'DRAG_MODE', 84 | type: InputType.Menu, 85 | menu: i => i.value === 'draggable' ? 'draggable' : 'not draggable' 86 | }] 87 | }, { 88 | name: 'loudness', 89 | opcode: 'sensing_loudness', 90 | type: BlockType.ReporterBlock 91 | }, { 92 | name: 'timer', 93 | opcode: 'sensing_timer', 94 | type: BlockType.ReporterBlock 95 | }, { 96 | name: 'resetTimer', 97 | opcode: 'sensing_resettimer', 98 | type: BlockType.Block 99 | }, { 100 | name: 'ofStage', 101 | opcode: 'sensing_of', 102 | type: BlockType.Block, 103 | args: [{ 104 | name: 'OBJECT', 105 | type: InputType.Constant, 106 | value: '_stage_', 107 | menuOpcode: 'sensing_of_object_menu' 108 | }, { 109 | name: 'PROPERTY', 110 | type: InputType.String 111 | }] 112 | }, { 113 | name: 'of', 114 | opcode: 'sensing_of', 115 | type: BlockType.Block, 116 | args: [{ 117 | name: 'OBJECT', 118 | type: InputType.Menu, 119 | menuOpcode: 'sensing_of_object_menu' 120 | }, { 121 | name: 'PROPERTY', 122 | type: InputType.String 123 | }] 124 | }, { 125 | name: 'current', 126 | opcode: 'sensing_current', 127 | type: BlockType.Block, 128 | args: [{ 129 | name: 'CURRENTMENU', 130 | type: InputType.Menu 131 | 132 | }] 133 | }, { 134 | name: 'dayssince2000', 135 | opcode: 'sensing_dayssince2000', 136 | type: BlockType.ReporterBlock 137 | }, { 138 | name: 'username', 139 | opcode: 'sensing_username', 140 | type: BlockType.ReporterBlock 141 | }] 142 | } 143 | -------------------------------------------------------------------------------- /src/code/blocks/sound.js: -------------------------------------------------------------------------------- 1 | 2 | import InputType from '../inputType' 3 | import BlockType from '../blockType' 4 | 5 | export default { 6 | name: 'Sound', 7 | id: 'sound', 8 | blocks: [{ 9 | name: 'playUntilDone', 10 | opcode: 'sound_playuntildone', 11 | type: BlockType.Block, 12 | args: [{ 13 | name: 'SOUND_MENU', 14 | type: InputType.Menu, 15 | menu: i => i, 16 | menuOpcode: 'sound_sounds_menu' 17 | }] 18 | }, { 19 | name: 'play', 20 | opcode: 'sound_play', 21 | type: BlockType.Block, 22 | args: [{ 23 | name: 'SOUND_MENU', 24 | type: InputType.Menu, 25 | menu: i => i, 26 | menuOpcode: 'sound_sounds_menu' 27 | }] 28 | }, { 29 | name: 'stopAllSounds', 30 | opcode: 'sound_stopallsounds', 31 | type: BlockType.Block 32 | }, { 33 | name: 'changeeffectby', 34 | opcode: 'sound_changeeffectby', 35 | type: BlockType.Block, 36 | args: [{ 37 | name: 'EFFECT', 38 | type: InputType.Menu 39 | }, { 40 | name: 'VALUE', 41 | type: InputType.Number 42 | }] 43 | }, { 44 | name: 'setEffect', 45 | opcode: 'sound_seteffectto', 46 | type: BlockType.Block, 47 | args: [{ 48 | name: 'EFFECT', 49 | type: InputType.Menu 50 | }, { 51 | name: 'VALUE', 52 | type: InputType.Number 53 | }] 54 | }, { 55 | name: 'clearEffects', 56 | opcode: 'sound_cleareffects', 57 | type: BlockType.Block 58 | }, { 59 | name: 'addVolume', 60 | opcode: 'sound_changevolumeby', 61 | type: BlockType.Block, 62 | args: [{ 63 | name: 'VOLUME', 64 | type: InputType.Number 65 | }] 66 | }, { 67 | name: 'setVolume', 68 | opcode: 'sound_setvolumeto', 69 | type: BlockType.Block, 70 | args: [{ 71 | name: 'VOLUME', 72 | type: InputType.Number 73 | }] 74 | }, { 75 | name: 'volume', 76 | opcode: 'sound_volume', 77 | type: BlockType.ReporterBlock 78 | }] 79 | } 80 | -------------------------------------------------------------------------------- /src/code/generator.js: -------------------------------------------------------------------------------- 1 | import uid from './uid' 2 | import { createWithCoreBlocks } from './blocks/index' 3 | import InputType from './inputType' 4 | import BlockType from './blockType' 5 | 6 | const BlockStorage = createWithCoreBlocks() 7 | 8 | /** 9 | * @enum {ShadowType} 10 | */ 11 | const ShadowType = { 12 | /** 13 | * 1, Which will move with parent block when draging 14 | */ 15 | SameShadow: 1, 16 | /** 17 | * 2 18 | */ 19 | NoShadow: 2, 20 | /** 21 | * 3 22 | */ 23 | DifferentShadow: 3 24 | } 25 | 26 | const ArgumentType = { 27 | bool: 'b', 28 | string: 's', 29 | number: 's' 30 | } 31 | 32 | const ArgumentDefaultValue = { 33 | bool: null, 34 | string: '', 35 | number: 0 36 | } 37 | 38 | const DefaultValues = { 39 | [InputType.Boolean]: null, 40 | [InputType.Broadcast]: null, 41 | [InputType.List]: null, 42 | [InputType.Menu]: null, 43 | [InputType.Variable]: null, 44 | [InputType.Color]: '#000000', 45 | [InputType.String]: '', 46 | [InputType.Integer]: 0, 47 | [InputType.PositionInteger]: 0, 48 | [InputType.PositiveNumber]: 0, 49 | [InputType.Number]: 0, 50 | // For procedure block 51 | string: InputType.String, 52 | number: InputType.Number, 53 | bool: InputType.Boolean 54 | } 55 | 56 | const nonMenus = [ 57 | InputType.Number, 58 | InputType.Angle, 59 | InputType.String, 60 | InputType.PositionInteger, 61 | InputType.PositiveNumber, 62 | InputType.Color, 63 | InputType.Integer 64 | ] 65 | 66 | /** 67 | * 68 | * @typedef {number} ShadowType Does this block is not a part of the parent? 69 | * @typedef {string} BlockId The block id. 70 | * @typedef {[number, string | number | null]} Constant 71 | * @typedef {string | null} BlockShadow The shadow block id. 72 | * @typedef {[ShadowType, BlockId | Constant, BlockShadow]} Input A block's input. 73 | * @typedef {Object.} Inputs A block's inputs, contains constants or blocks. 74 | * 75 | * @typedef {string} FieldValue The value of the field, if is variable it will be the name of it. 76 | * @typedef {string | null} FieldId The value of the field, if is variable it will be the name of it. 77 | * @typedef {[FieldValue, FieldId]} Field A block's field. 78 | * @typedef {Object.} Fields A block's fields, contains variables or menus. 79 | * 80 | * @typedef {Object} Block A block data. 81 | * @property {string} opcode 82 | * @property {string | null} next 83 | * @property {string | null} parent 84 | * @property {Inputs} inputs 85 | * @property {Fields} fields 86 | * @property {boolean} shadow 87 | * @property {boolean} topLevel 88 | * 89 | * @typedef {Object.} Blocks A object contains all the blocks. 90 | */ 91 | 92 | class BlocksHelper { 93 | /** 94 | * Generate a helper to make blocks operation easier. 95 | * @param {Blocks} blocks 96 | * @param {*} ast 97 | */ 98 | constructor (blocks, ast) { 99 | this._blocks = blocks 100 | this._ast = ast 101 | } 102 | 103 | /** 104 | * @param {Block} block 105 | */ 106 | saveBlock (block) { 107 | const id = uid() 108 | this._blocks[id] = block 109 | return id 110 | } 111 | 112 | /** 113 | * @param {Block} block 114 | * @returns {Block} 115 | */ 116 | getTopBlock (block) { 117 | let temp = block 118 | while (temp && temp.parent !== null) { 119 | temp = this._blocks[temp.parent] 120 | } 121 | return temp || null 122 | } 123 | 124 | getProtoBlock (block) { 125 | const top = this.getTopBlock(block) 126 | if (top && top.opcode === 'procedures_definition') { 127 | return this._blocks[top.inputs.custom_block[1]] || null 128 | } 129 | return null 130 | } 131 | 132 | /** 133 | * @returns {{block: Block, id: string}} 134 | */ 135 | newBlock () { 136 | const block = { 137 | opcode: '', 138 | next: null, 139 | parent: null, 140 | inputs: {}, 141 | fields: {}, 142 | shadow: false, 143 | topLevel: false 144 | } 145 | return { block, id: this.saveBlock(block) } 146 | } 147 | 148 | /** 149 | * @param {object} block The block object 150 | * @param {Object.} block.fields The block's fields 151 | * @param {string} name 152 | * @param {string | number} value 153 | * @param {*} isVariable 154 | */ 155 | setField (block, name, value, isVariable = false) { 156 | block.fields[name] = [value, null] 157 | if (isVariable) { 158 | const variable = this._ast.variables.find(v => v.name === name) 159 | if (!variable) throw new TypeError(`Undefined variable ${name}`) 160 | block.fields[name][1] = variable.id 161 | } 162 | } 163 | 164 | /** 165 | * @param {object} block The block object 166 | * @param {Object.} block.fields The block's fields 167 | * @param {string} name 168 | * @param {string | number} value 169 | * @param {*} isVariable 170 | */ 171 | setInput (block, name, value, isVariable = false) { 172 | block.fields[name] = [value, null] 173 | if (isVariable) { 174 | const variable = this._ast.variables.find(v => v.name === name) 175 | if (!variable) throw new TypeError(`Undefined variable ${name}`) 176 | block.fields[name][1] = variable.id 177 | } 178 | } 179 | } 180 | 181 | class CompileError extends TypeError { 182 | constructor (msg, node) { 183 | super(msg) 184 | this.node = node 185 | this.type = 'CompileError' 186 | } 187 | } 188 | 189 | const te = (msg, node) => new CompileError(msg, node) 190 | const noModuleSupported = async () => { throw new Error('This generator doesn\'t supplied module resolve function.') } 191 | const noRegisterSupported = async () => { throw new Error('This generator doesn\'t supplied register function.') } 192 | 193 | /** 194 | * Generate blocks object from the ast. 195 | * @param {Object} option 196 | * @param {import('./parser').AST} option.ast The AST object that generated by parser. 197 | * @param {Blocks?} option.blocks 198 | * @param {number?} option.optimizeLevel 199 | * @param {string?} option.thisModuleHash 200 | * @param {(usingStatement: import('./parser').UsingStatement) => Promise} option.getModuleHash 201 | * @param {(usingStatement: import('./parser').UsingStatement) => Promise} option.askForModule 202 | * @param {(registerStatement: import('./parser').RegisterStatement) => Promise} option.askForRegister 203 | * @returns {Promise<{blocks: Blocks, ast: import('./parser').AST}>} The block object. 204 | */ 205 | async function generator ({ 206 | ast, 207 | blocks = {}, 208 | optimizeLevel = 0, 209 | thisModuleHash = null, 210 | getModuleHash = noModuleSupported, 211 | askForModule = noModuleSupported, 212 | askForRegister = noRegisterSupported 213 | }) { 214 | const helper = new BlocksHelper(blocks, ast) 215 | BlockStorage.reset() 216 | /** 217 | * @param {import('./parser').Node} node 218 | * @param {string?} parentId 219 | * @returns {string | import('./parser').Constant} The block's id 220 | */ 221 | function generate (node, parentId = null) { 222 | /** 223 | * @param {import('./parser').Node} node 224 | * @param {{block: Block, id: string}} block 225 | * @param {import('./blocks').ArgumentD[]} args 226 | * @param {string?} parentId 227 | */ 228 | function addArgumentsToBlock (node, block, args, parentId = null) { 229 | if (!args || args.length === 0) return 230 | const constantArgs = args.filter(v => [InputType.Constant, InputType.MenuConstant].includes(v.type)) 231 | for (let i = 0; i < constantArgs.length; i++) { 232 | const arg = constantArgs[i] 233 | if (arg.type === InputType.Constant) { 234 | if (typeof arg.value === 'string') { 235 | block.block.inputs[arg.name] = [ShadowType.SameShadow, [InputType.String, arg.value]] 236 | } else if (typeof arg.value === 'number') { 237 | block.block.inputs[arg.name] = [ShadowType.SameShadow, [InputType.Number, arg.value]] 238 | } else if (arg.value instanceof Array) { 239 | block.block.inputs[arg.name] = [ShadowType.SameShadow, arg.value] 240 | } else { 241 | console.log(`WARN: Can't add ${arg.name} value.`) 242 | } 243 | } else { // Menu Constant 244 | if ('menuOpcode' in arg) { 245 | const menuBlock = helper.newBlock() 246 | menuBlock.block.opcode = arg.menuOpcode 247 | menuBlock.block.parent = block.id 248 | menuBlock.block.shadow = true 249 | menuBlock.block.fields[arg.name] = [arg.value, null] 250 | block.block.inputs[arg.name] = [ShadowType.SameShadow, menuBlock.id] 251 | } else { 252 | block.block.fields[arg.name] = [arg.value, null] 253 | } 254 | } 255 | } 256 | const realArgs = args.filter(v => v.type !== InputType.Constant && v.type !== InputType.MenuConstant) 257 | for (let i = 0; i < realArgs.length; i++) { 258 | const arg = realArgs[i] 259 | const narg = node.args[i] 260 | const defaultValue = DefaultValues[arg.type] 261 | if (narg === null) { 262 | continue 263 | } else if (narg.type === 'Constant') { 264 | if (nonMenus.includes(arg.type)) { 265 | block.block.inputs[arg.name] = [ShadowType.SameShadow, [arg.type, narg.value]] 266 | if (arg.type === InputType.Color && typeof narg.value === 'number') { 267 | const hex = narg.value.toString(16) 268 | if (hex.length > 6) throw te(`Color number is bigger than 1048575 (${narg.value})`, node) 269 | block.block.inputs[arg.name][1][1] = '#' + '0'.repeat(6 - hex.length) + hex 270 | } 271 | } else { 272 | // So we think it's a menu 273 | if (narg.type !== 'Constant') throw te(`Can't use non-constant to argument ${i} in block ${node.name}`, narg) 274 | if (arg.type === InputType.Variable) { 275 | const variable = ast.variables.find(v => v.name === narg.value && !(v.value instanceof Array)) 276 | if (!variable) throw te(`Undefined variable ${narg.value}`, narg) 277 | if (!variable.islocal) variable.used.push([parentId, 'fields', arg.name, '1']) 278 | block.block.fields[arg.name] = [variable.name, variable.id] 279 | } else if (arg.type === InputType.List) { 280 | const variable = ast.variables.find(v => v.name === narg.value && (v.value instanceof Array)) 281 | if (!variable) throw te(`Undefined list ${narg.value}`, narg) 282 | if (!variable.islocal) variable.used.push([parentId, 'fields', arg.name, '1']) 283 | block.block.fields[arg.name] = [variable.name, variable.id] 284 | } else if (arg.type === InputType.Menu) { 285 | if (arg.menuOpcode) { 286 | const menuBlock = helper.newBlock() 287 | menuBlock.block.opcode = arg.menuOpcode 288 | menuBlock.block.parent = block.id 289 | block.block.inputs[arg.name] = [ShadowType.SameShadow, menuBlock.id] 290 | menuBlock.block.fields[arg.name] = [arg.menu ? arg.menu(narg) : narg.value, null] 291 | } else { 292 | block.block.fields[arg.name] = [arg.menu ? arg.menu(narg) : narg.value, null] 293 | } 294 | } 295 | } 296 | } else { 297 | const subBlock = generate(narg, parentId) 298 | if (typeof subBlock !== 'string') { 299 | // It is constants, or array (variable or list) 300 | if (subBlock instanceof Array) { 301 | block.block.inputs[arg.name] = [ShadowType.DifferentShadow, subBlock, [arg.type, defaultValue]] 302 | } else if (nonMenus.includes(arg.type)) { 303 | block.block.inputs[arg.name] = [ShadowType.DifferentShadow, [arg.type, narg.value], [arg.type, defaultValue]] 304 | } else { 305 | // So we think it's a menu 306 | if (arg.type === InputType.Variable) { 307 | if (narg.type !== 'Constant') throw te(`Can't use non-constant to argument ${i} in block ${node.name}`, narg) 308 | const variable = ast.variables.find(v => v.name === narg.value) 309 | if (!variable) throw te(`Undefined variable ${narg.value}`, narg) 310 | if (!variable.islocal) variable.used.push([parentId, 'fields', arg.name, '1', '2']) 311 | block.block.fields[arg.name] = [InputType.Variable, variable.name, variable.id] 312 | } 313 | } 314 | } else { 315 | if (defaultValue === null) { 316 | block.block.inputs[arg.name] = [ShadowType.SameShadow, subBlock] 317 | } else { 318 | block.block.inputs[arg.name] = [ShadowType.DifferentShadow, subBlock, [arg.type, defaultValue]] 319 | } 320 | } 321 | } 322 | } 323 | } 324 | switch (node.type) { 325 | case 'FunctionDefinition': 326 | { 327 | let parentBlockId = node.defid 328 | for (const statement of node.body) { 329 | const temp = generate(statement, parentBlockId) 330 | if (temp) { 331 | if (parentBlockId === node.id) { 332 | parentBlockId = temp 333 | node.block.next = parentBlockId 334 | } else { 335 | blocks[parentBlockId].next = temp 336 | parentBlockId = blocks[parentBlockId].next 337 | } 338 | } 339 | } 340 | return null 341 | } 342 | case 'EventExpression': 343 | { 344 | const blockd = BlockStorage.getBlock(node.name, node.args.filter(v => v.type !== InputType.Constant).length) 345 | if (!blockd || blockd.type !== BlockType.EventBlock) { 346 | throw te(`Can't find event ${node.name} with ${node.args.length} argument${node.args.length > 1 ? 's' : ''}`, node) 347 | } 348 | const evtBlock = helper.newBlock() 349 | const block = evtBlock.block 350 | block.opcode = blockd.opcode 351 | block.topLevel = true 352 | block.x = 0 353 | block.y = 0 354 | let parentBlockId = evtBlock.id 355 | for (const statement of node.body) { 356 | const temp = generate(statement, parentBlockId) 357 | if (temp) { 358 | if (parentBlockId === evtBlock.id) { 359 | parentBlockId = temp 360 | block.next = parentBlockId 361 | } else { 362 | blocks[parentBlockId].next = temp 363 | parentBlockId = blocks[parentBlockId].next 364 | } 365 | } 366 | } 367 | addArgumentsToBlock(node, evtBlock, blockd.args, parentId) 368 | return evtBlock.id 369 | } 370 | case 'FunctionCall': 371 | { 372 | // Check if it's procedure block 373 | const procNode = ast.procedures.find(v => 374 | v.name === node.name && 375 | v.params.length === node.args.length 376 | ) 377 | if (procNode) { 378 | const protoBlock = blocks[procNode.protoid] 379 | const { block: callBlock, id: callId } = helper.newBlock() 380 | callBlock.opcode = 'procedures_call' 381 | callBlock.parent = parentId 382 | callBlock.mutation = { 383 | tagName: protoBlock.mutation.tagName, 384 | children: protoBlock.mutation.children, 385 | proccode: protoBlock.mutation.proccode, 386 | warp: protoBlock.mutation.warp, 387 | argumentids: protoBlock.mutation.argumentids 388 | } 389 | callBlock.mutation.argumentids.forEach((argid, i) => { 390 | const valueType = DefaultValues[procNode.params[i].argumentType] 391 | const defaultValue = DefaultValues[valueType] 392 | if (node.args[i].type !== 'Constant') { 393 | const subBlock = generate(node.args[i], callId) 394 | callBlock.inputs[argid] = [ShadowType.DifferentShadow, subBlock, [valueType, defaultValue]] 395 | if (typeof subBlock === 'object' && subBlock.type === 'Constant') { 396 | callBlock.inputs[argid][2] = [valueType, subBlock.value] 397 | } 398 | } else { 399 | callBlock.inputs[argid] = [ShadowType.DifferentShadow, [valueType, node.args[i].value], [valueType, defaultValue]] 400 | } 401 | }) 402 | callBlock.mutation.argumentids = JSON.stringify(callBlock.mutation.argumentids) 403 | return callId 404 | } 405 | const blockd = BlockStorage.getBlock(node.name, node.args.length) 406 | if (!(blockd && [ 407 | BlockType.Block, 408 | BlockType.ReporterBlock, 409 | BlockType.BooleanReporter 410 | ].includes(blockd.type))) { 411 | throw te(`Can't find block ${node.name} with ${node.args.length} argument${node.args.length > 1 ? 's' : ''}`, node) 412 | } 413 | let isAllConstants = true 414 | if (!blockd.args) blockd.args = [] 415 | for (let i = 0; i < blockd.args.length; i++) { 416 | if (!node.args[i]) { 417 | isAllConstants = false 418 | break 419 | } else if (node.args[i] && node.args[i].type !== 'Constant') { 420 | isAllConstants = false 421 | break 422 | } 423 | } 424 | if (isAllConstants && blockd.preprocess && blockd.subn === 0 && optimizeLevel > 0) { 425 | return blockd.preprocess(node, helper) 426 | } else { 427 | const funcBlock = helper.newBlock() 428 | const block = funcBlock.block 429 | block.opcode = blockd.opcode 430 | block.parent = parentId 431 | addArgumentsToBlock(node, funcBlock, blockd.args, parentId) 432 | // Check if block has substack 433 | for (let i = 1; i <= blockd.subn; i++) { 434 | // If they have something in this substack 435 | if (i in node.cases) { 436 | const thisCase = node.cases[i] 437 | const inputName = `SUBSTACK${i > 1 ? i : ''}` 438 | block.inputs[inputName] = [ShadowType.NoShadow, null] 439 | let parentBlockId = funcBlock.id 440 | for (const statement of thisCase.body) { 441 | const temp = generate(statement, parentBlockId) 442 | if (temp) { 443 | if (parentBlockId === funcBlock.id) { 444 | parentBlockId = temp 445 | block.inputs[inputName][1] = parentBlockId 446 | } else { 447 | blocks[parentBlockId].next = temp 448 | parentBlockId = blocks[parentBlockId].next 449 | } 450 | } 451 | } 452 | } 453 | } 454 | return funcBlock.id 455 | } 456 | } 457 | case 'Literal': 458 | { 459 | const protoBlock = helper.getProtoBlock(blocks[parentId]) 460 | if (protoBlock) { 461 | const argument = protoBlock.mutation.argumentnames.indexOf(node.name) 462 | if (argument !== -1) { 463 | const argBlock = helper.newBlock() 464 | argBlock.block.opcode = 'argument_reporter_string_number' 465 | argBlock.block.parent = parentId 466 | argBlock.block.fields.VALUE = [ 467 | node.name, 468 | null 469 | ] 470 | return argBlock.id 471 | } 472 | } 473 | const variable = ast.variables.find(v => v.name === node.name) 474 | if (!variable) throw te(`Undefined variable ${node.name}`, node) 475 | return [InputType.Variable, variable.name, variable.id] 476 | } 477 | case 'Comment': 478 | { 479 | // TODO 480 | return null 481 | } 482 | default: 483 | throw new SyntaxError(`Unknown AST node type ${node.type}`) 484 | } 485 | } 486 | const usedModules = [] 487 | if (thisModuleHash) usedModules.push(thisModuleHash) 488 | /** 489 | * @param {import('./parser').AST} ast 490 | */ 491 | async function tryFindAndMixModules (ast) { 492 | if (ast.usings.length > 0 && (getModuleHash === noModuleSupported || askForModule === noModuleSupported)) noModuleSupported() 493 | for (const use of ast.usings) { 494 | const moduleHash = await getModuleHash(use) 495 | if (!usedModules.includes(moduleHash)) { 496 | usedModules.push(moduleHash) 497 | const usingModule = await askForModule(use) 498 | if (usingModule) { 499 | if (usingModule.usings.length > 0) { 500 | await tryFindAndMixModules(usingModule) 501 | } 502 | ast.variables.unshift(...usingModule.variables) 503 | ast.procedures.unshift(...usingModule.procedures) 504 | ast.listeners.unshift(...usingModule.listeners) 505 | } else { 506 | return false 507 | } 508 | } 509 | } 510 | return true 511 | } 512 | if (!await tryFindAndMixModules(ast)) return null 513 | // Register extentions. 514 | for (const r of ast.registers) { 515 | // SCRATCHSCRIPT_INCLUDE_DIR 516 | if (askForRegister === noRegisterSupported) noRegisterSupported() 517 | const def = await askForRegister(r) 518 | if (!def) throw te(`Can't find module ${r.file}${r.rename ? ` as ${r.rename}` : ''}`, r) 519 | BlockStorage.register(def, r.rename) 520 | } 521 | // Give variables a uid for indexing. 522 | ast.variables.forEach(v => { v.id = uid(); if (!v.islocal) { v.used = [] } }) 523 | // Create prototype first 524 | ast.procedures.forEach((node) => { 525 | const protoBlock = helper.newBlock() 526 | protoBlock.block.opcode = 'procedures_prototype' 527 | protoBlock.block.shadow = true 528 | const defBlock = helper.newBlock() 529 | protoBlock.block.parent = defBlock.id 530 | defBlock.block.opcode = 'procedures_definition' 531 | defBlock.block.topLevel = true 532 | defBlock.block.x = 0 533 | defBlock.block.y = 0 534 | // Link to prototype block 535 | defBlock.block.inputs.custom_block = [ShadowType.SameShadow, protoBlock.id] 536 | protoBlock.block.mutation = { 537 | tagName: 'mutation', 538 | warp: node.warp, 539 | children: [], 540 | proccode: node.name + (node.params.length > 0 ? ' ' : '') + 541 | node.params.map(v => '%' + ArgumentType[v.argumentType]).join(' '), 542 | argumentids: node.params.map(v => { 543 | const argBlock = helper.newBlock() 544 | argBlock.block.opcode = 'argument_reporter_string_number' 545 | argBlock.block.parent = protoBlock.id 546 | argBlock.block.shadow = true 547 | argBlock.block.fields.VALUE = [ 548 | v.name, 549 | null 550 | ] 551 | return argBlock.id 552 | }), 553 | argumentnames: node.params.map(v => v.name), 554 | argumentdefaults: node.params.map(v => ArgumentDefaultValue[v.argumentType]) 555 | } 556 | // Store defid and protoid 557 | node.defid = defBlock.id 558 | node.protoid = protoBlock.id 559 | }) 560 | ast.procedures.forEach(node => { generate(node) }) 561 | ast.listeners.forEach(node => { generate(node) }) 562 | ast.procedures.forEach(node => { 563 | const mutation = blocks[node.protoid].mutation 564 | mutation.argumentids = JSON.stringify(mutation.argumentids) 565 | mutation.argumentnames = JSON.stringify(mutation.argumentnames) 566 | mutation.argumentdefaults = JSON.stringify(mutation.argumentdefaults) 567 | }) 568 | return { 569 | blocks, 570 | ast 571 | } 572 | } 573 | 574 | export default generator 575 | -------------------------------------------------------------------------------- /src/code/grammar.ne: -------------------------------------------------------------------------------- 1 | 2 | @{% 3 | const moo = require("moo") 4 | const lexer = moo.compile([ 5 | 6 | {type: "COMMENT", match: /\/\*[\W\w]*?\*\//, value: x => x.slice(2, -3)}, 7 | {type: "COMMENT", match: /\/{2}(?:.*?)\n?$/, value: x => x.slice(2)}, 8 | 9 | {type: "SPACE", match: /[\s;]+/, lineBreaks: true}, 10 | {type: "DELIMITER", match: ";"}, 11 | 12 | {type: "NUMBER", match: /0x[0-9A-Fa-f]+/, value: x => parseInt(x, 16)}, 13 | {type: "NUMBER", match: /0b[01]+/, value: x => parseInt(x, 2)}, 14 | {type: "NUMBER", match: /0[0-7]+/, value: x => parseInt(x, 8)}, 15 | {type: "NUMBER", match: /-?(?:[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)/, value: x => Number(x)}, 16 | {type: "NUMBER", match: /-?[1-9]\d*/, value: x => Number(x)}, 17 | {type: "COLOR", match: /#[A-Fa-f0-9]{3}(?:[A-Fa-f0-9]{3})?/}, 18 | {type: "STRING", match: /"(?:\\["\\]|[^\n"\\])*"/, value: x => JSON.parse(x)}, 19 | {type: "STRING", match: /'(?:\\['\\]|[^\n'\\])*'/, value: x => JSON.parse('"' + x.slice(1, -1).replace(/^\\'/, "'") + '"')}, 20 | 21 | {type: "COMMA", match: ","}, 22 | {type: "LP", match: "("}, 23 | {type: "RP", match: ")"}, 24 | {type: "LMP", match: "["}, 25 | {type: "RMP", match: "]"}, 26 | {type: "LCB", match: "{"}, 27 | {type: "RCB", match: "}"}, 28 | {type: "GT", match: ">"}, 29 | {type: "LT", match: "<"}, 30 | {type: 'OP', match: /[&|\=\.]{2}|[\+\-\*\/\%\!\<\>=]/}, 31 | 32 | // Keywords 33 | {type: "KW_REGISTER", match: "register"}, 34 | {type: "KW_FOREVER", match: "forever"}, 35 | {type: "KW_ATONCE", match: "atonce"}, 36 | {type: "KW_DEFINE", match: "define"}, 37 | {type: "KW_NUMBER", match: "number"}, 38 | {type: "KW_REPEAT", match: "repeat"}, 39 | {type: "KW_STRING", match: "string"}, 40 | {type: "KW_FALSE", match: "false"}, 41 | {type: "KW_USING", match: "using"}, 42 | {type: "KW_WHILE", match: "while"}, 43 | {type: "KW_BOOL", match: "bool"}, 44 | {type: "KW_ELSE", match: "else"}, 45 | {type: "KW_NULL", match: "null"}, 46 | {type: "KW_WHEN", match: "when"}, 47 | {type: "KW_TRUE", match: "true"}, 48 | {type: "KW_LET", match: "let"}, 49 | {type: "KW_VAR", match: "var"}, 50 | {type: "KW_IF", match: "if"}, 51 | {type: "KW_IN", match: "in"}, 52 | 53 | {type: "BLOCKIDEN", match: /[a-zA-Z_][0-9a-zA-Z_]*\.[a-zA-Z_][0-9a-zA-Z_]*/}, 54 | {type: "IDEN", match: /[a-zA-Z_][0-9a-zA-Z_]*/}, 55 | 56 | {type: 'UIDEN', match: /[^\n \t"'()<>=*\/+-]+/}, 57 | {type: "ERROR", error: true}, 58 | ]) 59 | 60 | %} 61 | 62 | @lexer lexer 63 | 64 | Program -> 65 | _ {% d => ({ 66 | type: "Program", 67 | listeners: [], 68 | procedures: [], 69 | variables: [], 70 | registers: [], 71 | usings: [] 72 | }) %} 73 | | _ _Program _ {% d => ({ 74 | type: "Program", 75 | listeners: d[1].filter(ast => ast.type === "EventExpression"), 76 | procedures: d[1].filter(ast => ast.type === "FunctionDefinition"), 77 | variables: d[1].filter(ast => ast.type === "VariableDefinition"), 78 | registers: d[1].filter(ast => ast.type === "RegisterStatement"), 79 | usings: d[1].filter(ast => ast.type === "UsingStatement") 80 | }) %} 81 | 82 | _Program -> 83 | OutsideStatement 84 | | _Program __ OutsideStatement {% d => { 85 | const r = d[0].slice() 86 | r.push(d[2]) 87 | return r 88 | } %} 89 | 90 | OutsideStatement -> 91 | Comment {% id %} 92 | | RegisterStatement {% id %} 93 | | UsingStatement {% id %} 94 | | VariableDefinition {% id %} 95 | | FunctionDefinition {% id %} 96 | | EventListener {% id %} 97 | 98 | RegisterStatement -> "register" __ %STRING (__ "as" __ %IDEN | null) {% d => ({ 99 | type: "RegisterStatement", 100 | file: d[2].value, 101 | rename: d[3].length === 4 ? d[3][3].value : null, 102 | line: d[0].line, 103 | col: d[0].col 104 | }) %} 105 | 106 | UsingStatement -> "using" __ %STRING {% d => ({ 107 | type: "UsingStatement", 108 | file: d[2].value, 109 | line: d[0].line, 110 | col: d[0].col 111 | }) %} 112 | 113 | Block -> _ _Block _ {% d => d[1] %} 114 | | _ {% v => [] %} 115 | 116 | _Block -> Statement {% d => [d[0]] %} 117 | | _Block _ Statement {% d => { 118 | const r = d[0].slice() 119 | r.push(d[2]) 120 | return r 121 | } %} 122 | 123 | Statement -> _Statement (_ ";" | null) {% id %} 124 | 125 | _Statement -> 126 | Comment {% id %} 127 | | RepeatCondition {% id %} 128 | | SetVariable {% id %} 129 | | WhileCondition {% id %} 130 | | IfCondition {% id %} 131 | | FunctionCall {% id %} 132 | 133 | EventListener -> 134 | %KW_WHEN __ %BLOCKIDEN _ "(" ArgList ")" _ FunctionBody 135 | {% (d, pos, reject) => { 136 | return { 137 | type: "EventExpression", 138 | name: d[2].value, 139 | args: d[5], 140 | body: d[8], 141 | line: d[0].line, 142 | col: d[0].col 143 | } 144 | } %} 145 | 146 | FunctionDefinition -> 147 | (%KW_ATONCE __ | null) %KW_DEFINE __ %IDEN _ "(" ParamList ")" _ FunctionBody 148 | {% d => { 149 | return { 150 | type: "FunctionDefinition", 151 | warp: !!d[0][0], 152 | name: d[3].value, 153 | params: d[6], 154 | body: d[9], 155 | line: d[0][0] ? d[0][0].line : d[1].line, 156 | col: d[0][0] ?d[0][0].col : d[1].line 157 | } 158 | } %} 159 | 160 | FunctionCall -> 161 | (%BLOCKIDEN | %IDEN) _ "(" ArgList ")" InCases 162 | {% d => ({ 163 | type: "FunctionCall", 164 | name: d[0][0].value, 165 | args: d[3], 166 | cases: d[5], 167 | line: d[0][0].line, 168 | col: d[0][0].col 169 | }) %} 170 | 171 | VariableDefinition -> _VariableDefinition {% ([d]) => ({ 172 | type: "VariableDefinition", 173 | islocal: d[0].value === "let", 174 | name: d[2].value, 175 | value: d[6], 176 | line: d[0].line, 177 | col: d[0].col 178 | }) %} 179 | _VariableDefinition -> 180 | "var" __ VariableName 181 | | "var" __ VariableName _ "=" _ Constant 182 | | "var" __ VariableName _ "=" _ ListConstant 183 | | "let" __ VariableName 184 | | "let" __ VariableName _ "=" _ Constant 185 | | "let" __ VariableName _ "=" _ ListConstant 186 | 187 | VariableName -> (%IDEN | %BLOCKIDEN) {% v => v[0][0] %} 188 | 189 | @{% 190 | 191 | function ifCondition (d) { 192 | return { 193 | type: "FunctionCall", 194 | condition: d[4], 195 | trueBlock: d[8], 196 | falseBlock: d[12], 197 | line: d[0].line, 198 | col: d[0].col 199 | } 200 | } 201 | 202 | %} 203 | 204 | IfCondition -> 205 | "if" _ "(" _ Expression _ ")" _ FunctionBody {% d => ({ 206 | type: "FunctionCall", 207 | name: "control.if", 208 | args: [d[4]], 209 | cases: { 210 | 1: { 211 | type: "CaseBody", 212 | name: { 213 | type: "Constant", 214 | value: 1, 215 | line: d[0].line, 216 | col: d[0].col 217 | }, 218 | body: d[8], 219 | line: d[0].line, 220 | col: d[0].col 221 | } 222 | }, 223 | line: d[0].line, 224 | col: d[0].col 225 | }) %} 226 | | "if" _ "(" _ Expression _ ")" _ FunctionBody _ "else" _ FunctionBody {% d => ({ 227 | type: "FunctionCall", 228 | name: "control.ifelse", 229 | args: [d[4]], 230 | cases: { 231 | 1: { 232 | type: "CaseBody", 233 | name: { 234 | type: "Constant", 235 | value: 1, 236 | line: d[0].line, 237 | col: d[0].col 238 | }, 239 | body: d[8], 240 | line: d[0].line, 241 | col: d[0].col 242 | }, 243 | 2: { 244 | type: "CaseBody", 245 | name: { 246 | type: "Constant", 247 | value: 2, 248 | line: d[0].line, 249 | col: d[0].col 250 | }, 251 | body: d[12], 252 | line: d[0].line, 253 | col: d[0].col 254 | } 255 | }, 256 | line: d[0].line, 257 | col: d[0].col 258 | }) %} 259 | 260 | WhileCondition -> 261 | "forever" _ FunctionBody 262 | {% 263 | d => ({ 264 | type: "FunctionCall", 265 | name: "control.forever", 266 | args: [], 267 | cases: { 268 | 1: { 269 | type: "CaseBody", 270 | name: { 271 | type: "Constant", 272 | value: 1, 273 | line: d[0].line, 274 | col: d[0].col 275 | }, 276 | body: d[2], 277 | line: d[0].line, 278 | col: d[0].col 279 | } 280 | }, 281 | line: d[0].line, 282 | col: d[0].col 283 | }) 284 | %} 285 | | %KW_WHILE _ "(" _ Expression _ ")" _ FunctionBody 286 | {% 287 | d => ({ 288 | type: "FunctionCall", 289 | name: "control.while", 290 | args: [d[4]], 291 | cases: { 292 | 1: { 293 | type: "CaseBody", 294 | name: { 295 | type: "Constant", 296 | value: 1, 297 | line: d[0].line, 298 | col: d[0].col 299 | }, 300 | body: d[8], 301 | line: d[0].line, 302 | col: d[0].col 303 | } 304 | }, 305 | line: d[0].line, 306 | col: d[0].col 307 | }) 308 | %} 309 | 310 | RepeatCondition -> 311 | "repeat" _ "(" _ Expression _ ")" _ FunctionBody 312 | {% 313 | d => ({ 314 | type: "FunctionCall", 315 | name: "control.repeat", 316 | args: [d[4]], 317 | cases: { 318 | 1: { 319 | type: "CaseBody", 320 | name: { 321 | type: "Constant", 322 | value: 1, 323 | line: d[0].line, 324 | col: d[0].col 325 | }, 326 | body: d[8], 327 | line: d[0].line, 328 | col: d[0].col 329 | } 330 | }, 331 | line: d[0].line, 332 | col: d[0].col 333 | }) 334 | %} 335 | 336 | ArgList -> _ {% d => [] %} 337 | | _ ExpList _ {% d => d[1] %} 338 | 339 | # Cases 340 | 341 | InCases -> null {% d => ({}) %} 342 | | _ _InCases {% d => Object.fromEntries(d[1]) %} 343 | 344 | _InCases -> 345 | InCase 346 | | _InCases __ InCase {% d => [d[2], ...d[0]] %} 347 | 348 | InCase -> "in" __ Constant __ FunctionBody {% d => [d[2].value, { 349 | type: "CaseBody", 350 | name: d[2], 351 | body: d[4], 352 | line: d[0].line, 353 | col: d[0].col 354 | }] %} 355 | 356 | ParamList -> 357 | _ {% d => [] %} 358 | | _ _ParamList _ {% d => d[1] %} 359 | 360 | _ParamList -> 361 | Param 362 | | _ParamList _ "," _ Param {% d => { const t = d[0]; t.push(d[4]); return t } %} 363 | 364 | 365 | Param -> 366 | %IDEN (_ ":" _ ("string" | "number" | "bool")):? {% d => ({ 367 | type: "Argument", 368 | name: d[0].value, 369 | argumentType: d[1] ? d[1][3][0].value : "string", 370 | line: d[0].line, 371 | col: d[0].col 372 | }) %} 373 | 374 | FunctionBody -> "{" Block "}" {% d => d[1] %} 375 | 376 | SetVariable -> 377 | %IDEN _ "=" _ Expression 378 | {% d => ({ 379 | type: "FunctionCall", 380 | name: "data.setVar", 381 | args: [{ 382 | type: "Constant", 383 | value: d[0].value 384 | }, d[4]], 385 | line: d[0].line, 386 | col: d[0].col 387 | }) %} 388 | 389 | ExpList -> 390 | Expression {% d => (d[0] === undefined || d[0] === null) ? [] : d %} 391 | | ExpList _ "," _ Expression 392 | {% d => { 393 | const r = d[0].slice() 394 | r.push(d[4]) 395 | return r 396 | } %} 397 | 398 | # Expressions 399 | Expression -> ExpOr {% id %} 400 | 401 | @{% 402 | function tryCalculate ([left,,sym,,right]) { 403 | const blocks = { 404 | "+": "math.add", 405 | "-": "math.subtract", 406 | "*": "math.multiply", 407 | "/": "math.divide", 408 | "<": "math.lt", 409 | ">": "math.gt", 410 | "%": "math.mod", 411 | "||": "math.or", 412 | "&&": "math.and", 413 | "!": "math.not", 414 | "==": "math.equals", 415 | "..": "math.join", 416 | } 417 | return { 418 | type: "FunctionCall", 419 | name: blocks[sym], 420 | args: [left, right].filter(v => v !== undefined), 421 | line: left.line, 422 | col: left.col 423 | } 424 | } 425 | %} 426 | 427 | Parenthesized -> "(" Expression ")" {% d => d[1] %} 428 | 429 | ExpOr -> ExpOr _ "||" _ ExpAnd {% tryCalculate %} 430 | | ExpAnd {% id %} 431 | 432 | ExpAnd -> ExpAnd _ "&&" _ ExpComparison {% tryCalculate %} 433 | | ExpComparison {% id %} 434 | 435 | ExpComparison -> 436 | ExpComparison _ ">" _ ExpConcatenation {% tryCalculate %} 437 | | ExpComparison _ "<" _ ExpConcatenation {% tryCalculate %} 438 | | ExpEquals {% id %} 439 | 440 | ExpEquals -> ExpComparison _ "==" _ ExpConcatenation {% tryCalculate %} 441 | | ExpConcatenation {% id %} 442 | 443 | ExpConcatenation -> 444 | ExpConcatenation _ ".." _ ExpSum {% tryCalculate %} 445 | | ExpSum {% id %} 446 | 447 | ExpSum -> 448 | ExpSum _ "+" _ ExpProduct {% tryCalculate %} 449 | | ExpSum _ "-" _ ExpProduct {% tryCalculate %} 450 | | ExpProduct {% id %} 451 | 452 | ExpProduct -> 453 | ExpProduct _ "*" _ ExpSum {% tryCalculate %} 454 | | ExpProduct _ "/" _ ExpSum {% tryCalculate %} 455 | | ExpProduct _ "%" _ ExpSum {% tryCalculate %} 456 | | "!" _ ExpSum {% d => tryCalculate([d[2],, d[0]]) %} 457 | | Atom {% id %} 458 | 459 | Atom -> 460 | %BLOCKIDEN {% ([name]) => ({ 461 | type: "FunctionCall", 462 | name: name.value, 463 | args: [], 464 | cases: {}, 465 | line: name.line, 466 | col: name.col 467 | }) %} 468 | | %IDEN {% ([name]) => ({ 469 | type: "Literal", 470 | name: name.value, 471 | line: name.line, 472 | col: name.col 473 | }) %} 474 | | Constant {% id %} 475 | | Parenthesized {% id %} 476 | | FunctionCall {% id %} 477 | 478 | ListConstant -> "[" _ ListItems _ "]" {% d => ({ 479 | type: "Constant", 480 | value: d[2], 481 | line: d[0].line, 482 | col: d[0].col 483 | }) %} 484 | | "[" _ "]" {% d => ({ 485 | type: "Constant", 486 | value: [], 487 | line: d[0].line, 488 | col: d[0].col 489 | }) %} 490 | 491 | ListItems -> 492 | Constant {% d => [d[0]]%} 493 | | ListItems _ "," _ Constant {% d => { 494 | const r = d[0].slice() 495 | r.push(d[4]) 496 | return r 497 | } %} 498 | 499 | Constant -> 500 | %STRING {% ([d]) => ({ 501 | type: "Constant", 502 | value: d.value, 503 | line: d.line, 504 | col: d.col 505 | }) %} 506 | | %COLOR {% ([d], l ,reject) => { 507 | if ([3, 6].includes(d.value.length - 1)) { 508 | if (d.value.length - 1 === 3) { 509 | return { 510 | type: "Constant", 511 | value: d.value[0] + d.value[1].repeat(2) + d.value[2].repeat(2) + d.value[3].repeat(2), 512 | line: d.line, 513 | col: d.col 514 | } 515 | } 516 | return { 517 | type: "Constant", 518 | value: d.value, 519 | line: d.line, 520 | col: d.col 521 | } 522 | } 523 | return reject 524 | } %} 525 | | %NUMBER {% ([d]) => ({ 526 | type: "Constant", 527 | value: d.value, 528 | line: d.line, 529 | col: d.col 530 | }) %} 531 | | %KW_FALSE {% () => null %} 532 | | %KW_NULL {% () => null %} 533 | | %KW_TRUE {% () => ({ 534 | type: "FunctionCall", 535 | name: "math.not", 536 | args: [null], 537 | cases: {}, 538 | line: name.line, 539 | col: name.col 540 | })%} 541 | 542 | _ -> null {% null %} 543 | | _ Comment {% d => d[1] %} 544 | | %SPACE {% null %} 545 | __ -> _ Comment {% d => d[1] %} 546 | | %SPACE {% null %} 547 | 548 | Comment -> %COMMENT 549 | {% d => ({ 550 | type: "Comment", 551 | message: d[0].value, 552 | line: d[0].line, 553 | col: d[0].col 554 | }) %} -------------------------------------------------------------------------------- /src/code/index.js: -------------------------------------------------------------------------------- 1 | import parser from './parser' 2 | import generator from './generator' 3 | import BlockType from './blockType' 4 | import InputType from './inputType' 5 | import * as BlockStorage from './blocks' 6 | 7 | export default { 8 | parser, 9 | generator, 10 | BlockType, 11 | InputType, 12 | BlockStorage 13 | } 14 | -------------------------------------------------------------------------------- /src/code/inputType.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @enum {number} 3 | * @readonly 4 | * @exports 5 | */ 6 | const InputType = { 7 | /** 8 | * 2, For compiler use. 9 | */ 10 | Boolean: 2, 11 | /** 12 | * 4 13 | */ 14 | Number: 4, 15 | /** 16 | * 5 17 | */ 18 | PositiveNumber: 5, 19 | /** 20 | * 6 21 | */ 22 | PositionInteger: 6, 23 | /** 24 | * 7 25 | */ 26 | Integer: 7, 27 | /** 28 | * 8 29 | */ 30 | Angle: 8, 31 | /** 32 | * 9 33 | */ 34 | Color: 9, 35 | /** 36 | * 10 37 | */ 38 | String: 10, 39 | /** 40 | * 11 41 | */ 42 | Broadcast: 11, 43 | /** 44 | * 12 45 | */ 46 | Variable: 12, 47 | /** 48 | * 13 49 | */ 50 | List: 13, 51 | /** 52 | * 20 53 | */ 54 | Menu: 20, 55 | /** 56 | * 30 57 | */ 58 | Constant: 30, 59 | /** 60 | * 31 61 | */ 62 | MenuConstant: 31 63 | } 64 | 65 | export default InputType 66 | -------------------------------------------------------------------------------- /src/code/parser.js: -------------------------------------------------------------------------------- 1 | import nearley from 'nearley' 2 | import nearleyGrammar from './grammar.ne' 3 | const te = token => new TypeError(`Unknown token "${token.value}" at ${token.location.line}:${token.location.row}`) 4 | 5 | /** 6 | * 7 | * @typedef {Object} Literal 8 | * @property {"Literal"} type 9 | * @property {string} name 10 | * @property {number} line 11 | * @property {number} col 12 | * 13 | * @typedef {Object} Constant 14 | * @property {"Constant"} type 15 | * @property {string} name 16 | * @property {number} line 17 | * @property {number} col 18 | * 19 | * @typedef {Literal | Constant | FunctionCall} Expression 20 | * 21 | * @typedef {FunctionCall | LoopExpression | IfCondition | Comment} Statement 22 | * 23 | * @typedef {Object} FunctionCall 24 | * @property {"FunctionCall"} type 25 | * @property {Expression[]} args 26 | * @property {string} name 27 | * @property {number} line 28 | * @property {number} col 29 | * 30 | * @typedef {Object} Argument 31 | * @property {"Argument"} type 32 | * @property {string} name 33 | * @property {"string" | "number" | "bool"} argumentType 34 | * @property {number} line 35 | * @property {number} col 36 | * 37 | * @typedef {Object} FunctionDefinition 38 | * @property {"FunctionDefinition"} type 39 | * @property {string} name 40 | * @property {Argument[]} params 41 | * @property {Expression[]} args 42 | * @property {number} line 43 | * @property {number} col 44 | * 45 | * @typedef {Object} IfCondition 46 | * @property {"IfCondition"} type 47 | * @property {Expression} condition 48 | * @property {Statement[]} trueBlock 49 | * @property {Statement[]} falseBlock 50 | * @property {number} line 51 | * @property {number} col 52 | * 53 | * @typedef {Object} LoopExpression 54 | * @property {"LoopExpression"} type 55 | * @property {"forever" | "condition" | "repeat"} loop 56 | * @property {Expression} time 57 | * @property {Expression} condition 58 | * @property {Statement[]} body 59 | * @property {number} line 60 | * @property {number} col 61 | * 62 | * @typedef {Object} EventExpression 63 | * @property {"EventExpression"} type 64 | * @property {string} name 65 | * @property {Expression[]} args 66 | * @property {Statement[]} body 67 | * @property {number} line 68 | * @property {number} col 69 | * 70 | * @typedef {Object} VariableDefinition 71 | * @property {"VariableDefinition"} type 72 | * @property {string} name 73 | * @property {boolean} islocal 74 | * @property {Constant} value 75 | * @property {number} line 76 | * @property {number} col 77 | * 78 | * @typedef {Object} UsingStatement 79 | * @property {"UsingStatement"} type 80 | * @property {string} file 81 | * @property {number} line 82 | * @property {number} col 83 | * 84 | * @typedef {Object} RegisterStatement 85 | * @property {"RegisterStatement"} type 86 | * @property {string} file 87 | * @property {string?} rename 88 | * @property {number} line 89 | * @property {number} col 90 | * 91 | * @typedef { EventExpression | FunctionCall | IfCondition | LoopExpression | Constant | Comment | Literal} Node 92 | * 93 | * @typedef {Object} AST 94 | * @property {"Program"} type 95 | * @property {string?} name 96 | * @property {EventExpression[]} listeners 97 | * @property {FunctionDefinition[]} procedures 98 | * @property {VariableDefinition[]} variables 99 | * @property {UsingStatement[]} usings 100 | * @property {RegisterStatement[]} registers 101 | */ 102 | 103 | /** 104 | * Parse source code into ast. 105 | * @param {string} src The tokens array 106 | * @returns {AST} 107 | */ 108 | function parser (src) { 109 | const grammar = nearley.Grammar.fromCompiled(nearleyGrammar) 110 | const ne = new nearley.Parser(grammar) 111 | ne.lexer.reset() 112 | ne.feed(src) 113 | const result = ne.finish() 114 | if (result.length === 0) { 115 | throw te('Unexpected end token.') 116 | } 117 | if (result.length !== 1) { 118 | console.log(`Warning: Parser has ${result.length} results.`) 119 | // (result.slice(0, 32).map(JSON.stringify)) 120 | } 121 | return result[0] 122 | } 123 | 124 | export default parser 125 | -------------------------------------------------------------------------------- /src/code/uid.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview UID generator, from Blockly. From scratch-vm. 3 | */ 4 | 5 | /** 6 | * Legal characters for the unique ID. 7 | * Should be all on a US keyboard. No XML special characters or control codes. 8 | * Removed $ due to issue 251. 9 | * @private 10 | */ 11 | const soup_ = '!#%()*+,-./:;=?@[]^_`{|}~' + 12 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' 13 | let counter = 0 14 | /** 15 | * Generate a unique ID, from Blockly. This should be globally unique. 16 | * 87 characters ^ 20 length > 128 bits (better than a UUID). 17 | * @return {string} A globally unique ID string. 18 | */ 19 | const uid = function () { 20 | const length = 20 21 | const soupLength = soup_.length 22 | const id = [] 23 | for (let i = 0; i < length; i++) { 24 | id[i] = soup_.charAt(Math.random() * soupLength) 25 | } 26 | return id.join('') + (counter++).toString(16) 27 | } 28 | 29 | export default uid 30 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import code from './code/index' 2 | import projectParser from './project/parser' 3 | 4 | const complieInNodeJS = () => { throw new Error('This is only nodejs use.') } 5 | 6 | export { 7 | code as default, 8 | projectParser, 9 | complieInNodeJS 10 | } 11 | -------------------------------------------------------------------------------- /src/index.node.js: -------------------------------------------------------------------------------- 1 | 2 | import { promises as fs, existsSync } from 'fs' 3 | import path from 'path' 4 | import JSZip from 'jszip' 5 | import projectParser from './project/parser' 6 | import code from './code/index' 7 | 8 | import EMPTY_AUDIO from './project/emptyAudio' 9 | import EMPTY_SVG from './project/emptySvg' 10 | import Package from '../package.json' 11 | 12 | import crypto from 'crypto' 13 | 14 | function createFileDescription ({ hash, filename, name, x, y }) { 15 | return { 16 | assetId: hash, 17 | md5ext: filename, 18 | dataFormat: path.extname(filename).substr(1), 19 | name, 20 | rotationCenterX: x, 21 | rotationCenterY: y 22 | } 23 | } 24 | 25 | let layerOrder = 0 26 | function createTarget (isStage = false) { 27 | return { 28 | isStage, 29 | name: isStage ? 'Stage' : '', 30 | variables: {}, 31 | lists: {}, 32 | broadcasts: {}, 33 | blocks: {}, 34 | comments: {}, 35 | currentCostume: 0, 36 | costumes: [], 37 | sounds: [], 38 | volume: 100, 39 | layerOrder: isStage ? 0 : ++layerOrder, 40 | tempo: 60, 41 | videoTransparency: 50, 42 | videoState: 'off', 43 | textToSpeechLanguage: null 44 | } 45 | } 46 | 47 | const setPath = (obj, path = [''], value = undefined) => { 48 | let temp = obj 49 | for (const key of path.slice(0, -2)) { 50 | temp = temp[key] 51 | } 52 | temp[path[path.length - 1]] = value 53 | } 54 | 55 | async function complieCode (file) { 56 | try { 57 | const dir = path.dirname(file) 58 | return await code.generator({ 59 | ast: await code.parser(await fs.readFile(file, { encoding: 'utf8' })), 60 | async getModuleHash (use) { 61 | return path.resolve(dir, use.file) 62 | }, 63 | async askForModule (use) { 64 | const modulePath = path.resolve(dir, use.file) 65 | const source = await fs.readFile(modulePath, { encoding: 'utf8' }) 66 | try { 67 | return code.parser(source) 68 | } catch (err) { 69 | if (err.type === 'CompileError') { 70 | if (err.node) { 71 | console.log('CompileError:', err.message + '\n On compiling code: ' + modulePath + ':' + err.node.line + ':' + err.node.col) 72 | } 73 | return null 74 | } else if (err.token) { 75 | console.log(`CompileError: Unknown token ${err.token.text} (${err.token.type})\n On compiling code: ${modulePath}:${err.token.line}:${err.token.col}`) 76 | return null 77 | } else throw err 78 | } 79 | }, 80 | async askForRegister (reg) { 81 | const relativeFile = path.resolve(dir, reg.file) 82 | if (existsSync(relativeFile)) { 83 | return await import(/* webpackIgnore: true */ relativeFile) 84 | } 85 | if (existsSync(relativeFile + '.js')) { 86 | return await import(/* webpackIgnore: true */ relativeFile) 87 | } 88 | const envPath = process.env.SCRATCHSCRIPT_INCLUDE_DIR 89 | ? path.resolve(process.env.SCRATCHSCRIPT_INCLUDE_DIR, reg.file) 90 | : path.resolve(__dirname, reg.file) 91 | if (existsSync(envPath)) { 92 | return await import(/* webpackIgnore: true */ relativeFile) 93 | } 94 | if (existsSync(envPath + '.js')) { 95 | return await import(/* webpackIgnore: true */ relativeFile) 96 | } 97 | return null 98 | } 99 | }) 100 | } catch (err) { 101 | if (err.type === 'CompileError') { 102 | if (err.node) { 103 | console.log('CompileError:', err.message + '\n On compiling code: ' + file + ':' + err.node.line + ':' + err.node.col) 104 | } 105 | return null 106 | } else if (err.token) { 107 | console.log(`CompileError: Unknown token ${err.token.text} (${err.token.type})\n On compiling code: ${file}:${err.token.line}:${err.token.col}`) 108 | } else throw err 109 | } 110 | } 111 | 112 | async function complieCodeForTarget (start, target, stage = null) { 113 | try { 114 | const codeResults = await complieCode(start) 115 | if (!codeResults) return 116 | for (const variable of codeResults.ast.variables) { 117 | if (!variable.islocal && stage && target !== stage) { 118 | if (variable.value.value instanceof Array) { 119 | const stageList = Object.entries(stage.lists).find(v => v[1][0] === variable.name) 120 | if (stageList) { 121 | for (const usedPath of variable.used) { 122 | setPath(codeResults.blocks, usedPath, stageList[1]) 123 | } 124 | } else { 125 | stage.lists[variable.id] = [variable.name, variable.value ? variable.value.map(v => v.value) : []] 126 | } 127 | } else { 128 | const stageVar = Object.entries(stage.variables).find(v => v[1][0] === variable.name) 129 | if (stageVar) { 130 | for (const usedPath of variable.used) { 131 | setPath(codeResults.blocks, usedPath, stageVar[1]) 132 | } 133 | } else { 134 | stage.variables[variable.id] = [variable.name, variable.value ? variable.value.value : ''] 135 | } 136 | } 137 | } else { 138 | if (variable.value instanceof Array) { 139 | target.lists[variable.id] = [variable.name, variable.value ? variable.value.map(v => v.value) : []] 140 | } else { 141 | target.variables[variable.id] = [variable.name, variable.value ? variable.value.value : ''] 142 | } 143 | } 144 | } 145 | target.blocks = codeResults.blocks 146 | } catch (err) { 147 | if (err.type === 'CompileError') { 148 | if (err.node) { 149 | console.log('CompileError: ', err.message + '\n On compiling code: ' + start + ':' + err.node.line + ':' + err.node.col) 150 | } 151 | return null 152 | } else if (err.token) { 153 | console.log(`CompileError: Unknown token ${err.token.text} (${err.token.type})\n On compiling code: ${start}:${err.token.line}:${err.token.col}`) 154 | } else throw err 155 | } 156 | } 157 | 158 | /* 159 | Resources: 160 | info.stage.costumes[].file 161 | info.stage.sounds[].file 162 | info.sprites[]costumes[].file 163 | info.sprites[]sounds[].file 164 | info.sprites[]code.file 165 | */ 166 | 167 | function * nameGenerator (nameSet) { 168 | let counter = 0 169 | while (true) { 170 | counter++ 171 | const thisName = `Sprite (${counter})` 172 | if (!nameSet.has(thisName)) { 173 | yield thisName 174 | } 175 | } 176 | } 177 | 178 | async function parseProject ({ projectInfo: proj, projectDir }) { 179 | const zip = new JSZip() 180 | const { stage, sprites } = proj.info 181 | const project = { 182 | targets: [createTarget(true)], 183 | monitors: [], 184 | extensions: [], 185 | meta: { 186 | semver: '3.0.0', 187 | agent: 'ScratchScriptKit/' + Package.version 188 | } 189 | } 190 | 191 | async function packFile (file) { 192 | const data = await fs.readFile(path.resolve(projectDir, file)) 193 | const hash = crypto.createHash('md5').update(data).digest('hex') 194 | const filename = hash + path.extname(file) 195 | zip.file(filename, data) 196 | return { hash, filename } 197 | } 198 | 199 | function packSvg (name) { 200 | if (!zip.files[EMPTY_SVG.filename]) { 201 | zip.file(EMPTY_SVG.filename, EMPTY_SVG.data) 202 | } 203 | return { 204 | assetId: EMPTY_SVG.hash, 205 | md5ext: EMPTY_SVG.filename, 206 | dataFormat: EMPTY_SVG.type, 207 | name, 208 | rotationCenterX: 0, 209 | rotationCenterY: 0 210 | } 211 | } 212 | 213 | function packEmptyAudio (name) { 214 | if (!zip.files[EMPTY_AUDIO.filename]) { 215 | zip.file(EMPTY_AUDIO.filename, EMPTY_AUDIO.data) 216 | } 217 | return { 218 | assetId: EMPTY_AUDIO.hash, 219 | md5ext: EMPTY_AUDIO.filename, 220 | dataFormat: 'wav', 221 | rate: 44100, 222 | sampleCount: 0, 223 | name 224 | } 225 | } 226 | 227 | // Collage resources 228 | let counter = 0 229 | if (stage) { 230 | if (stage.costumes) { 231 | if (stage.costumes.length === 0) { 232 | project.targets[0].costumes.push(packSvg('Background ' + (counter++))) 233 | } else { 234 | for (const costume of stage.costumes) { 235 | if (costume.file) { 236 | const desc = await packFile(path.resolve(projectDir, costume.file)) 237 | project.targets[0].costumes.push( 238 | createFileDescription({ 239 | hash: desc.hash, 240 | filename: desc.filename, 241 | name: costume.name 242 | }) 243 | ) 244 | } else { 245 | project.targets[0].costumes.push(packSvg('Background ' + (counter++))) 246 | } 247 | } 248 | } 249 | } else { 250 | project.targets[0].costumes.push(packSvg('Background ' + (counter++))) 251 | } 252 | if (stage.code && stage.code.file) { 253 | await complieCodeForTarget(path.resolve(projectDir, stage.code.file), project.targets[0]) 254 | } 255 | } else { 256 | project.targets[0].costumes.push(packSvg('Background ' + (counter++))) 257 | } 258 | 259 | // Sprites 260 | if (sprites && sprites.length > 0) { 261 | const nameSet = new Set() 262 | const nameGen = nameGenerator(nameSet) 263 | for (const sprite of sprites) { 264 | const target = createTarget() 265 | target.name = (nameSet.has(sprite.name) || !sprite.name) ? nameGen.next().value : sprite.name 266 | target.size = sprite.size || 100 267 | target.direction = sprite.direction || 90 268 | target.rotationType = sprite.rotationType || 'all around' 269 | target.currentCostume = sprite.costume || 0 270 | target.draggable = sprite.draggable || false 271 | if (sprite.pos) { 272 | target.x = sprite.pos.x || 0 273 | target.y = sprite.pos.y || 0 274 | } 275 | if (sprite.code && sprite.code.file) { 276 | await complieCodeForTarget(path.resolve(projectDir, sprite.code.file), target, project.targets[0]) 277 | } 278 | counter = 0 279 | if (sprite.costumes) { 280 | for (const costume of sprite.costumes) { 281 | if (costume.file) { 282 | const desc = await packFile(path.resolve(projectDir, costume.file)) 283 | target.costumes.push( 284 | createFileDescription({ 285 | hash: desc.hash, 286 | filename: desc.filename, 287 | name: costume.name 288 | }) 289 | ) 290 | } else { 291 | target.costumes.push(packSvg('Costume ' + (counter++))) 292 | } 293 | } 294 | } else { 295 | target.costumes.push(packSvg('Costume ' + (counter++))) 296 | } 297 | counter = 0 298 | if (sprite.sounds) { 299 | for (const sound of sprite.sounds) { 300 | if (sound.file) { 301 | const desc = await packFile(path.resolve(projectDir, sound.file)) 302 | target.sounds.push( 303 | createFileDescription({ 304 | hash: desc.hash, 305 | filename: desc.filename, 306 | name: sound.name 307 | }) 308 | ) 309 | } else { 310 | target.sounds.push(packEmptyAudio('Sound ' + (counter++))) 311 | } 312 | } 313 | } 314 | project.targets.push(target) 315 | } 316 | } 317 | 318 | zip.file('project.json', JSON.stringify(project)) 319 | return zip.generateAsync({ type: 'uint8array' }) 320 | } 321 | 322 | async function complieInNodeJS ({ 323 | projectDir 324 | }) { 325 | const projectFile = path.join(projectDir, './project.yaml') 326 | if ((await fs.stat(projectFile)).isFile()) { 327 | const projectInfo = projectParser(await fs.readFile(projectFile, { encoding: 'utf8' })) 328 | return parseProject({ projectInfo, projectDir }) 329 | } else if ((await fs.stat(path.join(projectDir, './project.json'))).isFile()) { 330 | const projectInfo = projectParser(await fs.readFile(projectFile, { encoding: 'utf8' }), true) 331 | return parseProject({ projectInfo, projectDir }) 332 | } else { 333 | throw new Error("Can't find project info file. (project.yaml or project.json)") 334 | } 335 | } 336 | 337 | export { 338 | code as default, 339 | projectParser, 340 | complieInNodeJS 341 | } 342 | -------------------------------------------------------------------------------- /src/playground/default.sb3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Steve-xmh/scratch-script/29b5ffc48b2706afee57c269822344a152281ec3/src/playground/default.sb3 -------------------------------------------------------------------------------- /src/playground/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ScratchScript Playground 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |

ScratchScript Playground

15 |
16 | Here is a playground use to debug ScratchScript compiler.
17 | If you like, you can make it as a drynamic code editor. 18 |
19 |
20 | 21 |
22 |
23 |
24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /src/playground/playground.js: -------------------------------------------------------------------------------- 1 | import GUI, { AppStateHOC } from 'scratch-gui' 2 | import ScratchScript from '../index' 3 | import React from 'react' 4 | import ReactDOM from 'react-dom' 5 | import CodeMirror from 'codemirror' 6 | import DefaultProject from './default.sb3' 7 | import Package from '../../package.json' 8 | import JSZip from 'jszip' 9 | import defaultsDeep from 'lodash.defaultsdeep' 10 | const appTarget = document.querySelector('#scratchgui') 11 | const textArea = document.querySelector('textarea') 12 | GUI.setAppElement(appTarget) 13 | const WrappedGui = AppStateHOC(GUI) 14 | const defaultCode = `var direction = 0; 15 | when events.flagClicked() { 16 | looks.sayFor('Hello ScratchScript!', 3); 17 | forever { 18 | direction = 1; 19 | repeat (10) { 20 | motion.changeY(5 * direction); 21 | } 22 | if (direction == 1) { 23 | direction = -1; 24 | } else { 25 | direction = 1; 26 | } 27 | } 28 | }` 29 | 30 | window.CodeArea = CodeMirror.fromTextArea(textArea, { 31 | lineNumbers: true 32 | }) 33 | window.CodeArea.setValue(defaultCode) 34 | window.CodeArea.getWrapperElement().style = 'height: calc(100% - 2rem); margin: 1rem; flex: 0.35; border-style: solid; border-width: 1px; border-color: black' 35 | 36 | const compiledTemplate = { 37 | targets: [{ 38 | isStage: true, 39 | name: 'Stage', 40 | variables: {}, 41 | lists: {}, 42 | broadcasts: {}, 43 | blocks: {}, 44 | comments: {}, 45 | currentCostume: 0, 46 | costumes: [], 47 | sounds: [], 48 | volume: 100, 49 | layerOrder: 0, 50 | tempo: 60, 51 | videoTransparency: 50, 52 | videoState: 'off', 53 | textToSpeechLanguage: null 54 | }], 55 | monitors: [], 56 | extensions: [], 57 | meta: { 58 | semver: '3.0.0', 59 | agent: 'ScratchScriptKit/' + Package.version 60 | } 61 | } 62 | 63 | // Register change and send to vm 64 | function onVmInit (vm) { 65 | let loadingProject = false 66 | let delayHandle = null 67 | let requiredUpdate = false 68 | async function compile (code) { 69 | if (loadingProject) return 70 | loadingProject = true 71 | try { 72 | const t = Date.now() 73 | const rawCode = code.getValue() 74 | console.log(rawCode) 75 | const ast = ScratchScript.parser(rawCode) 76 | console.log(Date.now() - t, ast) 77 | const result = await ScratchScript.generator({ ast }) 78 | console.log(Date.now() - t, result) 79 | const newProj = defaultsDeep({}, compiledTemplate) 80 | const stage = newProj.targets[0] 81 | stage.blocks = result.blocks 82 | for (const variable of result.ast.variables) { 83 | if (!variable.value) { 84 | stage.variables[variable.id] = [variable.name, ''] 85 | } else if (variable.value.value instanceof Array) { 86 | stage.lists[variable.id] = [variable.name, variable.value ? variable.value.value.map(v => v.value) : []] 87 | } else { 88 | stage.variables[variable.id] = [variable.name, variable.value ? variable.value.value : ''] 89 | } 90 | } 91 | console.log(newProj) 92 | const zip = await JSZip.loadAsync(DefaultProject) 93 | zip.file('project.json', 94 | JSON.stringify( 95 | defaultsDeep( 96 | {}, 97 | JSON.parse( 98 | await zip.file('project.json') 99 | .async('text') 100 | ), newProj 101 | ) 102 | ) 103 | ) 104 | await vm.loadProject(await zip.generateAsync({ type: 'uint8array' })) 105 | loadingProject = false 106 | } catch (err) { 107 | console.warn(err) 108 | } 109 | if (requiredUpdate) { 110 | requiredUpdate = false 111 | compile(code) 112 | return 113 | } 114 | loadingProject = false 115 | } 116 | window.CodeArea.on('change', code => { 117 | requiredUpdate = true 118 | if (delayHandle) clearTimeout(delayHandle) 119 | delayHandle = setTimeout(() => { 120 | requiredUpdate = false 121 | compile(code) 122 | }, 1000) 123 | }) 124 | loadingProject = true 125 | vm.loadProject(DefaultProject).then(() => { loadingProject = false }) 126 | console.log('Registered VM!', vm) 127 | } 128 | 129 | window.GUI = ReactDOM.render(React.createElement(WrappedGui, { 130 | canSave: false, 131 | isStandalone: true, 132 | backpackVisible: false, 133 | onVmInit 134 | }), appTarget) 135 | -------------------------------------------------------------------------------- /src/project/emptyAudio.js: -------------------------------------------------------------------------------- 1 | // A empty audio in mp3 format. 2 | 3 | export default { 4 | hash: '94b8c2c5d15e5a3d77c2e34eed3c7c87', 5 | filename: '94b8c2c5d15e5a3d77c2e34eed3c7c87.mp3', 6 | type: 'mp3', 7 | data: new Uint8Array([ 8 | 73, 68, 51, 4, 0, 0, 0, 0, 1, 6, 84, 88, 9 | 88, 88, 0, 0, 0, 18, 0, 0, 3, 109, 97, 106, 10 | 111, 114, 95, 98, 114, 97, 110, 100, 0, 105, 11 | 115, 111, 109, 0, 84, 88, 88, 88, 0, 0, 0, 19, 12 | 0, 0, 3, 109, 105, 110, 111, 114, 95, 118, 13 | 101, 114, 115, 105, 111, 110, 0, 53, 49, 50, 14 | 0, 84, 88, 88, 88, 0, 0, 0, 32, 0, 0, 3, 99, 15 | 111, 109, 112, 97, 116, 105, 98, 108, 101, 16 | 95, 98, 114, 97, 110, 100, 115, 0, 105, 115, 17 | 111, 109, 105, 115, 111, 50, 109, 112, 52, 18 | 49, 0, 84, 83, 83, 69, 0, 0, 0, 15, 0, 0, 3, 19 | 76, 97, 118, 102, 53, 56, 46, 51, 49, 46, 20 | 49, 48, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 21 | 255, 251, 80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23 | 0, 0, 0, 0, 0, 0, 0, 0, 73, 110, 102, 111, 0, 24 | 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 208, 0, 0, 0, 25 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 27 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31 | 0, 0, 0, 0, 0, 76, 97, 118, 99, 53, 56, 46, 53, 32 | 53, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33 | 0, 0, 0, 0, 0, 0, 0, 208, 0, 0, 215, 127, 0, 0, 34 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 35 | ]) 36 | } 37 | -------------------------------------------------------------------------------- /src/project/emptySvg.js: -------------------------------------------------------------------------------- 1 | 2 | export default { 3 | data: '' + 4 | '' + 5 | '', 8 | filename: '21b6f368d34e6da2b37c476982d1f393.svg', 9 | hash: '21b6f368d34e6da2b37c476982d1f393', 10 | type: 'svg' 11 | } 12 | -------------------------------------------------------------------------------- /src/project/parser.js: -------------------------------------------------------------------------------- 1 | import YAML from 'yaml' 2 | import AJV from 'ajv' 3 | import schema from './schema' 4 | 5 | /** 6 | * Transfer project info file to a type fine object. 7 | * @param {string} scriptInfo The project info writen in YAML. 8 | */ 9 | function parser (scriptInfo, useJSON = false) { 10 | const data = useJSON ? JSON.parse(scriptInfo) : YAML.parse(scriptInfo) 11 | const ajv = new AJV() 12 | const v = ajv.validate(schema, data) 13 | if (!v) { 14 | const errorText = `[Error] Project parser find error(s):\n${ajv.errors.map(v => `ProjectInfo${v.dataPath} ${v.message}`).join('\n')}` 15 | throw new Error(errorText) 16 | } 17 | return data 18 | } 19 | 20 | export default parser 21 | -------------------------------------------------------------------------------- /src/project/schema.js: -------------------------------------------------------------------------------- 1 | const fileItemSchema = { 2 | type: 'object', 3 | required: ['name', 'file'], 4 | properties: { 5 | name: { type: 'string' }, 6 | file: { type: 'string' } 7 | } 8 | } 9 | 10 | const fileArraySchema = { 11 | type: 'array', 12 | items: fileItemSchema 13 | } 14 | 15 | const codeSchema = { 16 | type: 'object', 17 | required: ['file'], 18 | properties: { 19 | file: { type: 'string' } 20 | } 21 | } 22 | 23 | const spriteSchema = { 24 | type: 'object', 25 | properties: { 26 | code: codeSchema, 27 | position: { 28 | type: 'object', 29 | required: ['x', 'y'], 30 | properties: { 31 | x: { type: 'number', minimum: -240, maximum: 240 }, 32 | y: { type: 'number', minimum: -180, maximum: 180 } 33 | } 34 | }, 35 | rotation: { type: 'number', minimum: -180, maximum: 180 }, 36 | rotationstyle: { 37 | type: 'string', 38 | enum: ['all around', 'left-right', "don't rotate"] 39 | }, 40 | size: { type: 'number', minimum: 0 }, 41 | visible: { type: 'boolean' }, 42 | draggable: { type: 'boolean' }, 43 | costume: { type: 'integer', minimum: 0 }, 44 | costumes: fileArraySchema, 45 | sounds: fileArraySchema 46 | } 47 | } 48 | 49 | const schema = { 50 | $schema: 'http://json-schema.org/draft-07/schema#', 51 | type: 'object', 52 | required: ['info'], 53 | properties: { 54 | info: { 55 | type: 'object', 56 | properties: { 57 | stage: { 58 | type: 'object', 59 | properties: { 60 | code: codeSchema, 61 | costume: { 62 | type: 'integer', 63 | minimum: 0 64 | }, 65 | costumes: fileArraySchema, 66 | sounds: fileArraySchema 67 | } 68 | }, 69 | sprites: { 70 | type: 'array', 71 | items: spriteSchema 72 | } 73 | } 74 | } 75 | } 76 | } 77 | 78 | export default schema 79 | -------------------------------------------------------------------------------- /test/test/test.js: -------------------------------------------------------------------------------- 1 | const test = require('ava') 2 | 3 | test('compile test', t => { 4 | t.pass() 5 | }) 6 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | 2 | const CopyWebpackPlugin = require('copy-webpack-plugin') 3 | const defaultsDeep = require('lodash.defaultsdeep') 4 | const TerserWebpackPlugin = require('terser-webpack-plugin') 5 | const path = require('path') 6 | 7 | console.log(process.env.NODE_ENV) 8 | 9 | const mode = process.env.NODE_ENV === 'production' ? 'production' : 'development' 10 | 11 | const base = { 12 | mode, 13 | devServer: { 14 | contentBase: false, 15 | host: '0.0.0.0', 16 | port: process.env.PORT || 8040 17 | }, 18 | devtool: 'cheap-module-source-map', 19 | output: { 20 | library: 'scratchscript', 21 | filename: '[name].js' 22 | }, 23 | module: { 24 | rules: [{ 25 | test: /\.js$/, 26 | loader: 'babel-loader', 27 | include: path.resolve(__dirname, 'src'), 28 | query: { 29 | plugins: [ 30 | '@babel/plugin-transform-runtime' 31 | ], 32 | presets: [[ 33 | '@babel/preset-env', { 34 | targets: { 35 | browsers: ['last 3 versions', 'Safari >= 8', 'iOS >= 8'] 36 | } 37 | } 38 | ]] 39 | } 40 | }, { 41 | test: /\.ne$/, 42 | loader: 'nearley-loader' 43 | }, { 44 | test: /\.sb3$/, 45 | loader: 'arraybuffer-loader' 46 | }] 47 | }, 48 | optimization: { 49 | minimizer: [ 50 | new TerserWebpackPlugin({ 51 | include: /\.min\.js$/ 52 | }) 53 | ] 54 | }, 55 | plugins: [] 56 | } 57 | 58 | const configs = [ 59 | // Web-compatible 60 | defaultsDeep({}, base, { 61 | target: 'web', 62 | entry: { 63 | ssc: './src/index.js', 64 | 'ssc.min': './src/index.js' 65 | }, 66 | output: { 67 | libraryTarget: 'umd', 68 | path: path.resolve('dist', 'web') 69 | } 70 | }), 71 | // Node-compatible 72 | defaultsDeep({}, base, { 73 | target: 'node', 74 | entry: { 75 | ssc: './src/index.node.js' 76 | }, 77 | output: { 78 | libraryTarget: 'commonjs2', 79 | path: path.resolve('dist', 'node') 80 | }, 81 | externals: { 82 | ajv: true, 83 | commander: true, 84 | jszip: true, 85 | moo: true, 86 | nearley: true, 87 | yaml: true 88 | } 89 | }) 90 | ] 91 | 92 | if (base.mode === 'development') { 93 | configs.push(// Playground: only development 94 | defaultsDeep({}, base, { 95 | target: 'web', 96 | entry: { 97 | playground: './src/playground/playground' 98 | }, 99 | output: { 100 | path: path.resolve(__dirname, 'playground'), 101 | filename: '[name].js' 102 | }, 103 | performance: { 104 | hints: false 105 | }, 106 | externals: { 107 | react: 'React', 108 | codemirror: 'CodeMirror', 109 | 'react-dom': 'ReactDOM', 110 | 'scratch-gui': 'GUI', 111 | jszip: 'JSZip' 112 | }, 113 | plugins: base.plugins.concat([ 114 | new CopyWebpackPlugin({ 115 | patterns: [ 116 | 'src/playground', 117 | { from: 'node_modules/scratch-gui/dist/static/blocks-media', to: 'static/blocks-media' }, 118 | { from: 'node_modules/scratch-gui/dist', to: '../' } 119 | ] 120 | }) 121 | ]) 122 | }) 123 | ) 124 | } 125 | 126 | module.exports = configs 127 | --------------------------------------------------------------------------------