game-village-politics-backend/app/Game/Tribes/Diplomacy.php

94 lines
3.1 KiB
PHP

<?php
namespace App\Game\Tribes;
use App\Game\WorldConfig;
use Carbon\CarbonImmutable;
/**
* Relations between tribes (architecture.md, "Tribes"). An alliance or a non-aggression
* pact holds once both tribes confirmed it and until its notice period ends; enmity is
* declared by one side alone. Members of one tribe, allies and NAP partners can't attack
* each other.
*/
final class Diplomacy
{
public const ALLY = 'ally';
public const NAP = 'nap';
public const ENEMY = 'enemy';
public const PACTS = [self::ALLY, self::NAP];
/** What one player is to another: own tribe, ally, NAP partner, enemy, or nothing. */
public const TRIBE = 'tribe';
public const NONE = 'none';
public function __construct(private readonly WorldConfig $config) {}
/** How long ending a pact takes, at world speed. */
public function noticeSeconds(): int
{
return max(1, (int) round($this->config->get('tribes.notice_hours', 24) * 3600 / $this->config->speed()));
}
public function maxMembers(): int
{
return (int) $this->config->get('tribes.max_members', 25);
}
/**
* The relation between two tribes, from the rows between them (both directions).
*
* @param iterable<array{tribe_id: int, other_tribe_id: int, state: string, confirmed: bool, ends_at: CarbonImmutable|null}> $rows
*/
public static function relation(?int $mine, ?int $theirs, iterable $rows, CarbonImmutable $now): string
{
if ($mine === null || $theirs === null) {
return self::NONE;
}
if ($mine === $theirs) {
return self::TRIBE;
}
$ours = $their = null;
foreach ($rows as $row) {
if ($row['tribe_id'] === $mine && $row['other_tribe_id'] === $theirs) {
$ours = $row;
} elseif ($row['tribe_id'] === $theirs && $row['other_tribe_id'] === $mine) {
$their = $row;
}
}
$holds = fn (?array $r, string $state) => $r && $r['state'] === $state && $r['confirmed'] && ($r['ends_at'] === null || $r['ends_at']->greaterThan($now));
foreach (self::PACTS as $pact) {
if ($holds($ours, $pact) && $holds($their, $pact)) {
return $pact;
}
}
if (($ours['state'] ?? null) === self::ENEMY || ($their['state'] ?? null) === self::ENEMY) {
return self::ENEMY;
}
return self::NONE;
}
/** Whether a relation forbids attacks between the two. */
public static function protects(string $relation): bool
{
return in_array($relation, [self::TRIBE, self::ALLY, self::NAP], true);
}
/** 3 to 32 characters, letters, digits, spaces and a few marks. */
public static function validName(string $name): bool
{
return (bool) preg_match('/^[\p{L}\p{N}][\p{L}\p{N} \'\-_.&]{1,30}[\p{L}\p{N}.]$/u', $name);
}
/** 2 to 6 characters, letters, digits and - _ . */
public static function validTag(string $tag): bool
{
return (bool) preg_match('/^[\p{L}\p{N}\-_.]{2,6}$/u', $tag);
}
}