Acme-Hospital-Bed

 view release on metacpan or  search on metacpan

lib/Acme/Hospital/Bed.pm  view on Meta::CPAN


sub next_patient {
	$_[0]->check_patients_out;
	my $available = $_[0]->available_rooms;
	if ($available == 0) {
		say('You won this time.');
		exit;
	}
	my %patient = $_[0]->_generate_patient();
	my @phrases = @{ $_[0]->{phrases}->[$patient{level}] };
	my $phrase = $phrases[int(rand(@phrases))];
	say(sprintf 'You have %s available rooms', $_[0]->available_rooms);
	say( sprintf('The next patients name is: %s. The patient will stay for: %s days.', $patient{name}, $patient{length}));
	say($phrase);
	my $ans = _wait_answer();
	if ($ans eq 'y') {
		$patient{level} < 6 ? do {
			$_[0]->_lose_a_life();
		} : do {
			push @{$_[0]->{rooms}}, \%patient;
		};
	} elsif ($patient{level} > 5) {
		$_[0]->_lose_a_life();
	}
	$_[0]->next_patient() unless $_[1];
}

sub check_patients_out {
	my $i = 0;
	for (@{$_[0]->{rooms}}) {
		$_->{length}--;
		if ($_->{length} == 0) {
			splice @{$_[0]->{rooms}}, $i, 1; 
			say('Patient checked out: ' . $_->{name});
		}
		$i++;
	}
}

sub _lose_a_life {
	if ($_[0]->{lifes}-- == 0) {
		say('GAME OVER!');
		exit;
	}
	say(sprintf 'You lose a life, %s lifes remaining.', $_[0]->{lifes});
}

sub _wait_answer {
	say('Should they go to hospital? (y/n) ');
	my $answer = <STDIN>;
	chomp $answer;
	if ($answer !~ m/y|n/) {
		return _wait_answer();
	}
	return $answer;
}

sub _generate_patient {
	my @names = @{$_[0]->{names}};
	return (
		name => sprintf('%s %s', map { $names[int(rand(@names))] } 0 .. 1),
		level => int(rand(10)),
		length => int(rand($_[0]->{max_length_of_stay})) || 1
	);
}

sub say {
	print $_[0] . "\n";
}

1;

__END__

=head1 NAME

Acme::Hospital::Bed - The great new Acme::Hospital::Bed!

=head1 VERSION

Version 0.07

=cut

=head1 SYNOPSIS

Quick summary of what the module does.

Perhaps a little code snippet.

	use Acme::Hospital::Bed;

	Acme::Hospital::Bed->start;

	...

	Acme::Hospital::Bed->new(
		total_num_of_beds => 4,
		lifes => 5,
		names => [qw/tom richard joy/],
		phrases => [
			[
				"Hello, I am fine.",
				"I still have my mind.",
			],
			[
				"Hello, I am still fine.",
				"I still have my mind."
			],
			[
				"Hello, I am also fine.",
				"I still have my mind."
			],
			[
				"Hello, I think I'm still fine.",
				"I still have my mind."
			],
			[
				"Hello, I think you think I'm fine.",
				"I still have my mind."
			],



( run in 1.382 second using v1.01-cache-2.11-cpan-bbc515a03b3 )