Skip to content

Instantly share code, notes, and snippets.

@AnaTofuZ AnaTofuZ/rectangle-ball.pl

Last active Jul 26, 2020
Embed
What would you like to do?
#!/usr/bin/env perl
use strict;
use warnings;
my $max_height = shift;
my $max_width = shift;
# 0 ------------- +
# |
# |
# |
# |
# |
# |
# +
my $status = {
width => 0,
height => 0,
dx => 1, #
dy => 1,#
};
my $counter = 1;
while (1) {
my $new_status = next_status($status);
print "$counter ($new_status->{height}, $new_status->{width})\n";
if (is_goal($new_status->{height}, $new_status->{width}) && $counter != 1) {
print "GOAL!\n";
exit 0;
}
$status = $new_status;
$counter++;
}
sub is_goal {
my ($height, $width) = @_;
if (($width == 1 ) || $width == $max_width) {
return 1 if ($height == 1); #左右の上の角
return 1 if ($height == $max_height); #左右の下の角
}
return 0;
}
sub next_status {
my $status = shift;
my ($new_height, $new_dy) = new_coordinate($status->{height}, $status->{dy}, $max_height);
my ($new_width, $new_dx) = new_coordinate($status->{width}, $status->{dx}, $max_width);
my $new_status = {
width => $new_width,
height => $new_height,
dx => $new_dx,
dy => $new_dy,
};
return $new_status;
}
sub new_coordinate {
my ($coordinate, $d, $max_coordinate) = @_;
my $new_coordinate = $coordinate + $d;
my $new_d = $d;
if ($new_coordinate < 1 ) { #上もしくは左の壁
$new_coordinate += 2; #-1が来ているので2を足して1にする
$new_d *= -1;
}
if ($new_coordinate > $max_coordinate) { #下もしくは右の壁
$new_coordinate -= 2;
$new_d *= -1;
}
return $new_coordinate, $new_d;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.