This repository has been archived by the owner on May 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
editor.html
985 lines (872 loc) · 28.2 KB
/
editor.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Editor de mundo de Juego#96</title>
<script src="script.js"></script>
<link rel="stylesheet" href="estilo.css">
<link href='https://fonts.googleapis.com/css?family=PT+Mono' rel='stylesheet' type='text/css'>
</head>
<body>
<header>
<h1>Editor de mundo de Juego#96</h1>
</header>
<div id="editor"></div>
<script>
//"use strict";
function elt(name, attr) {
var node = document.createElement(name);
if( attr ) {
for( var key in attr )
if( attr.hasOwnProperty( key ) )
node.setAttribute( key, attr[key] );
}
return node;
}
function Editor( parent, tools ) {
this.canvas = elt("canvas");
this.cx = this.canvas.getContext("2d");
this.canvas.addEventListener("contextmenu", function(e){e.preventDefault();});
this.toolbar = elt("form");
this.cursor = new Cursor(0,0); this.cursorColor = "blue";;
this.selection = null; this.history = []; this.historyIndex = 0;
try {
var maps = JSON.parse( localStorage.getItem("mapList") );
this.map = new Map( JSON.parse( localStorage.getItem( "map" + maps[0] ) ) );
} catch(e) {
this.map = new Map([" "," "," "," "," "]);
}
parent.appendChild( this.toolbar );
parent.appendChild( this.canvas );
var editor = this;
for( var tool in tools ) (function(tool) {
var radio = elt("input", {type: "radio", name: "tool", id: tool});
radio.addEventListener("change", function() {
removeEvents( editor.canvas );
removeEvents( window );
editor.refresh();
Array.prototype.forEach.call(editor.toolbar.querySelectorAll("div.tool"), function(each) {
each.removeAttribute("active");
});
editor.toolbar.querySelector("div."+tool).setAttribute("active", 1);
});
var label = elt("label", {"for": tool});
label.appendChild( tools[tool]( editor, radio ) );
var toolCont = elt("div", {class: tool + " tool"});
toolCont.appendChild( radio );
toolCont.appendChild( label );
editor.toolbar.appendChild( toolCont );
})(tool);
document.body.onkeydown = function(event) {
if( event.ctrlKey ) {
switch( event.keyCode ) {
case 90: // Z
event.preventDefault();
editor.moveHistory(1);
break;
case 89: // Y
editor.moveHistory(-1);
break;
}
}
};
editor.refresh( true );
var modals = this.toolbar.querySelectorAll(".options");
Array.prototype.forEach.call(modals, function(modal) {
var rect = this.canvas.getBoundingClientRect();
modal.style.left = rect.right + "px";
modal.style.top = "64px";
}, this);
}
Editor.prototype.moveHistory = function( num ) {
if( ! this.history[ this.historyIndex ] ||
!this.history[this.historyIndex + num] ) return false;
this.historyIndex += num;
this.map = new Map( this.history[ this.historyIndex ].split("\n") );
this.refresh();
}
Editor.prototype.drawMap = function() {
canvasRenderer( this.map, this.cx );
}
Editor.prototype.drawCursor = function() {
this.cx.lineWidth = 2;
this.cx.strokeStyle = this.cursorColor;
this.cx.strokeRect( this.cursor.x * scale-.5, this.cursor.y * scale-.5, scale+1, scale+1 );
}
Editor.prototype.drawSelection = function() {
if( !this.selection ) return false;
var width = Math.abs( this.selection[1].x - this.selection[0].x ) + 1;
var height = Math.abs( this.selection[1].y - this.selection[0].y ) + 1;
var selection_start = new Cursor(Math.min( this.selection[0].x, this.selection[1].x ),
Math.min( this.selection[0].y, this.selection[1].y ));
this.cx.lineWidth = 2;
this.cx.strokeStyle = this.cursorColor;
this.cx.strokeRect( selection_start.x * scale-.5, selection_start.y * scale-.5,
width * scale+1, height * scale+1);
return true;
}
Editor.prototype.refresh = function( history ) {
if( history === true ) {
if( this.historyIndex > 0 ) {
this.history = this.history.slice( this.historyIndex );
this.historyIndex = 0;
}
this.history.unshift( this.map.toString() );
if( this.history.length > 50 )
this.history.pop();
}
this.drawMap();
if(this.drawSelection() == false)
this.drawCursor();
}
Editor.prototype.moveCursor = function( movement ) {
this.cursor = this.cursor.add( movement );
if( this.cursor.x < 0 ) {
this.cursor.x = this.map.grid.width - 1;
this.cursor.y = this.cursor.y - 1;
}
if( this.cursor.x > this.map.grid.width - 1 ) {
this.cursor.x = 0;
this.cursor.y = this.cursor.y + 1;
}
this.cursor.y = Math.max( 0, Math.min( this.cursor.y, this.map.grid.height-1 ) );
}
var tools = Object.create(null);
tools.text = function( editor, radio ) {
var input = elt("input", {type: "text", class: "hidden"});
var cursor_caché = editor.cursor, arrows = {
37: new Cursor( -1, 0 ),
38: new Cursor( 0, -1 ),
39: new Cursor( 1, 0 ),
40: new Cursor( 0, 1 )
};
input.addEventListener("input", function( event ) {
event.preventDefault();
if( this.value ) {
var txt = this.value;
this.value = "";
for( var i = 0; i < txt.length; i++ ) {
if( txt[i] == "\n" ) {
editor.cursor = cursor_caché
editor.moveCursor( new Cursor(0,1) );
cursor_caché = editor.cursor;
continue;
}
if( txt[i] == "\t" ) {
editor.moveCursor(new Cursor(2, 0));
continue;
}
editor.map.grid.set( editor.cursor, txt[i] );
editor.moveCursor( new Cursor(1, 0) );
}
editor.refresh(true);
}
});
input.addEventListener("keydown", function( event ) {
switch( event.keyCode ) {
case 37:
case 38:
case 39:
case 40: // Arrows
event.preventDefault();
editor.moveCursor( arrows[ event.keyCode ] );
cursor_caché = editor.cursor;
editor.refresh();
break;
case 8: // Backspace
event.preventDefault();
editor.moveCursor( new Cursor(-1, 0) );
editor.map.grid.set( editor.cursor, " " );
editor.refresh(true);
break;
case 46: // Supr
event.preventDefault();
editor.map.grid.set( editor.cursor, " " );
editor.refresh(true);
break;
case 13: // Enter
event.preventDefault();
editor.cursor = cursor_caché
editor.moveCursor( new Cursor(0,1) );
cursor_caché = editor.cursor;
editor.refresh();
break;
default:
//console.log( event.keyCode );
break;
}
}, false);
var div = elt("div");
var span = elt("span")
span.textContent = "Texto";
div.appendChild(span);
div.appendChild( input );
radio.addEventListener("change", function() {
editor.selection = null; editor.refresh();
editor.canvas.onclick = function(event) {
event.preventDefault();
input.focus();
editor.cursor = getCursorPos(this, event);
cursor_caché = editor.cursor;
editor.refresh();
}
});
return div;
}
function removeEvents( elem ) {
elem.onmousedown = elem.onmousemove = elem.onmouseup
= elem.onmouseover = elem.onmouseout = elem.onclick
= elem.onkeydown = elem.onkeyup = elem.onkeypress
= elem.onfocus = elem.onblur = null;
}
function getRelativePos( elem, event ) {
var rect = elem.getBoundingClientRect();
return new Cursor(event.clientX - rect.left,
event.clientY - rect.top);
}
function getCursorPos( elem, event ) {
var pos = getRelativePos( elem, event );
pos.x = Math.floor(pos.x / scale);
pos.y = Math.floor(pos.y / scale);
return pos;
}
tools.brush = function( editor, radio ) {
var div = elt("div");
var brush = " ", mouse = 0;
radio.addEventListener("change", function() {
editor.selection = null;
editor.canvas.onmousedown = function( event ) {
event.preventDefault();
mouse = event.which;
handleMouseEvent( event );
}
editor.canvas.onmousemove = function( event ) {
event.preventDefault();
var curs = getCursorPos( this, event );
if( editor.map.grid.isInside(curs) ) editor.cursor = curs;
handleMouseEvent( event )
editor.refresh();
}
editor.canvas.onmouseout = editor.canvas.onmouseup = function() {
if( mouse == 1 || mouse == 3 )
editor.refresh(true);
mouse = 0;
}
});
function handleMouseEvent( event ) {
if(mouse == 1) {
editor.map.grid.set( editor.cursor, brush );
return;
}
if(mouse == 2) {
brush = editor.map.grid.get( editor.cursor );
var curs = dragEdit.map.grid.look( brush );
dragEdit.cursor = curs.length ? curs[0] : new Cursor(0,0);
dragEdit.refresh();
return false;
}
if(mouse == 3) {
editor.map.grid.set( editor.cursor, " " );
return;
}
}
var modal = createModal("Pinceles");
var rect = editor.canvas.getBoundingClientRect();
var dragEdit = new Editor( modal, {} );
removeEvents( document.body );
dragEdit.map = new Map(["`^|°¬ ",
"⋆ ■ᐁ ",
"▪▶-<¬ ",
" ᐂ%& ",
" ᐃ #◀▮",
" "]); // TILES
dragEdit.refresh();
dragEdit.canvas.addEventListener("click", function(event) {
event.preventDefault();
var curs = getCursorPos( this, event );
if( dragEdit.map.grid.isInside(curs) ) dragEdit.cursor = curs;
brush = dragEdit.map.grid.get( dragEdit.cursor );
dragEdit.refresh();
});
var span = elt("span");
span.textContent = "Pincel";
div.appendChild( span );
div.appendChild( modal );
return div;
}
tools.selection = function( editor, radio ) {
var div = elt("div");
var span = elt("span");
span.textContent = "Selección";
div.appendChild( span );
var modal = createModal("Funciones");
var rect = editor.canvas.getBoundingClientRect();
modal.id = "selectionOpt";
div.appendChild(modal);
var options = {
"select": {
content: "⇲ Seleccionar",
title: "Arrastrar el mouse para seleccionar una zona del mapa."
},
"move": {
content: "∗ Mover <small>(Ctrl)</small>",
title: "Arrastrar el mouse para mover la selección. También puede hacerse con 'Ctrl'. "
},
"copy": {
content: "↬ Copiar <small>(Ctrl+Shift)</small>",
title: "Arrastrar el mouse para copiar la selección. También puede hacerse con 'Shift'."
},
"switch": {
content: "⇄ Cambiar de lugar",
title: "Cambia de lugar lo que está en un lado por lo que está en otro."
}
};
var buttons = {
"erase": {
content: "✁ Borrar (Supr)",
title: "Borrar selección. También puede hacerse con 'Supr'.",
click: function() {
if( editor.selection == null )
editor.map.grid.set( editor.cursor, " " );
else
selectionForEach( editor.selection, function(cursor) {
editor.map.grid.set( cursor, " ");
});
editor.refresh( true );
}
},
"invertX": {
content:"↔ Invertir horizontal",
title: "Invertir en el eje horizontal",
click: function() {
if( editor.selection == null ) return false;
var str = "";
var selection = selectionForEach(editor.selection, function(cursor) {
str += editor.map.grid.get(cursor);
});
var width = selection[1].x - selection[0].x + 1, arr = [];
for( var i = 0; i < str.length; i += width )
arr.push( str.slice( i, i+width ) );
arr = arr.map(function(line) {
return line.split("").reverse().join("");
});
var str = arr.join(""), i = 0;
selectionForEach(editor.selection, function(cursor) {
editor.map.grid.set( cursor, str[i] );
i++;
});
editor.refresh( true );
}
},
"invertY":{
content: "↕ Invertir vertical",
title: "Invertir en el eje vertical",
click: function() {
if( editor.selection == null ) return false;
var str = "";
var selection = selectionForEach(editor.selection, function(cursor) {
str += editor.map.grid.get(cursor);
});
var width = selection[1].x - selection[0].x + 1, arr = [];
for( var i = 0; i < str.length; i += width )
arr.unshift( str.slice( i, i+width ) );
var str = arr.join(""), i = 0;
selectionForEach(editor.selection, function(cursor) {
editor.map.grid.set( cursor, str[i] );
i++;
});
editor.refresh( true );
}
}
}
for( var key in options )
if( options.hasOwnProperty(key) )
(function(key) {
var radio = elt("input", {
type: "radio",
id: key,
name: "selectOption"
});
var label = elt("label", {
title: options[key].title,
"for": key
});
label.innerHTML = options[key].content;
radio.addEventListener("change", function(){ tool = key; });
var div = elt("div")
div.appendChild(radio);
div.appendChild(label);
modal.appendChild( div );
})(key);
for( var key in buttons ) {
if( buttons.hasOwnProperty(key) ) {
var button = elt("button", {
type: "button",
title: buttons[key].title,
id: key
});
button.textContent = buttons[key].content;
button.onclick = buttons[key].click;
modal.appendChild(button);
}
}
modal.onclick = function() { editor.canvas.focus() }
modal.querySelector("#select").checked = true;
var mouse = 0, tool = "select";
var oldSelection, relativePosFromSelection;
radio.addEventListener("change", function() {
editor.canvas.onmousedown = function(event) {
mouse = event.which;
if( mouse == 1 ) {
if( tool== "switch" || event.ctrlKey || tool == "move" || tool == "copy" ) {
var curs = getCursorPos( this, event );
if( editor.map.grid.isInside(curs) ) relativePosFromSelection = curs;
oldSelection = editor.selection.slice(0);
if( editor.selection == null)
editor.selection = [relativePosFromSelection, relativePosFromSelection];
} else { //SELECT
var curs = getCursorPos( this, event );
if( editor.map.grid.isInside(curs) ) editor.cursor = curs;
editor.selection = [editor.cursor, editor.cursor];
editor.refresh();
}
}
}
editor.canvas.onmousemove = function(event) {
event.preventDefault();
var curs = getCursorPos( this, event );
if( editor.map.grid.isInside(curs) ) editor.cursor = curs;
if( mouse == 1 ) {
if( event.ctrlKey || tool == "move" || tool=="copy" ||
tool =="switch" ) {
var current_pos = getCursorPos( this, event );
var change = relativePosFromSelection.minus( current_pos );
relativePosFromSelection = current_pos;
editor.selection = editor.selection.map(function(curs) {
return curs.minus( change );
});
} else { // SELECT
if(editor.selection != null)
editor.selection[1] = editor.cursor;
}
editor.refresh();
}
};
editor.canvas.onmouseout = editor.canvas.onmouseup = function(event) {
event.preventDefault();
if( mouse == 1 ) {
if( tool == "move" || tool == "copy" || event.ctrlKey ) {
var i = 0;
var selectedText = "";
if( event.shiftKey || tool == "copy" ) {
selectionForEach( oldSelection, function(cursor) {
selectedText += editor.map.grid.get(cursor) || " ";
});
selectionForEach( editor.selection, function(cursor) {
if( selectedText[i] == " " ) return i++;
editor.map.grid.set( cursor, selectedText[i] );
i++;
});
} else { // MOVE
selectionForEach( oldSelection, function(cursor) {
selectedText += editor.map.grid.get(cursor) || " ";
editor.map.grid.set(cursor, " ");
});
selectionForEach( editor.selection, function(cursor) {
editor.map.grid.set( cursor, selectedText[i] );
i++;
});
}
editor.refresh( true );
} else if( tool =="switch") {
var oldText = "", oldSelectionCursors = [];
selectionForEach( oldSelection, function(cursor) {
oldText += editor.map.grid.get(cursor) || " ";
oldSelectionCursors.push(cursor);
});
var i = 0, newSelectionCursors = [];
selectionForEach( editor.selection, function(cursor) {
editor.map.grid.set( oldSelectionCursors[i], editor.map.grid.get(cursor) );
newSelectionCursors.push(cursor);
i++;
});
var i = 0;
selectionForEach( editor.selection, function(cursor) {
editor.map.grid.set( newSelectionCursors[i], oldText[i] );
i++;
});
editor.refresh(true);
}else {
editor.refresh();
}
if( editor.selection != null && editor.selection[0].isEqualTo( editor.selection[1] ) )
editor.selection = null;
}
mouse = 0;
}
window.onkeydown = function(event) {
if( event.keyCode == 46 ) // supr.
modal.querySelector("#erase").click();
}
});
function selectionForEach( selection, fn ) {
var selection = [
new Cursor(Math.min( selection[0].x, selection[1].x),
Math.min( selection[0].y, selection[1].y)),
new Cursor(Math.max( selection[0].x, selection[1].x),
Math.max( selection[0].y, selection[1].y))];
for( var y = selection[0].y; y <= selection[1].y; y++)
for( var x = selection[0].x; x <= selection[1].x; x++ ) {
fn( new Cursor( x, y ) );
}
return selection;
}
return div;
}
function createModal(title) {
var opt = elt("div", {class: "options"});
var drag = elt("div", {class: "drag", "tabIndex": 2});
drag.textContent = title;
var drag_mouse = 0, drag_pos;
drag.addEventListener("mousedown", function(event) {
var rect = opt.getBoundingClientRect();
drag_pos = {x: event.clientX - rect.left,
y: event.clientY - rect.top};
drag_mouse = event.which;
});
window.addEventListener("mousemove", function(event) {
if(drag_mouse == 1) {
event.preventDefault();
opt.style.left = event.clientX - drag_pos.x + "px";
opt.style.top = event.clientY - drag_pos.y + "px";
}
});
window.addEventListener("mouseup", function(event) {
if( drag_mouse == 1 )
drag_mouse = 0;
});
opt.appendChild( drag );
return opt;
}
tools.changeSize = function( editor, radio ) {
var div = elt("div");
var span = elt("span");
span.textContent = "Cambiar tamaño";
div.appendChild( span );
var opt = createModal("Tamaño");
var rect = editor.canvas.getBoundingClientRect();
var TVControllers = elt("div", {class: "TVControllers"});
var directions = ["up", "down", "left", "right"];
directions.forEach(function(direction) {
var button = elt("button", { type: "button", class:direction });
button.textContent = direction == "down" || direction == "right" ? "+" : "-" ;
TVControllers.appendChild( button );
button.onclick = function(){
var sketch = editor.map.toString().split("\n");
switch( this.className ){
case "up":
sketch.pop()
break;
case "down":
var newLine = '';
for (var i = editor.map.grid.width - 1; i >= 0; i--) {
newLine += ' ';
};
sketch.push( newLine );
break;
case "left":
sketch = sketch.map(function(line){
return line.slice( 0, line.length-1 );
});
break;
case "right":
sketch = sketch.map(function(line) {
return line + " ";
});
break;
}
editor.map = new Map(sketch);
editor.refresh(true);
};
});
opt.appendChild( TVControllers );
div.appendChild( opt );
return div;
}
tools.maps = function( editor, radio ) {
var span = elt("span");
span.textContent = "Gestión de mapas";
var div = elt("div");
div.appendChild(span);
var modal = createModal("Mapas");
var rect = editor.canvas.getBoundingClientRect();
div.appendChild( modal );
var buttonCont = elt("div", {id: "maptools"});
modal.appendChild( buttonCont );
var search = elt("input", {type: "text"});
var list = elt("ul");
var save = elt("button", {type: "button"}); save.textContent = "Guardar";
var open = elt("button", {type: "button"}); open.textContent = "Abrir";
var erase = elt("button", {type: "button"}); erase.textContent = "Borrar";
var hr = elt("hr");
var imp = elt("button", {type: "button"}); imp.textContent = "Importar";
var exp = elt("button", {type: "button"}); exp.textContent = "Exportar";
var impAll = elt("input", {type: "file"});
var impAllContainer = elt("div"); impAllContainer.textContent = "Importar desde archivo";
impAllContainer.appendChild(impAll);
var expAll = elt("button", {type: "button"}); expAll.textContent = "Exportar a archivo";
addChilds( buttonCont, search, list, save, open, erase, hr, imp, exp, impAllContainer, expAll );
function ACTUALIZAR() {
list.textContent = "";
var maps = JSON.parse(localStorage.getItem("mapList"));
if(maps)
maps.forEach(function(name) {
if( name.indexOf(search.value) == 0 ) {
var li = elt("li");
li.textContent = name;
li.onclick = function() {
Array.prototype.forEach.call(list.children, function(child) {
child.className = "";
});
this.className = "active";
search.value = this.textContent;
}
list.appendChild(li);
}
});
var first = list.querySelector("li")
if(!first) {
list.innerHTML = "<small style='opacity:.5;font-style:italic'>No se encontró ningún mapa.</small>";
}
}
search.addEventListener("input", ACTUALIZAR);
ACTUALIZAR();
save.addEventListener("click", function() {
var nombre = search.value;
if( !nombre ) {
var selected = list.querySelector(".active");
if( selected )
nombre = selected.textContent;
else
return createPopUp("ERROR", "Tenés que ingresar<br />un nombre para guardar.");
}
var maps = JSON.parse(localStorage.getItem("mapList")) || [];
if( maps.indexOf(nombre) != -1 )
maps.splice( maps.indexOf(nombre), 1 );
maps.unshift( nombre );
localStorage.setItem( "mapList", JSON.stringify(maps) );
localStorage.setItem( "map"+ nombre, JSON.stringify( editor.map.toString().split("\n") ) );
createPopUp("Info", "El mapa se guardó correctamente.");
search.value = "";
ACTUALIZAR();
list.querySelector("li").className = "active";
});
open.addEventListener("click", function() {
var selected = list.querySelector(".active");
if( selected == null ) return createPopUp("ERROR", "Tenés que seleccionar<br />un mapa para abrir.");
var map = JSON.parse( localStorage.getItem( "map"+ selected.textContent ) );
if( !map ) return createPopUp("ERROR", "Al parecer el mapa que querés<br />abrir no existe.");
editor.map = new Map( map );
editor.refresh( true );
search.value = "";
var nombre = selected.textContent;
var maps = JSON.parse(localStorage.getItem("mapList"));
if( maps.indexOf(nombre) != -1 )
maps.splice( maps.indexOf(nombre), 1 );
maps.unshift( nombre );
localStorage.setItem( "mapList", JSON.stringify(maps) );
ACTUALIZAR();
list.querySelector("li").className = "active";
});
erase.addEventListener("click", function() {
var selected = list.querySelector(".active");
if( selected == null ) return createPopUp("ERROR", "Tenés que seleccionar<br />un mapa para borrar.");
var maps = JSON.parse(localStorage.getItem("mapList"));
maps.splice( maps.indexOf( selected.textContent ), 1 );
localStorage.setItem( "mapList", JSON.stringify(maps) );
localStorage.removeItem( "map" + selected.textContent );
createPopUp("Info", "El mapa se borró correctamente");
search.value = "";
ACTUALIZAR();
});
imp.addEventListener("click", function() {
var popup = createPopUp("Importar",
"<p>Ingresar el mapa en formato<br />JSON (array de strings)</p>");
var textarea = elt("textarea");
textarea.select();
document.execCommand("paste")
var btn = elt("button", {type: "button"}); btn.textContent = "Importar";
addChilds(popup, textarea, elt("br"), btn);
btn.onclick = function() {
try {
var textarea = popup.querySelector("textarea");
if( !textarea.value ) throw new Error("¡No ingresaste nada!");
console.log( textarea.value );
var arr = JSON.parse(textarea.value);
if( typeof arr != "object" ) throw new SyntaxError("Formato inválido.<br />"+
'Ingresar como array en formato JSON.<br />'+
'Ej.: [" ", " ", " "];');
editor.map = new Map(arr);
editor.refresh( true );
popup.querySelector(".popUpClose").click();
} catch(e) {
return createPopUp("ERROR", e.toString() );
}
}
if( list.querySelector(".active") )
list.querySelector("li").className = "";
});
exp.addEventListener("click", function() {
var popup = createPopUp("Exportar",
"<p>Tu mapa:</p><hr />");
var textarea = elt("textarea", {class: "mapExport"});
var arr = editor.map.toString().split("\n");
textarea.value = JSON.stringify( arr ).replace(/"\,"/g, '",\n"');
popup.appendChild(textarea);
var btn = elt("button", {type: "button"});
btn.textContent = "Copiar";
btn.addEventListener("click", function() {
textarea.select();
try {
if( document.execCommand("copy") == "unsuccessful" )
throw new Error("Error: execComand unsuccessful");
} catch(err) {
createPopUp("ERROR", "No se pudo copiar. <br />"+ err.toString() );
}
});
popup.appendChild( elt("br") );
popup.appendChild(btn);
});
impAll.addEventListener("change",function() {
if( this.files.length == 0 ) return;
var reader = new FileReader();
reader.addEventListener("load", function(event) {
try {
eval(reader.result);
removeEvents(window);
} catch(e) {
createPopUp("ERROR", e.toString());
}
var game = getGAME();
var levels = game.levelSketches;
var maps = JSON.parse(localStorage.getItem("mapList")) || [];
levels.forEach(function(sketch, i) {
var nombre = "GAME_LEVEL "+ zeroPad(i);
if( maps.indexOf(nombre) != -1 )
maps.splice( maps.indexOf(nombre), 1 );
maps.unshift( nombre );
localStorage.setItem( "map"+ nombre, JSON.stringify( sketch ) );
});
localStorage.setItem( "mapList", JSON.stringify(maps) );
ACTUALIZAR();
});
reader.readAsText( this.files[0] );
});
function zeroPad(n) {
if(n < 10) return "0" + String(n);
else return String(n);
}
expAll.addEventListener("click", function() {
var maps = JSON.parse(localStorage.getItem("mapList")) || [];
maps = maps.filter(function(nombre) {
if( nombre.indexOf("GAME_LEVEL")== 0 )
return true;
else return false;
});
maps.sort(function(a,b) {
if(a<b) return -1;
if(a>b) return 1;
return 0;
});
var file =
"function getGAME() {\n"+
" var game = new Game();\n";
maps.forEach(function(nombre) {
file += ' game.addLevel(\n["';
file += JSON.parse( localStorage.getItem( "map"+ nombre ) ).join('",\n\t"');
file += '"]);\n';
});
file += " return game;\n";
file += "}";
downloadTextFile("application/javascript", "niveles.js", file);
});
return div;
}
function addChilds( parent ) {
for( var i = 1; i < arguments.length; i++ ) {
var child = arguments[i];
if( typeof child == "string" )
child = document.createTextNode( child );
parent.appendChild( child );
}
}
tools.test = function( editor, radio ) {
var div = elt("div")
var span = elt("span");
span.textContent = "Probar mapa";
div.appendChild( span );
radio.addEventListener("change", function() {
if(editor.map.grid.look("^").length == 1 &&
editor.map.grid.look("`").length == 1 &&
editor.map.grid.look("⋆").length == 2 ) {
var map = editor.map.toString().split("\n");
var game = new Game();
game.addLevel(map);
game.loadLevel();
game.level.onStatusChange = function status() {
setTimeout(function() {
game.loadLevel();
game.level.onStatusChange = status;
}, 1000);
}
game.refresh = function() {
canvasRenderer( game.level.map, editor.cx );
}
game.refresh();
} else {
createPopUp("ERROR",
"<p>Antes de probar el mapa, tené en cuenta lo siguiente:</p><hr />"+
"<pre>"+
"> Tiene que haber dos (2) personajes y dos\n"+
"(2) estrellas para poder jugar.\n\n"+
"> El personaje principal siempre va a ser\n"+
"el que esté en el lado izquierdo del mapa.\n\n"+
"> A cada personaje le corresponde sólamente\n"+
"una estrella.\n\n"+
"> Al personaje de la izquierda le correspon-\n"+
"de la estrella de la izquierda."+
"</pre>" );
}
});
return div;
}
function createPopUp(title, html) {
var old = document.body.querySelector(".popUp");
if( old ) document.body.removeChild(old);
var node = createModal( title );
node.className = "options popUp";
var content = elt("div", {class: "popUpContent"});
content.innerHTML = html;
node.appendChild( content );
var close = elt("span", {class: "popUpClose"});
close.textContent = "x";
close.onclick = function() {
document.body.removeChild( node );
}
node.querySelector(".drag").appendChild(close);
document.body.appendChild( node );
return node;
}
var editor = new Editor( document.querySelector("#editor"), tools );
function downloadTextFile(type, filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:'+type+';charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
</script>
</body>
</html>