Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Battle script

by Joost (Canon)
on Jun 06, 2002 at 13:32 UTC ( #172186=note: print w/replies, xml ) Need Help??

in reply to Battle script

What a strangely intruiging post... :-)

Ok. I'll bite... For this you need a ithreading perl (this is only tested on 5.8.0 RC1)

#!/opt/perl-latest/bin/perl -w use threads; use threads::shared; use strict; my @scores : shared = (10,10); my @ts; for my $num (0 .. 1) { my $t =threads->new(sub { battle($num) } ); push @ts,$t; } $_->join() for @ts; sub battle { my $me = shift; my $other = $me ? 0 : 1; while ($scores[$me] > 0 && $scores[$other] > 0) { $scores[$other]--; print "Bot $me hit bot $other\n"; select(undef,undef,undef,rand 0.1); threads->yield; } print "Bot $me ".($scores[$me] > 0 ? 'won' : 'lost')."\n"; }

Maybe not bare bones, but certainly bleading edge :-)

-- Joost downtime n. The period during which a system is error-free and immune from user input.

Replies are listed 'Best First'.
Re: Battle script
by Abigail-II (Bishop) on Jun 06, 2002 at 16:16 UTC
    Of course, one doesn't need those newfangled thread thingies. Here's one that can easily be backported to old versions of perl, and is using fork() and signals.

    #!/usr/bin/perl -w my $hp = 100; my $pid; sub get_hit; sub get_hit { unless (-- $hp) { kill USR2 => $pid or warn "Failed to send victory: $!\n"; print "$$: Arrrgh, I am dying!\n"; exit; } print "$$: I got hit! $hp hitpoints left.\n"; $SIG {USR1} = \&get_hit; } $SIG {USR1} = \&get_hit; $SIG {USR2} = sub {print "$$: I won! I won!\n"; exit}; $pid = fork; die "Fork failed\n" unless defined $pid; $pid ||= getppid; while (1) { my $timeleft = rand 1; (undef, $timeleft) = select (undef, undef, undef, $timeleft) while $timeleft; kill USR1 => $pid; # Ignore errors. } __END__

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://172186]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (3)
As of 2021-08-02 14:52 GMT
Find Nodes?
    Voting Booth?
    My primary motivation for participating at PerlMonks is: (Choices in context)

    Results (27 votes). Check out past polls.