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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
|
<?PHP
//Displays the map
//TODO: SOON TO DEPRECIATE!! YAY!
function DisplayMap($mapMatrix, $idprefix = 1, $style = 'normal', $speed = NULL) {
//Iterate through $mapMatrix and generate the html
$maptable = ""; //The string to return to the database.
$index = 0; //The current number of tiles from the last tile saved.
$example = false;
if ($style == 'example') {
$example = true;
}
$puzzle = false;
if ($style == 'puzzle') {
$puzzle = true;
}
if ($speed == NULL) {
if ($example) {
$speed = 1;
} else {
$speed = 2;
}
}
for($i = 1; $i < count($mapMatrix); $i++)
{
$maptable .= "<tr>";
for($j = 0; $j < count($mapMatrix[$i]); $j++)
{
$handle = "$idprefix,$i,$j";
$mapItemCode = $mapMatrix[$i][$j];
switch($mapMatrix[$i][$j])
{
case 's': $maptable .= "<td title='Start tile. Position: $j,$i' class='grid_td_start' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
case 'S': $maptable .= "<td title='Start tile. Position: $j,$i' class='grid_td_startB' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
case 'X': $maptable .= "<td title='Pathable By Path 1 or 2 not sure yet. Position: $j,$i' class='grid_td_rockxpath2' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
case 'x': $maptable .= "<td title='Pathable By Path 1 or 2 not sure yet. Position: $j,$i' class='grid_td_rockxpath1' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
case 'f': $maptable .= "<td title='Finish tile. Position: $j,$i' class='grid_td_finish' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
//TP1
case 't': $maptable .= "<td title='Teleport 1 in. Position: $j,$i' class='grid_td_tp1_in' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
case 'u': $maptable .= "<td title='Teleport 1 out. Position: $j,$i' class='grid_td_tp1_out' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
//TP2
case 'm': $maptable .= "<td title='Teleport 2 in. Position: $j,$i' class='grid_td_tp2_in' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
case 'n': $maptable .= "<td title='Teleport 2 out. Position: $j,$i' class='grid_td_tp2_out' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
//TP3
case 'g': $maptable .= "<td title='Teleport 3 in. Position: $j,$i' class='grid_td_tp3_in' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
case 'h': $maptable .= "<td title='Teleport 3 out. Position: $j,$i' class='grid_td_tp3_out' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
//TP4
case 'i': $maptable .= "<td title='Teleport 4 in. Position: $j,$i' class='grid_td_tp4_in' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
case 'j': $maptable .= "<td title='Teleport 4 out. Position: $j,$i' class='grid_td_tp4_out' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
//TP5
case 'k': $maptable .= "<td title='Teleport 5 in. Position: $j,$i' class='grid_td_tp5_in' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
case 'l': $maptable .= "<td title='Teleport 5 out. Position: $j,$i' class='grid_td_tp5_out' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break;
case 'a': case 'b': case 'c': case 'd': case 'e':
$checkpoint = strtoupper($mapMatrix[$i][$j]);
$maptable .= "<td title='Checkpoint $checkpoint. Position: $j,$i' class='grid_td_cp$mapItemCode' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>";
break;
case 'r': $maptable .= "<td title='Rock. Position: $j,$i' class='grid_td_rocks' id='$handle' ></td>"; break; //rock
case 'R': $maptable .= "<td title='Silver rock. Position: $j,$i' class='grid_td_gray' id='$handle' ></td>"; break; //metalic looking rock
case 'p': $maptable .= "<td class='grid_td_path' id='$handle' >
<div id='child_$handle' class='grid_inner'></div></td>"; break; //path
case 'q': $maptable .= "<td class='grid_td_blanks' id='$handle' ></td>"; break; //transparent
//Technically shouldn't ever be used to display a wall...
case 'w': $maptable .= "<td class='grid_td_walls' id='$handle' name='true' onClick='grid_click(this)' ></td>"; break; //wall
// default; normally 'o'.
//default: $maptable .= "<td title='Position: $j,$i' class='grid_td' id='$handle' onClick='grid_click(this)' ></td>";
default: $maptable .= "<td class='grid_td' title='Position: $j,$i' id='$handle' onClick='grid_click(this)' >
<div id='child_$handle' class='grid_inner'></div></td>";
}
}
$maptable .= "</tr>";
}
//Prepare mapdata.
$mapdata['height'] = $mapMatrix[0][0];
$mapdata['width'] = $mapMatrix[0][1];
$mapdata['points'] = $mapMatrix[0][2];
$mapdata['rocks'] = $mapMatrix[0][3];
$mapdata['walls'] = $mapMatrix[0][4];
$mapdata['teleports'] = $mapMatrix[0][5];
$mapdata['name'] = $mapMatrix[0][6];
$mapdata['example'] = $example;
$mapdata['mapid'] = $idprefix;
//TODO: del
//$path = routePath($mapMatrix);
$mapdata['code'] = GenerateMapCode($mapMatrix);
$width = (($j * 35) + 2).'px';
//$width = (($j * 23) + 2).'px';
$i -= 1;
$height = (($i * 35) + -1).'px';
//$height = (($i * 22) + 2).'px';
$jsonmap = str_replace("'", "\'", json_encode($mapdata));
//$mapdatadiv .= "<div id='$idprefix,mapdata' style='visibility:hidden;display:none'>";
//$mapdatadiv .= $jsonmap;
//$mapdatadiv .= '</div>';
//JSON Fix for search-engine cache.
$mapdatadiv = "<script>
jsonmapdata['$idprefix'] = '$jsonmap';
</script>";
$maptable = "<table style='width:$width;height:$height;' class='grid_table'>
$maptable
</table>";
$speedOption['Slow'] = 1;
$speedOption['Med'] = 2;
$speedOption['Fast'] = 3;
$speedOption['Ultra'] = 4;
if (isset($_COOKIE['pref_speed'])) {
$prefSpeed = $_COOKIE['pref_speed'];
if (!in_array($prefSpeed, $speedOption))
$prefSpeed = '2';
} else
$prefSpeed = '2';
$rOption = '';
foreach ($speedOption as $key => $value) {
$rOption .= "<option value='$value'";
if ($prefSpeed == $value)
$rOption .= " selected='selected'";
$rOption .= ">$key</option>\n";
}
if (isset($_COOKIE['pref_mute']) && $_COOKIE['pref_mute'] == "true") {
$mutebutton = "<label><input onclick='setMute(this.checked)' type='checkbox' id='$idprefix,mute' class='checkbox_mute' checked='checked' />Mute</label>";
} else {
$mutebutton = "<label><input onclick='setMute(this.checked)' type='checkbox' id='$idprefix,mute' class='checkbox_mute' />Mute</label>";
}
if ($example) {
$output = $maptable;
$output .= "
<div style='display:none'>
<select id='$idprefix,speed'>
$rOption
</select>
</div>
<div class='grid_dsp_left dsp_16'>
<input id='$idprefix,btn' type='button' onclick='doSend($idprefix)' value='Test' />
</div>
<div class='grid_dsp_mid dsp_16'>
$mutebutton
</div>
<div id='$idprefix,dspbr' class='grid_dsp_right dsp_60'>
<div id='$idprefix,dspCount' class='grid_dsp_data'>
0 moves
</div>
</div>
";
$output .= $mapdatadiv;
$output = "<div style='width:$width;height:$height;'>
$output
</div>";
return $output;
}
//$date = date("m-d-y");
//OUTPUT FOR PUZZLE-STYLE MAPS
if ($puzzle) {
$output = "
<div id='$idprefix,outer' class='grid_outer' style='width:".($width+2)."px;height:".($height+60)."px;'>
<div style='display:none;'>
<div id='$idprefix,dspID' title='MapID: $idprefix'>
</div>
</div>
<div id='$idprefix,dspbr' class='grid_dsp_left dsp_60'>
<div id='$idprefix,dspCount' class='grid_dsp_data'>
0 moves
</div>
</div>
<div id='$idprefix,dsptr' class='grid_dsp_right dsp_32'>
<span id='$idprefix,dspWalls' class='grid_dsp_data'>
".$mapdata['walls']." walls
</span>
</div>
$maptable
<div id='$idprefix,dspbl' class='grid_dsp_left dsp_60'>
<input id='$idprefix,btn' type='button' onclick='doSend($idprefix)' value='Go!' />
Speed:
<select onChange='savePref(\"speed\", this.value)' id='$idprefix,speed'>
$rOption
</select>
</div>
<div class='grid_dsp_mid dsp_24'>
$mutebutton
</div>
$mapdatadiv
</div>
";
return $output;
}
//NORMAL OUTPUT:
$output = "
<div id='$idprefix,outer' class='grid_outer' style='width:".($width+2)."px;height:".($height+60)."px;'>
<div class='grid_dsp_left dsp_60'>
<div id='$idprefix,dspID' title='MapID: $idprefix'>
MapID: $idprefix
</div>
</div>
<div id='$idprefix,dsptr' class='grid_dsp_right dsp_33'>
<span id='$idprefix,dspWalls' class='grid_dsp_data'>
".$mapdata['walls']." walls
</span>
<span>
( <a href='javascript:resetwalls($idprefix)'>Reset</a> )
</span>
</div>
$maptable
<div id='$idprefix,dspbl' class='grid_dsp_left dsp_49'>
<input id='$idprefix,btn' type='button' onclick='doSend($idprefix)' value='Go!' />
Speed:
<select onChange='savePref(\"speed\", this.value)' id='$idprefix,speed'>
$rOption
</select>
</div>
<div class='grid_dsp_mid dsp_16'>
$mutebutton
</div>
<div id='$idprefix,dspbr' class='grid_dsp_right dsp_33'>
<div id='$idprefix,dspCount' class='grid_dsp_data'>
0 moves
</div>
</div>
$mapdatadiv
</div>
";
return $output;
}
//This requires the map as an object.
//TODO: SOON TO DEPRECIATE!
function DisplayMapThumbnail($map, $link = false) {
$r = ''; //Prepare our return value:
$tileWidth = 1 / $map->width;
$tileHeight = $goalSize / $map->height;
$sourceWidth = $map->width;
$sourceHeight = $map->height;
$targetWidth = 150;
$sourceRatio = $sourceWidth / $sourceHeight;
// if ( $sourceRatio < $targetRatio ) {
$scale = $sourceWidth / $targetWidth;
// } else {
// $scale = $sourceHeight / $targetHeight;
// }
$resizeWidth = (int)($sourceWidth / $scale);
$resizeHeight = (int)($sourceHeight / $scale);
//$height = $width / ($tileWidth / $tileHeight);
//$height = round($height);
$width = $resizeWidth.'px';
$height = $resizeHeight.'px';
//$height = '100px';
//if ($map-height > $map->width;)
$size = $size.'%';
//$size = '1.2px';
if ($link) {
$r .= "<table style='cursor:pointer' onclick='document.location.href=\"$link\"' class='map'>";
} else {
$r .= "<table style='width:$width;height:$height;' class='map'>";
}
for ($y = 0; $y < $map->height; $y++) { //Number of Rows
$r .= "<tr>";
for ($x = 0; $x < $map->width; $x++) { //Number of Columns
$value = $map->tiles[$y][$x][TileValue];
$type = $map->tiles[$y][$x][TileType];
$r .= "<td class='$type$value' style='width:$tileWidth%;'></td>";
}
$r .= "</tr>";
}
$r .= "</table>";
return $r;
}
//Generates map
function GenerateMap($rows, $cols, $rockchance, $numBlocks = -1, $cp = -1, $tp = -1, $mapName = '') {
if ($numBlocks == -1)
$numBlocks = Rand(7, (int)($rows * $cols) * .12);
//Checkpoints and teleports.
if ($cp == -1)
$cp = rand(0, 5);
if ($tp == -1)
$tp = rand(0, 2);
$tp = $tp * 2; //Requires an out-teleport.
if ($rockchance < 2) $rockchance = 2;
//== Possibility of inf loop here, if the map is too small.
do {
$randvalue = rand(1, ($rows * $cols));
//As long as it isn't the first, or last column.
//if ((($randvalue +1) % ($rows)) > 1) {
//As long as it isn't in the first, 2nd, last and 2nd to last column.
if ((($randvalue +2) % ($rows)) > 3) {
$unique[] = $randvalue;
$unique = array_unique($unique);
$unique = array_values($unique);
}
} while (count($unique) < ($cp+$tp) );
//Prepare our checkpoint and teleport names.
$cpnames = Array("a", "b", "c", "d", "e");
// in out in out etc.
$tpnames = Array("t", "u", "m", "n", 'g', 'h', 'i', 'j', 'k', 'l');
$teleport = Array();
$checkpoint = Array();
//Assign our checkpoints and teleports a unique position on the map.
$i = 0;
for($p = 0; $p < $cp; $p++) {
$checkpoint[$cpnames[$p]] = $unique[$i];
$i++;
}
for($p = 0; $p < $tp; $p++) {
$teleport[$tpnames[$p]] = $unique[$i];
$i++;
}
$rocks = 0; //Number of rocks in the maze.
// We need to make sure the map we construct is valid.
// so we throw this in a do-while the map is invalid.
do {
$p = -1;
//Begin loop to populate grid.
for( $y = 1; $y <= $cols; $y++) { //Number of Columns
for( $x = 0; $x < $rows; $x++) { //Number of Rows
$p++;
//Start and Finish squares.
if ($x == 0) {
//if ($x == 0 AND $y == 1) {
//if ($x == 0 AND rand(1,3) == 1) {
$grid[$y][$x] = "s";
} elseif ($x == $rows - 1) {
//} elseif ($x == $rows - 1 AND $y == intval(($cols + 1) * .5) ) {
//} elseif ($x == $rows - 1 AND rand(1,3) == 1) {
$grid[$y][$x] = "f";
//Randomly Placed Rocks
} elseif (rand(1, $rockchance) == 2) {
$grid[$y][$x] = "r";
$rocks++;
//TODO: rock count could be off if covered by checkpoint.
//Just a normal square.
} else {
$grid[$y][$x] = "o";
}
//Absolutely placed points; Checkpoints.
foreach ($checkpoint as $key => $v) {
if ($v == $p) {
$grid[$y][$x] = $key;
}
} //Teleports too
foreach ($teleport as $key => $v) {
if ($v == $p) {
$grid[$y][$x] = $key;
}
}
} //Rows
} //Cols
//Fill $grid[0] with header information
$grid[0][0] = $rows;
$grid[0][1] = $cols;
$grid[0][2] = count($checkpoint);
$grid[0][3] = $rocks;
$grid[0][4] = $numBlocks;
$grid[0][5] = count($teleport);
$grid[0][6] = $mapName;
//Validate map
$path = routePath($grid, true);
//Only repeat if it's blocked.
} while ($path['blocked'] == true);
return $grid;
}
//Generates map based on $shape.
function GenerateShapedMap($shape, $params) {
//Get width and height.
$cols = strlen($shape[0]);
$rows = count($shape);
//Scan for checkpoints.
//$checkpoints = 0;
//$cpnames = Array("a", "b", "c", "d", "e");
//Get the amount of checkpoints on this map.
//foreach ($cpnames as $cpt)
// if (findTiles($mygrid, $cpt))
// $checkpoints++;
//Confirm params.
if (isset($params['rockchance']))
$rockchance = $params['rockchance'];
else
$rockchance = 10;
if (isset($params['checkpoints']))
$checkpoints = $params['checkpoints'];
else
$checkpoints = 0;
if (isset($params['teleports']))
$teleports = $params['teleports'];
else
$teleports = 0;
if (isset($params['name']))
$mapName = $params['name'];
else
$mapName = '';
if (isset($params['walls']) && is_int($params['walls']))
$walls = $params['walls'];
else
$walls = 13;
$mapMatrix[0][0] = $cols;
$mapMatrix[0][1] = $rows;
$mapMatrix[0][2] = $checkpoints;
//set after;
$mapMatrix[0][3] = 0;
//walls
$mapMatrix[0][4] = $walls;
$mapMatrix[0][5] = $teleports;
$mapMatrix[0][6] = $mapName;
do {
$rockcount = 0;
$i = 0;
if (! is_array($shape))
break;
foreach ($shape as $row) {
$i++;
for( $j = 0; $j < $cols; $j++) { //Number of Columns
$item = substr($row, $j, 1);
if ($item == '?') {
if (rand(1, $rockchance) == 1) {
$item = 'r';
$rockcount++;
} else {
$item = 'o';
}
}
$mapMatrix[$i][$j] = $item;
//echo $item;
}
//echo "\n";
}
//$path = routePath($mapMatrix, true);
$path = routeMultiPath($mapMatrix, true);
//echo $path['blocked']."\n";
//Only repeat if it's blocked.
} while ($path['blocked'] == true);
//Set rockcount.
$mapMatrix[0][3] = $rockcount;
//print_r ($mapMatrix);
return $mapMatrix;
}
//Inserts a point into a shape-array.
function insertPoint($array, $new, $target = '?') {
//Replaces a random element in $array that matches $target with $new,
// if $new is a single character.
//If $new is a string, replace a random element for each of $new's characters.
/*
Snap - "the goal is to turn something like:
$mymap = Array("s??????f". "s???????f")
// into; Array("s???a??f", "s???b???f")
after a couple calls to the function."
*/
//Getting $array parameters
$rows = count($array);
$length = strlen($array[0]);
$size = $rows * $length;
//Retrieving all cells == $target from $array
//This is more memory intensive, and probably more CPU-so, but far more safe.
$targetCells = array();
for( $i = 0; $i < $size; $i++)
{
$y = $i % $length; //Get coordinates based on $index
$x = (int)($i / $length);
//echo "<br />index: $i y: $y, x: $x <br />";
//echo $array[$x][$y];
if($array[$x][$y] == $target)
$targetCells[] = $i;
}
//Now that we have a definite selection of cells, we can pick easily with
// the only caveat being if there aren't enough $target cells.
if(strlen($new) > $length)
{
//There are too many replace requests and not enough free cells.
echo "Too many $new characters. No replacements made.<br/>";
return $array;
}
//Debug to see what indexes were selected as == $target
/*
echo "array = ";
print_r($array);
echo "<br/>";
echo "targetCells = ";
print_r($targetCells);
echo "<br/>";
echo "<br/>";
*/
while(strlen($new) > 0)
{
$length = count($targetCells);
$indexReplace = rand(0, $length - 1); //Get a random position in $targetCells
$indexTarget = $targetCells[$indexReplace]; //Get the index stored in $targetCells
$y = $indexTarget % strlen($array[0]); //Get coordinates based on $index
$x = (int)($indexTarget / strlen($array[0]));
if($array[$x][$y] == $target) //Shouldn't be necessary, but just in case...
{
$array[$x][$y] = $new[0]; //We've found a valid target. Replace.
$new = substr($new, 1); //Go to the next $new character.
unset($targetCells[$indexReplace]); //Remove the selected $targetCell.
$targetCells = array_values($targetCells); //Reorder the array for no holes.
continue;
}
else
{
//Somehow an invalid target got into our list of valid targets...
echo "<br/>";
echo "Error in selecting $indexTarget ($x,$y). Replacement stopped on $new[0].<br/>";
echo "indexTarget = $indexTarget<br/>";
echo "indexReplace = $indexReplace<br/>";
echo "array = ";
print_r($array);
echo "<br/>";
echo "targetCells = ";
print_r($targetCells);
echo "<br/>";
echo "<br/>";
return $array;
}
}
return $array;
}
//Turns a mapMatrix into a code - see GenerateMapByCode
function GenerateMapCode($mapMatrix) {
//Iterate through $mapMatrix and generate the code used to save and
// load the map through the database.
$code = ""; //The string to return to the database.
$index = 0; //The current number of tiles from the last tile saved.
// $mapMatrix[0] stores header data--dimensions, #checkpoints, #rocks, #walls
// $mapMatrix[1] count will always be the width.
$mapsize = $mapMatrix[0][0].'x'.$mapMatrix[0][1]; //Width x Height
$code = $mapsize;
$code .= '.c'.$mapMatrix[0][2];
$code .= '.r'.$mapMatrix[0][3];
$code .= '.w'.$mapMatrix[0][4];
$code .= '.t'.$mapMatrix[0][5];
$code .= '.'.$mapMatrix[0][6];
// dimensions + # checkpoints + # rocks + # placeable walls
//echo $code."<br />";
$code .= ".:";
for( $i = 1; $i < count($mapMatrix); $i++)
{
for( $j = 0; $j < count($mapMatrix[$i]); $j++)
{
if($mapMatrix[$i][$j] != 'o')
{
//As long as the tile is NOT open, embed it in the code.
$code .= $index.$mapMatrix[$i][$j].'.';
//Start from 0 again.
$index = -1;
}
$index += 1;
}
}
//== Don't need to fill in the last spot.
//if ($index > 1) {
// $code .= $index.'o.';
//}
return $code;
}
//Turns a mapcode into a mapMatrix, - see GenerateMapCode
function GenerateMapByCode($code) {
//Create $mapMatrix by iterating through $code (a string value).
//==$mapMatrix = array();
$tmp = explode( ":", $code);
$headers = explode( '.', $tmp[0]);
$splitCode = explode( '.', $tmp[1]);
//Extract header information.
//==$mapMatrix[0] = array();
$dimensions = explode( 'x', $headers[0]);
$mapMatrix[0][0] = $dimensions[0]; //Width
$mapMatrix[0][1] = $dimensions[1]; //Height
//Select the next parameters by ignoring the character label.
$mapMatrix[0][2] = (int)substr($headers[1], 1); //Number of Checkpoints
$mapMatrix[0][3] = (int)substr($headers[2], 1); //Number of Rocks
$mapMatrix[0][4] = (int)substr($headers[3], 1); //Number of Wall Blocks
$mapMatrix[0][5] = (int)substr($headers[4], 1); //Number of Teleports
$mapMatrix[0][6] = $headers[5]; //Map Name
//Printing out parameters for debug purposes...
/*
echo "<br />Map Parameters:<br />";
echo "mapMatrix[0][0]: ".$mapMatrix[0][0]."<br />";
echo "mapMatrix[0][1]: ".$mapMatrix[0][1]."<br />";
echo "mapMatrix[0][2]: ".$mapMatrix[0][2]."<br />";
echo "mapMatrix[0][3]: ".$mapMatrix[0][3]."<br />";
echo "mapMatrix[0][4]: ".$mapMatrix[0][4]."<br />";
echo "mapMatrix[0][5]: ".$mapMatrix[0][5]."<br />";
*/
//Begin creating our mapMatrix
$t = -1;
$index = 0;
for( $i = 1; $i <= $mapMatrix[0][1]; $i++) { //Number of Rows
for( $j = 0; $j < $mapMatrix[0][0]; $j++) { //Number of Columns
$t++;
$next = substr($splitCode[$index], 0, strlen($splitCode[$index]) - 1);
//Are we at the next target, if there is one.
if ($next == $t AND $next != '') {
//Update tile.
$type = substr($splitCode[$index], -1, 1);
$mapMatrix[$i][$j] = $type;
$index++;
//Start from 0 again.
$t = -1;
} else {
$mapMatrix[$i][$j] = 'o'; //Empty Tile
}
}
}
return $mapMatrix;
}
//Returns a mapMatrix merged with a solution/maze.
function MergeMapSolution($mapMatrix, $solution) {
//echo $solution;
$sa = explode( '.', $solution);
foreach($sa as $v) {
if ($v == '') continue;
$v= explode(",", $v);
$i = $v[0];
$j = $v[1];
//Trying to place a wall - where?
if ($mapMatrix[$i][$j] <> 'o') return -1;
$mapMatrix[$i][$j] = 'w';
//Are we out of blocks?
//if ($mapMatrix[0][2] < 1) return -2;
$mapMatrix[0][4]--;
}
return $mapMatrix;
}
function seperateMapSolution($mapMatrix) {
for( $i = 1; $i <= $mapMatrix[0][1]; $i++) //Number of Rows
for( $j = 0; $j < $mapMatrix[0][0]; $j++) //Number of Columns
if ($mapMatrix[$i][$j] == 'w')
$solution .= "$i,$j.";
$solution = ".".$solution;
return $solution;
}
//This is required to identify identical solutions, or even 'close' ones.
function formSolution($solution) {
$tmp = explode(".", $solution);
$tmp = array_filter($tmp);
sort($tmp);
$tmp = '.'.implode(".", $tmp).'.';
return $tmp;
}
//Returns the best solution.
function getSolution($userID, $mapID) {
include_once('sqlEmbedded.php');
$sql = "SELECT `solution`, `moves`
FROM `solutions`
WHERE `userID` = '$userID' AND
`mapID` = '$mapID'
";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
return mysql_fetch_assoc($result);
}
}
function getChallengeSolution($userID, $challengeID) {
include_once('sqlEmbedded.php');
$sql = "SELECT `solution`, `moves`
FROM `challengeSolutions`
WHERE `userID` = '$userID' AND
`challengeID` = '$challengeID'
";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
return mysql_fetch_assoc($result);
}
}
function getMapCode($mapID) {
include_once('sqlEmbedded.php');
$sql = "SELECT `code`
FROM `maps`
WHERE `ID` = '$mapID'
";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
list($map) = mysql_fetch_row($result);
return $map;
}
}
function pastMap($maptype, $daysago) {
$sql = "
SELECT `mapID`
FROM `mapOfTheDay`
WHERE DATE_ADD(CURDATE(), INTERVAL -$daysago DAY) =
DATE_FORMAT(mapDate,'%Y-%m-%d') AND
`mapType` = '$maptype'
";
//echo "<br />$sql<br />";
$result = mysql_query($sql) or die(mysql_error());
//No map for today?
if (mysql_num_rows($result) == 0)
return -1;
$r = mysql_result($result, 0, 'mapID');
//echo "result: $r";
return $r;
}
//Returns tiles as a string seperated like: x,y.x,y.
function findTiles ($mapMatrix, $search) {
$r = false;
for( $i = 1; $i <= $mapMatrix[0][1]; $i++) { //Number of Rows
for( $j = 0; $j < $mapMatrix[0][0]; $j++) { //Number of Columns
if ($mapMatrix[$i][$j] == $search)
$r.= "$j,$i.";
}
}
return $r;
}
// Returns: ARRAY( blocked, path, start, end )
function findPath($mapMatrix, $start = '0,1', $target = 'f', $isBlockedByX = false) {
//Remove last period if existing.
if (substr($start, -1) == '.')
$start = substr ($start, 0, -1);
//Create our starting locations
$seed = explode(".", $start);
foreach ($seed as &$v) {
$v = explode(",", $v);
$v[2] = $v[0].','.$v[1];
$v[3] = '';
//Remove Seeds as potential seeding slots.
$x = $v[0];
$y = $v[1];
unset($mapMatrix[$y][$x]);
}
//When traversing forwards (the normal start square, 's'), we are blocked by 'x', so can pass through 'X'
//Similarly, when tranversing backwards ('S'), we are blocked by 'X', so can pass through 'x'
if($isBlockedByX) {
$passableWallChar = 'x';
} else {
$passableWallChar = 'X';
}
$index = count($seed);
do {
foreach ($seed as $key => &$v) {
//Search the squares around, to spread the seeds
for($i = 1; $i <= 4; $i++) {
$x = $v[0];
$y = $v[1];
//Create a handle on the squares around it.
switch($i){
case 1: $y--; break; //up
case 2: $x++; break; //right
case 3: $y++; break; //down
case 4: $x--; break; //left
}
//Ensure we don't enter into our mapdata area
if ($y < 1 OR $x < 0) continue 1;
//Is this tile even on the map?
if (!isset($mapMatrix[$y][$x])) {
continue 1;
}
$path = '';
//What's there?
switch($mapMatrix[$y][$x]) {
case $target: //Finishline!
//Our search is over.
$r['blocked'] = false;
$r['path'] = $seed[$key][3].$i;
$r['start'] = $v[2];
$r['end'] = "$x,$y";
return $r;
break;
// Teleports m t g i k
case "m": case "t": case "g": case "i": case "k":
$path = $mapMatrix[$y][$x];
case "o": //Available squares
// TODO:
case "p":
case "s": case "f": //Start and end tiles
case "S": //New start type
case $passableWallChar: //The walls we can walk through
case "a": case "b": case "c": case "d": case "e": //Checkpoints too
case "u": case "n": case "h": case "j": case "l": //Teleport-out towers included!
//Plant Seed here
$seed[$index][0] = $x;
$seed[$index][1] = $y;
//Save our starting position.
$seed[$index][2] = $v[2];
//Save 'PATH'
$path = $i.$path;
$seed[$index][3] = $v[3].$path;
//Don't plant a seed here again.
unset($mapMatrix[$y][$x]);
//Move index
$index++;
break;
}
}
//Running out of seeds?
if (count($seed) < 2) {
$r['blocked'] = true;
$r['path'] = $seed[$key][3].$i;
$r['start'] = $v[2];
$r['end'] = "$x,$y";
return $r;
}
//Lets not try this again.
unset($seed[$key]);
}
} while ( 1);
echo "Ran outa seeds.<br />";
print_r($seed);
return $mapMatrix;
}
/* UNUSED FUNCTION
function GetTile($mapMatrix, $id)
{
//Returns the location in $mapMatrix indicated by $id
$toReturn = &$mapMatrix [ (int)($id / $mapMatrix[0][0]) ]
[ $id % $mapMatrix[0][0] ];
return $toReturn;
}
*/
function routeMultiPath($map, $validate = false) {
//Check both starting point groups for paths
$r['totalMoves'] = 0;
$r['blocked'] = false;
$containsNormalStart = (findTiles($map, "s") !== false);
$containsReverseStart = (findTiles($map, "S") !== false);
if($containsNormalStart) {
$r['path'][0] = routePath($map, $validate);
$r['totalMoves'] += $r['path'][0]['moves'];
$r['blocked'] = $r['path'][0]['blocked'];
}
if ($r['blocked'])
return $r;
if($containsReverseStart) {
//No need to run the "validation" twice;
$r['path'][1] = routePath($map, false, true);
$r['totalMoves'] += $r['path'][1]['moves'];
$r['blocked'] = $r['path'][1]['blocked'] || $r['blocked'];
}
return $r;
}
//Routes a path through all checkpoints and teleports, returning an array.
// [path] path-string. [blocked] boolean, [moves] int.
function routePath($mygrid, $validate = false, $traverseBackwards = false) {
//Our response
$r = array('start' => NULL, 'path' => NULL, 'blocked' => true);
//Scan the map for these tiles.
// Doing this scan once is far more effecient than rescanning.
$tileLocations = findTilesM($mygrid, str_split('S'));
if (in_array("S", $tileLocations)) {
}
// Tmp bad code..
if ($traverseBackwards) {
$start = findTiles($mygrid, "S");
} else {
$start = findTiles($mygrid, "s");
}
//Checkpoint names
$cpnames = array("a", "b", "c", "d", "e");
if ($traverseBackwards)
$cpnames = array("e", "d", "c", "b", "a");
//TODO: Improve the 'findTiles' function to prevent duplicate itterations.
//Add the existing checkpoints to target array.
foreach ($cpnames as $cpt)
if (findTiles($mygrid, $cpt))
$target[] = $cpt;
//Our last target is the finish line.
$target[] = 'f';
//Assume that we're not blocked, and raise a red flag later.
$blocked = false;
//All possible teleports in play.
$tpnames = array('t', 'm', 'g', 'i', 'k');
//Where there's an in, there's an out.
$teleout['t'] = 'u';
$teleout['m'] = 'n';
$teleout['g'] = 'h';
$teleout['i'] = 'j';
$teleout['k'] = 'l';
$teleport = array();
//Find all the existing teleports.
foreach ($tpnames as $tpt)
if (findTiles($mygrid, $tpt))
$teleport[] = $tpt;
//If validate, add teleport in/out's.
if ($validate) {
$target = array_merge($target, $teleport);
foreach ($teleport as $tin)
$target[] = $teleout[$tin];
}
//Prepare vars for iteration;
$tpath = '';
$movesoffset = 0;
//Loop through all the targets.
foreach($target as $t) {
//FindPath from where we are, to the target.
$p = Findpath($mygrid, $start, $t, $traverseBackwards);
//Mark where we ended up starting from.
if ($r['start'] == '')
$r['start'] = $p['start'];
$r['end'] = $p['end'];
//Could be blocked right already.
$blocked = $p['blocked'];
do {
//Exit if path is blocked.
if ($blocked) {
$r['blocked'] = true;
$r['lastTarget'] = $t;
$r['path'] = $tpath;
return $r;
}
//Make sure there is a teleport to search.
if (! is_array($teleport))
break 1;
//Search through the path to find first teleport hit, if any.
$pathary = str_split($p['path']);
//As per usual, it's best to assume that you've failed.
$foundtele = false;
//Search through pathary and compare all existing teleports.
foreach ($pathary as $position => $char) {
foreach ($teleport as $ktel => $port) {
//$r['z'] .= ';'.$f++;
if ($port == $char) {
//Disable teleport
unset($teleport[$ktel]);
//We found it
$foundtele = true;
break 2;
}
}
}
if ($foundtele == false)
break 1;
$outchar = $teleout[$port];
if ($position === false) continue;
//Find the teleport outs
$teleouts = findTiles($mygrid, $outchar);
//New path starting from an out-location.
$z = Findpath($mygrid, $teleouts, $t, $traverseBackwards);
if ($z['blocked']) $blocked = true; //Optional?
$out = $z['start'];
//Deactivate teleport
$teleactive[$port] = false;
//$r['debug'] = "TPD: $port";
//Apply modified path, and warp-cordinates.
//123 _Tele_ 222
//123
$p['path'] = substr($p['path'], 0, $position + 1);
//123
//123 U CORDS U
$p['path'] .= $outchar.$out.$outchar;
//123 U CORDS U
//123 U CORDS U 2322
$p['path'] .= $z['path'];
//Our end point may have been modified.
$p['end'] = $z['end'];
$movesoffset -= countmoves($out);
//}
} while ($foundtele);
//$start = explode(",", $p['end']);
$start = $p['end'];
if ($p['blocked']) $blocked = true;
$tpath .= $t.$p['path'].'r';
}
$r['blocked'] = $blocked;
$r['path'] = $tpath;
$moves = countmoves($tpath);
$moves += $movesoffset;
$r['moves'] = $moves;
return $r;
}
//For use with routepath;
function cmp($a, $b) {
if ($a === false) $a = 10000;
if ($b === false) $b = 10000;
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
//For use with routepath;
function countmoves($path) {
$moves = substr_count($path, '1');
$moves += substr_count($path, '2');
$moves += substr_count($path, '3');
$moves += substr_count($path, '4');
return $moves;
}
//Returns a random selection of one of the arguements.
function weight() {
$weights = func_get_args();
return $weights[rand(0, (count($weights) -1))];
}
function findTilesM ($mapMatrix, $search) {
$r = array();
for( $i = 1; $i <= $mapMatrix[0][1]; $i++) { //Number of Rows
for( $j = 0; $j < $mapMatrix[0][0]; $j++) { //Number of Columns
foreach($search as $item)
if ($mapMatrix[$i][$j] == $item)
$r[$item][] = "$j,$i";
}
}
return $r;
}
?>
|