这只允许两个玩家。
$players = array(
array('attack' => 1, 'defense' => 2, 'health' => 10, 'level' => 2, ),
array('attack' => 2, 'defense' => 1, 'health' => 10, 'level' => 2, ),
);
$count = 0;
while (true) {
$count++;
$players_temp = $players;
$attacker_key = array_rand($players);
$attacker =& $players[$attacker_key];
unset($players_temp[$attacker_key]);
$defender_key = array_rand($players_temp);
$defender =& $players[$defender_key];
$hit = ($attacker['attack']/$defender['defense']) + rand(1, $attacker['level']);
echo "{$count}. Player {$defender_key} ({$defender['health']} health) is hit a {$hit} by Player {$attacker_key} ({$attacker['health']} health)\n";
$defender['health'] = $defender['health'] - $hit;
if ($defender['health'] <= 0) {
echo "Player {$defender_key} dies, Player {$attacker_key} is victorious!\n";
break;
}
}
[已编辑]
这允许两个以上的玩家并且是回合制的。
set_time_limit(1);
$players = array(
'A' => array('attack' => 1, 'defense' => 2, 'health' => 10, 'level' => 2, ),
'B' => array('attack' => 2, 'defense' => 1, 'health' => 10, 'level' => 2, ),
'C' => array('attack' => 1, 'defense' => 1, 'health' => 10, 'level' => 2, ),
'D' => array('attack' => 2, 'defense' => 2, 'health' => 10, 'level' => 2, ),
);
$player_ids = array_keys($players);
$no_of_players = sizeof($player_ids);
$count = 0;
while (true) {
$defender_key=0;
for ($attacker_key=0;$attacker_key<$no_of_players;$attacker_key++) {
if (!isset($player_ids[$attacker_key])) continue;
$count++;
$attacker_id = $player_ids[$attacker_key];
$attacker =& $players[$attacker_id];
$defender_key = $attacker_key + 1;
while (!isset($player_ids[$defender_key])) {
$defender_key = ($defender_key+1 < $no_of_players) ? $defender_key + 1 : 0;
}
$defender_id = $player_ids[$defender_key];
$defender =& $players[$defender_id];
$hit = round(($attacker['attack']/$defender['defense']) + rand(1, $attacker['level']), 2);
echo "{$count}. Player {$attacker_id} ({$attacker['health']} health) has hit a {$hit} on Player {$defender_id} ({$defender['health']} health)<br />";
$defender['health'] = $defender['health'] - $hit;
if ($defender['health'] <= 0) {
echo "Player {$defender_id} dies<br />";
unset($players[$defender_id], $player_ids[$defender_key]);
if (sizeof($player_ids) == 1) {
echo "Player {$attacker_id} is victorious!<br />";
break 2;
}
}
//if ($count > 100) break 2;
}
}