I have a simple strategy game I've been writing in perl, and although 90% of the execution time is spent doing disk I/O after the processing is done, there are some things that I feel could be done better.
One thing that is bugging me is the way I'm rolling for initiative in combat.
- Given:
- A list of ships.
- Typical numbers are 10's of ships.
- 1000 may be seen in the late game crunch-time.
- An initiative weight/value for each ship.
- Currently, the most common values are 1 and 3, although 5 and 7 are seen, plus an occasional 31+
- An optimum algorithm would allow for real values rather than just integers.
- Determine
- The order that the ships will act.
- Initiative weight/value does not need to be recalculated given damage by earlier ships, but it would be a bonus. (Damage to weapons already degrades the ability of poor-initiative ships to fire back)
Currently:
Each ship gets a number of ballots equal to their initiative value, which are randomly mixed into an array.
Ships then act the first time one of their ballots is seen. The rest of the ship's ballots are wasted space and time.
While this algorithm is more than fast enough, and does the job, there is surely a better way.
A snippet from the combat routine:
foreach my $ship (@shipsInCombat)
{
# Add ship to initiative hash
push @shipsToAct, (($ship) x ($ship->{thruster}*2+1));
}
shuffle(\@shipsToAct);
SHIP: foreach my $ship (@shipsToAct)
{
next SHIP if exists($shipsAlreadyDone{$ship});
$shipsAlreadyDone{$ship} = "yes";
#...
#Simulated mayhem
#...
}
Note: strict and warnings are on, and the variables are declared. This is just a snippet of the node's focus.
Note2: Shuffle() is a simple loop in which each element is swapped with a random element.
As far as the question part of this node:
What would you suggest as a better algorithm for rolling initiative in this situation?
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.