-
Notifications
You must be signed in to change notification settings - Fork 479
/
craft.js
844 lines (753 loc) · 28.4 KB
/
craft.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
import $ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import Hammer from 'hammerjs';
import trackEvent from '../../util/trackEvent';
import { tryGetLocalStorage, trySetLocalStorage } from '../../utils';
import { singleton as studioApp } from '../../StudioApp';
import craftMsg from './locale';
import CustomMarshalingInterpreter from '../../lib/tools/jsinterpreter/CustomMarshalingInterpreter';
import {
GameController,
FacingDirection,
EventType,
utils as CraftUtils,
} from '@code-dot-org/craft';
import dom from '../../dom';
import MusicController from '../../MusicController';
import { Provider } from 'react-redux';
import AppView from '../../templates/AppView';
import CraftVisualizationColumn from './CraftVisualizationColumn';
import { getStore } from '../../redux';
import Sounds from '../../Sounds';
import { TestResults } from '../../constants';
import {captureThumbnailFromCanvas} from '../../util/thumbnail';
import {SignInState} from '../../code-studio/progressRedux';
const MEDIA_URL = '/blockly/media/craft/';
const ArrowIds = {
LEFT: 'leftButton',
UP: 'upButton',
RIGHT: 'rightButton',
DOWN: 'downButton',
};
const interfaceImages = {
DEFAULT: [
MEDIA_URL + 'Sliced_Parts/MC_Loading_Spinner.gif',
MEDIA_URL + 'Sliced_Parts/Frame_Large_Plus_Logo.png',
MEDIA_URL + 'Sliced_Parts/Pop_Up_Slice.png',
MEDIA_URL + 'Sliced_Parts/X_Button.png',
MEDIA_URL + 'Sliced_Parts/Button_Grey_Slice.png',
MEDIA_URL + 'Sliced_Parts/Run_Button_Up_Slice.png',
MEDIA_URL + 'Sliced_Parts/MC_Run_Arrow_Icon_Smaller.png',
MEDIA_URL + 'Sliced_Parts/Run_Button_Down_Slice.png',
MEDIA_URL + 'Sliced_Parts/Reset_Button_Up_Slice.png',
MEDIA_URL + 'Sliced_Parts/MC_Reset_Arrow_Icon.png',
MEDIA_URL + 'Sliced_Parts/Reset_Button_Down_Slice.png',
MEDIA_URL + 'Sliced_Parts/Callout_Tail.png',
],
1: [
MEDIA_URL + 'Sliced_Parts/Steve_Character_Select.png',
MEDIA_URL + 'Sliced_Parts/Alex_Character_Select.png',
MEDIA_URL + 'Sliced_Parts/Agent_Fail.png',
MEDIA_URL + 'Sliced_Parts/Agent_Neutral.png',
MEDIA_URL + 'Sliced_Parts/Agent_Success.png',
],
};
const MUSIC_METADATA = [
{ volume: 1, hasOgg: true, name: 'vignette1' },
{ volume: 1, hasOgg: true, name: 'vignette2-quiet' },
{ volume: 1, hasOgg: true, name: 'vignette3' },
{ volume: 1, hasOgg: true, name: 'vignette4-intro' },
{ volume: 1, hasOgg: true, name: 'vignette5-shortpiano' },
{ volume: 1, hasOgg: true, name: 'vignette7-funky-chirps-short' },
{ volume: 1, hasOgg: true, name: 'vignette8-free-play' },
{ volume: 1, hasOgg: true, name: 'nether2' },
];
const CHARACTER_STEVE = 'Steve';
const CHARACTER_ALEX = 'Alex';
const DEFAULT_CHARACTER = CHARACTER_STEVE;
const directionToFacing = {
upButton: FacingDirection.North,
downButton: FacingDirection.South,
leftButton: FacingDirection.West,
rightButton: FacingDirection.East,
};
export default class Craft {
/**
* Initialize Blockly and the Craft app. Called on page load.
*/
static init(config) {
if (config.level.puzzle_number === 1 && config.level.stage_total === 1) {
// Not viewing level within a script, bump puzzle # to unused one so
// asset loading system and levelbuilder overrides don't think this is
// level 1 or any other special level.
config.level.puzzle_number = 999;
}
if (config.level.isTestLevel) {
config.level.customSlowMotion = 0.1;
}
config.level.disableFinalStageMessage = true;
config.showInstructionsInTopPane = true;
// Return the version of Internet Explorer (8+) or undefined if not IE.
const getIEVersion = function () {
return document.documentMode;
};
const ieVersionNumber = getIEVersion();
if (ieVersionNumber) {
$('body').addClass('ieVersion' + ieVersionNumber);
}
if (config.level.isAgentLevel) {
$('body').addClass('minecraft-agent');
}
const bodyElement = document.body;
bodyElement.className = bodyElement.className + ' minecraft';
// Always add a hook for after the video but before the level proper begins.
// Use this to start music, and sometimes to show an extra dialog.
config.level.afterVideoBeforeInstructionsFn = (showInstructions) => {
Craft.beginBackgroundMusic();
if (config.level.showPopupOnLoad) {
if (config.level.showPopupOnLoad === 'playerSelection') {
Craft.showPlayerSelectionPopup(function (selectedPlayer) {
trackEvent('Minecraft', 'ChoseCharacter', selectedPlayer);
Craft.clearPlayerState();
trySetLocalStorage('craftSelectedPlayer', selectedPlayer);
Craft.initializeAppLevel(config.level);
showInstructions();
});
}
} else {
showInstructions();
}
};
Craft.initialConfig = config;
// replace studioApp() methods with our own
studioApp().reset = Craft.reset.bind(Craft);
studioApp().runButtonClick = Craft.runButtonClick.bind(Craft);
// set initial configurations
studioApp().setCheckForEmptyBlocks(true);
Craft.level = config.level;
Craft.skin = config.skin;
let levelTracks = [];
if (Craft.level.songs && MUSIC_METADATA) {
levelTracks = MUSIC_METADATA.filter(function (trackMetadata) {
return Craft.level.songs.indexOf(trackMetadata.name) !== -1;
});
}
Craft.musicController = new MusicController(
Sounds.getSingleton(),
function (filename) {
return config.skin.assetUrl(`music/${filename}`);
},
levelTracks,
levelTracks.length > 1 ? 7500 : null,
);
config.skin.staticAvatar = MEDIA_URL + 'Sliced_Parts/Agent_Neutral.png';
config.skin.smallStaticAvatar = MEDIA_URL + 'Sliced_Parts/Agent_Neutral.png';
config.skin.failureAvatar = MEDIA_URL + 'Sliced_Parts/Agent_Fail.png';
config.skin.winAvatar = MEDIA_URL + 'Sliced_Parts/Agent_Success.png';
const onMount = function () {
studioApp().init(
Object.assign({}, config, {
forceInsertTopBlock: 'when_run',
appStrings: {
generatedCodeDescription: craftMsg.generatedCodeDescription(),
},
loadAudio: function () {},
afterInject: function () {
if (config.level.showMovementBanner) {
studioApp().displayWorkspaceAlert(
'warning',
<div>
{craftMsg.useArrowKeys()}
</div>,
);
}
// NaN if not set
const slowMotionURLParam = parseFloat(
(location.search.split('customSlowMotion=')[1] || '')
.split('&')[0],
);
Craft.gameController = new GameController({
Phaser: window.Phaser,
containerId: 'phaser-game',
assetRoot: Craft.skin.assetUrl(''),
audioPlayer: {
register: studioApp().registerAudio.bind(studioApp()),
play: studioApp().playAudio.bind(studioApp()),
},
debug: false,
customSlowMotion: config.level.isTestLevel
? 0.5
: slowMotionURLParam,
/**
* First asset packs to load while video playing, etc.
* Won't matter for levels without delayed level initialization
* (due to e.g. character / house select popups).
*/
earlyLoadAssetPacks: Craft.earlyLoadAssetsForLevel(
config.level.puzzle_number,
),
afterAssetsLoaded: function () {
// Listen for hint events that draw a path in the game.
window.addEventListener('displayHintPath', e => {
Craft.gameController.levelView.drawHintPath(e.detail);
});
window.addEventListener('craftCollectibleCollected', e => {
if (e.blockType === "diamondMiniblock") {
Craft.setSessionDiamondCollected();
}
});
// preload music after essential game asset downloads completely finished
Craft.musicController.preload();
},
earlyLoadNiceToHaveAssetPacks: Craft.niceToHaveAssetsForLevel(
config.level.puzzle_number,
),
});
if (!config.level.showPopupOnLoad) {
Craft.initializeAppLevel(config.level);
}
if (studioApp().hideSource) {
// Set visualizationColumn width in share mode so it can be centered
const visualizationColumn = document.getElementById(
'visualizationColumn',
);
visualizationColumn.style.width = this.nativeVizWidth + 'px';
}
for (const btn in ArrowIds) {
dom.addMouseUpTouchEvent(
document.getElementById(ArrowIds[btn]),
(function (btn) {
return () => {
Craft.onArrowButtonUp(ArrowIds[btn]);
};
})(btn),
);
dom.addMouseDownTouchEvent(
document.getElementById(ArrowIds[btn]),
(function (btn) {
return e => {
Craft.onArrowButtonDown(e, ArrowIds[btn]);
};
})(btn),
);
}
dom.addMouseUpTouchEvent(document, Craft.onDocumentMouseUp, false);
$('#soft-buttons')
.removeClass('soft-buttons-none')
.addClass('soft-buttons-' + 4);
$('.arrow').prop("disabled", false);
const resetButton = document.getElementById('resetButton');
dom.addClickTouchEvent(resetButton, Craft.resetButtonClick);
const phaserGame = document.getElementById('phaser-game');
const hammerToButton = {
[Hammer.DIRECTION_LEFT]: 'leftButton',
[Hammer.DIRECTION_RIGHT]: 'rightButton',
[Hammer.DIRECTION_UP]: 'upButton',
[Hammer.DIRECTION_DOWN]: 'downButton',
};
const onDrag = function (e) {
if (hammerToButton[e.direction]) {
Craft.gameController.codeOrgAPI.arrowDown(
directionToFacing[hammerToButton[e.direction]],
);
}
e.preventDefault();
};
const onDragEnd = function (e) {
if (hammerToButton[e.direction]) {
Craft.gameController.codeOrgAPI.arrowUp(
directionToFacing[hammerToButton[e.direction]],
);
}
e.preventDefault();
};
const mc = new Hammer.Manager(phaserGame);
mc.add(new Hammer.Pan({ direction: Hammer.DIRECTION_ALL }));
mc.add(new Hammer.Press({ time: 150 }));
mc.add(new Hammer.Tap());
mc.on('pan', onDrag);
mc.on('panend pancancel', onDragEnd);
mc.on('press', () =>
Craft.gameController.codeOrgAPI.clickDown(() => {}),
);
mc.on('tap', () => {
Craft.gameController.codeOrgAPI.clickDown(() => {});
Craft.gameController.codeOrgAPI.clickUp(() => {});
});
mc.on('pressup', () =>
Craft.gameController.codeOrgAPI.clickUp(() => {}),
);
},
twitter: {
text: 'Share on Twitter',
hashtag: 'Craft',
},
}),
);
let interfaceImagesToLoad = [];
interfaceImagesToLoad = interfaceImagesToLoad.concat(
interfaceImages.DEFAULT,
);
if (
config.level.puzzle_number &&
interfaceImages[config.level.puzzle_number]
) {
interfaceImagesToLoad = interfaceImagesToLoad.concat(
interfaceImages[config.level.puzzle_number],
);
}
interfaceImagesToLoad.forEach(function (url) {
const img = new Image();
img.src = url;
});
const shareButton = $('.mc-share-button');
if (shareButton.length) {
dom.addClickTouchEvent(shareButton[0], function () {
Craft.reportResult(true);
});
}
};
// Push initial level properties into the Redux store
studioApp().setPageConstants(config, {
isMinecraft: true,
hideRunButton: config.level.specialLevelType === 'agentSpawn',
});
ReactDOM.render(
<Provider store={getStore()}>
<AppView
visualizationColumn={
<CraftVisualizationColumn
showFinishButton={!config.level.isProjectLevel}
/>
}
onMount={onMount}
/>
</Provider>,
document.getElementById(config.containerId),
);
}
/**
* Play music when the instructions are shown
*/
static beginBackgroundMusic() {
Sounds.getSingleton().whenAudioUnlocked(function () {
const hasSongInLevel = Craft.level.songs && Craft.level.songs.length > 1;
const songToPlayFirst = hasSongInLevel ? Craft.level.songs[0] : null;
Craft.musicController.play(songToPlayFirst);
});
}
static onArrowButtonDown(e, btn) {
Craft.gameController.codeOrgAPI.arrowDown(directionToFacing[btn]);
e.preventDefault(); // Stop normal events so we see mouseup later.
}
static onArrowButtonUp(btn) {
Craft.gameController.codeOrgAPI.arrowUp(directionToFacing[btn]);
}
static onDocumentMouseUp() {
if (!Craft.phaserLoaded() || !Craft.levelInitialized()) {
return;
}
for (const direction in directionToFacing) {
Craft.gameController.codeOrgAPI.arrowUp(directionToFacing[direction]);
}
}
static characterAssetPackName(playerName) {
return 'player' + playerName;
}
static getCurrentCharacter() {
return (
window.localStorage.getItem('craftSelectedPlayer') || DEFAULT_CHARACTER
);
}
/**
* Get the level IDs for which the player has collected a diamond this
* session.
*
* @return {Number[]} collectedLevels
*/
static getSessionDiamondCollectedLevels() {
return JSON.parse(tryGetLocalStorage('craftSessionDiamondCollectedLevels', '[]')) || [];
}
/**
* Mark this level as being one for which the player has collected a diamond
* this session, if not already marked as such.
*
* @return {boolean} whether or not the level was newly marked
*/
static setSessionDiamondCollected() {
const collectedLevels = Craft.getSessionDiamondCollectedLevels();
if (!collectedLevels.includes(Craft.initialConfig.serverLevelId)) {
collectedLevels.push(Craft.initialConfig.serverLevelId);
trySetLocalStorage('craftSessionDiamondCollectedLevels', JSON.stringify(collectedLevels));
return true;
}
return false;
}
static showPlayerSelectionPopup(onSelectedCallback) {
let selectedPlayer = DEFAULT_CHARACTER;
const popupDiv = document.createElement('div');
popupDiv.innerHTML = require('./dialogs/playerSelection.html.ejs')({
image: studioApp().assetUrl(),
});
const popupDialog = studioApp().createModalDialog({
contentDiv: popupDiv,
defaultBtnSelector: '#choose-steve',
onHidden: function () {
onSelectedCallback(selectedPlayer);
},
id: 'craft-popup-player-selection',
});
dom.addClickTouchEvent($('#close-character-select')[0], () => {
popupDialog.hide();
});
dom.addClickTouchEvent($('#choose-steve')[0], () => {
selectedPlayer = CHARACTER_STEVE;
trackEvent('MinecraftAgent', 'ClickedCharacter', selectedPlayer);
popupDialog.hide();
});
dom.addClickTouchEvent($('#choose-alex')[0], () => {
selectedPlayer = CHARACTER_ALEX;
trackEvent('MinecraftAgent', 'ClickedCharacter', selectedPlayer);
popupDialog.hide();
});
popupDialog.show();
}
static clearPlayerState() {
window.localStorage.removeItem('craftSelectedPlayer');
}
static initializeAppLevel(levelConfig) {
CraftUtils.convertActionPlaneEntitiesToConfig(levelConfig);
const fluffPlane = [];
// TODO(bjordan): remove configuration requirement in visualization
for (let i = 0; i < (levelConfig.gridWidth || 10) * (levelConfig.gridHeight || 10); i++) {
fluffPlane.push('');
}
const levelAssetPacks = {
beforeLoad: Craft.minAssetsForLevelWithCharacter(
levelConfig.puzzle_number,
),
afterLoad: Craft.afterLoadAssetsForLevel(levelConfig.puzzle_number),
};
Craft.gameController.loadLevel({
isDaytime: levelConfig.isDaytime,
groundPlane: levelConfig.groundPlane,
groundDecorationPlane: levelConfig.groundDecorationPlane,
actionPlane: levelConfig.actionPlane,
fluffPlane: fluffPlane,
entities: levelConfig.entities,
useAgent: !!levelConfig.agentStartPosition,
usePlayer: !!levelConfig.playerStartPosition,
playerStartPosition: levelConfig.playerStartPosition,
playerStartDirection: levelConfig.playerStartDirection,
agentStartPosition: levelConfig.agentStartPosition,
agentStartDirection: levelConfig.agentStartDirection,
playerName: Craft.getCurrentCharacter(),
assetPacks: levelAssetPacks,
specialLevelType: levelConfig.specialLevelType,
isAgentLevel: levelConfig.isAgentLevel,
gridDimensions:
levelConfig.gridWidth && levelConfig.gridHeight
? [levelConfig.gridWidth, levelConfig.gridHeight]
: null,
levelVerificationTimeout: levelConfig.levelVerificationTimeout,
// eslint-disable-next-line no-eval
verificationFunction: eval('[' + levelConfig.verificationFunction + ']')[0], // TODO(bjordan): add to utils
// eslint-disable-next-line no-eval
failureCheckFunction: eval('[' + levelConfig.failureCheckFunction + ']')[0], // TODO(bjordan): add to utils
// eslint-disable-next-line no-eval
timeoutResult: eval('[' + (levelConfig.timeoutVerificationFunction || `function() { return false; }`) + ']')[0],
});
}
static minAssetsForLevelWithCharacter(levelNumber) {
return Craft.minAssetsForLevelNumber(levelNumber).concat([
Craft.characterAssetPackName(Craft.getCurrentCharacter()),
]);
}
static minAssetsForLevelNumber(levelNumber) {
switch (levelNumber) {
default:
return ['heroAllAssetsMinusPlayer', 'playerAgent'];
}
}
static afterLoadAssetsForLevel(levelNumber) {
// After level loads & player starts playing, kick off further asset downloads
switch (levelNumber) {
default:
// May want to push this to occur on level with video
return ['heroAllAssetsMinusPlayer', 'playerAgent'];
}
}
static earlyLoadAssetsForLevel(levelNumber) {
switch (levelNumber) {
default:
return Craft.minAssetsForLevelWithCharacter(levelNumber);
}
}
static niceToHaveAssetsForLevel(levelNumber) {
switch (levelNumber) {
case 1:
return ['playerSteve', 'playerAlex'];
default:
return ['heroAllAssetsMinusPlayer'];
}
}
/**
* Reset the app to the start position and kill any pending animation tasks.
* @param {boolean} first true if first reset
*/
static reset(first) {
if (first) {
return;
}
captureThumbnailFromCanvas($('#minecraft-frame canvas')[0]);
Craft.gameController.codeOrgAPI.resetAttempt();
}
static phaserLoaded() {
return (
Craft.gameController &&
Craft.gameController.game &&
Craft.gameController.game.load &&
!Craft.gameController.game.load.isLoading
);
}
static levelInitialized() {
return Craft.gameController && Craft.gameController.levelModel;
}
/**
* Base's `studioApp().resetButtonClick` will be called first.
*/
static resetButtonClick() {
$('.arrow').prop("disabled", false);
}
static isPreAnimationFailure(testResult) {
switch (testResult) {
case TestResults.QUESTION_MARKS_IN_NUMBER_FIELD:
case TestResults.EMPTY_FUNCTIONAL_BLOCK:
case TestResults.EXTRA_TOP_BLOCKS_FAIL:
case TestResults.EXAMPLE_FAILED:
case TestResults.EMPTY_BLOCK_FAIL:
case TestResults.EMPTY_FUNCTION_NAME:
return true;
default:
return false;
}
}
/**
* Click the run button. Start the program.
*/
static runButtonClick() {
if (!Craft.phaserLoaded()) {
return;
}
studioApp().toggleRunReset('reset');
Blockly.mainBlockSpace.traceOn(true);
studioApp().attempts++;
Craft.executeUserCode();
if (Craft.level.freePlay && !studioApp().hideSource) {
const finishBtnContainer = $('#right-button-cell');
if (
finishBtnContainer.length &&
!finishBtnContainer.hasClass('right-button-cell-enabled')
) {
finishBtnContainer.addClass('right-button-cell-enabled');
studioApp().onResize();
const event = document.createEvent('Event');
event.initEvent('finishButtonShown', true, true);
document.dispatchEvent(event);
}
}
}
static executeUserCode() {
if (Craft.initialConfig.level.edit_blocks) {
Craft.reportResult(true);
return;
}
// Fail immediately for empty repeat blocks, etc.
const initialTestResults = studioApp().getTestResults(false);
if (Craft.isPreAnimationFailure(initialTestResults)) {
Craft.reportResult(false);
return;
}
studioApp().playAudio('start');
// Start tracing calls.
Blockly.mainBlockSpace.traceOn(true);
const appCodeOrgAPI = Craft.gameController.codeOrgAPI;
appCodeOrgAPI.startCommandCollection();
appCodeOrgAPI.registerEventCallback(null, event => {
if (
event.eventType === EventType.WhenUsed &&
event.targetType === 'sheep'
) {
appCodeOrgAPI.drop(null, 'wool', event.targetIdentifier);
}
if (
event.eventType === EventType.WhenTouched &&
event.targetType === 'creeper'
) {
appCodeOrgAPI.flashEntity(null, event.targetIdentifier);
appCodeOrgAPI.explodeEntity(null, event.targetIdentifier);
}
});
// Run user generated code, calling appCodeOrgAPI
let code = '';
let codeBlocks = Blockly.mainBlockSpace.getTopBlocks(true);
if (studioApp().initializationBlocks) {
codeBlocks = studioApp().initializationBlocks.concat(codeBlocks);
}
code = Blockly.Generator.blocksToCode('JavaScript', codeBlocks);
CustomMarshalingInterpreter.evalWith(code, {
moveForward: function (blockID) {
appCodeOrgAPI.moveForward(studioApp().highlight.bind(studioApp(), blockID), 'PlayerAgent');
},
moveBackward: function (blockID) {
appCodeOrgAPI.moveBackward(studioApp().highlight.bind(studioApp(), blockID), 'PlayerAgent');
},
turnLeft: function (blockID) {
appCodeOrgAPI.turnLeft(studioApp().highlight.bind(studioApp(), blockID), 'PlayerAgent');
},
turnRight: function (blockID) {
appCodeOrgAPI.turnRight(studioApp().highlight.bind(studioApp(), blockID), 'PlayerAgent');
},
destroyBlock: function (blockID) {
appCodeOrgAPI.destroyBlock(studioApp().highlight.bind(studioApp(), blockID), 'PlayerAgent');
},
whilePathAhead: function (blockID, callback) {
// if resurrected, move blockID be last parameter to fix "Show Code"
appCodeOrgAPI.whilePathAhead(studioApp().highlight.bind(studioApp(), blockID),
'',
'PlayerAgent',
callback);
},
whileBlockAhead: function (blockID, blockType, callback) {
// if resurrected, move blockID be last parameter to fix "Show Code"
appCodeOrgAPI.whilePathAhead(studioApp().highlight.bind(studioApp(), blockID),
blockType,
'PlayerAgent',
callback);
},
ifLavaAhead: function (callback, blockID) {
// if resurrected, move blockID be last parameter to fix "Show Code"
appCodeOrgAPI.ifBlockAhead(studioApp().highlight.bind(studioApp(), blockID),
"lava",
'PlayerAgent',
callback);
},
ifBlockAhead: function (blockType, callback, blockID) {
appCodeOrgAPI.ifBlockAhead(studioApp().highlight.bind(studioApp(), blockID),
blockType,
'PlayerAgent',
callback);
},
placeBlock: function (blockType, blockID) {
appCodeOrgAPI.placeBlock(studioApp().highlight.bind(studioApp(), blockID),
blockType,
'PlayerAgent');
},
placeDirection: function (blockType, direction, blockID) {
appCodeOrgAPI.placeDirection(studioApp().highlight.bind(studioApp(), blockID),
blockType,
'PlayerAgent',
direction);
},
moveDirection: function (direction, targetEntity, blockID) {
const dirStringToDirection = {
up: FacingDirection.North,
down: FacingDirection.South,
left: FacingDirection.West,
right: FacingDirection.East,
};
appCodeOrgAPI.moveDirection(studioApp().highlight.bind(studioApp(), blockID),
dirStringToDirection[direction], targetEntity);
},
});
Craft.gameController.codeOrgAPI.startAttempt(success => {
if (Craft.level.freePlay) {
return;
}
Craft.reportResult(success);
});
}
static getTestResultFrom(success, studioTestResults) {
if (studioTestResults === TestResults.LEVEL_INCOMPLETE_FAIL) {
return TestResults.APP_SPECIFIC_FAIL;
}
if (Craft.initialConfig.level.freePlay) {
return TestResults.FREE_PLAY;
}
return studioTestResults;
}
static reportResult(success) {
const studioTestResults = studioApp().getTestResults(success);
const testResultType = Craft.getTestResultFrom(success, studioTestResults);
const image = Craft.initialConfig.level.freePlay
? Craft.gameController.getScreenshot()
: null;
// Grab the encoded image, stripping out the metadata, e.g. `data:image/png;base64,`
const encodedImage = image ? encodeURIComponent(image.split(',')[1]) : null;
let message;
if (testResultType === TestResults.APP_SPECIFIC_FAIL) {
message = craftMsg.agentGenericFailureMessage();
} else if (testResultType === TestResults.TOO_FEW_BLOCKS_FAIL) {
message = craftMsg.agentTooFewBlocksFailureMessage();
} else if (testResultType === TestResults.ALL_PASS) {
const collectedLevels = Craft.getSessionDiamondCollectedLevels();
if (collectedLevels.includes(Craft.initialConfig.serverLevelId)) {
message = craftMsg.agentDiamondPathCongrats({
count: collectedLevels.length
});
}
}
studioApp().report({
app: 'craft',
level: Craft.initialConfig.level.id,
result: Craft.initialConfig.level.freePlay ? true : success,
testResult: testResultType,
image: encodedImage,
program: encodeURIComponent(
Blockly.Xml.domToText(
Blockly.Xml.blockSpaceToDom(Blockly.mainBlockSpace),
),
),
// typically delay feedback until response back
// for things like e.g. crowdsourced hints & hint blocks
onComplete: function (response) {
const sharing = Craft.initialConfig.level.freePlay;
if (sharing && response.level_source) {
trySetLocalStorage('craftHeroShareLink', response.level_source);
}
const isSignedIn = getStore().getState().progress.signInState === SignInState.SignedIn;
studioApp().displayFeedback({
feedbackType: testResultType,
response,
level: Craft.initialConfig.level,
defaultToContinue: Craft.shouldDefaultToContinue(testResultType),
message,
appStrings: {
reinfFeedbackMsg: craftMsg.reinfFeedbackMsg(),
nextLevelMsg: craftMsg.nextLevelMsg({
puzzleNumber: Craft.initialConfig.level.puzzle_number,
}),
tooManyBlocksFailMsgFunction: craftMsg.tooManyBlocksFail,
generatedCodeDescription: craftMsg.generatedCodeDescription(),
},
feedbackImage: image,
showingSharing: sharing,
saveToProjectGallery: true,
disableSaveToGallery: !isSignedIn,
});
},
});
}
/**
* Whether pressing "x" or pressing the backdrop of the "level completed" dialog
* should default to auto-advancing to the next level.
* @param {string} testResultType TestResults type of this level completion
* @returns {boolean} whether to continue
*/
static shouldDefaultToContinue(testResultType) {
const isFreePlay = testResultType === TestResults.FREE_PLAY;
const isSuccess = testResultType > TestResults.APP_SPECIFIC_ACCEPTABLE_FAIL;
return isSuccess && !isFreePlay;
}
}