lib/Games/Sudoku/Trainer/Run.pm untested

filter: Statementstmt 0.0% 0 / 261 Branchbran 0.0% 0 / 56 Conditioncond 0.0% 0 / 44 MC/DCmcdc 0.0% 0 / 26 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 424 CC 29 SCAR 36.8
CC
29
Cov
0%
_init_puzzle
132.0
initialize_and_start
42.0
_run_puzzle
42.0
CRAP 39.7
1 use strict;
2 use warnings;
3 #use feature qw( say );
4
5 # basic Sudoku structures
6 # don't panic - all basic Sudoku structures are constant
7 package main;
8 our @rows; # row objects (1 .. 9)
9 our @cols; # col objects (1 .. 9)
10 our @blocks; # block objects (1 .. 9)
11 our @units; # all unit objects (0 .. 26) rows, columns, and blocks
12 our @lines; # all line objects (0 .. 17) rows and columns
13
14 sub init_all {
15 use Games::Sudoku::Trainer::Const_structs;
16 use Games::Sudoku::Trainer::Priorities;
17 use Games::Sudoku::Trainer::Found_info;
18 use Games::Sudoku::Trainer::Strategies;
19 use Games::Sudoku::Trainer::Pause;
20 use Games::Sudoku::Trainer::GUI;
21 use Games::Sudoku::Trainer::GUIhist;
22 use Games::Sudoku::Trainer::Write_puzzle;
23 use Games::Sudoku::Trainer::Check_pause;
24 }
25
26 # basic Sudoku structures
27 # don't panic - all basic Sudoku structures are constant
28 package main;
29 our @cells; # cell objects (1 .. 81)
30 #our @units; # all unit objects (0 .. 26) rows, columns, and blocks
31
32 #package
33 # Games::Sudoku::Trainer::Run;
34 package Games::Sudoku::Trainer::Run;
35
36 use version; our $VERSION = qv('0.04'); # PBP
37
38 use Getopt::Long;
39 use Carp;
40 use List::Util qw(first);
41
42 # globals of package Run
43 my $gamestring; # the initial puzzle as a string of 81 char.s
44 my $testmode = 0;
45
46 # initialize the puzzle with the preset values, start the main loop,
47 # process eval errors.
48 # Called from package GUI when the main window is ready
49 #
50 sub initialize_and_start {
51 _commandline_options();
52
53 eval {
54 _init_puzzle();
55 _insert_presets();
56 _verify_puzzle();
57 $testmode and Games::Sudoku::Trainer::Pause->setMode('non-stop');
58 $testmode or Games::Sudoku::Trainer::Check_pause::pause();
59 Games::Sudoku::Trainer::GUI::set_status('');
60 _run_puzzle();
61 };
62 if ($@) {
63 my $eval_err = $@;
64 $eval_err =~ s/^(\d)\n//;
65 my ($err_type) = $1 || 0;
66 if ( $err_type == 0 ) { # unclassified error
67 $eval_err =~ /_TK_EXIT_\(0\)/ and exit;
68 if ( $eval_err =~ /^Undefined subroutine / ) {
69 $err_type = 3; # changed for 'Undefined subroutine xxx called'
70 }
71 else {
72 $err_type = 9; # unclassified error
73 # code position on new line
74 $eval_err =~ s/(?= at \S+ line \d+, <>)/\n/;
75 }
76 }
77
78 my %cosmetics = (
79 #<<< hands off, perltidy!
80 # $err_type $title $icon
81 1 => [ 'Data error', 'warning'],
82 2 => [ 'User error', 'warning'],
83 3 => [ 'Code error', 'error' ],
84 9 => [ 'Problem', 'error' ],
85 #>>>
86 );
87 my ( $title, $icon ) = @{ $cosmetics{$err_type} };
88 $title or do {
89 ( $title, $icon ) = ( 'Error', 'error' );
90 $eval_err .= "\n(unknown error type $err_type)";
91 };
92 if ($testmode) {
93 $eval_err =~ s{\n(?=\w)}{ }g;
94 print "$title: $eval_err";
95 Tk::exit;
96 }
97 if ( $err_type != 2 ) {
98 Games::Sudoku::Trainer::GUI::button_state( 'Run', 'disable' );
99 Games::Sudoku::Trainer::GUI::set_exit_on_delete();
100 }
101 Games::Sudoku::Trainer::GUI::showmessage(
102 -title => $title,
103 -icon => $icon,
104 -message => $eval_err,
105 );
106 return;
107 } ## end if...
108
109 $testmode and Tk::exit;
110 return;
111 } ## end sub initialize_and_start
112
113 # process the command line options
114 # including the non-documented flag 'test' for automated test suites
115 #
116 sub _commandline_options {
117 my $prio;
118 my $trail = ",\noption prio will be ignored.";
119
120 # catch warn to STDERR issued by GetOptions
121 local $SIG{__WARN__} =
122 sub { chomp( my $msg = $_[0] ); user_err("$msg$trail") };
123
124 GetOptions(
125 'prio=s' => \$prio, # file name of priority list
126 ## test flag for development (forces run mode 'non-stop')
127 'test' => \$testmode,
128 );
129 $prio or return;
130 -f $prio or do {
131 user_err( "File '$prio' doesn't exist", $trail );
132 return;
133 };
134 open( my $PRI, '<', $prio )
135 or do { user_err( "Cannot open file $prio: $!", $trail ); return };
136 my @strats = <$PRI>;
137 close $PRI or die "9\nCannot close file $prio: $!\n";
138 chomp @strats;
139 grep ( { $_ =~ $strats[0] } Games::Sudoku::Trainer::Priorities->copy_strats() )
140 or do { user_err("File $prio is no priority list$trail"); return };
141 Games::Sudoku::Trainer::Priorities::set_strats( \@strats );
142 return;
143 }
144
145 # read the initial puzzle
146 # prepare insertion of the preset values into the Sudoku board
147 #
148 sub _init_puzzle {
149 until ($gamestring) {
150 my @game;
151 if (@ARGV) {
152 unless ( -f $ARGV[0] ) {
153 user_err("File $ARGV[0] doesn't exist");
154 undef @ARGV;
155 next;
156 }
157 $#ARGV = 0; # ignore all but first
158 Games::Sudoku::Trainer::GUI::show_filename( $ARGV[0] );
159 @game = <>;
160 undef @ARGV;
161 }
162 else {
163 @game = Games::Sudoku::Trainer::GUI::get_initialpuzzle();
164 next unless @game; # no file or empty file
165 }
166
167 unless (@game) {
168 data_err('No data found');
169 next;
170 }
171
172 # ignore preceeding comment lines
173 while ( $game[0] =~ /^#/ ) { shift @game }
174 $gamestring = join( '', @game );
175 undef @game;
176
177 # In case of error sub data_err is called directly
178 # instead of using die.
179 # So the user has the chance to select a different puzzle.
180 #
181 $gamestring =~ s/\n//g; # ignore newlines
182
183 # ignore whitespace
184 if ( length($gamestring) > 81 ) { $gamestring =~ s/\s//g }
185 my $l = length($gamestring);
186 if ( $l == 0 ) {
187 data_err('No puzzle found');
188 undef $gamestring;
189 next;
190 }
191 unless ( $l == 81 ) {
192 data_err("Length of game string is $l, should be 81");
193 undef $gamestring;
194 next;
195 }
196 unless ( $gamestring =~ /[1-9]/ ) {
197 data_err('No preset values found');
198 undef $gamestring;
199 next;
200 }
201 if ( $gamestring =~ /^[1-9]+$/ ) {
202 data_err('Initial puzzle is solved already');
203 undef $gamestring;
204 }
205 } ## end until...
206
207 # Insert the preset values in @found
208 # sub _insert_presets will insert them into the Sudoku board
209 #
210 for ( my $pos = 0 ; $pos < 81 ; $pos++ ) {
211 my $char = substr( $gamestring, $pos, 1 );
212 next unless $char =~ /[1-9]/;
213 Games::Sudoku::Trainer::Found_info->new(
214 [ $cells[ $pos + 1 ], $char, 'preset' ] );
215 }
216 return;
217 } ## end sub _init_puzzle
218
219 # Insert all preset values in the Sudoku board
220 # _insert_presets();
221 #
222 sub _insert_presets {
223 my ( $cell, $digit, $strategy );
224 my $found_info_ref;
225
226 # Inform class Cell that we are inserting preset values
227 # This delays some error messages until verify
228 Games::Sudoku::Trainer::Pause->setMode('in_preset');
229 while (1) {
230 my $oldest = Games::Sudoku::Trainer::Found_info->oldest();
231 last unless $oldest;
232 $found_info_ref = $oldest;
233 ( $cell, $digit, $strategy ) = @$found_info_ref;
234 $cell->insert_digit($digit);
235 Games::Sudoku::Trainer::GUI::display_cellvalue(
236 $cell->Row_num, $cell->Col_num, $digit, $strategy,
237 );
238 }
239 Games::Sudoku::Trainer::GUI::set_status("Done presetting values");
240 Games::Sudoku::Trainer::Pause->setMode('single-step');
241
242 # look for full house that is caused by presetting
243
244 foreach my $unit (@units) {
245 my @members = $unit->active_Members;
246 next unless ( @members == 1 );
247 Games::Sudoku::Trainer::Strategies::full_house( $members[0] );
248 }
249 return;
250 }
251
252 # look for obvious errors in the initial puzzle
253 #
254 sub _verify_puzzle {
255 my $errhead = 'Error in preset data:';
256
257 foreach my $unit (@units) {
258 my @presets;
259 my @members = $unit->get_Members;
260 foreach my $member (@members) {
261 my $preset = $member->Value;
262 next unless $preset;
263 ++$presets[$preset] > 1
264 and die "1\n$errhead\nDuplicate value $preset in unit ",
265 $unit->Name, "\n";
266 }
267 }
268
269 foreach my $unit (@units) {
270 my %check;
271 my @presets;
272 my @members = $unit->get_Members;
273 foreach my $member (@members) {
274 my $preset = $member->Value;
275 ++$presets[$preset] if $preset;
276 foreach my $cand ( split( '', $member->Candidates ) ) {
277 ++$check{$cand};
278 }
279 }
280
281 # each digit must either be preset as a value
282 # or be a cand. in at least 1 cell
283 foreach my $cand ( 1 .. 9 ) {
284 $check{$cand}
285 or $presets[$cand]
286 or die "1\n$errhead\nNo cell left for candidate $cand in unit ",
287 $unit->Name, "\n";
288 }
289 }
290
291 foreach my $cell ( @cells[ 1 .. 81 ] ) {
292 next if $cell->Value;
293 $cell->Candidates
294 or die "1\n$errhead\nNo candidate left for cell ", $cell->Name,
295 "\n";
296 }
297 Games::Sudoku::Trainer::GUI::button_state( 'Run', 'enable' );
298 return;
299 } ## end sub _verify_puzzle
300
301 # the main loop of SudokuTrainer
302 #
303 sub _run_puzzle {
304
305 # fetch the oldest find from module Found_info
306 # if no find returned
307 # call module Strategies to search in the puzzle
308 # terminate the main loop if nothing found
309 # check whether a pause is requested at this state of the puzzle
310 # if yes, pause until the user hits the "Run" button
311 # update the internal structures and the displayed board
312 # add the processed find to the history
313 #
314 my $found_info_ref;
315 my ( $cell, $digit, $strategy );
316
317 while (1) {
318 $found_info_ref = Games::Sudoku::Trainer::Found_info->oldest();
319 unless ($found_info_ref) {
320 Games::Sudoku::Trainer::Strategies::try_strategies();
321 $found_info_ref = Games::Sudoku::Trainer::Found_info->oldest();
322 last unless $found_info_ref;
323 }
324 $strategy = $found_info_ref->[0];
325 if ( $found_info_ref->[1] eq 'insert' ) {
326 ( $digit, $cell ) = @{ $found_info_ref->[3] };
327 next if ( $cell->Value ); # already found
328 Games::Sudoku::Trainer::Check_pause::check_pause($found_info_ref);
329 Games::Sudoku::Trainer::GUI::display_cellvalue(
330 $cell->Row_num, $cell->Col_num,
331 $digit, $strategy
332 );
333 $cell->insert_digit($digit);
334 Games::Sudoku::Trainer::Strategies::full_house($cell);
335
336 } else { # exclude cand.s
337
338 Games::Sudoku::Trainer::Check_pause::check_pause($found_info_ref);
339 my @exclude_info = @{ $found_info_ref->[3] };
340 foreach my $info (@exclude_info) {
341 my ( $cell_num, $exclude_cands ) = split( '-', $info );
342 $cell = $cells[$cell_num];
343 foreach my $digit ( split( '', $exclude_cands ) ) {
344 $cell->exclude_candidate($digit);
345 }
346 }
347 }
348 Games::Sudoku::Trainer::GUIhist::add_history($found_info_ref);
349 }
350 # the main loop has terminated
351
352 if ( ( my $valuecount = grep { $_->Value } @cells[ 1 .. 81 ] ) == 81 ) {
353 Games::Sudoku::Trainer::GUI::set_status('Sudoku puzzle is solved');
354 $testmode and print "found all\n";
355 }
356 else {
357 Games::Sudoku::Trainer::GUI::set_status('Sorry - cannot find more');
358 $testmode and print 'missing ', 81 - $valuecount, "\n";
359 }
360 # disable the Run button
361 Games::Sudoku::Trainer::GUI::button_state( 'Run', 'disable' );
362 Games::Sudoku::Trainer::GUI::set_exit_on_delete();
363 return;
364 } ## end sub _run_puzzle
365
366 # return the initial puzzle as a sting
367 # my $gamestring = initial_puzzle();
368 #
369 sub initial_puzzle {
370 return $gamestring;
371 }
372
373 sub data_err {
374 # disable the Run button
375 Games::Sudoku::Trainer::GUI::button_state( 'Run', 'disable' );
376 if ($testmode) { die "1\n@_\n" }
377 Games::Sudoku::Trainer::GUI::showmessage(
378 -title => 'Data error',
379 -message => "@_",
380 -icon => 'error'
381 );
382 return;
383 }
384
385 sub user_err {
386 if ($testmode) { die "2\n@_\n" }
387 Games::Sudoku::Trainer::GUI::showmessage(
388 -title => 'User error',
389 -message => "@_",
390 -icon => 'warning'
391 );
392 return;
393 }
394
395 sub code_err {
396 # disable the Run button
397 Games::Sudoku::Trainer::GUI::button_state( 'Run', 'disable' );
398 if ($testmode) { die "3\n@_\n" }
399 Games::Sudoku::Trainer::GUI::showmessage(
400 -title => 'Code error',
401 -message => "@_",
402 -icon => 'error'
403 );
404 return;
405 }
406
407 1;