game-village-politics-backend/app/Actions/MarketDeals.php

53 lines
2.1 KiB
PHP

<?php
namespace App\Actions;
use App\Engine\Market;
use App\Engine\Simulation;
use App\Game\GameRuleViolation;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
/** Sending resources, making and taking back offers, and accepting another player's offer. */
final class MarketDeals extends VillageAction
{
/** @param array<string, mixed> $amounts wood, clay, iron */
public function send(User $user, int $villageId, int $x, int $y, array $amounts): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($x, $y, $amounts) {
$market = Market::of($village, $sim);
$market->requireMarket();
$market->send(self::target($village, $x, $y), $amounts, $now);
});
}
public function offer(User $user, int $villageId, string $give, int $giveAmount, string $want, int $wantAmount, int $count): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village) use ($give, $giveAmount, $want, $wantAmount, $count) {
Market::of($village, $sim)->offer($give, $giveAmount, $want, $wantAmount, $count);
});
}
public function cancelOffer(User $user, int $villageId, int $offerId): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village) use ($offerId) {
Market::of($village, $sim)->cancelOffer($offerId);
});
}
public function accept(User $user, int $villageId, int $offerId, int $count): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($offerId, $count) {
Market::of($village, $sim)->accept($offerId, $count, $now);
});
}
/** The village at x|y on the same world. */
public static function target(Village $village, int $x, int $y): Village
{
return Village::with('player')->where('world_id', $village->world_id)->where('x', $x)->where('y', $y)->first()
?? throw new GameRuleViolation('not_found', 'No village there.');
}
}