forked from amyjko/Gidget
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathui.js
2120 lines (1520 loc) · 61.6 KB
/
ui.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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
GIDGET.ui = {
// The level to initialize on each run.
level: undefined,
// Contains all the data for the world being run
world: undefined,
messages: "",
competence: undefined, //adaptive setting
stepSpeedInMilliseconds: 100,
images: {},
stepState: undefined,
hasImage: function(name, state) {
if (name == "gidget") {
return this.images.hasOwnProperty("control." + state) && this.images["control." + state] !== false;
}
return this.images.hasOwnProperty(name + "." + state) && this.images[name + "." + state] !== false;
},
getImage: function(name, state) {
// Set Gidget's image for Control Condition
var label;
if ((name === "gidget") && (GIDGET.experiment.isControl()))
label = "control." + state;
else
label = name + "." + state;
// If this has already been checked, return what's there.
if(this.images.hasOwnProperty(label))
return this.images[label];
// For now, mark it as false.
this.images[label] = false;
$.ajax({ url: "media/" + label + ".png", context: this,
success: function(){
// An image has loaded! Create the image, cache it, and update the UI.
var image = new Image();
// Only once the image has loaded do we store it and update the image in the database; this is because sometimes local AJAX requests lie.
// Moreover, we set the callback first, then the source, because sometimes the callback gets called asynchronously before the callback is set
// when we define the source first.
image.onload = function () {
GIDGET.ui.images[label] = image;
GIDGET.ui.updateRuntimeUserInterface();
};
image.src = "media/" + label + ".png";
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// Mark this name as not existing
this.images[label] = false;
}
});
return false;
},
log: function(message) {
this.messages = this.messages + "<br>" + message;
if (GIDGET.experiment.verbose) {
console.log("[gidget] " + message);
}
},
setCodeToWorldDefault: function() {
$('#code').html(this.gidgetCodeToHTML(this.world.code));
},
getNumberOfLevelsPassed: function() {
if(localStorage.getItem('levelMetadata') === null)
return 0;
var levelMetadata = getLocalStorageObject('levelMetadata');
var count = 0;
for(var level in levelMetadata) {
if(levelMetadata.hasOwnProperty(level)) {
var data = levelMetadata[level];
if(data.passed === true)
count++;
}
}
return count;
},
showLevelInfo: function() {
if (!isDef(this.world.levelNumber))
this.world.addLevelNumber();
$('#levelTitle').html("Level " + this.world.levelNumber + ". " + this.world.levelTitle);
},
removeSpecialCharacters: function(myString) {
return myString.replace(/[^a-zA-Z 0-9.();?!]+/g,' ');
},
radioEmpty: function(name) {
if (!isDef($('input[name='+name+']:radio:checked').val())) {return "";}
else {return $('input[name='+name+']:radio:checked').val();}
},
quit: function(message) {
$('#postSurvey').hide();
var level = localStorage.getItem('currentLevel');
$('#quitResults').html("<p>" + message + " Saving your achievements...").show();
function randomPassword(length) {
chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
pass = "";
for(x = 0; x < length; x++) {
i = Math.floor(Math.random() * 62);
pass += chars.charAt(i);
}
return pass;
}
var password = randomPassword(10);
var systemDetect = {
init: function () {
this.browser = this.searchString(this.dataBrowser) || "unknown";
this.version = this.searchVersion(navigator.userAgent)
|| this.searchVersion(navigator.appVersion)
|| "an unknown version";
this.OS = this.searchString(this.dataOS) || "unknown";
},
searchString: function (data) {
for (var i=0;i<data.length;i++) {
var dataString = data[i].string;
var dataProp = data[i].prop;
this.versionSearchString = data[i].versionSearch || data[i].identity;
if (dataString) {
if (dataString.indexOf(data[i].subString) != -1)
return data[i].identity;
}
else if (dataProp)
return data[i].identity;
}
},
searchVersion: function (dataString) {
var index = dataString.indexOf(this.versionSearchString);
if (index == -1) return;
return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
},
dataBrowser: [
{
string: navigator.userAgent,
subString: "Chrome",
identity: "Chrome"
},
{
string: navigator.vendor,
subString: "Apple",
identity: "Safari",
versionSearch: "Version"
},
{
prop: window.opera,
identity: "Opera"
},
{
string: navigator.userAgent,
subString: "Firefox",
identity: "Firefox"
},
{
string: navigator.userAgent,
subString: "MSIE",
identity: "Explorer",
versionSearch: "MSIE"
}
],
dataOS : [
{
string: navigator.platform,
subString: "Win",
identity: "Windows"
},
{
string: navigator.platform,
subString: "Mac",
identity: "Mac"
},
{
string: navigator.platform,
subString: "Linux",
identity: "Linux"
}
]
};
systemDetect.init();
var payload = {
condition: GIDGET.experiment.condition,
studentid: $('input[name=stnumber]').val(),
currentLevel: localStorage.getItem('currentLevel'),
levelsPassed: this.getNumberOfLevelsPassed(),
code: password,
levelMetadata: getLocalStorageObject('levelMetadata'),
browser: systemDetect.browser,
os: systemDetect.OS,
finalTime: (new Date()).getTime(),
// Extract all of the questionnaire data from the form.
survey: {
gender: this.radioEmpty("gender") == "unlisted" ? $('input[name=other_gender]').val() : this.radioEmpty("gender"),
age: this.removeSpecialCharacters($('input[name=age]').val()),
//country: $('select[name=country] option:selected').val(),
education: $('select[name=education] option:selected').val(),
experience1: $('input[name=experience1]').attr('checked'),
experience2: $('input[name=experience2]').attr('checked'),
experience3: $('input[name=experience3]').attr('checked'),
experience4: $('input[name=experience4]').attr('checked'),
experience5: $('input[name=experience5]').attr('checked'),
experience6: $('input[name=experience6]').attr('checked'),
enjoyment: this.radioEmpty("enjoyment"),
recommend: this.radioEmpty("recommend"),
helpGidget:this.radioEmpty("helpGidget"),
dialogue: this.removeSpecialCharacters($('textarea[name=freeDialogue]').val()),
avatar: this.removeSpecialCharacters($('textarea[name=freeAvatar]').val()),
experience: this.removeSpecialCharacters($('textarea[name=freeExperience]').val()),
whyQuit: this.removeSpecialCharacters($('textarea[name=freeQuit]').val()),
whyMore: this.removeSpecialCharacters($('textarea[name=freeMore]').val()),
CORE01: this.radioEmpty("CORE01"),
CORE02: this.radioEmpty("CORE02"),
CORE03: this.radioEmpty("CORE03"),
CORE04: this.radioEmpty("CORE04"),
CORE05: this.radioEmpty("CORE05"),
CORE06: this.radioEmpty("CORE06"),
CORE07: this.radioEmpty("CORE07"),
CORE08: this.radioEmpty("CORE08"),
CORE09: this.radioEmpty("CORE09"),
CORE10: this.radioEmpty("CORE10"),
CORE11: this.radioEmpty("CORE11"),
CORE12: this.radioEmpty("CORE12"),
CORE13: this.radioEmpty("CORE13"),
CORE14: this.radioEmpty("CORE14"),
CORE15: this.radioEmpty("CORE15"),
CORE16: this.radioEmpty("CORE16"),
CORE17: this.radioEmpty("CORE17"),
CORE18: this.radioEmpty("CORE18"),
CORE19: this.radioEmpty("CORE19"),
CORE20: this.radioEmpty("CORE20"),
CORE21: this.radioEmpty("CORE21"),
CORE22: this.radioEmpty("CORE22"),
PGAME01: this.radioEmpty("PGAME01"),
PGAME02: this.radioEmpty("PGAME02"),
PGAME03: this.radioEmpty("PGAME03"),
PGAME04: this.radioEmpty("PGAME04"),
PGAME05: this.radioEmpty("PGAME05"),
PGAME06: this.radioEmpty("PGAME06"),
PGAME07: this.radioEmpty("PGAME07"),
PGAME08: this.radioEmpty("PGAME08"),
PGAME09: this.radioEmpty("PGAME09"),
PGAME10: this.radioEmpty("PGAME10"),
PGAME11: this.radioEmpty("PGAME11"),
PGAME12: this.radioEmpty("PGAME12"),
PGAME13: this.radioEmpty("PGAME13"),
PGAME14: this.radioEmpty("PGAME14"),
//doop: this.radioEmpty("doop"),//test survey
}
}
payload = "data=" + JSON.stringify(payload);
//alert(payload);
localStorage.setItem("quit", password);
$.ajax({
type: "POST",
url: "submit.php",
data: payload,
success: function(msg) {
GIDGET.ui.disable("Successfully saved your results!");
},
error: function(jqXHR, textStatus, errorThrown) {
GIDGET.ui.disable("Your results could not be saved :(");
}
});
},
// Hides the whole UI
disable: function(message) {
$('#container').hide();
$('#quitResults').html(
"<p>" + message + "</p>" +
//"<p>Your MTurk completion code is: <b>" + localStorage.getItem('quit') + "</b>.</p><p>Please enter it back on the MTurk HIT page.</p>" +
//"<p>From this point on, the game will be disabled."
""
).show();
},
// Hides all but the mission and thoughts
showAllButMission: function(show) {
var duration = 200;
var opacity = show ? 0.0 : 1.0;
$('#instructionsContainer').animate({ 'opacity': opacity }, duration);
$('#code').animate({ 'opacity': opacity }, duration);
$('#goals').animate({ 'opacity': opacity}, duration);
$('#learnerThought').animate({ 'opacity': opacity}, duration);
$('#rightPanel').animate({ 'opacity': opacity}, duration);
},
getCurrentLevel: function() {
return localStorage.getItem('currentLevel');
},
saveCurrentLevelCode: function() {
var currentCode = this.htmlToGidgetCode($('#code').html());
var levelData = getLocalStorageObject('levelMetadata');
// Create an empty object literal to store level versions.
if(levelData === null)
levelData = { };
// Get the list of versions for this level. If there isn't one, make an empty list.
if(!levelData.hasOwnProperty(this.getCurrentLevel())) {
levelData[this.getCurrentLevel()] = {
passed: false,
startTime: (new Date()).getTime(),
endTime: undefined,
versions: [],
stepLog: [],
//Adaptive data
failCount: 0,
minEnergy: 1000,
energyUsed: 0,
solutionLength: undefined,
totalTime: undefined
};
}
// Add the current version to the list of versions.
levelData[this.getCurrentLevel()].versions.push({ time: (new Date).getTime(), version: currentCode });
// Add all steps logged to the store and empty the store in memory.
levelData[this.getCurrentLevel()].stepLog = levelData[this.getCurrentLevel()].stepLog.concat(this.stepLog);
this.stepLog = [];
//ADAPTIVE: Add failCount
levelData[this.getCurrentLevel()].failCount += this.failCount;
this.failCount = 0;
//ADAPTIVE: Add minEnergy
levelData[this.getCurrentLevel()].minEnergy = this.minEnergy;
this.minEnergy = 1000;
//ADAPTIVE: Add energyUsed
levelData[this.getCurrentLevel()].energyUsed = this.energyUsed;
this.energyUsed = 0;
// Stringify the current versions object
setLocalStorageObject('levelMetadata', levelData);
},
gidgetCodeToHTML: function(code) {
var count = 0;
var first = false;
function tokenToHTML(string) {
var classes = 'sourceToken';
if(string.match(/scan|say|analyze|goto|ask|to|grab|drop|it|if|is|are|on|avoid/i))
classes = classes + ' keyword';
if(first) {
classes = classes + ' first';
first = false;
}
var html = "<span class='" + classes + "' id='sourceToken" + count + "'>" + string + "</span>";
count++;
return html;
}
// Convert the given gidget code into marked up HTML amenable for highlighting.
var lines = code.split(/\r\n|\r|\n/);
var lineNumber;
var html = "";
for(lineNumber = 0; lineNumber < lines.length; lineNumber++) {
first = true;
var line = lines[lineNumber];
var classes = "sourceLine";
// If this is not Firefox, add indent
if(!$.browser.mozilla)
classes = classes + " indent";
var lineText = "<div class='" + classes + "' id='sourceLine" + lineNumber + "'>";
// If it was just a line break, keep it
if(line.length === 0) {
lineText = lineText + "<br>";
}
else {
var charIndex, char;
var id = "";
for(charIndex = 0; charIndex < line.length; charIndex++) {
char = line.charAt(charIndex);
// If it's a space, add a space.
if(char.match(/\s/)) {
if(id.length > 0)
lineText = lineText + tokenToHTML(id);
lineText = lineText + " "; // this needs to be " " instead of   for text-wrapping purposes.
id = "";
}
// If it's a comma, add the accumulated id if necessary and then add a comma,
// resetting the accumulated id.
else if(char === ',') {
if(id.length > 0)
lineText = lineText + tokenToHTML(id);
lineText = lineText + tokenToHTML(",");
id = "";
}
// Otherwise, just accumulate characters for the id.
else
id = id + char;
}
// If there's text accumulated for the id, generate a token for it.
if(id.length > 0)
lineText = lineText + tokenToHTML(id);
}
// End the line.
lineText = lineText + "</div>";
// Increment the token number to account for the new line
count++;
// Add the line to the html.
html = html + lineText;
}
return html;
},
htmlToGidgetCode: function(html) {
/* console.log("Before\n" + html); */
var ce = $("<pre />").html(html);
// If this is mozilla, opera, or IE, replace non-last child, non-only-child <br> tags with new lines.
// The reason for this is that <br>s don't actually create a new line when immediately followed by a block.
// We do this before replacing divs, so we can keep track of which <br>s are only or last children.
if($.browser.mozilla || $.browser.opera ||$.browser.msie )
ce.find("br:not(:last-child,:only-child)").replaceWith("<span>\n</span>");
// After doing this, replace all divs with new lines.
if ($.browser.webkit || $.browser.mozilla) {
// We do this in a loop since divs within divs are eliminated when outer divs are replaced.
// We just keep replacing until there are no more divs.
do {
var divs = ce.find("div");
divs.replaceWith(function() { return "\n" + this.innerHTML; });
} while(divs.length > 0);
}
// If this is IE, which inserts <p> tags, replace the <p> with the text followed by a <br>
if ($.browser.msie)
ce.find("p").replaceWith(function() { return this.innerHTML + "<br>"; });
/* console.log("After transformation\n" + ce.html()); */
var code = ce.text();
code = jQuery.trim(code);
/* console.log("Extracted, trimmed text\n" + code); */
return code;
},
currentMissionText: undefined,
// Should only be called once upon starting the level or when the user requests to start over.
setLevel: function(level) {
this.level = GIDGET.levels[level];
localStorage.currentLevel = level;
this.reset();
// Initialize the Gidget code with the code provided in the level specification.
this.setCodeToWorldDefault();
// Initially disable the reset button
$('#reset').attr('disabled', true);
this.currentMissionText = -1;
this.saveCurrentLevelCode();
// Set titlebar with level number and title (if there is one)
this.showLevelInfo();
this.showAllButMission(true);
// Show the first mission text.
this.showNextMissionText();
// Make the code editable
$('#code').attr('contentEditable', 'true');
// Hide all commands in the hidden command list.
this.hideUnknownCommands();
},
performAdaptations: function(competence){
if (competence == 0){
this.world.highAdapt();
//this.world.gidget.setEnergy(this.world.adaptEnergy);
//example: add extra object
//new GIDGET.Thing(this.world, "rock", 2, 2, "brown", [], {});
//example: rat enemy
/*
var rat = new GIDGET.Thing(this.world, "rat", 3, 4, "yellow", [], {});
rat.setCode(
"say Yum! I want to munch on your tasty wires to take all your energy!\n" +
"when gidget on rat, set gidget energy 0\n" +
"scan gidget\n" +
"goto gidget\n"
);
rat.setSpeed(10);
*/
//example: battery replacing energy
/*new GIDGET.Thing(this.world, "battery", 2, 2, "yellow", [],
{
energize : new GIDGET.Action([ "beneficiary" ],
"raise beneficiary energy 10"
)
}
);
this.world.gidget.setEnergy(this.world.gidget.energy-10);
*/
//example: extra goal
/*new GIDGET.Thing(this.world, "goop", 4, 4, "green", [], {});
this.world.addGoal("goop on bucket");
*/
}
else if (competence > 4){
console.log("LowAdaptGo");
this.world.lowAdapt();
//example: energy boost
//this.world.gidget.setEnergy(9000);
//example: add batteries
/*new GIDGET.Thing(this.world, "battery", 2, 2, "yellow", [],
{
energize : new GIDGET.Action([ "beneficiary" ],
"raise beneficiary energy 10"
)
}
);*/
}
},
hideUnknownCommands: function() {
$('.cheatsheetItem').show();
var command;
for(command in this.world.hiddenCommands) {
if(this.world.hiddenCommands.hasOwnProperty(command)) {
$('#cheat-' + command).hide();
}
}
},
// Checks to see if current code has changed from the original code.
didCodeChange: function(currentCode) {
// String comparison doesn't work correctly without removing all whitespace characters
return (this.world.code.replace(/\s/g, "") != this.htmlToGidgetCode(currentCode).replace(/\s/g, ""));
},
showNextMissionText: function() {
$('*').removeClass('runtimeReference');
this.currentMissionText++;
if(this.currentMissionText >= this.world.missionText.length) {
this.visualizeDecision(new GIDGET.text.Message(this.world.missionText[this.currentMissionText - 1].text));
this.currentMissionText = undefined;
this.showExecutionControls();
this.showAllButMission(false);
}
else {
this.visualizeDecision(new GIDGET.text.Message(this.world.missionText[this.currentMissionText].text + "<div><button onclick='GIDGET.ui.step()' class='align-right'>next...</button></div>", undefined, this.world.missionText[this.currentMissionText].state), false);
}
},
nextLevel: function() {
// Disable any UI in the learner's thought bubble, so the learner can't do anything yet.
GIDGET.ui.setThought("<span id='learnerSpeech'></span>", 0, "learner");
var levelData = getLocalStorageObject('levelMetadata');
//ADAPT check performance
if (levelData[this.getCurrentLevel()].failCount > 4){
this.competence = 0;
}
else if (levelData[this.getCurrentLevel()].failCount == 0){
this.competence = 2;
}
// Remember that this level was passed, what time, and the final code.
this.saveCurrentLevelCode();
//var levelData = getLocalStorageObject('levelMetadata');
levelData[this.getCurrentLevel()].passed = true;
levelData[this.getCurrentLevel()].endTime = (new Date()).getTime();
setLocalStorageObject('levelMetadata', levelData);
// Now find the next level.
var found = false;
var nextLevel = undefined;
for(var level in GIDGET.levels) {
if(GIDGET.levels.hasOwnProperty(level)) {
if(found) {
nextLevel = level;
break;
}
else if(level === localStorage.currentLevel) {
found = true;
}
}
}
if(isDef(nextLevel)) {
this.setLevel(nextLevel);
}
else {
$('#container').fadeTo(1000, 0.0);
$('#finishedLevels').show();
//this.quit("Congratulations! You beat all of the levels.");
}
},
// Restores the defaults for the current level.
reset: function() {
this.messages = "";
// Restore the world to its defaults.
this.world = this.level.call();
//adaptive condition
this.energyUsed = 0;
if (GIDGET.experiment.adapt && this.world.levelNumber > 1) {
// this.world.gidget.setEnergy(9000);
this.performAdaptations(this.competence);
}
$('#goals').empty();
// Add the goals text.
var i;
var table = "<table>";
for(i = 0; i < this.world.goals.length; i++)
table = table + "<tr><td><div class='goal' id='goal" + i + "'>" + this.gidgetCodeToHTML(this.world.goals[i]) + "</div></td><td><span class='success'>✔</span><span class='failure'>✖</span></td></tr>";
$('#goals').html(table);
$('.success').hide();
$('.failure').hide();
$('#goals').removeClass('runtimeReference');
this.done();
this.drawGrid();
this.updateRuntimeUserInterface();
},
done: function() {
this.highlightToken(undefined);
},
start: function() {
// This creates a new world, reset to its defaults.
this.reset();
$('#goal').css('backgroundColor', 'rgb(42,33,28)');
$('#code').attr('contentEditable', 'false');
// Start the world, but give Gidget the users code.
this.world.start(this.htmlToGidgetCode($('#code').html()));
this.updateRuntimeUserInterface();
},
showExecutionControls: function() {
var message;
if (GIDGET.experiment.condition)
message = "Tell Gidget to execute:";
else
message = "Gidget, please execute...";
GIDGET.ui.setThought("<span id='learnerSpeech'>"+message+"</span> <br>\n" +
"<button id='step' onclick='hideToolTip(); GIDGET.ui.stepOnce();' title='Ask Gidget to execute one step of the instructions - there may be multiple steps per line - this button may need to be pressed multiple times to go through the instructions and evaluate the goals. This also toggles the command helper sheet when errors are detected.'>one<br />step</button>\n" +
"<button id='line' onclick='hideToolTip(); GIDGET.ui.runToNextLine();' title='Ask Gidget to execute one whole line of the instructions - this button may need to be pressed multiple times to go through the instructions and evaluate the goals. This also toggles the command helper sheet when errors are detected.'>one<br />line</button>\n"+
"<button id='play' onclick='hideToolTip(); GIDGET.ui.playToEnd();' title='Ask Gidget to execute all the instruction and check the goals step-by-step. This button does not stop for any errors.'>all<br />steps</button>\n" +
"<button id='end' onclick='hideToolTip(); GIDGET.ui.runToEnd();' title='Ask Gidget to execute all the instructions and check the goals in one step, showing only the final output. This button does not stop for any errors.'>to<br />end</button>\n",
0, "learner");
},
retryLevel: function() {
GIDGET.ui.showExecutionControls();
GIDGET.ui.currentMissionText = undefined;
$('#code').attr('contentEditable', 'true');
GIDGET.ui.reset();
},
showLevelControls: function(succeeded) {
var message;
if (GIDGET.experiment.isControl())
message = "Tell Gidget to:";
else
message = "Gidget, let's...";
if (!succeeded) {
GIDGET.ui.setThought(
"<span id='learnerSpeech'>"+message+"</span> <br>" +
"<button onclick='GIDGET.ui.retryLevel();'>retry this mission!</button><br>",
0, "learner");
} else {
GIDGET.ui.setThought(
"<span id='learnerSpeech'>"+message+"</span> <br>" +
"<button onclick='GIDGET.ui.nextLevel()'>start the next mission!</button><br>" +
"<button onclick='GIDGET.ui.retryLevel()'>redo this mission!</button><br>",
0, "learner");
}
},
modifyCommStylesForControl: function() {
$('#learnerThought').css('margin-top', '.5em');
$('.bubbleText').css('font-family', '\"Courier New\", Courier, monospace');
$('#code').css({'border-radius': '.25em .25em 0em 0em', '-moz-border-radius': '.25em .25em 0em 0em'})
$('#goals').css({'border-radius': '0em 0em .25em .25em', '-moz-border-radius': '0em 0em .25em .25em'})
$('#memory').css({'border-radius': '.25em', '-moz-border-radius': '.25em'})
$("body").append("<style type='text/css'>.bubbleText button{font-family: \"Courier New\", Courier, monospace;}</style>");
},
modifyCommStylesForExperimental: function() {
$('.bubbleText').css('font-family', 'Verdana, Arial, Helvetica, sans-serif');
$('#code').css({'border-radius': '1em .5em 0 0', '-moz-border-radius': '1em .5em 0 0'})
$('#goals').css({'border-radius': '0 0 1em .5em', '-moz-border-radius': '0 0 1em .5em'})
$('#memory').css({'border-radius': '1em .5em 1em .5em', '-moz-border-radius': '1em .5em 1em .5em'})
$("body").append("<style type='text/css'>.bubbleText button{font-family: Verdana, Arial, Helvetica, sans-serif;}</style>");
},
modifyCommStyles: function() {
if (GIDGET.experiment.isControl())
this.modifyCommStylesForControl();
else
this.modifyCommStylesForExperimental();
},
createLearnerBubble: function(message) {
var image;
switch (GIDGET.experiment.condition) {
case "control":
image = "satellite";
break;
case "female":
image = "female";
break;
case "male":
image = "male";
break;
default:
image = "experimental";
break;
}
if (GIDGET.experiment.isControl()){
return "<div class='thoughtBubbleControl'><table class='thoughtTable'><tr><td><img src='media/" + image + ".default.png' class='thing' title='This is you.' style='padding: 0 .15 0 .15em;' /></td><td style='width: 100%;'>" + message + "</td></tr></table></div>";
}
else {
return "<table class='thoughtTable thoughtTableLearner'><tr><td><img src='media/" + image + ".default.png' class='thing' title='This is you!' style='display: block;' /><img src='media/speechTailLearner.default.png' style='position: relative; right: -1.85em; top: -2em;' /></td><td class='thoughtBubbleCommunication' style='padding: 1em 0 1em 1em;'>" + message + "</td></tr></table>";
}
},
createGidgetBubble: function(message) {
var gidgetImg;
if (GIDGET.experiment.isControl())
gidgetImg = "media/control.";
else
gidgetImg = "media/gidget.";
if (GIDGET.experiment.isControl()){
return "<div class='thoughtBubbleControl' style='width: 18em;'><table class='thoughtTable'><tr><td><img src='" + gidgetImg + this.world.gidget.runtime.state + ".png' class='thing' title='This is your communication window with Gidget' style='padding: 0 1em 0 .5em;' /></td><td><span id='gidgetSpeech'>" + message + "</span></td></tr></table></div>";
}
else {
return "<table class='thoughtTable thoughtTableGidget'><tr><td class='thoughtBubbleCommunication'><span id='gidgetSpeech'>" + message + "</span></td><td><img src='" + gidgetImg + this.world.gidget.runtime.state + ".png' class='thing' title='This is Gidget communicating with you!' style='display: block;' /><img src='media/speechTailGidget.default.png' style='position: relative; left: -1.6em; top: -2.2em;' /></td></tr></table>";
}
},
setThought: function(message, time, target) {
var html;
var delay = isDef(time) ? time : 0;
var who = isDef(target) ? target : "gidget";
if (who === "gidget")
html = this.createGidgetBubble(message);
else
html = this.createLearnerBubble(message);
if(delay === 0) {
$('#'+who+"Thought").html(html);
}
else {
$('#'+who+"Thought").animate({
opacity: 0.0
}, delay,
function() {
$('#'+who+"Thought").html(html);
$('#'+who+"Thought").animate({ opacity: 1.0 }, delay);
}
);
}
},
// Used to temporarily store the list of commands logged for this level.
// These are saved when the levelMetadata is saved.
stepLog: [],
failCount: 0,
minEnergy: 1000,
energyUsed: 0,
currentExecutionMode: undefined,
logStep: function(kind) {
this.currentExecutionMode = kind;
// Save the kind of command, when it happened, and for which level.
this.stepLog.push({
kind: kind,
time: (new Date()).getTime()
});
},
stepOnce: function() {
this.logStep("step");
GIDGET.ui.step(false, true);
this.currentExecutionMode = undefined;
},
// Just a helper function for playToEnd() to call.
stepContinue: function() {
GIDGET.ui.step(true, false);
},
// Executes, but does not animate, each instruction
runToEnd: function() {
GIDGET.ui.media.disableSounds = true;
this.logStep("end");
this.enableExecutionButtons(false);
// Start the world.
if(!this.world.isExecuting())
this.start();
while(this.world.isExecuting())
GIDGET.ui.step(false, false);
this.executeGoals();
GIDGET.ui.media.disableSounds = false;
while(this.goalNumberBeingExecuted <= this.world.goals.length)
GIDGET.ui.step(false, false);
this.enableExecutionButtons(true);
this.currentExecutionMode = undefined;