PHP、OOP、および Extends を使用した非常に単純化された例があれば、非常にありがたいです。
キャラクター クラス、2 つの特定のタイプのメイジとウォリアー、および戦闘システムの作成の例。
何かのようなもの:
class Character{
}
class Wizard extends Character{
}
class Warrior extends Character{
}
class Battle {
}
ロジックを理解するだけです。
これは単なる出発点であり、あなたのケースの悪い例です。
すべてのキャラクターには名前があります。したがって、キャラクターの名前は Character クラスに含めることができます。
class Character {
public $name = "unknown";
}
すべての人はまた、標準的な力と生命を持っています
class Character {
public $name = "unknown";
public $force = 10;
public $life = 100;
}
拡張クラスは、これらのプロパティを継承します。例えば:
$me = new Wizard();
echo "The name of wizard is " . $me->name; // The name of wizard is unknown
コンストラクタメソッドでキャラクターの名前を設定できます
class Character {
public $name = "unknown";
public $force = 10;
public function __construct($name) {
$this->name = $name;
}
}
$me = new Wizard("Gandalf");
echo "The name of wizard is " . $me->name; // The name of wizard is Gandalf
ウィザードには、単純なキャラクターにはないものがあります。マナの例:
class Wizard extends Character{
public $mana = 100;
}
と
$me = new Wizard("Gandalf");
echo "The name of wizard is " . $me->name; // The name of wizard is Gandalf
echo "\nAnd its mana is " . $me->mana;
戦士は武器を持っているので、標準的な力の乗数を持っています。
class Warrior extends Character{
public $weapon = 12;
}
$opponent = new Warrior("Grunt");
echo "The name of warrior is " . $opponent->name . " and the powrfull of its weapon is " . $opponent->weapon;
すべてのキャラクターは、その力に応じて強力な能力を持っています:
class Character {
public $name = "unknown";
public $force = 10;
public $life = 100;
public function __construct($name) {
$this->name = $name;
}
protected function get_powerfull() {
return $this->force;
}
}
しかしウィザードの場合、力はマナに依存します
class Wizard extends Character{
public $mana = 100;
// override
public function get_powerfull() {
return $this->mana;
}
}
戦士の場合、武器とその力に依存します。
class Warrior extends Character{
public $weapon = 12;
// override
public function get_powerfull() {
return $this->weapon*$this->force;
}
}
すべてのキャラクターが戦うことができ、結果はクラスに依存する強力なものに依存します
class Battle {
public function fight(Character $player1, Character $player2) {
$damage1 = $player1->get_powerfull();
$damage2 = $player2->get_powerfull();
$player1->life -= $damage2;
$player2->life -= $damage1;
echo "{$player1->name} hits {$player2->name} for $damage1 points.<br/>";
echo "{$player2->name} hits {$player1->name} for $damage2 points.<br/>";
}
}
と
$me = new Wizard("Gandalf");
echo "The name of wizard is " . $me->name . "<br/>"; // The name of wizard is Gandalf
echo "\nAnd its mana is " . $me->mana. "<br/>";
$opponent = new Warrior("Grunt");
echo "The name of warrior is " . $opponent->name . " and the powrfull of its weapon is " . $opponent->weapon. "<br/>";
そう:
$battle = new Battle();
$battle->fight($me,$opponent);
出力:
Gandalf hits Grunt for 100 points.
Grunt hits Gandalf for 120 points.
これが役立つことを願っています
あなたが投稿したこの例は、単純化されています:
class Character{
}
class Mage extends Character{
}
class Warrior extends Character{
}
class Battle {
}
空のコメントとその後の余分なスペースを削除し、Warrior extends
のスペルを修正しましたMage
。