我正在尝试用PHP制作文本游戏,但我有问题因为我在php中编程了几天。我需要调用功能攻击(我需要$ _mainAttack,因为它是$ _baseAttack和特殊攻击的组合)来自防御功能所以我可以计算我放置的健康损失-5只是为了看它是否正常工作..
同样在健康方面我需要攻击才能降低hp,这样我才能计算出hp损失。我做的while循环是错误的,我需要帮助才能使其正常运行。我希望当健康状况低于0时退出循环。当它退出循环时,它将打印游戏结束。我陷入无休止的循环中,我不知道如何解决这个问题。
这是index.php:
<?php
include 'Duel.php';
$duel = new Duel();
$duel->attack();
$duel->defend();
?>
这是我的班级决斗:
<?php
class Duel{
public $_maxHealth = 20;
public $_currentHealth;
public $_baseAttack, $_specialAttack, $_mainAttack;
public $_specialChance, $deflectChance;
public $_defense;
function __construct()
{
echo 'begining of attack <br/>';
}
function attack()
{
$_specialChance = rand(0, 20);
$_specialAttack = 0;
if ($_specialChance < 10) {
$_specialAttack = 0;
} elseif ($_specialChance < 15) {
$_specialAttack = (int) rand(0, 5);
} elseif ($_specialChance <= 20) {
$_specialAttack = (int) rand(5, 10);
}
$_baseAttack = rand(1, 6);
$_mainAttack = $_baseAttack + $_specialAttack;
echo "Base attack is $_baseAttack: and special attack is : $_specialAttack attack is : $_mainAttack<br/>";
}
function defend()
{
$_maxHealth = 20;
do{
$deflectChance = rand(1, 10);
$deflect = 0;
if ($deflectChance < 5) {
$deflect = 0;
echo 'attack cannot be deflected';
}
elseif ($deflectChance > 5) {
$deflect = (int) rand(0, 3);
echo "attack is deflected for {$deflect} damage";
}
$_currentHealth = $_maxHealth + $deflect - 5;
echo "<br/>health is {$_currentHealth} <br/>";
}while($_currentHealth > 0);
if($_currentHealth > 0) echo "Game over";
}
} //end of class
答案 0 :(得分:1)
您始终根据$_maxHealth
计算$_currentHealth
,而不是之前的$_currentHealth = $_maxHealth;
。
在循环之前添加:
$_currentHealth = $_maxHealth + $deflect - 5;
并将$_currentHealth = $_currentHealth + $deflect - 5;
更改为:
{{1}}
答案 1 :(得分:1)
您可以尝试从攻击函数返回主攻击变量,只需在防御函数上调用它。
答案 2 :(得分:0)
你是计算$_mainAttack
但不会从你的健康中减去它,因此你的玩家不会死,你会在无限循环中结束。