状態を更新してこれを解決しようとするのではなく、関数型プログラミングの方法で解決しようとすることを検討できます。たとえば、既知の条件(生産が開始されたときなど)が与えられた場合に、リソースの量を計算できる関数を記述します。非常に単純化:
状態ベースのモデル:
class Gold {
public $amount = 0;
}
class GoldDigger {
public $amount_per_second = 1;
}
$player_gold = new Gold();
$player_worker = new GoldDigger();
while (true) {
$player_gold->amount += $player_worker->amount_per_second;
sleep(1);
echo "Player has {$player_gold->amount} gold pieces\n";
}
機能ベースのモデル:
class Gold {
public $workers = array();
function getAmount() {
$total = 0;
foreach ($this->workers as $worker) {
$total += $worker->getAmount();
}
return $total;
}
}
class GoldDigger {
public $amount_per_second = 1;
public $started = 0;
function __construct() {
$this->started = time();
}
function getAmount() {
return $this->amount_per_second * (time() - $this->started);
}
}
$player_gold = new Gold();
$player_gold->workers[] = new GoldDigger();
while (true) {
sleep(1);
echo "Player has {$player_gold->getAmount()} gold pieces\n";
}
これらの例はどちらも少し工夫されています。データベースなどにデータを保存する可能性があり、問題が少し複雑になりますが、2つの戦略の違いを示していると思います。