PHP code example of pfinalclub / asyncio-gamekit
1. Go to this page and download the library: Download pfinalclub/asyncio-gamekit library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
pfinalclub / asyncio-gamekit example snippets
use PfinalClub\AsyncioGamekit\Room\Room;
use PfinalClub\AsyncioGamekit\Player;
use function PfinalClub\Asyncio\{run, sleep};
class MyGameRoom extends Room
{
protected function run(): mixed
{
// 游戏开始
$this->broadcast('game:start', ['message' => '游戏开始!']);
// 游戏主循环
for ($round = 1; $round <= 3; $round++) {
$this->broadcast('game:round', ['round' => $round]);
sleep(5); // 每回合5秒
}
// 游戏结束
$this->broadcast('game:end', ['message' => '游戏结束!']);
$this->destroy();
}
}
// 运行游戏
function main(): mixed {
$room = new MyGameRoom('room_001');
$player1 = new Player('p1', null, 'Alice');
$player2 = new Player('p2', null, 'Bob');
$room->addPlayer($player1);
$room->addPlayer($player2);
$room->start();
}
run(main(...));
use PfinalClub\AsyncioGamekit\GameServer;
$server = new GameServer('0.0.0.0', 2345, [
'name' => 'MyGameServer',
'count' => 4,
]);
$server->run();
protected function getDefaultConfig(): array
{
return [
'max_players' => 4, // 最大玩家数
'min_players' => 2, // 最小玩家数
'auto_start' => false, // 是否自动开始
];
}
// 房间创建时(异步)
protected function onCreate(): mixed
{
$this->broadcast('room:created', ['message' => '房间已创建']);
}
// 游戏开始时(异步)
protected function onStart(): mixed
{
$this->broadcast('game:start', ['message' => '游戏即将开始']);
sleep(3);
}
// 游戏主循环(必须实现)
abstract protected function run(): mixed;
// 房间销毁时(异步)
protected function onDestroy(): mixed
{
$this->broadcast('room:destroyed', ['message' => '房间已销毁']);
}
// 玩家加入时(同步)
protected function onPlayerJoin(Player $player): void
{
echo "{$player->getName()} 加入房间\n";
}
// 玩家离开时(同步)
protected function onPlayerLeave(Player $player): void
{
echo "{$player->getName()} 离开房间\n";
}
// 处理玩家消息(异步)
public function onPlayerMessage(Player $player, string $event, mixed $data): mixed
{
if ($event === 'action') {
// 处理玩家动作
}
}
// 广播消息
$this->broadcast('event_name', $data);
$this->broadcast('event_name', $data, $exceptPlayer); // 排除某玩家
// 异步广播(延迟)
$this->broadcastAsync('event_name', $data, 2.0); // 延迟2秒
// 延迟执行
$this->delay(5.0); // 延迟5秒
// 添加定时器
$timerId = $this->addTimer(1.0, function() {
echo "每秒执行一次\n";
}, true); // true = 重复执行
// 移除定时器
$this->removeTimer($timerId);
// 玩家管理
$this->addPlayer($player);
$this->removePlayer($playerId);
$player = $this->getPlayer($playerId);
$players = $this->getPlayers();
$count = $this->getPlayerCount();
// 数据存储
$this->set('key', 'value');
$value = $this->get('key', 'default');
// 房间状态
$status = $this->getStatus(); // waiting, running, finished
$canStart = $this->canStart();
// 创建玩家
$player = new Player('player_id', $connection, 'PlayerName');
// 发送消息
$player->send('event_name', ['data' => 'value']);
// 数据管理
$player->set('score', 100);
$score = $player->get('score', 0);
$hasScore = $player->has('score');
// 准备状态
$player->setReady(true);
$isReady = $player->isReady();
// 获取信息
$id = $player->getId();
$name = $player->getName();
$room = $player->getRoom();
$array = $player->toArray();
$manager = new RoomManager();
// 创建房间
$room = $manager->createRoom(MyGameRoom::class, 'room_id', [
'max_players' => 4
]);
// 玩家加入/离开房间
$manager->joinRoom($player, 'room_id');
$manager->leaveRoom($player);
// 获取房间
$room = $manager->getRoom('room_id');
$rooms = $manager->getRooms();
$playerRoom = $manager->getPlayerRoom($player);
// 快速匹配(自动创建或加入房间)
$room = $manager->quickMatch($player, MyGameRoom::class, [
'max_players' => 4
]);
// 删除房间
yield from $manager->removeRoom('room_id');
// 统计信息
$stats = $manager->getStats();
$server = new GameServer('0.0.0.0', 2345, [
'name' => 'GameServer',
'count' => 4, // Worker 进程数
'protocol' => 'websocket',
]);
$server->run();
use PfinalClub\AsyncioGamekit\Logger\LoggerFactory;
use PfinalClub\AsyncioGamekit\Logger\LogLevel;
// 配置日志
LoggerFactory::configure([
'min_level' => LogLevel::INFO,
'console' => ['enabled' => true, 'color' => true],
'file' => [
'enabled' => true,
'path' => 'logs/game.log',
'max_size' => 10 * 1024 * 1024,
],
]);
// 记录日志
LoggerFactory::info('Game started', ['room_id' => 'room_001']);
LoggerFactory::error('Error: {message}', ['message' => 'Connection lost']);
use PfinalClub\AsyncioGamekit\Exceptions\RoomException;
try {
$room->addPlayer($player);
} catch (RoomException $e) {
// 获取结构化异常信息
$player->send('error', [
'message' => $e->getMessage(),
'code' => $e->getCode(),
'context' => $e->getContext()
]);
}
use PfinalClub\AsyncioGamekit\Persistence\{FileAdapter, RedisAdapter, RoomStateManager};
// 使用文件存储
$adapter = new FileAdapter('storage/game');
$stateManager = new RoomStateManager($adapter);
// 或使用 Redis(推荐)
$adapter = RedisAdapter::create('127.0.0.1', 6379);
$stateManager = new RoomStateManager($adapter);
// 保存和恢复房间状态
$stateManager->saveRoomState($room);
$state = $stateManager->getRoomState('room_001');
use PfinalClub\AsyncioGamekit\LoadBalance\{
RoomDistributor,
LeastConnectionsBalancer
};
// 创建负载均衡器
$balancer = new LeastConnectionsBalancer();
$distributor = new RoomDistributor($balancer);
// 注册工作进程
$distributor->registerWorker(1, ['connections' => 10]);
$distributor->registerWorker(2, ['connections' => 5]);
// 分配房间(会选择连接数最少的进程)
$workerId = $distributor->assignRoom('room_001');
protected function run(): Generator
{
// 添加定时器
$timerId = $this->addTimer(1.0, function() {
$elapsed = time() - $this->get('start_time');
$this->broadcast('game:timer', ['elapsed' => $elapsed]);
}, true);
$this->set('start_time', time());
// 游戏逻辑
sleep(60);
// 清理定时器
$this->removeTimer($timerId);
}
use function PfinalClub\Asyncio\{create_task, gather};
protected function run(): mixed
{
// 并发执行多个任务
$task1 = create_task(fn() => $this->taskA());
$task2 = create_task(fn() => $this->taskB());
$results = gather($task1, $task2);
// 继续游戏逻辑...
}
private function taskA(): mixed
{
sleep(2);
return 'Result A';
}
private function taskB(): mixed
{
sleep(1);
return 'Result B';
}
use function PfinalClub\Asyncio\wait_for;
use PfinalClub\Asyncio\TimeoutException;
protected function run(): mixed
{
try {
// 等待玩家响应,最多10秒
$result = wait_for(fn() => $this->waitForPlayerAction(), 10.0);
} catch (TimeoutException $e) {
// 超时处理
$this->broadcast('game:timeout', ['message' => '超时!']);
}
}
// 通过 RoomManager 实现房间间通信
$roomManager = new RoomManager();
$room1 = $roomManager->getRoom('room_001');
$room2 = $roomManager->getRoom('room_002');
// Room1 广播消息给 Room2 的玩家
foreach ($room2->getPlayers() as $player) {
$player->send('cross_room_message', ['from' => $room1->getId()]);
}
$server = new GameServer('0.0.0.0', 2345, [
'name' => 'ProductionGameServer',
'count' => 8, // 根据 CPU 核心数调整
]);
// 开启 Workerman 调试模式
use Workerman\Worker;
Worker::$daemonize = false;
Worker::$stdoutFile = '/tmp/workerman.log';
bash
php examples/SimpleGame.php
bash
php examples/CardGame.php
bash
php examples/WebSocketServer.php
bash
php examples/AdvancedGame.php