From abe9f7d8bc0a0229d2453939cc2325055e9aa2fc Mon Sep 17 00:00:00 2001 From: Petr Baudis Date: Fri, 9 Dec 2011 01:37:50 +0100 Subject: [PATCH] Example client: Use persistent state --- client/example.pl | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/client/example.pl b/client/example.pl index 7c589a0..3176483 100755 --- a/client/example.pl +++ b/client/example.pl @@ -15,12 +15,11 @@ use IO::Socket; $/ = "\r\n"; -sub tick($) { - my ($socket) = @_; +sub tick($$) { + my ($socket, $state) = @_; # read message from socket and parse it my $line = ''; - my %state = (); print "\n"; while ( chomp($line = <$socket>) ) { print "# $line\n"; @@ -41,23 +40,21 @@ sub tick($) { if ($type eq 'tick') { $value =~ /^\d+$/ or die "[ee] type tick wrong value ($value)\n"; - $state{tick} = $value; + $state->{tick} = $value; } elsif ($type eq 'energy') { $value =~ /^\d+$/ or die "[ee] type energy wrong value ($value)\n"; - $state{energy} = $value; + $state->{energy} = $value; } elsif ($type eq 'visual') { $value =~ /^([^ ][^ ] )+([^ ][^ ])$/ or die "[ee] type visual wrong value ($value)\n"; - $state{visual} = [ split(" ", $value) ]; + $state->{visual} = [ split(" ", $value) ]; } } - - %state; } -sub take_action($%) { - my ($socket, %state) = @_; +sub take_action($$) { + my ($socket, $state) = @_; # FIXME: We use a common direction choice for both move_dir # and attack_dir, but in fact the agent can do both actions @@ -84,8 +81,8 @@ sub take_action($%) { # Default direction in case of nothing interesting in the vicinity # is [1, -1]. - for my $i (0..$#{$state{visual}}) { - my ($type, $agent) = split(//, $state{visual}->[$i]); + for my $i (0..$#{$state->{visual}}) { + my ($type, $agent) = split(//, $state->{visual}->[$i]); my $dir = $vdirs[$i]; if (abs($dir->[0]) > 1 or abs($dir->[1]) > 1) { @@ -148,12 +145,13 @@ print $socket "defense 1.0\r\n"; print $socket "\r\n"; print "[ii] agent created\r\n"; -my %state = (); -while (%state = tick($socket)) { - print $state{energy} . "\n"; - print "[", join('], [', @{$state{visual}}), "]\n"; +my $state = {}; +while (1) { + tick($socket, $state); + print $state->{energy} . "\n"; + print "[", join('], [', @{$state->{visual}}), "]\n"; - take_action($socket, %state); + take_action($socket, $state); } shutdown($socket, 2);