lpst/MNU.pm

116 lines
1.9 KiB
Perl
Raw Normal View History

2021-04-11 18:41:44 -04:00
#!/usr/bin/perl
2021-04-11 20:36:01 -04:00
package MNU;
2021-04-11 18:41:44 -04:00
use warnings;
use strict;
use lib "./";
use NTVL;
use LPST;
2021-04-11 20:36:01 -04:00
use Try::Tiny;
my $SAVE_FN = "save.txt";
sub roll_back($){
my @arr;
my $game_str = shift;
@arr = split(/\n/, $game_str);
if(scalar @arr == 1){
return "";
}
return join("\n", splice(@arr, 0, -1))."\n";
}
sub eval_game_str($$){
my ($b, $game_str) = (shift, shift);
try {
NTVL->f1($b, $game_str);
$b->disp_board();
2021-04-11 20:36:01 -04:00
} catch {
warn "invalid move: $_";
$game_str = roll_back($game_str);
};
return $game_str;
}
sub disp_board($){
my $b = shift;
$b->disp_board();
}
sub load(){
my $game_str;
2021-04-11 18:41:44 -04:00
2021-04-11 20:36:01 -04:00
$game_str = "";
open FILE, "<".$SAVE_FN or die "couldn't open save file";
while(<FILE>){
$game_str .= $_;
}
close FILE;
return $game_str;
}
sub save($){
my $game_str = shift;
open FILE, ">".$SAVE_FN or die "couldn't open save file";
printf FILE "%s", $game_str;
close FILE;
return $game_str;
}
sub parse_cmd($){
my $in = shift;
return -1 if $in =~ /^q(uit)?$/i;
return 1 if($in =~ /^save$/i);
return 2 if($in =~ /^load$/i);
return 3 if($in =~ /^show$/i);
2021-04-11 20:36:01 -04:00
return 0;
}
sub show($$){
my ($b, $game_str) = (shift, shift);
$b->shade_all_p1_mvmt();
disp_board($b);
return prompt($b, $game_str);
}
sub prompt($$){
my ($b, $game_str) = (shift, shift);
2021-04-11 20:36:01 -04:00
2021-04-11 18:41:44 -04:00
printf("> ");
my $in;
$in = <STDIN>;
chomp $in;
2021-04-11 20:36:01 -04:00
return "QUIT" if(parse_cmd($in) == -1);
return save($game_str) if parse_cmd($in) == 1;
return load() if parse_cmd($in) == 2;
return show($b, $game_str) if parse_cmd($in) == 3;
2021-04-11 20:36:01 -04:00
$game_str .= $in."\n";
return $game_str;
2021-04-11 18:41:44 -04:00
}
2021-04-11 20:36:01 -04:00
sub loop($$){
my ($class, $game_str) = (shift, shift);
my $in;
my $b;
2021-04-11 20:36:01 -04:00
$b = LPST->new();
$game_str = eval_game_str($b, $game_str);
printf("%s\n", $game_str);
$game_str = prompt($b, $game_str);
2021-04-11 20:36:01 -04:00
return $game_str;
2021-04-11 18:41:44 -04:00
}
return 1;