-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcrossword.cgi
2613 lines (2289 loc) · 100 KB
/
crossword.cgi
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
#!/usr/bin/perl
#future ideas ver 3.0 meta recurse using blocks. blocks will consist of a starting word and dir and all it's crossing words
#allow sentences in words (strip out spaces)
# speed up word load use 1 line of coma, separated words??
#separate experimental options on front page
#shadow (> 1) does not work if letter only belongs to a horiz or vert word
#also fails on british
#cookies store keys / no chat
use strict;
use CGI;
use List::Util qw(shuffle);
use Time::HiRes;
use Fcntl qw(:flock SEEK_END);
use lib '.'; #nuts, PERL has changed. add local path to @INC
use vpvars;
#get setup variables the proper way
my $archivepath = $vpvars::archivepath;
my $archiveurl = $vpvars::archiveurl;
my $scripturl = $vpvars::scripturl;
print "Content-type: text/html\n\n";
if ( -e "processing.txt") { print"Already running."; die("$0 is already running. Exiting.\n"); };
open(my $processing, ">processing.txt") or die "Can't open : $!";
lock($processing);
&PrintResults( "Wait for it!" ) ;
$|=1; #keep it alive as long as possible
#globals
my %in; #input arguments $in{argname}
my @wordsOfLengthString = ();
#set $wordsOfLengthString[$wordLength] = "$wordsOfLengthString[$wordLength]$word,"; #build a comma delimited string of each possible word length
#my $tempMask = $mask; #of form $unoccupiedAT$unoccupied oATo
#$tempMask =~ s/$unoccupied/\./g; #make a mask of 'GO$unoccupiedT' into 'GO.T' for the regexp
#my $wordLength = length($tempMask);
#@word_list = ($wordsOfLengthString[$wordLength] =~ /($tempMask),/g);
#must update both below at same time!
my @puzzle=();
#the puzzle with the letters inserted. array[][] of hash $puzzle[][]->{Letter}
#input file of the form where o are blank and x is black. Letters are capatalized
#ooooxoooooxoooooxCATS
#ooooxoooooxoooooxoooo
#ooooxoooooxooooooooo
my @allMasksOnBoard;
#all words on board whether still a mask or complete $allMasksOnBoard[word number][dir 0=across 1=down] many will be undef
#start at 1 as that is the first word number
my @letterPositionsOfWord;
#$letterPositionsOfWord[word #][dir] an array of all the word letter positions [[x,y],[x,y]....]
#set $letterPositionsOfWord[$numberCount][$dir] = [@TempLetterPositions]; #an annonomyous array reference of $x,$y pairs of all letters in the word
#get my @WordLetterPositions = @{$letterPositionsOfWord[$wordNumber][$dir]}
#used to find crossing words fast with @ThisSquareBelongsToWordNumber
my @ThisSquareBelongsToWordNumber;
# $ThisSquareBelongsToWordNumber[x][y][0] returns the word number this square belongs to
#set $ThisSquareBelongsToWordNumber[$xx][$yy][$dir] = $numberCount
#get my $crossingwordNumber = $ThisSquareBelongsToWordNumber[$x][$y][$crossingWordDir]
my @nextWordOnBoard;
#all words position on board used for cycling through word placements, etc
# [{wordNumber => $wordNumber, dir => $dir},{},{}...]
#$nextWordOnBoard[]{wordNumber} $nextWordOnBoard[]{dir}
my @PositionInWord;
#$PositionInWord[x][y][dir] returns the pos of letter in the word this square belongs to starting at 0
#set $PositionInWord[$xx][$yy][$dir] = $PositionCount
#get my $NthLetterPosition = $PositionInWord[$x][$y][$crossingWordDir]
my %wordsThatAreInserted = ();
#hash of hashes. $wordsThatAreInserted{word} = 1 or undef
#used to prevent duplicate words on the board
my %wordLengths; #used to identify word lengths possible on the grid. $wordLength{6} = 1. we will only load words of lengths that exist!
my %WordListByMask = (); #no longer used but keep for testing. Not much faster than regex routies
# keys $wordListByMask{oYo} returns a list of all words fitting the mask
#created by taking each word, then creating a binary mask for the word and
#$wordListByMask{ooRo}{WORD}=1
#$wordListByMask{WoRo}{WORD}=1 etc
#huge database but very fast search for words fitting a mask or pattern
#------------------------------------
#letter search variables
my @nextLetterPositionsOnBoard;
#all letter position on board used for cycling through letter placements, etc
# [{x => $x, y => $y} , , ]
#$nextLetterPositionsOnBoard[]{x} $NextWordPositionsOnBoard[]{y}
my %linearWordSearch = (); #no longer used
#very fast for finding the next possible letters in a word
#$linearWordSearch{mask}{key1 , key2} and it will return a list of keys (so there are no duplicates) representing the next possible letters.
#@letters = keys %{$linearWordSearch{$mask}};
#mask must be a prefix mask ie: TOOLooooo
#---------------------------------------------
my $padChar = 'x';
my $unoccupied = 'o';
my $padsEitherSide = 'padsEitherSide';
#$dir 0 = horiz 1 = vertical
my $dir;
my %clues;
my $hints_across;
my $hints_down;
my $biggestwordNumber;
my @OppositeDirection;$OppositeDirection[0] = 1;$OppositeDirection[1] = 0; #instead of using (not)
my $timeForCrossword;
my $recursiveCount = 1;
my $timelimit = 60 * 1 ; #only allow the script to run this long
my $debug = 0; # 1 to show debug info. could be used for attacks. leave set to 0
eval { &Main; }; # Trap any fatal errors so the program hopefully
if ($@) { &PrintProcessing("fatal error: $@"); &cgierr("fatal error: $@"); } # never produces that nasty 500 server error page.
exit; # There are only two exit calls in the script, here and in in &cgierr.
my $game;
my $uid;
my $message;
#optimal search variables
my %wordNumberDirUsed; #$wordNumberDirUsed{$wordNumber}{$dir} so we only backtrack or note words that have been filled
my $naiveBacktrack; #a counter
my $optimalBacktrack; #a counter
my %touchingWordsForBackTrack; #global as we need to backtrack to the first member of it we encounter. if not == () we are in a backtrack state!
my %targetWordsForBackTrack; #global as we need to backtrack to the first member of it we encounter. if $targetWordsForBackTrack{# source}{dir source} == undef there are NO targets!
#eg $targetWordsForBackTrack{$wordNumberSource}{$dirSource}{$crossingWordNumber}{$crossingWordDir}
#rule 1. All letters in the horizontal and vertical words (up to the failed letter) can affect the failure of laying a letter
#rule 2. All crossing words of both the horizontal and vertical words of the failed letter can affect the failure of laying a letter
#rule 3 Remove shadows by only keeping the intersection of rule 1 and 2
#rule 3 is ignored (> 1) and is nor (> 0) as it fails (over prunes) on British style crosswords
# eg: $targetLettersForBackTrack{x failed letter}{y failed letter}{x}{y} > 0 #pregenerated for speed!
my %targetLettersForBackTrack; #global as we need to backtrack to the first member of it we encounter. if $targetLettersForBackTrack{x failed letter}{y failed letter} == undef there are NO targets!
my $oldTime;
my $grids;
sub Main {
$game = time; #this will determine the folder
$uid = $in{uid}; #facebook user ID number
if ($uid eq '') {$uid='common'} #for non facebook games
srand;
$in{TimeLimit} = 1;
$in{layouts} = 'grids';
$in{grid} = 'BigOne';
$in{grid} = '6x6';
$in{grid} = "13x13_22_112";
#$in{grid} = '5x5';
$in{grid} = "13x13_56_144";
$in{optimalbacktrack} = 1;
$in{shuffle} = 1;
$in{wordfile} = "Sympathy_31121";
$in{wordfile} = "Clues_248505";
$in{walkpath} = 'crossingwords';
#$in{walkpath} = 'GenerateNextLetterPositionsOnBoardFlat';
#$in{walkpath} = 'GenerateNextLetterPositionsOnBoardDiag';
#$in{walkpath} = 'GenerateNextLetterPositionsOnBoardDiag';
#$in{walkpath} = 'GenerateNextLetterPositionsOnBoardZigZag';
%in = &parse_form; #get input arguments. comment out for commandline running
&Process_arguments();
$timeForCrossword = time();
$message = $message . "Loading or creating grid...\n";
&PrintProcessing($message);
if ($debug ) {print "\n\nLoading or creating grid...\n\n";}
if ($in{layouts} eq 'grids')
{
&LoadGrid( $in{grid} );
}
if ($in{layouts} eq 'doublespaced')
{
if ($debug) {print "full $in{doublespacedfull} evenodd $in{evenodd}\n\n"}
if ($in{doublespacedfull})
{
&GenerateGridDoubleSpaced($in{doublespacedwidth},$in{evenodd});
}
else
{
&GenerateGridDoubleSpaced2($in{doublespacedwidth},$in{evenodd});
}
}
$message = $message . "Numbering grid...\n";
&PrintProcessing($message);
if ($debug ) {print time()-$timeForCrossword . " sec Numbering grid...\n\n";}
&NumberBlankSquares();
$message = $message . "Loading word list...\n";
&PrintProcessing($message);
if ($debug ) {print time()-$timeForCrossword . " sec Loading word list...\n\n";}
&LoadWordList( $in{wordfile} );
if ($debug ) {print time()-$timeForCrossword . " sec Calculating word walk path...\n\n";}
if ($in{walkpath} eq 'crossingwords')
{
&GenerateNextWordPositionsOnBoardCrossing(); #good all purpose start anywhere!
$in{mode} = 'word';
}
if ($in{walkpath} eq 'zigzag')
{
&GenerateNextWordPositionsOnBoardZigZag();
$in{mode} = 'word';
}
if ($in{walkpath} eq 'numerical')
{
&GenerateNextWordPositionsOnBoardNumerical();
$in{mode} = 'word';
}
if ($in{walkpath} eq 'random')
{
&GenerateNextWordPositionsOnBoardRandom();
$in{mode} = 'word';
}
if ($in{walkpath} eq 'acrossthendown')
{
&GenerateNextWordPositionsOnBoardAcrossThenDown();
$in{mode} = 'word';
}
if ($in{walkpath} eq 'diagonal')
{
&GenerateNextWordPositionsOnBoardDiag();
$in{mode} = 'word';
}
if ($in{'walkpath'} eq 'GenerateNextLetterPositionsOnBoardFlat')
{
&GenerateNextLetterPositionsOnBoardFlat();
$in{'mode'} = 'letter';
my $rr = 9;
}
if ($in{walkpath} eq 'GenerateNextLetterPositionsOnBoardZigZag')
{
&GenerateNextLetterPositionsOnBoardZigZag();
$in{mode} = 'letter';
}
if ($in{walkpath} eq 'GenerateNextLetterPositionsOnBoardDiag')
{
&GenerateNextLetterPositionsOnBoardDiag();
$in{mode} = 'letter';
}
if ($in{walkpath} eq 'GenerateNextLetterPositionsOnBoardSwitchWalk')
{
&GenerateNextLetterPositionsOnBoardSwitchWalk();
$in{mode} = 'letter';
}
if ($in{walkpath} eq 'GenerateNextLetterPositionsOnBoardSnakeWalk')
{
&GenerateNextLetterPositionsOnBoardSnakeWalk();
$in{mode} = 'letter';
}
$timeForCrossword = time(); #reset counter so we mesure time to find solution only
if ($in{optimalbacktrack}) {
$message = $message . "Calculating Optimal Backtracks...\n";
&PrintProcessing($message);
if ($debug ) {print time()-$timeForCrossword . " sec Numbering grid...\n\n";}
&CalculateOptimalBacktracks();
}
if ( $in{mode} eq 'word' ) {
if ( &RecursiveWords() == 0 ) {
$message = "\n\nFailed to fill grid Counts:$recursiveCount \n\n";
print $message;
PrintResults($message);
&Quit();
}
}
else {
if ( &RecursiveLetters() == 0 )
{
my $cnt = scalar keys %wordsThatAreInserted;
$message = "\n\nFailed to fill grid Counts:$recursiveCount Words layed:$cnt \n\n";
print $message;
PrintResults($message);
&Quit();
}
}
&PrintProcessing();
if ($debug ) {print time()-$timeForCrossword . " sec Done.\n\nNumbering clue list.\n\n";}
&PrintProcessing("Getting clues...");
$timeForCrossword = time(); #reset counter so we mesure time to find solution only
&Number_clue_list();
if ($debug ) {print time()-$timeForCrossword . " sec Print solved puzzle.\n\n";}
my $solved_puzzle = "";
$solved_puzzle = &print_solved_puzzle;
if ($debug ) {print time()-$timeForCrossword . " sec Print puzzle\n\n";}
my $puzzle_string = &print_puzzle;
open (DATA, "<./templates/index.html") or die("Template file /templates/index.html does not exist");
my @DATA = <DATA>;
close (DATA);
my $template_file = join('' , @DATA);
my $startx;
my $starty;
#find word 1 across or down and replace x , y in template js . fixes error when there is no letter at 0,0
for ($dir = 0; $dir < 2 ;$dir++)
{
#$letterPositionsOfWord[word #][dir] an array of all the word letter positions [[x,y],[x,y]....]
if ($letterPositionsOfWord[1][$dir] != undef)
{
$startx = ${$letterPositionsOfWord[1][$dir]}[0][0];
$starty = ${$letterPositionsOfWord[1][$dir]}[0][1];
last;
}
}
$template_file =~ s/%startx%/$startx/g;
$template_file =~ s/%starty%/$starty/g;
$template_file =~ s/<%answers%>/$solved_puzzle/g;
$template_file =~ s/<%across%>/$hints_across/g;
$template_file =~ s/<%down%>/$hints_down/g;
$template_file =~ s/<%down%>/$hints_down/g;
$template_file =~ s/<%puzzle%>/$puzzle_string/g;
$template_file =~ s/\%archivepath\%/$archivepath/g;
$template_file =~ s/\%archiveurl\%/$archiveurl/g;
$template_file =~ s/\%scripturl\%/$scripturl/g;
$template_file =~ s/\%uid\%/$uid/g;
my $name = $in{name}; #facebook user name
$name =~ s/\%20/ /g; #get rid of %20 for spaces
$template_file =~ s/\%name\%/$name/g;
#archive the puzzle!
#my $game = time;
#$filename .= ".html";
#print '<\pre>';
$template_file =~ s/\%game\%/$game/g;
#print $template_file;
#write archive game file and directory
if (not -d ("$archivepath")) {mkdir("$archivepath") or die("Could not create archive path $archivepath");}
if (not -d ("$archivepath/$uid")) {mkdir("$archivepath/$uid") or die("Could not create archive path $archivepath/$uid");}
if (not -d ("$archivepath/$uid/$game")) {mkdir("$archivepath/$uid/$game") or die("Could not create archive path $archivepath/$uid/$game");}
open (DATA, ">$archivepath/$uid/$game/index.html") or die("Could not create archive file $archivepath/$uid/$game/index.html");
print DATA $template_file;
close (DATA);
#create empty chat.txt file - cuts down on 404 errors
open (DATA, ">$archivepath/$uid/$game/chat.txt") or die("Could not create chat file $archivepath/$game/chat.txt");
close (DATA);
#create empty out.txt file - cuts down on 404 errors
open (DATA, ">$archivepath/$uid/$game/out.txt") or die("Could not create chat file $archivepath/$uid/$game/out.txt");
close (DATA);
#print a jump to game page output
#print qq|<META HTTP-EQUIV="Refresh" CONTENT="0; URL=$archiveurl/$uid/$game/?uid=$uid&name=$name">|; #name is for chat
#print qq|<META HTTP-EQUIV="Refresh" CONTENT="0; URL=$archiveurl/$uid/$game/">|;
&PrintResults( qq| Your crossword is at:<br><a href="$archivepath/$uid/$game/index.html">$archivepath/$uid/$game/index.html</a><br> | );
&Quit( qq| Done. Look at "Crossword Result after you click OK." | );
exit;
}
sub Quit()
{
print $_[0]; #feedback to web browser
close($processing);
unlink('processing.txt');
exit;
}
sub PrintResults()
{
my $message = $_[0];
open(my $results, ">results.txt") or die "Can't open : $!";
print $results $message;
close $results;
};
sub PrintProcessing {
my $message = $_[0];
my ($x , $y);
my $line;
my $string;
my $time;
$time = time - $timeForCrossword;
#open(my $processing, ">processing.txt") or die "Can't open : $!";
#limit script run time!
if ($time > $timelimit)
{
&PrintResults( qq| Time limit exceeded | );
&Quit( "Time limit exceeded<br>\n\n" );
}
$string = $string . "\n";
$string = $string . "Loops per Sec: " . $recursiveCount / (time + 1 - $timeForCrossword); #print time to create crosword
$string = $string . "\n";
for ($y = 0 ; $y < $in{height} ; $y++)
{
for ($x = 0 ; $x < $in{width} ; $x++)
{
my $t = &GetXY($x,$y);
$line = "$line$t";
}
$string = $string . $line;
$string = $string . "\n";
$line = '';
}
for (my $wordNumber = 1 ; $wordNumber < 300 ; $wordNumber++)
{
for (my $dir = 0 ; $dir < 2 ; $dir++)
{
my $word = $allMasksOnBoard[$wordNumber][$dir];
#if (undef ne $word)
if ($word)
{
#$string = $string . "$wordNumber $dir: $word \n"
}
}
}
$string = $string . "\n";
$string = $string . "Time: " . $time; #print time to create crosword
$string = $string . "\n";
$string = $string . "Loops: " . $recursiveCount; #print time to create crosword
$string = $string . "\n";
$string = $string . "Sec per Loop: " . (time - $timeForCrossword) / $recursiveCount; #print time to create crosword
$string = $string . "\n";
$string = $string . "Loops per Sec: " . $recursiveCount / (time + 1 - $timeForCrossword); #print time to create crosword
$string = $string . "\n\n";
$string = $string . "optimalBacktrack:$optimalBacktrack naiveBacktrack:$naiveBacktrack recursive calls:$recursiveCount\n";
if ($message ne "") {
if ($string =~ /^!/)
{$string = "$message\n\n$string";}
else
{$string = "$message";}
}
seek($processing, 0 , 0); #need to keep file open to lock it!
print $processing "$string";
};
sub Process_arguments {
#process input arguments
# Test inputs to see if they are valid and set defaults
#defaults
if ( (not $in{timeout}) or ($in{timeout} !~ /^\d+$/ ) ) { $in{timeout} = 5; };
if (not $in{wordfile}){$in{wordfile} = "./wordlists/MyClues_248505/"};
#set bounds
if ($in{timeout} > 30) { $in{timeout} = 30; }
$in{grid} =~ s/[^\d\w]//g;
$in{wordfile} =~ s/[^\d\w]//g;
if ( $in{TimeLimit} > 10 ) {$in{TimeLimit} = 10}
$timelimit = $in{TimeLimit} * 60;
if ( $in{SlowDown} > 5 ) {$in{SlowDown} = 5}
};
sub GenerateNextWordPositionsOnBoardCrossing
{
#start with 1 horiz.
#find all crossing words
#find all their crossing words.
#only add # and direction once!
#FIFO
my @wordLetterPositions = ();
my %alreadyInList = (); # $alreadyInList{number}{direction} = 1 if already in list
my $wordNumber = 1;
my $dir = 0;
if (not defined $allMasksOnBoard[$wordNumber][$dir] ) # oops no horizontal #1 word. go vertical
{$dir = 1;}
my @toDoList = (); #list of words and directions to process. ((1,0) , (2,0) , .... ) shift off and push on so we do in an orderly fasion!
push @toDoList , [$wordNumber,$dir];
$alreadyInList{$wordNumber}{$dir} = 1;
push @nextWordOnBoard , {wordNumber => $wordNumber, dir => $dir};
while ( scalar @toDoList > 0 )
{
($wordNumber , $dir) = @{ shift @toDoList };
my @crossingWords = &GetCrossingWords( $wordNumber , $dir );
while ( scalar @crossingWords > 0 )
{
($wordNumber , $dir) = @{ shift @crossingWords };
if ( $alreadyInList{$wordNumber}{$dir} == 1)
{
next;
}
push @toDoList , [$wordNumber , $dir];
push @nextWordOnBoard , {wordNumber => $wordNumber, dir => $dir};
$alreadyInList{$wordNumber}{$dir} = 1;
}
}
foreach my $item (@nextWordOnBoard)
{
if ($debug ) {print "($item->{wordNumber},$item->{dir})";}
}
}
sub GenerateNextWordPositionsOnBoardNumerical
{
#create a sequential list in which we will lay down words. FIFO
#just go numerically 1 .. ??? alternating horiz / vert
for (my $wordNumber = 1 ; $wordNumber < 300 ; $wordNumber++) #loop through all word numbers even if they don't exist
{
for (my $dir = 0 ; $dir < 2 ; $dir++) #loop through each direction even if it doesnt exist
{
my $word = $allMasksOnBoard[$wordNumber][$dir]; # get WORD or MASK at this crossword position
if ($word eq undef) {next;} # if this [$wordNumber][$dir] does not exists in xword grid, find next one that does
push @nextWordOnBoard , {wordNumber => $wordNumber, dir => $dir};
if ($debug ) {print "($wordNumber,$dir)";}
}
}
}
sub GenerateNextWordPositionsOnBoardRandom
{
#create a sequential list in which we will lay down words. FIFO
#just go numerically 1 .. ??? alternating horiz / vert
for (my $wordNumber = 1 ; $wordNumber < 300 ; $wordNumber++) #loop through all word numbers even if they don't exist
{
for (my $dir = 0 ; $dir < 2 ; $dir++) #loop through each direction even if it doesnt exist
{
my $word = $allMasksOnBoard[$wordNumber][$dir]; # get WORD or MASK at this crossword position
if ($word eq undef) {next;} # if this [$wordNumber][$dir] does not exists in xword grid, find next one that does
push @nextWordOnBoard , {wordNumber => $wordNumber, dir => $dir};
}
}
@nextWordOnBoard = shuffle @nextWordOnBoard ;
my $nextWordOnBoard ;
foreach $nextWordOnBoard (@nextWordOnBoard) #loop through all word numbers
{
if ($debug ) {print "(${$nextWordOnBoard}{'wordNumber'} , ${$nextWordOnBoard}{'dir'} )";}
}
}
sub GenerateNextWordPositionsOnBoardAcrossThenDown
{
#create a sequential list in which we will lay down words. FIFO
#just go numerically 1 .. ??? alternating all horiz then all vert
for (my $dir = 0 ; $dir < 2 ; $dir++) #loop through each direction even if it doesnt exist
{
for (my $wordNumber = 1 ; $wordNumber < 300 ; $wordNumber++) #loop through all word numbers even if they don't exist
{
my $word = $allMasksOnBoard[$wordNumber][$dir]; # get WORD or MASK at this crossword position
if ($word eq undef) {next;} # if this [$wordNumber][$dir] does not exists in xword grid, find next one that does
push @nextWordOnBoard , {wordNumber => $wordNumber, dir => $dir};
if ($debug ) {print "($wordNumber,$dir)";}
}
}
}
sub GenerateNextWordPositionsOnBoardZigZag
{
#create a top right to bottom left list in which we will lay down words. FIFO
#zigzag alternate top right to bottom left then botom left to top right
my $x = 1;
my $y = -1;
my $divX = -1;
my $divY = 1;
do {
#move cursor
$x = $x + $divX;
$y = $y + $divY;
#test cursor position
if ( ($x < 0) and ($y >= $in{height}) ) {#bottom left corner
$divX = -$divX; $divY = -$divY; #change directions
$x = 1;
$y = $in{height} - 1;
}
if ( ($x >= $in{width}) and ($y < 0) ) {#top right corner
$divX = -$divX; $divY = -$divY; #change directions
$x = $in{width} - 1;
$y = 1;
#$myWidth = $in{width};
}
if ($x < 0){#off left
$divX = -$divX; $divY = -$divY; #change directions
$x = 0;
}
if ($y < 0){#off top
$divX = -$divX; $divY = -$divY; #change directions
$y = 0;
}
if ($x >= $in{width}){#off right
$divX = -$divX; $divY = -$divY; #change directions
$x = $in{width} - 1;
$y = $y + 2;
}
if ($y >= $in{height}){#off bottom
$divX = -$divX; $divY = -$divY; #change directions
$x = $x + 2;
$y = $in{height} - 1;
}
#process cursor position
if ($puzzle[$x][$y]->{Letter} ne $padChar)
{
#see if we are at start of word. If sio add to list
for (my $dir = 0 ; $dir < 2 ; $dir++)
{
my $wordNumber = $ThisSquareBelongsToWordNumber[$x][$y][$dir];
my @wordLetterPositions = @{$letterPositionsOfWord[$wordNumber][$dir]};
if ( ($wordLetterPositions[0][0] == $x) and ($wordLetterPositions[0][1] == $y) )
{
push @nextWordOnBoard , {wordNumber => $wordNumber, dir => $dir};
if ($debug ) {print "($x,$y)word#:$wordNumber,dir:$dir | ";}
}
}
}
}
until ( ($x == $in{width} - 1) and ($y == $in{height} - 1) );
}
sub GenerateNextWordPositionsOnBoardDiag
{
#create a top right to bottom left list in which we will lay down words. FIFO
#zigzag alternate top right to bottom left then botom left to top right
my $x = 1;
my $y = -1;
my $divX = -1;
my $divY = 1;
my $diagCount;
@nextWordOnBoard = ();
do {
#move cursor
$x = $x + $divX;
$y = $y + $divY;
if (($x < 0) or ($y >= $in{height}) ) {
$diagCount++;
$x = $diagCount;
if ($x >= $in{width} - 1) {
$x = $in{width} - 1;
$y = $diagCount - $x;
}
else {
$y = 0;
}
}
if ($debug ) {print "($x,$y)";}
#process cursor position
if ($puzzle[$x][$y]->{Letter} ne $padChar) {
#see if we are at start of word. If sio add to list
for (my $dir = 0 ; $dir < 2 ; $dir++)
{
my $wordNumber = $ThisSquareBelongsToWordNumber[$x][$y][$dir];
my @wordLetterPositions = @{$letterPositionsOfWord[$wordNumber][$dir]};
if ( ($wordLetterPositions[0][0] == $x) and ($wordLetterPositions[0][1] == $y) )
{
push @nextWordOnBoard , {wordNumber => $wordNumber, dir => $dir};
if ($debug ) {print "($x,$y)word#:$wordNumber,dir:$dir | ";}
}
}
}
}
until ( ($x >= $in{width} - 1) and ($y >= $in{height} - 1) );
}
sub GenerateGridDoubleSpaced()
{
#input width (which gives height) and oddEven style
#output a text array of width and height and create full double space pattern
#also set globals $in{width} and $in{height}
my $width = $_[0];
my $oddEven = $_[1] | 0;
$in{width} = $width;
$in{height} = $width;
#build a basic double spaced grid
for (my $y = 0 ; $y < $width ; $y++)
{
for (my $x = 0 ; $x < $width ; $x++)
{
$puzzle[$x][$y]->{Letter} = $unoccupied; # assume, then change as required
if ( ( ($y % 2) != $oddEven) and ( ($x % 2) != $oddEven) )
{
$puzzle[$x][$y]->{Letter} = $padChar;
}
}
}
}
my %breadCrumbs;
sub GenerateGridDoubleSpaced2()
{#random british grid generator
#fill with whitespace and pads then add pads one at a time. If pad separates any area, undo and try again.
#fill all joining squares with breadcrumbs using recursion. If all surrounding whitespace has a breadcrumb then there are no islads of white
#if words nsew are > 2 try again
my $width = $_[0];
my $oddEven = $_[1] | 0;
my ($x , $xx , $y , $yy);
my @unoccupiedNSEWWhitespace;
my $wordSizeH;
my $wordSizeV;
$in{width} = $width;
$in{height} = $width;
&GenerateGridDoubleSpaced($width,$oddEven);
my $padCells;
my $whiteCells;
#calculate density
for ($y = 0 ; $y < $in{height} ; $y++)
{
for ($x = 0 ; $x < $in{width} ; $x++) {
if ($puzzle[$x][$y]->{Letter} eq $padChar)
{$padCells++;}
if ($puzzle[$x][$y]->{Letter} eq $unoccupied)
{$whiteCells++;}
}
}
my $totalCells = $in{height} * $in{width};
my $time_to_quit = time() + 3; #5 seconds!
MAINLOOP: while (time() < $time_to_quit)
{
$x = int(rand( $in{width} ));
$y = int(rand( $in{height} ));
if ( $in{doublespacedpercentage} > int(100 * ($totalCells - $padCells) / $totalCells) )
{
last; #we have reached black pad percentage quota
}
#already is a pad
if ( $puzzle[$x][$y]->{Letter} eq $padChar )
{
next;
}
#place pad first so we can calculate word sizes, remove if fail!
$puzzle[$x][$y]->{Letter} = $padChar;
$padCells++;
#get first whitespace around proposed pad space
%breadCrumbs = (); #start fresh
@unoccupiedNSEWWhitespace = &ReturnLocalWhiteSquares($x,$y);
#see if surrounded by pads - next!
if (scalar @unoccupiedNSEWWhitespace == 0)
{
$puzzle[$x][$y]->{Letter} = $unoccupied;
$padCells--;
next;
}
#take 1st local whitespace and run with it
$xx = $unoccupiedNSEWWhitespace[0][0];
$yy = $unoccupiedNSEWWhitespace[0][1];
&BreadCrumbAllWhiteFromHere($xx,$yy); #mark all touching whitespace starting from either NSEW
#check each local surrounding whitespace for a breadcrumb and check for legal word sizes
foreach my $item (@unoccupiedNSEWWhitespace)
{
$xx = $item->[0];
$yy = $item->[1];
#check to see if both horiz and vert word size are valid
$wordSizeH = &calcWordSize( $xx ,$yy , 0);
$wordSizeV = &calcWordSize( $xx ,$yy , 1);
if ( $wordSizeH == 1 and $wordSizeV == 1 )
{
$puzzle[$x][$y]->{Letter} = $unoccupied;
$padCells--;
next MAINLOOP;
}
if ( not($wordSizeH == 1) and ($wordSizeH < 3) )
{
$puzzle[$x][$y]->{Letter} = $unoccupied;
$padCells--;
next MAINLOOP;
}
if ( not($wordSizeV == 1) and ($wordSizeV < 3) )
{
$puzzle[$x][$y]->{Letter} = $unoccupied;
$padCells--;
next MAINLOOP;
}
#check to see if bread crumb exists for all surrounding whitespace or next
if ( $breadCrumbs{$xx}{$yy} != 1 )
{
$puzzle[$x][$y]->{Letter} = $unoccupied;
$padCells--;
next MAINLOOP;
}
}
}
};
sub BreadCrumbAllWhiteFromHere()
{
#given a starting location $unoccupied, mark all adjoining whitespace with breadcrumbs and when done, return
my $x = $_[0];
my $y = $_[1];
my @unoccupiedNSEWWhitespace = ();
$breadCrumbs{$x}{$y} = 1; #mark visited
#get all $unoccupied and unvisited local pads around x y and push to a list
@unoccupiedNSEWWhitespace = &ReturnLocalWhiteSquares($x,$y);
if ( (scalar @unoccupiedNSEWWhitespace) == 0) #surrounded by pads or already visited
{
return; #start of the end
}
foreach my $item (@unoccupiedNSEWWhitespace)
{
#choose next adjoining white space
$x = $item->[0];
$y = $item->[1];
#continue recursive journey
&BreadCrumbAllWhiteFromHere($x,$y);
}
};
sub ReturnLocalWhiteSquares()
{
#give a sqare and return a list of ([x y] [x y] [x y] ....) of NSEW white squares
my @unoccupiedNSEWWhitespace;
my ($x , $y);
#check N
$x = $_[0];
$y = $_[1] - 1;
if ( not &outsideCrossword($x,$y) and ($puzzle[$x][$y]->{Letter} eq $unoccupied) and ($breadCrumbs{$x}{$y} != 1))
{
push @unoccupiedNSEWWhitespace , [$x,$y];
}
#check S
$x = $_[0];
$y = $_[1] + 1;
if ( not &outsideCrossword($x,$y) and ($puzzle[$x][$y]->{Letter} eq $unoccupied) and ($breadCrumbs{$x}{$y} != 1))
{
push @unoccupiedNSEWWhitespace , [$x,$y];
}
#check E
$x = $_[0] + 1;
$y = $_[1];
if ( not &outsideCrossword($x,$y) and ($puzzle[$x][$y]->{Letter} eq $unoccupied) and ($breadCrumbs{$x}{$y} != 1))
{
push @unoccupiedNSEWWhitespace , [$x,$y];
}
#check W
$x = $_[0] - 1;
$y = $_[1];
if ( not &outsideCrossword($x,$y) and ($puzzle[$x][$y]->{Letter} eq $unoccupied) and ($breadCrumbs{$x}{$y} != 1))
{
push @unoccupiedNSEWWhitespace , [$x,$y];
}
return @unoccupiedNSEWWhitespace;
};
sub Number_clue_list {
my $x = -1;
my $y = -1;
my @word_sort;
my $wordNumber;
my $positionPair;
my @wordLetterPositions;
my $wordLetterPositions;
my @temp;
my $word;
my $hints;
my $dir;
my @clues;
for ($dir=0 ; $dir < 2 ; $dir++)
{
$hints = '';
for ($wordNumber=1 ; $wordNumber <= $biggestwordNumber ; $wordNumber++)
{
$word = $allMasksOnBoard[$wordNumber][$dir];
if ($word ne undef)
{
#get clue(s)
my $first2Leters = substr $word , 0 , 2;
my $directory = "./wordlists/$in{wordfile}/clues/";
#my $filename = "$directory"."_"."$word\.clu";
my $filename = "$directory"."_"."$first2Leters\.clu";
open (DATA, "<$filename") or die("Word file $filename does not exist");
my $line;
@clues = ();
foreach $line (<DATA>)
{
#filter for just word
#my $lineWord;
#my $lineClue;
(my $lineWord , my $lineClue) = split /\|/ , $line;
if ($lineWord eq $word)
{
push (@clues , $lineClue);
}
}
close DATA;
my $clue = $clues[int(rand(scalar @clues))];
$clues{$word} = $clue;
$wordLetterPositions = &javascriptArrayFromLetterPositions(@{$letterPositionsOfWord[$wordNumber][$dir]}); #clear last one
$x = $letterPositionsOfWord[$wordNumber][$dir]->[0]->[0];
$y = $letterPositionsOfWord[$wordNumber][$dir]->[0]->[1];
my $temp = qq| <font size=-1><a href='http://www.google.ca/search?q=$word' target='_blank'>google</a></font> |;
#<font><i><A ONCLICK="if (this.innerHTML=='show') {this.innerHTML='$word'} else {this.innerHTML='show'}" HREF="\#self">show</A></i></font>
$hints .= qq|
$wordNumber\. <a href="\#self" id="$word" class="clues" ONCLICK="choose('$word' , $x , $y , [$wordLetterPositions]);">$clues{$word}</a>
<font size=-2><a href="http://www.google.ca/search?q=$clues{$word}" target="_blank">google</a></font>
<font><i>
<span id='show$word' ONCLICK="hide2('show$word');show2('clue$word');show2('google$word');" >
<a href="#" ONCLICK="return false">show</a>
</span>
<span id='clue$word' ONCLICK="hide2('clue$word');hide2('google$word');show2('show$word');" >
<a href="#" ONCLICK="return false">$word</a>
</span>
<span id='google$word' >
<font size=-2><a href="http://www.google.ca/search?q=$word" target="_blank">google</a></font>
</span>
<i></font>
</br>
<script>hide2('clue$word');hide2('google$word');</script>
|;
}
}
if ($dir == 0) {$hints_across = $hints}
if ($dir == 1) {$hints_down = $hints}
}
}
sub LoadGrid
{
my $filename = $_[0];
my ($x , $y);
$in{height} = 0;
$in{width} = 0;
my $square;
my $temp = 0;
$filename = "./grids/$filename.txt";
open (DATA, "<$filename") or die("Grid file $filename does not exist");
foreach my $line (<DATA>)
{
$x = 0;
chomp($line);
my @squares = split(// , $line);
foreach $square (@squares)
{
$puzzle[$x][$y]->{Letter} = $square; #should be an x or a o.
$x++;
}
if ($x > $temp) {$temp = $x};
$y++;
}
close (DATA);