Compare commits
68 Commits
v2.1.0
..
06864a9cec
| Author | SHA1 | Date | |
|---|---|---|---|
| 06864a9cec | |||
| 622bc94377 | |||
| 575e92e03f | |||
| 522eea72f6 | |||
| fc7930046d | |||
| 7ba7b34ca7 | |||
| 3eaf37a648 | |||
| 221f629ec2 | |||
| 18acd7d890 | |||
| 09a2b0d85f | |||
| b60f3615c1 | |||
| 363c45a140 | |||
| 181cc6a0b0 | |||
| 3c95478097 | |||
| 45ce8b2b2d | |||
| 50b050c4bc | |||
| 6748fbc44e | |||
| 449894e3e5 | |||
| 5173275a92 | |||
| ee56792beb | |||
| 02ed8ea319 | |||
| 2bebc78e82 | |||
| 4fe4155ec0 | |||
| c640a31302 | |||
| 6ae452c4b9 | |||
| 1607f57e3c | |||
| 3672140987 | |||
| 092b51cd95 | |||
| fe3e74b5f8 | |||
| 192259f0a4 | |||
| a50055deaf | |||
| 578f587941 | |||
| fb4a7171f4 | |||
| dc9c09c722 | |||
| 317dfd04d7 | |||
| 1192fe5bdb | |||
| e0679b164e | |||
| 82d762d070 | |||
| 5962d6d2b3 | |||
| 2f9b2eed64 | |||
| 434f2b8e0f | |||
| 9bc085cb7d | |||
| f13cfe4bc1 | |||
| cd1621f497 | |||
| 3973b7770c | |||
| 0847877ce2 | |||
| b886d98d8c | |||
| 4ff62e29bd | |||
| 461c6a6f56 | |||
| 1850a5f4e9 | |||
| 0850004d39 | |||
| df96b56ab0 | |||
| 495efdf9e0 | |||
| 0dd85879af | |||
| 64434516d7 | |||
| e155a0e3d0 | |||
| d6e8a64ce3 | |||
| abb5512222 | |||
| 55fd770fdd | |||
| 4fb78eaca9 | |||
| 05ec4a72b7 | |||
| f3d883b5ed | |||
| 96e0e21f8b | |||
| c8adbff78e | |||
| aa6046d89b | |||
| cdec289740 | |||
| d63aeef45b | |||
| 2be7e6caef |
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "chatroom-local-marketplace",
|
||||
"interface": {
|
||||
"displayName": "Chatroom Local Plugins"
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
"name": "chatroom-ride-development",
|
||||
"source": {
|
||||
"source": "local",
|
||||
"path": "./plugins/chatroom-ride-development"
|
||||
},
|
||||
"policy": {
|
||||
"installation": "AVAILABLE",
|
||||
"authentication": "ON_INSTALL"
|
||||
},
|
||||
"category": "Productivity"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -35,6 +35,9 @@ enum CurrencySource: string
|
||||
/** 商城购买消耗(扣除金币) */
|
||||
case SHOP_BUY = 'shop_buy';
|
||||
|
||||
/** 购买聊天室座驾消耗(扣除金币) */
|
||||
case RIDE_BUY = 'ride_buy';
|
||||
|
||||
/** 管理员手动调整(后台直接修改经验/金币/魅力) */
|
||||
case ADMIN_ADJUST = 'admin_adjust';
|
||||
|
||||
@@ -158,6 +161,9 @@ enum CurrencySource: string
|
||||
/** 购买头像框消耗(扣除金币) */
|
||||
case AVATAR_FRAME_BUY = 'avatar_frame_buy';
|
||||
|
||||
/** 猜谜活动奖励 */
|
||||
case GAME_REWARD = 'game_reward';
|
||||
|
||||
/**
|
||||
* 返回该来源的中文名称,用于后台统计展示。
|
||||
*/
|
||||
@@ -171,6 +177,7 @@ enum CurrencySource: string
|
||||
self::RECV_GIFT => '收到礼物',
|
||||
self::NEWBIE_BONUS => '新人礼包',
|
||||
self::SHOP_BUY => '商城购买',
|
||||
self::RIDE_BUY => '座驾购买',
|
||||
self::ADMIN_ADJUST => '管理员调整',
|
||||
self::POSITION_REWARD => '职务奖励',
|
||||
self::SIGN_IN => '每日签到',
|
||||
@@ -210,6 +217,7 @@ enum CurrencySource: string
|
||||
self::MSG_TEXT_COLOR_BUY => '文字颜色购买',
|
||||
self::MSG_DECORATION_BUY => '消息装扮购买(旧)',
|
||||
self::AVATAR_FRAME_BUY => '头像框购买',
|
||||
self::GAME_REWARD => '猜谜活动奖励',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,9 @@ use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* 类功能:向指定房间广播百家乐押注人数变化。
|
||||
*/
|
||||
class BaccaratPoolUpdated implements ShouldBroadcastNow
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
@@ -38,7 +41,7 @@ class BaccaratPoolUpdated implements ShouldBroadcastNow
|
||||
*/
|
||||
public function broadcastOn(): array
|
||||
{
|
||||
return [new PresenceChannel('room.1')];
|
||||
return [new PresenceChannel('room.'.$this->round->room_id)];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -58,6 +61,7 @@ class BaccaratPoolUpdated implements ShouldBroadcastNow
|
||||
{
|
||||
return [
|
||||
'round_id' => $this->round->id,
|
||||
'room_id' => (int) $this->round->room_id,
|
||||
'bet_count_big' => $this->round->bet_count_big,
|
||||
'bet_count_small' => $this->round->bet_count_small,
|
||||
'bet_count_triple' => $this->round->bet_count_triple,
|
||||
|
||||
@@ -20,6 +20,9 @@ use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* 类功能:向指定房间广播百家乐开局事件。
|
||||
*/
|
||||
class BaccaratRoundOpened implements ShouldBroadcastNow
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
@@ -38,7 +41,7 @@ class BaccaratRoundOpened implements ShouldBroadcastNow
|
||||
*/
|
||||
public function broadcastOn(): array
|
||||
{
|
||||
return [new PresenceChannel('room.1')];
|
||||
return [new PresenceChannel('room.'.$this->round->room_id)];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -58,6 +61,7 @@ class BaccaratRoundOpened implements ShouldBroadcastNow
|
||||
{
|
||||
return [
|
||||
'round_id' => $this->round->id,
|
||||
'room_id' => (int) $this->round->room_id,
|
||||
'bet_opens_at' => $this->round->bet_opens_at->toIso8601String(),
|
||||
'bet_closes_at' => $this->round->bet_closes_at->toIso8601String(),
|
||||
'bet_seconds' => (int) now()->diffInSeconds($this->round->bet_closes_at),
|
||||
|
||||
@@ -20,6 +20,9 @@ use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* 类功能:向指定房间广播百家乐结算结果。
|
||||
*/
|
||||
class BaccaratRoundSettled implements ShouldBroadcastNow
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
@@ -38,7 +41,7 @@ class BaccaratRoundSettled implements ShouldBroadcastNow
|
||||
*/
|
||||
public function broadcastOn(): array
|
||||
{
|
||||
return [new PresenceChannel('room.1')];
|
||||
return [new PresenceChannel('room.'.$this->round->room_id)];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -58,6 +61,7 @@ class BaccaratRoundSettled implements ShouldBroadcastNow
|
||||
{
|
||||
return [
|
||||
'round_id' => $this->round->id,
|
||||
'room_id' => (int) $this->round->room_id,
|
||||
'dice' => [$this->round->dice1, $this->round->dice2, $this->round->dice3],
|
||||
'total_points' => $this->round->total_points,
|
||||
'result' => $this->round->result,
|
||||
|
||||
@@ -19,6 +19,9 @@ use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* 类功能:广播聊天室全屏特效播放指令,并携带操作者与定向接收者信息。
|
||||
*/
|
||||
class EffectBroadcast implements ShouldBroadcastNow
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
@@ -26,16 +29,19 @@ class EffectBroadcast implements ShouldBroadcastNow
|
||||
/**
|
||||
* 支持的特效类型列表(用于校验)
|
||||
*/
|
||||
public const TYPES = ['fireworks', 'rain', 'lightning', 'snow', 'sakura', 'meteors', 'gold-rain', 'hearts', 'confetti', 'fireflies'];
|
||||
public const TYPES = ['fireworks', 'rain', 'lightning', 'snow', 'sakura', 'meteors', 'gold-rain', 'hearts', 'confetti', 'fireflies', 'j35', '99a', 'df5c', 'fujian'];
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
*
|
||||
* @param int $roomId 房间 ID
|
||||
* @param string $type 特效类型:fireworks / rain / lightning / snow / sakura / meteors / gold-rain / hearts / confetti / fireflies
|
||||
* @param string $type 特效类型:fireworks / rain / lightning / snow / sakura / meteors / gold-rain / hearts / confetti / fireflies / j35 / 99a / df5c / fujian
|
||||
* @param string $operator 触发特效的用户名(购买者)
|
||||
* @param string|null $targetUsername 接收者用户名(null = 全员)
|
||||
* @param string|null $giftMessage 附带赠言
|
||||
* @param string|null $effectTitle 特效画面标题
|
||||
* @param string|null $rideName 座驾名称
|
||||
* @param string|null $effectUserInfo 特效画面用户身份信息
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $roomId,
|
||||
@@ -43,6 +49,9 @@ class EffectBroadcast implements ShouldBroadcastNow
|
||||
public readonly string $operator,
|
||||
public readonly ?string $targetUsername = null,
|
||||
public readonly ?string $giftMessage = null,
|
||||
public readonly ?string $effectTitle = null,
|
||||
public readonly ?string $rideName = null,
|
||||
public readonly ?string $effectUserInfo = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -70,6 +79,9 @@ class EffectBroadcast implements ShouldBroadcastNow
|
||||
'operator' => $this->operator,
|
||||
'target_username' => $this->targetUsername, // null = 全员
|
||||
'gift_message' => $this->giftMessage,
|
||||
'effect_title' => $this->effectTitle,
|
||||
'ride_name' => $this->rideName,
|
||||
'effect_user_info' => $this->effectUserInfo,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,9 @@ use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* 类功能:向指定房间广播赛马开局事件。
|
||||
*/
|
||||
class HorseRaceOpened implements ShouldBroadcastNow
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
@@ -38,7 +41,7 @@ class HorseRaceOpened implements ShouldBroadcastNow
|
||||
*/
|
||||
public function broadcastOn(): array
|
||||
{
|
||||
return [new PresenceChannel('room.1')];
|
||||
return [new PresenceChannel('room.'.$this->race->room_id)];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -58,6 +61,7 @@ class HorseRaceOpened implements ShouldBroadcastNow
|
||||
{
|
||||
return [
|
||||
'race_id' => $this->race->id,
|
||||
'room_id' => (int) $this->race->room_id,
|
||||
'horses' => $this->race->horses,
|
||||
'total_pool' => $this->race->total_pool,
|
||||
'bet_opens_at' => $this->race->bet_opens_at->toIso8601String(),
|
||||
|
||||
@@ -19,6 +19,9 @@ use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* 类功能:向指定房间持续广播赛马进度。
|
||||
*/
|
||||
class HorseRaceProgress implements ShouldBroadcastNow
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
@@ -31,6 +34,7 @@ class HorseRaceProgress implements ShouldBroadcastNow
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $raceId,
|
||||
public readonly int $roomId,
|
||||
public readonly array $positions,
|
||||
public readonly bool $finished = false,
|
||||
public readonly ?int $leaderId = null,
|
||||
@@ -43,7 +47,7 @@ class HorseRaceProgress implements ShouldBroadcastNow
|
||||
*/
|
||||
public function broadcastOn(): array
|
||||
{
|
||||
return [new PresenceChannel('room.1')];
|
||||
return [new PresenceChannel('room.'.$this->roomId)];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,6 +67,7 @@ class HorseRaceProgress implements ShouldBroadcastNow
|
||||
{
|
||||
return [
|
||||
'race_id' => $this->raceId,
|
||||
'room_id' => $this->roomId,
|
||||
'positions' => $this->positions,
|
||||
'finished' => $this->finished,
|
||||
'leader_id' => $this->leaderId,
|
||||
|
||||
@@ -46,7 +46,7 @@ class HorseRaceSettled implements ShouldBroadcastNow
|
||||
*/
|
||||
public function broadcastOn(): array
|
||||
{
|
||||
return [new PresenceChannel('room.1')];
|
||||
return [new PresenceChannel('room.'.$this->race->room_id)];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -94,6 +94,7 @@ class HorseRaceSettled implements ShouldBroadcastNow
|
||||
|
||||
return [
|
||||
'race_id' => $this->race->id,
|
||||
'room_id' => (int) $this->race->room_id,
|
||||
'winner_horse_id' => $this->race->winner_horse_id,
|
||||
'winner_name' => $winnerName,
|
||||
'total_pool' => (int) $this->race->total_pool,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:猜谜活动答题结果广播事件
|
||||
*
|
||||
* 用户答对题目时广播,通知房间内所有用户结果。
|
||||
*/
|
||||
|
||||
namespace App\Events;
|
||||
|
||||
use Illuminate\Broadcasting\InteractsWithSockets;
|
||||
use Illuminate\Broadcasting\PresenceChannel;
|
||||
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* 类功能:向指定房间广播猜谜活动答题结果。
|
||||
*/
|
||||
class RiddleGameAnswered implements ShouldBroadcastNow
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
|
||||
/**
|
||||
* 方法功能:构造答题成功广播事件载荷。
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $roomId,
|
||||
public readonly int $roundId,
|
||||
public readonly string $quizType,
|
||||
public readonly string $answer,
|
||||
public readonly string $winnerUsername,
|
||||
public readonly int $rewardGold = 0,
|
||||
public readonly int $rewardExp = 0,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 方法功能:声明广播频道。
|
||||
*/
|
||||
public function broadcastOn(): array
|
||||
{
|
||||
return [
|
||||
new PresenceChannel('room.'.$this->roomId),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:声明广播数据。
|
||||
*/
|
||||
public function broadcastWith(): array
|
||||
{
|
||||
$quizTypeLabel = \App\Models\Riddle::labelForType($this->quizType);
|
||||
|
||||
return [
|
||||
'round_id' => $this->roundId,
|
||||
'quiz_type' => $this->quizType,
|
||||
'quiz_type_label' => $quizTypeLabel,
|
||||
'quiz_round_id' => $this->roundId,
|
||||
'quiz_answer' => $this->answer,
|
||||
'quiz_reward_gold' => $this->rewardGold,
|
||||
'quiz_reward_exp' => $this->rewardExp,
|
||||
'quiz_round_ended_id' => $this->roundId,
|
||||
'answer' => $this->answer,
|
||||
'winner_username' => $this->winnerUsername,
|
||||
'reward_gold' => $this->rewardGold,
|
||||
'reward_exp' => $this->rewardExp,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:猜谜活动开始广播事件
|
||||
*
|
||||
* 管理员手动出题或系统自动出题时触发,广播提示到聊天室。
|
||||
*/
|
||||
|
||||
namespace App\Events;
|
||||
|
||||
use Illuminate\Broadcasting\InteractsWithSockets;
|
||||
use Illuminate\Broadcasting\PresenceChannel;
|
||||
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* 类功能:向指定房间广播新一轮猜谜活动题目。
|
||||
*/
|
||||
class RiddleGameStarted implements ShouldBroadcastNow
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
|
||||
/**
|
||||
* 方法功能:构造新回合广播事件载荷。
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $roomId,
|
||||
public readonly string $quizType,
|
||||
public readonly string $hint,
|
||||
public readonly int $roundId,
|
||||
public readonly int $rewardGold = 0,
|
||||
public readonly int $rewardExp = 0,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 方法功能:声明广播频道。
|
||||
*/
|
||||
public function broadcastOn(): array
|
||||
{
|
||||
return [
|
||||
new PresenceChannel('room.'.$this->roomId),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:声明广播数据。
|
||||
*/
|
||||
public function broadcastWith(): array
|
||||
{
|
||||
$quizTypeLabel = \App\Models\Riddle::labelForType($this->quizType);
|
||||
|
||||
return [
|
||||
'round_id' => $this->roundId,
|
||||
'quiz_type' => $this->quizType,
|
||||
'quiz_type_label' => $quizTypeLabel,
|
||||
'quiz_round_id' => $this->roundId,
|
||||
'quiz_hint' => $this->hint,
|
||||
'quiz_reward_gold' => $this->rewardGold,
|
||||
'quiz_reward_exp' => $this->rewardExp,
|
||||
'hint' => $this->hint,
|
||||
'reward_gold' => $this->rewardGold,
|
||||
'reward_exp' => $this->rewardExp,
|
||||
'message' => "📣 【猜谜活动·{$quizTypeLabel}】第 #{$this->roundId} 题开始!题面:{$this->hint}",
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:用户"拍一拍"广播事件
|
||||
*
|
||||
* 用户输入 /拍一拍 用户名 后触发,通过 WebSocket 广播给房间内所有用户,
|
||||
* 前端显示 "XXX拍了拍XXX" 消息并触发屏幕抖动动画。
|
||||
*
|
||||
* @author ChatRoom Laravel
|
||||
*
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
namespace App\Events;
|
||||
|
||||
use Illuminate\Broadcasting\InteractsWithSockets;
|
||||
use Illuminate\Broadcasting\PresenceChannel;
|
||||
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class UserPat implements ShouldBroadcastNow
|
||||
{
|
||||
use Dispatchable, InteractsWithSockets, SerializesModels;
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
*
|
||||
* @param int $roomId 房间 ID
|
||||
* @param string $fromUser 拍人的用户
|
||||
* @param string $targetUser 被拍的用户
|
||||
* @param string $displayText 前端展示文本,如 "流星 拍了拍 张三"
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $roomId,
|
||||
public readonly string $fromUser,
|
||||
public readonly string $targetUser,
|
||||
public readonly string $displayText,
|
||||
public readonly ?string $fromUserHeadface = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 广播频道:向房间内所有在线用户推送
|
||||
*
|
||||
* @return array<int, \Illuminate\Broadcasting\Channel>
|
||||
*/
|
||||
public function broadcastOn(): array
|
||||
{
|
||||
return [
|
||||
new PresenceChannel('room.'.$this->roomId),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 广播数据
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function broadcastWith(): array
|
||||
{
|
||||
return [
|
||||
'from_user' => $this->fromUser,
|
||||
'target_user' => $this->targetUser,
|
||||
'display_text' => $this->displayText,
|
||||
'from_user_headface' => $this->fromUserHeadface,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -14,14 +14,20 @@
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\UpdateGameConfigParamsRequest;
|
||||
use App\Models\GameConfig;
|
||||
use App\Models\LotteryIssue;
|
||||
use App\Models\Room;
|
||||
use App\Services\GameRoomScopeService;
|
||||
use App\Services\LotteryService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
/**
|
||||
* 类功能:统一处理后台游戏开关、参数保存与手动操作入口。
|
||||
*/
|
||||
class GameConfigController extends Controller
|
||||
{
|
||||
/**
|
||||
@@ -30,8 +36,9 @@ class GameConfigController extends Controller
|
||||
public function index(): View
|
||||
{
|
||||
$games = GameConfig::orderBy('id')->get();
|
||||
$availableRooms = Room::query()->orderBy('id')->get();
|
||||
|
||||
return view('admin.game-configs.index', compact('games'));
|
||||
return view('admin.game-configs.index', compact('games', 'availableRooms'));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,15 +63,19 @@ class GameConfigController extends Controller
|
||||
*
|
||||
* 接收前端提交的 params JSON 对象并合并至现有配置。
|
||||
*/
|
||||
public function updateParams(Request $request, GameConfig $gameConfig): RedirectResponse
|
||||
public function updateParams(UpdateGameConfigParamsRequest $request, GameConfig $gameConfig, GameRoomScopeService $roomScopeService): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'params' => 'required|array',
|
||||
]);
|
||||
|
||||
// 合并参数,保留已有键,只更新传入的键
|
||||
$current = $gameConfig->params ?? [];
|
||||
$updated = array_merge($current, $request->input('params'));
|
||||
// 这里不能只读取 validated('params')。
|
||||
// 当前请求类只对公共房间字段做了显式规则约束,像 fishing_cooldown 这类普通游戏参数
|
||||
// 在 validated 数据中会被裁掉,导致后台提示成功但实际没有写入数据库。
|
||||
$validatedParams = (array) $request->input('params', []);
|
||||
$updated = array_merge($current, $validatedParams);
|
||||
|
||||
$scopeConfig = $roomScopeService->getScopeConfigForParams($validatedParams);
|
||||
$updated['room_scope_mode'] = $scopeConfig['room_scope_mode'];
|
||||
$updated['room_ids'] = $scopeConfig['room_ids'];
|
||||
|
||||
if ($gameConfig->game_key === 'mystery_box') {
|
||||
$legacyMap = [
|
||||
@@ -107,17 +118,19 @@ class GameConfigController extends Controller
|
||||
}
|
||||
|
||||
// 检查是否有正在开放的箱子(避免同时多个)
|
||||
if (\App\Models\MysteryBox::currentOpenBox()) {
|
||||
$targetRoomId = app(GameRoomScopeService::class)->getPrimaryRoomIdForGame('mystery_box');
|
||||
|
||||
if (\App\Models\MysteryBox::currentOpenBox($targetRoomId)) {
|
||||
return response()->json(['ok' => false, 'message' => '当前已有一个神秘箱子正在等待领取,请等它结束后再投放。']);
|
||||
}
|
||||
|
||||
\App\Jobs\DropMysteryBoxJob::dispatch($boxType, 1, null, (int) auth()->id());
|
||||
\App\Jobs\DropMysteryBoxJob::dispatch($boxType, $targetRoomId, null, (int) auth()->id());
|
||||
|
||||
$typeNames = ['normal' => '普通箱', 'rare' => '稀有箱', 'trap' => '黑化箱'];
|
||||
|
||||
return response()->json([
|
||||
'ok' => true,
|
||||
'message' => "✅ 已投放「{$typeNames[$boxType]}」到 #1 房间,暗号将实时发送到公屏!",
|
||||
'message' => "✅ 已投放「{$typeNames[$boxType]}」到 #{$targetRoomId} 房间,暗号将实时发送到公屏!",
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -126,19 +139,31 @@ class GameConfigController extends Controller
|
||||
*
|
||||
* 仅在当前无进行中期次时生效,防止重复开期。
|
||||
*/
|
||||
public function openLotteryIssue(): JsonResponse
|
||||
public function openLotteryIssue(GameRoomScopeService $roomScopeService): JsonResponse
|
||||
{
|
||||
if (! GameConfig::isEnabled('lottery')) {
|
||||
return response()->json(['ok' => false, 'message' => '双色球彩票未开启,请先开启游戏。']);
|
||||
}
|
||||
|
||||
if (LotteryIssue::currentIssue()) {
|
||||
return response()->json(['ok' => false, 'message' => '当前已有进行中的期次,无需重复开期。']);
|
||||
$openedRoomIds = [];
|
||||
|
||||
foreach ($roomScopeService->getScopedRoomIdsForGame('lottery') as $roomId) {
|
||||
if (LotteryIssue::currentIssue($roomId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
\App\Jobs\OpenLotteryIssueJob::dispatch($roomId);
|
||||
$openedRoomIds[] = $roomId;
|
||||
}
|
||||
|
||||
\App\Jobs\OpenLotteryIssueJob::dispatch();
|
||||
if ($openedRoomIds === []) {
|
||||
return response()->json(['ok' => false, 'message' => '目标房间当前已有进行中的期次,无需重复开期。']);
|
||||
}
|
||||
|
||||
return response()->json(['ok' => true, 'message' => '✅ 已排队开期任务,新期次将就绪建立!']);
|
||||
return response()->json([
|
||||
'ok' => true,
|
||||
'message' => '✅ 已排队开期任务,目标房间:#'.implode('、#', $openedRoomIds),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:猜谜活动题库后台管理控制器
|
||||
*
|
||||
* 负责后台题库的列表筛选、题目增删改和启用状态切换。
|
||||
*/
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Riddle;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\View\View;
|
||||
|
||||
/**
|
||||
* 类功能:统一处理猜谜活动题库的后台管理动作。
|
||||
*/
|
||||
class RiddleController extends Controller
|
||||
{
|
||||
/**
|
||||
* 方法功能:显示题库列表,并支持按题型和关键词筛选。
|
||||
*/
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$typeOptions = Riddle::typeOptions();
|
||||
$selectedType = trim((string) $request->query('type', ''));
|
||||
$keyword = trim((string) $request->query('keyword', ''));
|
||||
|
||||
$idiomQuery = Riddle::query();
|
||||
|
||||
if ($selectedType !== '' && isset($typeOptions[$selectedType])) {
|
||||
// 题型筛选只接受系统支持值,避免非法参数污染查询。
|
||||
$idiomQuery->ofType($selectedType);
|
||||
}
|
||||
|
||||
if ($keyword !== '') {
|
||||
// 关键词同时匹配答案与提示,方便后台快速定位题目。
|
||||
$idiomQuery->where(function ($query) use ($keyword): void {
|
||||
$query->where('answer', 'like', '%'.$keyword.'%')
|
||||
->orWhere('hint', 'like', '%'.$keyword.'%');
|
||||
});
|
||||
}
|
||||
|
||||
$idioms = $idiomQuery
|
||||
->orderBy('type')
|
||||
->orderBy('sort')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
|
||||
$typeStats = Riddle::query()
|
||||
->selectRaw('type, COUNT(*) as total')
|
||||
->groupBy('type')
|
||||
->pluck('total', 'type')
|
||||
->all();
|
||||
|
||||
return view('admin.riddles.index', [
|
||||
'idioms' => $idioms,
|
||||
'typeOptions' => $typeOptions,
|
||||
'selectedType' => $selectedType,
|
||||
'keyword' => $keyword,
|
||||
'typeStats' => $typeStats,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:创建新的猜谜活动题目。
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$data = $this->validateRiddlePayload($request);
|
||||
|
||||
// 新增时默认启用,便于后台批量补题后立即可用。
|
||||
$data['is_active'] = $request->boolean('is_active', true);
|
||||
Riddle::create($data);
|
||||
|
||||
$typeLabel = Riddle::labelForType($data['type']);
|
||||
|
||||
return redirect()
|
||||
->route('admin.riddles.index', $this->buildIndexFilters($request))
|
||||
->with('success', "{$typeLabel}题目已添加!");
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:更新已有题目内容与题型。
|
||||
*/
|
||||
public function update(Request $request, Riddle $idiom): RedirectResponse
|
||||
{
|
||||
$data = $this->validateRiddlePayload($request);
|
||||
|
||||
// 编辑时显式按复选框结果落库,避免旧状态残留。
|
||||
$data['is_active'] = $request->boolean('is_active');
|
||||
$idiom->update($data);
|
||||
|
||||
return redirect()
|
||||
->route('admin.riddles.index', $this->buildIndexFilters($request))
|
||||
->with('success', "题目「{$idiom->answer}」已更新!");
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:通过 AJAX 切换题目的启用状态。
|
||||
*/
|
||||
public function toggle(Riddle $idiom): JsonResponse
|
||||
{
|
||||
// 开关按钮只变更启用状态,不改动其他题库字段。
|
||||
$idiom->update(['is_active' => ! $idiom->is_active]);
|
||||
|
||||
return response()->json([
|
||||
'ok' => true,
|
||||
'is_active' => $idiom->is_active,
|
||||
'message' => $idiom->is_active ? "「{$idiom->answer}」已启用" : "「{$idiom->answer}」已禁用",
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:删除指定题目。
|
||||
*/
|
||||
public function destroy(Request $request, Riddle $idiom): RedirectResponse
|
||||
{
|
||||
$answer = $idiom->answer;
|
||||
$idiom->delete();
|
||||
|
||||
return redirect()
|
||||
->route('admin.riddles.index', $this->buildIndexFilters($request))
|
||||
->with('success', "题目「{$answer}」已删除!");
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:校验后台题库保存载荷。
|
||||
*
|
||||
* @return array{type:string,answer:string,hint:string,sort:int}
|
||||
*/
|
||||
private function validateRiddlePayload(Request $request): array
|
||||
{
|
||||
return $request->validate([
|
||||
'type' => ['required', 'string', Rule::in(Riddle::supportedTypes())],
|
||||
'answer' => ['required', 'string', 'max:120'],
|
||||
'hint' => ['required', 'string', 'max:255'],
|
||||
'sort' => ['required', 'integer', 'min:0'],
|
||||
'is_active' => ['sometimes', 'boolean'],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:保留列表筛选参数,方便后台操作后返回原筛选结果。
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function buildIndexFilters(Request $request): array
|
||||
{
|
||||
$filters = [];
|
||||
$type = trim((string) $request->input('redirect_type', $request->query('type', '')));
|
||||
$keyword = trim((string) $request->input('redirect_keyword', $request->query('keyword', '')));
|
||||
|
||||
if ($type !== '') {
|
||||
$filters['type'] = $type;
|
||||
}
|
||||
|
||||
if ($keyword !== '') {
|
||||
$filters['keyword'] = $keyword;
|
||||
}
|
||||
|
||||
return $filters;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:后台座驾独立管理控制器。
|
||||
*
|
||||
* 提供座驾列表、新增、编辑、上下架切换与删除能力,不依赖商店商品模块。
|
||||
*/
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\StoreRideRequest;
|
||||
use App\Http\Requests\UpdateRideRequest;
|
||||
use App\Models\Ride;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\View\View;
|
||||
|
||||
/**
|
||||
* 后台座驾管理控制器
|
||||
* 负责独立 rides 表的后台管理流程。
|
||||
*/
|
||||
class RideController extends Controller
|
||||
{
|
||||
/**
|
||||
* 显示座驾管理列表页。
|
||||
*/
|
||||
public function index(): View
|
||||
{
|
||||
$rides = Ride::query()
|
||||
->orderBy('sort_order')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
|
||||
return view('admin.rides.index', compact('rides'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增座驾(仅 id=1 超级站长)。
|
||||
*/
|
||||
public function store(StoreRideRequest $request): RedirectResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
Ride::create($data);
|
||||
|
||||
return redirect()->route('admin.rides.index')->with('success', '座驾「'.$data['name'].'」创建成功!');
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新座驾信息。
|
||||
*/
|
||||
public function update(UpdateRideRequest $request, Ride $ride): RedirectResponse
|
||||
{
|
||||
$ride->update($request->validated());
|
||||
|
||||
return redirect()->route('admin.rides.index')->with('success', '座驾「'.$ride->name.'」更新成功!');
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换座驾上下架状态。
|
||||
*/
|
||||
public function toggle(Ride $ride): RedirectResponse
|
||||
{
|
||||
$ride->update(['is_active' => ! $ride->is_active]);
|
||||
$status = $ride->is_active ? '上架' : '下架';
|
||||
|
||||
return redirect()->route('admin.rides.index')->with('success', "「{$ride->name}」已{$status}。");
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除座驾(仅 id=1 超级站长)。
|
||||
*/
|
||||
public function destroy(Ride $ride): RedirectResponse
|
||||
{
|
||||
abort_unless(Auth::id() === 1, 403);
|
||||
|
||||
$name = $ride->name;
|
||||
$ride->delete();
|
||||
|
||||
return redirect()->route('admin.rides.index')->with('success', "「{$name}」已删除。");
|
||||
}
|
||||
}
|
||||
@@ -14,9 +14,10 @@
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\StoreShopItemRequest;
|
||||
use App\Http\Requests\UpdateShopItemRequest;
|
||||
use App\Models\ShopItem;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\View\View;
|
||||
|
||||
@@ -35,11 +36,9 @@ class ShopItemController extends Controller
|
||||
/**
|
||||
* 新增商品(仅 id=1 超级站长)
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
public function store(StoreShopItemRequest $request): RedirectResponse
|
||||
{
|
||||
abort_unless(Auth::id() === 1, 403);
|
||||
|
||||
$data = $this->validateItem($request);
|
||||
$data = $request->validated();
|
||||
ShopItem::create($data);
|
||||
|
||||
return redirect()->route('admin.shop.index')->with('success', '商品「'.$data['name'].'」创建成功!');
|
||||
@@ -50,9 +49,9 @@ class ShopItemController extends Controller
|
||||
*
|
||||
* @param ShopItem $shopItem 路由模型自动注入
|
||||
*/
|
||||
public function update(Request $request, ShopItem $shopItem): RedirectResponse
|
||||
public function update(UpdateShopItemRequest $request, ShopItem $shopItem): RedirectResponse
|
||||
{
|
||||
$data = $this->validateItem($request, $shopItem);
|
||||
$data = $request->validated();
|
||||
$shopItem->update($data);
|
||||
|
||||
return redirect()->route('admin.shop.index')->with('success', '商品「'.$shopItem->name.'」更新成功!');
|
||||
@@ -85,29 +84,4 @@ class ShopItemController extends Controller
|
||||
|
||||
return redirect()->route('admin.shop.index')->with('success', "「{$name}」已删除。");
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一验证商品表单(新增/编辑共用)
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function validateItem(Request $request, ?ShopItem $item = null): array
|
||||
{
|
||||
return $request->validate([
|
||||
'name' => 'required|string|max:100',
|
||||
'slug' => ['required', 'string', 'max:100',
|
||||
\Illuminate\Validation\Rule::unique('shop_items', 'slug')->ignore($item?->id),
|
||||
],
|
||||
'icon' => 'required|string|max:20',
|
||||
'description' => 'nullable|string|max:500',
|
||||
'price' => 'required|integer|min:0',
|
||||
'type' => 'required|in:instant,duration,one_time,ring,auto_fishing,sign_repair,msg_bubble,msg_name_color,msg_text_color,avatar_frame',
|
||||
'duration_days' => 'nullable|integer|min:0',
|
||||
'duration_minutes' => 'nullable|integer|min:0',
|
||||
'intimacy_bonus' => 'nullable|integer|min:0',
|
||||
'charm_bonus' => 'nullable|integer|min:0',
|
||||
'sort_order' => 'required|integer|min:0',
|
||||
'is_active' => 'boolean',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -524,6 +524,13 @@ class AdminCommandController extends Controller
|
||||
'font_color' => '#b91c1c',
|
||||
'action' => '',
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
'toast_notification' => [
|
||||
'title' => '📢 公屏公告',
|
||||
'message' => strip_tags($content),
|
||||
'icon' => '📢',
|
||||
'color' => '#b91c1c',
|
||||
'duration' => 10000,
|
||||
],
|
||||
];
|
||||
$this->chatState->pushMessage($roomId, $msg);
|
||||
broadcast(new MessageSent($roomId, $msg));
|
||||
|
||||
@@ -20,16 +20,21 @@ use App\Models\BaccaratBet;
|
||||
use App\Models\BaccaratRound;
|
||||
use App\Models\GameConfig;
|
||||
use App\Services\BaccaratLossCoverService;
|
||||
use App\Services\GameRoomScopeService;
|
||||
use App\Services\UserCurrencyService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* 类功能:提供百家乐当前局查询、下注与历史接口。
|
||||
*/
|
||||
class BaccaratController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly UserCurrencyService $currency,
|
||||
private readonly BaccaratLossCoverService $lossCoverService,
|
||||
private readonly GameRoomScopeService $roomScopeService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -38,7 +43,13 @@ class BaccaratController extends Controller
|
||||
public function currentRound(Request $request): JsonResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$round = BaccaratRound::currentRound();
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request, $user);
|
||||
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('baccarat', $roomId)) {
|
||||
return response()->json(['round' => null, 'jjb' => (int) ($user->jjb ?? 0)]);
|
||||
}
|
||||
|
||||
$round = BaccaratRound::currentRound($roomId);
|
||||
|
||||
if (! $round) {
|
||||
return response()->json([
|
||||
@@ -98,6 +109,11 @@ class BaccaratController extends Controller
|
||||
'bet_type' => 'required|in:big,small,triple',
|
||||
'amount' => 'required|integer|min:1',
|
||||
]);
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request, $request->user());
|
||||
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('baccarat', $roomId)) {
|
||||
return response()->json(['ok' => false, 'message' => '当前房间未开启百家乐。'], 403);
|
||||
}
|
||||
|
||||
$config = GameConfig::forGame('baccarat')?->params ?? [];
|
||||
$minBet = (int) ($config['min_bet'] ?? 100);
|
||||
@@ -109,7 +125,7 @@ class BaccaratController extends Controller
|
||||
|
||||
$round = BaccaratRound::find($data['round_id']);
|
||||
|
||||
if (! $round || ! $round->isBettingOpen()) {
|
||||
if (! $round || (int) $round->room_id !== $roomId || ! $round->isBettingOpen()) {
|
||||
return response()->json(['ok' => false, 'message' => '当前不在下注时间内。']);
|
||||
}
|
||||
|
||||
@@ -212,7 +228,9 @@ class BaccaratController extends Controller
|
||||
*/
|
||||
public function history(): JsonResponse
|
||||
{
|
||||
$roomId = $this->roomScopeService->resolveUserRoomId(auth()->user());
|
||||
$rounds = BaccaratRound::query()
|
||||
->where('room_id', $roomId)
|
||||
->where('status', 'settled')
|
||||
->orderByDesc('id')
|
||||
->limit(10)
|
||||
|
||||
@@ -28,6 +28,7 @@ use App\Services\ChatStateService;
|
||||
use App\Services\ChatUserPresenceService;
|
||||
use App\Services\MessageFilterService;
|
||||
use App\Services\PositionPermissionService;
|
||||
use App\Services\RideService;
|
||||
use App\Services\RoomBroadcastService;
|
||||
use App\Services\UserCurrencyService;
|
||||
use App\Services\VipService;
|
||||
@@ -65,6 +66,7 @@ class ChatController extends Controller
|
||||
private readonly AppointmentService $appointmentService,
|
||||
private readonly RoomBroadcastService $broadcast,
|
||||
private readonly PositionPermissionService $positionPermissionService,
|
||||
private readonly RideService $rideService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -116,6 +118,8 @@ class ChatController extends Controller
|
||||
|
||||
// 3. 广播和初始化欢迎(仅限初次进入)
|
||||
$newbieEffect = null;
|
||||
$initialRideEffect = null;
|
||||
$initialRideEffectOptions = null;
|
||||
$initialPresenceTheme = null;
|
||||
$initialWelcomeMessage = null;
|
||||
$initialWelcomeMessages = [];
|
||||
@@ -192,40 +196,84 @@ class ChatController extends Controller
|
||||
}
|
||||
|
||||
// 统一走通用进场播报逻辑,管理员不再发送单独的特殊登录提示。
|
||||
[$text, $color] = $this->broadcast->buildEntryBroadcast($user);
|
||||
$vipPresencePayload = $this->broadcast->buildVipPresencePayload($user, 'join');
|
||||
$ridePresencePayload = $this->rideService->buildPresencePayload($user);
|
||||
if (! $ridePresencePayload) {
|
||||
[$text, $color] = $this->broadcast->buildEntryBroadcast($user);
|
||||
$vipPresencePayload = $this->broadcast->buildVipPresencePayload($user, 'join');
|
||||
|
||||
$generalWelcomeMsg = [
|
||||
'id' => $this->chatState->nextMessageId($id),
|
||||
'room_id' => $id,
|
||||
'from_user' => '进出播报',
|
||||
'to_user' => '大家',
|
||||
'content' => "<span style=\"color: {$color}; font-weight: bold;\">{$text}</span>",
|
||||
'is_secret' => false,
|
||||
'font_color' => $color,
|
||||
'action' => empty($vipPresencePayload) ? 'system_welcome' : 'vip_presence',
|
||||
'welcome_user' => $user->username,
|
||||
'welcome_kind' => 'entry_broadcast',
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
$generalWelcomeMsg = [
|
||||
'id' => $this->chatState->nextMessageId($id),
|
||||
'room_id' => $id,
|
||||
'from_user' => '进出播报',
|
||||
'to_user' => '大家',
|
||||
'content' => "<span style=\"color: {$color}; font-weight: bold;\">{$text}</span>",
|
||||
'is_secret' => false,
|
||||
'font_color' => $color,
|
||||
'action' => empty($vipPresencePayload) ? 'system_welcome' : 'vip_presence',
|
||||
'welcome_user' => $user->username,
|
||||
'welcome_kind' => 'entry_broadcast',
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
|
||||
// 当会员等级带有专属主题时,把横幅与特效字段并入系统消息,供前端展示豪华进场效果。
|
||||
if (! empty($vipPresencePayload)) {
|
||||
$generalWelcomeMsg = array_merge($generalWelcomeMsg, $vipPresencePayload);
|
||||
$initialPresenceTheme = $vipPresencePayload;
|
||||
// 当会员等级带有专属主题时,把横幅与特效字段并入系统消息,供前端展示豪华进场效果。
|
||||
if (! empty($vipPresencePayload)) {
|
||||
$generalWelcomeMsg = array_merge($generalWelcomeMsg, $vipPresencePayload);
|
||||
$initialPresenceTheme = $vipPresencePayload;
|
||||
}
|
||||
|
||||
// 把当前这次进房生成的欢迎消息带回前端,确保用户自己也一定能看到。
|
||||
$initialWelcomeMessage = $generalWelcomeMsg;
|
||||
$initialWelcomeMessages[] = $generalWelcomeMsg;
|
||||
|
||||
$this->chatState->pushMessage($id, $generalWelcomeMsg);
|
||||
// 修复:之前使用了 ->toOthers() 导致自己看不到自己的进场提示
|
||||
broadcast(new MessageSent($id, $generalWelcomeMsg));
|
||||
|
||||
// 会员专属特效需要单独广播给其他在线成员,自己则在页面初始化后本地补播。
|
||||
if (! empty($vipPresencePayload['presence_effect'])) {
|
||||
broadcast(new \App\Events\EffectBroadcast($id, $vipPresencePayload['presence_effect'], $user->username))->toOthers();
|
||||
}
|
||||
}
|
||||
|
||||
// 把当前这次进房生成的欢迎消息带回前端,确保用户自己也一定能看到。
|
||||
$initialWelcomeMessage = $generalWelcomeMsg;
|
||||
$initialWelcomeMessages[] = $generalWelcomeMsg;
|
||||
if ($ridePresencePayload) {
|
||||
$rideWelcomeMsg = [
|
||||
'id' => $this->chatState->nextMessageId($id),
|
||||
'room_id' => $id,
|
||||
'from_user' => '座驾播报',
|
||||
'to_user' => '大家',
|
||||
'content' => "<span style=\"color:#0f766e;font-weight:bold;\">{$ridePresencePayload['ride_icon']} {$ridePresencePayload['identity_text']} · {$ridePresencePayload['welcome_text']}</span>",
|
||||
'is_secret' => false,
|
||||
'font_color' => '#0f766e',
|
||||
'action' => 'ride_presence',
|
||||
'welcome_user' => $user->username,
|
||||
'welcome_kind' => 'ride_presence',
|
||||
'ride_key' => $ridePresencePayload['ride_key'],
|
||||
'ride_name' => $ridePresencePayload['ride_name'],
|
||||
'effect_title' => $ridePresencePayload['effect_title'],
|
||||
'effect_user_info' => $ridePresencePayload['effect_user_info'],
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
|
||||
$this->chatState->pushMessage($id, $generalWelcomeMsg);
|
||||
// 修复:之前使用了 ->toOthers() 导致自己看不到自己的进场提示
|
||||
broadcast(new MessageSent($id, $generalWelcomeMsg));
|
||||
// 座驾进场独立追加一条播报,并广播全屏特效给其他在线用户。
|
||||
$this->chatState->pushMessage($id, $rideWelcomeMsg);
|
||||
broadcast(new MessageSent($id, $rideWelcomeMsg));
|
||||
broadcast(new \App\Events\EffectBroadcast(
|
||||
$id,
|
||||
$ridePresencePayload['ride_key'],
|
||||
$user->username,
|
||||
effectTitle: $ridePresencePayload['effect_title'],
|
||||
rideName: $ridePresencePayload['ride_name'],
|
||||
effectUserInfo: $ridePresencePayload['effect_user_info'],
|
||||
))->toOthers();
|
||||
|
||||
// 会员专属特效需要单独广播给其他在线成员,自己则在页面初始化后本地补播。
|
||||
if (! empty($vipPresencePayload['presence_effect'])) {
|
||||
broadcast(new \App\Events\EffectBroadcast($id, $vipPresencePayload['presence_effect'], $user->username))->toOthers();
|
||||
$initialRideEffect = $ridePresencePayload['ride_key'];
|
||||
$initialRideEffectOptions = [
|
||||
'effect_title' => $ridePresencePayload['effect_title'],
|
||||
'effect_user_info' => $ridePresencePayload['effect_user_info'],
|
||||
'ride_name' => $ridePresencePayload['ride_name'],
|
||||
'operator' => $user->username,
|
||||
];
|
||||
$initialWelcomeMessages[] = $rideWelcomeMsg;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,6 +362,8 @@ class ChatController extends Controller
|
||||
'user' => $user,
|
||||
'weekEffect' => $this->shopService->getActiveWeekEffect($user),
|
||||
'newbieEffect' => $newbieEffect,
|
||||
'initialRideEffect' => $initialRideEffect,
|
||||
'initialRideEffectOptions' => $initialRideEffectOptions,
|
||||
'initialPresenceTheme' => $initialPresenceTheme,
|
||||
'initialWelcomeMessage' => $initialWelcomeMessage,
|
||||
'initialWelcomeMessages' => $initialWelcomeMessages,
|
||||
@@ -449,6 +499,17 @@ class ChatController extends Controller
|
||||
$messageData = array_merge($messageData, $imagePayload);
|
||||
}
|
||||
|
||||
// 欢迎动作:增加右下角弹窗通知(内容含发送者信息)
|
||||
if (($data['action'] ?? '') === '欢迎') {
|
||||
$messageData['toast_notification'] = [
|
||||
'title' => '👋 欢迎',
|
||||
'message' => strip_tags($pureContent),
|
||||
'icon' => '👋',
|
||||
'color' => '#e11d48',
|
||||
'duration' => 8000,
|
||||
];
|
||||
}
|
||||
|
||||
// 6.5 将用户当前激活的消息装扮注入广播 payload(气泡样式 + 昵称颜色),前端据此渲染消息外观
|
||||
$decorations = app(\App\Services\DecorationService::class)->getDecorationsForMessage($user);
|
||||
$messageData = array_merge($messageData, $decorations);
|
||||
@@ -1404,6 +1465,76 @@ class ChatController extends Controller
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 拍一拍:用户通过 /拍一拍 命令向所选对象发送拍一拍通知。
|
||||
*/
|
||||
public function pat(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
if ($response = $this->ensureUserCanActInRoom($id, $user, '请先进入当前房间后再使用拍一拍。')) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
// 0. 检查用户是否被禁言
|
||||
$muteKey = "mute:{$id}:{$user->username}";
|
||||
if (Redis::exists($muteKey)) {
|
||||
$ttl = Redis::ttl($muteKey);
|
||||
$minutes = ceil($ttl / 60);
|
||||
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => "您正在禁言中,还需等待约 {$minutes} 分钟。",
|
||||
], 403);
|
||||
}
|
||||
|
||||
$targetUser = $request->input('target_user', '');
|
||||
if (empty($targetUser) || $targetUser === '大家') {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => '请选择一个聊天对象(不能为大家)进行拍一拍。',
|
||||
], 422);
|
||||
}
|
||||
|
||||
// 检查目标是否在线
|
||||
$isOnline = Redis::hexists("room:{$id}:users", $targetUser);
|
||||
if (! $isOnline) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => "【{$targetUser}】目前已离开聊天室或不在线。",
|
||||
], 200);
|
||||
}
|
||||
|
||||
// 不能拍自己
|
||||
if ($targetUser === $user->username) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => '不能拍自己哦~',
|
||||
], 422);
|
||||
}
|
||||
|
||||
// 获取发送者头像
|
||||
$headface = $user->usersf ?: '1.gif';
|
||||
$headSrc = str_starts_with($headface, 'storage/') ? '/'.$headface : '/images/headface/'.$headface;
|
||||
|
||||
// 构造展示文本
|
||||
$displayText = "{$user->username} 拍了拍 {$targetUser}";
|
||||
|
||||
// 广播到房间
|
||||
broadcast(new \App\Events\UserPat(
|
||||
roomId: $id,
|
||||
fromUser: $user->username,
|
||||
targetUser: $targetUser,
|
||||
displayText: $displayText,
|
||||
fromUserHeadface: $headSrc,
|
||||
));
|
||||
|
||||
return response()->json([
|
||||
'status' => 'success',
|
||||
'message' => $displayText,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验目标用户是否仍在当前房间在线,避免跨房间赠送和消息注入。
|
||||
*/
|
||||
|
||||
@@ -185,9 +185,10 @@ class DailySignInController extends Controller
|
||||
.',当前连续签到 '.$streakDays.' 天,获得 '.$rewardText.$identityText.'。';
|
||||
}
|
||||
|
||||
// 聊天消息内的快捷按钮使用相对字号,避免覆盖用户选择的消息字号。
|
||||
$quickButton = '<button type="button" onclick="window.quickDailySignIn && window.quickDailySignIn()" '
|
||||
.'style="display:inline-block;margin-left:6px;padding:1px 8px;border:none;border-radius:999px;'
|
||||
.'background:#ccfbf1;color:#0f766e;font-size:10px;font-weight:bold;cursor:pointer;vertical-align:middle;">'
|
||||
.'background:#ccfbf1;color:#0f766e;font-size:0.78em;font-weight:bold;cursor:pointer;vertical-align:middle;">'
|
||||
.'✅ 快速签到</button>';
|
||||
|
||||
return '【'.e($user->username).'】完成今日签到,连续签到 '
|
||||
|
||||
@@ -43,6 +43,11 @@ class EarnController extends Controller
|
||||
*/
|
||||
public function claimVideoReward(Request $request): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => '看视频赚钱功能已关闭。',
|
||||
]);
|
||||
|
||||
/** @var User $user */
|
||||
$user = Auth::user();
|
||||
|
||||
@@ -99,9 +104,10 @@ class EarnController extends Controller
|
||||
|
||||
// 6. 广播全服系统消息
|
||||
if ($roomId > 0) {
|
||||
// 公屏消息内的入口标签使用相对字号,跟随用户在聊天室选择的字号。
|
||||
$promoTag = ' <span onclick="window.dispatchEvent(new CustomEvent(\'open-earn-panel\'))" '
|
||||
.'style="display:inline-block;margin-left:6px;padding:1px 7px;background:#e9e4f5;'
|
||||
.'color:#6d4fa8;border-radius:10px;font-size:10px;cursor:pointer;font-weight:bold;vertical-align:middle;'
|
||||
.'color:#6d4fa8;border-radius:10px;font-size:0.78em;cursor:pointer;font-weight:bold;vertical-align:middle;'
|
||||
.'border:1px solid #d0c4ec;" title="点击赚金币">💰 看视频赚金币</span>';
|
||||
|
||||
$sysMsg = [
|
||||
|
||||
@@ -19,8 +19,10 @@ namespace App\Http\Controllers;
|
||||
use App\Enums\CurrencySource;
|
||||
use App\Models\GameConfig;
|
||||
use App\Models\Sysparam;
|
||||
use App\Models\User;
|
||||
use App\Services\ChatStateService;
|
||||
use App\Services\FishingService;
|
||||
use App\Services\GameRoomScopeService;
|
||||
use App\Services\ShopService;
|
||||
use App\Services\UserCurrencyService;
|
||||
use App\Services\VipService;
|
||||
@@ -30,14 +32,21 @@ use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* 类功能:处理钓鱼小游戏的抛竿与收竿流程。
|
||||
*/
|
||||
class FishingController extends Controller
|
||||
{
|
||||
/**
|
||||
* 注入钓鱼流程需要的状态、会员、金币、商店和房间范围服务。
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly ChatStateService $chatState,
|
||||
private readonly VipService $vipService,
|
||||
private readonly UserCurrencyService $currencyService,
|
||||
private readonly ShopService $shopService,
|
||||
private readonly FishingService $fishingService,
|
||||
private readonly GameRoomScopeService $roomScopeService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -63,6 +72,10 @@ class FishingController extends Controller
|
||||
return response()->json(['status' => 'error', 'message' => '钓鱼功能暂未开放。'], 403);
|
||||
}
|
||||
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('fishing', $id)) {
|
||||
return response()->json(['status' => 'error', 'message' => '当前房间未开启钓鱼小游戏。'], 403);
|
||||
}
|
||||
|
||||
// 1. 检查冷却时间(Redis TTL)
|
||||
$cooldownKey = "fishing:cd:{$user->id}";
|
||||
if (Redis::exists($cooldownKey)) {
|
||||
@@ -75,6 +88,14 @@ class FishingController extends Controller
|
||||
], 429);
|
||||
}
|
||||
|
||||
$tokenKey = "fishing:token:{$user->id}";
|
||||
if (Redis::exists($tokenKey)) {
|
||||
$activeSessionResponse = $this->restoreActiveFishingSessionResponse($user, $tokenKey);
|
||||
if ($activeSessionResponse) {
|
||||
return $activeSessionResponse;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 检查金币是否足够
|
||||
$cost = (int) (GameConfig::param('fishing', 'fishing_cost') ?? Sysparam::getValue('fishing_cost', '5'));
|
||||
if (($user->jjb ?? 0) < $cost) {
|
||||
@@ -84,34 +105,54 @@ class FishingController extends Controller
|
||||
], 422);
|
||||
}
|
||||
|
||||
// 3. 扣除金币
|
||||
$this->currencyService->change(
|
||||
$user, 'gold', -$cost,
|
||||
CurrencySource::FISHING_COST,
|
||||
"钓鱼抛竿消耗 {$cost} 金币",
|
||||
$id,
|
||||
);
|
||||
$user->refresh();
|
||||
|
||||
// 4. 生成一次性 token,存入 Redis(TTL = 等待时间 + 收竿窗口 + 缓冲)
|
||||
// 3. 生成一次性 token,存入 Redis(TTL = 等待时间 + 收竿窗口 + 缓冲)
|
||||
$waitMin = (int) (GameConfig::param('fishing', 'fishing_wait_min') ?? Sysparam::getValue('fishing_wait_min', '8'));
|
||||
$waitMax = (int) (GameConfig::param('fishing', 'fishing_wait_max') ?? Sysparam::getValue('fishing_wait_max', '15'));
|
||||
$waitTime = rand($waitMin, $waitMax);
|
||||
$token = Str::random(32);
|
||||
$tokenKey = "fishing:token:{$user->id}";
|
||||
// token 有效期 = 等待时间 + 8秒点击窗口 + 5秒缓冲
|
||||
// 同时把 cast 时间戳和 wait_time 一起存入,供 reel 做服务端时间校验
|
||||
Redis::setex($tokenKey, $waitTime + 13, json_encode([
|
||||
$tokenTtl = $waitTime + 13;
|
||||
$tokenPayload = json_encode([
|
||||
'token' => $token,
|
||||
'cast_at' => time(),
|
||||
'wait_time' => $waitTime,
|
||||
]));
|
||||
]);
|
||||
|
||||
// 5. 生成随机浮漂坐标(百分比,避开边缘)
|
||||
// 原子占用本次抛竿 token,避免多标签页自动钓鱼互相覆盖令牌。
|
||||
$reserved = Redis::command('set', [$tokenKey, $tokenPayload, 'EX', $tokenTtl, 'NX']);
|
||||
if (! $reserved) {
|
||||
$activeSessionResponse = $this->restoreActiveFishingSessionResponse($user, $tokenKey);
|
||||
if ($activeSessionResponse) {
|
||||
return $activeSessionResponse;
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => '钓鱼状态同步中,请稍后重试。',
|
||||
'retry_after' => 3,
|
||||
], 409);
|
||||
}
|
||||
|
||||
try {
|
||||
// token 占用成功后才扣金币,确保重复抛竿不会多扣费用。
|
||||
$this->currencyService->change(
|
||||
$user, 'gold', -$cost,
|
||||
CurrencySource::FISHING_COST,
|
||||
"钓鱼抛竿消耗 {$cost} 金币",
|
||||
$id,
|
||||
);
|
||||
$user->refresh();
|
||||
} catch (\Throwable $exception) {
|
||||
// 金币扣除失败时释放 token,避免用户被短时间卡在未收竿状态。
|
||||
Redis::del($tokenKey);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
// 4. 生成随机浮漂坐标(百分比,避开边缘)
|
||||
$bobberX = rand(15, 85); // 左右 15%~85%
|
||||
$bobberY = rand(20, 65); // 上下 20%~65%
|
||||
|
||||
// 6. 检查是否持有有效自动钓鱼卡
|
||||
// 5. 检查是否持有有效自动钓鱼卡
|
||||
$autoFishingMinutes = $this->shopService->getActiveAutoFishingMinutesLeft($user);
|
||||
|
||||
return response()->json([
|
||||
@@ -128,6 +169,37 @@ class FishingController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复已有钓鱼会话,避免刷新页面后丢失前端内存里的收竿令牌。
|
||||
*/
|
||||
private function restoreActiveFishingSessionResponse(User $user, string $tokenKey): ?JsonResponse
|
||||
{
|
||||
$stored = json_decode((string) Redis::get($tokenKey), true);
|
||||
if (! is_array($stored) || empty($stored['token'])) {
|
||||
Redis::del($tokenKey);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$elapsed = time() - (int) ($stored['cast_at'] ?? 0);
|
||||
$waitTime = max(0, (int) ($stored['wait_time'] ?? 0) - $elapsed);
|
||||
$autoFishingMinutes = $this->shopService->getActiveAutoFishingMinutesLeft($user);
|
||||
|
||||
return response()->json([
|
||||
'status' => 'success',
|
||||
'message' => '已恢复正在进行的钓鱼,请等待本次收竿。',
|
||||
'wait_time' => $waitTime,
|
||||
'bobber_x' => rand(15, 85),
|
||||
'bobber_y' => rand(20, 65),
|
||||
'token' => (string) $stored['token'],
|
||||
'auto_fishing' => $autoFishingMinutes > 0,
|
||||
'auto_fishing_minutes_left' => $autoFishingMinutes,
|
||||
'cost' => 0,
|
||||
'jjb' => $user->jjb,
|
||||
'restored' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 收竿 — 验证浮漂 token,随机计算钓鱼结果,更新经验/金币,广播到聊天室。
|
||||
*
|
||||
@@ -142,6 +214,10 @@ class FishingController extends Controller
|
||||
return response()->json(['status' => 'error', 'message' => '请先登录'], 401);
|
||||
}
|
||||
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('fishing', $id)) {
|
||||
return response()->json(['status' => 'error', 'message' => '当前房间未开启钓鱼小游戏。'], 403);
|
||||
}
|
||||
|
||||
// 1. 验证 token + 服务端时间校验(防止前端篡改 wait_time 跳过等待)
|
||||
$tokenKey = "fishing:token:{$user->id}";
|
||||
$storedJson = Redis::get($tokenKey);
|
||||
|
||||
@@ -18,14 +18,19 @@ namespace App\Http\Controllers;
|
||||
use App\Enums\CurrencySource;
|
||||
use App\Models\FortuneLog;
|
||||
use App\Models\GameConfig;
|
||||
use App\Services\GameRoomScopeService;
|
||||
use App\Services\UserCurrencyService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* 类功能:提供神秘占卜状态、抽签和历史接口。
|
||||
*/
|
||||
class FortuneTellingController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly UserCurrencyService $currency,
|
||||
private readonly GameRoomScopeService $roomScopeService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -37,6 +42,11 @@ class FortuneTellingController extends Controller
|
||||
return response()->json(['enabled' => false]);
|
||||
}
|
||||
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request, $request->user());
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('fortune_telling', $roomId)) {
|
||||
return response()->json(['enabled' => false]);
|
||||
}
|
||||
|
||||
$user = $request->user();
|
||||
$config = GameConfig::forGame('fortune_telling')?->params ?? [];
|
||||
|
||||
@@ -81,6 +91,11 @@ class FortuneTellingController extends Controller
|
||||
return response()->json(['ok' => false, 'message' => '神秘占卜当前未开启。']);
|
||||
}
|
||||
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request, $request->user());
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('fortune_telling', $roomId)) {
|
||||
return response()->json(['ok' => false, 'message' => '当前房间未开启神秘占卜。'], 403);
|
||||
}
|
||||
|
||||
$user = $request->user();
|
||||
$config = GameConfig::forGame('fortune_telling')?->params ?? [];
|
||||
|
||||
@@ -145,6 +160,11 @@ class FortuneTellingController extends Controller
|
||||
*/
|
||||
public function history(Request $request): JsonResponse
|
||||
{
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request, $request->user());
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('fortune_telling', $roomId)) {
|
||||
return response()->json(['history' => []]);
|
||||
}
|
||||
|
||||
$logs = FortuneLog::query()
|
||||
->where('user_id', $request->user()->id)
|
||||
->orderByDesc('id')
|
||||
|
||||
@@ -24,17 +24,22 @@ use App\Events\GomokuInviteEvent;
|
||||
use App\Events\GomokuMovedEvent;
|
||||
use App\Models\GameConfig;
|
||||
use App\Models\GomokuGame;
|
||||
use App\Services\GameRoomScopeService;
|
||||
use App\Services\GomokuAiService;
|
||||
use App\Services\UserCurrencyService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* 类功能:处理五子棋创建、加入与对局过程接口。
|
||||
*/
|
||||
class GomokuController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly GomokuAiService $ai,
|
||||
private readonly UserCurrencyService $currency,
|
||||
private readonly GameRoomScopeService $roomScopeService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -58,6 +63,10 @@ class GomokuController extends Controller
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('gomoku', (int) $data['room_id'])) {
|
||||
return response()->json(['ok' => false, 'message' => '当前房间未开启五子棋。'], 403);
|
||||
}
|
||||
|
||||
// PvP:检查是否已在等待/对局中(一次只能参与一场)
|
||||
$activeGame = GomokuGame::query()
|
||||
->where(function ($q) use ($user) {
|
||||
|
||||
@@ -23,15 +23,23 @@ use App\Models\GameConfig;
|
||||
use App\Models\HorseBet;
|
||||
use App\Models\HorseRace;
|
||||
use App\Services\ChatStateService;
|
||||
use App\Services\GameRoomScopeService;
|
||||
use App\Services\UserCurrencyService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* 类功能:赛马竞猜前台控制器
|
||||
*
|
||||
* 负责聊天室赛马玩法的当前场次查询、下注提交、历史记录读取,
|
||||
* 并在发现线上遗留的超时 running 场次时执行最小范围的状态自愈。
|
||||
*/
|
||||
class HorseRaceController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly UserCurrencyService $currency,
|
||||
private readonly GameRoomScopeService $roomScopeService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -44,7 +52,12 @@ class HorseRaceController extends Controller
|
||||
return response()->json(['message' => '未登录', 'status' => 'error'], 401);
|
||||
}
|
||||
|
||||
$race = HorseRace::currentRace();
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request, $user);
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('horse_racing', $roomId)) {
|
||||
return response()->json(['race' => null, 'jjb' => (int) ($user->jjb ?? 0)]);
|
||||
}
|
||||
|
||||
$race = $this->resolveCurrentRaceState(HorseRace::currentRace($roomId));
|
||||
|
||||
if (! $race) {
|
||||
return response()->json([
|
||||
@@ -139,6 +152,11 @@ class HorseRaceController extends Controller
|
||||
'horse_id' => 'required|integer|min:1',
|
||||
'amount' => 'required|integer|min:1',
|
||||
]);
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request, $request->user());
|
||||
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('horse_racing', $roomId)) {
|
||||
return response()->json(['ok' => false, 'message' => '当前房间未开启赛马竞猜。'], 403);
|
||||
}
|
||||
|
||||
$config = GameConfig::forGame('horse_racing')?->params ?? [];
|
||||
$minBet = (int) ($config['min_bet'] ?? 100);
|
||||
@@ -150,7 +168,7 @@ class HorseRaceController extends Controller
|
||||
|
||||
$race = HorseRace::find($data['race_id']);
|
||||
|
||||
if (! $race || ! $race->isBettingOpen()) {
|
||||
if (! $race || (int) $race->room_id !== $roomId || ! $race->isBettingOpen()) {
|
||||
return response()->json(['ok' => false, 'message' => '当前不在下注时间内。']);
|
||||
}
|
||||
|
||||
@@ -207,8 +225,8 @@ class HorseRaceController extends Controller
|
||||
$formattedAmount = number_format($data['amount']);
|
||||
$content = "🐎 <b>【赛马】【{$user->username}】</b> 押注了 <b>{$formattedAmount}</b> 金币({$horseName})!✨";
|
||||
$msg = [
|
||||
'id' => $chatState->nextMessageId(1),
|
||||
'room_id' => 1,
|
||||
'id' => $chatState->nextMessageId((int) $race->room_id),
|
||||
'room_id' => (int) $race->room_id,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => $content,
|
||||
@@ -217,8 +235,8 @@ class HorseRaceController extends Controller
|
||||
'action' => '',
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
$chatState->pushMessage(1, $msg);
|
||||
event(new MessageSent(1, $msg));
|
||||
$chatState->pushMessage((int) $race->room_id, $msg);
|
||||
event(new MessageSent((int) $race->room_id, $msg));
|
||||
SaveMessageJob::dispatch($msg);
|
||||
|
||||
return response()->json([
|
||||
@@ -235,7 +253,9 @@ class HorseRaceController extends Controller
|
||||
*/
|
||||
public function history(): JsonResponse
|
||||
{
|
||||
$roomId = $this->roomScopeService->resolveUserRoomId(auth()->user());
|
||||
$races = HorseRace::query()
|
||||
->where('room_id', $roomId)
|
||||
->where('status', 'settled')
|
||||
->orderByDesc('id')
|
||||
->limit(10)
|
||||
@@ -264,6 +284,119 @@ class HorseRaceController extends Controller
|
||||
return response()->json(['history' => $history]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自愈当前场次状态,避免线上遗漏结算时长期卡在 running。
|
||||
*/
|
||||
private function resolveCurrentRaceState(?HorseRace $race): ?HorseRace
|
||||
{
|
||||
if (! $race || $race->status !== 'running') {
|
||||
return $race;
|
||||
}
|
||||
|
||||
if (! $this->shouldRecoverStaleRunningRace($race)) {
|
||||
return $race;
|
||||
}
|
||||
|
||||
$race = $this->prepareRunningRaceForSettlement($race);
|
||||
if (! $race || $race->status !== 'running' || ! $race->winner_horse_id) {
|
||||
return $race;
|
||||
}
|
||||
|
||||
// 线上若漏消费 CloseHorseRaceJob,这里同步补做一次结算,避免界面一直显示“跑马中”。
|
||||
app()->call([new \App\Jobs\CloseHorseRaceJob($race), 'handle']);
|
||||
|
||||
return HorseRace::currentRace((int) $race->room_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 running 场次是否已经超过合理比赛时长,需要请求侧补偿收尾。
|
||||
*/
|
||||
private function shouldRecoverStaleRunningRace(HorseRace $race): bool
|
||||
{
|
||||
if (! $race->race_starts_at) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$config = GameConfig::forGame('horse_racing')?->params ?? [];
|
||||
$raceDuration = max(1, (int) ($config['race_duration'] ?? 30));
|
||||
$recoveryGraceSeconds = 5;
|
||||
|
||||
return $race->race_starts_at->lte(now()->subSeconds($raceDuration + $recoveryGraceSeconds));
|
||||
}
|
||||
|
||||
/**
|
||||
* 为超时 running 场次补齐缺失赛果字段,确保后续结算任务可以安全执行。
|
||||
*/
|
||||
private function prepareRunningRaceForSettlement(HorseRace $race): ?HorseRace
|
||||
{
|
||||
if ($race->winner_horse_id && $race->race_ends_at) {
|
||||
return $race->fresh();
|
||||
}
|
||||
|
||||
$horses = $this->normalizeRaceHorses($race->horses);
|
||||
$winnerHorseId = $race->winner_horse_id ?: $this->resolveStaleRunningWinnerId($race, $horses);
|
||||
if (! $winnerHorseId) {
|
||||
return $race;
|
||||
}
|
||||
|
||||
$config = GameConfig::forGame('horse_racing')?->params ?? [];
|
||||
$seedPool = (int) ($config['seed_pool'] ?? 0);
|
||||
|
||||
// 线上补偿场景下以当前下注快照补齐统计,确保本次请求内的结算口径与正常流程一致。
|
||||
$totalBets = HorseBet::query()->where('race_id', $race->id)->count();
|
||||
$totalPool = $seedPool + (int) HorseBet::query()->where('race_id', $race->id)->sum('amount');
|
||||
|
||||
HorseRace::query()
|
||||
->where('id', $race->id)
|
||||
->where('status', 'running')
|
||||
->update([
|
||||
'winner_horse_id' => $winnerHorseId,
|
||||
'race_ends_at' => $race->race_ends_at ?? now(),
|
||||
'total_bets' => $totalBets,
|
||||
'total_pool' => $totalPool,
|
||||
]);
|
||||
|
||||
return $race->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 为异常滞留的 running 场次推导一个稳定冠军,避免多次请求得到不同结算结果。
|
||||
*
|
||||
* @param array<int, array{id:int,name:string,emoji:string}> $horses
|
||||
*/
|
||||
private function resolveStaleRunningWinnerId(HorseRace $race, array $horses): ?int
|
||||
{
|
||||
if ($horses === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$horsePools = HorseBet::query()
|
||||
->where('race_id', $race->id)
|
||||
->groupBy('horse_id')
|
||||
->selectRaw('horse_id, SUM(amount) as pool')
|
||||
->pluck('pool', 'horse_id')
|
||||
->map(fn ($pool) => (int) $pool)
|
||||
->toArray();
|
||||
|
||||
$candidateIds = array_map(
|
||||
fn (array $horse): int => (int) $horse['id'],
|
||||
$horses,
|
||||
);
|
||||
|
||||
usort($candidateIds, function (int $leftId, int $rightId) use ($horsePools): int {
|
||||
$leftPool = (int) ($horsePools[$leftId] ?? 0);
|
||||
$rightPool = (int) ($horsePools[$rightId] ?? 0);
|
||||
|
||||
if ($leftPool === $rightPool) {
|
||||
return $leftId <=> $rightId;
|
||||
}
|
||||
|
||||
return $rightPool <=> $leftPool;
|
||||
});
|
||||
|
||||
return $candidateIds[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 兼容旧赛马数据结构,统一清洗为前端可消费的马匹数组。
|
||||
*
|
||||
|
||||
@@ -19,27 +19,38 @@ namespace App\Http\Controllers;
|
||||
use App\Models\GameConfig;
|
||||
use App\Models\LotteryIssue;
|
||||
use App\Models\LotteryTicket;
|
||||
use App\Services\GameRoomScopeService;
|
||||
use App\Services\LotteryService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
/**
|
||||
* 类功能:提供双色球当前期、购票和历史记录接口。
|
||||
*/
|
||||
class LotteryController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly LotteryService $lottery,
|
||||
private readonly GameRoomScopeService $roomScopeService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 返回当期状态:期号、奖池、剩余时间、我本期购票列表。
|
||||
*/
|
||||
public function current(): JsonResponse
|
||||
public function current(Request $request): JsonResponse
|
||||
{
|
||||
if (! GameConfig::isEnabled('lottery')) {
|
||||
return response()->json(['enabled' => false]);
|
||||
}
|
||||
|
||||
$issue = LotteryIssue::currentIssue() ?? LotteryIssue::latestIssue();
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request);
|
||||
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('lottery', $roomId)) {
|
||||
return response()->json(['enabled' => false, 'message' => '当前房间未开启双色球彩票。'], 403);
|
||||
}
|
||||
|
||||
$issue = LotteryIssue::currentIssue($roomId) ?? LotteryIssue::latestIssue($roomId);
|
||||
|
||||
if (! $issue) {
|
||||
return response()->json(['enabled' => true, 'issue' => null]);
|
||||
@@ -90,6 +101,11 @@ class LotteryController extends Controller
|
||||
*/
|
||||
public function buy(Request $request): JsonResponse
|
||||
{
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request);
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('lottery', $roomId)) {
|
||||
return response()->json(['status' => 'error', 'message' => '当前房间未开启双色球彩票。'], 403);
|
||||
}
|
||||
|
||||
$request->validate([
|
||||
'numbers' => 'required|array|min:1',
|
||||
'numbers.*.reds' => 'required|array|size:3',
|
||||
@@ -132,7 +148,9 @@ class LotteryController extends Controller
|
||||
*/
|
||||
public function history(): JsonResponse
|
||||
{
|
||||
$roomId = $this->roomScopeService->resolveUserRoomId(Auth::user());
|
||||
$issues = LotteryIssue::query()
|
||||
->where('room_id', $roomId)
|
||||
->where('status', 'settled')
|
||||
->latest()
|
||||
->limit(20)
|
||||
|
||||
@@ -28,28 +28,38 @@ use App\Models\GameConfig;
|
||||
use App\Models\MysteryBox;
|
||||
use App\Models\MysteryBoxClaim;
|
||||
use App\Services\ChatStateService;
|
||||
use App\Services\GameRoomScopeService;
|
||||
use App\Services\UserCurrencyService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* 类功能:提供神秘箱子状态查询与暗号开箱接口。
|
||||
*/
|
||||
class MysteryBoxController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly UserCurrencyService $currency,
|
||||
private readonly ChatStateService $chatState,
|
||||
private readonly GameRoomScopeService $roomScopeService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 查询当前可领取的箱子状态(给前端轮询/显示用)。
|
||||
*/
|
||||
public function status(): JsonResponse
|
||||
public function status(Request $request): JsonResponse
|
||||
{
|
||||
if (! GameConfig::isEnabled('mystery_box')) {
|
||||
return response()->json(['active' => false]);
|
||||
}
|
||||
|
||||
$box = MysteryBox::currentOpenBox();
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request);
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('mystery_box', $roomId)) {
|
||||
return response()->json(['active' => false]);
|
||||
}
|
||||
|
||||
$box = MysteryBox::currentOpenBox($roomId);
|
||||
|
||||
if (! $box) {
|
||||
return response()->json(['active' => false]);
|
||||
@@ -85,10 +95,16 @@ class MysteryBoxController extends Controller
|
||||
}
|
||||
|
||||
$user = $request->user();
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request, $user);
|
||||
|
||||
return DB::transaction(function () use ($user, $passcode): JsonResponse {
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('mystery_box', $roomId)) {
|
||||
return response()->json(['ok' => false, 'message' => '当前房间未开启神秘箱子。'], 403);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($user, $passcode, $roomId): JsonResponse {
|
||||
// 查找匹配暗号的可领取箱子(加锁防并发)
|
||||
$box = MysteryBox::query()
|
||||
->where('room_id', $roomId)
|
||||
->where('passcode', $passcode)
|
||||
->where('status', 'open')
|
||||
->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))
|
||||
@@ -147,18 +163,16 @@ class MysteryBoxController extends Controller
|
||||
$typeName = $box->typeName();
|
||||
|
||||
if ($reward >= 0) {
|
||||
$content = "{$emoji}【神秘箱子】开箱播报:恭喜 【{$username}】 抢到了神秘{$typeName}!"
|
||||
.'获得 💰'.number_format($reward).' 金币!';
|
||||
$content = "{$emoji} 【{$username}】抢到{$typeName},获得 💰".number_format($reward).' 金币!';
|
||||
$color = $box->box_type === 'rare' ? '#c4b5fd' : '#34d399';
|
||||
} else {
|
||||
$content = "☠️【神秘箱子】《黑化陷阱》haha!【{$username}】 中了神秘黑化箱的陷阱!"
|
||||
.'被扣除 💰'.number_format(abs($reward)).' 金币!点背~';
|
||||
$content = "☠️ 【{$username}】踩中黑化陷阱,扣除 💰".number_format(abs($reward)).' 金币!';
|
||||
$color = '#f87171';
|
||||
}
|
||||
|
||||
$msg = [
|
||||
'id' => $this->chatState->nextMessageId(1),
|
||||
'room_id' => 1,
|
||||
'id' => $this->chatState->nextMessageId((int) $box->room_id),
|
||||
'room_id' => (int) $box->room_id,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => $content,
|
||||
@@ -168,8 +182,8 @@ class MysteryBoxController extends Controller
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
|
||||
$this->chatState->pushMessage(1, $msg);
|
||||
broadcast(new MessageSent(1, $msg));
|
||||
$this->chatState->pushMessage((int) $box->room_id, $msg);
|
||||
broadcast(new MessageSent((int) $box->room_id, $msg));
|
||||
SaveMessageJob::dispatch($msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:猜谜活动控制器
|
||||
*
|
||||
* 负责兼容现有 idiom-quiz 路由,同时支持猜成语与脑筋急转弯
|
||||
* 两类题型的开题、答题与当前回合查询。
|
||||
*/
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Events\RiddleGameAnswered;
|
||||
use App\Models\GameConfig;
|
||||
use App\Models\Riddle;
|
||||
use App\Models\RiddleGameRound;
|
||||
use App\Services\RiddleGameService;
|
||||
use App\Services\UserCurrencyService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
|
||||
/**
|
||||
* 类功能:处理猜谜活动开题、答题和当前回合读取。
|
||||
*/
|
||||
class RiddleQuizController extends Controller
|
||||
{
|
||||
/**
|
||||
* 方法功能:注入猜谜活动所需的服务。
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly RiddleGameService $riddleGameService,
|
||||
private readonly UserCurrencyService $currencyService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 方法功能:管理员手动为指定房间与题型发起一轮猜谜活动。
|
||||
*/
|
||||
public function start(Request $request): JsonResponse
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// 仅站长或具备后台职务的管理用户可手动开题。
|
||||
if (! $user || ($user->id !== 1 && ! $request->user()?->activePosition)) {
|
||||
return response()->json(['status' => 'error', 'message' => '无权限'], 403);
|
||||
}
|
||||
|
||||
$roomId = (int) $request->input('room_id', 0);
|
||||
// 兼容后台新字段 quiz_type 与旧字段 type,两边都允许触发手动出题。
|
||||
$quizType = $this->riddleGameService->normalizeQuizType($request->input('quiz_type', $request->input('type', Riddle::TYPE_IDIOM)));
|
||||
if ($roomId <= 0) {
|
||||
return response()->json(['status' => 'error', 'message' => '缺少房间 ID'], 422);
|
||||
}
|
||||
|
||||
// 猜谜活动总开关关闭时,直接返回明确提示,避免误报成“题库为空”。
|
||||
if (! GameConfig::isEnabled(Riddle::TYPE_IDIOM)) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => '猜谜活动未开启,请先到游戏管理中开启后再出题。',
|
||||
], 400);
|
||||
}
|
||||
|
||||
// 后台手动出题允许覆盖当前同题型回合,避免管理员还要先人工结束上一题。
|
||||
$this->riddleGameService->endActiveRoundsForRoom($roomId, $quizType);
|
||||
|
||||
$round = $this->riddleGameService->startRound($roomId, $quizType);
|
||||
if (! $round) {
|
||||
if (! $this->riddleGameService->pickRandomQuestion($quizType)) {
|
||||
return response()->json(['status' => 'error', 'message' => '当前题型题库中没有可用题目,请先在后台添加。'], 400);
|
||||
}
|
||||
|
||||
return response()->json(['status' => 'error', 'message' => '当前题型暂时无法出题,请检查游戏配置与参与房间设置。'], 400);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'status' => 'success',
|
||||
'data' => [
|
||||
'quiz_type' => $round->quiz_type,
|
||||
'quiz_type_label' => $this->riddleGameService->getQuizTypeLabel($round->quiz_type),
|
||||
'round_id' => $round->id,
|
||||
'quiz_round_id' => $round->id,
|
||||
'hint' => $round->idiom?->hint ?? '',
|
||||
'quiz_hint' => $round->idiom?->hint ?? '',
|
||||
'reward_gold' => $round->reward_gold,
|
||||
'reward_exp' => $round->reward_exp,
|
||||
'quiz_reward_gold' => $round->reward_gold,
|
||||
'quiz_reward_exp' => $round->reward_exp,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:提交当前猜谜活动回合的答案。
|
||||
*/
|
||||
public function answer(Request $request): JsonResponse
|
||||
{
|
||||
$user = Auth::user();
|
||||
if (! $user) {
|
||||
return response()->json(['status' => 'error', 'message' => '请先登录'], 401);
|
||||
}
|
||||
|
||||
$roundId = (int) $request->input('round_id');
|
||||
$roomId = (int) $request->input('room_id');
|
||||
$quizType = $this->riddleGameService->normalizeQuizType($request->input('quiz_type', $request->input('type', Riddle::TYPE_IDIOM)));
|
||||
$userAnswer = trim((string) $request->input('answer', ''));
|
||||
|
||||
if ($roundId <= 0 || $roomId <= 0 || $userAnswer === '') {
|
||||
return response()->json(['status' => 'error', 'message' => '参数不完整'], 422);
|
||||
}
|
||||
|
||||
$round = RiddleGameRound::with('idiom')->find($roundId);
|
||||
if (! $round || $round->room_id !== $roomId || $round->quiz_type !== $quizType) {
|
||||
return response()->json(['status' => 'error', 'message' => '回合不存在'], 404);
|
||||
}
|
||||
|
||||
// 判题前先做超时结算,避免用户继续抢答无效回合。
|
||||
if ($this->riddleGameService->expireRound($round)) {
|
||||
return response()->json(['status' => 'error', 'message' => '该回合已超时结束'], 400);
|
||||
}
|
||||
|
||||
if ($round->status !== 'active') {
|
||||
if ($round->status === 'answered') {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => "这道{$this->riddleGameService->getQuizTypeLabel($round->quiz_type)}已被「{$round->winner_username}」抢先答对了!",
|
||||
], 400);
|
||||
}
|
||||
|
||||
return response()->json(['status' => 'error', 'message' => '该回合已结束'], 400);
|
||||
}
|
||||
|
||||
// 答案对比忽略空格与大小写,减少正常输入误判。
|
||||
$normalizedAnswer = str_replace(' ', '', $userAnswer);
|
||||
$normalizedCorrect = str_replace(' ', '', (string) $round->idiom?->answer);
|
||||
if (mb_strtolower($normalizedAnswer) !== mb_strtolower($normalizedCorrect)) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => '答案不正确,再想想!',
|
||||
]);
|
||||
}
|
||||
|
||||
$lockKey = "riddle:answer_lock:{$roundId}";
|
||||
if (! Redis::setnx($lockKey, 1)) {
|
||||
return response()->json([
|
||||
'status' => 'error',
|
||||
'message' => "这道{$this->riddleGameService->getQuizTypeLabel($round->quiz_type)}已被「{$round->winner_username}」抢先答对了!",
|
||||
], 400);
|
||||
}
|
||||
|
||||
Redis::expire($lockKey, 10);
|
||||
|
||||
// 抢答成功后立即封盘,确保并发请求读到统一状态。
|
||||
$round->update([
|
||||
'status' => 'answered',
|
||||
'winner_id' => $user->id,
|
||||
'winner_username' => $user->username,
|
||||
'ended_at' => now(),
|
||||
]);
|
||||
|
||||
if ($round->reward_gold > 0) {
|
||||
$this->currencyService->change(
|
||||
$user,
|
||||
'gold',
|
||||
$round->reward_gold,
|
||||
\App\Enums\CurrencySource::GAME_REWARD,
|
||||
$this->riddleGameService->buildRewardDescription($round),
|
||||
$roomId,
|
||||
);
|
||||
}
|
||||
|
||||
if ($round->reward_exp > 0) {
|
||||
// 经验奖励仍沿用现有字段,避免引入额外奖励服务改动。
|
||||
$user->exp_num = ($user->exp_num ?? 0) + $round->reward_exp;
|
||||
$user->save();
|
||||
}
|
||||
|
||||
broadcast(new RiddleGameAnswered(
|
||||
roomId: $roomId,
|
||||
roundId: $round->id,
|
||||
quizType: $round->quiz_type,
|
||||
answer: (string) $round->idiom?->answer,
|
||||
winnerUsername: $user->username,
|
||||
rewardGold: $round->reward_gold,
|
||||
rewardExp: $round->reward_exp,
|
||||
));
|
||||
|
||||
$quizTypeLabel = $this->riddleGameService->getQuizTypeLabel($round->quiz_type);
|
||||
$resultMsg = [
|
||||
'id' => app(\App\Services\ChatStateService::class)->nextMessageId($roomId),
|
||||
'room_id' => $roomId,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => "🎉 【猜谜活动·{$quizTypeLabel}】{$user->username} 率先答对「{$round->idiom?->answer}」,获得 {$round->reward_gold} 金币、{$round->reward_exp} 经验!",
|
||||
'is_secret' => false,
|
||||
'font_color' => '#16a34a',
|
||||
'action' => 'idiom_result',
|
||||
'winner_username' => $user->username,
|
||||
'quiz_type' => $round->quiz_type,
|
||||
'quiz_type_label' => $quizTypeLabel,
|
||||
'quiz_answer' => (string) $round->idiom?->answer,
|
||||
'quiz_reward_gold' => $round->reward_gold,
|
||||
'quiz_reward_exp' => $round->reward_exp,
|
||||
'quiz_round_id' => $round->id,
|
||||
'quiz_round_ended_id' => $round->id,
|
||||
'idiom_answer' => (string) $round->idiom?->answer,
|
||||
'idiom_result_reward_gold' => $round->reward_gold,
|
||||
'idiom_result_reward_exp' => $round->reward_exp,
|
||||
'idiom_game_round_ended_id' => $round->id,
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
app(\App\Services\ChatStateService::class)->pushMessage($roomId, $resultMsg);
|
||||
|
||||
Redis::del($lockKey);
|
||||
|
||||
return response()->json([
|
||||
'status' => 'success',
|
||||
'message' => "🎉 回答正确!获得 {$round->reward_gold} 金币、{$round->reward_exp} 经验!",
|
||||
'data' => [
|
||||
'quiz_type' => $round->quiz_type,
|
||||
'quiz_type_label' => $quizTypeLabel,
|
||||
'answer' => (string) $round->idiom?->answer,
|
||||
'quiz_answer' => (string) $round->idiom?->answer,
|
||||
'reward_gold' => $round->reward_gold,
|
||||
'reward_exp' => $round->reward_exp,
|
||||
'quiz_reward_gold' => $round->reward_gold,
|
||||
'quiz_reward_exp' => $round->reward_exp,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:查询当前房间指定题型的进行中回合。
|
||||
*/
|
||||
public function current(Request $request): JsonResponse
|
||||
{
|
||||
$roomId = (int) $request->input('room_id', 0);
|
||||
$quizType = $this->riddleGameService->normalizeQuizType($request->input('quiz_type', $request->input('type', Riddle::TYPE_IDIOM)));
|
||||
if ($roomId <= 0) {
|
||||
return response()->json(['status' => 'error', 'message' => '缺少房间 ID'], 422);
|
||||
}
|
||||
|
||||
$round = $this->riddleGameService->findActiveRound($roomId, $quizType);
|
||||
if (! $round) {
|
||||
return response()->json(['status' => 'success', 'data' => null]);
|
||||
}
|
||||
|
||||
if ($this->riddleGameService->expireRound($round)) {
|
||||
return response()->json(['status' => 'success', 'data' => null]);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'status' => 'success',
|
||||
'data' => [
|
||||
'quiz_type' => $round->quiz_type,
|
||||
'quiz_type_label' => $this->riddleGameService->getQuizTypeLabel($round->quiz_type),
|
||||
'round_id' => $round->id,
|
||||
'quiz_round_id' => $round->id,
|
||||
'hint' => $round->idiom?->hint ?? '',
|
||||
'quiz_hint' => $round->idiom?->hint ?? '',
|
||||
'reward_gold' => $round->reward_gold,
|
||||
'reward_exp' => $round->reward_exp,
|
||||
'quiz_reward_gold' => $round->reward_gold,
|
||||
'quiz_reward_exp' => $round->reward_exp,
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:聊天室座驾前台接口控制器。
|
||||
*
|
||||
* 提供座驾列表、用户当前座驾、购买记录与购买座驾接口。
|
||||
*/
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Requests\BuyRideRequest;
|
||||
use App\Models\Ride;
|
||||
use App\Models\Room;
|
||||
use App\Services\ChatStateService;
|
||||
use App\Services\RideService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
/**
|
||||
* 聊天室座驾控制器
|
||||
* 负责前台座驾页面的数据读取与购买操作。
|
||||
*/
|
||||
class RideController extends Controller
|
||||
{
|
||||
/**
|
||||
* 构造座驾控制器依赖。
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly RideService $rideService,
|
||||
private readonly ChatStateService $chatState,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 获取座驾页面需要的商品、当前座驾和购买记录。
|
||||
*/
|
||||
public function items(): JsonResponse
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
return response()->json([
|
||||
'items' => $this->rideService->activeItems()
|
||||
->map(fn (Ride $item) => $this->rideService->formatItem($item))
|
||||
->values(),
|
||||
'current_ride' => $this->rideService->formatCurrentRide($user),
|
||||
'purchases' => $this->rideService->purchaseRecords($user),
|
||||
'user_jjb' => $user->jjb ?? 0,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 购买座驾并返回最新金币和当前座驾状态。
|
||||
*/
|
||||
public function buy(BuyRideRequest $request): JsonResponse
|
||||
{
|
||||
$user = Auth::user();
|
||||
$roomId = (int) $request->integer('room_id');
|
||||
$room = Room::query()->findOrFail($roomId);
|
||||
|
||||
if (! $room->canUserEnter($user) || ! $this->chatState->isUserInRoom($roomId, $user->username)) {
|
||||
return response()->json(['status' => 'error', 'message' => '请先进入当前房间后再购买座驾。'], 403);
|
||||
}
|
||||
|
||||
$item = Ride::query()->findOrFail((int) $request->integer('item_id'));
|
||||
$result = $this->rideService->buy($user, $item, $roomId);
|
||||
|
||||
if (! $result['ok']) {
|
||||
return response()->json(['status' => 'error', 'message' => $result['message']], 400);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'status' => 'success',
|
||||
'message' => $result['message'],
|
||||
'current_ride' => $result['current_ride'] ?? null,
|
||||
'purchases' => $this->rideService->purchaseRecords($user->fresh()),
|
||||
'jjb' => $user->fresh()->jjb,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -40,19 +40,23 @@ class ShopController extends Controller
|
||||
public function items(): JsonResponse
|
||||
{
|
||||
$user = Auth::user();
|
||||
$items = ShopItem::active()->map(fn ($item) => [
|
||||
'id' => $item->id,
|
||||
'name' => $item->name,
|
||||
'slug' => $item->slug,
|
||||
'description' => $item->description,
|
||||
'icon' => $item->icon,
|
||||
'price' => $item->price,
|
||||
'type' => $item->type,
|
||||
'duration_days' => $item->duration_days,
|
||||
'duration_minutes' => $item->duration_minutes,
|
||||
'intimacy_bonus' => $item->intimacy_bonus,
|
||||
'charm_bonus' => $item->charm_bonus,
|
||||
]);
|
||||
$items = ShopItem::query()
|
||||
->where('is_active', true)
|
||||
->orderBy('sort_order')
|
||||
->get()
|
||||
->map(fn ($item) => [
|
||||
'id' => $item->id,
|
||||
'name' => $item->name,
|
||||
'slug' => $item->slug,
|
||||
'description' => $item->description,
|
||||
'icon' => $item->icon,
|
||||
'price' => $item->price,
|
||||
'type' => $item->type,
|
||||
'duration_days' => $item->duration_days,
|
||||
'duration_minutes' => $item->duration_minutes,
|
||||
'intimacy_bonus' => $item->intimacy_bonus,
|
||||
'charm_bonus' => $item->charm_bonus,
|
||||
]);
|
||||
|
||||
$signRepairCard = $items->firstWhere('type', ShopItem::TYPE_SIGN_REPAIR);
|
||||
|
||||
|
||||
@@ -23,16 +23,21 @@ use App\Jobs\SaveMessageJob;
|
||||
use App\Models\GameConfig;
|
||||
use App\Models\SlotMachineLog;
|
||||
use App\Services\ChatStateService;
|
||||
use App\Services\GameRoomScopeService;
|
||||
use App\Services\UserCurrencyService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* 类功能:提供老虎机信息查询、转动和个人记录接口。
|
||||
*/
|
||||
class SlotMachineController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly UserCurrencyService $currency,
|
||||
private readonly ChatStateService $chatState,
|
||||
private readonly GameRoomScopeService $roomScopeService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -44,6 +49,11 @@ class SlotMachineController extends Controller
|
||||
return response()->json(['enabled' => false]);
|
||||
}
|
||||
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request, $request->user());
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('slot_machine', $roomId)) {
|
||||
return response()->json(['enabled' => false]);
|
||||
}
|
||||
|
||||
$config = GameConfig::forGame('slot_machine')?->params ?? [];
|
||||
$user = $request->user();
|
||||
$dailyLimit = (int) ($config['daily_limit'] ?? 0);
|
||||
@@ -77,6 +87,11 @@ class SlotMachineController extends Controller
|
||||
return response()->json(['ok' => false, 'message' => '老虎机未开放。']);
|
||||
}
|
||||
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request, $request->user());
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('slot_machine', $roomId)) {
|
||||
return response()->json(['ok' => false, 'message' => '当前房间未开启老虎机。'], 403);
|
||||
}
|
||||
|
||||
$config = GameConfig::forGame('slot_machine')?->params ?? [];
|
||||
$cost = (int) ($config['cost_per_spin'] ?? 100);
|
||||
$dailyLimit = (int) ($config['daily_limit'] ?? 0);
|
||||
@@ -100,7 +115,7 @@ class SlotMachineController extends Controller
|
||||
}
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($user, $cost, $config): JsonResponse {
|
||||
return DB::transaction(function () use ($user, $cost, $config, $roomId): JsonResponse {
|
||||
// ① 扣费
|
||||
$this->currency->change(
|
||||
$user,
|
||||
@@ -164,16 +179,16 @@ class SlotMachineController extends Controller
|
||||
|
||||
if ($resultType === 'jackpot') {
|
||||
// 三个7:全服公屏广播
|
||||
$this->broadcastJackpot($user->username, $payout, $cost);
|
||||
$this->broadcastJackpot($user->username, $payout, $cost, $roomId);
|
||||
} elseif (in_array($resultType, ['triple_gem', 'triple', 'pair'], true)) {
|
||||
// 普通中奖:仅向本人发送聊天室系统通知
|
||||
$net = $payout - $cost;
|
||||
$content = "🎰 {$resultLabel}!{$e1}{$e2}{$e3} 赢得 +💰".number_format($net).' 金币';
|
||||
$this->broadcastPersonal($user->username, $content);
|
||||
$this->broadcastPersonal($user->username, $content, $roomId);
|
||||
} elseif ($resultType === 'curse') {
|
||||
// 诅咒:通知本人
|
||||
$content = "☠️ 三骷髅诅咒!{$e1}{$e2}{$e3} 额外扣除 💰".number_format($cost).' 金币!';
|
||||
$this->broadcastPersonal($user->username, $content);
|
||||
$this->broadcastPersonal($user->username, $content, $roomId);
|
||||
}
|
||||
|
||||
$user->refresh();
|
||||
@@ -200,6 +215,11 @@ class SlotMachineController extends Controller
|
||||
*/
|
||||
public function history(Request $request): JsonResponse
|
||||
{
|
||||
$roomId = $this->roomScopeService->resolveRequestRoomId($request, $request->user());
|
||||
if (! $this->roomScopeService->isRoomAllowedForGame('slot_machine', $roomId)) {
|
||||
return response()->json(['history' => []]);
|
||||
}
|
||||
|
||||
$logs = SlotMachineLog::query()
|
||||
->where('user_id', $request->user()->id)
|
||||
->orderByDesc('id')
|
||||
@@ -239,15 +259,15 @@ class SlotMachineController extends Controller
|
||||
/**
|
||||
* 三个7全服公屏广播。
|
||||
*/
|
||||
private function broadcastJackpot(string $username, int $payout, int $cost): void
|
||||
private function broadcastJackpot(string $username, int $payout, int $cost, int $roomId): void
|
||||
{
|
||||
$net = $payout - $cost;
|
||||
$content = "🎰🎉【老虎机大奖】恭喜 【{$username}】 转出三个7️⃣!"
|
||||
.'狂揽 💰'.number_format($net).' 金币!全服见证奇迹!';
|
||||
|
||||
$msg = [
|
||||
'id' => $this->chatState->nextMessageId(1),
|
||||
'room_id' => 1,
|
||||
'id' => $this->chatState->nextMessageId($roomId),
|
||||
'room_id' => $roomId,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => $content,
|
||||
@@ -257,8 +277,8 @@ class SlotMachineController extends Controller
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
|
||||
$this->chatState->pushMessage(1, $msg);
|
||||
broadcast(new MessageSent(1, $msg));
|
||||
$this->chatState->pushMessage($roomId, $msg);
|
||||
broadcast(new MessageSent($roomId, $msg));
|
||||
SaveMessageJob::dispatch($msg);
|
||||
}
|
||||
|
||||
@@ -268,11 +288,11 @@ class SlotMachineController extends Controller
|
||||
* @param string $toUsername 接收用户名
|
||||
* @param string $content 消息内容
|
||||
*/
|
||||
private function broadcastPersonal(string $toUsername, string $content): void
|
||||
private function broadcastPersonal(string $toUsername, string $content, int $roomId): void
|
||||
{
|
||||
$msg = [
|
||||
'id' => $this->chatState->nextMessageId(1),
|
||||
'room_id' => 1,
|
||||
'id' => $this->chatState->nextMessageId($roomId),
|
||||
'room_id' => $roomId,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => $toUsername,
|
||||
'content' => $content,
|
||||
@@ -282,7 +302,7 @@ class SlotMachineController extends Controller
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
|
||||
broadcast(new MessageSent(1, $msg));
|
||||
broadcast(new MessageSent($roomId, $msg));
|
||||
SaveMessageJob::dispatch($msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,19 +303,37 @@ class UserController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存聊天室屏蔽与禁音偏好。
|
||||
* 保存聊天室屏蔽、禁音与字号偏好。
|
||||
*/
|
||||
public function updateChatPreferences(UpdateChatPreferencesRequest $request): JsonResponse
|
||||
{
|
||||
$user = Auth::user();
|
||||
$data = $request->validated();
|
||||
$existingPreferences = is_array($user->chat_preferences) ? $user->chat_preferences : [];
|
||||
$blockedSystemSenders = collect($data['blocked_system_senders'] ?? [])
|
||||
->map(function (string $sender): string {
|
||||
// 猜谜活动前端文案允许升级,但持久化键仍复用旧值,避免历史偏好失效。
|
||||
return $sender === '猜谜活动' ? '猜成语' : $sender;
|
||||
})
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
$preferences = [
|
||||
// 去重并重建索引,保持存储结构稳定,便于后续继续扩展其它屏蔽项。
|
||||
'blocked_system_senders' => array_values(array_unique($data['blocked_system_senders'] ?? [])),
|
||||
'blocked_system_senders' => $blockedSystemSenders,
|
||||
'sound_muted' => (bool) $data['sound_muted'],
|
||||
];
|
||||
|
||||
// 字号偏好和屏蔽/禁音共用账号配置,旧请求未携带字号时保留原值。
|
||||
$fontSize = array_key_exists('font_size', $data) && $data['font_size'] !== null
|
||||
? (int) $data['font_size']
|
||||
: ($existingPreferences['font_size'] ?? null);
|
||||
|
||||
if ($fontSize !== null) {
|
||||
$preferences['font_size'] = (int) $fontSize;
|
||||
}
|
||||
|
||||
$user->update([
|
||||
'chat_preferences' => $preferences,
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:前台座驾购买请求验证。
|
||||
*
|
||||
* 校验用户购买座驾时传入的座驾与房间上下文,避免未进房直接购买聊天室座驾。
|
||||
*/
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 座驾购买请求
|
||||
* 负责校验座驾 ID 与当前房间 ID。
|
||||
*/
|
||||
class BuyRideRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 判断当前用户是否允许购买座驾。
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取座驾购买请求验证规则。
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'item_id' => ['required', 'integer', 'exists:rides,id'],
|
||||
'room_id' => ['required', 'integer', 'exists:rooms,id'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取座驾购买请求中文错误提示。
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'item_id.required' => '请选择要购买的座驾。',
|
||||
'item_id.exists' => '座驾不存在或已被删除。',
|
||||
'room_id.required' => '请先进入聊天室后再购买座驾。',
|
||||
'room_id.exists' => '当前房间不存在。',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:后台新增座驾请求验证。
|
||||
*
|
||||
* 校验座驾独立模块的名称、特效 key、价格、使用天数、欢迎语和上下架状态。
|
||||
*/
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* 后台新增座驾请求
|
||||
* 负责新增座驾时的权限与字段校验。
|
||||
*/
|
||||
class StoreRideRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 判断当前用户是否允许新增座驾。
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()?->id === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取新增座驾验证规则。
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:100'],
|
||||
'slug' => ['required', 'string', 'max:100', 'regex:/^ride_[a-z0-9_]+$/', Rule::unique('rides', 'slug')],
|
||||
'effect_key' => ['required', 'string', 'max:50', 'regex:/^[a-z0-9_]+$/', Rule::unique('rides', 'effect_key')],
|
||||
'icon' => ['required', 'string', 'max:20'],
|
||||
'description' => ['nullable', 'string', 'max:500'],
|
||||
'price' => ['required', 'integer', 'min:0'],
|
||||
'duration_days' => ['required', 'integer', 'min:1'],
|
||||
'welcome_message' => ['nullable', 'string', 'max:255'],
|
||||
'sort_order' => ['required', 'integer', 'min:0'],
|
||||
'is_active' => ['boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取新增座驾中文错误提示。
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'slug.regex' => '座驾标识必须使用 ride_ 开头,例如 ride_j35。',
|
||||
'effect_key.regex' => '特效 key 只能包含小写字母、数字和下划线。',
|
||||
'duration_days.min' => '使用天数至少为 1 天。',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:后台新增商店商品请求验证。
|
||||
*
|
||||
* 统一校验商店商品字段。
|
||||
*/
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Models\ShopItem;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* 后台新增商店商品请求
|
||||
* 负责新增商品时的权限与字段校验。
|
||||
*/
|
||||
class StoreShopItemRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 判断当前用户是否允许新增商品。
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()?->id === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取新增商品验证规则。
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:100'],
|
||||
'slug' => ['required', 'string', 'max:100', Rule::unique('shop_items', 'slug')],
|
||||
'icon' => ['required', 'string', 'max:20'],
|
||||
'description' => ['nullable', 'string', 'max:500'],
|
||||
'price' => ['required', 'integer', 'min:0'],
|
||||
'type' => ['required', Rule::in($this->allowedTypes())],
|
||||
'duration_days' => ['nullable', 'integer', 'min:0'],
|
||||
'duration_minutes' => ['nullable', 'integer', 'min:0'],
|
||||
'intimacy_bonus' => ['nullable', 'integer', 'min:0'],
|
||||
'charm_bonus' => ['nullable', 'integer', 'min:0'],
|
||||
'sort_order' => ['required', 'integer', 'min:0'],
|
||||
'is_active' => ['boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取允许后台配置的商品类型。
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
protected function allowedTypes(): array
|
||||
{
|
||||
return [
|
||||
'instant',
|
||||
'duration',
|
||||
'one_time',
|
||||
'ring',
|
||||
'auto_fishing',
|
||||
ShopItem::TYPE_SIGN_REPAIR,
|
||||
'msg_bubble',
|
||||
'msg_name_color',
|
||||
'msg_text_color',
|
||||
'avatar_frame',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
/**
|
||||
* 文件功能:聊天室偏好设置验证器
|
||||
* 负责校验用户提交的屏蔽播报与禁音配置。
|
||||
* 负责校验用户提交的屏蔽播报、禁音与聊天室字号配置。
|
||||
*/
|
||||
|
||||
namespace App\Http\Requests;
|
||||
@@ -12,7 +12,7 @@ use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* 聊天室偏好设置验证器
|
||||
* 仅允许提交白名单内的屏蔽项与布尔型禁音状态。
|
||||
* 仅允许提交白名单内的屏蔽项、布尔型禁音状态与合法字号。
|
||||
*/
|
||||
class UpdateChatPreferencesRequest extends FormRequest
|
||||
{
|
||||
@@ -35,9 +35,10 @@ class UpdateChatPreferencesRequest extends FormRequest
|
||||
'blocked_system_senders' => ['nullable', 'array'],
|
||||
'blocked_system_senders.*' => [
|
||||
'string',
|
||||
Rule::in(['钓鱼播报', '星海小博士', '百家乐', '跑马','神秘箱子']),
|
||||
Rule::in(['钓鱼播报', '猜成语', '猜谜活动', '星海小博士', '百家乐', '跑马', '神秘箱子', '五子棋', '老虎机', '双色球彩票']),
|
||||
],
|
||||
'sound_muted' => ['required', 'boolean'],
|
||||
'font_size' => ['nullable', 'integer', 'min:10', 'max:30'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -53,6 +54,9 @@ class UpdateChatPreferencesRequest extends FormRequest
|
||||
'blocked_system_senders.*.in' => '存在不支持的屏蔽项目。',
|
||||
'sound_muted.required' => '请传入禁音状态。',
|
||||
'sound_muted.boolean' => '禁音状态格式无效。',
|
||||
'font_size.integer' => '聊天室字号格式无效。',
|
||||
'font_size.min' => '聊天室字号不能小于 10。',
|
||||
'font_size.max' => '聊天室字号不能大于 30。',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:保存游戏参数请求校验
|
||||
*
|
||||
* 统一校验后台“游戏管理”页提交的 params 结构,
|
||||
* 并在所有游戏共用的房间范围字段上执行归一化。
|
||||
*/
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Services\GameRoomScopeService;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 类功能:约束后台游戏参数保存请求的公共结构。
|
||||
*/
|
||||
class UpdateGameConfigParamsRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 判断当前请求是否允许执行。
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验规则。
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'params' => ['required', 'array'],
|
||||
'params.room_scope_mode' => ['nullable', 'in:all,single,multiple'],
|
||||
'params.room_ids' => ['nullable', 'array'],
|
||||
'params.room_ids.*' => ['integer', 'exists:rooms,id'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义错误消息。
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'params.required' => '缺少游戏参数数据。',
|
||||
'params.array' => '游戏参数格式无效。',
|
||||
'params.room_scope_mode.in' => '参与房间模式无效。',
|
||||
'params.room_ids.array' => '参与房间列表格式无效。',
|
||||
'params.room_ids.*.integer' => '参与房间编号格式无效。',
|
||||
'params.room_ids.*.exists' => '所选房间不存在,请刷新页面后重试。',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 在校验前先把房间范围字段归一化,兼容单值与旧字段。
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$params = (array) $this->input('params', []);
|
||||
$roomScopeService = app(GameRoomScopeService::class);
|
||||
$scopeConfig = $roomScopeService->getScopeConfigForParams($params);
|
||||
|
||||
$params['room_scope_mode'] = $scopeConfig['room_scope_mode'];
|
||||
$params['room_ids'] = $scopeConfig['room_ids'];
|
||||
|
||||
$this->merge([
|
||||
'params' => $params,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验通过后补充“单选/多选至少选择一个房间”的约束。
|
||||
*/
|
||||
public function withValidator($validator): void
|
||||
{
|
||||
$validator->after(function ($validator): void {
|
||||
$params = (array) $this->input('params', []);
|
||||
$roomMode = (string) ($params['room_scope_mode'] ?? GameRoomScopeService::MODE_SINGLE);
|
||||
$roomIds = (array) ($params['room_ids'] ?? []);
|
||||
|
||||
if (in_array($roomMode, [GameRoomScopeService::MODE_SINGLE, GameRoomScopeService::MODE_MULTIPLE], true) && $roomIds === []) {
|
||||
$validator->errors()->add('params.room_ids', '单选/多选房间模式下,请至少选择一个房间。');
|
||||
}
|
||||
|
||||
if ($roomMode === GameRoomScopeService::MODE_SINGLE && count($roomIds) > 1) {
|
||||
$validator->errors()->add('params.room_ids', '单选房间模式下只能选择一个房间。');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:后台更新座驾请求验证。
|
||||
*
|
||||
* 校验座驾编辑时的唯一标识、价格、使用天数和欢迎语配置。
|
||||
*/
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* 后台更新座驾请求
|
||||
* 负责编辑座驾时的权限与字段校验。
|
||||
*/
|
||||
class UpdateRideRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 判断当前用户是否允许编辑座驾。
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取更新座驾验证规则。
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$ride = $this->route('ride');
|
||||
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:100'],
|
||||
'slug' => ['required', 'string', 'max:100', 'regex:/^ride_[a-z0-9_]+$/', Rule::unique('rides', 'slug')->ignore($ride?->id)],
|
||||
'effect_key' => ['required', 'string', 'max:50', 'regex:/^[a-z0-9_]+$/', Rule::unique('rides', 'effect_key')->ignore($ride?->id)],
|
||||
'icon' => ['required', 'string', 'max:20'],
|
||||
'description' => ['nullable', 'string', 'max:500'],
|
||||
'price' => ['required', 'integer', 'min:0'],
|
||||
'duration_days' => ['required', 'integer', 'min:1'],
|
||||
'welcome_message' => ['nullable', 'string', 'max:255'],
|
||||
'sort_order' => ['required', 'integer', 'min:0'],
|
||||
'is_active' => ['boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取更新座驾中文错误提示。
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'slug.regex' => '座驾标识必须使用 ride_ 开头,例如 ride_j35。',
|
||||
'effect_key.regex' => '特效 key 只能包含小写字母、数字和下划线。',
|
||||
'duration_days.min' => '使用天数至少为 1 天。',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:后台更新商店商品请求验证。
|
||||
*
|
||||
* 统一校验商店商品编辑字段。
|
||||
*/
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Models\ShopItem;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* 后台更新商店商品请求
|
||||
* 负责编辑商品时的权限与字段校验。
|
||||
*/
|
||||
class UpdateShopItemRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 判断当前用户是否允许编辑商品。
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取更新商品验证规则。
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$shopItem = $this->route('shopItem');
|
||||
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:100'],
|
||||
'slug' => ['required', 'string', 'max:100', Rule::unique('shop_items', 'slug')->ignore($shopItem?->id)],
|
||||
'icon' => ['required', 'string', 'max:20'],
|
||||
'description' => ['nullable', 'string', 'max:500'],
|
||||
'price' => ['required', 'integer', 'min:0'],
|
||||
'type' => ['required', Rule::in($this->allowedTypes())],
|
||||
'duration_days' => ['nullable', 'integer', 'min:0'],
|
||||
'duration_minutes' => ['nullable', 'integer', 'min:0'],
|
||||
'intimacy_bonus' => ['nullable', 'integer', 'min:0'],
|
||||
'charm_bonus' => ['nullable', 'integer', 'min:0'],
|
||||
'sort_order' => ['required', 'integer', 'min:0'],
|
||||
'is_active' => ['boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取允许后台配置的商品类型。
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
protected function allowedTypes(): array
|
||||
{
|
||||
return [
|
||||
'instant',
|
||||
'duration',
|
||||
'one_time',
|
||||
'ring',
|
||||
'auto_fishing',
|
||||
ShopItem::TYPE_SIGN_REPAIR,
|
||||
'msg_bubble',
|
||||
'msg_name_color',
|
||||
'msg_text_color',
|
||||
'avatar_frame',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -290,12 +290,8 @@ class AiBaccaratBetJob implements ShouldQueue
|
||||
*/
|
||||
private function broadcastPassMessage(User $user, int $roomId, string $reason): void
|
||||
{
|
||||
if (empty($reason)) {
|
||||
$reason = '风大雨大,保本最大,这把我决定观望一下!';
|
||||
}
|
||||
|
||||
$chatState = app(ChatStateService::class);
|
||||
$content = "🌟 🎲 【百家乐】 <b>{$user->username}</b> 本局选择挂机观望:✨ <br/><span style='color:#666;'>[🤖 策略分析] {$reason}</span>";
|
||||
$content = "🎲 【百家乐】 {$user->username} 本局选择挂机观望";
|
||||
|
||||
$msg = [
|
||||
'id' => $chatState->nextMessageId($roomId),
|
||||
@@ -335,9 +331,8 @@ class AiBaccaratBetJob implements ShouldQueue
|
||||
$chatState = app(ChatStateService::class);
|
||||
$labelMap = ['big' => '大', 'small' => '小', 'triple' => '豹子'];
|
||||
$label = $labelMap[$betType] ?? $betType;
|
||||
|
||||
$sourceText = $decisionSource === 'ai' ? '🤖 经过深度算法预测,本局我看好:' : '📊 观察了下最近的路单,这把我觉得是:';
|
||||
$content = "🌟 🎲 【百家乐】 <b>{$user->username}</b> 已下注:<span style='color:#1d4ed8;font-weight:bold;'>{$label}</span> (".number_format($amount)." 金币)<br/><span style='color:#666;'>{$sourceText} {$label}!</span>";
|
||||
// AI 下注播报统一压成单行,避免游戏通知卡片出现多行正文挤占高度。
|
||||
$content = "🌟 🎲 【百家乐】 <b>{$user->username}</b> 已下注:<span style='color:#1d4ed8;font-weight:bold;'>{$label}</span> (".number_format($amount).' 金币)';
|
||||
|
||||
$msg = [
|
||||
'id' => $chatState->nextMessageId($roomId),
|
||||
|
||||
@@ -28,6 +28,9 @@ use Illuminate\Foundation\Queue\Queueable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
|
||||
/**
|
||||
* 类功能:完成一局百家乐的开奖、派奖与通知。
|
||||
*/
|
||||
class CloseBaccaratRoundJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
@@ -227,7 +230,7 @@ class CloseBaccaratRoundJob implements ShouldQueue
|
||||
return;
|
||||
}
|
||||
|
||||
$roomId = 1;
|
||||
$roomId = (int) $round->room_id;
|
||||
$roundResultLabel = $round->resultLabel();
|
||||
|
||||
foreach ($participantSettlements as $settlement) {
|
||||
@@ -309,11 +312,11 @@ class CloseBaccaratRoundJob implements ShouldQueue
|
||||
|
||||
$detail = $detailParts ? ' '.implode(' ', $detailParts) : '';
|
||||
|
||||
$content = "🎲 【百家乐】第 #{$round->id} 局开奖!{$diceStr} 总点 {$round->total_points} → {$resultText}!{$payoutText}。{$detail}";
|
||||
$content = "🎲 第 #{$round->id} 局开奖:{$diceStr} {$round->total_points} 点,{$resultText}。{$payoutText}{$detail}";
|
||||
|
||||
$msg = [
|
||||
'id' => $chatState->nextMessageId(1),
|
||||
'room_id' => 1,
|
||||
'id' => $chatState->nextMessageId((int) $round->room_id),
|
||||
'room_id' => (int) $round->room_id,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => $content,
|
||||
@@ -322,8 +325,8 @@ class CloseBaccaratRoundJob implements ShouldQueue
|
||||
'action' => '大声宣告',
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
$chatState->pushMessage(1, $msg);
|
||||
broadcast(new MessageSent(1, $msg));
|
||||
$chatState->pushMessage((int) $round->room_id, $msg);
|
||||
broadcast(new MessageSent((int) $round->room_id, $msg));
|
||||
SaveMessageJob::dispatch($msg);
|
||||
|
||||
// 触发微信机器人消息推送 (百家乐结果,无人参与时不推送微信群防止刷屏)
|
||||
|
||||
@@ -26,6 +26,9 @@ use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* 类功能:完成一场赛马竞猜的派奖与结果广播。
|
||||
*/
|
||||
class CloseHorseRaceJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
@@ -181,7 +184,7 @@ class CloseHorseRaceJob implements ShouldQueue
|
||||
return;
|
||||
}
|
||||
|
||||
$roomId = 1;
|
||||
$roomId = (int) $race->room_id;
|
||||
$winnerName = $this->resolveWinnerHorseName($race);
|
||||
|
||||
foreach ($participantSettlements as $settlement) {
|
||||
@@ -243,11 +246,11 @@ class CloseHorseRaceJob implements ShouldQueue
|
||||
? '共派发 💰'.number_format($totalPayout).' 金币'
|
||||
: '本场无人获奖';
|
||||
|
||||
$content = "🏆 【赛马】第 #{$race->id} 场结束!冠军:{$winnerName}!{$payoutText}。";
|
||||
$content = "🏆 第 #{$race->id} 场结束,冠军:{$winnerName}。{$payoutText}";
|
||||
|
||||
$msg = [
|
||||
'id' => $chatState->nextMessageId(1),
|
||||
'room_id' => 1,
|
||||
'id' => $chatState->nextMessageId((int) $race->room_id),
|
||||
'room_id' => (int) $race->room_id,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => $content,
|
||||
@@ -256,8 +259,8 @@ class CloseHorseRaceJob implements ShouldQueue
|
||||
'action' => '大声宣告',
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
$chatState->pushMessage(1, $msg);
|
||||
broadcast(new MessageSent(1, $msg));
|
||||
$chatState->pushMessage((int) $race->room_id, $msg);
|
||||
broadcast(new MessageSent((int) $race->room_id, $msg));
|
||||
SaveMessageJob::dispatch($msg);
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,9 @@ use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* 类功能:按房间投放神秘箱子并广播暗号。
|
||||
*/
|
||||
class DropMysteryBoxJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
@@ -80,6 +83,7 @@ class DropMysteryBoxJob implements ShouldQueue
|
||||
|
||||
// 创建箱子记录
|
||||
$box = MysteryBox::create([
|
||||
'room_id' => $targetRoom,
|
||||
'box_type' => $this->boxType,
|
||||
'passcode' => $passcode,
|
||||
'reward_min' => $rewardMin,
|
||||
@@ -94,8 +98,7 @@ class DropMysteryBoxJob implements ShouldQueue
|
||||
$typeName = $box->typeName();
|
||||
$source = $this->droppedBy ? '管理员' : '系统';
|
||||
|
||||
$content = "{$emoji}【神秘箱子】《{$typeName}》{$source}投放了一个神秘箱子!"
|
||||
."发送暗号「{$passcode}」即可开箱!限时 {$claimWindow} 秒,先到先得!";
|
||||
$content = "{$emoji} 《{$typeName}》{$source}投放,暗号「{$passcode}」,限时 {$claimWindow} 秒。";
|
||||
|
||||
$msg = [
|
||||
'id' => $chatState->nextMessageId($targetRoom),
|
||||
|
||||
@@ -18,6 +18,9 @@ use App\Services\ChatStateService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
|
||||
/**
|
||||
* 类功能:关闭已超时的神秘箱子并广播过期提醒。
|
||||
*/
|
||||
class ExpireMysteryBoxJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
@@ -49,8 +52,8 @@ class ExpireMysteryBoxJob implements ShouldQueue
|
||||
|
||||
// 公屏广播过期通知
|
||||
$msg = [
|
||||
'id' => $chatState->nextMessageId(1),
|
||||
'room_id' => 1,
|
||||
'id' => $chatState->nextMessageId((int) $box->room_id),
|
||||
'room_id' => (int) $box->room_id,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => "⏰ 神秘箱子(暗号:{$box->passcode})已超时,箱子消失了!下次要快哦~",
|
||||
@@ -60,8 +63,8 @@ class ExpireMysteryBoxJob implements ShouldQueue
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
|
||||
$chatState->pushMessage(1, $msg);
|
||||
broadcast(new MessageSent(1, $msg));
|
||||
$chatState->pushMessage((int) $box->room_id, $msg);
|
||||
broadcast(new MessageSent((int) $box->room_id, $msg));
|
||||
SaveMessageJob::dispatch($msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,10 +21,22 @@ use App\Services\ChatStateService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
|
||||
/**
|
||||
* 类功能:按房间开启一局新的百家乐押注回合。
|
||||
*/
|
||||
class OpenBaccaratRoundJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
/**
|
||||
* 构造开局任务。
|
||||
*
|
||||
* @param int $roomId 目标房间
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $roomId = 1,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 最大重试次数。
|
||||
*/
|
||||
@@ -44,7 +56,7 @@ class OpenBaccaratRoundJob implements ShouldQueue
|
||||
$betSeconds = (int) ($config['bet_window_seconds'] ?? 60);
|
||||
|
||||
// 防止重复开局(如果上一局还在押注中则跳过)
|
||||
if (BaccaratRound::currentRound()) {
|
||||
if (BaccaratRound::currentRound($this->roomId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -53,6 +65,7 @@ class OpenBaccaratRoundJob implements ShouldQueue
|
||||
|
||||
// 创建新局次
|
||||
$round = BaccaratRound::create([
|
||||
'room_id' => $this->roomId,
|
||||
'status' => 'betting',
|
||||
'bet_opens_at' => $now,
|
||||
'bet_closes_at' => $closesAt,
|
||||
@@ -77,10 +90,10 @@ class OpenBaccaratRoundJob implements ShouldQueue
|
||||
.'onclick="event.preventDefault(); Alpine.$data(document.getElementById(\'baccarat-panel\')).openFromHall();" '
|
||||
.'style="margin-left:8px; padding:2px 8px; border:1px solid #7c3aed; border-radius:999px; background:#fff; color:#7c3aed; font-size:12px; font-weight:bold; cursor:pointer;">'
|
||||
.'快速参与</button>';
|
||||
$content = "🎲 【百家乐】第 #{$round->id} 局开始!下注时间 {$betSeconds} 秒,押注范围 {$minBet}~{$maxBet} 金币。赔率:🔵大/🟡小 1:{$bigRate} · 💥豹子 1:{$tripleRate}(☠️ {$killText} 点庄家收割)".$quickOpenButton;
|
||||
$content = "🎲 第 #{$round->id} 局开局:{$betSeconds} 秒下注,{$minBet}~{$maxBet} 金币,🔵/🟡 1:{$bigRate},💥 1:{$tripleRate},☠️ {$killText} 点收割。".$quickOpenButton;
|
||||
$msg = [
|
||||
'id' => $chatState->nextMessageId(1),
|
||||
'room_id' => 1,
|
||||
'id' => $chatState->nextMessageId($this->roomId),
|
||||
'room_id' => $this->roomId,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => $content,
|
||||
@@ -89,8 +102,8 @@ class OpenBaccaratRoundJob implements ShouldQueue
|
||||
'action' => '大声宣告',
|
||||
'sent_at' => $now->toDateTimeString(),
|
||||
];
|
||||
$chatState->pushMessage(1, $msg);
|
||||
broadcast(new MessageSent(1, $msg));
|
||||
$chatState->pushMessage($this->roomId, $msg);
|
||||
broadcast(new MessageSent($this->roomId, $msg));
|
||||
SaveMessageJob::dispatch($msg);
|
||||
|
||||
// 如果允许 AI 参与,延迟一定时间派发 AI 下注任务
|
||||
|
||||
@@ -21,10 +21,22 @@ use App\Services\ChatStateService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
|
||||
/**
|
||||
* 类功能:按房间开启一场新的赛马竞猜回合。
|
||||
*/
|
||||
class OpenHorseRaceJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
/**
|
||||
* 构造开赛任务。
|
||||
*
|
||||
* @param int $roomId 目标房间
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $roomId = 1,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 最大重试次数。
|
||||
*/
|
||||
@@ -41,7 +53,7 @@ class OpenHorseRaceJob implements ShouldQueue
|
||||
}
|
||||
|
||||
// 防止重复开赛(上一场还在进行中)
|
||||
if (HorseRace::currentRace()) {
|
||||
if (HorseRace::currentRace($this->roomId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -60,6 +72,7 @@ class OpenHorseRaceJob implements ShouldQueue
|
||||
|
||||
// 创建新场次
|
||||
$race = HorseRace::create([
|
||||
'room_id' => $this->roomId,
|
||||
'status' => 'betting',
|
||||
'bet_opens_at' => $now,
|
||||
'bet_closes_at' => $closesAt,
|
||||
@@ -79,11 +92,11 @@ class OpenHorseRaceJob implements ShouldQueue
|
||||
.'onclick="event.preventDefault(); Alpine.$data(document.getElementById(\'horse-race-panel\')).openFromHall();" '
|
||||
.'style="margin-left:8px; padding:2px 8px; border:1px solid #d97706; border-radius:999px; background:#fff7ed; color:#b45309; font-size:12px; font-weight:bold; cursor:pointer;">'
|
||||
.'快速参与赌马</button>';
|
||||
$content = "🐎 【赛马】第 #{$race->id} 场开始!押注时间 {$betSeconds} 秒,参赛马匹:{$horseList}。押注范围 ".number_format($minBet).'~'.number_format($maxBet).' 金币!'.$quickOpenButton;
|
||||
$content = "🐎 第 #{$race->id} 场开赛:{$horseList},{$betSeconds} 秒下注,".number_format($minBet).'~'.number_format($maxBet).' 金币。'.$quickOpenButton;
|
||||
|
||||
$msg = [
|
||||
'id' => $chatState->nextMessageId(1),
|
||||
'room_id' => 1,
|
||||
'id' => $chatState->nextMessageId($this->roomId),
|
||||
'room_id' => $this->roomId,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => $content,
|
||||
@@ -92,8 +105,8 @@ class OpenHorseRaceJob implements ShouldQueue
|
||||
'action' => '大声宣告',
|
||||
'sent_at' => $now->toDateTimeString(),
|
||||
];
|
||||
$chatState->pushMessage(1, $msg);
|
||||
broadcast(new MessageSent(1, $msg));
|
||||
$chatState->pushMessage($this->roomId, $msg);
|
||||
broadcast(new MessageSent($this->roomId, $msg));
|
||||
SaveMessageJob::dispatch($msg);
|
||||
|
||||
// 押注截止后触发跑马 & 结算任务
|
||||
|
||||
@@ -19,10 +19,22 @@ use App\Models\LotteryIssue;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
|
||||
/**
|
||||
* 类功能:按房间创建一条新的双色球期次。
|
||||
*/
|
||||
class OpenLotteryIssueJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
/**
|
||||
* 构造开期任务。
|
||||
*
|
||||
* @param int $roomId 目标房间
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly int $roomId = 1,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 最大重试次数。
|
||||
*/
|
||||
@@ -38,7 +50,7 @@ class OpenLotteryIssueJob implements ShouldQueue
|
||||
}
|
||||
|
||||
// 已有进行中的期次则跳过
|
||||
if (LotteryIssue::currentIssue()) {
|
||||
if (LotteryIssue::currentIssue($this->roomId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -56,7 +68,8 @@ class OpenLotteryIssueJob implements ShouldQueue
|
||||
$closeAt = $drawAt->copy()->subMinutes($stopMinutes);
|
||||
|
||||
LotteryIssue::create([
|
||||
'issue_no' => LotteryIssue::nextIssueNo(),
|
||||
'room_id' => $this->roomId,
|
||||
'issue_no' => LotteryIssue::nextIssueNo($this->roomId),
|
||||
'status' => 'open',
|
||||
'pool_amount' => 0,
|
||||
'carry_amount' => 0,
|
||||
|
||||
@@ -22,6 +22,12 @@ use App\Services\ChatStateService;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Queue\Queueable;
|
||||
|
||||
/**
|
||||
* 类功能:赛马跑马动画广播与结算衔接任务
|
||||
*
|
||||
* 负责在押注截止后推进 running 流程、广播实时进度,
|
||||
* 并在同一条任务链中补齐赛果与触发最终结算,避免线上状态滞留。
|
||||
*/
|
||||
class RunHorseRaceJob implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
@@ -72,18 +78,18 @@ class RunHorseRaceJob implements ShouldQueue
|
||||
));
|
||||
|
||||
$startMsg = [
|
||||
'id' => $chatState->nextMessageId(1),
|
||||
'room_id' => 1,
|
||||
'id' => $chatState->nextMessageId((int) $race->room_id),
|
||||
'room_id' => (int) $race->room_id,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => "🏇 【赛马】第 #{$race->id} 场押注截止!马匹已进入跑道,比赛开始!参赛阵容:{$horseList}",
|
||||
'content' => "🏇 第 #{$race->id} 场比赛开始:{$horseList}",
|
||||
'is_secret' => false,
|
||||
'font_color' => '#16a34a',
|
||||
'action' => '大声宣告',
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
$chatState->pushMessage(1, $startMsg);
|
||||
broadcast(new MessageSent(1, $startMsg));
|
||||
$chatState->pushMessage((int) $race->room_id, $startMsg);
|
||||
broadcast(new MessageSent((int) $race->room_id, $startMsg));
|
||||
SaveMessageJob::dispatch($startMsg);
|
||||
|
||||
$config = GameConfig::forGame('horse_racing')?->params ?? [];
|
||||
@@ -126,7 +132,7 @@ class RunHorseRaceJob implements ShouldQueue
|
||||
}
|
||||
|
||||
// 广播当前帧进度
|
||||
broadcast(new HorseRaceProgress($race->id, $positions, $finished, $winnerId ?? $this->leadingHorse($positions)));
|
||||
broadcast(new HorseRaceProgress($race->id, (int) $race->room_id, $positions, $finished, $winnerId ?? $this->leadingHorse($positions)));
|
||||
|
||||
if ($finished) {
|
||||
break;
|
||||
@@ -156,8 +162,8 @@ class RunHorseRaceJob implements ShouldQueue
|
||||
'total_pool' => $totalPool,
|
||||
]);
|
||||
|
||||
// 触发结算任务
|
||||
CloseHorseRaceJob::dispatch($race->fresh());
|
||||
// 在同一条队列任务里直接完成结算,避免线上出现“已跑完但 Close 任务未继续消费”的断链。
|
||||
app()->call([new CloseHorseRaceJob($race->fresh()), 'handle']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,9 +16,13 @@ namespace App\Models;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* 类功能:保存百家乐局次数据并提供当前局查询能力。
|
||||
*/
|
||||
class BaccaratRound extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'room_id',
|
||||
'dice1', 'dice2', 'dice3',
|
||||
'total_points', 'result', 'status',
|
||||
'bet_opens_at', 'bet_closes_at', 'settled_at',
|
||||
@@ -36,6 +40,7 @@ class BaccaratRound extends Model
|
||||
'bet_opens_at' => 'datetime',
|
||||
'bet_closes_at' => 'datetime',
|
||||
'settled_at' => 'datetime',
|
||||
'room_id' => 'integer',
|
||||
'dice1' => 'integer',
|
||||
'dice2' => 'integer',
|
||||
'dice3' => 'integer',
|
||||
@@ -104,12 +109,16 @@ class BaccaratRound extends Model
|
||||
/**
|
||||
* 查询当前正在进行的局次(状态为 betting 且未截止)。
|
||||
*/
|
||||
public static function currentRound(): ?static
|
||||
public static function currentRound(?int $roomId = null): ?static
|
||||
{
|
||||
return static::query()
|
||||
$query = static::query()
|
||||
->where('status', 'betting')
|
||||
->where('bet_closes_at', '>', now())
|
||||
->latest()
|
||||
->first();
|
||||
->where('bet_closes_at', '>', now());
|
||||
|
||||
if ($roomId !== null) {
|
||||
$query->where('room_id', $roomId);
|
||||
}
|
||||
|
||||
return $query->latest()->first();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,9 +16,16 @@ namespace App\Models;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* 类功能:赛马竞猜局次模型
|
||||
*
|
||||
* 负责描述赛马场次的生命周期、参赛马匹、下注汇总与派奖计算,
|
||||
* 并为控制器和队列任务提供当前场次、赔率与奖池算法支持。
|
||||
*/
|
||||
class HorseRace extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'room_id',
|
||||
'status',
|
||||
'bet_opens_at',
|
||||
'bet_closes_at',
|
||||
@@ -42,6 +49,7 @@ class HorseRace extends Model
|
||||
'race_starts_at' => 'datetime',
|
||||
'race_ends_at' => 'datetime',
|
||||
'settled_at' => 'datetime',
|
||||
'room_id' => 'integer',
|
||||
'horses' => 'array',
|
||||
'winner_horse_id' => 'integer',
|
||||
'total_bets' => 'integer',
|
||||
@@ -69,12 +77,15 @@ class HorseRace extends Model
|
||||
/**
|
||||
* 查询当前正在进行的场次(状态为 betting 且押注未截止)。
|
||||
*/
|
||||
public static function currentRace(): ?static
|
||||
public static function currentRace(?int $roomId = null): ?static
|
||||
{
|
||||
return static::query()
|
||||
->whereIn('status', ['betting', 'running'])
|
||||
->latest()
|
||||
->first();
|
||||
$query = static::query()->whereIn('status', ['betting', 'running']);
|
||||
|
||||
if ($roomId !== null) {
|
||||
$query->where('room_id', $roomId);
|
||||
}
|
||||
|
||||
return $query->latest()->first();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,9 +16,13 @@ namespace App\Models;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* 类功能:保存双色球期次数据并提供按房间查询能力。
|
||||
*/
|
||||
class LotteryIssue extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'room_id',
|
||||
'issue_no',
|
||||
'status',
|
||||
'red1', 'red2', 'red3', 'blue',
|
||||
@@ -38,6 +42,7 @@ class LotteryIssue extends Model
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'room_id' => 'integer',
|
||||
'is_super_issue' => 'boolean',
|
||||
'pool_amount' => 'integer',
|
||||
'carry_amount' => 'integer',
|
||||
@@ -71,29 +76,44 @@ class LotteryIssue extends Model
|
||||
/**
|
||||
* 获取当前正在购票的期次(status=open)。
|
||||
*/
|
||||
public static function currentIssue(): ?static
|
||||
public static function currentIssue(?int $roomId = null): ?static
|
||||
{
|
||||
return static::query()->where('status', 'open')->latest()->first();
|
||||
$query = static::query()->where('status', 'open');
|
||||
|
||||
if ($roomId !== null) {
|
||||
$query->where('room_id', $roomId);
|
||||
}
|
||||
|
||||
return $query->latest()->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最新一期(不论状态)。
|
||||
*/
|
||||
public static function latestIssue(): ?static
|
||||
public static function latestIssue(?int $roomId = null): ?static
|
||||
{
|
||||
return static::query()->latest()->first();
|
||||
$query = static::query();
|
||||
|
||||
if ($roomId !== null) {
|
||||
$query->where('room_id', $roomId);
|
||||
}
|
||||
|
||||
return $query->latest()->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成下一期的期号(格式:年份 + 三位序号,如 2026001)。
|
||||
*/
|
||||
public static function nextIssueNo(): string
|
||||
public static function nextIssueNo(?int $roomId = null): string
|
||||
{
|
||||
$year = now()->year;
|
||||
$last = static::query()
|
||||
->whereYear('created_at', $year)
|
||||
->latest()
|
||||
->first();
|
||||
$query = static::query()->whereYear('created_at', $year);
|
||||
|
||||
if ($roomId !== null) {
|
||||
$query->where('room_id', $roomId);
|
||||
}
|
||||
|
||||
$last = $query->latest()->first();
|
||||
|
||||
$seq = $last ? ((int) substr($last->issue_no, -3)) + 1 : 1;
|
||||
|
||||
|
||||
@@ -17,9 +17,13 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
|
||||
/**
|
||||
* 类功能:保存神秘箱子投放记录并提供当前箱子查询能力。
|
||||
*/
|
||||
class MysteryBox extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'room_id',
|
||||
'box_type',
|
||||
'passcode',
|
||||
'reward_min',
|
||||
@@ -35,6 +39,7 @@ class MysteryBox extends Model
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'room_id' => 'integer',
|
||||
'reward_min' => 'integer',
|
||||
'reward_max' => 'integer',
|
||||
'expires_at' => 'datetime',
|
||||
@@ -64,13 +69,17 @@ class MysteryBox extends Model
|
||||
/**
|
||||
* 当前可领取(open 状态 + 未过期)的箱子。
|
||||
*/
|
||||
public static function currentOpenBox(): ?static
|
||||
public static function currentOpenBox(?int $roomId = null): ?static
|
||||
{
|
||||
return static::query()
|
||||
$query = static::query()
|
||||
->where('status', 'open')
|
||||
->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))
|
||||
->latest()
|
||||
->first();
|
||||
->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()));
|
||||
|
||||
if ($roomId !== null) {
|
||||
$query->where('room_id', $roomId);
|
||||
}
|
||||
|
||||
return $query->latest()->first();
|
||||
}
|
||||
|
||||
// ─── 工具方法 ────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:猜谜活动题库模型
|
||||
*
|
||||
* 对应 idioms 表,统一承载成语题与脑筋急转弯题目。
|
||||
*/
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* 类功能:统一管理猜谜活动的题目、答案、提示与题型。
|
||||
*/
|
||||
class Riddle extends Model
|
||||
{
|
||||
/**
|
||||
* 属性功能:显式绑定历史题库表名,避免类名重命名后推导到错误表。
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'idioms';
|
||||
|
||||
/**
|
||||
* 常量功能:声明成语题题型标识。
|
||||
*/
|
||||
public const TYPE_IDIOM = 'idiom';
|
||||
|
||||
/**
|
||||
* 常量功能:声明脑筋急转弯题型标识。
|
||||
*/
|
||||
public const TYPE_BRAIN_TEASER = 'brain_teaser';
|
||||
|
||||
/**
|
||||
* 方法功能:声明允许批量赋值的题库字段。
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $fillable = [
|
||||
'type',
|
||||
'answer',
|
||||
'hint',
|
||||
'is_active',
|
||||
'sort',
|
||||
];
|
||||
|
||||
/**
|
||||
* 方法功能:定义题库字段的类型转换规则。
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_active' => 'boolean',
|
||||
'sort' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:返回系统支持的全部题型。
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function supportedTypes(): array
|
||||
{
|
||||
return [
|
||||
self::TYPE_IDIOM,
|
||||
self::TYPE_BRAIN_TEASER,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:判断给定题型是否属于系统支持范围。
|
||||
*/
|
||||
public static function isSupportedType(string $type): bool
|
||||
{
|
||||
return in_array($type, self::supportedTypes(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:根据题型返回面向用户的中文名称。
|
||||
*/
|
||||
public static function labelForType(string $type): string
|
||||
{
|
||||
return match ($type) {
|
||||
self::TYPE_BRAIN_TEASER => '脑筋急转弯',
|
||||
default => '猜成语',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:返回后台表单可直接使用的题型键值对。
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function typeOptions(): array
|
||||
{
|
||||
return collect(self::supportedTypes())
|
||||
->mapWithKeys(fn (string $type): array => [$type => self::labelForType($type)])
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:返回题型对应的活动标题。
|
||||
*/
|
||||
public static function activityLabelForType(string $type): string
|
||||
{
|
||||
return '猜谜活动·'.self::labelForType($type);
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:按题型筛选题库记录。
|
||||
*/
|
||||
public function scopeOfType(Builder $query, string $type): Builder
|
||||
{
|
||||
return $query->where('type', self::isSupportedType($type) ? $type : self::TYPE_IDIOM);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:猜谜活动回合模型
|
||||
*
|
||||
* 每次出题对应一个回合,记录题型、题目、状态、奖励和获胜者。
|
||||
*/
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* 类功能:记录猜谜活动每一轮的题型、奖励与结算状态。
|
||||
*/
|
||||
class RiddleGameRound extends Model
|
||||
{
|
||||
/**
|
||||
* 属性功能:显式绑定历史回合表名,避免类名重命名后推导到错误表。
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $table = 'idiom_game_rounds';
|
||||
|
||||
/**
|
||||
* 方法功能:声明可批量赋值的回合字段。
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $fillable = [
|
||||
'room_id',
|
||||
'idiom_id',
|
||||
'quiz_type',
|
||||
'status',
|
||||
'reward_gold',
|
||||
'reward_exp',
|
||||
'winner_id',
|
||||
'winner_username',
|
||||
'started_at',
|
||||
'ended_at',
|
||||
];
|
||||
|
||||
/**
|
||||
* 方法功能:定义回合字段的类型转换规则。
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'room_id' => 'integer',
|
||||
'idiom_id' => 'integer',
|
||||
'reward_gold' => 'integer',
|
||||
'reward_exp' => 'integer',
|
||||
'started_at' => 'datetime',
|
||||
'ended_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:关联本回合对应的猜谜题目。
|
||||
*/
|
||||
public function idiom(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Riddle::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:聊天室座驾模型。
|
||||
*
|
||||
* 对应 rides 表,保存座驾名称、特效 key、价格、使用天数、欢迎语与上下架状态。
|
||||
*/
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* 聊天室座驾模型
|
||||
* 负责提供座驾定义、全屏特效 key 和购买记录关系。
|
||||
*/
|
||||
class Ride extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'name', 'slug', 'effect_key', 'icon', 'description', 'price',
|
||||
'duration_days', 'welcome_message', 'sort_order', 'is_active',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
|
||||
/**
|
||||
* 获取座驾对应的所有购买记录。
|
||||
*/
|
||||
public function purchases(): HasMany
|
||||
{
|
||||
return $this->hasMany(UserRidePurchase::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取座驾全屏特效 key。
|
||||
*/
|
||||
public function rideKey(): string
|
||||
{
|
||||
return $this->effect_key;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有上架座驾。
|
||||
*
|
||||
* @return Collection<int, self>
|
||||
*/
|
||||
public static function active(): Collection
|
||||
{
|
||||
return static::query()
|
||||
->where('is_active', true)
|
||||
->orderBy('sort_order')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ class ShopItem extends Model
|
||||
{
|
||||
public const TYPE_SIGN_REPAIR = 'sign_repair';
|
||||
|
||||
public const DECORATION_TYPES = ['msg_bubble', 'msg_name_color', 'msg_text_color', 'avatar_frame'];
|
||||
|
||||
protected $table = 'shop_items';
|
||||
|
||||
protected $fillable = [
|
||||
@@ -51,6 +53,14 @@ class ShopItem extends Model
|
||||
return $this->type === self::TYPE_SIGN_REPAIR;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为个人装扮(气泡、颜色、头像框等)。
|
||||
*/
|
||||
public function isDecoration(): bool
|
||||
{
|
||||
return in_array($this->type, self::DECORATION_TYPES, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否为特效类商品(instant 或 duration,slug 以 once_ 或 week_ 开头)
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:用户座驾购买记录模型。
|
||||
*
|
||||
* 对应 user_ride_purchases 表,追踪用户座驾购买、续期、替换和过期状态。
|
||||
*/
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* 用户座驾购买记录模型
|
||||
* 负责连接用户与座驾,并判断当前记录是否仍有效。
|
||||
*/
|
||||
class UserRidePurchase extends Model
|
||||
{
|
||||
protected $fillable = [
|
||||
'user_id', 'ride_id', 'status', 'price_paid', 'expires_at', 'used_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'expires_at' => 'datetime',
|
||||
'used_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* 获取购买记录所属用户。
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取购买记录对应座驾。
|
||||
*/
|
||||
public function ride(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Ride::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断座驾购买记录是否仍然有效。
|
||||
*/
|
||||
public function isAlive(): bool
|
||||
{
|
||||
if ($this->status !== 'active') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->expires_at && $this->expires_at->isPast()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -400,7 +400,8 @@ class BaccaratLossCoverService
|
||||
}
|
||||
|
||||
if ($compensableCount > 0) {
|
||||
$button = '<button onclick="claimBaccaratLossCover('.$event->id.')" style="margin-left:8px;padding:3px 12px;background:#16a34a;color:#fff;border:none;border-radius:12px;cursor:pointer;font-size:12px;font-weight:bold;">领取补偿</button>';
|
||||
// 聊天消息内的按钮使用相对字号,跟随用户在底部工具栏选择的聊天字号。
|
||||
$button = '<button onclick="claimBaccaratLossCover('.$event->id.')" style="margin-left:8px;padding:3px 12px;background:#16a34a;color:#fff;border:none;border-radius:12px;cursor:pointer;font-size:0.82em;font-weight:bold;">领取补偿</button>';
|
||||
$content = "📣 【{$event->title}】活动已结束并完成结算!本次共有 <b>{$compensableCount}</b> 位玩家可领取补偿,截止时间:{$event->claim_deadline_at?->format('m-d H:i')}。{$button}";
|
||||
} else {
|
||||
$content = "📣 【{$event->title}】活动已结束!本次活动没有产生可领取补偿的记录。";
|
||||
@@ -446,7 +447,7 @@ class BaccaratLossCoverService
|
||||
|
||||
$formattedAmount = number_format($amount);
|
||||
$button = $event->status === 'claimable'
|
||||
? ' <button onclick="claimBaccaratLossCover('.$event->id.')" style="margin-left:8px;padding:3px 12px;background:#16a34a;color:#fff;border:none;border-radius:12px;cursor:pointer;font-size:12px;font-weight:bold;">领取补偿</button>'
|
||||
? ' <button onclick="claimBaccaratLossCover('.$event->id.')" style="margin-left:8px;padding:3px 12px;background:#16a34a;color:#fff;border:none;border-radius:12px;cursor:pointer;font-size:0.82em;font-weight:bold;">领取补偿</button>'
|
||||
: '';
|
||||
|
||||
// 领取成功的公屏格式复用百家乐参与播报风格,保证聊天室感知一致。
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
* (会员加成:+经验X,+金币Y)
|
||||
*
|
||||
* @author ChatRoom Laravel
|
||||
*
|
||||
* @version 1.2.0
|
||||
*/
|
||||
|
||||
@@ -24,20 +25,19 @@ use App\Models\User;
|
||||
class FishingService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ChatStateService $chatState,
|
||||
private readonly VipService $vipService,
|
||||
private readonly ChatStateService $chatState,
|
||||
private readonly VipService $vipService,
|
||||
private readonly UserCurrencyService $currencyService,
|
||||
private readonly ShopService $shopService,
|
||||
)
|
||||
{
|
||||
}
|
||||
private readonly ShopService $shopService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 处理收竿逻辑:计算结果、发放积分并全服广播。
|
||||
*
|
||||
* @param User $user 收竿的用户实体
|
||||
* @param int $roomId 所在房间 ID
|
||||
* @param bool $isAi 是否为 AI 调用(用于影响文案或标签)
|
||||
* @param User $user 收竿的用户实体
|
||||
* @param int $roomId 所在房间 ID
|
||||
* @param bool $isAi 是否为 AI 调用(用于影响文案或标签)
|
||||
* @return array{emoji:string,message:string,exp:int,jjb:int,base_exp:int,base_jjb:int,bonus_exp:int,bonus_jjb:int}
|
||||
*/
|
||||
public function processCatch(User $user, int $roomId, bool $isAi = false): array
|
||||
{
|
||||
@@ -54,11 +54,11 @@ class FishingService
|
||||
|
||||
if ($result['exp'] !== 0) {
|
||||
// 当经验为 正数 则可使用会员翻倍,负数则不
|
||||
$finalExp = $result['exp'] > 0 ? (int)round($result['exp'] * $expMul) : $result['exp'];
|
||||
$finalExp = $result['exp'] > 0 ? (int) round($result['exp'] * $expMul) : $result['exp'];
|
||||
}
|
||||
|
||||
if ($result['jjb'] !== 0) {
|
||||
$finalJjb = $result['jjb'] > 0 ? (int)round($result['jjb'] * $jjbMul) : $result['jjb'];
|
||||
$finalJjb = $result['jjb'] > 0 ? (int) round($result['jjb'] * $jjbMul) : $result['jjb'];
|
||||
}
|
||||
|
||||
// 4. 计算会员额外加成部分
|
||||
@@ -92,16 +92,19 @@ class FishingService
|
||||
|
||||
// 8. 广播钓鱼结果到聊天室
|
||||
$promoTag = '';
|
||||
if (!$isAi) {
|
||||
if (! $isAi) {
|
||||
$autoFishingMinutesLeft = $this->shopService->getActiveAutoFishingMinutesLeft($user);
|
||||
// 公屏消息内的促销标签使用相对字号,避免覆盖用户在聊天室选择的字号。
|
||||
$promoTag = $autoFishingMinutesLeft > 0
|
||||
? ' <span onclick="window.openShopModal&&window.openShopModal()" '
|
||||
. 'style="display:inline-block;margin-left:6px;padding:1px 7px;background:#e9e4f5;'
|
||||
. 'color:#6d4fa8;border-radius:10px;font-size:10px;cursor:pointer;font-weight:bold;vertical-align:middle;'
|
||||
. 'border:1px solid #d0c4ec;" title="点击购买自动钓鱼卡">🎣 自动钓鱼卡</span>'
|
||||
.'style="display:inline-block;margin-left:6px;padding:1px 7px;background:#e9e4f5;'
|
||||
.'color:#6d4fa8;border-radius:10px;font-size:0.78em;cursor:pointer;font-weight:bold;vertical-align:middle;'
|
||||
.'border:1px solid #d0c4ec;" title="点击购买自动钓鱼卡">🎣 自动钓鱼卡</span>'
|
||||
: '';
|
||||
}
|
||||
|
||||
// 广播结果时额外带上统一动作标记和钓鱼者用户名,
|
||||
// 方便前端把“钓鱼者本人”的公屏结果折叠到包厢窗口,避免重复显示。
|
||||
$sysMsg = [
|
||||
'id' => $this->chatState->nextMessageId($roomId),
|
||||
'room_id' => $roomId,
|
||||
@@ -110,7 +113,8 @@ class FishingService
|
||||
'content' => "{$result['emoji']} 【{$user->username}】{$finalMessage}{$promoTag}",
|
||||
'is_secret' => false,
|
||||
'font_color' => ($result['exp'] < 0 || $result['jjb'] < 0) ? '#dc2626' : '#16a34a',
|
||||
'action' => '',
|
||||
'action' => 'fishing_result',
|
||||
'fishing_username' => $user->username,
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
|
||||
@@ -154,7 +158,7 @@ class FishingService
|
||||
return $baseMessage;
|
||||
}
|
||||
|
||||
return $baseMessage . '(' . $user->vipName() . '追加:' . implode(',', $bonusParts) . ')';
|
||||
return $baseMessage.'('.$user->vipName().'追加:'.implode(',', $bonusParts).')';
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -168,7 +172,7 @@ class FishingService
|
||||
{
|
||||
$event = FishingEvent::rollOne();
|
||||
|
||||
if (!$event) {
|
||||
if (! $event) {
|
||||
return [
|
||||
'emoji' => '🐟',
|
||||
'message' => '钓到一条小鱼,获得金币10',
|
||||
@@ -180,8 +184,8 @@ class FishingService
|
||||
return [
|
||||
'emoji' => $event->emoji,
|
||||
'message' => $event->message,
|
||||
'exp' => (int)$event->exp,
|
||||
'jjb' => (int)$event->jjb,
|
||||
'exp' => (int) $event->exp,
|
||||
'jjb' => (int) $event->jjb,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:游戏房间范围配置服务
|
||||
*
|
||||
* 统一解析所有游戏的 room_scope_mode 与 room_ids 配置,
|
||||
* 供后台保存、调度任务、前台准入校验和公共回合查询复用。
|
||||
*/
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\GameConfig;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* 类功能:统一管理所有游戏的房间范围读取与房间判定。
|
||||
*/
|
||||
class GameRoomScopeService
|
||||
{
|
||||
/**
|
||||
* 房间模式常量:全部房间。
|
||||
*/
|
||||
public const MODE_ALL = 'all';
|
||||
|
||||
/**
|
||||
* 房间模式常量:单选房间。
|
||||
*/
|
||||
public const MODE_SINGLE = 'single';
|
||||
|
||||
/**
|
||||
* 房间模式常量:多选房间。
|
||||
*/
|
||||
public const MODE_MULTIPLE = 'multiple';
|
||||
|
||||
/**
|
||||
* 支持的房间模式列表。
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
public const SUPPORTED_MODES = [
|
||||
self::MODE_ALL,
|
||||
self::MODE_SINGLE,
|
||||
self::MODE_MULTIPLE,
|
||||
];
|
||||
|
||||
/**
|
||||
* 构造房间范围服务。
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly ChatStateService $chatState,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 归一化房间模式。
|
||||
*/
|
||||
public function normalizeRoomScopeMode(?string $mode, string $default = self::MODE_SINGLE): string
|
||||
{
|
||||
$normalizedMode = (string) $mode;
|
||||
|
||||
if (! in_array($normalizedMode, self::SUPPORTED_MODES, true)) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $normalizedMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把原始房间数组归一化为去重后的整型数组。
|
||||
*
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public function normalizeRoomIds(mixed $roomIds, array $default = [1]): array
|
||||
{
|
||||
$items = is_array($roomIds)
|
||||
? $roomIds
|
||||
: preg_split('/[\s,,]+/u', (string) $roomIds, -1, PREG_SPLIT_NO_EMPTY);
|
||||
|
||||
$normalizedRoomIds = collect($items)
|
||||
->map(fn (mixed $roomId): int => (int) $roomId)
|
||||
->filter(fn (int $roomId): bool => $roomId > 0)
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
if ($normalizedRoomIds === []) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $normalizedRoomIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 params 数组中解析房间范围配置。
|
||||
*
|
||||
* @return array{room_scope_mode:string,room_ids:array<int, int>}
|
||||
*/
|
||||
public function getScopeConfigForParams(array $params, array $defaultRoomIds = [1]): array
|
||||
{
|
||||
if (
|
||||
! array_key_exists('room_scope_mode', $params)
|
||||
&& ! array_key_exists('room_ids', $params)
|
||||
&& ! array_key_exists('room_id', $params)
|
||||
) {
|
||||
return [
|
||||
'room_scope_mode' => self::MODE_ALL,
|
||||
'room_ids' => $this->normalizeRoomIds($defaultRoomIds, [1]),
|
||||
];
|
||||
}
|
||||
|
||||
$roomScopeMode = $this->normalizeRoomScopeMode(
|
||||
mode: (string) ($params['room_scope_mode'] ?? self::MODE_SINGLE),
|
||||
default: self::MODE_SINGLE,
|
||||
);
|
||||
|
||||
$roomIds = $this->normalizeRoomIds(
|
||||
roomIds: $params['room_ids'] ?? (($params['room_id'] ?? null) !== null ? [$params['room_id']] : []),
|
||||
default: $defaultRoomIds,
|
||||
);
|
||||
|
||||
return [
|
||||
'room_scope_mode' => $roomScopeMode,
|
||||
'room_ids' => $roomIds,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取指定游戏当前配置中的房间范围。
|
||||
*
|
||||
* @return array{room_scope_mode:string,room_ids:array<int, int>}
|
||||
*/
|
||||
public function getScopeConfigForGame(string $gameKey, array $defaultRoomIds = [1]): array
|
||||
{
|
||||
$params = GameConfig::forGame($gameKey)?->params ?? [];
|
||||
|
||||
return $this->getScopeConfigForParams($params, $defaultRoomIds);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定游戏真正生效的房间 ID 列表。
|
||||
*
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public function getScopedRoomIdsForGame(string $gameKey, array $defaultRoomIds = [1]): array
|
||||
{
|
||||
$scopeConfig = $this->getScopeConfigForGame($gameKey, $defaultRoomIds);
|
||||
|
||||
if ($scopeConfig['room_scope_mode'] === self::MODE_ALL) {
|
||||
return $this->resolveAllAvailableRoomIds($defaultRoomIds);
|
||||
}
|
||||
|
||||
return $scopeConfig['room_ids'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定游戏的首选房间。
|
||||
*/
|
||||
public function getPrimaryRoomIdForGame(string $gameKey, int $fallback = 1): int
|
||||
{
|
||||
$roomIds = $this->getScopedRoomIdsForGame($gameKey, [$fallback]);
|
||||
|
||||
return $roomIds[0] ?? $fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断某个房间是否在指定游戏允许范围内。
|
||||
*/
|
||||
public function isRoomAllowedForGame(string $gameKey, int $roomId, array $defaultRoomIds = [1]): bool
|
||||
{
|
||||
return in_array($roomId, $this->getScopedRoomIdsForGame($gameKey, $defaultRoomIds), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从请求或在线状态解析当前操作房间。
|
||||
*/
|
||||
public function resolveRequestRoomId(Request $request, ?User $user = null, int $fallback = 1): int
|
||||
{
|
||||
$requestedRoomId = (int) $request->integer('room_id', 0);
|
||||
if ($requestedRoomId > 0) {
|
||||
return $requestedRoomId;
|
||||
}
|
||||
|
||||
return $this->resolveUserRoomId($user ?? $request->user(), $fallback);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从用户在线房间或用户资料中推断当前房间。
|
||||
*/
|
||||
public function resolveUserRoomId(?User $user, int $fallback = 1): int
|
||||
{
|
||||
if (! $user) {
|
||||
return $fallback;
|
||||
}
|
||||
|
||||
$activeRoomIds = $this->chatState->getUserRooms($user->username);
|
||||
if ($activeRoomIds !== []) {
|
||||
return (int) $activeRoomIds[0];
|
||||
}
|
||||
|
||||
$profileRoomId = (int) ($user->room_id ?? 0);
|
||||
|
||||
return $profileRoomId > 0 ? $profileRoomId : $fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回通用后台复用的默认房间范围配置。
|
||||
*
|
||||
* @return array{room_scope_mode:string,room_ids:array<int, int>}
|
||||
*/
|
||||
public function defaultScopeConfig(array $defaultRoomIds = [1]): array
|
||||
{
|
||||
return [
|
||||
'room_scope_mode' => self::MODE_SINGLE,
|
||||
'room_ids' => $this->normalizeRoomIds($defaultRoomIds, [1]),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 在“全部房间”模式下解析当前可用房间。
|
||||
*
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private function resolveAllAvailableRoomIds(array $defaultRoomIds = [1]): array
|
||||
{
|
||||
$roomIds = \App\Models\Room::query()
|
||||
->orderBy('id')
|
||||
->pluck('id')
|
||||
->map(fn (mixed $roomId): int => (int) $roomId)
|
||||
->all();
|
||||
|
||||
return $roomIds !== [] ? $roomIds : $defaultRoomIds;
|
||||
}
|
||||
}
|
||||
@@ -22,11 +22,15 @@ use App\Models\LotteryTicket;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* 类功能:负责双色球购票、开奖、滚存与房间广播。
|
||||
*/
|
||||
class LotteryService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly UserCurrencyService $currency,
|
||||
private readonly ChatStateService $chatState,
|
||||
private readonly GameRoomScopeService $roomScopeService,
|
||||
) {}
|
||||
|
||||
// ─── 购票 ─────────────────────────────────────────────────────────
|
||||
@@ -49,7 +53,8 @@ class LotteryService
|
||||
throw new \RuntimeException('双色球彩票游戏未开启');
|
||||
}
|
||||
|
||||
$issue = LotteryIssue::currentIssue();
|
||||
$roomId = $this->roomScopeService->resolveUserRoomId($user);
|
||||
$issue = LotteryIssue::currentIssue($roomId);
|
||||
if (! $issue || ! $issue->isOpen()) {
|
||||
throw new \RuntimeException('当前无正在进行的期次,或已停售');
|
||||
}
|
||||
@@ -135,7 +140,7 @@ class LotteryService
|
||||
$firstTicket = $tickets[0];
|
||||
$numsStr = $firstTicket->numbersLabel();
|
||||
$moreStr = $buyCount > 1 ? "等 {$buyCount} 注号码" : '';
|
||||
$this->pushSystemMessage("🎟️ 【双色球彩票】财神爷保佑!玩家【{$user->username}】豪掷千金,购买了当前 #{$issue->issue_no} 期双色球 {$numsStr} {$moreStr},祝 Ta 中大奖!");
|
||||
$this->pushSystemMessage("🎟️ 【{$user->username}】购买 {$issue->issue_no} 期 {$numsStr} {$moreStr}", (int) $issue->room_id);
|
||||
|
||||
return $tickets;
|
||||
}
|
||||
@@ -364,7 +369,8 @@ class LotteryService
|
||||
}
|
||||
|
||||
$newIssue = LotteryIssue::create([
|
||||
'issue_no' => LotteryIssue::nextIssueNo(),
|
||||
'room_id' => (int) $prevIssue->room_id,
|
||||
'issue_no' => LotteryIssue::nextIssueNo((int) $prevIssue->room_id),
|
||||
'status' => 'open',
|
||||
'pool_amount' => $carryAmount + $injectAmount,
|
||||
'carry_amount' => $carryAmount,
|
||||
@@ -444,9 +450,9 @@ class LotteryService
|
||||
|
||||
$detailStr = $details ? ' '.implode(' | ', $details) : '';
|
||||
|
||||
$content = "🎟️ 【双色球 第{$issue->issue_no}期 开奖】{$drawNums} {$line1}{$detailStr}";
|
||||
$content = "🎟️ 第 #{$issue->issue_no} 期开奖:{$drawNums} {$line1}{$detailStr}";
|
||||
|
||||
$this->pushSystemMessage($content);
|
||||
$this->pushSystemMessage($content, (int) $issue->room_id);
|
||||
|
||||
// 触发微信机器人消息推送 (彩票开奖)
|
||||
try {
|
||||
@@ -463,20 +469,19 @@ class LotteryService
|
||||
private function broadcastSuperIssue(LotteryIssue $issue): void
|
||||
{
|
||||
$pool = number_format($issue->pool_amount);
|
||||
$content = "🎊🎟️ 【双色球超级期预警】第 {$issue->issue_no} 期已连续 {$issue->no_winner_streak} 期无一等奖!"
|
||||
."当前奖池 💰 {$pool} 金币,系统已追加注入!今日 {$issue->draw_at?->format('H:i')} 开奖,赶紧购票!";
|
||||
$content = "🎊 第 #{$issue->issue_no} 期超级期:已连续 {$issue->no_winner_streak} 期无一等奖,奖池 💰 {$pool},{$issue->draw_at?->format('H:i')} 开奖。";
|
||||
|
||||
$this->pushSystemMessage($content);
|
||||
$this->pushSystemMessage($content, (int) $issue->room_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 向公屏发送系统消息。
|
||||
*/
|
||||
private function pushSystemMessage(string $content): void
|
||||
private function pushSystemMessage(string $content, int $roomId): void
|
||||
{
|
||||
$msg = [
|
||||
'id' => $this->chatState->nextMessageId(1),
|
||||
'room_id' => 1,
|
||||
'id' => $this->chatState->nextMessageId($roomId),
|
||||
'room_id' => $roomId,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => $content,
|
||||
@@ -485,8 +490,8 @@ class LotteryService
|
||||
'action' => '大声宣告',
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
$this->chatState->pushMessage(1, $msg);
|
||||
broadcast(new MessageSent(1, $msg));
|
||||
$this->chatState->pushMessage($roomId, $msg);
|
||||
broadcast(new MessageSent($roomId, $msg));
|
||||
\App\Jobs\SaveMessageJob::dispatch($msg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,493 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:猜谜活动回合服务
|
||||
*
|
||||
* 统一处理题型兼容、房间范围、自动出题、超时结算与公屏公告,
|
||||
* 避免控制器与定时任务各自维护一套猜谜活动逻辑。
|
||||
*/
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Events\MessageSent;
|
||||
use App\Events\RiddleGameStarted;
|
||||
use App\Models\GameConfig;
|
||||
use App\Models\Riddle;
|
||||
use App\Models\RiddleGameRound;
|
||||
use App\Models\Room;
|
||||
|
||||
/**
|
||||
* 类功能:提供猜谜活动的配置读取、出题、过期结算与公告能力。
|
||||
*/
|
||||
class RiddleGameService
|
||||
{
|
||||
/**
|
||||
* 方法功能:注入聊天室状态服务,复用现有公屏消息推送链路。
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly ChatStateService $chatState,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 方法功能:读取指定题型的完整配置,并兼容旧版平铺参数。
|
||||
*
|
||||
* @return array{reward_gold:int,reward_exp:int,expire_minutes:int,auto_start_interval:int,room_mode:string,room_ids:array<int, int>}
|
||||
*/
|
||||
public function getTypeConfig(?string $quizType = null): array
|
||||
{
|
||||
$normalizedQuizType = $this->normalizeQuizType($quizType);
|
||||
$config = GameConfig::forGame(Riddle::TYPE_IDIOM) ?? GameConfig::forGame($normalizedQuizType);
|
||||
$params = $config?->params ?? [];
|
||||
$typeConfig = (array) (($params['type_configs'] ?? [])[$normalizedQuizType] ?? []);
|
||||
$sharedRoomIds = $this->normalizeRoomIds(
|
||||
$params['room_ids']
|
||||
?? (($params['room_id'] ?? null) !== null ? [$params['room_id']] : [])
|
||||
);
|
||||
$roomMode = (string) ($params['room_scope_mode'] ?? ($typeConfig['room_mode'] ?? 'single'));
|
||||
|
||||
if (! in_array($roomMode, ['all', 'single', 'multiple'], true)) {
|
||||
$roomMode = 'single';
|
||||
}
|
||||
|
||||
$roomIds = $sharedRoomIds !== []
|
||||
? $sharedRoomIds
|
||||
: $this->normalizeRoomIds($typeConfig['room_ids'] ?? [1]);
|
||||
|
||||
return [
|
||||
'reward_gold' => max(0, (int) ($params['reward_gold'] ?? ($typeConfig['reward_gold'] ?? 50))),
|
||||
'reward_exp' => max(0, (int) ($params['reward_exp'] ?? ($typeConfig['reward_exp'] ?? 30))),
|
||||
'expire_minutes' => max(0, (int) ($params['expire_minutes'] ?? ($typeConfig['expire_minutes'] ?? 5))),
|
||||
'auto_start_interval' => max(0, (int) ($params['auto_start_interval'] ?? ($typeConfig['auto_start_interval'] ?? 0))),
|
||||
'room_mode' => $roomMode,
|
||||
'room_ids' => $roomIds,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:读取题目有效时长配置,单位分钟。
|
||||
*/
|
||||
public function getExpireMinutes(?string $quizType = null): int
|
||||
{
|
||||
return $this->getTypeConfig($quizType)['expire_minutes'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:读取自动出题间隔配置,单位分钟。
|
||||
*/
|
||||
public function getAutoStartInterval(?string $quizType = null): int
|
||||
{
|
||||
return $this->getTypeConfig($quizType)['auto_start_interval'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:读取答题奖励配置。
|
||||
*
|
||||
* @return array{reward_gold:int,reward_exp:int}
|
||||
*/
|
||||
public function getRewardConfig(?string $quizType = null): array
|
||||
{
|
||||
$typeConfig = $this->getTypeConfig($quizType);
|
||||
|
||||
return [
|
||||
'reward_gold' => $typeConfig['reward_gold'],
|
||||
'reward_exp' => $typeConfig['reward_exp'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:将外部传入的题型归一化为系统支持值。
|
||||
*/
|
||||
public function normalizeQuizType(?string $quizType): string
|
||||
{
|
||||
$normalizedType = trim((string) $quizType);
|
||||
|
||||
return Riddle::isSupportedType($normalizedType)
|
||||
? $normalizedType
|
||||
: Riddle::TYPE_IDIOM;
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:返回题型对应的中文名称。
|
||||
*/
|
||||
public function getQuizTypeLabel(string $quizType): string
|
||||
{
|
||||
return Riddle::labelForType($this->normalizeQuizType($quizType));
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:读取自动出题的房间范围模式。
|
||||
*/
|
||||
public function getRoomScopeMode(?string $quizType = null): string
|
||||
{
|
||||
return $this->getTypeConfig($quizType)['room_mode'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:读取自动出题允许覆盖的房间列表。
|
||||
*
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public function getScopedRoomIds(?string $quizType = null): array
|
||||
{
|
||||
$typeConfig = $this->getTypeConfig($quizType);
|
||||
$mode = $typeConfig['room_mode'];
|
||||
$configuredRoomIds = $typeConfig['room_ids'];
|
||||
|
||||
if ($mode === 'all') {
|
||||
return Room::query()->orderBy('id')->pluck('id')->map(fn (mixed $id): int => (int) $id)->all();
|
||||
}
|
||||
|
||||
if ($mode === 'single') {
|
||||
return array_slice($configuredRoomIds !== [] ? $configuredRoomIds : [1], 0, 1);
|
||||
}
|
||||
|
||||
return $configuredRoomIds !== [] ? $configuredRoomIds : [1];
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:判断指定回合是否已经超过有效时长。
|
||||
*/
|
||||
public function isRoundExpired(RiddleGameRound $round): bool
|
||||
{
|
||||
$expireMinutes = $this->getExpireMinutes($round->quiz_type);
|
||||
if ($expireMinutes <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! in_array($round->status, ['pending', 'active'], true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! $round->started_at) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $round->started_at->copy()->addMinutes($expireMinutes)->lte(now());
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:结算并结束已过期的回合,必要时发送超时公告。
|
||||
*/
|
||||
public function expireRound(RiddleGameRound $round, bool $announce = true): bool
|
||||
{
|
||||
if (! $this->isRoundExpired($round)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$round->loadMissing('idiom');
|
||||
|
||||
// 已过期回合统一落为 ended,防止继续答题或阻塞新开题。
|
||||
$round->update([
|
||||
'status' => 'ended',
|
||||
'ended_at' => $round->ended_at ?? now(),
|
||||
]);
|
||||
|
||||
if ($announce) {
|
||||
$this->pushExpiredRoundMessage($round);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:批量清理指定房间内已超时但仍处于进行中的回合。
|
||||
*/
|
||||
public function expireActiveRoundsForRoom(int $roomId, bool $announce = true, ?string $quizType = null): int
|
||||
{
|
||||
$expiredCount = 0;
|
||||
$normalizedQuizType = $quizType !== null ? $this->normalizeQuizType($quizType) : null;
|
||||
|
||||
RiddleGameRound::with('idiom')
|
||||
->where('room_id', $roomId)
|
||||
->when(
|
||||
$normalizedQuizType !== null,
|
||||
fn ($query) => $query->where('quiz_type', $normalizedQuizType),
|
||||
)
|
||||
->whereIn('status', ['pending', 'active'])
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->each(function (RiddleGameRound $round) use ($announce, &$expiredCount): void {
|
||||
if ($this->expireRound($round, $announce)) {
|
||||
$expiredCount++;
|
||||
}
|
||||
});
|
||||
|
||||
return $expiredCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:手动结束指定房间指定题型的所有进行中回合。
|
||||
*/
|
||||
public function endActiveRoundsForRoom(int $roomId, ?string $quizType = null): int
|
||||
{
|
||||
$endedCount = 0;
|
||||
$normalizedQuizType = $quizType !== null ? $this->normalizeQuizType($quizType) : null;
|
||||
|
||||
RiddleGameRound::query()
|
||||
->where('room_id', $roomId)
|
||||
->when(
|
||||
$normalizedQuizType !== null,
|
||||
fn ($query) => $query->where('quiz_type', $normalizedQuizType),
|
||||
)
|
||||
->whereIn('status', ['pending', 'active'])
|
||||
->orderBy('id')
|
||||
->get()
|
||||
->each(function (RiddleGameRound $round) use (&$endedCount): void {
|
||||
// 手动出题覆盖旧题时,直接结束旧回合,不再额外发超时公告。
|
||||
$round->update([
|
||||
'status' => 'ended',
|
||||
'ended_at' => $round->ended_at ?? now(),
|
||||
]);
|
||||
$endedCount++;
|
||||
});
|
||||
|
||||
return $endedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:为指定房间和题型创建一轮新题。
|
||||
*/
|
||||
public function startRound(int $roomId, ?string $quizType = null): ?RiddleGameRound
|
||||
{
|
||||
$normalizedQuizType = $this->normalizeQuizType($quizType);
|
||||
|
||||
if (! $this->isGameEnabled($normalizedQuizType)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 先清理同房间同题型的过期回合,避免旧记录卡住新题。
|
||||
$this->expireActiveRoundsForRoom($roomId, true, $normalizedQuizType);
|
||||
|
||||
if ($this->findActiveRound($roomId, $normalizedQuizType)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$idiom = $this->pickRandomQuestion($normalizedQuizType);
|
||||
if (! $idiom) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$rewardConfig = $this->getRewardConfig($normalizedQuizType);
|
||||
|
||||
// 新回合显式记录 quiz_type,保证房间与题型维度都能独立判定。
|
||||
$round = RiddleGameRound::create([
|
||||
'room_id' => $roomId,
|
||||
'idiom_id' => $idiom->id,
|
||||
'quiz_type' => $normalizedQuizType,
|
||||
'status' => 'active',
|
||||
'reward_gold' => $rewardConfig['reward_gold'],
|
||||
'reward_exp' => $rewardConfig['reward_exp'],
|
||||
'started_at' => now(),
|
||||
]);
|
||||
|
||||
$round->setRelation('idiom', $idiom);
|
||||
$this->broadcastStartedRound($round);
|
||||
|
||||
return $round;
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:按配置范围自动为各房间各题型尝试开题。
|
||||
*/
|
||||
public function autoStartEligibleRounds(): int
|
||||
{
|
||||
$startedCount = 0;
|
||||
|
||||
foreach (Riddle::supportedTypes() as $quizType) {
|
||||
$interval = $this->getAutoStartInterval($quizType);
|
||||
if ($interval <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($this->getScopedRoomIds($quizType) as $roomId) {
|
||||
// 房间与题型维度独立结算过期回合,互不干扰。
|
||||
$this->expireActiveRoundsForRoom($roomId, true, $quizType);
|
||||
|
||||
if ($this->findActiveRound($roomId, $quizType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $this->hasReachedAutoStartInterval($roomId, $quizType, $interval)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! $this->pickRandomQuestion($quizType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($this->startRound($roomId, $quizType)) {
|
||||
$startedCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $startedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:查询指定房间指定题型的进行中回合。
|
||||
*/
|
||||
public function findActiveRound(int $roomId, ?string $quizType = null): ?RiddleGameRound
|
||||
{
|
||||
return RiddleGameRound::query()
|
||||
->with('idiom')
|
||||
->where('room_id', $roomId)
|
||||
->where('quiz_type', $this->normalizeQuizType($quizType))
|
||||
->whereIn('status', ['pending', 'active'])
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:随机抽取一条启用中的题目。
|
||||
*/
|
||||
public function pickRandomQuestion(?string $quizType = null): ?Riddle
|
||||
{
|
||||
return Riddle::query()
|
||||
->where('type', $this->normalizeQuizType($quizType))
|
||||
->where('is_active', true)
|
||||
->inRandomOrder()
|
||||
->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:生成答题奖励日志文案。
|
||||
*/
|
||||
public function buildRewardDescription(RiddleGameRound $round): string
|
||||
{
|
||||
$quizTypeLabel = $this->getQuizTypeLabel($round->quiz_type);
|
||||
|
||||
return "猜谜活动{$quizTypeLabel}答对「{$round->idiom?->answer}」奖励";
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:向公屏推送回合超时公告。
|
||||
*/
|
||||
public function pushExpiredRoundMessage(RiddleGameRound $round): void
|
||||
{
|
||||
$answer = $round->idiom?->answer ?? '未知答案';
|
||||
$quizTitle = Riddle::activityLabelForType($round->quiz_type);
|
||||
$message = [
|
||||
'id' => $this->chatState->nextMessageId($round->room_id),
|
||||
'room_id' => $round->room_id,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => "⏳ 【{$quizTitle}】第 #{$round->id} 题已超时结束!正确答案:{$answer}",
|
||||
'is_secret' => false,
|
||||
'font_color' => '#d97706',
|
||||
'action' => '',
|
||||
'quiz_type' => $this->normalizeQuizType($round->quiz_type),
|
||||
'quiz_type_label' => $this->getQuizTypeLabel($round->quiz_type),
|
||||
'quiz_round_id' => $round->id,
|
||||
'quiz_round_ended_id' => $round->id,
|
||||
'quiz_answer' => $answer,
|
||||
'idiom_game_round_ended_id' => $round->id,
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
|
||||
$this->chatState->pushMessage($round->room_id, $message);
|
||||
broadcast(new MessageSent($round->room_id, $message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:广播新回合开始事件并同步写入公屏消息。
|
||||
*/
|
||||
public function broadcastStartedRound(RiddleGameRound $round): void
|
||||
{
|
||||
$round->loadMissing('idiom');
|
||||
|
||||
broadcast(new RiddleGameStarted(
|
||||
roomId: $round->room_id,
|
||||
quizType: $round->quiz_type,
|
||||
hint: $round->idiom?->hint ?? '',
|
||||
roundId: $round->id,
|
||||
rewardGold: $round->reward_gold,
|
||||
rewardExp: $round->reward_exp,
|
||||
));
|
||||
|
||||
$message = [
|
||||
'id' => $this->chatState->nextMessageId($round->room_id),
|
||||
'room_id' => $round->room_id,
|
||||
'from_user' => '系统传音',
|
||||
'to_user' => '大家',
|
||||
'content' => $this->buildStartMessage($round->quiz_type, $round->id, $round->idiom?->hint ?? ''),
|
||||
'is_secret' => false,
|
||||
'font_color' => '#b91c1c',
|
||||
'action' => '',
|
||||
'quiz_type' => $this->normalizeQuizType($round->quiz_type),
|
||||
'quiz_type_label' => $this->getQuizTypeLabel($round->quiz_type),
|
||||
'quiz_round_id' => $round->id,
|
||||
'quiz_hint' => $round->idiom?->hint ?? '',
|
||||
'quiz_reward_gold' => $round->reward_gold,
|
||||
'quiz_reward_exp' => $round->reward_exp,
|
||||
'idiom_game_round_id' => $round->id,
|
||||
'idiom_reward_gold' => $round->reward_gold,
|
||||
'idiom_reward_exp' => $round->reward_exp,
|
||||
'sent_at' => now()->toDateTimeString(),
|
||||
];
|
||||
|
||||
$this->chatState->pushMessage($round->room_id, $message);
|
||||
broadcast(new MessageSent($round->room_id, $message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:判断指定房间指定题型是否已到自动开题间隔。
|
||||
*/
|
||||
private function hasReachedAutoStartInterval(int $roomId, string $quizType, int $interval): bool
|
||||
{
|
||||
$lastRound = RiddleGameRound::query()
|
||||
->where('room_id', $roomId)
|
||||
->where('quiz_type', $this->normalizeQuizType($quizType))
|
||||
->latest()
|
||||
->first();
|
||||
|
||||
if (! $lastRound) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$lastTime = $lastRound->ended_at ?? $lastRound->started_at ?? $lastRound->created_at;
|
||||
|
||||
return ! $lastTime || $lastTime->diffInMinutes(now()) >= $interval;
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:把 room_ids 配置归一化为整型数组。
|
||||
*
|
||||
* @return array<int, int>
|
||||
*/
|
||||
private function normalizeRoomIds(mixed $roomIds): array
|
||||
{
|
||||
$items = is_array($roomIds)
|
||||
? $roomIds
|
||||
: preg_split('/[\s,,]+/u', (string) $roomIds, -1, PREG_SPLIT_NO_EMPTY);
|
||||
|
||||
return collect($items)
|
||||
->map(fn (mixed $roomId): int => (int) $roomId)
|
||||
->filter(fn (int $roomId): bool => $roomId > 0)
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:返回题型对应的活动标题。
|
||||
*/
|
||||
private function buildStartMessage(string $quizType, int $roundId, string $hint): string
|
||||
{
|
||||
$normalizedQuizType = $this->normalizeQuizType($quizType);
|
||||
$quizLabel = $this->getQuizTypeLabel($normalizedQuizType);
|
||||
$icon = $normalizedQuizType === Riddle::TYPE_BRAIN_TEASER ? '🧠' : '🧩';
|
||||
|
||||
return "{$icon} 【猜谜活动·{$quizLabel}】第 #{$roundId} 题开始!题面:{$hint}";
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:判断猜谜活动总开关是否处于启用状态。
|
||||
*/
|
||||
private function isGameEnabled(?string $quizType = null): bool
|
||||
{
|
||||
$normalizedQuizType = $this->normalizeQuizType($quizType);
|
||||
$config = GameConfig::forGame($normalizedQuizType) ?? GameConfig::forGame(Riddle::TYPE_IDIOM);
|
||||
|
||||
return (bool) $config?->enabled;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:聊天室座驾业务服务。
|
||||
*
|
||||
* 统一管理座驾商品列表、购买续期、当前激活座驾、购买记录和入场欢迎语载荷。
|
||||
*/
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\CurrencySource;
|
||||
use App\Models\Ride;
|
||||
use App\Models\User;
|
||||
use App\Models\UserRidePurchase;
|
||||
use App\Support\ChatContentSanitizer;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* 聊天室座驾服务
|
||||
* 负责通过 rides 与 user_ride_purchases 完成座驾购买、续期、替换与进房展示。
|
||||
*/
|
||||
class RideService
|
||||
{
|
||||
/**
|
||||
* 构造座驾服务依赖。
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly UserCurrencyService $currencyService,
|
||||
private readonly ChatUserPresenceService $chatUserPresenceService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 获取全部上架座驾商品。
|
||||
*
|
||||
* @return Collection<int, Ride>
|
||||
*/
|
||||
public function activeItems(): Collection
|
||||
{
|
||||
return Ride::active();
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化座驾商品,供前端页面直接渲染。
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function formatItem(Ride $item): array
|
||||
{
|
||||
return [
|
||||
'id' => $item->id,
|
||||
'name' => $item->name,
|
||||
'slug' => $item->slug,
|
||||
'ride_key' => $item->rideKey(),
|
||||
'description' => $item->description,
|
||||
'icon' => $item->icon,
|
||||
'price' => $item->price,
|
||||
'duration_days' => (int) ($item->duration_days ?? 0),
|
||||
'welcome_message' => $item->welcome_message,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户当前有效座驾,若已过期则自动标记为 expired。
|
||||
*/
|
||||
public function currentRide(User $user): ?UserRidePurchase
|
||||
{
|
||||
$purchase = UserRidePurchase::query()
|
||||
->with('ride')
|
||||
->where('user_id', $user->id)
|
||||
->where('status', 'active')
|
||||
->orderByDesc('expires_at')
|
||||
->first();
|
||||
|
||||
if (! $purchase) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($purchase->expires_at && $purchase->expires_at->isPast()) {
|
||||
// 过期座驾必须及时落库,避免后续进房继续播放旧特效。
|
||||
$purchase->update(['status' => 'expired']);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $purchase;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化用户当前座驾。
|
||||
*
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public function formatCurrentRide(User $user): ?array
|
||||
{
|
||||
$purchase = $this->currentRide($user);
|
||||
if (! $purchase || ! $purchase->ride) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->formatPurchase($purchase);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户最近座驾购买记录。
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function purchaseRecords(User $user, int $limit = 20): array
|
||||
{
|
||||
return UserRidePurchase::query()
|
||||
->with('ride')
|
||||
->where('user_id', $user->id)
|
||||
->latest()
|
||||
->limit($limit)
|
||||
->get()
|
||||
->map(fn (UserRidePurchase $purchase) => $this->formatPurchase($purchase))
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 购买座驾:同款续期,不同款替换旧座驾且不退款。
|
||||
*
|
||||
* @return array{ok:bool, message:string, current_ride?:array<string, mixed>}
|
||||
*/
|
||||
public function buy(User $user, Ride $item, ?int $roomId = null): array
|
||||
{
|
||||
if (! $item->is_active) {
|
||||
return ['ok' => false, 'message' => '该座驾暂未上架。'];
|
||||
}
|
||||
|
||||
$days = (int) ($item->duration_days ?? 0);
|
||||
if ($days <= 0) {
|
||||
return ['ok' => false, 'message' => '该座驾使用天数配置异常,请联系管理员。'];
|
||||
}
|
||||
|
||||
if ($user->jjb < $item->price) {
|
||||
return ['ok' => false, 'message' => "金币不足,购买【{$item->name}】需要 {$item->price} 金币,当前仅有 {$user->jjb} 金币。"];
|
||||
}
|
||||
|
||||
$purchased = DB::transaction(function () use ($user, $item, $days, $roomId): bool {
|
||||
$now = Carbon::now();
|
||||
|
||||
// 先清理已过期的 active 座驾,避免旧状态影响替换判断。
|
||||
UserRidePurchase::query()
|
||||
->where('user_id', $user->id)
|
||||
->where('status', 'active')
|
||||
->whereNotNull('expires_at')
|
||||
->where('expires_at', '<=', $now)
|
||||
->update(['status' => 'expired']);
|
||||
|
||||
$activeRide = UserRidePurchase::query()
|
||||
->with('ride')
|
||||
->where('user_id', $user->id)
|
||||
->where('status', 'active')
|
||||
->orderByDesc('expires_at')
|
||||
->first();
|
||||
|
||||
$balanceAfter = $this->currencyService->deductGoldIfEnough(
|
||||
$user,
|
||||
(int) $item->price,
|
||||
CurrencySource::RIDE_BUY,
|
||||
"购买聊天室座驾:{$item->name}",
|
||||
$roomId,
|
||||
);
|
||||
|
||||
if ($balanceAfter === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($activeRide && (int) $activeRide->ride_id === (int) $item->id) {
|
||||
$baseTime = $activeRide->expires_at && $activeRide->expires_at->greaterThan($now)
|
||||
? $activeRide->expires_at
|
||||
: $now;
|
||||
|
||||
// 同款续购先取消旧 active,再创建新 active,既保留购买记录,又保持当前座驾唯一。
|
||||
$activeRide->update(['status' => 'cancelled']);
|
||||
UserRidePurchase::create([
|
||||
'user_id' => $user->id,
|
||||
'ride_id' => $item->id,
|
||||
'status' => 'active',
|
||||
'price_paid' => $item->price,
|
||||
'expires_at' => $baseTime->copy()->addDays($days),
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($activeRide) {
|
||||
// 不同座驾替换旧座驾,旧记录保留为 cancelled 供后台追溯。
|
||||
$activeRide->update(['status' => 'cancelled']);
|
||||
}
|
||||
|
||||
UserRidePurchase::create([
|
||||
'user_id' => $user->id,
|
||||
'ride_id' => $item->id,
|
||||
'status' => 'active',
|
||||
'price_paid' => $item->price,
|
||||
'expires_at' => $now->copy()->addDays($days),
|
||||
]);
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
if (! $purchased) {
|
||||
return ['ok' => false, 'message' => "金币不足,购买【{$item->name}】需要 {$item->price} 金币,当前仅有 {$user->fresh()->jjb} 金币。"];
|
||||
}
|
||||
|
||||
return [
|
||||
'ok' => true,
|
||||
'message' => "购买成功!{$item->icon} {$item->name} 已激活({$days}天有效)。",
|
||||
'current_ride' => $this->formatCurrentRide($user->fresh()),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建进房座驾欢迎语与特效载荷。
|
||||
*
|
||||
* @return array<string, string>|null
|
||||
*/
|
||||
public function buildPresencePayload(User $user): ?array
|
||||
{
|
||||
$purchase = $this->currentRide($user);
|
||||
$item = $purchase?->ride;
|
||||
$rideKey = $item?->rideKey();
|
||||
|
||||
if (! $purchase || ! $item || ! $rideKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$template = trim((string) ($item->welcome_message ?: '【{name}】驾驶【{ride}】震撼入场,全场请注意!'));
|
||||
$rendered = strtr($template, [
|
||||
'{name}' => $user->username,
|
||||
'{ride}' => $item->name,
|
||||
]);
|
||||
$identitySummary = $this->chatUserPresenceService->buildIdentitySummary($user);
|
||||
$effectUserInfo = "用户 {$user->username} · {$identitySummary['inline']}";
|
||||
|
||||
return [
|
||||
'ride_key' => $rideKey,
|
||||
'ride_name' => $item->name,
|
||||
'ride_icon' => (string) ($item->icon ?? '🚘'),
|
||||
'effect_title' => "乘坐【{$item->name}】闪亮登场",
|
||||
'effect_user_info' => $effectUserInfo,
|
||||
'identity_text' => ChatContentSanitizer::htmlText($identitySummary['inline']),
|
||||
'welcome_text' => ChatContentSanitizer::htmlText($rendered),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化单条座驾购买记录。
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function formatPurchase(UserRidePurchase $purchase): array
|
||||
{
|
||||
$item = $purchase->ride;
|
||||
|
||||
return [
|
||||
'id' => $purchase->id,
|
||||
'status' => $purchase->status,
|
||||
'price_paid' => (int) $purchase->price_paid,
|
||||
'expires_at' => $purchase->expires_at?->toDateTimeString(),
|
||||
'used_at' => $purchase->used_at?->toDateTimeString(),
|
||||
'created_at' => $purchase->created_at?->toDateTimeString(),
|
||||
'item' => $item ? $this->formatItem($item) : null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ class ShopService
|
||||
*/
|
||||
public function buyItem(User $user, ShopItem $item, int $quantity = 1): array
|
||||
{
|
||||
if ($quantity !== 1 && $item->type !== ShopItem::TYPE_SIGN_REPAIR) {
|
||||
if ($quantity !== 1 && $item->type !== ShopItem::TYPE_SIGN_REPAIR && !$item->isDecoration()) {
|
||||
return ['ok' => false, 'message' => '该商品暂不支持批量购买。'];
|
||||
}
|
||||
|
||||
|
||||
+32
-1
@@ -1,5 +1,35 @@
|
||||
<?php
|
||||
|
||||
$normalizeReverbAllowedOrigins = static function (?string $rawOrigins): array {
|
||||
if ($rawOrigins === null || trim($rawOrigins) === '') {
|
||||
return ['*'];
|
||||
}
|
||||
|
||||
$normalizedOrigins = [];
|
||||
|
||||
foreach (explode(',', $rawOrigins) as $origin) {
|
||||
$candidate = trim($origin);
|
||||
|
||||
if ($candidate === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($candidate === '*') {
|
||||
return ['*'];
|
||||
}
|
||||
|
||||
$host = parse_url($candidate, PHP_URL_HOST);
|
||||
|
||||
if (! is_string($host) || $host === '') {
|
||||
$host = parse_url('http://'.$candidate, PHP_URL_HOST);
|
||||
}
|
||||
|
||||
$normalizedOrigins[] = is_string($host) && $host !== '' ? $host : $candidate;
|
||||
}
|
||||
|
||||
return array_values(array_unique($normalizedOrigins));
|
||||
};
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
@@ -82,7 +112,8 @@ return [
|
||||
'scheme' => env('REVERB_SCHEME', 'https'),
|
||||
'useTLS' => env('REVERB_SCHEME', 'https') === 'https',
|
||||
],
|
||||
'allowed_origins' => ['*'],
|
||||
// Reverb 内部按 Origin 的主机名比对,这里统一转成 host,避免把完整 URL 写进 .env 后被误拒绝。
|
||||
'allowed_origins' => $normalizeReverbAllowedOrigins(env('REVERB_ALLOWED_ORIGIN')),
|
||||
'ping_interval' => env('REVERB_APP_PING_INTERVAL', 60),
|
||||
'activity_timeout' => env('REVERB_APP_ACTIVITY_TIMEOUT', 30),
|
||||
'max_connections' => env('REVERB_APP_MAX_CONNECTIONS'),
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:创建猜成语题库表
|
||||
*
|
||||
* 存储成语题目及答案,管理员可在后台增删改。
|
||||
*
|
||||
* @author ChatRoom Laravel
|
||||
*
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* 创建 idioms 表。
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('idioms', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('answer', 50)->comment('成语答案');
|
||||
$table->string('hint', 255)->comment('谜语线索提示');
|
||||
$table->boolean('is_active')->default(true)->comment('是否启用');
|
||||
$table->unsignedSmallInteger('sort')->default(0)->comment('排序');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 回滚迁移。
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('idioms');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:创建猜成语游戏回合表
|
||||
*
|
||||
* 每次出题对应一个回合,记录答题状态、奖励和获胜者。
|
||||
*
|
||||
* @author ChatRoom Laravel
|
||||
*
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* 创建 idiom_game_rounds 表。
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('idiom_game_rounds', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('room_id')->comment('游戏所在房间 ID');
|
||||
$table->unsignedBigInteger('idiom_id')->comment('当前题目 ID');
|
||||
$table->string('status', 20)->default('pending')->comment('状态:pending/active/answered/ended');
|
||||
$table->integer('reward_gold')->default(0)->comment('答对奖励金币');
|
||||
$table->integer('reward_exp')->default(0)->comment('答对奖励经验');
|
||||
$table->unsignedBigInteger('winner_id')->nullable()->comment('答对用户 ID');
|
||||
$table->string('winner_username', 50)->nullable()->comment('答对用户名');
|
||||
$table->timestamp('started_at')->nullable()->comment('开始答题时间');
|
||||
$table->timestamp('ended_at')->nullable()->comment('结束答题时间');
|
||||
$table->timestamps();
|
||||
|
||||
$table->foreign('idiom_id')->references('id')->on('idioms')->onDelete('cascade');
|
||||
$table->index('status');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 回滚迁移。
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('idiom_game_rounds');
|
||||
}
|
||||
};
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:将猜成语数据结构升级为猜谜活动通用结构
|
||||
*
|
||||
* 为题库增加题型字段,为回合增加 quiz_type 与复合索引,
|
||||
* 兼容既有“猜成语”数据并为脑筋急转弯题型预留能力。
|
||||
*/
|
||||
|
||||
use App\Models\Riddle;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* 方法功能:执行表结构升级并补齐历史数据默认值。
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('idioms', function (Blueprint $table): void {
|
||||
if (! Schema::hasColumn('idioms', 'type')) {
|
||||
$table->string('type', 30)->default(Riddle::TYPE_IDIOM)->after('id')->comment('题型:idiom/brain_teaser');
|
||||
}
|
||||
});
|
||||
|
||||
// 历史成语题默认归类到 idiom,保证旧数据无需人工修复。
|
||||
DB::table('idioms')
|
||||
->whereNull('type')
|
||||
->orWhere('type', '')
|
||||
->update(['type' => Riddle::TYPE_IDIOM]);
|
||||
|
||||
Schema::table('idiom_game_rounds', function (Blueprint $table): void {
|
||||
if (! Schema::hasColumn('idiom_game_rounds', 'quiz_type')) {
|
||||
$table->string('quiz_type', 30)->default(Riddle::TYPE_IDIOM)->after('idiom_id')->comment('回合题型:idiom/brain_teaser');
|
||||
}
|
||||
});
|
||||
|
||||
// 历史回合默认按成语题处理,确保旧记录仍可正常展示与过期结算。
|
||||
DB::table('idiom_game_rounds')
|
||||
->whereNull('quiz_type')
|
||||
->orWhere('quiz_type', '')
|
||||
->update(['quiz_type' => Riddle::TYPE_IDIOM]);
|
||||
|
||||
Schema::table('idioms', function (Blueprint $table): void {
|
||||
$table->index(['type', 'is_active'], 'idioms_type_is_active_index');
|
||||
});
|
||||
|
||||
Schema::table('idiom_game_rounds', function (Blueprint $table): void {
|
||||
$table->index(['room_id', 'quiz_type', 'status'], 'idiom_rounds_room_type_status_index');
|
||||
$table->index(['room_id', 'quiz_type', 'id'], 'idiom_rounds_room_type_id_index');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:回滚猜谜活动通用结构升级。
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('idiom_game_rounds', function (Blueprint $table): void {
|
||||
$table->dropIndex('idiom_rounds_room_type_status_index');
|
||||
$table->dropIndex('idiom_rounds_room_type_id_index');
|
||||
$table->dropColumn('quiz_type');
|
||||
});
|
||||
|
||||
Schema::table('idioms', function (Blueprint $table): void {
|
||||
$table->dropIndex('idioms_type_is_active_index');
|
||||
$table->dropColumn('type');
|
||||
});
|
||||
}
|
||||
};
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:为公共回合型游戏补充 room_id 字段
|
||||
*
|
||||
* 让百家乐、赛马、彩票和神秘箱子可以按房间独立开局、查询与广播。
|
||||
*/
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* 执行迁移。
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('baccarat_rounds', function (Blueprint $table) {
|
||||
$table->unsignedBigInteger('room_id')->default(1)->after('id')->index();
|
||||
});
|
||||
|
||||
Schema::table('horse_races', function (Blueprint $table) {
|
||||
$table->unsignedBigInteger('room_id')->default(1)->after('id')->index();
|
||||
});
|
||||
|
||||
Schema::table('lottery_issues', function (Blueprint $table) {
|
||||
$table->unsignedBigInteger('room_id')->default(1)->after('id')->index();
|
||||
});
|
||||
|
||||
Schema::table('mystery_boxes', function (Blueprint $table) {
|
||||
$table->unsignedBigInteger('room_id')->default(1)->after('id')->index();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 回滚迁移。
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('baccarat_rounds', function (Blueprint $table) {
|
||||
$table->dropIndex(['room_id']);
|
||||
$table->dropColumn('room_id');
|
||||
});
|
||||
|
||||
Schema::table('horse_races', function (Blueprint $table) {
|
||||
$table->dropIndex(['room_id']);
|
||||
$table->dropColumn('room_id');
|
||||
});
|
||||
|
||||
Schema::table('lottery_issues', function (Blueprint $table) {
|
||||
$table->dropIndex(['room_id']);
|
||||
$table->dropColumn('room_id');
|
||||
});
|
||||
|
||||
Schema::table('mystery_boxes', function (Blueprint $table) {
|
||||
$table->dropIndex(['room_id']);
|
||||
$table->dropColumn('room_id');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:创建聊天室座驾独立数据表。
|
||||
*
|
||||
* 座驾定义和用户座驾购买记录独立于商店模块,支持后台单独配置价格、使用天数和欢迎语。
|
||||
*/
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* 方法功能:创建 rides 与 user_ride_purchases 并预置默认座驾。
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('rides', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('name', 100)->comment('座驾名称');
|
||||
$table->string('slug', 100)->unique()->comment('座驾唯一标识,格式 ride_key');
|
||||
$table->string('effect_key', 50)->unique()->comment('全屏特效 key');
|
||||
$table->string('icon', 20)->default('🚘')->comment('座驾图标');
|
||||
$table->text('description')->nullable()->comment('座驾说明');
|
||||
$table->unsignedInteger('price')->default(0)->comment('购买价格');
|
||||
$table->unsignedInteger('duration_days')->default(7)->comment('使用天数');
|
||||
$table->string('welcome_message', 255)->nullable()->comment('入场欢迎语模板');
|
||||
$table->unsignedInteger('sort_order')->default(0)->comment('排序权重');
|
||||
$table->boolean('is_active')->default(true)->comment('是否上架');
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
Schema::create('user_ride_purchases', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
|
||||
$table->foreignId('ride_id')->constrained('rides')->cascadeOnDelete();
|
||||
$table->enum('status', ['active', 'expired', 'cancelled'])->default('active')->comment('座驾状态');
|
||||
$table->unsignedInteger('price_paid')->default(0)->comment('实际支付金币');
|
||||
$table->timestamp('expires_at')->nullable()->comment('到期时间');
|
||||
$table->timestamp('used_at')->nullable()->comment('首次使用时间');
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['user_id', 'status', 'expires_at']);
|
||||
});
|
||||
|
||||
$this->seedDefaultRides();
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:删除座驾独立数据表。
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('user_ride_purchases');
|
||||
Schema::dropIfExists('rides');
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:写入当前默认四个全屏座驾。
|
||||
*/
|
||||
private function seedDefaultRides(): void
|
||||
{
|
||||
$now = now();
|
||||
$rides = [
|
||||
[
|
||||
'name' => '歼-35隐身战机',
|
||||
'slug' => 'ride_j35',
|
||||
'effect_key' => 'j35',
|
||||
'description' => '驾驶歼-35划破长空入场,附带全屏战机掠过特效。',
|
||||
'icon' => '🛩️',
|
||||
'price' => 18888,
|
||||
'duration_days' => 7,
|
||||
'sort_order' => 80,
|
||||
'welcome_message' => '【{name}】驾驶【{ride}】划破长空,震撼降临聊天室!',
|
||||
],
|
||||
[
|
||||
'name' => '99A主战坦克',
|
||||
'slug' => 'ride_99a',
|
||||
'effect_key' => '99a',
|
||||
'description' => '驾驶 99A 主战坦克重装入场,附带履带尘土与炮击冲击特效。',
|
||||
'icon' => '🛡️',
|
||||
'price' => 18888,
|
||||
'duration_days' => 7,
|
||||
'sort_order' => 81,
|
||||
'welcome_message' => '【{name}】驾驶【{ride}】重装入场,地面都为之一震!',
|
||||
],
|
||||
[
|
||||
'name' => '东风-5C战略导弹',
|
||||
'slug' => 'ride_df5c',
|
||||
'effect_key' => 'df5c',
|
||||
'description' => '乘东风-5C 发射升空入场,附带尾焰、烟尘和雷达 HUD 特效。',
|
||||
'icon' => '🚀',
|
||||
'price' => 28888,
|
||||
'duration_days' => 7,
|
||||
'sort_order' => 82,
|
||||
'welcome_message' => '【{name}】乘【{ride}】点火升空,战略级排面拉满!',
|
||||
],
|
||||
[
|
||||
'name' => '福建舰航母',
|
||||
'slug' => 'ride_fujian',
|
||||
'effect_key' => 'fujian',
|
||||
'description' => '乘福建舰破浪入场,附带海浪、舰载机和甲板 HUD 特效。',
|
||||
'icon' => '⚓',
|
||||
'price' => 28888,
|
||||
'duration_days' => 7,
|
||||
'sort_order' => 83,
|
||||
'welcome_message' => '【{name}】乘【{ride}】破浪而来,全场列队欢迎!',
|
||||
],
|
||||
];
|
||||
|
||||
foreach ($rides as $ride) {
|
||||
DB::table('rides')->insert($ride + [
|
||||
'is_active' => true,
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
]);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:清理旧版商店座驾数据。
|
||||
*
|
||||
* 如果环境曾跑过“座驾复用商店”的旧迁移,本迁移会移除商店里的座驾字段和残留记录。
|
||||
*/
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* 方法功能:删除 shop_items 中旧座驾记录并移除欢迎语字段。
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
DB::table('shop_items')->where('slug', 'like', 'ride_%')->delete();
|
||||
|
||||
if (DB::getDriverName() === 'mysql' && $this->shopItemTypeContainsRide()) {
|
||||
DB::statement("UPDATE `shop_items` SET `type` = 'one_time' WHERE `type` = 'ride'");
|
||||
DB::statement("ALTER TABLE `shop_items` MODIFY `type` ENUM('instant','duration','one_time','ring','auto_fishing','sign_repair','msg_bubble','msg_name_color','avatar_frame','msg_text_color') NOT NULL COMMENT '道具类型'");
|
||||
}
|
||||
|
||||
if (Schema::hasColumn('shop_items', 'welcome_message')) {
|
||||
Schema::table('shop_items', function (Blueprint $table) {
|
||||
$table->dropColumn('welcome_message');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:清理迁移不恢复旧商店座驾结构。
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* 方法功能:判断当前 shop_items.type 枚举是否包含旧座驾类型。
|
||||
*/
|
||||
private function shopItemTypeContainsRide(): bool
|
||||
{
|
||||
$column = DB::selectOne("SHOW COLUMNS FROM `shop_items` LIKE 'type'");
|
||||
|
||||
return $column && str_contains((string) $column->Type, "'ride'");
|
||||
}
|
||||
};
|
||||
@@ -32,6 +32,8 @@ class GameConfigSeeder extends Seeder
|
||||
'description' => '系统每隔一段时间自动开一局,玩家在倒计时内押注大/小/豹子,骰子结果决定胜负。',
|
||||
'enabled' => false,
|
||||
'params' => [
|
||||
'room_scope_mode' => 'single', // 参与房间模式
|
||||
'room_ids' => [1], // 参与房间列表
|
||||
'interval_minutes' => 2, // 多少分钟开一局
|
||||
'bet_window_seconds' => 60, // 每局押注窗口(秒)
|
||||
'min_bet' => 100, // 最低押注金币
|
||||
@@ -51,6 +53,8 @@ class GameConfigSeeder extends Seeder
|
||||
'description' => '消耗金币转动老虎机,三列图案匹配可获得不同倍率奖励,三个7大奖全服广播。',
|
||||
'enabled' => false,
|
||||
'params' => [
|
||||
'room_scope_mode' => 'single',
|
||||
'room_ids' => [1],
|
||||
'cost_per_spin' => 100, // 每次旋转消耗
|
||||
'house_edge_percent' => 15, // 庄家边际(%)
|
||||
'daily_limit' => 100, // 每日最多转动次数(0=不限)
|
||||
@@ -70,6 +74,8 @@ class GameConfigSeeder extends Seeder
|
||||
'description' => '管理员随时投放或系统定时自动投放神秘箱,最快发送暗号的用户开箱获得奖励。',
|
||||
'enabled' => false,
|
||||
'params' => [
|
||||
'room_scope_mode' => 'single',
|
||||
'room_ids' => [1],
|
||||
'auto_drop_enabled' => false, // 是否自动定时投放
|
||||
'auto_interval_hours' => 2, // 自动投放间隔(小时)
|
||||
'claim_window_seconds' => 60, // 领取窗口(秒)
|
||||
@@ -91,6 +97,8 @@ class GameConfigSeeder extends Seeder
|
||||
'description' => '系统定期举办赛马,用户在倒计时内下注,按注池赔率结算,跑马过程 WebSocket 实时播报。',
|
||||
'enabled' => false,
|
||||
'params' => [
|
||||
'room_scope_mode' => 'single',
|
||||
'room_ids' => [1],
|
||||
'interval_minutes' => 30, // 多少分钟一场
|
||||
'bet_window_seconds' => 90, // 押注窗口(秒)
|
||||
'race_duration' => 30, // 跑马动画时长(秒)
|
||||
@@ -110,6 +118,8 @@ class GameConfigSeeder extends Seeder
|
||||
'description' => '每日一次免费占卜,系统生成玄学签文并赋予当日加成效果(幸运/倒霉)。额外占卜消耗金币。',
|
||||
'enabled' => false,
|
||||
'params' => [
|
||||
'room_scope_mode' => 'single',
|
||||
'room_ids' => [1],
|
||||
'free_count_per_day' => 1, // 每日免费次数
|
||||
'extra_cost' => 500, // 额外次数消耗金币
|
||||
'buff_duration_hours' => 24, // 加成效果持续时间
|
||||
@@ -128,6 +138,8 @@ class GameConfigSeeder extends Seeder
|
||||
'description' => '消耗金币抛竿,等待浮漂下沉后点击收竿,随机获得奖励或惩罚。持有自动钓鱼卡可自动循环。',
|
||||
'enabled' => false,
|
||||
'params' => [
|
||||
'room_scope_mode' => 'single',
|
||||
'room_ids' => [1],
|
||||
'fishing_cost' => 5, // 每次抛竿消耗金币
|
||||
'fishing_wait_min' => 8, // 浮漂等待最短秒数
|
||||
'fishing_wait_max' => 15, // 浮漂等待最长秒数
|
||||
@@ -143,6 +155,8 @@ class GameConfigSeeder extends Seeder
|
||||
'description' => '每日一期,选3红球(1-12)+1蓝球(1-6),按奖池比例派奖,无一等奖滚存累积。',
|
||||
'enabled' => false,
|
||||
'params' => [
|
||||
'room_scope_mode' => 'single',
|
||||
'room_ids' => [1],
|
||||
// ── 开奖时间 ──
|
||||
'draw_hour' => 20, // 每天几点开奖(24小时制)
|
||||
'draw_minute' => 0, // 几分开奖
|
||||
@@ -169,6 +183,31 @@ class GameConfigSeeder extends Seeder
|
||||
'super_issue_inject' => 20000, // 超级期系统注入金额上限
|
||||
],
|
||||
],
|
||||
|
||||
// ─── 五子棋 ───────────────────────────────────────────────
|
||||
[
|
||||
'game_key' => 'gomoku',
|
||||
'name' => '五子棋',
|
||||
'icon' => '♟️',
|
||||
'description' => 'PvP 对战/人机对战,房间内随时发起邀请,超时或认输均自动结算。',
|
||||
'enabled' => false,
|
||||
'params' => [
|
||||
'room_scope_mode' => 'single',
|
||||
'room_ids' => [1],
|
||||
'pvp_reward' => 200, // PvP 胜利奖励金币
|
||||
'pvp_invite_timeout' => 30, // PvP 邀请超时(秒)
|
||||
'pvp_move_timeout' => 45, // 每步落子超时(秒)
|
||||
'pvp_ready_timeout' => 20, // 对局准备超时(秒)
|
||||
'pve_fee_level_1' => 50, // AI简单 入场费
|
||||
'pve_reward_level_1' => 100, // AI简单 胜利奖励
|
||||
'pve_fee_level_2' => 100, // AI普通 入场费
|
||||
'pve_reward_level_2' => 200, // AI普通 胜利奖励
|
||||
'pve_fee_level_3' => 200, // AI困难 入场费
|
||||
'pve_reward_level_3' => 400, // AI困难 胜利奖励
|
||||
'pve_fee_level_4' => 500, // AI专家 入场费
|
||||
'pve_reward_level_4' => 1000, // AI专家 胜利奖励
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
foreach ($games as $game) {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:猜谜活动旧 Seeder 兼容入口
|
||||
*
|
||||
* 兼容仍然使用 `IdiomSeeder` 名称的旧命令与旧文档,
|
||||
* 实际执行逻辑委托给新的 RiddleSeeder。
|
||||
*/
|
||||
|
||||
namespace Database\Seeders;
|
||||
|
||||
/**
|
||||
* 类功能:兼容旧的 IdiomSeeder 调用入口。
|
||||
*/
|
||||
class IdiomSeeder extends RiddleSeeder
|
||||
{
|
||||
/**
|
||||
* 方法功能:复用新的猜谜活动题库填充逻辑。
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
parent::run();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* 文件功能:猜谜活动题库填充器
|
||||
*
|
||||
* 初始化猜谜活动配置、成语题库与脑筋急转弯题库数据。
|
||||
* 使用 updateOrCreate 确保重复执行不影响已有数据。
|
||||
*
|
||||
* @author ChatRoom Laravel
|
||||
*
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
namespace Database\Seeders;
|
||||
|
||||
use App\Models\GameConfig;
|
||||
use App\Models\Riddle;
|
||||
use Illuminate\Database\Seeder;
|
||||
|
||||
/**
|
||||
* 类功能:初始化猜谜活动配置、成语题库与脑筋急转弯题库。
|
||||
*/
|
||||
class RiddleSeeder extends Seeder
|
||||
{
|
||||
/**
|
||||
* 填充猜谜活动配置与题库。
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
// ── 游戏配置(已存在则更新为统一猜谜活动结构) ──
|
||||
GameConfig::updateOrCreate(
|
||||
['game_key' => 'idiom'],
|
||||
[
|
||||
'name' => '猜谜活动',
|
||||
'icon' => '🧩',
|
||||
'description' => '管理员手动出题或系统定时自动出题,支持成语题与脑筋急转弯题,第一个答对的用户获得金币和经验奖励。',
|
||||
'enabled' => false,
|
||||
'params' => [
|
||||
'reward_gold' => 50,
|
||||
'reward_exp' => 30,
|
||||
'auto_start_interval' => 0,
|
||||
'expire_minutes' => 5,
|
||||
'room_scope_mode' => 'single',
|
||||
'room_ids' => [1],
|
||||
'type_configs' => [
|
||||
Riddle::TYPE_IDIOM => [
|
||||
'reward_gold' => 50,
|
||||
'reward_exp' => 30,
|
||||
'auto_start_interval' => 0,
|
||||
'expire_minutes' => 5,
|
||||
'room_mode' => 'single',
|
||||
'room_ids' => [1],
|
||||
],
|
||||
Riddle::TYPE_BRAIN_TEASER => [
|
||||
'reward_gold' => 50,
|
||||
'reward_exp' => 30,
|
||||
'auto_start_interval' => 0,
|
||||
'expire_minutes' => 5,
|
||||
'room_mode' => 'single',
|
||||
'room_ids' => [1],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
// ── 题库数据 ──
|
||||
$idioms = [
|
||||
['answer' => '画蛇添足', 'hint' => '🧩 四人比赛画蛇,最慢的那个反而多此一举。猜一成语'],
|
||||
['answer' => '守株待兔', 'hint' => '🧩 农夫不干活,天天蹲树桩旁等天上掉馅饼。猜一成语'],
|
||||
['answer' => '掩耳盗铃', 'hint' => '🧩 小偷以为捂住自己耳朵,别人就听不见铃铛响了。猜一成语'],
|
||||
['answer' => '亡羊补牢', 'hint' => '🧩 羊圈破了个洞,羊跑了几只才想起修。猜一成语'],
|
||||
['answer' => '刻舟求剑', 'hint' => '🧩 船上做了个记号就能在江里找回剑?猜一成语'],
|
||||
['answer' => '叶公好龙', 'hint' => '🧩 家里到处画龙雕龙,真龙来了却吓得屁滚尿流。猜一成语'],
|
||||
['answer' => '狐假虎威', 'hint' => '🧩 狐狸走在老虎前面,小动物们到底怕谁?猜一成语'],
|
||||
['answer' => '井底之蛙', 'hint' => '🧩 住在井里,却以为天空只有井口那么大。猜一成语'],
|
||||
['answer' => '对牛弹琴', 'hint' => '🧩 弹了一首好曲子,听众却在低头吃草。猜一成语'],
|
||||
['answer' => '杯弓蛇影', 'hint' => '🧩 酒杯里有个弯弯曲曲的东西在动,吓得大病一场。猜一成语'],
|
||||
['answer' => '鹤立鸡群', 'hint' => '🧩 一只长腿白鸟混进了院子里的小黄鸡中。猜一成语'],
|
||||
['answer' => '画龙点睛', 'hint' => '🧩 最后两笔点上后,墙上的龙竟然飞走了。猜一成语'],
|
||||
['answer' => '鸡飞蛋打', 'hint' => '🧩 偷鸡不成,竹篮打水一场空。猜一成语'],
|
||||
['answer' => '马到成功', 'hint' => '🧩 战旗一挥,马蹄刚踏出去就赢了。猜一成语'],
|
||||
['answer' => '虎头蛇尾', 'hint' => '🧩 开头气势如虹,结尾却草草收场。猜一成语'],
|
||||
['answer' => '龙飞凤舞', 'hint' => '🧩 王羲之喝醉了,笔下的字好像要飞起来。猜一成语'],
|
||||
['answer' => '鸡犬不宁', 'hint' => '🧩 闹得天翻地覆,连院子里的小动物都不得安生。猜一成语'],
|
||||
['answer' => '狼吞虎咽', 'hint' => '🧩 饿了三天的壮汉看到一碗面。猜一成语'],
|
||||
['answer' => '鱼目混珠', 'hint' => '🧩 地摊上有人拿玻璃球当夜明珠卖。猜一成语'],
|
||||
['answer' => '鼠目寸光', 'hint' => '🧩 只看得到眼前一寸的路,走远就迷路。猜一成语'],
|
||||
['answer' => '九牛一毛', 'hint' => '🧩 亿万富翁丢了一分钱,连弯腰捡都懒得捡。猜一成语'],
|
||||
['answer' => '如鱼得水', 'hint' => '🧩 刘备说:有了诸葛亮,就像什么回到了什么里?猜一成语'],
|
||||
['answer' => '鸟语花香', 'hint' => '🧩 春天来了,你能听到什么、闻到什么?猜一成语'],
|
||||
['answer' => '风花雪月', 'hint' => '🧩 才子佳人写的诗,看起来很美,其实没什么实际内容。猜一成语'],
|
||||
['answer' => '山清水秀', 'hint' => '🧩 桂林漓江边上,你能看到什么颜色?猜一成语'],
|
||||
['answer' => '水落石出', 'hint' => '🧩 水位下降后,河床下的东西藏不住了。猜一成语'],
|
||||
['answer' => '火中取栗', 'hint' => '🧩 猫爪子被烫伤了,猴子却在旁边偷笑吃栗子。猜一成语'],
|
||||
['answer' => '石破天惊', 'hint' => '🧩 一块石头裂开,伴随着一声巨响,所有人都惊呆了。猜一成语'],
|
||||
['answer' => '翻天覆地', 'hint' => '🧩 孙悟空大闹天宫后,凌霄宝殿变成了什么样?猜一成语'],
|
||||
['answer' => '开天辟地', 'hint' => '🧩 盘古拿着斧头,对着混沌用力一劈。猜一成语'],
|
||||
['answer' => '惊天动地', 'hint' => '🧩 汶川大地震那天,连天上的云都在颤抖。猜一成语'],
|
||||
['answer' => '花好月圆', 'hint' => '🧩 婚礼请柬上最常见的四个字祝福。猜一成语'],
|
||||
['answer' => '冰清玉洁', 'hint' => '🧩 她的品格像冬天的什么和深山里的什么?猜一成语'],
|
||||
['answer' => '海阔天空', 'hint' => '🧩 走出小县城,来到大都市,才发现世界有多大。猜一成语'],
|
||||
['answer' => '雪中送炭', 'hint' => '🧩 大冬天你最需要什么?有人偏偏就送来了什么。猜一成语'],
|
||||
['answer' => '锦上添花', 'hint' => '🧩 已经够漂亮了,还要再点缀一下。猜一成语'],
|
||||
['answer' => '落井下石', 'hint' => '🧩 有人掉坑里了,你不救也就算了,还往下面扔砖头。猜一成语'],
|
||||
['answer' => '纸上谈兵', 'hint' => '🧩 赵括说起兵法头头是道,上了战场却一败涂地。猜一成语'],
|
||||
['answer' => '胸有成竹', 'hint' => '🧩 画家文同还没下笔,心里已经有了完整的竹子。猜一成语'],
|
||||
['answer' => '一帆风顺', 'hint' => '🧩 出海前最想听到的一句祝福。猜一成语'],
|
||||
['answer' => '水到渠成', 'hint' => '🧩 不用刻意挖渠,水自然会找到它的路。猜一成语'],
|
||||
['answer' => '百发百中', 'hint' => '🧩 养由基站在百步之外射柳叶,箭无虚发。猜一成语'],
|
||||
['answer' => '一鸣惊人', 'hint' => '🧩 齐威王三年不上朝不理政,一出手就震惊了各国。猜一成语'],
|
||||
['answer' => '对答如流', 'hint' => '🧩 老师提问,他不用思考就说出答案,像江水一样不停。猜一成语'],
|
||||
['answer' => '顺手牵羊', 'hint' => '🧩 路过别人家门口,看到一只羊没人看管……猜一成语'],
|
||||
['answer' => '勇往直前', 'hint' => '🧩 前面是刀山火海,他眼睛都不眨一下继续走。猜一成语'],
|
||||
['answer' => '百折不挠', 'hint' => '🧩 被摔倒一百次,第一百零一次依然站起来。猜一成语'],
|
||||
['answer' => '持之以恒', 'hint' => '🧩 水滴不断地滴在石头上,千年后石头被滴穿了。猜一成语'],
|
||||
['answer' => '知己知彼', 'hint' => '🧩 孙子兵法说:了解自己又了解对方,百战不殆。猜一成语'],
|
||||
['answer' => '四面楚歌', 'hint' => '🧩 项羽被包围在垓下,四面八方都传来熟悉的歌声。猜一成语'],
|
||||
['answer' => '草木皆兵', 'hint' => '🧩 淝水之战中,苻坚看到山上的草和树,都以为是敌军。猜一成语'],
|
||||
['answer' => '一箭双雕', 'hint' => '🧩 长孙晟一箭射出去,两只大鸟应声落地。猜一成语'],
|
||||
['answer' => '背水一战', 'hint' => '🧩 韩信把军队放在河边列阵,断了所有人的退路。猜一成语'],
|
||||
['answer' => '声东击西', 'hint' => '🧩 明明要打左边,却装作全力进攻右边。猜一成语'],
|
||||
['answer' => '调虎离山', 'hint' => '🧩 想占老虎的老窝,得先把老虎引出去。猜一成语'],
|
||||
['answer' => '空城计', 'hint' => '🧩 诸葛亮大开城门,在城楼上弹琴,敌军反而不敢进城。猜一成语'],
|
||||
['answer' => '缓兵之计', 'hint' => '🧩 打不过怎么办?先假装谈判争取时间。猜一成语'],
|
||||
['answer' => '卧薪尝胆', 'hint' => '🧩 越王勾践每天睡在柴堆上,还要舔一口苦胆。猜一成语'],
|
||||
['answer' => '三顾茅庐', 'hint' => '🧩 刘备为了请一个人出山,大冬天跑了三趟。猜一成语'],
|
||||
['answer' => '望梅止渴', 'hint' => '🧩 曹操说前面有片梅林,士兵们嘴里都开始流口水了。猜一成语'],
|
||||
['answer' => '七步成诗', 'hint' => '🧩 曹植被亲哥哥逼着在很短的时间里写诗保命。猜一成语'],
|
||||
['answer' => '才高八斗', 'hint' => '🧩 谢灵运说:天下才华共一石,曹植独占八斗。猜一成语'],
|
||||
['answer' => '入木三分', 'hint' => '🧩 王羲之在木板上写字,墨迹渗入木头三分深。猜一成语'],
|
||||
['answer' => '一字千金', 'hint' => '🧩 吕不韦悬赏:谁能给《吕氏春秋》改动一个字,赏千金。猜一成语'],
|
||||
['answer' => '一诺千金', 'hint' => '🧩 季布的一句话,比黄金千两还贵重。猜一成语'],
|
||||
['answer' => '半途而废', 'hint' => '🧩 走到半山腰觉得累了,就转身下山了。猜一成语'],
|
||||
['answer' => '实事求是', 'hint' => '🧩 不夸大不缩小,是什么就是什么。猜一成语'],
|
||||
['answer' => '量力而行', 'hint' => '🧩 蚂蚁想搬走大象?先掂量掂量自己有几斤几两。猜一成语'],
|
||||
['answer' => '自相矛盾', 'hint' => '🧩 楚国人夸自己的矛能刺穿任何盾,又夸自己的盾什么都刺不穿。猜一成语'],
|
||||
['answer' => '买椟还珠', 'hint' => '🧩 花大价钱买了精美盒子,却把里面的珍珠还给了老板。猜一成语'],
|
||||
['answer' => '杞人忧天', 'hint' => '🧩 有个怪人天天担心天会塌下来,地会陷下去。猜一成语'],
|
||||
['answer' => '画饼充饥', 'hint' => '🧩 饿了看着墙上画的大饼,假装自己吃饱了。猜一成语'],
|
||||
['answer' => '空中楼阁', 'hint' => '🧩 没有地基,没有支柱,一座房子浮在云端。猜一成语'],
|
||||
['answer' => '异想天开', 'hint' => '🧩 有人想在天上种田,海里摘星星。猜一成语'],
|
||||
['answer' => '千方百计', 'hint' => '🧩 为了达到目的,把所有能想到的办法都用上了。猜一成语'],
|
||||
['answer' => '不计其数', 'hint' => '🧩 海边的沙子有多少?天上的星星有多少?猜一成语'],
|
||||
['answer' => '成千上万', 'hint' => '🧩 体育场里坐满了人,放眼望去黑压压一片。猜一成语'],
|
||||
['answer' => '独一无二', 'hint' => '🧩 世界上没有第二个一模一样的你。猜一成语'],
|
||||
['answer' => '举世闻名', 'hint' => '🧩 地球上有几个人,就有几个人知道他。猜一成语'],
|
||||
['answer' => '名不虚传', 'hint' => '🧩 听说很好吃,亲自尝了一口,果然名不虚传。不对,我说的就是~猜一成语'],
|
||||
['answer' => '名副其实', 'hint' => '🧩 大家都叫他「神算子」,他算卦确实从没错过。猜一成语'],
|
||||
['answer' => '引人入胜', 'hint' => '🧩 这本书太好看了,一翻开就停不下来,像被吸进去了一样。猜一成语'],
|
||||
['answer' => '身临其境', 'hint' => '🧩 VR眼镜里的世界太真实了,好像自己真的在里面。猜一成语'],
|
||||
['answer' => '迫不及待', 'hint' => '🧩 快递到了,鞋都没穿就跑下楼去拿。猜一成语'],
|
||||
['answer' => '争先恐后', 'hint' => '🧩 超市大减价,大门一开所有人都在往前冲。猜一成语'],
|
||||
['answer' => '如履薄冰', 'hint' => '🧩 每一步都小心翼翼,生怕脚下突然裂开。猜一成语'],
|
||||
['answer' => '小心翼翼', 'hint' => '🧩 手里捧着一个装满水的气球,大气都不敢喘。猜一成语'],
|
||||
['answer' => '心花怒放', 'hint' => '🧩 听到被录取的消息,心里像有千万朵花同时绽放。猜一成语'],
|
||||
['answer' => '欢天喜地', 'hint' => '🧩 过年了,小孩拿到压岁钱在大街上又蹦又跳。猜一成语'],
|
||||
['answer' => '眉开眼笑', 'hint' => '🧩 嘴角上扬,眼角弯弯,整张脸都在表达开心。猜一成语'],
|
||||
['answer' => '手舞足蹈', 'hint' => '🧩 听到最喜欢的歌,身体不由自主地跟着节奏动起来。猜一成语'],
|
||||
['answer' => '兴高采烈', 'hint' => '🧩 中彩票后,他整个人像打了鸡血一样。猜一成语'],
|
||||
['answer' => '得意忘形', 'hint' => '🧩 考了第一名就开始翘尾巴,连走路姿势都不一样了。猜一成语'],
|
||||
['answer' => '怒气冲天', 'hint' => '🧩 他气得头顶冒烟,火焰快要烧到天花板了。猜一成语'],
|
||||
['answer' => '火冒三丈', 'hint' => '🧩 听到这个消息,他脑袋上的火苗蹿得比房子还高。猜一成语'],
|
||||
['answer' => '心急如焚', 'hint' => '🧩 等结果的那几分钟,心脏像放在火上烤。猜一成语'],
|
||||
['answer' => '愁眉苦脸', 'hint' => '🧩 眉头拧成麻花,嘴角向下弯,整张脸写满了不开心。猜一成语'],
|
||||
['answer' => '泪如雨下', 'hint' => '🧩 他哭得比外面的倾盆大雨还要猛。猜一成语'],
|
||||
['answer' => '目瞪口呆', 'hint' => '🧩 看到 UFO 从头顶飞过,他张大了嘴巴一句话也说不出来。猜一成语'],
|
||||
['answer' => '惊弓之鸟', 'hint' => '🧩 被弓箭射过一次的鸟,听到弓弦声就吓得乱飞。猜一成语'],
|
||||
['answer' => '千钧一发', 'hint' => '🧩 一万斤的重物吊在一根头发丝上,随时会断。猜一成语'],
|
||||
['answer' => '愚公移山', 'hint' => '🧩 九十岁老头发誓要搬走门口的两座大山,子子孙孙无穷匮也。猜一成语'],
|
||||
];
|
||||
|
||||
foreach ($idioms as $index => $idiom) {
|
||||
Riddle::updateOrCreate(
|
||||
[
|
||||
'type' => Riddle::TYPE_IDIOM,
|
||||
'answer' => $idiom['answer'],
|
||||
],
|
||||
[
|
||||
'hint' => $idiom['hint'],
|
||||
'is_active' => true,
|
||||
'sort' => $index + 1,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// 新增脑筋急转弯题库,供猜谜活动切换题型时直接使用。
|
||||
$brainTeasers = [
|
||||
['answer' => '影子', 'hint' => '🧠 天天跟着你走,白天有晚上无,看得见摸不着,是什么?'],
|
||||
['answer' => '回声', 'hint' => '🧠 你喊它也喊,你停它就停,山谷里最常见,是什么?'],
|
||||
['answer' => '镜子', 'hint' => '🧠 你哭它也哭,你笑它也笑,但它永远不会先动,是什么?'],
|
||||
['answer' => '口罩', 'hint' => '🧠 戴在脸上不是面具,遮住口鼻保健康,是什么?'],
|
||||
['answer' => '手套', 'hint' => '🧠 五个小兄弟住两套房,冬天最爱穿,是什么?'],
|
||||
['answer' => '袜子', 'hint' => '🧠 一对好朋友,天天躲鞋里,是什么?'],
|
||||
['answer' => '鞋带', 'hint' => '🧠 两条细长蛇,天天趴鞋上,不打结鞋就跑,是什么?'],
|
||||
['answer' => '雨伞', 'hint' => '🧠 下雨天开花,晴天就收起,是什么?'],
|
||||
['answer' => '帽子', 'hint' => '🧠 不长头发却总爱站在头顶,是什么?'],
|
||||
['answer' => '围巾', 'hint' => '🧠 冬天挂脖子,既不是项链也不是绳子,是什么?'],
|
||||
['answer' => '口红', 'hint' => '🧠 不是彩笔,却常在嘴上画颜色,是什么?'],
|
||||
['answer' => '牙刷', 'hint' => '🧠 头上长毛,天天进嘴里干活,是什么?'],
|
||||
['answer' => '牙膏', 'hint' => '🧠 白白一条小胖虫,挤出来给牙刷帮忙,是什么?'],
|
||||
['answer' => '肥皂', 'hint' => '🧠 越洗越瘦,越搓泡泡越多,是什么?'],
|
||||
['answer' => '毛巾', 'hint' => '🧠 洗完脸后最爱找它抱一抱,是什么?'],
|
||||
['answer' => '梳子', 'hint' => '🧠 一排小牙齿,不吃饭,只理头发,是什么?'],
|
||||
['answer' => '吹风机', 'hint' => '🧠 会吹热风的小机器,洗完头总请它帮忙,是什么?'],
|
||||
['answer' => '指甲刀', 'hint' => '🧠 身子很小嘴巴很硬,专门啃手指头,是什么?'],
|
||||
['answer' => '钥匙', 'hint' => '🧠 个子不大本事大,能把锁头嘴巴打开,是什么?'],
|
||||
['answer' => '锁', 'hint' => '🧠 一张铁嘴不吃饭,钥匙一来才张口,是什么?'],
|
||||
['answer' => '门铃', 'hint' => '🧠 客人到门口,不敲门先叫唤,是什么?'],
|
||||
['answer' => '电梯', 'hint' => '🧠 关上门就上下跑,不是汽车不上路,是什么?'],
|
||||
['answer' => '楼梯', 'hint' => '🧠 一节一节往上走,不会动却能送人上楼,是什么?'],
|
||||
['answer' => '窗户', 'hint' => '🧠 墙上开个洞,白天爱看风景,晚上爱看月亮,是什么?'],
|
||||
['answer' => '窗帘', 'hint' => '🧠 白天拉开,晚上关上,帮房间遮眼睛,是什么?'],
|
||||
['answer' => '镜框', 'hint' => '🧠 不会照人,却总抱着照片或镜子,是什么?'],
|
||||
['answer' => '桌子', 'hint' => '🧠 四条腿不会走,肚皮平平能放东西,是什么?'],
|
||||
['answer' => '椅子', 'hint' => '🧠 有脚不走路,专门让人坐,是什么?'],
|
||||
['answer' => '沙发', 'hint' => '🧠 胖胖软软客厅王,大家累了都爱躺,是什么?'],
|
||||
['answer' => '床', 'hint' => '🧠 白天安安静静,晚上最忙,是什么?'],
|
||||
['answer' => '枕头', 'hint' => '🧠 软绵绵的小山包,睡觉时总垫在头下,是什么?'],
|
||||
['answer' => '被子', 'hint' => '🧠 白天叠成豆腐块,晚上张开抱住你,是什么?'],
|
||||
['answer' => '闹钟', 'hint' => '🧠 不会说早安,却总把你从梦里拽出来,是什么?'],
|
||||
['answer' => '日历', 'hint' => '🧠 每过一天就瘦一张,是什么?'],
|
||||
['answer' => '时钟', 'hint' => '🧠 三根兄弟赛跑,一圈一圈不停歇,是什么?'],
|
||||
['answer' => '手机', 'hint' => '🧠 不长嘴巴却能说话,不长耳朵却能听见,是什么?'],
|
||||
['answer' => '电话', 'hint' => '🧠 两地相隔很远,也能贴耳说悄悄话,是什么?'],
|
||||
['answer' => '电视', 'hint' => '🧠 小小方盒子,里面天天演大戏,是什么?'],
|
||||
['answer' => '遥控器', 'hint' => '🧠 不用走过去,按按它就能让电视听话,是什么?'],
|
||||
['answer' => '电脑', 'hint' => '🧠 肚子里装知识,手指一敲就干活,是什么?'],
|
||||
['answer' => '键盘', 'hint' => '🧠 一排排小方块,不是钢琴也能打字,是什么?'],
|
||||
['answer' => '鼠标', 'hint' => '🧠 名字像老鼠,却最怕猫,天天趴桌上,是什么?'],
|
||||
['answer' => '耳机', 'hint' => '🧠 一左一右挂耳边,音乐只给你一个人听,是什么?'],
|
||||
['answer' => '音箱', 'hint' => '🧠 肚里藏着喇叭,最会放大声音,是什么?'],
|
||||
['answer' => '充电器', 'hint' => '🧠 手机饿了它喂饭,是什么?'],
|
||||
['answer' => '电池', 'hint' => '🧠 个子小,电量大,很多机器靠它活,是什么?'],
|
||||
['answer' => '电灯', 'hint' => '🧠 太阳下班它上岗,是什么?'],
|
||||
['answer' => '灯泡', 'hint' => '🧠 玻璃肚里藏火苗,黑夜一亮像白天,是什么?'],
|
||||
['answer' => '蜡烛', 'hint' => '🧠 有泪不会哭,有火不会叫,越烧越短,是什么?'],
|
||||
['answer' => '火柴', 'hint' => '🧠 头戴红帽子,脾气特别火,一擦就冒火星,是什么?'],
|
||||
['answer' => '打火机', 'hint' => '🧠 小盒子脾气爆,拇指一按就出火,是什么?'],
|
||||
['answer' => '冰箱', 'hint' => '🧠 肚子大又冷,专门帮食物避暑,是什么?'],
|
||||
['answer' => '空调', 'hint' => '🧠 夏天送凉风,冬天送暖风,挂在墙上最勤快,是什么?'],
|
||||
['answer' => '风扇', 'hint' => '🧠 没有翅膀也会转,专给人送风,是什么?'],
|
||||
['answer' => '洗衣机', 'hint' => '🧠 不长手,却特别会洗衣服,是什么?'],
|
||||
['answer' => '熨斗', 'hint' => '🧠 衣服皱巴巴,它一来就服服帖帖,是什么?'],
|
||||
['answer' => '微波炉', 'hint' => '🧠 剩饭剩菜进去转几圈,就又热乎了,是什么?'],
|
||||
['answer' => '电饭煲', 'hint' => '🧠 白米进去,香饭出来,是什么?'],
|
||||
['answer' => '锅', 'hint' => '🧠 黑脸大肚子,天天在灶台上唱歌,是什么?'],
|
||||
['answer' => '筷子', 'hint' => '🧠 两个瘦兄弟,合作夹饭菜,是什么?'],
|
||||
['answer' => '勺子', 'hint' => '🧠 有个圆脑袋,喝汤最拿手,是什么?'],
|
||||
['answer' => '碗', 'hint' => '🧠 圆圆小肚皮,最爱装米饭和汤,是什么?'],
|
||||
['answer' => '盘子', 'hint' => '🧠 扁扁一张脸,端菜最稳,是什么?'],
|
||||
['answer' => '杯子', 'hint' => '🧠 不会说话却总装水,是什么?'],
|
||||
['answer' => '水壶', 'hint' => '🧠 肚子能装水,嘴巴细细长长,是什么?'],
|
||||
['answer' => '吸管', 'hint' => '🧠 不用嘴碰杯,也能把饮料送进肚,是什么?'],
|
||||
['answer' => '铅笔', 'hint' => '🧠 身子细细穿木衣,肚里黑黑会写字,是什么?'],
|
||||
['answer' => '橡皮', 'hint' => '🧠 不会写字专会擦,哪里写错它就上,是什么?'],
|
||||
['answer' => '尺子', 'hint' => '🧠 身子直直会量长短,还能帮人画直线,是什么?'],
|
||||
['answer' => '书包', 'hint' => '🧠 不会走路却天天背着书上学,是什么?'],
|
||||
['answer' => '课本', 'hint' => '🧠 不会说话却肚子里全是知识,是什么?'],
|
||||
['answer' => '黑板', 'hint' => '🧠 一张大黑脸,粉笔天天在上面写字,是什么?'],
|
||||
['answer' => '粉笔', 'hint' => '🧠 白白瘦瘦,最爱在黑板上留下痕迹,是什么?'],
|
||||
['answer' => '粉笔擦', 'hint' => '🧠 不会写字却专门抹掉黑板上的字,是什么?'],
|
||||
['answer' => '书签', 'hint' => '🧠 个子小小住书里,帮你记住看到哪一页,是什么?'],
|
||||
['answer' => '放大镜', 'hint' => '🧠 小东西一到它眼前,立刻显得很大,是什么?'],
|
||||
['answer' => '望远镜', 'hint' => '🧠 明明站在原地,却能看见很远的东西,是什么?'],
|
||||
['answer' => '相机', 'hint' => '🧠 不会画画却能把风景留住,是什么?'],
|
||||
['answer' => '照片', 'hint' => '🧠 不会动不会说,却能把昨天留下来,是什么?'],
|
||||
['answer' => '地图', 'hint' => '🧠 不出门也能带你认识世界,是什么?'],
|
||||
['answer' => '地球仪', 'hint' => '🧠 一个蓝色大圆球,抱着全世界,是什么?'],
|
||||
['answer' => '篮球', 'hint' => '🧠 穿着橙色外衣,最爱往框里钻,是什么?'],
|
||||
['answer' => '足球', 'hint' => '🧠 用脚最喜欢的圆朋友,是什么?'],
|
||||
['answer' => '羽毛球', 'hint' => '🧠 头圆圆,尾巴白白,飞起来像小鸟,是什么?'],
|
||||
['answer' => '乒乓球', 'hint' => '🧠 白白小圆豆,桌上跳来跳去,是什么?'],
|
||||
['answer' => '跳绳', 'hint' => '🧠 一根长线会转圈,小朋友最爱跳过去,是什么?'],
|
||||
['answer' => '秋千', 'hint' => '🧠 坐上去前后飞,却飞不离原地,是什么?'],
|
||||
['answer' => '风筝', 'hint' => '🧠 长着尾巴在天上飞,线一松就跑,是什么?'],
|
||||
['answer' => '气球', 'hint' => '🧠 胖胖肚子装着气,手一松就想上天,是什么?'],
|
||||
['answer' => '雪人', 'hint' => '🧠 冬天站院里,太阳一晒就瘦,是什么?'],
|
||||
['answer' => '彩虹', 'hint' => '🧠 雨过天晴天上挂着七色桥,是什么?'],
|
||||
['answer' => '云', 'hint' => '🧠 白天像棉花,风一吹就变样,是什么?'],
|
||||
['answer' => '雾', 'hint' => '🧠 没下雨却湿漉漉,早晨最爱挡路,是什么?'],
|
||||
['answer' => '霜', 'hint' => '🧠 不是雪却白在草上,太阳一出就化,是什么?'],
|
||||
['answer' => '露珠', 'hint' => '🧠 清晨叶子上挂着一颗颗小珍珠,是什么?'],
|
||||
['answer' => '月亮', 'hint' => '🧠 白天看不清,晚上天上挂银盘,是什么?'],
|
||||
['answer' => '星星', 'hint' => '🧠 白天藏起来,晚上眨眼睛,是什么?'],
|
||||
['answer' => '太阳', 'hint' => '🧠 白天值班最勤快,大家都靠它发光发热,是什么?'],
|
||||
['answer' => '雷', 'hint' => '🧠 看不见摸不着,却能在天上大声打鼓,是什么?'],
|
||||
['answer' => '闪电', 'hint' => '🧠 先看到一道亮鞭子,再听见轰隆隆,是什么?'],
|
||||
];
|
||||
|
||||
foreach ($brainTeasers as $index => $brainTeaser) {
|
||||
Riddle::updateOrCreate(
|
||||
[
|
||||
'type' => Riddle::TYPE_BRAIN_TEASER,
|
||||
'answer' => $brainTeaser['answer'],
|
||||
],
|
||||
[
|
||||
'hint' => $brainTeaser['hint'],
|
||||
'is_active' => true,
|
||||
'sort' => 1000 + $index + 1,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+75
-12
@@ -9,6 +9,22 @@ NC='\033[0m'
|
||||
|
||||
PROJECT_ROOT="/www/wwwroot/chat.ay.lc" # <--- 确认这里的路径是否正确
|
||||
export COMPOSER_ALLOW_SUPERUSER=1
|
||||
SUPERVISORCTL_BIN=""
|
||||
PHP_BIN=""
|
||||
|
||||
for candidate in /usr/bin/supervisorctl /usr/local/bin/supervisorctl /www/server/panel/pyenv/bin/supervisorctl; do
|
||||
if [ -x "$candidate" ]; then
|
||||
SUPERVISORCTL_BIN="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
for candidate in /www/server/php/84/bin/php /usr/bin/php /usr/local/bin/php; do
|
||||
if [ -x "$candidate" ]; then
|
||||
PHP_BIN="$candidate"
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
echo -e "${BLUE}========================================${NC}"
|
||||
echo -e "${BLUE} 🚀 Laravel 稳健更新脚本 (带严格检查) ${NC}"
|
||||
@@ -16,14 +32,22 @@ echo -e "${BLUE}========================================${NC}"
|
||||
|
||||
cd "$PROJECT_ROOT" || { echo -e "${RED}❌ 无法进入项目目录:$PROJECT_ROOT${NC}"; exit 1; }
|
||||
|
||||
if [ -z "$PHP_BIN" ]; then
|
||||
echo -e "${RED}❌ 未找到可用 PHP 可执行文件,请确认服务器已安装 PHP 8.4。${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
PHP_VERSION=$("$PHP_BIN" -r 'echo PHP_VERSION;' 2>/dev/null)
|
||||
echo -e "${BLUE}使用 PHP:$PHP_BIN (版本:${PHP_VERSION:-unknown})${NC}"
|
||||
|
||||
# 1. Git Pull(先重置 lock 文件,避免服务器环境差异导致冲突)
|
||||
echo -e "${YELLOW}[1/7] 拉取代码...${NC}"
|
||||
echo -e "${YELLOW}[1/8] 拉取代码...${NC}"
|
||||
git checkout -- composer.lock package-lock.json 2>/dev/null || true
|
||||
git fetch origin && git pull origin master
|
||||
if [ $? -ne 0 ]; then echo -e "${RED}❌ Git 失败${NC}"; exit 1; fi
|
||||
|
||||
# 2. Composer Install (关键检查点)
|
||||
echo -e "${YELLOW}[2/7] 安装依赖 (Composer)...${NC}"
|
||||
echo -e "${YELLOW}[2/8] 安装依赖 (Composer)...${NC}"
|
||||
composer install --no-dev --optimize-autoloader --classmap-authoritative --no-interaction
|
||||
COMPOSER_EXIT_CODE=$?
|
||||
|
||||
@@ -58,7 +82,7 @@ composer dump-autoload --no-dev --optimize --classmap-authoritative --no-interac
|
||||
if [ $? -ne 0 ]; then echo -e "${RED}❌ Composer autoload 重建失败${NC}"; exit 1; fi
|
||||
|
||||
# 用当前 PHP 直接加载 Laravel autoload,提前暴露 vendor 缺文件 / 权限 / autoload 缓存问题
|
||||
php -d opcache.enable_cli=0 -r "require __DIR__.'/vendor/autoload.php'; echo 'Composer autoload OK'.PHP_EOL;"
|
||||
"$PHP_BIN" -d opcache.enable_cli=0 -r "require __DIR__.'/vendor/autoload.php'; echo 'Composer autoload OK'.PHP_EOL;"
|
||||
if [ $? -ne 0 ]; then
|
||||
echo -e "${RED}========================================${NC}"
|
||||
echo -e "${RED} ❌ 致命错误:PHP 无法加载 vendor/autoload.php! ${NC}"
|
||||
@@ -68,27 +92,66 @@ if [ $? -ne 0 ]; then
|
||||
fi
|
||||
|
||||
# 3. 前端构建
|
||||
echo -e "${YELLOW}[3/7] 前端构建 (npm run build)...${NC}"
|
||||
echo -e "${YELLOW}[3/8] 前端构建 (npm run build)...${NC}"
|
||||
npm run build
|
||||
if [ $? -ne 0 ]; then echo -e "${RED}❌ npm run build 失败${NC}"; exit 1; fi
|
||||
echo -e "${GREEN}✅ 前端资源构建完成。${NC}"
|
||||
|
||||
|
||||
# 4. 数据库迁移
|
||||
echo -e "${YELLOW}[5/7] 数据库迁移...${NC}"
|
||||
php artisan migrate --force
|
||||
echo -e "${YELLOW}[4/8] 数据库迁移...${NC}"
|
||||
"$PHP_BIN" artisan migrate --force
|
||||
|
||||
# 5. 优化
|
||||
echo -e "${YELLOW}[5/8] 生产环境优化...${NC}"
|
||||
# 注意:optimize 命令内部已经包含了 config:cache, route:cache, event:cache,此处无须多余处理
|
||||
php artisan optimize:clear && php artisan optimize && php artisan view:cache
|
||||
"$PHP_BIN" artisan optimize:clear && "$PHP_BIN" artisan optimize && "$PHP_BIN" artisan view:cache
|
||||
|
||||
# 6. 重启 Horizon / 队列进程
|
||||
echo -e "${YELLOW}[6/8] 重启 Horizon...${NC}"
|
||||
php artisan horizon:terminate
|
||||
"$PHP_BIN" artisan horizon:terminate >/dev/null 2>&1 || true
|
||||
if [ -n "$SUPERVISORCTL_BIN" ]; then
|
||||
"$SUPERVISORCTL_BIN" restart horizon >/dev/null 2>&1 || "$SUPERVISORCTL_BIN" restart horizon:* >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
# 7. 重载 PHP-FPM / opcache,避免 Web 进程继续使用旧的 autoload 缓存
|
||||
echo -e "${YELLOW}[7/8] 重载 PHP-FPM...${NC}"
|
||||
# 7. 重启 Reverb,确保长驻 WebSocket 进程加载最新代码和配置
|
||||
echo -e "${YELLOW}[7/8] 重启 Reverb...${NC}"
|
||||
REVERB_RESTARTED=0
|
||||
REVERB_CAN_AUTO_RESTART=0
|
||||
SUPERVISOR_REVERB_TARGET=""
|
||||
|
||||
# 先探测是否存在可自动拉起 Reverb 的进程管理器,避免在纯手工启动场景下执行 reverb:restart 后把聊天室停掉。
|
||||
if [ -n "$SUPERVISORCTL_BIN" ]; then
|
||||
if "$SUPERVISORCTL_BIN" status reverb >/dev/null 2>&1; then
|
||||
SUPERVISOR_REVERB_TARGET="reverb"
|
||||
REVERB_CAN_AUTO_RESTART=1
|
||||
elif "$SUPERVISORCTL_BIN" status reverb:* >/dev/null 2>&1; then
|
||||
SUPERVISOR_REVERB_TARGET="reverb:*"
|
||||
REVERB_CAN_AUTO_RESTART=1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Laravel 官方文档说明:reverb:restart 适合在 Supervisor 等进程管理器托管下使用。
|
||||
if [ "$REVERB_CAN_AUTO_RESTART" -eq 1 ]; then
|
||||
"$PHP_BIN" artisan reverb:restart >/dev/null 2>&1
|
||||
if [ $? -eq 0 ]; then
|
||||
REVERB_RESTARTED=1
|
||||
echo -e "${GREEN}✅ 已执行 php artisan reverb:restart。${NC}"
|
||||
fi
|
||||
|
||||
# 若线上通过 Supervisor 托管 reverb:start,再补一次显式 restart,尽量确保进程被拉起。
|
||||
if [ -n "$SUPERVISOR_REVERB_TARGET" ]; then
|
||||
"$SUPERVISORCTL_BIN" restart "$SUPERVISOR_REVERB_TARGET" >/dev/null 2>&1 || true
|
||||
REVERB_RESTARTED=1
|
||||
echo -e "${GREEN}✅ 已尝试重启 Supervisor 托管的 Reverb 进程。${NC}"
|
||||
fi
|
||||
else
|
||||
echo -e "${YELLOW}⚠️ 未检测到 Reverb 进程管理器,已跳过 reverb:restart,避免把手工启动的聊天室长连接服务停掉。${NC}"
|
||||
echo -e "${YELLOW}⚠️ 若当前服务器是手工执行 php artisan reverb:start,请在部署完成后手动重启该进程。${NC}"
|
||||
fi
|
||||
|
||||
# 8. 重载 PHP-FPM / opcache,避免 Web 进程继续使用旧的 autoload 缓存
|
||||
echo -e "${YELLOW}[8/8] 重载 PHP-FPM...${NC}"
|
||||
PHP_FPM_RELOADED=0
|
||||
if command -v systemctl >/dev/null 2>&1; then
|
||||
for svc in php-fpm php-fpm-84 php-fpm-83 php-fpm-82 php84-php-fpm php83-php-fpm php82-php-fpm; do
|
||||
@@ -110,8 +173,8 @@ else
|
||||
echo -e "${YELLOW}⚠️ 未识别到 PHP-FPM 服务,请在面板中手动重启当前站点使用的 PHP。${NC}"
|
||||
fi
|
||||
|
||||
# 6. 权限 (针对宝塔或Nginx+FPM环境的修正)
|
||||
echo -e "${YELLOW}[8/8] 修复权限...${NC}"
|
||||
# 权限修正(针对宝塔或 Nginx + FPM 环境)
|
||||
echo -e "${YELLOW}[后处理] 修复权限...${NC}"
|
||||
# 将所有文件所属权变更为 Web 运行用户(如 www),防止 root 权限导致框架日志或缓存写入失败
|
||||
chown -R www:www .
|
||||
# 默认读写执行权限
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "chatroom-ride-development",
|
||||
"version": "0.2.0",
|
||||
"description": "聊天室座驾开发插件,沉淀独立座驾模块、金币流水、特效注册、命名规则和测试清单。",
|
||||
"interface": {
|
||||
"displayName": "Chatroom Ride Development"
|
||||
},
|
||||
"skills": [
|
||||
{
|
||||
"name": "chatroom-ride-development",
|
||||
"path": "skills/chatroom-ride-development/SKILL.md"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
name: chatroom-ride-development
|
||||
description: "开发 /Users/pllx/Web/Herd/chatroom 的聊天室座驾。适用于新增 ride_<key> 独立座驾、全屏 Canvas 特效、座驾音效、后台配置、前台座驾页面和进房欢迎语。"
|
||||
---
|
||||
|
||||
# Chatroom Ride Development
|
||||
|
||||
## 适用场景
|
||||
|
||||
- 新增或修改聊天室独立座驾。
|
||||
- 新增 `resources/js/effects/<key>.js` 全屏座驾特效。
|
||||
- 调整座驾购买、续期、替换、入场欢迎语或后台价格/天数配置。
|
||||
- 排查座驾进房后特效不播放、欢迎语不显示、购买记录不正确的问题。
|
||||
- 排查座驾购买没有金币流水、后台座驾列表为空、前台座驾弹窗为空的问题。
|
||||
|
||||
## 必须遵守
|
||||
|
||||
- 座驾是独立模块:必须使用 `rides` 和 `user_ride_purchases`,不要写入 `shop_items` 或 `user_purchases`。
|
||||
- 商店模块只管理普通商店商品;不要给 `ShopItem` 增加 `TYPE_RIDE`、`isRide()`、`rideKey()` 或座驾欢迎语字段。
|
||||
- 座驾 slug 固定为 `ride_<effect_key>`。
|
||||
- `<effect_key>` 必须同时出现在:
|
||||
- `rides.slug`
|
||||
- `rides.effect_key`
|
||||
- `Ride::rideKey()` 可解析结果
|
||||
- `EffectBroadcast::TYPES`
|
||||
- `resources/js/effects/effect-manager.js`
|
||||
- `resources/js/effects/effect-sounds.js`
|
||||
- `resources/js/effects/<effect_key>.js`
|
||||
- 新增座驾默认通过迁移或 Seeder 写入 `rides`,字段至少包含名称、slug、`effect_key`、图标、价格、`duration_days`、排序和 `welcome_message`。
|
||||
- `welcome_message` 支持 `{name}` 和 `{ride}`,输出前必须转义,不能直接信任后台输入。
|
||||
- 当前版本只允许用户同时拥有一个 active 座驾;同款续购叠加有效期,不同款替换旧座驾并把旧记录置为 `cancelled`。
|
||||
- 用户购买记录必须写入 `user_ride_purchases`,不要复用商店购买记录。
|
||||
- 座驾购买扣金币必须走 `UserCurrencyService::deductGoldIfEnough()`,来源使用 `CurrencySource::RIDE_BUY`,并写入 `user_currency_logs`。
|
||||
- 座驾购买接口必须携带房间 ID,并把 `room_id` 传给金币流水,方便后台按房间追溯。
|
||||
- 测试中禁止使用 `Redis::flushall()` 清理聊天室状态;只允许清理 `room:*` 相关 key,避免把本机登录 session 一起删掉。
|
||||
|
||||
## 模块边界
|
||||
|
||||
- 前台接口:`GET /rides/items`、`POST /rides/buy`。
|
||||
- 后台入口:`GET /admin/rides`,页面文件为 `resources/views/admin/rides/index.blade.php`。
|
||||
- 前台弹窗脚本:`resources/js/chat-room/ride-controls.js`。
|
||||
- 业务服务:`app/Services/RideService.php`。
|
||||
- 数据模型:`app/Models/Ride.php`、`app/Models/UserRidePurchase.php`。
|
||||
- 请求验证:`BuyRideRequest`、`StoreRideRequest`、`UpdateRideRequest`。
|
||||
|
||||
## 已验收的进房展示规则
|
||||
|
||||
- 用户有有效座驾时,座驾优先级最高:
|
||||
- 只发送一条 `座驾播报` 文字消息。
|
||||
- 不再发送普通 `进出播报`。
|
||||
- 不再播放会员进场横幅或会员全屏特效。
|
||||
- 座驾全屏特效播放范围是当前房间内所有在线用户:
|
||||
- 进房用户本人通过 `initialRideEffect` 本地播放。
|
||||
- 其他在线用户通过 `EffectBroadcast` 的 `room.{roomId}` PresenceChannel 播放。
|
||||
- 不设置 `target_username`,表示当前房间全员可见。
|
||||
- 座驾文字播报口径:
|
||||
- 显示 `部门 <部门> · 职务 <图标 职务> · 会员 <图标 会员>`。
|
||||
- 不在身份行前面显示 `用户 <用户名>`,因为后面的欢迎语模板已经包含 `{name}`。
|
||||
- 示例:`🚀 部门 办公厅 · 职务 🎖️ 技术总监 · 会员 👑 至尊会员 · 【流星】乘【东风-5C战略导弹】点火升空...`
|
||||
- 座驾动画 HUD 标题口径:
|
||||
- 第一行用户身份信息显示 `用户 <用户名> · 部门 <部门> · 职务 <图标 职务> · 会员 <图标 会员>`。
|
||||
- 第二行标题只显示 `乘坐【<座驾名称>】闪亮登场`,不要重复用户名。
|
||||
- `effect_user_info` 供动画 HUD 第一行使用,`effect_title` 供动画 HUD 第二行使用,`identity_text` 只供文字播报使用。
|
||||
- 前端改动后如果浏览器仍显示旧动画标题,必须运行 `npm run build` 或确认 Vite dev server 已刷新,避免加载旧的 `public/build` 资源。
|
||||
|
||||
## 新增座驾步骤
|
||||
|
||||
1. 新增全屏特效文件:`resources/js/effects/<effect_key>.js`。
|
||||
2. 在 `effect-manager.js` 注册模块加载和启动分支。
|
||||
3. 在 `effect-sounds.js` 注册音效启动分支。
|
||||
4. 在 `EffectBroadcast::TYPES` 加入 `<effect_key>`。
|
||||
5. 在迁移或 Seeder 中新增 `rides` 记录,slug 使用 `ride_<effect_key>`,`effect_key` 使用 `<effect_key>`。
|
||||
6. 确认后台 `座驾管理` 可以配置价格、使用天数、欢迎语、上下架状态和排序。
|
||||
7. 确认 `RideService::buy()` 购买时写入 `user_ride_purchases` 和 `user_currency_logs`。
|
||||
8. 更新座驾相关 PHPUnit 测试,至少覆盖列表、余额不足、购买成功、金币流水、续期、替换和进房触发。
|
||||
|
||||
## 金币流水要求
|
||||
|
||||
- 购买成功必须在 `user_currency_logs` 中写入:
|
||||
- `currency = gold`
|
||||
- `amount = -座驾价格`
|
||||
- `source = ride_buy`
|
||||
- `remark = 购买聊天室座驾:<座驾名称>`
|
||||
- `room_id = 当前房间 ID`
|
||||
- 余额不足时不能写 `user_ride_purchases`,也不能写 `user_currency_logs`。
|
||||
- 不要用 `$user->decrement('jjb', ...)` 直接扣金币。
|
||||
|
||||
## 旧方案清理要求
|
||||
|
||||
- 不要恢复 `add_ride_fields_to_shop_items` 这类把座驾挂到商店表的迁移。
|
||||
- 允许保留清理迁移,用于删除旧环境中 `shop_items.slug like ride_%`、`shop_items.type = ride` 或 `shop_items.welcome_message` 残留。
|
||||
- 修改座驾模块后,检查 `rg 'TYPE_RIDE|ShopItem::rideKey|RideItemController|复用商店购买记录'`,确认没有旧方案引用。
|
||||
|
||||
## 验证清单
|
||||
|
||||
- `node --check resources/js/effects/<effect_key>.js`
|
||||
- `node --check resources/js/effects/effect-manager.js`
|
||||
- `node --check resources/js/effects/effect-sounds.js`
|
||||
- `php artisan test --compact tests/Feature/RideControllerTest.php`
|
||||
- 有进房逻辑变更时运行相关 `ChatControllerTest` 过滤用例。
|
||||
- 涉及商店边界时运行 `php artisan test --compact tests/Feature/ShopControllerTest.php`。
|
||||
- 修改 PHP 后运行 `vendor/bin/pint --dirty --format=agent`。
|
||||
|
||||
## 特别注意
|
||||
|
||||
- 如果从 stash 恢复昨天的座驾特效,必须确认 untracked 父提交中的新特效文件也已恢复,不能只恢复已跟踪文件。
|
||||
- `99a` 这种以数字开头的 key 在 JS 对象字面量里必须加引号。
|
||||
- 新座驾的展示名可以是中文,但 effect key 必须保持小写短横线/数字/字母风格,避免前后端匹配失败。
|
||||
- 本项目 PHP 文件要求类和方法上方有中文 DocBlock;新增座驾相关 PHP 文件时必须补齐。
|
||||
+2
-2
@@ -216,7 +216,7 @@ a:hover {
|
||||
}
|
||||
|
||||
.msg-line .msg-time {
|
||||
font-size: 9px;
|
||||
font-size: 0.72em;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
@@ -245,7 +245,7 @@ a:hover {
|
||||
.msg-line.sys-msg {
|
||||
color: #cc0000;
|
||||
text-align: center;
|
||||
font-size: 9pt;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
/* ── 底部输入工具栏 ─────────────────────────────── */
|
||||
|
||||
+26
-2
@@ -7,6 +7,30 @@
|
||||
* @version 1.0.0
|
||||
*/
|
||||
|
||||
/* ═══════════════════════════════════════════════════
|
||||
拍一拍:屏幕抖动动画
|
||||
═══════════════════════════════════════════════════ */
|
||||
@keyframes chat-shake {
|
||||
0%, 100% { transform: translateX(0); }
|
||||
10%, 50%, 90% { transform: translateX(-4px); }
|
||||
30%, 70% { transform: translateX(4px); }
|
||||
}
|
||||
|
||||
.chat-shake {
|
||||
animation: chat-shake 0.4s ease-in-out;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════
|
||||
斜杠命令菜单
|
||||
═══════════════════════════════════════════════════ */
|
||||
.slash-command-menu::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
.slash-command-menu::-webkit-scrollbar-thumb {
|
||||
background: #cbd5e1;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
/* Alpine.js x-cloak:初始化完成前完全隐藏,防止弹窗闪烁 */
|
||||
[x-cloak] {
|
||||
display: none !important;
|
||||
@@ -216,7 +240,7 @@ a:hover {
|
||||
}
|
||||
|
||||
.msg-line .msg-time {
|
||||
font-size: 9px;
|
||||
font-size: 0.72em;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
@@ -245,7 +269,7 @@ a:hover {
|
||||
.msg-line.sys-msg {
|
||||
color: #cc0000;
|
||||
text-align: center;
|
||||
font-size: 9pt;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
/* ── 底部输入工具栏 ─────────────────────────────── */
|
||||
|
||||
@@ -139,6 +139,10 @@ const _shop = createLazyModule(
|
||||
() => import("./chat-room/shop-controls.js"),
|
||||
(mod) => mod.bindShopControls()
|
||||
);
|
||||
const _ride = createLazyModule(
|
||||
() => import("./chat-room/ride-controls.js"),
|
||||
(mod) => mod.bindRideControls()
|
||||
);
|
||||
const _compactShop = createLazyModule(
|
||||
() => import("./chat-room/compact-shop-panel.js"),
|
||||
(mod) => mod.bindCompactShopPanelControls()
|
||||
@@ -216,7 +220,7 @@ import { initChatImageLightboxEvents, closeChatImageLightbox, openChatImageLight
|
||||
import { bindRoomStatusControls, normalizeRoomStatus, renderRoomStatusRow, renderRoomsOnlineStatus, renderRoomsOnlineStatusToContainer, resolveRoomUrl } from "./chat-room/rooms.js";
|
||||
import { bindChatRightPanelControls } from "./chat-room/right-panel.js";
|
||||
import { bindChatImageUploadControl } from "./chat-room/image-upload.js";
|
||||
import { applyFontSize, bindChatFontSizeControl, CHAT_FONT_SIZE_STORAGE_KEY, restoreChatFontSize } from "./chat-room/font-size.js";
|
||||
import { applyFontSize, bindChatFontSizeControl, CHAT_DEFAULT_FONT_SIZE, CHAT_FONT_SIZE_STORAGE_KEY, restoreChatFontSize } from "./chat-room/font-size.js";
|
||||
import { bindAppointmentAnnouncementControls, showAppointmentBanner } from "./chat-room/appointment-announcement.js";
|
||||
import { bindChatBanner } from "./chat-room/banner.js";
|
||||
import { bindChatBotControls, clearChatBotContext, sendToChatBot } from "./chat-room/chat-bot.js";
|
||||
@@ -288,9 +292,22 @@ import { leaveRoom, notifyExpiredLeave, saveExp, startHeartbeat, stopHeartbeat }
|
||||
import { bindToolbarControls, runFeatureShortcut, runToolbarAction } from "./chat-room/toolbar.js";
|
||||
import { bindChatInitialStateControls } from "./chat-room/initial-state.js";
|
||||
|
||||
// 拍一拍模块
|
||||
import "./chat-room/pat.js";
|
||||
|
||||
// 猜成语游戏模块
|
||||
import "./chat-room/riddle-quiz.js";
|
||||
import { bindIdiomQuizControls } from "./chat-room/riddle-quiz.js";
|
||||
|
||||
// 斜杠命令菜单
|
||||
import { bindSlashCommands, registerSlashCommand } from "./chat-room/slash-commands.js";
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
bindInstantHoverTooltip();
|
||||
|
||||
// 初始化斜杠命令菜单
|
||||
bindSlashCommands();
|
||||
|
||||
// 保留聚合入口,懒加载模块通过按需动态导入自动初始化。
|
||||
window.ChatRoomTools = {
|
||||
// ── 静态核心模块(直接引用) ────────────────
|
||||
@@ -379,6 +396,13 @@ if (typeof window !== "undefined") {
|
||||
renderShop: (...args) => _shop.wrap('renderShop')(...args),
|
||||
showShopToast: (...args) => _shop.wrap('showShopToast')(...args),
|
||||
submitRename: (...args) => _shop.wrap('submitRename')(...args),
|
||||
bindRideControls: (...args) => _ride.wrap('bindRideControls')(...args),
|
||||
buyRide: (...args) => _ride.wrap('buyRide')(...args),
|
||||
closeRideModal: (...args) => _ride.wrap('closeRideModal')(...args),
|
||||
fetchRideData: (...args) => _ride.wrap('fetchRideData')(...args),
|
||||
loadRides: (...args) => _ride.wrap('loadRides')(...args),
|
||||
openRideModal: (...args) => _ride.wrap('openRideModal')(...args),
|
||||
renderRides: (...args) => _ride.wrap('renderRides')(...args),
|
||||
bindCompactShopPanelControls: (...args) => _compactShop.wrap('bindCompactShopPanelControls')(...args),
|
||||
buyCompactShopItem: (...args) => _compactShop.wrap('buyCompactShopItem')(...args),
|
||||
closeCompactRenameModal: (...args) => _compactShop.wrap('closeCompactRenameModal')(...args),
|
||||
@@ -448,6 +472,7 @@ if (typeof window !== "undefined") {
|
||||
sendToChatBot,
|
||||
applyFontSize,
|
||||
bindChatFontSizeControl,
|
||||
CHAT_DEFAULT_FONT_SIZE,
|
||||
CHAT_FONT_SIZE_STORAGE_KEY,
|
||||
restoreChatFontSize,
|
||||
bindChatImageUploadControl,
|
||||
@@ -469,6 +494,7 @@ if (typeof window !== "undefined") {
|
||||
bindWelcomeMenuControls,
|
||||
toggleWelcomeMenu,
|
||||
bindAdminMenuControls,
|
||||
registerSlashCommand,
|
||||
bindBaccaratEvents,
|
||||
bindBaccaratLossCoverAdminControls,
|
||||
closeAdminBaccaratLossCoverModal,
|
||||
@@ -613,6 +639,12 @@ if (typeof window !== "undefined") {
|
||||
window.renderShop = (...args) => _shop.wrap('renderShop')(...args);
|
||||
window.showShopToast = (...args) => _shop.wrap('showShopToast')(...args);
|
||||
window.submitRename = (...args) => _shop.wrap('submitRename')(...args);
|
||||
window.buyRide = (...args) => _ride.wrap('buyRide')(...args);
|
||||
window.closeRideModal = (...args) => _ride.wrap('closeRideModal')(...args);
|
||||
window.fetchRideData = (...args) => _ride.wrap('fetchRideData')(...args);
|
||||
window.loadRides = (...args) => _ride.wrap('loadRides')(...args);
|
||||
window.openRideModal = (...args) => _ride.wrap('openRideModal')(...args);
|
||||
window.renderRides = (...args) => _ride.wrap('renderRides')(...args);
|
||||
window.closeAvatarPicker = (...args) => _profile.wrap('closeAvatarPicker')(...args);
|
||||
window.closeSettingsModal = (...args) => _profile.wrap('closeSettingsModal')(...args);
|
||||
window.copyWechatBindCode = (...args) => _profile.wrap('copyWechatBindCode')(...args);
|
||||
@@ -680,6 +712,7 @@ if (typeof window !== "undefined") {
|
||||
window.loadFeedbackData = loadFeedbackData;
|
||||
window.loadMoreFeedback = loadMoreFeedback;
|
||||
window.bindFeedbackControls = bindFeedbackControls;
|
||||
window.registerSlashCommand = registerSlashCommand;
|
||||
|
||||
// ── Alpine 组件(静态导入,Blade 中 x-data 引用时同步可用) ──
|
||||
window.userCardComponent = userCardComponent;
|
||||
@@ -767,4 +800,5 @@ if (typeof window !== "undefined") {
|
||||
bindChatBotControls();
|
||||
bindGuestbookControls();
|
||||
bindFeedbackControls();
|
||||
bindIdiomQuizControls();
|
||||
}
|
||||
|
||||
@@ -46,6 +46,19 @@ export function bindAdminMenuControls() {
|
||||
return;
|
||||
}
|
||||
|
||||
const effectPreviewButton = event.target.closest("[data-chat-admin-effect-preview]");
|
||||
if (effectPreviewButton) {
|
||||
event.preventDefault();
|
||||
const effect = effectPreviewButton.getAttribute("data-chat-admin-effect-preview") || "";
|
||||
const menu = document.getElementById("admin-menu");
|
||||
if (menu) {
|
||||
menu.style.display = "none";
|
||||
}
|
||||
// 预览按钮仅在当前浏览器播放,方便测试新特效时不打扰房间其他用户。
|
||||
window.EffectManager?.play?.(effect);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.target.closest("[data-chat-admin-menu]")) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import { enqueueChatMessage } from "./message-renderer.js";
|
||||
|
||||
// ── 事件注册标记 ──
|
||||
let chatEventsBound = false;
|
||||
let chatWebSocketInitRetryTimer = null;
|
||||
const GOMOKU_INVITE_BUTTON_FONT_SIZE = "0.82em";
|
||||
|
||||
// ── 辅助函数 ──
|
||||
function csrf() {
|
||||
@@ -21,9 +23,40 @@ function getState() {
|
||||
* 启动 WebSocket 初始化(DOMContentLoaded 之后调用)。
|
||||
*/
|
||||
function initChatWebSocket() {
|
||||
if (chatWebSocketInitRetryTimer) {
|
||||
window.clearTimeout(chatWebSocketInitRetryTimer);
|
||||
chatWebSocketInitRetryTimer = null;
|
||||
}
|
||||
|
||||
if (typeof window.initChat === "function" && window.chatContext?.roomId) {
|
||||
window.initChat(window.chatContext.roomId);
|
||||
return;
|
||||
}
|
||||
|
||||
// chat.js 会在模块末尾才把 initChat 挂到 window;若这里抢先执行,稍后自动补一次初始化。
|
||||
chatWebSocketInitRetryTimer = window.setTimeout(() => {
|
||||
chatWebSocketInitRetryTimer = null;
|
||||
initChatWebSocket();
|
||||
}, 100);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 DOM 已就绪时立即执行回调,避免 Vite 模块晚于 DOMContentLoaded 执行时漏掉初始化。
|
||||
*
|
||||
* @param {() => void} callback 页面就绪后的回调
|
||||
* @returns {void}
|
||||
*/
|
||||
function runWhenDomReady(callback) {
|
||||
if (typeof callback !== "function") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", callback, { once: true });
|
||||
return;
|
||||
}
|
||||
|
||||
callback();
|
||||
}
|
||||
|
||||
// ── 禁言逻辑 ──
|
||||
@@ -203,13 +236,13 @@ function setupGomokuInviteListener() {
|
||||
const acceptBtn = isSelf
|
||||
? `<button type="button" data-gomoku-open-panel class="gomoku-invite-open"
|
||||
style="margin-left:10px; padding:3px 12px; border:1.5px solid #2d6096;
|
||||
border-radius:12px; background:#f0f6ff; color:#2d6096; font-size:12px;
|
||||
border-radius:12px; background:#f0f6ff; color:#2d6096; font-size:${GOMOKU_INVITE_BUTTON_FONT_SIZE};
|
||||
cursor:pointer; font-family:inherit; transition:all .15s;">
|
||||
⤴️ 打开面板
|
||||
</button>`
|
||||
: `<button type="button" data-gomoku-accept-id="${gomokuGameId}" id="gomoku-accept-${gomokuGameId}" class="gomoku-invite-accept"
|
||||
style="margin-left:10px; padding:3px 12px; border:1.5px solid #336699;
|
||||
border-radius:12px; background:#336699; color:#fff; font-size:12px;
|
||||
border-radius:12px; background:#336699; color:#fff; font-size:${GOMOKU_INVITE_BUTTON_FONT_SIZE};
|
||||
cursor:pointer; font-family:inherit; transition:opacity .15s;">
|
||||
⚔️ 接受挑战
|
||||
</button>`;
|
||||
@@ -277,8 +310,8 @@ export function bindChatEvents() {
|
||||
}
|
||||
chatEventsBound = true;
|
||||
|
||||
// WebSocket 初始化
|
||||
document.addEventListener("DOMContentLoaded", initChatWebSocket);
|
||||
// 页面已完成解析时立刻补做初始化,确保 Presence 连接不会因为错过 DOMContentLoaded 而丢失。
|
||||
runWhenDomReady(initChatWebSocket);
|
||||
|
||||
// chat:here — Presence 初始用户列表
|
||||
window.addEventListener("chat:here", (e) => {
|
||||
@@ -370,8 +403,8 @@ export function bindChatEvents() {
|
||||
window.showVipPresenceBanner(msg);
|
||||
}
|
||||
|
||||
// 若消息携带 toast_notification 字段且当前用户是接收者,弹右下角小卡片
|
||||
if (msg.toast_notification && msg.to_user === window.chatContext?.username) {
|
||||
// 若消息携带 toast_notification 字段且当前用户是接收者或为公屏广播或为欢迎动作,弹右下角小卡片
|
||||
if (msg.toast_notification && (msg.to_user === window.chatContext?.username || msg.to_user === '大家' || msg.action === '欢迎')) {
|
||||
const t = msg.toast_notification;
|
||||
window.chatToast?.show({
|
||||
title: t.title || "通知",
|
||||
@@ -449,16 +482,49 @@ export function bindChatEvents() {
|
||||
const target = e.detail?.target_username;
|
||||
const operator = e.detail?.operator;
|
||||
const myName = window.chatContext?.username;
|
||||
const effectOptions = {
|
||||
effect_title: e.detail?.effect_title,
|
||||
effect_user_info: e.detail?.effect_user_info,
|
||||
ride_name: e.detail?.ride_name,
|
||||
operator,
|
||||
};
|
||||
|
||||
if (type && typeof EffectManager !== "undefined") {
|
||||
if (!target || target === myName || operator === myName) {
|
||||
EffectManager.play(type);
|
||||
EffectManager.play(type, effectOptions);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Echo 级监听器(延迟绑定,等待 Echo 就绪)
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
// chat:pat — 拍一拍事件
|
||||
window.addEventListener("chat:pat", (e) => {
|
||||
const { from_user, target_user, display_text, from_user_headface } = e.detail || {};
|
||||
if (!display_text) return;
|
||||
|
||||
if (typeof window.appendPatMessage === "function") {
|
||||
window.appendPatMessage(display_text, from_user_headface, from_user, target_user);
|
||||
}
|
||||
if (typeof window.triggerPatShake === "function") {
|
||||
window.triggerPatShake();
|
||||
}
|
||||
});
|
||||
|
||||
// chat:idiom-started — 猜成语出题
|
||||
window.addEventListener("chat:idiom-started", (e) => {
|
||||
if (typeof window.handleRiddleGameStarted === "function") {
|
||||
window.handleRiddleGameStarted(e);
|
||||
}
|
||||
});
|
||||
|
||||
// chat:idiom-answered — 猜成语答题结果
|
||||
window.addEventListener("chat:idiom-answered", (e) => {
|
||||
if (typeof window.handleRiddleGameAnswered === "function") {
|
||||
window.handleRiddleGameAnswered(e);
|
||||
}
|
||||
});
|
||||
|
||||
// Echo 级监听器同样要兼容“脚本加载时页面已完成”的场景。
|
||||
runWhenDomReady(() => {
|
||||
setupScreenClearedListener();
|
||||
setupRoomBrowserRefreshListener();
|
||||
setupChangelogPublishedListener();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// 聊天室共享运行时状态,桥接 Blade 闭包作用域与 Vite 模块。
|
||||
// 所有需要跨模块共享的可变状态集中在此管理,通过 window.chatState 访问。
|
||||
|
||||
export const BLOCKABLE_SYSTEM_SENDERS = ["钓鱼播报", "星海小博士", "百家乐", "跑马", "神秘箱子"];
|
||||
export const BLOCKABLE_SYSTEM_SENDERS = ["钓鱼播报", "猜成语", "星海小博士", "百家乐", "跑马", "神秘箱子"];
|
||||
export const BLOCKED_SYSTEM_SENDERS_STORAGE_KEY = "chat_blocked_system_senders";
|
||||
export const CHAT_SOUND_MUTED_STORAGE_KEY = "chat_sound_muted";
|
||||
export const PUBLIC_MESSAGE_NODE_LIMIT = 600;
|
||||
@@ -9,7 +9,7 @@ export const PRIVATE_MESSAGE_NODE_LIMIT = 300;
|
||||
export const CHAT_MESSAGE_FLUSH_BATCH_SIZE = 8;
|
||||
export const ROOMS_ONLINE_STATUS_CACHE_TTL = 10000;
|
||||
export const HEARTBEAT_INTERVAL = 60 * 1000;
|
||||
export const SYSTEM_USERS = ["钓鱼播报", "星海小博士", "系统传音", "系统公告", "送花播报", "系统", "欢迎", "系统播报", "神秘箱子"];
|
||||
export const SYSTEM_USERS = ["钓鱼播报", "星海小博士", "系统传音", "系统公告", "送花播报", "座驾播报", "系统", "欢迎", "系统播报", "神秘箱子"];
|
||||
|
||||
// 消息动作文字映射表:情绪型(着/地,放"对"之前)和动作型(了,替换"对X说")
|
||||
export const ACTION_TEXT_MAP = {
|
||||
|
||||
@@ -177,6 +177,18 @@ async function sendMessage(e) {
|
||||
const composerState = collectChatComposerState();
|
||||
const { contentInput, submitBtn, content, contentRaw, selectedImage, toUser } = composerState;
|
||||
|
||||
// 拦截 /拍一拍 命令:使用当前选中的聊天对象
|
||||
if (content && typeof window.isPatCommand === "function" && window.isPatCommand(content)) {
|
||||
if (state) {
|
||||
state.isSending = false;
|
||||
state.sendStartedAt = 0;
|
||||
}
|
||||
if (typeof window.executePat === "function") {
|
||||
await window.executePat();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!content && !selectedImage) {
|
||||
contentInput?.focus();
|
||||
if (state) {
|
||||
|
||||
@@ -44,7 +44,7 @@ function openDialog({ message, title, color, type, defaultVal, confirmText, canc
|
||||
|
||||
header.textContent = title;
|
||||
header.style.background = color;
|
||||
messageBox.textContent = message;
|
||||
messageBox.innerText = message;
|
||||
confirmButton.style.background = color;
|
||||
confirmButton.textContent = confirmText || "确定";
|
||||
cancelButton.textContent = cancelText || "取消";
|
||||
@@ -239,4 +239,18 @@ export function bindGlobalDialogControls() {
|
||||
window.chatDialog?._cancel?.();
|
||||
}
|
||||
});
|
||||
|
||||
// 点击遮罩层(弹窗外部)关闭弹窗
|
||||
document.addEventListener("click", (event) => {
|
||||
const modal = document.getElementById("global-dialog-modal");
|
||||
if (!modal || modal.style.display === "none") return;
|
||||
if (event.target === modal) {
|
||||
// alert 模式直接隐藏,confirm/prompt 视为取消
|
||||
if (currentDialogType === "alert") {
|
||||
window.chatDialog?._hide?.();
|
||||
} else {
|
||||
window.chatDialog?._cancel?.();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ let fishToken = null;
|
||||
let autoFishing = false;
|
||||
let autoFishCooldownTimer = null;
|
||||
let autoFishCooldownCountdown = null;
|
||||
let fishingCastPending = false;
|
||||
const FISHING_MESSAGE_META_FONT_SIZE = "0.78em";
|
||||
const FISHING_MESSAGE_BODY_FONT_SIZE = "1em";
|
||||
|
||||
/**
|
||||
* 读取 CSRF Token。
|
||||
@@ -199,6 +202,25 @@ function setFishingButton(text, disabled) {
|
||||
button.disabled = disabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前是否已有进行中的钓鱼会话。
|
||||
*
|
||||
* 说明:
|
||||
* - 手动点击抛竿后,在等待浮漂、等待点击、等待自动收竿期间都视为会话未结束。
|
||||
* - 购买自动钓鱼卡后的自动接管,也必须避开这些中间态,避免重复抛竿。
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function hasActiveFishingSession() {
|
||||
return Boolean(
|
||||
fishingCastPending ||
|
||||
fishToken ||
|
||||
fishingTimer ||
|
||||
fishingReelTimeout ||
|
||||
document.getElementById("fishing-bobber"),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动自动钓鱼冷却倒计时(基于时间戳,不受浏览器后台节流影响)。
|
||||
*
|
||||
@@ -206,6 +228,8 @@ function setFishingButton(text, disabled) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function startAutoFishingCooldown(cooldown) {
|
||||
clearAutoFishingTimers();
|
||||
|
||||
const endTime = Date.now() + cooldown * 1000;
|
||||
setFishingButton(`⏳ 冷却 ${cooldown}s`, true);
|
||||
showAutoFishStopButton(cooldown);
|
||||
@@ -214,6 +238,7 @@ function startAutoFishingCooldown(cooldown) {
|
||||
autoFishCooldownCountdown = window.setInterval(() => {
|
||||
const remaining = Math.max(0, Math.ceil((endTime - Date.now()) / 1000));
|
||||
setFishingButton(`⏳ 冷却 ${remaining}s`, true);
|
||||
updateAutoFishStopButtonCountdown(remaining);
|
||||
|
||||
if (remaining <= 0) {
|
||||
window.clearInterval(autoFishCooldownCountdown);
|
||||
@@ -226,10 +251,13 @@ function startAutoFishingCooldown(cooldown) {
|
||||
const checkEnd = () => {
|
||||
if (Date.now() >= endTime) {
|
||||
autoFishCooldownTimer = null;
|
||||
hideAutoFishStopButton();
|
||||
if (autoFishing) {
|
||||
updateAutoFishStopButtonCountdown(0, "正在继续自动钓鱼");
|
||||
void startFishing();
|
||||
return;
|
||||
}
|
||||
|
||||
hideAutoFishStopButton();
|
||||
return;
|
||||
}
|
||||
autoFishCooldownTimer = window.setTimeout(checkEnd, 200);
|
||||
@@ -244,7 +272,9 @@ function startAutoFishingCooldown(cooldown) {
|
||||
* @returns {void}
|
||||
*/
|
||||
function showAutoFishStopButton(cooldown) {
|
||||
if (document.getElementById("auto-fish-stop-btn")) {
|
||||
const currentButton = document.getElementById("auto-fish-stop-btn");
|
||||
if (currentButton) {
|
||||
updateAutoFishStopButtonCountdown(cooldown);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -272,6 +302,23 @@ function showAutoFishStopButton(cooldown) {
|
||||
document.body.appendChild(button);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步更新停止自动钓鱼浮层上的冷却秒数,避免与主按钮倒计时不一致。
|
||||
*
|
||||
* @param {number} cooldown
|
||||
* @param {string|null} text
|
||||
* @returns {void}
|
||||
*/
|
||||
function updateAutoFishStopButtonCountdown(cooldown, text = null) {
|
||||
const hint = document.querySelector("#auto-fish-stop-btn .drag-hint");
|
||||
|
||||
if (!(hint instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
hint.textContent = text || `冷却 ${Number(cooldown) || 0}s · 可拖动`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 给停止自动钓鱼按钮绑定拖拽和点击停止事件。
|
||||
*
|
||||
@@ -363,6 +410,11 @@ function hideAutoFishStopButton() {
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function startFishing() {
|
||||
if (hasActiveFishingSession()) {
|
||||
return;
|
||||
}
|
||||
|
||||
fishingCastPending = true;
|
||||
setFishingButton("🎣 抛竿中...", true);
|
||||
|
||||
try {
|
||||
@@ -376,11 +428,25 @@ export async function startFishing() {
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || data.status !== "success") {
|
||||
if (autoFishing && response.status === 429) {
|
||||
// 服务端冷却 TTL 可能与前端倒计时有毫秒级误差,自动模式下按服务端剩余时间续等。
|
||||
startAutoFishingCooldown(Math.max(1, Number(data.cooldown) || 1));
|
||||
return;
|
||||
}
|
||||
|
||||
if (autoFishing && response.status === 409) {
|
||||
// 多标签页或重复自动抛竿时,后端会保留先到的 token,当前页等待后再接管。
|
||||
appendFishingMessage(`<span style="color:#d97706;">【钓鱼】${escapeHtml(data.message || "已有钓鱼正在进行,稍后自动重试。")}</span><span class="msg-time">(${timeText()})</span>`);
|
||||
startAutoFishingCooldown(Math.max(1, Number(data.retry_after) || 5));
|
||||
return;
|
||||
}
|
||||
|
||||
window.chatDialog?.alert?.(data.message || "钓鱼失败", "操作失败", "#cc4444");
|
||||
setFishingButton("🎣 钓鱼", false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 抛竿成功后进入正式钓鱼会话,由 token / timer 接管后续状态。
|
||||
fishToken = data.token;
|
||||
autoFishing = Boolean(data.auto_fishing);
|
||||
appendFishingMessage(`<span style="color:#2563eb;font-weight:bold;">🎣【钓鱼】</span>${escapeHtml(data.message)}<span class="msg-time">(${timeText()})</span>`);
|
||||
@@ -389,12 +455,21 @@ export async function startFishing() {
|
||||
const bobber = createBobber(data.bobber_x, data.bobber_y);
|
||||
document.body.appendChild(bobber);
|
||||
|
||||
if (data.auto_fishing) {
|
||||
showAutoFishStopButton(0);
|
||||
updateAutoFishStopButtonCountdown(0, "等待鱼儿上钩 · 可拖动");
|
||||
}
|
||||
|
||||
fishingTimer = window.setTimeout(() => {
|
||||
// 等待计时器触发后必须立即释放句柄,否则自动钓鱼冷却结束会误判仍有会话进行中。
|
||||
fishingTimer = null;
|
||||
bobber.classList.add("sinking");
|
||||
bobber.textContent = "🐟";
|
||||
|
||||
if (data.auto_fishing) {
|
||||
appendFishingMessage(`<span style="color:#7c3aed;font-weight:bold;">🎣 自动钓鱼卡生效!自动收竿中... <span style="font-size:10px;opacity:0.7">(剩余${Number(data.auto_fishing_minutes_left) || 0}分钟)</span></span>`);
|
||||
showAutoFishStopButton(0);
|
||||
updateAutoFishStopButtonCountdown(0, "自动收竿中 · 可拖动");
|
||||
appendFishingMessage(`<span style="color:#7c3aed;font-weight:bold;">🎣 自动钓鱼卡生效!自动收竿中... <span style="font-size:${FISHING_MESSAGE_META_FONT_SIZE};opacity:0.7">(剩余${Number(data.auto_fishing_minutes_left) || 0}分钟)</span></span>`);
|
||||
fishingReelTimeout = window.setTimeout(() => {
|
||||
removeBobber();
|
||||
void reelFish();
|
||||
@@ -402,7 +477,7 @@ export async function startFishing() {
|
||||
return;
|
||||
}
|
||||
|
||||
appendFishingMessage('<span style="color:#d97706;font-weight:bold;font-size:14px;">🐟 鱼上钩了!快点击屏幕上的浮漂!</span>');
|
||||
appendFishingMessage(`<span style="color:#d97706;font-weight:bold;font-size:${FISHING_MESSAGE_BODY_FONT_SIZE};">🐟 鱼上钩了!快点击屏幕上的浮漂!</span>`);
|
||||
setFishingButton("🎣 点击浮漂!", true);
|
||||
bobber.addEventListener("click", () => {
|
||||
removeBobber();
|
||||
@@ -426,6 +501,8 @@ export async function startFishing() {
|
||||
window.chatDialog?.alert?.(`网络错误:${error.message}`, "网络异常", "#cc4444");
|
||||
removeBobber();
|
||||
setFishingButton("🎣 钓鱼", false);
|
||||
} finally {
|
||||
fishingCastPending = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -462,7 +539,7 @@ export async function reelFish() {
|
||||
const color = Number(result.exp || 0) >= 0 ? "#16a34a" : "#dc2626";
|
||||
appendFishingMessage(
|
||||
`<span style="color:${color};font-weight:bold;">${escapeHtml(result.emoji || "🎣")}【钓鱼结果】</span>${escapeHtml(result.message || "")}` +
|
||||
` <span style="color:#666;font-size:11px;">(经验:${Number(data.exp_num) || 0} 金币:${Number(data.jjb) || 0})</span>` +
|
||||
` <span style="color:#666;font-size:${FISHING_MESSAGE_META_FONT_SIZE};">(经验:${Number(data.exp_num) || 0} 金币:${Number(data.jjb) || 0})</span>` +
|
||||
`<span class="msg-time">(${timeText()})</span>`,
|
||||
);
|
||||
|
||||
@@ -547,6 +624,7 @@ function clearAutoFishingTimers() {
|
||||
*/
|
||||
export function resetFishingBtn() {
|
||||
autoFishing = false;
|
||||
fishingCastPending = false;
|
||||
clearAutoFishingTimers();
|
||||
hideAutoFishStopButton();
|
||||
|
||||
@@ -573,7 +651,7 @@ export function checkAndAutoStartFishing() {
|
||||
const minutesLeft = Number(window.chatContext?.autoFishingMinutesLeft || 0);
|
||||
const initialCooldown = Number(window.chatContext?.fishingCooldownSeconds || 0);
|
||||
|
||||
if (minutesLeft <= 0 || autoFishing) {
|
||||
if (minutesLeft <= 0 || autoFishing || hasActiveFishingSession()) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,17 +1,70 @@
|
||||
// 聊天室字号偏好控制,保留旧的 localStorage key 以兼容已有用户设置。
|
||||
|
||||
export const CHAT_FONT_SIZE_STORAGE_KEY = "chat_font_size";
|
||||
export const CHAT_DEFAULT_FONT_SIZE = 13;
|
||||
export const CHAT_FONT_SIZE_MIN = 10;
|
||||
export const CHAT_FONT_SIZE_MAX = 30;
|
||||
let fontSizeEventsBound = false;
|
||||
|
||||
/**
|
||||
* 应用字号到聊天消息窗口,并保存到 localStorage。
|
||||
* 规整聊天室字号,过滤非法或越界的旧缓存值。
|
||||
*
|
||||
* @param {unknown} size 字号大小
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function normalizeChatFontSize(size) {
|
||||
const px = Number.parseInt(String(size ?? ""), 10);
|
||||
|
||||
if (Number.isNaN(px) || px < CHAT_FONT_SIZE_MIN || px > CHAT_FONT_SIZE_MAX) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return px;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步底部输入框上方工具按钮字号。
|
||||
*
|
||||
* @param {number} px 用户选择的聊天字号
|
||||
* @returns {void}
|
||||
*/
|
||||
function applyInputToolbarFontSize(px) {
|
||||
const toolbarRow = document.querySelector("#chat-form > .input-row");
|
||||
if (!(toolbarRow instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const toolbarFontSize = Math.max(1, px - 1);
|
||||
const fontSize = `${toolbarFontSize}px`;
|
||||
toolbarRow.style.fontSize = fontSize;
|
||||
toolbarRow.style.fontFamily = "inherit";
|
||||
toolbarRow.style.lineHeight = "1.2";
|
||||
toolbarRow.querySelectorAll([
|
||||
":scope > label",
|
||||
":scope > label select",
|
||||
":scope > label input",
|
||||
":scope > button",
|
||||
":scope > div > button",
|
||||
"#feature-menu button",
|
||||
"#admin-menu button",
|
||||
].join(",")).forEach((control) => {
|
||||
control.style.fontFamily = "inherit";
|
||||
control.style.fontSize = "inherit";
|
||||
control.style.lineHeight = "1.2";
|
||||
control.style.fontWeight = "400";
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用字号到聊天消息窗口和输入栏工具按钮,并保存到 localStorage。
|
||||
*
|
||||
* @param {string|number} size 字号大小
|
||||
* @param {{syncContext?:boolean}} options 同步选项
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function applyFontSize(size) {
|
||||
const px = Number.parseInt(size, 10);
|
||||
if (Number.isNaN(px) || px < 10 || px > 30) {
|
||||
export function applyFontSize(size, options = {}) {
|
||||
const px = normalizeChatFontSize(size);
|
||||
if (px === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -23,8 +76,15 @@ export function applyFontSize(size) {
|
||||
if (privateContainer) {
|
||||
privateContainer.style.fontSize = `${px}px`;
|
||||
}
|
||||
applyInputToolbarFontSize(px);
|
||||
|
||||
localStorage.setItem(CHAT_FONT_SIZE_STORAGE_KEY, String(px));
|
||||
if (options.syncContext !== false && window.chatContext && typeof window.chatContext === "object") {
|
||||
window.chatContext.chatPreferences = {
|
||||
...(window.chatContext.chatPreferences || {}),
|
||||
font_size: px,
|
||||
};
|
||||
}
|
||||
|
||||
const selector = document.getElementById("font_size_select");
|
||||
if (selector) {
|
||||
@@ -35,14 +95,16 @@ export function applyFontSize(size) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 localStorage 恢复已保存的聊天室字号。
|
||||
* 从账号偏好或 localStorage 恢复已保存的聊天室字号。
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function restoreChatFontSize() {
|
||||
const saved = localStorage.getItem(CHAT_FONT_SIZE_STORAGE_KEY);
|
||||
const serverFontSize = normalizeChatFontSize(window.chatContext?.chatPreferences?.font_size);
|
||||
const localFontSize = normalizeChatFontSize(localStorage.getItem(CHAT_FONT_SIZE_STORAGE_KEY));
|
||||
const saved = serverFontSize ?? localFontSize ?? CHAT_DEFAULT_FONT_SIZE;
|
||||
|
||||
return saved ? applyFontSize(saved) : false;
|
||||
return applyFontSize(saved, { syncContext: serverFontSize !== null });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,6 +123,8 @@ export function bindChatFontSizeControl() {
|
||||
return;
|
||||
}
|
||||
|
||||
applyFontSize(event.target.value);
|
||||
if (applyFontSize(event.target.value)) {
|
||||
void window.saveChatPreferences?.();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ function playEntryEffect(initialState) {
|
||||
}
|
||||
|
||||
window.setTimeout(() => {
|
||||
window.EffectManager?.play?.(initialState.entryEffect);
|
||||
window.EffectManager?.play?.(initialState.entryEffect, initialState.entryEffectOptions || {});
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,13 @@
|
||||
// 从 Blade 内联脚本 scripts.blade.php 迁移至 Vite 模块。
|
||||
|
||||
import { escapeHtml, normalizeSafeChatUrl } from "./html.js";
|
||||
import {
|
||||
attachIdiomAnswerButton,
|
||||
buildQuizActivityTitle,
|
||||
disableIdiomAnswerButtons,
|
||||
isQuizStartMessage,
|
||||
normalizeQuizRoundPayload,
|
||||
} from "./riddle-quiz.js";
|
||||
import { isExpiredChatImageMessage } from "./message-utils.js";
|
||||
import { normalizeDailyStatus, resolveBlockedSystemSenderKey } from "./preferences-status.js";
|
||||
import { escapePresenceText } from "./vip-presence.js";
|
||||
@@ -16,6 +23,14 @@ import {
|
||||
|
||||
// ── 游戏标签判断 ──
|
||||
const GAME_LABEL_PREFIXES = ["五子棋", "双色球", "钓鱼", "老虎机", "百家乐", "赛马"];
|
||||
const CHAT_NOTICE_CHIP_FONT_SIZE = "0.82em";
|
||||
const CHAT_NOTICE_META_FONT_SIZE = "0.72em";
|
||||
const CHAT_NOTICE_BUTTON_FONT_SIZE = "0.82em";
|
||||
const CHAT_NOTICE_BODY_FONT_SIZE = "1em";
|
||||
const CHAT_NOTICE_ICON_FONT_SIZE = "1.08em";
|
||||
const CHAT_NOTICE_LARGE_ICON_FONT_SIZE = "1.35em";
|
||||
const CHAT_NOTICE_DECOR_ICON_FONT_SIZE = "4.25em";
|
||||
|
||||
function isGameLabel(name) {
|
||||
if (GAME_LABEL_PREFIXES.some((p) => name.startsWith(p))) return true;
|
||||
if (name.includes(" ")) return true;
|
||||
@@ -49,6 +64,461 @@ function parseBracketUsers(content, color = "#000099") {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建统一的猜谜活动标题与题型标签。
|
||||
*/
|
||||
function buildGameLabelChipHtml(label, accentColor) {
|
||||
return `<span style="display:inline-flex;align-items:center;padding:2px 9px;border-radius:999px;background:${accentColor};color:#fff;font-size:${CHAT_NOTICE_CHIP_FONT_SIZE};font-weight:700;line-height:1;border:1px solid ${accentColor};">${escapeHtml(label)}</span>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前是否为礼包发放公告。
|
||||
*/
|
||||
function isRedPacketAnnouncementMessage(msg) {
|
||||
const content = String(msg?.content || "");
|
||||
|
||||
return String(msg?.from_user || "") === "系统公告"
|
||||
&& content.includes("发出了一个")
|
||||
&& content.includes("礼包")
|
||||
&& content.includes("立即抢包");
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建礼包发放公告的紧凑卡片,整体比例对齐猜谜活动。
|
||||
*/
|
||||
function buildRedPacketAnnouncementHtml(msg, timeStr) {
|
||||
const rawContent = String(msg?.content || "");
|
||||
const isExpPacket = rawContent.includes("经验的礼包");
|
||||
const colorPalette = isExpPacket
|
||||
? {
|
||||
accent: "#16a34a",
|
||||
text: "#166534",
|
||||
softBackground: "linear-gradient(135deg,#f0fdf4,#f7fee7)",
|
||||
softBorder: "rgba(22,163,74,.18)",
|
||||
chipBackground: "#dcfce7",
|
||||
chipBorder: "#86efac",
|
||||
chipText: "#15803d",
|
||||
}
|
||||
: {
|
||||
accent: "#dc2626",
|
||||
text: "#b91c1c",
|
||||
softBackground: "linear-gradient(135deg,#fef2f2,#fff7ed)",
|
||||
softBorder: "rgba(220,38,38,.18)",
|
||||
chipBackground: "#fee2e2",
|
||||
chipBorder: "#fca5a5",
|
||||
chipText: "#dc2626",
|
||||
};
|
||||
const accentColor = colorPalette.accent;
|
||||
const typeLabel = isExpPacket ? "经验礼包" : "金币礼包";
|
||||
const icon = isExpPacket ? "✨" : "🧧";
|
||||
const buttonMatch = rawContent.match(/<button\b([^>]*)>([\s\S]*?)<\/button>/iu);
|
||||
const buttonLabel = String(buttonMatch?.[2] || "立即抢包").trim();
|
||||
const onclickMatch = String(buttonMatch?.[1] || "").match(/\bonclick=(["'])([\s\S]*?)\1/iu);
|
||||
const buttonOnclick = onclickMatch ? onclickMatch[2] : "";
|
||||
|
||||
const textOnlyContent = rawContent
|
||||
.replace(/<button\b[\s\S]*?<\/button>/giu, "")
|
||||
.replace(/<\/?b>/giu, "")
|
||||
.replace(/^🧧\s*/u, "")
|
||||
.trim();
|
||||
|
||||
const summary = escapeHtml(textOnlyContent);
|
||||
const actionButtonHtml = `<button type="button"${buttonOnclick ? ` onclick="${escapeHtml(buttonOnclick)}"` : ""} style="display:inline-flex;align-items:center;padding:2px 9px;border-radius:999px;background:${accentColor};color:#fff;font-size:${CHAT_NOTICE_BUTTON_FONT_SIZE};font-weight:700;line-height:1;border:1px solid ${accentColor};cursor:pointer;box-shadow:none;vertical-align:middle;">${escapeHtml(buttonLabel)}</button>`;
|
||||
|
||||
return `
|
||||
<div style="display:flex;align-items:center;gap:7px;padding:5px 9px;border-radius:11px;background:${colorPalette.softBackground};border:1px solid ${colorPalette.softBorder};box-shadow:0 4px 12px rgba(15,23,42,.045);overflow:hidden;">
|
||||
<div style="width:23px;height:23px;border-radius:7px;background:${accentColor};display:flex;align-items:center;justify-content:center;color:#fff;font-size:${CHAT_NOTICE_ICON_FONT_SIZE};box-shadow:0 2px 6px ${colorPalette.softBorder};flex-shrink:0;">${icon}</div>
|
||||
<div style="min-width:0;flex:1;display:flex;align-items:center;gap:7px;flex-wrap:wrap;color:${colorPalette.text};">
|
||||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;flex-shrink:0;">
|
||||
${buildGameLabelChipHtml("礼包红包", accentColor)}
|
||||
<span style="display:inline-flex;align-items:center;padding:2px 9px;border-radius:999px;background:${colorPalette.chipBackground};color:${colorPalette.chipText};font-size:${CHAT_NOTICE_CHIP_FONT_SIZE};font-weight:700;line-height:1;border:1px solid ${colorPalette.chipBorder};">${escapeHtml(typeLabel)}</span>
|
||||
</div>
|
||||
<div style="display:flex;align-items:center;gap:5px;flex-wrap:wrap;font-size:${CHAT_NOTICE_BODY_FONT_SIZE};line-height:1.25;font-weight:700;min-width:200px;flex:1;">
|
||||
<span>${summary}</span>
|
||||
<span class="msg-time" style="font-size:${CHAT_NOTICE_META_FONT_SIZE};color:#94a3b8;">(${timeStr})</span>
|
||||
${actionButtonHtml}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建统一的猜谜活动标题与题型标签。
|
||||
*/
|
||||
function buildQuizBadgeHtml(msg, accentColor = "#7c3aed") {
|
||||
const { activityLabel, typeLabel } = buildQuizActivityTitle(msg);
|
||||
|
||||
return `
|
||||
<span style="display:inline-flex;align-items:center;gap:6px;flex-wrap:wrap;">
|
||||
${buildGameLabelChipHtml(activityLabel, accentColor)}
|
||||
<span style="display:inline-flex;align-items:center;padding:2px 9px;border-radius:999px;background:${accentColor}1A;color:${accentColor};font-size:${CHAT_NOTICE_CHIP_FONT_SIZE};font-weight:700;line-height:1;border:1px solid ${accentColor}33;">${escapeHtml(typeLabel)}</span>
|
||||
</span>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前公屏消息是否属于“我自己”的钓鱼结果广播。
|
||||
*
|
||||
* 说明:
|
||||
* - 收竿后,钓鱼者本人已经会在包厢窗口收到本地结果提示;
|
||||
* - 这里需要把同一条公屏广播对本人隐藏,避免自己同时看到两条。
|
||||
*/
|
||||
function isOwnFishingResultBroadcast(msg) {
|
||||
const currentUsername = String(window.chatContext?.username || "").trim();
|
||||
const fishingUsername = String(msg?.fishing_username || "").trim();
|
||||
|
||||
if (!currentUsername) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return String(msg?.from_user || "") === "钓鱼播报"
|
||||
&& String(msg?.action || "") === "fishing_result"
|
||||
&& fishingUsername === currentUsername;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前消息是否应该使用统一的游戏通知卡片。
|
||||
*/
|
||||
function resolveGameNotificationCardMeta(msg) {
|
||||
const normalizedContent = String(msg?.content || "");
|
||||
const fromUser = String(msg?.from_user || "");
|
||||
|
||||
if (
|
||||
normalizedContent.includes("【百家乐】")
|
||||
|| (normalizedContent.includes("开局:") && normalizedContent.includes("点收割"))
|
||||
|| (normalizedContent.startsWith("🎲") && normalizedContent.includes("点"))
|
||||
|| (normalizedContent.includes("快速参与") && normalizedContent.includes("1:24"))
|
||||
) {
|
||||
return {
|
||||
label: "百家乐",
|
||||
icon: "🎲",
|
||||
accent: "#2563eb",
|
||||
background: "linear-gradient(135deg,#eff6ff,#f8fbff)",
|
||||
border: "rgba(37,99,235,.16)",
|
||||
text: "#1e3a8a",
|
||||
chipBg: "#dbeafe",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedContent.includes("【赛马】")
|
||||
|| normalizedContent.startsWith("🐎 开赛:")
|
||||
|| normalizedContent.startsWith("🏇 比赛开始:")
|
||||
|| normalizedContent.startsWith("🏆 冠军:")
|
||||
|| /^🐎\s*第\s*#?\d+\s*场开赛/u.test(normalizedContent)
|
||||
|| /^🏇\s*第\s*#?\d+\s*场比赛开始/u.test(normalizedContent)
|
||||
|| /^🏆\s*第\s*#?\d+\s*场结束/u.test(normalizedContent)
|
||||
) {
|
||||
return {
|
||||
label: "赛马",
|
||||
icon: "🏇",
|
||||
accent: "#0f766e",
|
||||
background: "linear-gradient(135deg,#ecfeff,#f0fdfa)",
|
||||
border: "rgba(15,118,110,.16)",
|
||||
text: "#115e59",
|
||||
chipBg: "#ccfbf1",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedContent.includes("神秘箱子")
|
||||
|| (normalizedContent.includes("暗号") && normalizedContent.includes("《"))
|
||||
|| normalizedContent.includes("抢到")
|
||||
|| normalizedContent.includes("箱子消失")
|
||||
) {
|
||||
return {
|
||||
label: "神秘箱子",
|
||||
icon: "📦",
|
||||
accent: "#7c3aed",
|
||||
background: "linear-gradient(135deg,#faf5ff,#fdf4ff)",
|
||||
border: "rgba(124,58,237,.16)",
|
||||
text: "#6b21a8",
|
||||
chipBg: "#ede9fe",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
normalizedContent.includes("双色球")
|
||||
|| /购买\s+\d+\s*期/u.test(normalizedContent)
|
||||
|| /\d+\s*期:\s*🔴/u.test(normalizedContent)
|
||||
|| normalizedContent.includes("超级期")
|
||||
) {
|
||||
return {
|
||||
label: "双色球彩票",
|
||||
icon: "🎟️",
|
||||
accent: "#dc2626",
|
||||
background: "linear-gradient(135deg,#fef2f2,#fff7ed)",
|
||||
border: "rgba(220,38,38,.16)",
|
||||
text: "#991b1b",
|
||||
chipBg: "#fee2e2",
|
||||
};
|
||||
}
|
||||
|
||||
if (normalizedContent.includes("【五子棋】")) {
|
||||
return {
|
||||
label: "五子棋",
|
||||
icon: "♟️",
|
||||
accent: "#475569",
|
||||
background: "linear-gradient(135deg,#f8fafc,#f1f5f9)",
|
||||
border: "rgba(71,85,105,.16)",
|
||||
text: "#334155",
|
||||
chipBg: "#e2e8f0",
|
||||
};
|
||||
}
|
||||
|
||||
if (normalizedContent.includes("老虎机")) {
|
||||
return {
|
||||
label: "老虎机",
|
||||
icon: "🎰",
|
||||
accent: "#d97706",
|
||||
background: "linear-gradient(135deg,#fff7ed,#fffbeb)",
|
||||
border: "rgba(217,119,6,.16)",
|
||||
text: "#9a3412",
|
||||
chipBg: "#fed7aa",
|
||||
};
|
||||
}
|
||||
|
||||
if (fromUser === "钓鱼播报") {
|
||||
return {
|
||||
label: "钓鱼",
|
||||
icon: "🎣",
|
||||
accent: "#059669",
|
||||
background: "linear-gradient(135deg,#ecfdf5,#f0fdf4)",
|
||||
border: "rgba(5,150,105,.16)",
|
||||
text: "#065f46",
|
||||
chipBg: "#a7f3d0",
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提炼系统传音卡片正文,去掉和标签重复的前缀。
|
||||
*/
|
||||
function extractSystemGameCardSummary(content, meta) {
|
||||
const normalizedContent = String(content || "").trim();
|
||||
|
||||
if (!meta) {
|
||||
return normalizedContent;
|
||||
}
|
||||
|
||||
if (meta.label === "神秘箱子") {
|
||||
return normalizedContent
|
||||
.replace(/^[📦💎☠️]\s*/u, "")
|
||||
.replace(/^【神秘箱子】/u, "")
|
||||
.replace(/^开箱播报[::]\s*/u, "")
|
||||
.trim();
|
||||
}
|
||||
|
||||
if (meta.label === "百家乐") {
|
||||
if (normalizedContent.includes("开局:")) {
|
||||
return normalizedContent
|
||||
.replace(/^[🎲]+\s*/u, "")
|
||||
.replace(/【百家乐】/u, "")
|
||||
.replace(/\s+/gu, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
if (/第\s*#?\d+\s*局开奖/u.test(normalizedContent)) {
|
||||
return normalizedContent
|
||||
.replace(/^[🎲🎉]+\s*/u, "")
|
||||
.replace(/^【百家乐】/u, "")
|
||||
.replace(/\s+/gu, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
return normalizedContent
|
||||
.replace(/^[🎲🎉]+\s*/u, "")
|
||||
.replace(/^【百家乐】/u, "")
|
||||
.replace(/\s+/gu, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
if (meta.label === "赛马") {
|
||||
return normalizedContent
|
||||
.replace(/^[🐎🏇🏆]+\s*/u, "")
|
||||
.replace(/^【赛马】/u, "")
|
||||
.trim();
|
||||
}
|
||||
|
||||
if (meta.label === "双色球彩票") {
|
||||
return normalizedContent
|
||||
.replace(/^[🎟️🎊]+\s*/u, "")
|
||||
.replace(/^【双色球[^】]*】/u, "")
|
||||
.trim();
|
||||
}
|
||||
|
||||
if (meta.label === "五子棋") {
|
||||
return normalizedContent
|
||||
.replace(/^[♟️🏆]+\s*/u, "")
|
||||
.replace(/^【五子棋】/u, "")
|
||||
.replace(/^玩家对战结果!/u, "对战结果:")
|
||||
.replace(/^棋神降临!/u, "人机获胜:")
|
||||
.replace(/^AI 大获全胜!/u, "AI获胜:")
|
||||
.trim();
|
||||
}
|
||||
|
||||
if (meta.label === "老虎机") {
|
||||
return normalizedContent
|
||||
.replace(/^[🎰🎉]+\s*/u, "")
|
||||
.replace(/^【老虎机大奖】/u, "大奖:")
|
||||
.trim();
|
||||
}
|
||||
|
||||
return normalizedContent;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一系统游戏卡片中的内嵌按钮样式,避免不同游戏沿用旧尺寸。
|
||||
*/
|
||||
function normalizeSystemGameCardActions(content, meta) {
|
||||
const normalizedContent = String(content || "");
|
||||
|
||||
return normalizedContent.replace(/<button\b([^>]*)>([\s\S]*?)<\/button>/giu, (_match, attributes, label) => {
|
||||
const onclickMatch = String(attributes || "").match(/\bonclick=(["'])([\s\S]*?)\1/iu);
|
||||
const onclickAttr = onclickMatch ? ` onclick="${escapeHtml(onclickMatch[2])}"` : "";
|
||||
const safeLabel = String(label || "").trim();
|
||||
|
||||
return `<button type="button"${onclickAttr} style="display:inline-flex;align-items:center;padding:2px 9px;border-radius:999px;background:#fff;color:${meta.accent};font-size:${CHAT_NOTICE_BUTTON_FONT_SIZE};font-weight:700;line-height:1;border:1px solid ${meta.accent};cursor:pointer;box-shadow:none;vertical-align:middle;">${safeLabel}</button>`;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 将系统传音中的游戏通知渲染为和猜谜活动同级的紧凑卡片。
|
||||
*/
|
||||
function buildSystemGameNotificationHtml(msg, timeStr) {
|
||||
const content = String(msg.content || "");
|
||||
const meta = resolveGameNotificationCardMeta(msg);
|
||||
if (!meta) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const summary = normalizeSystemGameCardActions(extractSystemGameCardSummary(content, meta), meta);
|
||||
|
||||
return `
|
||||
<div style="display:flex;align-items:center;gap:7px;padding:5px 9px;border-radius:11px;background:${meta.background};border:1px solid ${meta.border};box-shadow:0 4px 12px rgba(15,23,42,.045);overflow:hidden;">
|
||||
<div style="width:23px;height:23px;border-radius:7px;background:${meta.accent};display:flex;align-items:center;justify-content:center;color:#fff;font-size:${CHAT_NOTICE_ICON_FONT_SIZE};box-shadow:0 2px 6px ${meta.border};flex-shrink:0;">${meta.icon}</div>
|
||||
<div style="min-width:0;flex:1;display:flex;align-items:center;gap:7px;flex-wrap:wrap;color:${meta.text};">
|
||||
${buildGameLabelChipHtml(meta.label, meta.accent)}
|
||||
<div style="display:flex;align-items:center;gap:5px;flex-wrap:wrap;font-size:${CHAT_NOTICE_BODY_FONT_SIZE};line-height:1.25;font-weight:700;min-width:200px;flex:1;">
|
||||
<span>${parseBracketUsers(summary, meta.text)}</span>
|
||||
<span class="msg-time" style="font-size:${CHAT_NOTICE_META_FONT_SIZE};color:#94a3b8;font-weight:600;">(${timeStr})</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 猜谜活动开题消息统一渲染为卡片。
|
||||
*/
|
||||
function buildQuizStartHtml(msg, timeStr) {
|
||||
const quizMeta = normalizeQuizRoundPayload(msg);
|
||||
const rawHint = String(quizMeta.hint || msg.content || "")
|
||||
.replace(/^🧩\s*/, "")
|
||||
.replace(/^📣\s*/, "")
|
||||
.replace(/^【[^】]+】\s*第\s*#?\d+\s*题开始!?\s*题面:\s*/u, "")
|
||||
.replace(/^【[^】]+】\s*/u, "")
|
||||
.replace(/^第\s*#?\d+\s*题开始!?\s*题面:\s*/u, "")
|
||||
.replace(/^题面:\s*/u, "")
|
||||
.trim();
|
||||
const safeHint = escapeHtml(rawHint);
|
||||
|
||||
return `
|
||||
<div style="display:flex;align-items:center;gap:7px;padding:5px 9px;border-radius:11px;background:linear-gradient(135deg,#f5f3ff,#faf5ff);border:1px solid rgba(124,58,237,.16);box-shadow:0 4px 12px rgba(124,58,237,.07);overflow:hidden;">
|
||||
<div style="width:23px;height:23px;border-radius:7px;background:linear-gradient(135deg,#7c3aed,#a78bfa);display:flex;align-items:center;justify-content:center;color:#fff;font-size:${CHAT_NOTICE_ICON_FONT_SIZE};box-shadow:0 2px 6px rgba(124,58,237,.16);flex-shrink:0;">🧩</div>
|
||||
<div style="min-width:0;flex:1;display:flex;align-items:center;gap:7px;flex-wrap:wrap;color:#312e81;">
|
||||
<div style="display:flex;align-items:center;gap:7px;flex-wrap:wrap;flex-shrink:0;">${buildQuizBadgeHtml(msg)}</div>
|
||||
<div data-quiz-inline-text style="display:flex;align-items:center;gap:5px;flex-wrap:wrap;font-size:${CHAT_NOTICE_BODY_FONT_SIZE};line-height:1.25;font-weight:700;min-width:200px;flex:1;">
|
||||
<span>${safeHint}</span>
|
||||
<span class="msg-time" style="font-size:${CHAT_NOTICE_META_FONT_SIZE};color:#94a3b8;">(${timeStr})</span>
|
||||
<span data-quiz-inline-action-anchor></span>
|
||||
</div>
|
||||
<div style="display:flex;align-items:center;gap:5px;flex-wrap:wrap;color:#6d28d9;font-size:${CHAT_NOTICE_META_FONT_SIZE};flex-shrink:0;margin-left:auto;">
|
||||
<span style="padding:1px 6px;border-radius:999px;background:#ffffff;box-shadow:inset 0 0 0 1px rgba(124,58,237,.10);white-space:nowrap;">💰 ${quizMeta.rewardGold} 金币</span>
|
||||
<span style="padding:1px 6px;border-radius:999px;background:#ffffff;box-shadow:inset 0 0 0 1px rgba(124,58,237,.10);white-space:nowrap;">⭐ ${quizMeta.rewardExp} 经验</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取猜谜活动结束消息里的正确答案,兼容中奖与超时文案。
|
||||
*/
|
||||
function resolveQuizResultAnswerText(msg) {
|
||||
const quizMeta = normalizeQuizRoundPayload(msg);
|
||||
const explicitAnswer = String(quizMeta.answer || "").trim();
|
||||
if (explicitAnswer) {
|
||||
return explicitAnswer;
|
||||
}
|
||||
|
||||
const content = String(msg.content || "");
|
||||
const matchedAnswer = content.match(/正确答案:(.+?)(?:!|。|$)/u);
|
||||
|
||||
return matchedAnswer?.[1]?.trim() || content.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 猜谜活动结束消息统一渲染为和开题通知同级的紧凑卡片。
|
||||
*/
|
||||
function buildQuizResultHtml(msg, timeStr) {
|
||||
const quizMeta = normalizeQuizRoundPayload(msg);
|
||||
const winnerUsername = String(msg.winner_username || "").trim();
|
||||
const answerText = escapeHtml(resolveQuizResultAnswerText(msg));
|
||||
const isAnsweredResult = winnerUsername !== "";
|
||||
const accentColor = isAnsweredResult ? "#7c3aed" : "#d97706";
|
||||
const accentBackground = isAnsweredResult
|
||||
? "linear-gradient(135deg,#f5f3ff,#faf5ff)"
|
||||
: "linear-gradient(135deg,#fff7ed,#fffbeb)";
|
||||
const accentBorder = isAnsweredResult ? "rgba(124,58,237,.16)" : "rgba(217,119,6,.18)";
|
||||
const textColor = isAnsweredResult ? "#312e81" : "#9a3412";
|
||||
const icon = isAnsweredResult ? "🎉" : "⏳";
|
||||
const iconBackground = isAnsweredResult
|
||||
? "linear-gradient(135deg,#7c3aed,#a78bfa)"
|
||||
: "linear-gradient(135deg,#f59e0b,#f97316)";
|
||||
const badgeColor = isAnsweredResult ? "#7c3aed" : "#d97706";
|
||||
const summaryHtml = isAnsweredResult
|
||||
? `【${clickableUser(winnerUsername, "#6d28d9")}】率先答对「${answerText}」`
|
||||
: `第 #${quizMeta.endedRoundId || quizMeta.roundId || 0} 题已超时结束,正确答案:${answerText}`;
|
||||
|
||||
return `
|
||||
<div style="display:flex;align-items:center;gap:7px;padding:5px 9px;border-radius:11px;background:${accentBackground};border:1px solid ${accentBorder};box-shadow:0 4px 12px rgba(15,23,42,.045);overflow:hidden;">
|
||||
<div style="width:23px;height:23px;border-radius:7px;background:${iconBackground};display:flex;align-items:center;justify-content:center;color:#fff;font-size:${CHAT_NOTICE_ICON_FONT_SIZE};box-shadow:0 2px 6px ${accentBorder};flex-shrink:0;">${icon}</div>
|
||||
<div style="min-width:0;flex:1;display:flex;align-items:center;gap:7px;flex-wrap:wrap;color:${textColor};">
|
||||
<div style="display:flex;align-items:center;gap:7px;flex-wrap:wrap;flex-shrink:0;">${buildQuizBadgeHtml(msg, badgeColor)}</div>
|
||||
<div style="display:flex;align-items:center;gap:5px;flex-wrap:wrap;font-size:${CHAT_NOTICE_BODY_FONT_SIZE};line-height:1.25;font-weight:700;min-width:200px;flex:1;">
|
||||
<span>${summaryHtml}</span>
|
||||
<span class="msg-time" style="font-size:${CHAT_NOTICE_META_FONT_SIZE};color:#94a3b8;">(${timeStr})</span>
|
||||
</div>
|
||||
${isAnsweredResult ? `
|
||||
<div style="display:flex;align-items:center;gap:5px;flex-wrap:wrap;color:${textColor};font-size:${CHAT_NOTICE_META_FONT_SIZE};flex-shrink:0;margin-left:auto;">
|
||||
<span style="padding:1px 6px;border-radius:999px;background:#ffffff;box-shadow:inset 0 0 0 1px ${isAnsweredResult ? "rgba(124,58,237,.10)" : "rgba(217,119,6,.12)"};white-space:nowrap;">💰 ${quizMeta.rewardGold} 金币</span>
|
||||
<span style="padding:1px 6px;border-radius:999px;background:#ffffff;box-shadow:inset 0 0 0 1px ${isAnsweredResult ? "rgba(124,58,237,.10)" : "rgba(217,119,6,.12)"};white-space:nowrap;">⭐ ${quizMeta.rewardExp} 经验</span>
|
||||
</div>
|
||||
` : ""}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 只保留包厢窗口最近几条猜成语答题记录,避免答题历史无限堆积。
|
||||
*/
|
||||
function prunePrivateIdiomResultMessages(targetContainer, maxRecords = 3) {
|
||||
if (!targetContainer) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nodes = Array.from(targetContainer.querySelectorAll('[data-idiom-result="1"]'));
|
||||
while (nodes.length > maxRecords) {
|
||||
const firstNode = nodes.shift();
|
||||
firstNode?.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建聊天消息的内容 HTML。
|
||||
*/
|
||||
@@ -84,7 +554,7 @@ export function buildChatMessageContent(msg, fontColor, textColorClass) {
|
||||
|
||||
return `
|
||||
<span style="display:inline-flex; align-items:center; gap:6px; vertical-align:middle;">
|
||||
<span style="display:inline-flex; align-items:center; padding:4px 8px; border:1px dashed #94a3b8; border-radius:999px; background:#f8fafc; color:#64748b; font-size:12px;">🖼️ 图片已过期</span>
|
||||
<span style="display:inline-flex; align-items:center; padding:4px 8px; border:1px dashed #94a3b8; border-radius:999px; background:#f8fafc; color:#64748b; font-size:${CHAT_NOTICE_BUTTON_FONT_SIZE};">🖼️ 图片已过期</span>
|
||||
${captionHtml}
|
||||
</span>
|
||||
`;
|
||||
@@ -105,17 +575,42 @@ export function appendMessage(msg, renderBatch = null) {
|
||||
|
||||
state.trackMaxMsgId(msg.id || 0);
|
||||
|
||||
if (isOwnFishingResultBroadcast(msg)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const quizMeta = normalizeQuizRoundPayload(msg);
|
||||
const idiomRoundId = quizMeta.roundId;
|
||||
const isIdiomStartMessage = isQuizStartMessage(msg)
|
||||
&& ["星海小博士", "系统传音"].includes(String(msg.from_user || ""));
|
||||
|
||||
if (isIdiomStartMessage) {
|
||||
const existingIdiomNode = document.querySelector(`[data-idiom-round-id="${idiomRoundId}"]`);
|
||||
if (existingIdiomNode) {
|
||||
attachIdiomAnswerButton(existingIdiomNode, msg);
|
||||
return existingIdiomNode;
|
||||
}
|
||||
}
|
||||
|
||||
const isMe = msg.from_user === window.chatContext?.username;
|
||||
// 系统播报屏蔽只作用于公屏窗口;自己相关消息仍要进入包厢窗口,避免屏蔽误伤个人提示。
|
||||
const isIdiomWinnerHistory = msg.action === "idiom_result" && msg.winner_username === window.chatContext?.username;
|
||||
const isRelatedToMe = isMe || msg.is_secret || msg.to_user === window.chatContext?.username || isIdiomWinnerHistory;
|
||||
const fontColor = msg.font_color || "#000000";
|
||||
const blockRuleKey = resolveBlockedSystemSenderKey(msg);
|
||||
const shouldHideByBlock = blockRuleKey ? state.blockedSystemSenders.has(blockRuleKey) : false;
|
||||
const shouldApplyBlockRule = Boolean(blockRuleKey && !isRelatedToMe);
|
||||
const shouldHideByBlock = shouldApplyBlockRule ? state.blockedSystemSenders.has(blockRuleKey) : false;
|
||||
|
||||
const div = document.createElement("div");
|
||||
div.className = "msg-line";
|
||||
if (msg?.from_user) {
|
||||
div.dataset.fromUser = msg.from_user;
|
||||
}
|
||||
if (blockRuleKey) {
|
||||
if (idiomRoundId > 0) {
|
||||
div.dataset.idiomRoundId = String(idiomRoundId);
|
||||
div.dataset.quizRoundId = String(idiomRoundId);
|
||||
}
|
||||
if (shouldApplyBlockRule) {
|
||||
div.dataset.blockKey = blockRuleKey;
|
||||
}
|
||||
|
||||
@@ -172,6 +667,15 @@ export function appendMessage(msg, renderBatch = null) {
|
||||
const iconImg = `<img src="/images/bugle.png" style="display:inline;width:16px;height:16px;vertical-align:middle;margin-right:2px;mix-blend-mode: multiply;" onerror="this.src='/images/headface/1.gif'">`;
|
||||
const parsedContent = parseBracketUsers(msg.content);
|
||||
html = `${iconImg} ${parsedContent}`;
|
||||
} else if (msg.action === "idiom_result") {
|
||||
div.dataset.idiomResult = "1";
|
||||
div.dataset.quizRoundEndedId = String(quizMeta.endedRoundId || quizMeta.roundId || 0);
|
||||
div.dataset.quizWinnerUsername = String(msg.winner_username || "");
|
||||
html = buildQuizResultHtml(msg, timeStr);
|
||||
timeStrOverride = true;
|
||||
} else if (isIdiomStartMessage) {
|
||||
html = buildQuizStartHtml(msg, timeStr);
|
||||
timeStrOverride = true;
|
||||
} else if (msg.action === "vip_presence") {
|
||||
const accent = msg.presence_color || "#f59e0b";
|
||||
div.style.cssText =
|
||||
@@ -186,16 +690,16 @@ export function appendMessage(msg, renderBatch = null) {
|
||||
|
||||
html = `
|
||||
<div style="display:flex;align-items:center;gap:12px;">
|
||||
<div style="width:48px;height:48px;border-radius:14px;background:linear-gradient(135deg, ${accent}, #fbbf24);display:flex;align-items:center;justify-content:center;font-size:24px;box-shadow: 0 4px 12px ${accent}44; flex-shrink: 0;">${icon}</div>
|
||||
<div style="width:48px;height:48px;border-radius:14px;background:linear-gradient(135deg, ${accent}, #fbbf24);display:flex;align-items:center;justify-content:center;font-size:${CHAT_NOTICE_LARGE_ICON_FONT_SIZE};box-shadow: 0 4px 12px ${accent}44; flex-shrink: 0;">${icon}</div>
|
||||
<div style="min-width:0;flex:1;">
|
||||
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
|
||||
<span style="font-size:13px;font-weight:900;letter-spacing:.05em;color:${accent}; text-shadow: 0.5px 0.5px 0px rgba(0,0,0,0.05);">${typeLabel}</span>
|
||||
<span style="font-size:13px;color:#475569;font-weight:bold;">${levelName}</span>
|
||||
<span style="font-size:11px;color:#94a3b8;">(${timeStr})</span>
|
||||
<span style="font-size:${CHAT_NOTICE_CHIP_FONT_SIZE};font-weight:900;letter-spacing:.05em;color:${accent}; text-shadow: 0.5px 0.5px 0px rgba(0,0,0,0.05);">${typeLabel}</span>
|
||||
<span style="font-size:${CHAT_NOTICE_CHIP_FONT_SIZE};color:#475569;font-weight:bold;">${levelName}</span>
|
||||
<span style="font-size:${CHAT_NOTICE_META_FONT_SIZE};color:#94a3b8;">(${timeStr})</span>
|
||||
</div>
|
||||
<div style="margin-top:4px;font-size:15px;line-height:1.6;color:#1e293b;font-weight:500;">${safeText}</div>
|
||||
<div style="margin-top:4px;font-size:${CHAT_NOTICE_BODY_FONT_SIZE};line-height:1.6;color:#1e293b;font-weight:500;">${safeText}</div>
|
||||
</div>
|
||||
<div style="position:absolute; right:-10px; bottom:-10px; font-size:60px; opacity:0.05; transform:rotate(-15deg); pointer-events:none;">${icon}</div>
|
||||
<div style="position:absolute; right:-10px; bottom:-10px; font-size:${CHAT_NOTICE_DECOR_ICON_FONT_SIZE}; opacity:0.05; transform:rotate(-15deg); pointer-events:none;">${icon}</div>
|
||||
</div>
|
||||
`;
|
||||
timeStrOverride = true;
|
||||
@@ -220,32 +724,55 @@ export function appendMessage(msg, renderBatch = null) {
|
||||
}
|
||||
}
|
||||
const parsedBody = parseBracketUsers(bodyPart, "#1d4ed8");
|
||||
html = `<div style="color: #1e40af;">💬 ${clickablePrefix}${parsedBody} <span style="color: #93c5fd; font-size: 11px; font-weight: normal;">(${timeStr})</span></div>`;
|
||||
html = `<div style="color: #1e40af;">💬 ${clickablePrefix}${parsedBody} <span style="color: #93c5fd; font-size: ${CHAT_NOTICE_META_FONT_SIZE}; font-weight: normal;">(${timeStr})</span></div>`;
|
||||
timeStrOverride = true;
|
||||
} else if (SYSTEM_USERS.includes(msg.from_user)) {
|
||||
if (msg.from_user === "系统公告") {
|
||||
div.style.cssText =
|
||||
"background: linear-gradient(135deg, #fef2f2, #fff1f2); border: 2px solid #ef4444; border-radius: 8px; padding: 10px 14px; margin: 6px 0; box-shadow: 0 3px 8px rgba(239,68,68,0.16);";
|
||||
const parsedContent = parseBracketUsers(msg.content, "#dc2626");
|
||||
html = `<div style="font-size: 18px; line-height: 1.75; font-weight: 800; color: #dc2626;">${parsedContent} <span style="color: #999; font-size: 14px; font-weight: 500;">(${timeStr})</span></div>`;
|
||||
timeStrOverride = true;
|
||||
if (isRedPacketAnnouncementMessage(msg)) {
|
||||
html = buildRedPacketAnnouncementHtml(msg, timeStr);
|
||||
timeStrOverride = true;
|
||||
} else {
|
||||
div.style.cssText =
|
||||
"background: linear-gradient(135deg, #fef2f2, #fff1f2); border: 2px solid #ef4444; border-radius: 8px; padding: 10px 14px; margin: 6px 0; box-shadow: 0 3px 8px rgba(239,68,68,0.16);";
|
||||
const parsedContent = parseBracketUsers(msg.content, "#dc2626");
|
||||
html = `<div style="font-size: ${CHAT_NOTICE_BODY_FONT_SIZE}; line-height: 1.75; font-weight: 800; color: #dc2626;">${parsedContent} <span style="color: #999; font-size: ${CHAT_NOTICE_META_FONT_SIZE}; font-weight: 500;">(${timeStr})</span></div>`;
|
||||
timeStrOverride = true;
|
||||
}
|
||||
} else if (msg.from_user === "系统传音") {
|
||||
const content = msg.content || "";
|
||||
const isRedPacketClaimNotification = content.includes("抢到了") && content.includes("礼包");
|
||||
const isBaccaratLossCoverNotification = content.includes("【你玩游戏我买单】") || content.includes("金币补偿");
|
||||
const isDailySignInNotification = content.includes("完成今日签到") || content.includes("使用补签卡补签");
|
||||
const isPlainNotification =
|
||||
content.includes("【百家乐】") ||
|
||||
content.includes("【赛马】") ||
|
||||
content.includes("神秘箱子") ||
|
||||
content.includes("【双色球") ||
|
||||
content.includes("【五子棋】") ||
|
||||
content.includes("【老虎机】") ||
|
||||
content.includes("购买了");
|
||||
const isQuizEndNotification = content.includes("猜谜活动") && (content.includes("已超时结束") || content.includes("正确答案"));
|
||||
const isQuizStartNotification = !isQuizEndNotification && (isIdiomStartMessage || content.includes("猜谜活动") || content.includes("猜成语时间"));
|
||||
const systemGameCardMeta = resolveGameNotificationCardMeta(msg);
|
||||
const isPlainNotification = content.includes("购买了");
|
||||
|
||||
if (isRedPacketClaimNotification || isBaccaratLossCoverNotification || isDailySignInNotification) {
|
||||
if (isQuizEndNotification) {
|
||||
html = buildQuizResultHtml(msg, timeStr);
|
||||
timeStrOverride = true;
|
||||
} else if (isQuizStartNotification) {
|
||||
div.style.cssText =
|
||||
"background:linear-gradient(135deg,#fff7ed,#fffbeb);border:1px solid rgba(245,158,11,.28);border-left:4px solid #f59e0b;border-radius:12px;padding:8px 12px;margin:4px 0;box-shadow:0 10px 24px rgba(245,158,11,.14);";
|
||||
html = `
|
||||
<div style="display:flex;align-items:flex-start;gap:10px;">
|
||||
<div style="width:38px;height:38px;border-radius:12px;background:linear-gradient(135deg,#f59e0b,#f97316);display:flex;align-items:center;justify-content:center;color:#fff;font-size:${CHAT_NOTICE_LARGE_ICON_FONT_SIZE};box-shadow:0 8px 18px rgba(249,115,22,.22);flex-shrink:0;">📣</div>
|
||||
<div style="min-width:0;flex:1;">
|
||||
<div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
|
||||
${buildQuizBadgeHtml(msg, "#d97706")}
|
||||
<span class="msg-time">(${timeStr})</span>
|
||||
</div>
|
||||
<div style="margin-top:7px;color:#9a3412;font-size:${CHAT_NOTICE_BODY_FONT_SIZE};font-weight:800;line-height:1.75;">${parseBracketUsers(content, "#b45309")}</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
timeStrOverride = true;
|
||||
} else if (isRedPacketClaimNotification || isBaccaratLossCoverNotification || isDailySignInNotification) {
|
||||
let plainAccentContent = parseBracketUsers(msg.content);
|
||||
html = `<span style="color: #b45309;">🌟 ${plainAccentContent}</span>`;
|
||||
} else if (systemGameCardMeta) {
|
||||
html = buildSystemGameNotificationHtml(msg, timeStr);
|
||||
timeStrOverride = true;
|
||||
} else if (isPlainNotification) {
|
||||
let parsedContent = parseBracketUsers(msg.content);
|
||||
html = `${headImg}<span style="font-weight: bold;">${clickableUser(msg.from_user, fontColor, nameClass)}:</span><span class="msg-content${textColorClass}" style="color: ${fontColor}; font-weight: bold;">${parsedContent}</span>`;
|
||||
@@ -255,6 +782,9 @@ export function appendMessage(msg, renderBatch = null) {
|
||||
let sysTranContent = parseBracketUsers(msg.content);
|
||||
html = `<span style="color: #b45309;">🌟 ${sysTranContent}</span>`;
|
||||
}
|
||||
} else if (resolveGameNotificationCardMeta(msg)) {
|
||||
html = buildSystemGameNotificationHtml(msg, timeStr);
|
||||
timeStrOverride = true;
|
||||
} else if (msg.from_user === "系统" && msg.to_user && msg.to_user !== "大家") {
|
||||
div.style.cssText =
|
||||
"background:#f0fdf4;border-left:3px solid #16a34a;border-radius:4px;padding:3px 8px;margin:2px 0;";
|
||||
@@ -270,7 +800,7 @@ export function appendMessage(msg, renderBatch = null) {
|
||||
} else if (msg.is_secret) {
|
||||
if (msg.from_user === "系统") {
|
||||
div.style.cssText =
|
||||
"background:#f0fdf4;border-left:3px solid #16a34a;border-radius:4px;padding:3px 8px;margin:2px 0;font-size:12px;";
|
||||
"background:#f0fdf4;border-left:3px solid #16a34a;border-radius:4px;padding:3px 8px;margin:2px 0;";
|
||||
html = `<span style="color:#16a34a;font-weight:bold;">📢 系统:</span><span style="color:#15803d;">${msg.content}</span>`;
|
||||
} else {
|
||||
const fromHtml = clickableUser(msg.from_user, "#cc00cc", nameClass);
|
||||
@@ -300,6 +830,12 @@ export function appendMessage(msg, renderBatch = null) {
|
||||
html += ` <span class="msg-time">(${timeStr})</span>`;
|
||||
}
|
||||
div.innerHTML = html;
|
||||
attachIdiomAnswerButton(div, msg);
|
||||
|
||||
// 历史消息恢复或实时结算时,都立即把对应回合按钮置为结束态,保留消息结构便于回看。
|
||||
if (quizMeta.endedRoundId > 0) {
|
||||
disableIdiomAnswerButtons(quizMeta.endedRoundId, "本回合已结束", String(msg.winner_username || ""));
|
||||
}
|
||||
|
||||
// 命中屏蔽规则时,消息仍保留在 DOM 中,便于取消屏蔽后立即恢复显示。
|
||||
if (shouldHideByBlock) {
|
||||
@@ -324,9 +860,6 @@ export function appendMessage(msg, renderBatch = null) {
|
||||
removeSameWelcome(renderBatch?.privateFragment);
|
||||
}
|
||||
|
||||
// 路由规则:公众窗口(say1) — 别人的公聊消息;包厢窗口(say2) — 自己发的 + 悄悄话 + 对自己说的
|
||||
const isRelatedToMe = isMe || msg.is_secret || msg.to_user === window.chatContext?.username;
|
||||
|
||||
// 存点通知标记
|
||||
const isAutoSave = (msg.from_user === "系统" || msg.from_user === "") &&
|
||||
msg.content && (msg.content.includes("自动存点") || msg.content.includes("手动存点"));
|
||||
@@ -343,12 +876,18 @@ export function appendMessage(msg, renderBatch = null) {
|
||||
renderBatch.privateFragment.appendChild(div);
|
||||
renderBatch.shouldPrunePrivate = true;
|
||||
renderBatch.shouldScrollPrivate = renderBatch.shouldScrollPrivate || state.autoScroll;
|
||||
if (msg.action === "idiom_result") {
|
||||
renderBatch.shouldPrunePrivateIdiomResults = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const container2 = state.container2;
|
||||
if (container2) {
|
||||
container2.appendChild(div);
|
||||
pruneMessageContainer(container2, PRIVATE_MESSAGE_NODE_LIMIT);
|
||||
if (msg.action === "idiom_result") {
|
||||
prunePrivateIdiomResultMessages(container2, 3);
|
||||
}
|
||||
if (state.autoScroll) {
|
||||
container2.scrollTop = container2.scrollHeight;
|
||||
}
|
||||
@@ -398,6 +937,7 @@ export function createChatMessageRenderBatch() {
|
||||
privateFragment: document.createDocumentFragment(),
|
||||
shouldPrunePublic: false,
|
||||
shouldPrunePrivate: false,
|
||||
shouldPrunePrivateIdiomResults: false,
|
||||
shouldScrollPublic: false,
|
||||
shouldScrollPrivate: false,
|
||||
};
|
||||
@@ -429,6 +969,10 @@ export function commitChatMessageRenderBatch(renderBatch) {
|
||||
const container2 = state.container2;
|
||||
if (container2) pruneMessageContainer(container2, PRIVATE_MESSAGE_NODE_LIMIT);
|
||||
}
|
||||
if (renderBatch.shouldPrunePrivateIdiomResults) {
|
||||
const container2 = state.container2;
|
||||
if (container2) prunePrivateIdiomResultMessages(container2, 3);
|
||||
}
|
||||
if (renderBatch.shouldScrollPublic) {
|
||||
const container = state.container;
|
||||
if (container) container.scrollTop = container.scrollHeight;
|
||||
@@ -523,7 +1067,7 @@ export function flushQueuedChatMessages() {
|
||||
const notice = document.createElement("div");
|
||||
notice.className = "msg-line msg-burst-notice";
|
||||
notice.style.cssText =
|
||||
"text-align:center;padding:6px 0;margin:4px 0;font-size:12px;color:#94a3b8;border-top:1px dashed #d1d5db;border-bottom:1px dashed #d1d5db;";
|
||||
`text-align:center;padding:6px 0;margin:4px 0;font-size:${CHAT_NOTICE_META_FONT_SIZE};color:#94a3b8;border-top:1px dashed #d1d5db;border-bottom:1px dashed #d1d5db;`;
|
||||
notice.textContent = `⏫ 省略了 ${dropped} 条系统通知`;
|
||||
container.appendChild(notice);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
// 拍一拍功能模块
|
||||
// 拦截输入框中的 /拍一拍 命令,向所选对象发送拍一拍通知并触发屏幕抖动。
|
||||
|
||||
import { pruneMessageContainer } from "./message-renderer.js";
|
||||
|
||||
function csrf() {
|
||||
return document.querySelector('meta[name="csrf-token"]')?.content ?? "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断输入是否为 /拍一拍 命令。
|
||||
*/
|
||||
function isPatCommand(text) {
|
||||
return /^\/拍一拍\s*$/.test(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前选中的聊天对象。
|
||||
*/
|
||||
function getSelectedTarget() {
|
||||
const toUserSelect = document.getElementById("to_user");
|
||||
if (!toUserSelect) return null;
|
||||
const val = toUserSelect.value?.trim();
|
||||
return val || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行拍一拍请求。
|
||||
*/
|
||||
async function executePat() {
|
||||
const targetUser = getSelectedTarget();
|
||||
if (!targetUser || targetUser === "大家") {
|
||||
window.chatDialog?.alert("请先选择一个聊天对象(不能为大家),再进行拍一拍。", "拍一拍", "#f472b6");
|
||||
return false;
|
||||
}
|
||||
|
||||
const roomId = window.chatContext?.roomId;
|
||||
if (!roomId) return false;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/room/${roomId}/pat`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"X-CSRF-TOKEN": csrf(),
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ target_user: targetUser }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.status === "success") {
|
||||
// 清空输入并触发本机抖动
|
||||
const contentInput = document.getElementById("content");
|
||||
if (contentInput) {
|
||||
contentInput.value = "";
|
||||
if (typeof window.persistChatDraft === "function") {
|
||||
window.persistChatDraft("");
|
||||
}
|
||||
contentInput.focus();
|
||||
}
|
||||
triggerPatShake();
|
||||
return true;
|
||||
}
|
||||
|
||||
window.chatDialog?.alert(data.message || "拍一拍失败", "拍一拍", "#f472b6");
|
||||
return false;
|
||||
} catch (error) {
|
||||
console.error("拍一拍请求失败:", error);
|
||||
window.chatDialog?.alert("网络错误,拍一拍发送失败。", "拍一拍", "#f472b6");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 触发屏幕抖动动画。
|
||||
*/
|
||||
function triggerPatShake() {
|
||||
const layout = document.querySelector(".chat-layout");
|
||||
if (!layout) return;
|
||||
|
||||
layout.classList.remove("chat-shake");
|
||||
// 强制回流后重新添加动画
|
||||
void layout.offsetWidth;
|
||||
layout.classList.add("chat-shake");
|
||||
|
||||
// 动画结束后移除 class
|
||||
setTimeout(() => {
|
||||
layout.classList.remove("chat-shake");
|
||||
}, 500);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加拍一拍消息到聊天窗口(使用正常聊天样式渲染)。
|
||||
*/
|
||||
function appendPatMessage(displayText, fromUserHeadface, fromUser, targetUser) {
|
||||
const state = window.chatState;
|
||||
const container = state?.container;
|
||||
if (!container) return;
|
||||
|
||||
const now = new Date();
|
||||
const timeStr = now.getHours().toString().padStart(2, "0") + ":" +
|
||||
now.getMinutes().toString().padStart(2, "0") + ":" +
|
||||
now.getSeconds().toString().padStart(2, "0");
|
||||
|
||||
const fromUserSafe = fromUser || "";
|
||||
const targetUserSafe = targetUser || "";
|
||||
|
||||
// 获取发送者的在线数据,获取正确头像
|
||||
const senderInfo = state.onlineUsers[fromUserSafe];
|
||||
const senderHead = (senderInfo && senderInfo.headface) || "1.gif";
|
||||
let headImgSrc = senderHead.startsWith("storage/") ? "/" + senderHead : "/images/headface/" + senderHead;
|
||||
|
||||
const headImg = '<img src="' + headImgSrc + '" style="display:inline;width:16px;height:16px;vertical-align:middle;margin-right:2px;mix-blend-mode: multiply;" onerror="this.src=\'/images/headface/1.gif\'">';
|
||||
|
||||
// 可点击用户名(与正常消息一致)
|
||||
const fromHtml = '<span class="msg-user" data-chat-message-user data-u="' + fromUserSafe + '" style="color: #000099; cursor: pointer;">' + fromUserSafe + '</span>';
|
||||
const toHtml = '<span class="msg-user" data-chat-message-user data-u="' + targetUserSafe + '" style="color: #000099; cursor: pointer;">' + targetUserSafe + '</span>';
|
||||
|
||||
const div = document.createElement("div");
|
||||
div.className = "msg-line";
|
||||
if (fromUserSafe) {
|
||||
div.dataset.fromUser = fromUserSafe;
|
||||
}
|
||||
|
||||
div.innerHTML = headImg + fromHtml + "对" + toHtml + "说:<span class=\"msg-content\" style=\"color: #000000\">👋 我刚拍了拍你</span> <span class=\"msg-time\">(" + timeStr + ")</span>";
|
||||
|
||||
// 路由规则:发送者和被拍者在包厢看到,其他用户在公屏看到
|
||||
const currentUser = window.chatContext?.username || "";
|
||||
const isRelatedToMe = fromUser === currentUser || targetUser === currentUser;
|
||||
|
||||
if (isRelatedToMe) {
|
||||
const container2 = state?.container2;
|
||||
if (container2) {
|
||||
container2.appendChild(div);
|
||||
pruneMessageContainer(container2, 300);
|
||||
if (state?.autoScroll) {
|
||||
container2.scrollTop = container2.scrollHeight;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
container.appendChild(div);
|
||||
pruneMessageContainer(container, 600);
|
||||
if (state?.autoScroll) {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 导出 ──
|
||||
export { isPatCommand, executePat, triggerPatShake, appendPatMessage };
|
||||
|
||||
// 挂载到 window 供其他模块使用
|
||||
window.isPatCommand = isPatCommand;
|
||||
window.executePat = executePat;
|
||||
window.triggerPatShake = triggerPatShake;
|
||||
window.appendPatMessage = appendPatMessage;
|
||||
@@ -1,6 +1,8 @@
|
||||
// 聊天室偏好与每日状态工具,承接从 Blade 内联脚本迁移出的纯数据规整逻辑。
|
||||
|
||||
export const BLOCKABLE_SYSTEM_SENDERS = ["钓鱼播报", "星海小博士", "百家乐", "跑马", "神秘箱子"];
|
||||
import { CHAT_FONT_SIZE_STORAGE_KEY, normalizeChatFontSize } from "./font-size.js";
|
||||
|
||||
export const BLOCKABLE_SYSTEM_SENDERS = ["钓鱼播报", "猜成语", "星海小博士", "百家乐", "跑马", "神秘箱子", "五子棋", "老虎机", "双色球彩票"];
|
||||
export const BLOCKED_SYSTEM_SENDERS_STORAGE_KEY = "chat_blocked_system_senders";
|
||||
export const CHAT_SOUND_MUTED_STORAGE_KEY = "chat_sound_muted";
|
||||
// 白名单、localStorage key 与绑定标记共同保证偏好读取可控、事件只注册一次。
|
||||
@@ -12,7 +14,7 @@ let blockMenuEventsBound = false;
|
||||
*
|
||||
* @param {Record<string, unknown>|null|undefined} raw
|
||||
* @param {string[]} blockableSystemSenders
|
||||
* @returns {{blocked_system_senders:string[],sound_muted:boolean}}
|
||||
* @returns {{blocked_system_senders:string[],sound_muted:boolean,font_size:number|null}}
|
||||
*/
|
||||
export function normalizeChatPreferences(raw, blockableSystemSenders = BLOCKABLE_SYSTEM_SENDERS) {
|
||||
// 服务端或旧本地缓存可能包含已下架发送者,规整时只保留当前白名单。
|
||||
@@ -23,6 +25,7 @@ export function normalizeChatPreferences(raw, blockableSystemSenders = BLOCKABLE
|
||||
return {
|
||||
blocked_system_senders: Array.from(new Set(blocked)),
|
||||
sound_muted: Boolean(raw?.sound_muted),
|
||||
font_size: normalizeChatFontSize(raw?.font_size),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -454,17 +457,19 @@ export function bindBlockMenuControls() {
|
||||
/**
|
||||
* 当前登录账号没有服务端偏好时,判断是否需要迁移旧本地偏好。
|
||||
*
|
||||
* @param {{blocked_system_senders?:string[],sound_muted?:boolean}} serverPreferences
|
||||
* @param {{blocked_system_senders?:string[],sound_muted?:boolean,font_size?:number|null}} serverPreferences
|
||||
* @param {string[]} localBlockedSenders
|
||||
* @param {boolean} localMuted
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function shouldMigrateLocalChatPreferences(serverPreferences, localBlockedSenders, localMuted) {
|
||||
// 只有服务端尚无偏好时才迁移旧本地设置,避免覆盖已同步的账号配置。
|
||||
const localFontSize = normalizeChatFontSize(localStorage.getItem(CHAT_FONT_SIZE_STORAGE_KEY));
|
||||
const hasServerPreferences = (serverPreferences?.blocked_system_senders || []).length > 0
|
||||
|| Boolean(serverPreferences?.sound_muted);
|
||||
|| Boolean(serverPreferences?.sound_muted)
|
||||
|| normalizeChatFontSize(serverPreferences?.font_size) !== null;
|
||||
|
||||
return !hasServerPreferences && (localBlockedSenders.length > 0 || localMuted);
|
||||
return !hasServerPreferences && (localBlockedSenders.length > 0 || localMuted || localFontSize !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -476,6 +481,26 @@ export function shouldMigrateLocalChatPreferences(serverPreferences, localBlocke
|
||||
export function resolveBlockedSystemSenderKey(msg) {
|
||||
const fromUser = String(msg?.from_user || "");
|
||||
const content = String(msg?.content || "");
|
||||
const action = String(msg?.action || "");
|
||||
const idiomRoundId = Number.parseInt(
|
||||
String(msg?.quiz_round_id || msg?.idiom_game_round_id || msg?.idom_game_round_id || msg?.quiz_round_ended_id || msg?.idiom_game_round_ended_id || "0"),
|
||||
10,
|
||||
);
|
||||
const quizType = String(msg?.quiz_type || "");
|
||||
const quizTypeLabel = String(msg?.quiz_type_label || "");
|
||||
const isSystemBroadcast = fromUser === "系统传音" || fromUser === "系统";
|
||||
|
||||
// 猜谜活动消息独立作为一个通知类型管理,不再复用“星海小博士”的屏蔽规则。
|
||||
if (
|
||||
idiomRoundId > 0 ||
|
||||
action === "idiom_result" ||
|
||||
quizType === "idiom" ||
|
||||
quizTypeLabel.includes("成语") ||
|
||||
(fromUser === "星海小博士" && (content.includes("猜成语") || content.includes("猜谜活动"))) ||
|
||||
(isSystemBroadcast && (content.includes("猜成语") || content.includes("猜谜活动")))
|
||||
) {
|
||||
return "猜成语";
|
||||
}
|
||||
|
||||
if (fromUser === "钓鱼播报") {
|
||||
return "钓鱼播报";
|
||||
@@ -490,22 +515,68 @@ export function resolveBlockedSystemSenderKey(msg) {
|
||||
}
|
||||
|
||||
// 兼容旧版自动钓鱼卡购买通知:历史上该消息曾以"系统传音"发送,但正文里带有"钓鱼播报"字样。
|
||||
if ((fromUser === "系统传音" || fromUser === "系统") && (content.includes("钓鱼播报") || content.includes("自动钓鱼模式"))) {
|
||||
if (isSystemBroadcast && (content.includes("钓鱼播报") || content.includes("自动钓鱼模式"))) {
|
||||
return "钓鱼播报";
|
||||
}
|
||||
|
||||
if ((fromUser === "系统传音" || fromUser === "系统") && content.includes("神秘箱子")) {
|
||||
// 神秘箱子公告已精简为“《普通箱》...暗号...”等格式,不能再只依赖“神秘箱子”字样。
|
||||
if (
|
||||
isSystemBroadcast && (
|
||||
content.includes("神秘箱子") ||
|
||||
(content.includes("暗号") && content.includes("《")) ||
|
||||
content.includes("抢到普通箱") ||
|
||||
content.includes("抢到黑化箱") ||
|
||||
content.includes("抢到神秘") ||
|
||||
content.includes("箱子消失")
|
||||
)
|
||||
) {
|
||||
return "神秘箱子";
|
||||
}
|
||||
|
||||
if ((fromUser === "系统传音" || fromUser === "系统") && content.includes("百家乐")) {
|
||||
// 百家乐通知已缩短为“开局:...”“🎲 9点...”这类格式,这里同步兼容新旧文案。
|
||||
if (
|
||||
isSystemBroadcast && (
|
||||
content.includes("百家乐") ||
|
||||
(content.includes("开局:") && content.includes("点收割")) ||
|
||||
(content.startsWith("🎲") && content.includes("点")) ||
|
||||
(content.includes("快速参与") && content.includes("1:24"))
|
||||
)
|
||||
) {
|
||||
return "百家乐";
|
||||
}
|
||||
|
||||
if ((fromUser === "系统传音" || fromUser === "系统") && (content.includes("赛马") || content.includes("跑马"))) {
|
||||
// 赛马通知已缩短为“开赛:...”“比赛开始:...”“冠军:...”等格式。
|
||||
if (
|
||||
isSystemBroadcast && (
|
||||
content.includes("赛马") ||
|
||||
content.includes("跑马") ||
|
||||
content.startsWith("🐎 开赛:") ||
|
||||
content.startsWith("🏇 比赛开始:") ||
|
||||
content.startsWith("🏆 冠军:")
|
||||
)
|
||||
) {
|
||||
return "跑马";
|
||||
}
|
||||
|
||||
if (isSystemBroadcast && (content.includes("【五子棋】") || content.includes("五子棋"))) {
|
||||
return "五子棋";
|
||||
}
|
||||
|
||||
if (isSystemBroadcast && (content.includes("老虎机") || content.includes("【老虎机大奖】"))) {
|
||||
return "老虎机";
|
||||
}
|
||||
|
||||
if (
|
||||
isSystemBroadcast && (
|
||||
content.includes("双色球") ||
|
||||
/购买\s+\d+\s*期/u.test(content) ||
|
||||
/\d+\s*期:\s*🔴/u.test(content) ||
|
||||
content.includes("超级期")
|
||||
)
|
||||
) {
|
||||
return "双色球彩票";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -514,13 +585,19 @@ export function resolveBlockedSystemSenderKey(msg) {
|
||||
/**
|
||||
* 构建当前聊天室偏好快照。
|
||||
*
|
||||
* @returns {{blocked_system_senders:string[],sound_muted:boolean}}
|
||||
* @returns {{blocked_system_senders:string[],sound_muted:boolean,font_size:number|null}}
|
||||
*/
|
||||
export function buildChatPreferencesPayload() {
|
||||
const state = window.chatState;
|
||||
const selector = document.getElementById("font_size_select");
|
||||
const fontSize = normalizeChatFontSize(selector?.value)
|
||||
?? normalizeChatFontSize(localStorage.getItem(CHAT_FONT_SIZE_STORAGE_KEY))
|
||||
?? normalizeChatFontSize(window.chatContext?.chatPreferences?.font_size);
|
||||
|
||||
return {
|
||||
blocked_system_senders: state ? Array.from(state.blockedSystemSenders) : [],
|
||||
sound_muted: isSoundMuted(),
|
||||
font_size: fontSize,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -581,10 +658,14 @@ export function syncBlockedSystemSenderCheckboxes() {
|
||||
|
||||
const checkboxMap = {
|
||||
"block-sender-fishing": "钓鱼播报",
|
||||
"block-sender-idiom": "猜成语",
|
||||
"block-sender-doctor": "星海小博士",
|
||||
"block-sender-baccarat": "百家乐",
|
||||
"block-sender-horse-race": "跑马",
|
||||
"block-sender-mystery-box": "神秘箱子",
|
||||
"block-sender-gomoku": "五子棋",
|
||||
"block-sender-slot-machine": "老虎机",
|
||||
"block-sender-lottery": "双色球彩票",
|
||||
};
|
||||
|
||||
Object.entries(checkboxMap).forEach(([id, sender]) => {
|
||||
@@ -603,27 +684,28 @@ export function syncBlockedSystemSenderCheckboxes() {
|
||||
*/
|
||||
export function setRenderedMessagesVisibilityBySender(blockKey, hidden) {
|
||||
const state = window.chatState;
|
||||
[state?.container, state?.container2].forEach(targetContainer => {
|
||||
if (!targetContainer) return;
|
||||
const targetContainer = state?.container;
|
||||
|
||||
if (targetContainer) {
|
||||
targetContainer.querySelectorAll("[data-block-key]").forEach(node => {
|
||||
if (node.dataset.blockKey === blockKey) {
|
||||
if (hidden) {
|
||||
node.dataset.blockHidden = "1";
|
||||
node.style.display = "none";
|
||||
} else if (node.dataset.blockHidden === "1") {
|
||||
node.removeAttribute("data-block-hidden");
|
||||
node.style.display = "";
|
||||
}
|
||||
if (node.dataset.blockKey !== blockKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 屏蔽项只清理公屏已有播报,包厢窗口保留用户自己的钓鱼过程和结果提示。
|
||||
if (hidden) {
|
||||
node.dataset.blockHidden = "1";
|
||||
node.style.display = "none";
|
||||
} else if (node.dataset.blockHidden === "1") {
|
||||
node.removeAttribute("data-block-hidden");
|
||||
node.style.display = "";
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (!hidden && state?.autoScroll) {
|
||||
const container = state.container;
|
||||
const container2 = state.container2;
|
||||
if (container) container.scrollTop = container.scrollHeight;
|
||||
if (container2) container2.scrollTop = container2.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
// 猜谜活动前端模块
|
||||
// 监听 RiddleGameStarted / RiddleGameAnswered 事件,提供答题弹窗与刷新恢复能力。
|
||||
|
||||
function csrf() {
|
||||
return document.querySelector('meta[name="csrf-token"]')?.content ?? "";
|
||||
}
|
||||
|
||||
let currentRoundId = 0;
|
||||
let currentRoomId = 0;
|
||||
let currentQuizType = "idiom";
|
||||
const QUIZ_TYPES = ["idiom", "brain_teaser"];
|
||||
const QUIZ_INLINE_BUTTON_FONT_SIZE = "0.82em";
|
||||
const QUIZ_INLINE_META_FONT_SIZE = "0.78em";
|
||||
|
||||
/**
|
||||
* 兼容新旧字段,提取前端统一使用的猜谜活动回合信息。
|
||||
*/
|
||||
export function normalizeQuizRoundPayload(payload) {
|
||||
const source = payload && typeof payload === "object" ? payload : {};
|
||||
const quizType = String(source.quiz_type || source.idiom_type || "idiom");
|
||||
const quizTypeLabel = String(source.quiz_type_label || source.idiom_type_label || (quizType === "idiom" ? "成语题" : "谜题"));
|
||||
const roundId = Number.parseInt(
|
||||
String(source.quiz_round_id || source.idiom_game_round_id || source.idom_game_round_id || source.round_id || source.quiz_round_ended_id || source.idiom_game_round_ended_id || "0"),
|
||||
10,
|
||||
);
|
||||
const endedRoundId = Number.parseInt(
|
||||
String(source.quiz_round_ended_id || source.idiom_game_round_ended_id || "0"),
|
||||
10,
|
||||
);
|
||||
const rewardGold = Number.parseInt(
|
||||
String(source.quiz_reward_gold ?? source.idiom_reward_gold ?? source.idiom_result_reward_gold ?? source.reward_gold ?? 0),
|
||||
10,
|
||||
);
|
||||
const rewardExp = Number.parseInt(
|
||||
String(source.quiz_reward_exp ?? source.idiom_reward_exp ?? source.idiom_result_reward_exp ?? source.reward_exp ?? 0),
|
||||
10,
|
||||
);
|
||||
const hint = String(source.quiz_hint || source.hint || source.content || "");
|
||||
const answer = String(source.quiz_answer || source.idiom_answer || source.answer || "");
|
||||
|
||||
return {
|
||||
quizType,
|
||||
quizTypeLabel,
|
||||
roundId: Number.isNaN(roundId) ? 0 : roundId,
|
||||
endedRoundId: Number.isNaN(endedRoundId) ? 0 : endedRoundId,
|
||||
rewardGold: Number.isNaN(rewardGold) ? 0 : rewardGold,
|
||||
rewardExp: Number.isNaN(rewardExp) ? 0 : rewardExp,
|
||||
hint,
|
||||
answer,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一构建“猜谜活动 + 题型”展示标题。
|
||||
*/
|
||||
export function buildQuizActivityTitle(payload) {
|
||||
const quizMeta = normalizeQuizRoundPayload(payload);
|
||||
|
||||
return {
|
||||
activityLabel: "猜谜活动",
|
||||
typeLabel: quizMeta.quizTypeLabel || "谜题",
|
||||
quizType: quizMeta.quizType,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断一条消息是否属于开题消息。
|
||||
*/
|
||||
export function isQuizStartMessage(payload) {
|
||||
const quizMeta = normalizeQuizRoundPayload(payload);
|
||||
const action = String(payload?.action || "");
|
||||
|
||||
return quizMeta.roundId > 0 && quizMeta.endedRoundId <= 0 && !action;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找当前回合是否已经有对应的聊天室消息节点。
|
||||
*/
|
||||
function findIdiomRoundMessageNode(roundId) {
|
||||
if (roundId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return document.querySelector(`[data-idiom-round-id="${roundId}"]`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新后若历史消息里缺少当前进行中的开题卡片,则主动补回一条系统传音消息。
|
||||
*/
|
||||
function restoreCurrentQuizMessage(roomId, payload) {
|
||||
const quizMeta = normalizeQuizRoundPayload(payload);
|
||||
if (quizMeta.roundId <= 0 || !quizMeta.hint) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (findIdiomRoundMessageNode(quizMeta.roundId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { activityLabel, typeLabel } = buildQuizActivityTitle(payload);
|
||||
const now = new Date();
|
||||
const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")} ${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}:${String(now.getSeconds()).padStart(2, "0")}`;
|
||||
|
||||
window.appendMessage?.({
|
||||
id: `quiz-start-restore-${quizMeta.roundId}`,
|
||||
room_id: roomId,
|
||||
from_user: "系统传音",
|
||||
to_user: "大家",
|
||||
content: `🧩 【${activityLabel}|${typeLabel}】${quizMeta.hint}`,
|
||||
is_secret: false,
|
||||
font_color: "#7c3aed",
|
||||
action: "",
|
||||
quiz_type: quizMeta.quizType,
|
||||
quiz_type_label: typeLabel,
|
||||
quiz_round_id: quizMeta.roundId,
|
||||
quiz_hint: quizMeta.hint,
|
||||
quiz_reward_gold: quizMeta.rewardGold,
|
||||
quiz_reward_exp: quizMeta.rewardExp,
|
||||
idiom_game_round_id: quizMeta.roundId,
|
||||
idiom_reward_gold: quizMeta.rewardGold,
|
||||
idiom_reward_exp: quizMeta.rewardExp,
|
||||
sent_at: timeStr,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 为指定回合创建统一样式的答题按钮。
|
||||
*/
|
||||
function buildIdiomAnswerButton(roundId, hint, rewardGold, rewardExp, typeLabel, quizType = "idiom") {
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.dataset.idiomAnswerBtn = String(roundId);
|
||||
btn.dataset.quizAnswerBtn = String(roundId);
|
||||
btn.dataset.idiomHint = hint;
|
||||
btn.dataset.quizHint = hint;
|
||||
btn.dataset.idiomGold = String(rewardGold);
|
||||
btn.dataset.quizGold = String(rewardGold);
|
||||
btn.dataset.idiomExp = String(rewardExp);
|
||||
btn.dataset.quizExp = String(rewardExp);
|
||||
btn.dataset.quizTypeLabel = typeLabel;
|
||||
btn.dataset.quizType = quizType;
|
||||
btn.dataset.quizEnded = "0";
|
||||
btn.textContent = "🎯 立即答题";
|
||||
btn.style.cssText =
|
||||
"display:inline-flex;align-items:center;gap:4px;padding:2px 9px;background:linear-gradient(135deg,#7c3aed,#a78bfa);" +
|
||||
`color:#fff;border:1px solid #7c3aed;border-radius:999px;font-size:${QUIZ_INLINE_BUTTON_FONT_SIZE};cursor:pointer;` +
|
||||
"font-weight:700;line-height:1;vertical-align:middle;box-shadow:0 2px 6px rgba(124,58,237,.14);";
|
||||
|
||||
return btn;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找指定回合的所有答题按钮。
|
||||
*/
|
||||
function queryQuizAnswerButtons(roundId = 0) {
|
||||
const selector = roundId > 0
|
||||
? `[data-quiz-answer-btn="${roundId}"], [data-idiom-answer-btn="${roundId}"]`
|
||||
: "[data-quiz-answer-btn], [data-idiom-answer-btn]";
|
||||
|
||||
return Array.from(document.querySelectorAll(selector));
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取当前页面上该回合已渲染的结算消息,用于历史恢复时补挂答对人名字。
|
||||
*/
|
||||
function findQuizWinnerUsername(roundId = 0) {
|
||||
if (roundId <= 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const resultNode = document.querySelector(`[data-quiz-round-ended-id="${roundId}"]`);
|
||||
|
||||
return String(resultNode?.dataset?.quizWinnerUsername || "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理指定回合的所有答题按钮。
|
||||
*/
|
||||
export function removeIdiomAnswerButtons(roundId = 0) {
|
||||
queryQuizAnswerButtons(roundId).forEach((button) => button.remove());
|
||||
}
|
||||
|
||||
/**
|
||||
* 为结束态按钮补一个答对人标记,避免用户只看到“已结束”不知道是谁抢到了。
|
||||
*/
|
||||
function syncQuizWinnerLabel(button, winnerUsername = "") {
|
||||
if (!(button instanceof HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingLabel = button.parentElement?.querySelector(`[data-quiz-winner-label="${button.dataset.quizAnswerBtn || button.dataset.idiomAnswerBtn || ""}"]`);
|
||||
if (!winnerUsername) {
|
||||
existingLabel?.remove();
|
||||
return;
|
||||
}
|
||||
|
||||
const winnerLabel = existingLabel || document.createElement("span");
|
||||
winnerLabel.dataset.quizWinnerLabel = String(button.dataset.quizAnswerBtn || button.dataset.idiomAnswerBtn || "0");
|
||||
winnerLabel.textContent = `答对:${winnerUsername}`;
|
||||
winnerLabel.style.cssText = `margin-left:6px;font-size:${QUIZ_INLINE_META_FONT_SIZE};line-height:1.2;color:#64748b;font-weight:700;white-space:nowrap;`;
|
||||
|
||||
if (!existingLabel) {
|
||||
button.insertAdjacentElement("afterend", winnerLabel);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将指定回合的答题按钮标记为结束态,保留在历史消息中供用户回看。
|
||||
*/
|
||||
export function disableIdiomAnswerButtons(roundId = 0, endedText = "本回合已结束", winnerUsername = "") {
|
||||
queryQuizAnswerButtons(roundId).forEach((button) => {
|
||||
button.disabled = true;
|
||||
button.dataset.quizEnded = "1";
|
||||
button.style.background = "linear-gradient(135deg,#94a3b8,#cbd5e1)";
|
||||
button.style.color = "#f8fafc";
|
||||
button.style.border = "1px solid #94a3b8";
|
||||
button.style.cursor = "not-allowed";
|
||||
button.style.boxShadow = "none";
|
||||
button.style.opacity = ".92";
|
||||
button.style.padding = "2px 9px";
|
||||
button.style.fontSize = QUIZ_INLINE_BUTTON_FONT_SIZE;
|
||||
button.style.lineHeight = "1";
|
||||
button.title = endedText;
|
||||
button.textContent = "已结束";
|
||||
syncQuizWinnerLabel(button, winnerUsername);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据当前回合状态同步按钮可点击性,避免刷新后仍显示过期入口。
|
||||
*/
|
||||
function syncQuizAnswerButtons(activeRoundIds) {
|
||||
const activeIds = new Set((Array.isArray(activeRoundIds) ? activeRoundIds : [activeRoundIds]).filter((roundId) => roundId > 0));
|
||||
|
||||
queryQuizAnswerButtons().forEach((button) => {
|
||||
const buttonRoundId = Number.parseInt(String(button.dataset.quizAnswerBtn || button.dataset.idiomAnswerBtn || "0"), 10);
|
||||
if (activeIds.has(buttonRoundId)) {
|
||||
button.disabled = false;
|
||||
button.dataset.quizEnded = "0";
|
||||
button.style.background = "linear-gradient(135deg,#7c3aed,#a78bfa)";
|
||||
button.style.color = "#fff";
|
||||
button.style.border = "1px solid #7c3aed";
|
||||
button.style.cursor = "pointer";
|
||||
button.style.boxShadow = "0 2px 6px rgba(124,58,237,.14)";
|
||||
button.style.opacity = "1";
|
||||
button.style.padding = "2px 9px";
|
||||
button.style.fontSize = QUIZ_INLINE_BUTTON_FONT_SIZE;
|
||||
button.style.lineHeight = "1";
|
||||
button.title = "";
|
||||
button.textContent = "🎯 立即答题";
|
||||
syncQuizWinnerLabel(button, "");
|
||||
return;
|
||||
}
|
||||
|
||||
disableIdiomAnswerButtons(buttonRoundId);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 把答题按钮挂到对应的消息节点上,而不是盲目追加到最后一条消息。
|
||||
*/
|
||||
export function attachIdiomAnswerButton(messageNode, message) {
|
||||
if (!messageNode || !message) {
|
||||
return;
|
||||
}
|
||||
|
||||
const quizMeta = normalizeQuizRoundPayload(message);
|
||||
const roundId = quizMeta.endedRoundId || quizMeta.roundId;
|
||||
if (roundId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (quizMeta.endedRoundId > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!["星海小博士", "系统传音"].includes(String(message.from_user || ""))) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (messageNode.querySelector(`[data-quiz-answer-btn="${roundId}"], [data-idiom-answer-btn="${roundId}"]`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const button = buildIdiomAnswerButton(roundId, quizMeta.hint, quizMeta.rewardGold, quizMeta.rewardExp, quizMeta.quizTypeLabel, quizMeta.quizType);
|
||||
const inlineActionAnchor = messageNode.querySelector("[data-quiz-inline-action-anchor]");
|
||||
|
||||
if (inlineActionAnchor?.parentNode) {
|
||||
inlineActionAnchor.parentNode.insertBefore(button, inlineActionAnchor.nextSibling);
|
||||
} else {
|
||||
messageNode.appendChild(button);
|
||||
}
|
||||
|
||||
if (quizMeta.endedRoundId > 0) {
|
||||
disableIdiomAnswerButtons(roundId);
|
||||
return;
|
||||
}
|
||||
|
||||
const winnerUsername = findQuizWinnerUsername(roundId);
|
||||
if (winnerUsername) {
|
||||
disableIdiomAnswerButtons(roundId, "本回合已结束", winnerUsername);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据当前服务端回合状态,清理刷新后残留的旧答题按钮。
|
||||
*/
|
||||
async function syncCurrentIdiomRound() {
|
||||
const roomId = Number.parseInt(String(window.chatContext?.roomId || "0"), 10);
|
||||
if (roomId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentRoomId = roomId;
|
||||
|
||||
try {
|
||||
const responses = await Promise.all(QUIZ_TYPES.map(async (quizType) => {
|
||||
const response = await fetch(`/riddle-quiz/current?room_id=${roomId}&type=${encodeURIComponent(quizType)}`, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
return response.json();
|
||||
}));
|
||||
responses.forEach((data) => {
|
||||
if (data?.status === "success" && data?.data) {
|
||||
restoreCurrentQuizMessage(roomId, data.data);
|
||||
}
|
||||
});
|
||||
const activeRoundIds = responses
|
||||
.map((data) => Number.parseInt(String(data?.data?.quiz_round_id || data?.data?.round_id || "0"), 10))
|
||||
.filter((roundId) => roundId > 0);
|
||||
|
||||
currentRoundId = activeRoundIds[0] || 0;
|
||||
currentQuizType = responses.find((data) => Number.parseInt(String(data?.data?.quiz_round_id || data?.data?.round_id || "0"), 10) === currentRoundId)?.data?.quiz_type || currentQuizType;
|
||||
syncQuizAnswerButtons(activeRoundIds);
|
||||
} catch (_error) {
|
||||
// 当前回合同步失败时不打断聊天主流程,保留现有按钮状态。
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 收到猜成语出题事件时,在聊天窗口显示提示消息。
|
||||
*/
|
||||
function handleRiddleGameStarted(e) {
|
||||
const quizMeta = normalizeQuizRoundPayload(e.detail);
|
||||
const { activityLabel, typeLabel } = buildQuizActivityTitle(e.detail);
|
||||
const { roundId, hint, rewardGold, rewardExp } = quizMeta;
|
||||
const message = String(e.detail?.message || "");
|
||||
if (!roundId || !hint) return;
|
||||
|
||||
currentRoundId = roundId;
|
||||
currentRoomId = window.chatContext?.roomId || 0;
|
||||
currentQuizType = quizMeta.quizType || "idiom";
|
||||
|
||||
// 线上如果 MessageSent 补消息没有到达,这里主动补一条公屏消息兜底;
|
||||
// 本地或正常链路下若消息已存在,则只补挂答题按钮,避免重复渲染。
|
||||
const existingMessageNode = findIdiomRoundMessageNode(roundId);
|
||||
if (existingMessageNode) {
|
||||
attachIdiomAnswerButton(existingMessageNode, {
|
||||
from_user: "星海小博士",
|
||||
content: message || `🧩 【${activityLabel}|${typeLabel}】${hint}`,
|
||||
quiz_type: quizMeta.quizType,
|
||||
quiz_type_label: typeLabel,
|
||||
quiz_round_id: roundId,
|
||||
quiz_reward_gold: rewardGold,
|
||||
quiz_reward_exp: rewardExp,
|
||||
idiom_game_round_id: roundId,
|
||||
idiom_reward_gold: rewardGold,
|
||||
idiom_reward_exp: rewardExp,
|
||||
});
|
||||
console.log(`猜谜活动开始:${hint},奖励 ${rewardGold}金/${rewardExp}经验`);
|
||||
return;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")} ${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}:${String(now.getSeconds()).padStart(2, "0")}`;
|
||||
window.appendMessage?.({
|
||||
id: `quiz-start-live-${roundId}`,
|
||||
room_id: currentRoomId || window.chatContext?.roomId || 0,
|
||||
from_user: "系统传音",
|
||||
to_user: "大家",
|
||||
content: message || `🧩 【${activityLabel}|${typeLabel}】${hint}`,
|
||||
is_secret: false,
|
||||
font_color: "#7c3aed",
|
||||
action: "",
|
||||
quiz_type: quizMeta.quizType,
|
||||
quiz_type_label: typeLabel,
|
||||
quiz_round_id: roundId,
|
||||
quiz_reward_gold: rewardGold,
|
||||
quiz_reward_exp: rewardExp,
|
||||
idiom_game_round_id: roundId,
|
||||
idiom_reward_gold: rewardGold,
|
||||
idiom_reward_exp: rewardExp,
|
||||
sent_at: timeStr,
|
||||
});
|
||||
|
||||
console.log(`猜谜活动开始:${hint},奖励 ${rewardGold}金/${rewardExp}经验`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 收到猜成语结果事件。
|
||||
*/
|
||||
function handleRiddleGameAnswered(e) {
|
||||
const quizMeta = normalizeQuizRoundPayload(e.detail);
|
||||
const { activityLabel, typeLabel } = buildQuizActivityTitle(e.detail);
|
||||
const answer = quizMeta.answer;
|
||||
const winnerUsername = String(e.detail?.winner_username || "");
|
||||
const rewardGold = quizMeta.rewardGold;
|
||||
const rewardExp = quizMeta.rewardExp;
|
||||
const roundId = quizMeta.endedRoundId || quizMeta.roundId;
|
||||
if (!answer) return;
|
||||
|
||||
currentRoundId = 0;
|
||||
currentQuizType = "idiom";
|
||||
disableIdiomAnswerButtons(roundId, "本回合已结束", winnerUsername);
|
||||
|
||||
// 关闭当前用户的答题弹窗(如果开着的话)
|
||||
const answerModal = document.getElementById("idiom-answer-modal");
|
||||
if (answerModal && answerModal.style.display !== "none") {
|
||||
answerModal.style.display = "none";
|
||||
}
|
||||
|
||||
// 实时答题结果与刷新后的历史恢复统一走 appendMessage,避免两套分流逻辑跑偏。
|
||||
const now = new Date();
|
||||
const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")} ${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}:${String(now.getSeconds()).padStart(2, "0")}`;
|
||||
window.appendMessage?.({
|
||||
id: `quiz-result-live-${roundId}-${Date.now()}`,
|
||||
room_id: currentRoomId || window.chatContext?.roomId || 0,
|
||||
from_user: "系统传音",
|
||||
to_user: "大家",
|
||||
content: `🎉 【${winnerUsername}】率先答对${typeLabel}「${answer}」,获得 ${rewardGold} 金币、${rewardExp} 经验!`,
|
||||
is_secret: false,
|
||||
font_color: "#16a34a",
|
||||
action: "idiom_result",
|
||||
winner_username: winnerUsername,
|
||||
quiz_type: quizMeta.quizType,
|
||||
quiz_type_label: typeLabel,
|
||||
quiz_answer: answer,
|
||||
quiz_reward_gold: rewardGold,
|
||||
quiz_reward_exp: rewardExp,
|
||||
quiz_round_ended_id: roundId,
|
||||
idiom_answer: answer,
|
||||
idiom_result_reward_gold: rewardGold,
|
||||
idiom_result_reward_exp: rewardExp,
|
||||
idiom_game_round_ended_id: roundId,
|
||||
sent_at: timeStr,
|
||||
});
|
||||
|
||||
// ── Toast 通知(所有用户都能看到) ──
|
||||
window.chatToast?.show({
|
||||
title: `🧩 ${activityLabel} · ${typeLabel}`,
|
||||
message: `<b>${winnerUsername}</b> 答对了「${answer}」,获得 ${rewardGold}💰 + ${rewardExp}⭐!`,
|
||||
icon: "🎉",
|
||||
color: "#16a34a",
|
||||
duration: 6000,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开答题弹窗。
|
||||
*/
|
||||
function openIdiomAnswerModal(roundId, hint, rewardGold, rewardExp, typeLabel = "成语题", quizType = "idiom") {
|
||||
currentRoundId = roundId;
|
||||
currentRoomId = window.chatContext?.roomId || 0;
|
||||
currentQuizType = quizType || "idiom";
|
||||
|
||||
const modal = document.getElementById("idiom-answer-modal");
|
||||
if (!modal) return;
|
||||
|
||||
const hintEl = document.getElementById("idiom-answer-hint");
|
||||
const rewardEl = document.getElementById("idiom-answer-reward");
|
||||
const typeEl = document.getElementById("idiom-answer-type");
|
||||
if (hintEl) hintEl.textContent = hint;
|
||||
if (rewardEl) rewardEl.textContent = `🎁 答对奖励:${rewardGold} 金币 + ${rewardExp} 经验`;
|
||||
if (typeEl) typeEl.textContent = typeLabel;
|
||||
|
||||
modal.style.display = "flex";
|
||||
|
||||
const input = document.getElementById("idiom-answer-input");
|
||||
if (input) {
|
||||
input.value = "";
|
||||
input.focus();
|
||||
input.disabled = false;
|
||||
}
|
||||
|
||||
const submitBtn = document.getElementById("idiom-answer-submit");
|
||||
if (submitBtn) {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = "提交答案";
|
||||
}
|
||||
|
||||
const feedbackEl = document.getElementById("idiom-answer-feedback");
|
||||
if (feedbackEl) feedbackEl.textContent = "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭答题弹窗。
|
||||
*/
|
||||
function closeIdiomAnswerModal() {
|
||||
const modal = document.getElementById("idiom-answer-modal");
|
||||
if (modal) modal.style.display = "none";
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交答案。
|
||||
*/
|
||||
async function submitIdiomAnswer() {
|
||||
const input = document.getElementById("idiom-answer-input");
|
||||
const feedbackEl = document.getElementById("idiom-answer-feedback");
|
||||
const submitBtn = document.getElementById("idiom-answer-submit");
|
||||
|
||||
if (!input || !feedbackEl || !submitBtn) return;
|
||||
|
||||
const answer = input.value.trim();
|
||||
if (!answer) {
|
||||
feedbackEl.textContent = "请输入答案";
|
||||
feedbackEl.style.color = "#ef4444";
|
||||
return;
|
||||
}
|
||||
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = "提交中...";
|
||||
|
||||
try {
|
||||
const response = await fetch("/riddle-quiz/answer", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"X-CSRF-TOKEN": csrf(),
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
round_id: currentRoundId,
|
||||
answer: answer,
|
||||
room_id: currentRoomId,
|
||||
quiz_type: currentQuizType,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.status === "success") {
|
||||
feedbackEl.textContent = data.message || "🎉 回答正确!";
|
||||
feedbackEl.style.color = "#16a34a";
|
||||
input.disabled = true;
|
||||
disableIdiomAnswerButtons(
|
||||
currentRoundId,
|
||||
"本回合已结束",
|
||||
String(window.chatContext?.username || ""),
|
||||
);
|
||||
|
||||
// 延迟关闭弹窗
|
||||
setTimeout(() => {
|
||||
closeIdiomAnswerModal();
|
||||
}, 2000);
|
||||
} else {
|
||||
feedbackEl.textContent = data.message || "答案不正确";
|
||||
feedbackEl.style.color = "#ef4444";
|
||||
if ((data.message || "").includes("已结束") || (data.message || "").includes("抢先答对") || (data.message || "").includes("超时")) {
|
||||
disableIdiomAnswerButtons(currentRoundId, data.message || "本回合已结束");
|
||||
}
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = "提交答案";
|
||||
input.focus();
|
||||
input.select();
|
||||
}
|
||||
} catch (error) {
|
||||
feedbackEl.textContent = "网络错误,请稍后重试";
|
||||
feedbackEl.style.color = "#ef4444";
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = "提交答案";
|
||||
}
|
||||
}
|
||||
|
||||
// ── 事件绑定 ──
|
||||
|
||||
export function bindIdiomQuizControls() {
|
||||
// 已经绑定的不再重复绑定
|
||||
if (document.getElementById("idiom-answer-modal")?.dataset?.idiomBound) return;
|
||||
const modal = document.getElementById("idiom-answer-modal");
|
||||
if (modal) modal.dataset.idiomBound = "1";
|
||||
|
||||
// 关闭按钮
|
||||
document.addEventListener("click", (e) => {
|
||||
const closeBtn = e.target.closest("[data-idiom-answer-close]");
|
||||
if (closeBtn) {
|
||||
closeIdiomAnswerModal();
|
||||
return;
|
||||
}
|
||||
|
||||
// 点击遮罩层关闭
|
||||
const overlay = e.target.closest("#idiom-answer-modal");
|
||||
if (overlay && e.target === overlay) {
|
||||
closeIdiomAnswerModal();
|
||||
}
|
||||
});
|
||||
|
||||
// 提交按钮
|
||||
document.addEventListener("click", (e) => {
|
||||
const submitBtn = e.target.closest("[data-idiom-answer-submit]");
|
||||
if (submitBtn) {
|
||||
e.preventDefault();
|
||||
submitIdiomAnswer();
|
||||
}
|
||||
});
|
||||
|
||||
// 输入框 Enter 提交
|
||||
document.addEventListener("keydown", (e) => {
|
||||
const input = e.target.closest("#idiom-answer-input");
|
||||
if (input && e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
submitIdiomAnswer();
|
||||
}
|
||||
});
|
||||
|
||||
// 聊天消息中的【答题】按钮点击
|
||||
document.addEventListener("click", (e) => {
|
||||
const btn = e.target.closest("[data-idiom-answer-btn]");
|
||||
if (!btn) return;
|
||||
|
||||
if (btn instanceof HTMLButtonElement && (btn.disabled || btn.dataset.quizEnded === "1")) {
|
||||
return;
|
||||
}
|
||||
|
||||
const roundId = parseInt(btn.dataset.quizAnswerBtn || btn.dataset.idiomAnswerBtn || "0", 10);
|
||||
const hint = btn.dataset.quizHint || btn.dataset.idiomHint || "";
|
||||
const rewardGold = parseInt(btn.dataset.quizGold || btn.dataset.idiomGold || "0", 10);
|
||||
const rewardExp = parseInt(btn.dataset.quizExp || btn.dataset.idiomExp || "0", 10);
|
||||
const typeLabel = btn.dataset.quizTypeLabel || "成语题";
|
||||
currentQuizType = btn.dataset.quizType || (typeLabel === "脑筋急转弯" ? "brain_teaser" : "idiom");
|
||||
|
||||
if (roundId > 0) {
|
||||
openIdiomAnswerModal(roundId, hint, rewardGold, rewardExp, typeLabel, currentQuizType);
|
||||
}
|
||||
});
|
||||
|
||||
// ── 猜成语结果消息中的用户名可点击 → 打开用户名片
|
||||
// 注:单击/双击已由 right-panel.js 的全局 [data-chat-message-user] 事件委托统一处理
|
||||
|
||||
window.setTimeout(() => {
|
||||
syncCurrentIdiomRound();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// ── 挂载到 window ──
|
||||
window.openIdiomAnswerModal = openIdiomAnswerModal;
|
||||
window.closeIdiomAnswerModal = closeIdiomAnswerModal;
|
||||
window.submitIdiomAnswer = submitIdiomAnswer;
|
||||
window.handleRiddleGameStarted = handleRiddleGameStarted;
|
||||
window.handleRiddleGameAnswered = handleRiddleGameAnswered;
|
||||
@@ -0,0 +1,346 @@
|
||||
// 聊天室座驾弹窗模块,负责座驾列表、购买、当前座驾和购买记录展示。
|
||||
|
||||
import { escapeHtml } from "./html.js";
|
||||
|
||||
const DEFAULT_RIDE_ITEMS_URL = "/rides/items";
|
||||
const DEFAULT_RIDE_BUY_URL = "/rides/buy";
|
||||
|
||||
let rideEventsBound = false;
|
||||
let rideLoaded = false;
|
||||
let rideState = {
|
||||
items: [],
|
||||
currentRide: null,
|
||||
purchases: [],
|
||||
};
|
||||
|
||||
/**
|
||||
* 读取座驾弹窗接口地址配置。
|
||||
*
|
||||
* @returns {{items:string,buy:string}}
|
||||
*/
|
||||
function rideUrls() {
|
||||
const modal = document.getElementById("ride-modal");
|
||||
|
||||
return {
|
||||
items: modal?.dataset.rideItemsUrl || DEFAULT_RIDE_ITEMS_URL,
|
||||
buy: modal?.dataset.rideBuyUrl || DEFAULT_RIDE_BUY_URL,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取 CSRF Token。
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function csrf() {
|
||||
return document.querySelector('meta[name="csrf-token"]')?.content || "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取座驾接口请求头。
|
||||
*
|
||||
* @param {boolean} withJson 是否携带 JSON Content-Type
|
||||
* @returns {Record<string, string>}
|
||||
*/
|
||||
function rideHeaders(withJson = false) {
|
||||
const headers = {
|
||||
"X-CSRF-TOKEN": csrf(),
|
||||
"Accept": "application/json",
|
||||
};
|
||||
|
||||
if (withJson) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开座驾弹窗并首次加载数据。
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
export function openRideModal() {
|
||||
const modal = document.getElementById("ride-modal");
|
||||
if (!modal) {
|
||||
return;
|
||||
}
|
||||
|
||||
modal.style.display = "flex";
|
||||
if (!rideLoaded) {
|
||||
rideLoaded = true;
|
||||
void loadRides();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭座驾弹窗。
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
export function closeRideModal() {
|
||||
const modal = document.getElementById("ride-modal");
|
||||
if (modal) {
|
||||
modal.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 拉取座驾页面数据。
|
||||
*
|
||||
* @returns {Promise<Record<string, any>>}
|
||||
*/
|
||||
export async function fetchRideData() {
|
||||
const response = await fetch(rideUrls().items, {
|
||||
headers: rideHeaders(),
|
||||
credentials: "same-origin",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("座驾数据加载失败");
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载并渲染座驾页面。
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function loadRides() {
|
||||
const list = document.getElementById("ride-items-list");
|
||||
if (list) {
|
||||
list.innerHTML = '<div class="ride-empty">加载中...</div>';
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await fetchRideData();
|
||||
rideState = {
|
||||
items: Array.isArray(data.items) ? data.items : [],
|
||||
currentRide: data.current_ride || null,
|
||||
purchases: Array.isArray(data.purchases) ? data.purchases : [],
|
||||
};
|
||||
renderRides(data);
|
||||
} catch (error) {
|
||||
if (list) {
|
||||
list.innerHTML = '<div class="ride-empty ride-error">加载失败,请稍后重试</div>';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染座驾弹窗全部内容。
|
||||
*
|
||||
* @param {Record<string, any>} data 接口返回数据
|
||||
* @returns {void}
|
||||
*/
|
||||
export function renderRides(data) {
|
||||
const balance = document.getElementById("ride-jjb");
|
||||
if (balance) {
|
||||
balance.textContent = Number(data.user_jjb || data.jjb || 0).toLocaleString();
|
||||
}
|
||||
|
||||
renderCurrentRide(data.current_ride || null);
|
||||
renderRideItems(Array.isArray(data.items) ? data.items : rideState.items);
|
||||
renderRidePurchases(Array.isArray(data.purchases) ? data.purchases : rideState.purchases);
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染当前激活座驾。
|
||||
*
|
||||
* @param {Record<string, any>|null} currentRide 当前座驾记录
|
||||
* @returns {void}
|
||||
*/
|
||||
function renderCurrentRide(currentRide) {
|
||||
const box = document.getElementById("ride-current");
|
||||
if (!box) {
|
||||
return;
|
||||
}
|
||||
|
||||
const item = currentRide?.item;
|
||||
if (!item) {
|
||||
box.innerHTML = '<span class="ride-current-empty">当前未启用座驾</span>';
|
||||
return;
|
||||
}
|
||||
|
||||
box.innerHTML = `
|
||||
<span class="ride-current-icon">${escapeHtml(item.icon || "🚘")}</span>
|
||||
<span><b>${escapeHtml(item.name)}</b> 生效中</span>
|
||||
<span class="ride-current-expire">到期:${escapeHtml(currentRide.expires_at || "-")}</span>
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染座驾商品卡片。
|
||||
*
|
||||
* @param {Array<Record<string, any>>} items 座驾商品列表
|
||||
* @returns {void}
|
||||
*/
|
||||
function renderRideItems(items) {
|
||||
const list = document.getElementById("ride-items-list");
|
||||
if (!list) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!items.length) {
|
||||
list.innerHTML = '<div class="ride-empty">暂无上架座驾</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
const activeItemId = Number(rideState.currentRide?.item?.id || 0);
|
||||
list.innerHTML = items.map((item) => {
|
||||
const isActive = Number(item.id) === activeItemId;
|
||||
const duration = Number(item.duration_days || 0);
|
||||
|
||||
return `
|
||||
<div class="ride-card${isActive ? " active" : ""}">
|
||||
<div class="ride-card-head">
|
||||
<span class="ride-card-icon">${escapeHtml(item.icon || "🚘")}</span>
|
||||
<span class="ride-card-title">${escapeHtml(item.name || "")}</span>
|
||||
${isActive ? '<span class="ride-active-badge">当前</span>' : ""}
|
||||
</div>
|
||||
<div class="ride-card-desc">${escapeHtml(item.description || "")}</div>
|
||||
<div class="ride-card-meta">
|
||||
<span>💰 ${Number(item.price || 0).toLocaleString()} 金币</span>
|
||||
<span>⏱ ${duration > 0 ? `${duration} 天` : "未配置"}</span>
|
||||
</div>
|
||||
<button type="button" class="ride-buy-btn" data-ride-buy="${Number(item.id)}">
|
||||
${isActive ? "续费座驾" : "购买座驾"}
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* 渲染座驾购买记录。
|
||||
*
|
||||
* @param {Array<Record<string, any>>} purchases 购买记录
|
||||
* @returns {void}
|
||||
*/
|
||||
function renderRidePurchases(purchases) {
|
||||
const list = document.getElementById("ride-purchase-list");
|
||||
if (!list) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!purchases.length) {
|
||||
list.innerHTML = '<div class="ride-empty">暂无座驾购买记录</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
list.innerHTML = purchases.map((purchase) => {
|
||||
const item = purchase.item || {};
|
||||
const statusMap = {
|
||||
active: "使用中",
|
||||
expired: "已过期",
|
||||
cancelled: "已替换",
|
||||
used: "已使用",
|
||||
};
|
||||
|
||||
return `
|
||||
<div class="ride-record">
|
||||
<span>${escapeHtml(item.icon || "🚘")} ${escapeHtml(item.name || "未知座驾")}</span>
|
||||
<span>${escapeHtml(statusMap[purchase.status] || purchase.status || "-")}</span>
|
||||
<span>${Number(purchase.price_paid || 0).toLocaleString()} 金币</span>
|
||||
<span>${escapeHtml(purchase.expires_at || "-")}</span>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* 购买或续费座驾。
|
||||
*
|
||||
* @param {number|string} itemId 商品 ID
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function buyRide(itemId) {
|
||||
const item = rideState.items.find((entry) => Number(entry.id) === Number(itemId));
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
|
||||
const duration = Number(item.duration_days || 0);
|
||||
const ok = await window.chatDialog?.confirm?.(
|
||||
`确认花费 ${Number(item.price || 0).toLocaleString()} 金币购买【${item.name}】吗?\n有效期:${duration} 天\n同款续购会自动叠加有效期。`,
|
||||
"确认购买座驾",
|
||||
);
|
||||
if (!ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(rideUrls().buy, {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
headers: rideHeaders(true),
|
||||
body: JSON.stringify({
|
||||
item_id: Number(itemId),
|
||||
room_id: window.chatContext?.roomId || 0,
|
||||
}),
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || data.status !== "success") {
|
||||
window.chatDialog?.alert?.(data.message || "购买失败", "座驾购买", "#cc4444");
|
||||
return;
|
||||
}
|
||||
|
||||
rideState.currentRide = data.current_ride || null;
|
||||
rideState.purchases = Array.isArray(data.purchases) ? data.purchases : [];
|
||||
renderRides({
|
||||
items: rideState.items,
|
||||
current_ride: rideState.currentRide,
|
||||
purchases: rideState.purchases,
|
||||
jjb: data.jjb,
|
||||
});
|
||||
|
||||
const shopBalance = document.getElementById("shop-jjb");
|
||||
if (shopBalance) {
|
||||
shopBalance.textContent = Number(data.jjb || 0).toLocaleString();
|
||||
}
|
||||
|
||||
window.chatDialog?.alert?.(data.message || "座驾购买成功", "座驾购买", "#16a34a");
|
||||
} catch (error) {
|
||||
window.chatDialog?.alert?.("网络异常,请稍后重试。", "座驾购买", "#cc4444");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定座驾弹窗事件。
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
export function bindRideControls() {
|
||||
if (rideEventsBound || typeof document === "undefined") {
|
||||
return;
|
||||
}
|
||||
|
||||
rideEventsBound = true;
|
||||
document.addEventListener("click", (event) => {
|
||||
if (!(event.target instanceof Element)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const closeButton = event.target.closest("[data-ride-modal-close]");
|
||||
const modal = document.getElementById("ride-modal");
|
||||
if (closeButton || (modal && event.target === modal)) {
|
||||
event.preventDefault();
|
||||
closeRideModal();
|
||||
return;
|
||||
}
|
||||
|
||||
const buyButton = event.target.closest("[data-ride-buy]");
|
||||
if (buyButton) {
|
||||
event.preventDefault();
|
||||
void buyRide(buyButton.getAttribute("data-ride-buy") || "");
|
||||
}
|
||||
});
|
||||
|
||||
window.openRideModal = openRideModal;
|
||||
window.closeRideModal = closeRideModal;
|
||||
window.loadRides = loadRides;
|
||||
window.buyRide = buyRide;
|
||||
}
|
||||
@@ -548,16 +548,18 @@ async function confirmAndBuyItem(item) {
|
||||
}
|
||||
}
|
||||
|
||||
// 个性装扮支持多份购买(叠加天数),弹出数量选择
|
||||
if (DECORATION_TYPE_TO_SLOT[item.type] && item.type !== "sign_repair") {
|
||||
quantity = await window.promptQuantity?.(`购买多份【${item.name}】可叠加天数\n已激活的同款续购自动延长,无需一次买满`, 1, 99) ?? 1;
|
||||
const isDecoration = DECORATION_TYPE_TO_SLOT[item.type] && item.type !== "sign_repair";
|
||||
if (isDecoration) {
|
||||
const unitPrice = Number(item.price || 0);
|
||||
quantity = await promptDecorationQuantity(item);
|
||||
if (quantity === null || quantity === undefined) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const validityText = buildValidityText(item);
|
||||
const confirmMessage = `确认花费 💰 ${Number(Number(item.price || 0) * quantity).toLocaleString()} 金币购买\n【${item.name}】${quantity > 1 ? ` × ${quantity}` : ""}${validityText ? `\n${validityText}` : ""}\n\n确定购买吗?`;
|
||||
const stackingHint = isDecoration ? "\n💡 已激活同款续购自动叠加天数,可多次购买" : "";
|
||||
const confirmMessage = `确认花费 💰 ${Number(Number(item.price || 0) * quantity).toLocaleString()} 金币购买\n【${item.name}】${quantity > 1 ? ` × ${quantity}` : ""}${validityText ? `\n${validityText}` : ""}${stackingHint}\n\n确定购买吗?`;
|
||||
const confirmed = await confirmShopPurchase(confirmMessage);
|
||||
|
||||
if (confirmed) {
|
||||
@@ -565,6 +567,47 @@ async function confirmAndBuyItem(item) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 装饰品数量输入弹窗(参照补签卡样式)。
|
||||
*
|
||||
* @param {Record<string, any>} item 装饰品数据
|
||||
* @returns {Promise<number|null>} 返回数量,取消返回 null
|
||||
*/
|
||||
async function promptDecorationQuantity(item) {
|
||||
const unitPrice = Number(item.price || 0);
|
||||
const validityText = buildValidityText(item);
|
||||
const validHint = validityText ? `\n有效期:${validityText}` : "";
|
||||
const promptPromise = window.chatDialog?.prompt(
|
||||
`请输入要购买的份数(1-99份):\n单价 ${unitPrice.toLocaleString()} 金币${validHint}\n💡 已激活同款续购自动叠加天数,可多次购买`,
|
||||
'1',
|
||||
`购买 ${item.name}`,
|
||||
'#7c3aed',
|
||||
);
|
||||
|
||||
const inputEl = document.getElementById('global-dialog-input');
|
||||
const previousInputStyle = inputEl?.getAttribute('style') || '';
|
||||
|
||||
if (inputEl) {
|
||||
inputEl.style.minHeight = '40px';
|
||||
inputEl.style.height = '40px';
|
||||
inputEl.style.resize = 'none';
|
||||
inputEl.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
const rawQuantity = await promptPromise;
|
||||
|
||||
if (inputEl) inputEl.setAttribute('style', previousInputStyle);
|
||||
if (rawQuantity === null || rawQuantity === undefined) return null;
|
||||
|
||||
const quantity = Number.parseInt(String(rawQuantity).trim(), 10);
|
||||
if (!Number.isInteger(quantity) || quantity < 1 || quantity > 99) {
|
||||
window.chatDialog?.alert('购买数量必须是 1 到 99 之间的整数。', '数量不正确', '#cc4444');
|
||||
return null;
|
||||
}
|
||||
|
||||
return quantity;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通用数量输入弹窗。
|
||||
*
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
// 斜杠命令菜单模块
|
||||
// 输入 / 时弹出可用命令列表,支持键盘/鼠标选择,可扩展的命令注册表。
|
||||
|
||||
// ── 命令注册表(后续新命令只需 push 到此数组)──
|
||||
|
||||
const SLASH_COMMANDS = [
|
||||
{
|
||||
id: "pat",
|
||||
name: "/拍一拍",
|
||||
description: "向当前选中的聊天对象发送拍一拍,屏幕会抖动",
|
||||
icon: "👋",
|
||||
fill(_input) {
|
||||
if (typeof window.executePat === "function") {
|
||||
window.executePat();
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "profile",
|
||||
name: "/查看资料",
|
||||
description: "查看当前选中对象的个人资料名片",
|
||||
icon: "📋",
|
||||
fill(_input) {
|
||||
const toUserSelect = document.getElementById("to_user");
|
||||
const target = toUserSelect?.value?.trim() || null;
|
||||
if (!target || target === "大家") {
|
||||
window.chatDialog?.alert("请先选择一个聊天对象,再查看资料。", "查看资料", "#6366f1");
|
||||
return;
|
||||
}
|
||||
if (typeof window.openUserCard === "function") {
|
||||
window.openUserCard(target);
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "signin",
|
||||
name: "/签到",
|
||||
description: "自动完成今日签到,领取每日奖励",
|
||||
icon: "✅",
|
||||
fill(_input) {
|
||||
if (typeof window.claimDailySignInFromModal === "function") {
|
||||
window.claimDailySignInFromModal();
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
// ── 菜单状态 ──
|
||||
|
||||
let visible = false;
|
||||
let selectedIndex = 0;
|
||||
let currentFilter = "";
|
||||
|
||||
// ── 过滤 ──
|
||||
|
||||
function getFilteredCommands(filter) {
|
||||
if (!filter || filter === "/") return SLASH_COMMANDS;
|
||||
const q = filter.toLowerCase();
|
||||
return SLASH_COMMANDS.filter((c) => c.id.includes(q) || c.name.includes(q));
|
||||
}
|
||||
|
||||
// ── DOM 构建 ──
|
||||
|
||||
function ensureMenu() {
|
||||
const input = document.getElementById("content");
|
||||
const inputRow = input?.closest(".input-row");
|
||||
if (!input || !inputRow) return null;
|
||||
|
||||
let menu = document.getElementById("slash-command-menu");
|
||||
if (!menu) {
|
||||
menu = document.createElement("div");
|
||||
menu.id = "slash-command-menu";
|
||||
menu.className = "slash-command-menu";
|
||||
menu.style.cssText =
|
||||
"display:none;position:absolute;bottom:100%;left:0;z-index:9999;" +
|
||||
"min-width:380px;max-width:420px;max-height:200px;overflow-y:auto;" +
|
||||
"background:#fff;border:1px solid #cbd5e1;border-radius:10px;" +
|
||||
"box-shadow:0 6px 20px rgba(15,23,42,.18);padding:6px 0;";
|
||||
inputRow.style.position = "relative";
|
||||
inputRow.appendChild(menu);
|
||||
}
|
||||
return menu;
|
||||
}
|
||||
|
||||
function renderMenu(filtered, filter) {
|
||||
const menu = ensureMenu();
|
||||
if (!menu) return;
|
||||
|
||||
menu.innerHTML = "";
|
||||
|
||||
if (filtered.length === 0) {
|
||||
const empty = document.createElement("div");
|
||||
empty.style.cssText =
|
||||
"padding:10px 14px;color:#94a3b8;font-size:12px;text-align:center;";
|
||||
empty.textContent = "没有匹配的命令";
|
||||
menu.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
filtered.forEach((cmd, i) => {
|
||||
const item = document.createElement("div");
|
||||
item.dataset.index = String(i);
|
||||
item.style.cssText =
|
||||
"display:flex;align-items:center;gap:10px;padding:8px 14px;" +
|
||||
"cursor:pointer;transition:background .1s;white-space:nowrap;" +
|
||||
(i === selectedIndex ? "background:#eef2ff;" : "");
|
||||
|
||||
// 高亮匹配文字
|
||||
const nameHtml = highlightMatch(cmd.name, filter);
|
||||
const descHtml = cmd.description
|
||||
? `<span style="font-size:11px;color:#64748b;margin-left:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${cmd.description}</span>`
|
||||
: "";
|
||||
|
||||
item.innerHTML =
|
||||
`<span style="font-size:16px;flex:none;">${cmd.icon}</span>` +
|
||||
`<span style="flex:1;min-width:0;display:flex;align-items:baseline;gap:4px;">${nameHtml}${descHtml}</span>`;
|
||||
|
||||
item.addEventListener("mousedown", (e) => {
|
||||
e.preventDefault();
|
||||
selectCommand(i);
|
||||
});
|
||||
item.addEventListener("mouseenter", () => {
|
||||
selectedIndex = i;
|
||||
highlightItem(menu, i);
|
||||
});
|
||||
|
||||
menu.appendChild(item);
|
||||
});
|
||||
}
|
||||
|
||||
function highlightMatch(text, filter) {
|
||||
if (!filter || filter === "/") return text;
|
||||
const idx = text.toLowerCase().indexOf(filter.toLowerCase());
|
||||
if (idx === -1) return text;
|
||||
return (
|
||||
text.slice(0, idx) +
|
||||
`<b style="color:#4f46e5;">${text.slice(idx, idx + filter.length)}</b>` +
|
||||
text.slice(idx + filter.length)
|
||||
);
|
||||
}
|
||||
|
||||
function highlightItem(menu, index) {
|
||||
const items = menu.querySelectorAll("[data-index]");
|
||||
items.forEach((el, i) => {
|
||||
el.style.background = i === index ? "#eef2ff" : "";
|
||||
});
|
||||
}
|
||||
|
||||
// ── 选择 ──
|
||||
|
||||
function selectCommand(index) {
|
||||
const filtered = getFilteredCommands(currentFilter);
|
||||
const cmd = filtered[index];
|
||||
if (!cmd) return;
|
||||
|
||||
const input = document.getElementById("content");
|
||||
if (!input) return;
|
||||
|
||||
if (typeof cmd.fill === "function") {
|
||||
cmd.fill(input);
|
||||
} else {
|
||||
input.value = cmd.name;
|
||||
window.persistChatDraft?.(cmd.name);
|
||||
}
|
||||
|
||||
// 统一清除输入框中的 /
|
||||
input.value = "";
|
||||
window.persistChatDraft?.("");
|
||||
|
||||
hideMenu();
|
||||
input.focus();
|
||||
}
|
||||
|
||||
// ── 显示/隐藏 ──
|
||||
|
||||
function showMenu(filter) {
|
||||
const menu = ensureMenu();
|
||||
if (!menu) return;
|
||||
|
||||
currentFilter = filter;
|
||||
selectedIndex = 0;
|
||||
const filtered = getFilteredCommands(filter);
|
||||
visible = filtered.length > 0;
|
||||
renderMenu(filtered, filter);
|
||||
menu.style.display = visible ? "block" : "none";
|
||||
}
|
||||
|
||||
function hideMenu() {
|
||||
const menu = document.getElementById("slash-command-menu");
|
||||
if (menu) menu.style.display = "none";
|
||||
visible = false;
|
||||
selectedIndex = 0;
|
||||
currentFilter = "";
|
||||
}
|
||||
|
||||
// ── 事件绑定 ──
|
||||
|
||||
function handleInput(e) {
|
||||
const input = e.target;
|
||||
const val = input.value;
|
||||
|
||||
if (val.startsWith("/")) {
|
||||
// 如果输入值已是完整命令名,不弹出菜单
|
||||
const exactMatch = SLASH_COMMANDS.some(
|
||||
(c) => c.name === val.trim()
|
||||
);
|
||||
if (!exactMatch) {
|
||||
const filter = val.trim();
|
||||
showMenu(filter);
|
||||
return;
|
||||
}
|
||||
}
|
||||
hideMenu();
|
||||
}
|
||||
|
||||
function handleKeydown(e) {
|
||||
if (!visible) return;
|
||||
|
||||
const filtered = getFilteredCommands(currentFilter);
|
||||
if (filtered.length === 0) return;
|
||||
|
||||
switch (e.key) {
|
||||
case "ArrowDown":
|
||||
e.preventDefault();
|
||||
selectedIndex = Math.min(selectedIndex + 1, filtered.length - 1);
|
||||
highlightItem(ensureMenu(), selectedIndex);
|
||||
break;
|
||||
case "ArrowUp":
|
||||
e.preventDefault();
|
||||
selectedIndex = Math.max(selectedIndex - 1, 0);
|
||||
highlightItem(ensureMenu(), selectedIndex);
|
||||
break;
|
||||
case "Enter":
|
||||
if (visible) {
|
||||
e.preventDefault();
|
||||
selectCommand(selectedIndex);
|
||||
}
|
||||
break;
|
||||
case "Escape":
|
||||
e.preventDefault();
|
||||
hideMenu();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function handleDocumentClick(e) {
|
||||
if (visible) {
|
||||
const menu = document.getElementById("slash-command-menu");
|
||||
const input = document.getElementById("content");
|
||||
if (menu && !menu.contains(e.target) && input !== e.target) {
|
||||
hideMenu();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── 初始化 ──
|
||||
|
||||
export function bindSlashCommands() {
|
||||
const input = document.getElementById("content");
|
||||
if (!input) {
|
||||
// 如果 DOM 未就绪,稍后重试
|
||||
setTimeout(bindSlashCommands, 200);
|
||||
return;
|
||||
}
|
||||
|
||||
// 避免重复绑定
|
||||
if (input.dataset.slashBound) return;
|
||||
input.dataset.slashBound = "1";
|
||||
|
||||
input.addEventListener("input", handleInput);
|
||||
input.addEventListener("keydown", handleKeydown);
|
||||
document.addEventListener("click", handleDocumentClick);
|
||||
}
|
||||
|
||||
// 允许外部扩展命令列表
|
||||
export function registerSlashCommand(cmd) {
|
||||
SLASH_COMMANDS.push(cmd);
|
||||
}
|
||||
|
||||
export { SLASH_COMMANDS };
|
||||
@@ -12,6 +12,7 @@ export function runToolbarAction(action) {
|
||||
// 工具条只做入口分发,具体业务仍由原有全局函数负责。
|
||||
const actions = {
|
||||
shop: () => window.openShopModal?.(),
|
||||
ride: () => window.openRideModal?.(),
|
||||
vip: () => window.openVipModal?.(),
|
||||
"save-exp": () => window.saveExp?.(),
|
||||
game: () => window.openGameHall?.(),
|
||||
|
||||
@@ -175,12 +175,19 @@ export function normalizeHolidayBroadcastEvent(payload = {}) {
|
||||
|
||||
window.normalizeHolidayBroadcastEvent = normalizeHolidayBroadcastEvent;
|
||||
|
||||
let chatConnectionInitialized = false;
|
||||
|
||||
export function initChat(roomId) {
|
||||
if (chatConnectionInitialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!roomId) {
|
||||
console.error("未提供 roomId,无法初始化 WebSocket 连接。");
|
||||
return;
|
||||
}
|
||||
|
||||
chatConnectionInitialized = true;
|
||||
const userId = window.chatContext?.userId;
|
||||
|
||||
// 监听全局系统事件(如 AI 机器人开关)
|
||||
@@ -264,6 +271,21 @@ export function initChat(roomId) {
|
||||
console.log("特效播放:", e);
|
||||
window.dispatchEvent(new CustomEvent("chat:effect", { detail: e }));
|
||||
})
|
||||
// 监听拍一拍
|
||||
.listen("UserPat", (e) => {
|
||||
console.log("拍一拍:", e);
|
||||
window.dispatchEvent(new CustomEvent("chat:pat", { detail: e }));
|
||||
})
|
||||
// 监听猜成语出题
|
||||
.listen("RiddleGameStarted", (e) => {
|
||||
console.log("猜成语:", e);
|
||||
window.dispatchEvent(new CustomEvent("chat:idiom-started", { detail: e }));
|
||||
})
|
||||
// 监听猜成语答题结果
|
||||
.listen("RiddleGameAnswered", (e) => {
|
||||
console.log("猜成语结果:", e);
|
||||
window.dispatchEvent(new CustomEvent("chat:idiom-answered", { detail: e }));
|
||||
})
|
||||
// 监听任命公告(礼花 + 隆重弹窗)
|
||||
.listen("AppointmentAnnounced", (e) => {
|
||||
console.log("任命公告:", e);
|
||||
@@ -405,3 +427,7 @@ export function initMarriagePrivateChannel(userId) {
|
||||
// 供全局调用
|
||||
window.initChat = initChat;
|
||||
window.initMarriagePrivateChannel = initMarriagePrivateChannel;
|
||||
|
||||
if (window.chatContext?.roomId) {
|
||||
window.initChat(window.chatContext.roomId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
/**
|
||||
* 文件功能:聊天室 99A 主战坦克重装入场特效
|
||||
*
|
||||
* 使用全屏透明 Canvas 绘制中国 99A 主战坦克横穿屏幕、履带滚动、
|
||||
* 长炮管炮击、楔形复合装甲、侧裙、尘土冲击波与重装入场 HUD。
|
||||
*/
|
||||
|
||||
const Type99AEffect = (() => {
|
||||
const DURATION = 8200;
|
||||
const ARMOR = "#5f6f3a";
|
||||
const DARK_ARMOR = "#1f2a1d";
|
||||
const CAMO = "#7c6a36";
|
||||
const DUST = "#fde68a";
|
||||
const FIRE = "#f97316";
|
||||
|
||||
/**
|
||||
* 缓出曲线,让坦克进场有重量感。
|
||||
*
|
||||
* @param {number} t 0 到 1 的进度
|
||||
* @returns {number}
|
||||
*/
|
||||
function easeOutCubic(t) {
|
||||
return 1 - Math.pow(1 - t, 3);
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓入缓出曲线,用于 HUD 和冲击波。
|
||||
*
|
||||
* @param {number} t 0 到 1 的进度
|
||||
* @returns {number}
|
||||
*/
|
||||
function easeInOutSine(t) {
|
||||
return -(Math.cos(Math.PI * t) - 1) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建地面尘土粒子。
|
||||
*
|
||||
* @param {number} w 画布宽度
|
||||
* @param {number} h 画布高度
|
||||
* @returns {Array<Record<string, number>>}
|
||||
*/
|
||||
function createDust(w, h) {
|
||||
return Array.from({ length: 90 }, () => ({
|
||||
x: Math.random() * w,
|
||||
y: h * (0.66 + Math.random() * 0.18),
|
||||
speed: 1.6 + Math.random() * 4.8,
|
||||
size: 2 + Math.random() * 8,
|
||||
alpha: 0.12 + Math.random() * 0.34,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制战场式地面背景。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} w 画布宽度
|
||||
* @param {number} h 画布高度
|
||||
* @param {number} progress 播放进度
|
||||
*/
|
||||
function drawBackdrop(ctx, w, h, progress) {
|
||||
const fade = Math.min(1, progress / 0.16) * Math.min(1, (1 - progress) / 0.12);
|
||||
const gradient = ctx.createRadialGradient(w * 0.5, h * 0.62, 0, w * 0.5, h * 0.62, Math.max(w, h) * 0.76);
|
||||
gradient.addColorStop(0, `rgba(41,37,36,${0.42 * fade})`);
|
||||
gradient.addColorStop(0.55, `rgba(63,98,18,${0.18 * fade})`);
|
||||
gradient.addColorStop(1, "rgba(0,0,0,0)");
|
||||
|
||||
ctx.save();
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.fillRect(0, 0, w, h);
|
||||
ctx.globalCompositeOperation = "lighter";
|
||||
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const y = h * (0.7 + i * 0.028);
|
||||
ctx.strokeStyle = `rgba(253,230,138,${0.1 * fade})`;
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(0, y + Math.sin(progress * 12 + i) * 4);
|
||||
ctx.lineTo(w, y + Math.cos(progress * 9 + i) * 4);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制履带带起的尘土。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {Array<Record<string, number>>} dust 尘土粒子
|
||||
* @param {number} w 画布宽度
|
||||
* @param {number} progress 播放进度
|
||||
*/
|
||||
function drawDust(ctx, dust, w, progress) {
|
||||
const fade = Math.min(1, progress / 0.18) * Math.min(1, (1 - progress) / 0.12);
|
||||
|
||||
ctx.save();
|
||||
ctx.globalCompositeOperation = "lighter";
|
||||
dust.forEach((particle, index) => {
|
||||
const travel = (progress * (620 + particle.speed * 80) + index * 47) % (w + 420);
|
||||
const x = w + 210 - travel;
|
||||
ctx.globalAlpha = particle.alpha * fade;
|
||||
ctx.fillStyle = DUST;
|
||||
ctx.shadowColor = DUST;
|
||||
ctx.shadowBlur = particle.size * 1.4;
|
||||
ctx.beginPath();
|
||||
ctx.ellipse(x, particle.y, particle.size * 1.8, particle.size * 0.7, 0, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
});
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制炮击冲击波。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} w 画布宽度
|
||||
* @param {number} h 画布高度
|
||||
* @param {number} progress 播放进度
|
||||
*/
|
||||
function drawShockwave(ctx, w, h, progress) {
|
||||
const shot = Math.max(0, Math.min(1, (progress - 0.5) / 0.2));
|
||||
if (shot <= 0 || shot >= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const alpha = Math.sin(shot * Math.PI);
|
||||
ctx.save();
|
||||
ctx.globalCompositeOperation = "lighter";
|
||||
ctx.strokeStyle = `rgba(253,230,138,${0.38 * alpha})`;
|
||||
ctx.lineWidth = 5;
|
||||
ctx.beginPath();
|
||||
ctx.ellipse(w * 0.48, h * 0.68, w * (0.08 + shot * 0.38), h * (0.03 + shot * 0.08), 0, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制 99A 主炮炮口火焰。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} progress 播放进度
|
||||
*/
|
||||
function drawMuzzleFlash(ctx, progress) {
|
||||
const flash = Math.max(0, 1 - Math.abs(progress - 0.5) / 0.045);
|
||||
if (flash <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.save();
|
||||
ctx.globalCompositeOperation = "lighter";
|
||||
ctx.shadowColor = FIRE;
|
||||
ctx.shadowBlur = 28;
|
||||
ctx.fillStyle = `rgba(249,115,22,${0.78 * flash})`;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(408, -118);
|
||||
ctx.lineTo(528, -156);
|
||||
ctx.lineTo(468, -112);
|
||||
ctx.lineTo(532, -76);
|
||||
ctx.lineTo(408, -100);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = `rgba(255,255,255,${0.74 * flash})`;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(414, -114);
|
||||
ctx.lineTo(486, -132);
|
||||
ctx.lineTo(452, -108);
|
||||
ctx.lineTo(492, -92);
|
||||
ctx.lineTo(414, -102);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制 99A 主战坦克主体。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} x 坦克中心 x
|
||||
* @param {number} y 坦克中心 y
|
||||
* @param {number} scale 缩放比例
|
||||
* @param {number} progress 播放进度
|
||||
*/
|
||||
function drawTank(ctx, x, y, scale, progress) {
|
||||
ctx.save();
|
||||
ctx.translate(x, y);
|
||||
ctx.scale(scale, scale);
|
||||
|
||||
ctx.save();
|
||||
ctx.shadowColor = "rgba(0,0,0,0.72)";
|
||||
ctx.shadowBlur = 16;
|
||||
ctx.fillStyle = "rgba(0,0,0,0.45)";
|
||||
ctx.beginPath();
|
||||
ctx.ellipse(0, 54, 250, 22, 0, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
drawMuzzleFlash(ctx, progress);
|
||||
|
||||
// 99A 履带底盘:右侧前导轮更大,模拟参考图的右前方视角。
|
||||
const track = ctx.createLinearGradient(-246, 24, 246, 94);
|
||||
track.addColorStop(0, "#0a0a0a");
|
||||
track.addColorStop(0.42, DARK_ARMOR);
|
||||
track.addColorStop(1, "#030712");
|
||||
ctx.fillStyle = track;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-250, 32);
|
||||
ctx.lineTo(-206, 10);
|
||||
ctx.lineTo(184, 12);
|
||||
ctx.lineTo(252, 38);
|
||||
ctx.lineTo(218, 94);
|
||||
ctx.lineTo(-226, 96);
|
||||
ctx.lineTo(-270, 70);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = "rgba(15,23,42,0.74)";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-236, 22);
|
||||
ctx.lineTo(180, 23);
|
||||
ctx.lineTo(236, 43);
|
||||
ctx.lineTo(204, 62);
|
||||
ctx.lineTo(-218, 58);
|
||||
ctx.lineTo(-256, 42);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
|
||||
for (let i = 0; i < 7; i++) {
|
||||
const wheelX = -180 + i * 58;
|
||||
const wheelY = 62 + (i > 4 ? 2 : 0);
|
||||
drawRoadWheel(ctx, wheelX, wheelY, progress + i * 0.05);
|
||||
}
|
||||
|
||||
ctx.strokeStyle = "rgba(253,230,138,0.14)";
|
||||
ctx.lineWidth = 4;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-218, 82);
|
||||
ctx.lineTo(212, 82);
|
||||
ctx.stroke();
|
||||
|
||||
// 99A 车体:右侧为前装甲,首上装甲呈明显楔形下压。
|
||||
const hull = ctx.createLinearGradient(-238, -50, 250, 36);
|
||||
hull.addColorStop(0, "#42512b");
|
||||
hull.addColorStop(0.38, ARMOR);
|
||||
hull.addColorStop(0.66, CAMO);
|
||||
hull.addColorStop(1, "#253018");
|
||||
ctx.fillStyle = hull;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-238, 24);
|
||||
ctx.lineTo(-212, -30);
|
||||
ctx.lineTo(86, -52);
|
||||
ctx.lineTo(226, -24);
|
||||
ctx.lineTo(252, 14);
|
||||
ctx.lineTo(202, 38);
|
||||
ctx.lineTo(-216, 36);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = "rgba(15,23,42,0.34)";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(68, -44);
|
||||
ctx.lineTo(226, -22);
|
||||
ctx.lineTo(248, 9);
|
||||
ctx.lineTo(138, 18);
|
||||
ctx.lineTo(86, -5);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
|
||||
// 侧裙装甲模块和数码迷彩块,增强 99A 识别度。
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const panelX = -206 + i * 50;
|
||||
ctx.fillStyle = i % 2 === 0 ? "rgba(54,83,20,0.86)" : "rgba(120,113,55,0.82)";
|
||||
ctx.fillRect(panelX, -2, 42, 24);
|
||||
ctx.strokeStyle = "rgba(15,23,42,0.34)";
|
||||
ctx.lineWidth = 1.4;
|
||||
ctx.strokeRect(panelX, -2, 42, 24);
|
||||
}
|
||||
|
||||
[
|
||||
[-186, -24, 34, 18, "#7f8f57"],
|
||||
[-118, -34, 42, 20, "#b9855a"],
|
||||
[-32, -39, 48, 22, "#344329"],
|
||||
[52, -46, 44, 20, "#8a9b61"],
|
||||
[118, -30, 38, 19, "#a36f52"],
|
||||
[182, -14, 46, 21, "#415329"],
|
||||
[-220, 2, 30, 20, "#27351f"],
|
||||
[-72, 4, 36, 18, "#718246"],
|
||||
[22, 2, 42, 20, "#ac7654"],
|
||||
].forEach(([px, py, pw, ph, color]) => {
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillRect(px, py, pw, ph);
|
||||
});
|
||||
|
||||
// 参考图里的大号车号、国旗和前车灯。
|
||||
ctx.fillStyle = "rgba(255,255,255,0.9)";
|
||||
ctx.font = "900 31px serif";
|
||||
ctx.fillText("807", -216, -12);
|
||||
ctx.fillStyle = "rgba(220,38,38,0.95)";
|
||||
ctx.fillRect(-128, -31, 34, 22);
|
||||
ctx.fillStyle = "rgba(253,224,71,0.95)";
|
||||
ctx.font = "900 12px serif";
|
||||
ctx.fillText("★", -122, -16);
|
||||
ctx.fillStyle = "rgba(254,242,242,0.88)";
|
||||
roundRect(ctx, 178, -17, 18, 9, 5);
|
||||
ctx.fill();
|
||||
roundRect(ctx, 214, -8, 18, 9, 5);
|
||||
ctx.fill();
|
||||
|
||||
// 低矮楔形炮塔和 125mm 长炮管:炮管朝右并略微上扬。
|
||||
const turret = ctx.createLinearGradient(-128, -108, 156, -28);
|
||||
turret.addColorStop(0, "#66734a");
|
||||
turret.addColorStop(0.46, "#87905d");
|
||||
turret.addColorStop(1, "#24301d");
|
||||
ctx.fillStyle = turret;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-132, -36);
|
||||
ctx.lineTo(-82, -96);
|
||||
ctx.lineTo(86, -108);
|
||||
ctx.lineTo(158, -72);
|
||||
ctx.lineTo(112, -32);
|
||||
ctx.lineTo(-118, -20);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
|
||||
[
|
||||
[-98, -76, 42, 22, "#314222"],
|
||||
[-28, -90, 50, 22, "#a36f52"],
|
||||
[46, -92, 48, 20, "#73844d"],
|
||||
[98, -66, 34, 20, "#2f3f24"],
|
||||
].forEach(([px, py, pw, ph, color]) => {
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillRect(px, py, pw, ph);
|
||||
});
|
||||
|
||||
ctx.save();
|
||||
ctx.strokeStyle = "rgba(17,24,39,0.96)";
|
||||
ctx.lineWidth = 18;
|
||||
ctx.lineCap = "round";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(106, -70);
|
||||
ctx.lineTo(410, -120);
|
||||
ctx.stroke();
|
||||
ctx.strokeStyle = "#64748b";
|
||||
ctx.lineWidth = 6;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(114, -75);
|
||||
ctx.lineTo(404, -123);
|
||||
ctx.stroke();
|
||||
ctx.fillStyle = "#1f2937";
|
||||
roundRect(ctx, 392, -132, 30, 24, 8);
|
||||
ctx.fill();
|
||||
ctx.fillStyle = "#40513a";
|
||||
roundRect(ctx, 250, -107, 24, 20, 5);
|
||||
ctx.fill();
|
||||
roundRect(ctx, 322, -120, 24, 20, 5);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
ctx.fillStyle = "rgba(17,24,39,0.95)";
|
||||
roundRect(ctx, 86, -80, 62, 24, 8);
|
||||
ctx.fill();
|
||||
|
||||
// 炮塔前装甲、烟幕弹发射器和车长机枪。
|
||||
ctx.fillStyle = "rgba(15,23,42,0.5)";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(42, -48);
|
||||
ctx.lineTo(96, -78);
|
||||
ctx.lineTo(154, -66);
|
||||
ctx.lineTo(112, -36);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
|
||||
for (let i = 0; i < 4; i++) {
|
||||
ctx.fillStyle = "rgba(15,23,42,0.9)";
|
||||
roundRect(ctx, -124 + i * 13, -58 + (i % 2) * 10, 10, 18, 4);
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
ctx.strokeStyle = "rgba(15,23,42,0.9)";
|
||||
ctx.lineWidth = 3;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-24, -102);
|
||||
ctx.lineTo(-18, -132);
|
||||
ctx.lineTo(40, -138);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.fillStyle = "rgba(15,23,42,0.84)";
|
||||
roundRect(ctx, -32, -108, 58, 14, 7);
|
||||
ctx.fill();
|
||||
|
||||
// 装甲高光。
|
||||
ctx.strokeStyle = "rgba(226,232,240,0.28)";
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-184, -22);
|
||||
ctx.lineTo(92, -40);
|
||||
ctx.moveTo(-142, 8);
|
||||
ctx.lineTo(172, -2);
|
||||
ctx.moveTo(92, -82);
|
||||
ctx.lineTo(144, -66);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制坦克负重轮。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} x 中心 x
|
||||
* @param {number} y 中心 y
|
||||
* @param {number} progress 播放进度
|
||||
*/
|
||||
function drawRoadWheel(ctx, x, y, progress) {
|
||||
ctx.save();
|
||||
ctx.translate(x, y);
|
||||
ctx.rotate(progress * 30);
|
||||
ctx.fillStyle = "#111827";
|
||||
ctx.beginPath();
|
||||
ctx.arc(0, 0, 21, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = "#475569";
|
||||
ctx.lineWidth = 3;
|
||||
ctx.stroke();
|
||||
ctx.strokeStyle = "#94a3b8";
|
||||
ctx.lineWidth = 2;
|
||||
for (let i = 0; i < 6; i++) {
|
||||
ctx.rotate(Math.PI / 3);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(0, 0);
|
||||
ctx.lineTo(16, 0);
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.fillStyle = "#cbd5e1";
|
||||
ctx.beginPath();
|
||||
ctx.arc(0, 0, 5, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制 99A 重装入场 HUD 字幕。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} w 画布宽度
|
||||
* @param {number} h 画布高度
|
||||
* @param {number} progress 播放进度
|
||||
* @param {string} title 入场标题
|
||||
* @param {string} userInfo 用户身份信息
|
||||
*/
|
||||
function drawHud(ctx, w, h, progress, title, userInfo) {
|
||||
const enter = Math.min(1, Math.max(0, (progress - 0.14) / 0.2));
|
||||
const leave = Math.min(1, Math.max(0, (1 - progress) / 0.16));
|
||||
const alpha = easeInOutSine(enter) * leave;
|
||||
const y = h * 0.17 - (1 - enter) * 24;
|
||||
|
||||
ctx.save();
|
||||
ctx.globalAlpha = alpha;
|
||||
ctx.textAlign = "center";
|
||||
ctx.shadowColor = "rgba(253,230,138,0.95)";
|
||||
ctx.shadowBlur = 22;
|
||||
ctx.fillStyle = "rgba(28,25,23,0.66)";
|
||||
ctx.strokeStyle = "rgba(253,230,138,0.72)";
|
||||
ctx.lineWidth = 2;
|
||||
roundRect(ctx, w * 0.5 - 340, y - 56, 680, 120, 18);
|
||||
ctx.fill();
|
||||
ctx.stroke();
|
||||
|
||||
ctx.fillStyle = "#fef3c7";
|
||||
ctx.font = "700 16px serif";
|
||||
ctx.fillText("ZTZ-99A ARMORED FORCE", w * 0.5, y - 24);
|
||||
ctx.fillStyle = "#fde68a";
|
||||
ctx.font = "700 18px serif";
|
||||
ctx.fillText(userInfo, w * 0.5, y + 8, 620);
|
||||
ctx.fillStyle = "#ffffff";
|
||||
ctx.font = "900 34px serif";
|
||||
ctx.fillText(title, w * 0.5, y + 45, 620);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制圆角矩形路径。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} x 左上角 x
|
||||
* @param {number} y 左上角 y
|
||||
* @param {number} w 宽度
|
||||
* @param {number} h 高度
|
||||
* @param {number} r 圆角半径
|
||||
*/
|
||||
function roundRect(ctx, x, y, w, h, r) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y);
|
||||
ctx.lineTo(x + w - r, y);
|
||||
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
|
||||
ctx.lineTo(x + w, y + h - r);
|
||||
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
|
||||
ctx.lineTo(x + r, y + h);
|
||||
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
|
||||
ctx.lineTo(x, y + r);
|
||||
ctx.quadraticCurveTo(x, y, x + r, y);
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动 99A 主战坦克重装入场特效。
|
||||
*
|
||||
* @param {HTMLCanvasElement} canvas 全屏特效画布
|
||||
* @param {Function} onEnd 结束回调
|
||||
* @param {object} options 特效附加参数
|
||||
* @returns {{cancel: Function}}
|
||||
*/
|
||||
function start(canvas, onEnd, options = {}) {
|
||||
const ctx = canvas.getContext("2d");
|
||||
const w = canvas.width;
|
||||
const h = canvas.height;
|
||||
const dust = createDust(w, h);
|
||||
const title = String(options.effect_title || "99A主战坦克 重装入场").trim() || "99A主战坦克 重装入场";
|
||||
const userInfo = String(options.effect_user_info || "").trim();
|
||||
const startTime = performance.now();
|
||||
let animId = null;
|
||||
let finished = false;
|
||||
|
||||
/**
|
||||
* 统一结束动画,手动取消时只清理不回调。
|
||||
*
|
||||
* @param {boolean} canceled 是否为手动取消
|
||||
*/
|
||||
function finish(canceled) {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
|
||||
finished = true;
|
||||
if (animId) {
|
||||
cancelAnimationFrame(animId);
|
||||
}
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
if (!canceled) {
|
||||
onEnd();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐帧绘制坦克入场动画。
|
||||
*
|
||||
* @param {number} now 当前高精度时间
|
||||
*/
|
||||
function animate(now) {
|
||||
const elapsed = now - startTime;
|
||||
const progress = Math.min(1, elapsed / DURATION);
|
||||
const entry = easeOutCubic(Math.min(1, progress / 0.64));
|
||||
const exit = easeInOutSine(Math.max(0, (progress - 0.76) / 0.24));
|
||||
const tankX = -w * 0.24 + entry * w * 0.92 + exit * w * 0.62;
|
||||
const tankY = h * 0.66 + Math.sin(progress * 24) * 2.5;
|
||||
const scale = Math.min(1.12, Math.max(0.68, w / 1180));
|
||||
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
drawBackdrop(ctx, w, h, progress);
|
||||
drawDust(ctx, dust, w, progress);
|
||||
drawShockwave(ctx, w, h, progress);
|
||||
drawTank(ctx, tankX, tankY, scale, progress);
|
||||
drawHud(ctx, w, h, progress, title, userInfo);
|
||||
|
||||
if (progress < 1) {
|
||||
animId = requestAnimationFrame(animate);
|
||||
} else {
|
||||
finish(false);
|
||||
}
|
||||
}
|
||||
|
||||
animId = requestAnimationFrame(animate);
|
||||
|
||||
return {
|
||||
cancel() {
|
||||
finish(true);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { start };
|
||||
})();
|
||||
|
||||
window.Type99AEffect = Type99AEffect;
|
||||
@@ -0,0 +1,407 @@
|
||||
/**
|
||||
* 文件功能:聊天室东风-5C洲际导弹发射预览特效
|
||||
*
|
||||
* 使用全屏透明 Canvas 绘制风格化洲际导弹升空、尾焰、烟尘冲击波、
|
||||
* 雷达扫描网格和测试 HUD。该效果只用于聊天室视觉预览,不表达真实装备参数。
|
||||
*/
|
||||
|
||||
const Df5cEffect = (() => {
|
||||
const DURATION = 8200;
|
||||
const FIRE = "#fb923c";
|
||||
const HOT = "#fef3c7";
|
||||
const RED = "#dc2626";
|
||||
const BODY = "#e5e7eb";
|
||||
const BODY_DARK = "#64748b";
|
||||
|
||||
/**
|
||||
* 缓入缓出曲线,用于导弹升空和 HUD 动画。
|
||||
*
|
||||
* @param {number} t 0 到 1 的进度
|
||||
* @returns {number}
|
||||
*/
|
||||
function easeInOutCubic(t) {
|
||||
return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓出曲线,用于烟尘扩散。
|
||||
*
|
||||
* @param {number} t 0 到 1 的进度
|
||||
* @returns {number}
|
||||
*/
|
||||
function easeOutCubic(t) {
|
||||
return 1 - Math.pow(1 - t, 3);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建尾焰和烟尘粒子。
|
||||
*
|
||||
* @param {number} count 粒子数量
|
||||
* @returns {Array<Record<string, number>>}
|
||||
*/
|
||||
function createParticles(count) {
|
||||
return Array.from({ length: count }, () => ({
|
||||
angle: Math.random() * Math.PI * 2,
|
||||
spread: 0.3 + Math.random() * 1.3,
|
||||
speed: 0.4 + Math.random() * 2.4,
|
||||
size: 4 + Math.random() * 18,
|
||||
alpha: 0.12 + Math.random() * 0.6,
|
||||
phase: Math.random() * Math.PI * 2,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制夜空、雷达网格和扫描线。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} w 画布宽度
|
||||
* @param {number} h 画布高度
|
||||
* @param {number} progress 播放进度
|
||||
*/
|
||||
function drawBackdrop(ctx, w, h, progress) {
|
||||
const fade = Math.min(1, progress / 0.14) * Math.min(1, (1 - progress) / 0.12);
|
||||
const sky = ctx.createLinearGradient(0, 0, 0, h);
|
||||
sky.addColorStop(0, `rgba(2,6,23,${0.86 * fade})`);
|
||||
sky.addColorStop(0.58, `rgba(15,23,42,${0.62 * fade})`);
|
||||
sky.addColorStop(1, `rgba(30,41,59,${0.26 * fade})`);
|
||||
ctx.fillStyle = sky;
|
||||
ctx.fillRect(0, 0, w, h);
|
||||
|
||||
ctx.save();
|
||||
ctx.globalAlpha = fade;
|
||||
ctx.strokeStyle = "rgba(56,189,248,0.16)";
|
||||
ctx.lineWidth = 1;
|
||||
for (let x = -w; x < w * 2; x += 72) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + progress * 120, 0);
|
||||
ctx.lineTo(x - h * 0.55 + progress * 120, h);
|
||||
ctx.stroke();
|
||||
}
|
||||
for (let y = h * 0.2; y < h; y += 46) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(0, y + Math.sin(progress * 18 + y) * 2);
|
||||
ctx.lineTo(w, y + Math.cos(progress * 14 + y) * 2);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
ctx.strokeStyle = "rgba(248,113,113,0.34)";
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.arc(w * 0.16, h * 0.76, w * (0.18 + progress * 0.22), -Math.PI * 0.95, -Math.PI * 0.12);
|
||||
ctx.stroke();
|
||||
|
||||
const beamAngle = -Math.PI * 0.85 + progress * Math.PI * 1.15;
|
||||
ctx.strokeStyle = "rgba(34,211,238,0.34)";
|
||||
ctx.lineWidth = 3;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(w * 0.16, h * 0.76);
|
||||
ctx.lineTo(w * 0.16 + Math.cos(beamAngle) * w * 0.42, h * 0.76 + Math.sin(beamAngle) * w * 0.42);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制发射井底座、光柱和冲击波。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} w 画布宽度
|
||||
* @param {number} h 画布高度
|
||||
* @param {number} progress 播放进度
|
||||
*/
|
||||
function drawLaunchPad(ctx, w, h, progress) {
|
||||
const ignition = Math.min(1, progress / 0.24);
|
||||
const pulse = Math.sin(progress * Math.PI * 12) * 0.5 + 0.5;
|
||||
const cx = w * 0.18;
|
||||
const cy = h * 0.78;
|
||||
|
||||
ctx.save();
|
||||
ctx.globalCompositeOperation = "lighter";
|
||||
const beam = ctx.createRadialGradient(cx, cy, 0, cx, cy, h * 0.42);
|
||||
beam.addColorStop(0, `rgba(251,146,60,${0.54 * ignition})`);
|
||||
beam.addColorStop(0.3, `rgba(254,243,199,${0.18 * ignition})`);
|
||||
beam.addColorStop(1, "rgba(0,0,0,0)");
|
||||
ctx.fillStyle = beam;
|
||||
ctx.fillRect(0, 0, w, h);
|
||||
|
||||
ctx.strokeStyle = `rgba(251,146,60,${(0.32 + pulse * 0.2) * ignition})`;
|
||||
ctx.lineWidth = 5;
|
||||
ctx.beginPath();
|
||||
ctx.ellipse(cx, cy, w * (0.06 + progress * 0.28), h * (0.025 + progress * 0.08), 0, 0, Math.PI * 2);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
|
||||
ctx.save();
|
||||
ctx.fillStyle = "rgba(15,23,42,0.82)";
|
||||
ctx.beginPath();
|
||||
ctx.ellipse(cx, cy + 18, w * 0.12, h * 0.035, 0, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = "rgba(148,163,184,0.7)";
|
||||
ctx.lineWidth = 3;
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制尾焰和烟尘。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {Array<Record<string, number>>} particles 粒子数组
|
||||
* @param {number} tailX 尾部 x
|
||||
* @param {number} tailY 尾部 y
|
||||
* @param {number} progress 播放进度
|
||||
*/
|
||||
function drawExhaust(ctx, particles, tailX, tailY, progress) {
|
||||
ctx.save();
|
||||
ctx.globalCompositeOperation = "lighter";
|
||||
particles.forEach((particle, index) => {
|
||||
const t = (progress * 3.2 + index * 0.013) % 1;
|
||||
const spread = easeOutCubic(t) * 118 * particle.spread;
|
||||
const x = tailX - spread * 0.62 + Math.cos(particle.angle) * spread * 0.36;
|
||||
const y = tailY + spread * 0.86 + Math.sin(particle.angle + particle.phase) * spread * 0.24;
|
||||
const alpha = particle.alpha * (1 - t);
|
||||
const radius = particle.size * (0.7 + t * 2.4);
|
||||
|
||||
ctx.globalAlpha = alpha;
|
||||
ctx.fillStyle = t < 0.34 ? HOT : t < 0.62 ? FIRE : "rgba(148,163,184,0.9)";
|
||||
ctx.shadowColor = t < 0.55 ? FIRE : "rgba(148,163,184,0.8)";
|
||||
ctx.shadowBlur = radius * 1.2;
|
||||
ctx.beginPath();
|
||||
ctx.ellipse(x, y, radius * 0.9, radius * 1.35, -0.38, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
});
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制东风-5C风格化导弹。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} x 导弹中心 x
|
||||
* @param {number} y 导弹中心 y
|
||||
* @param {number} scale 缩放比例
|
||||
* @param {number} progress 播放进度
|
||||
*/
|
||||
function drawMissile(ctx, x, y, scale, progress) {
|
||||
ctx.save();
|
||||
ctx.translate(x, y);
|
||||
// 导弹沿左下到右上的轨迹飞行,箭体头部必须朝右上,尾焰才会落在后方。
|
||||
ctx.rotate(0.62 + Math.sin(progress * 7) * 0.012);
|
||||
ctx.scale(scale, scale);
|
||||
|
||||
ctx.save();
|
||||
ctx.shadowColor = "rgba(251,146,60,0.9)";
|
||||
ctx.shadowBlur = 26;
|
||||
ctx.fillStyle = "rgba(251,146,60,0.86)";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-28, 170);
|
||||
ctx.lineTo(0, 260);
|
||||
ctx.lineTo(28, 170);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.fillStyle = "rgba(254,243,199,0.86)";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-12, 176);
|
||||
ctx.lineTo(0, 236);
|
||||
ctx.lineTo(12, 176);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
const body = ctx.createLinearGradient(-44, -178, 44, 168);
|
||||
body.addColorStop(0, "#f8fafc");
|
||||
body.addColorStop(0.45, BODY);
|
||||
body.addColorStop(1, BODY_DARK);
|
||||
ctx.fillStyle = body;
|
||||
roundRect(ctx, -42, -156, 84, 326, 40);
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = RED;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-42, -126);
|
||||
ctx.quadraticCurveTo(0, -214, 42, -126);
|
||||
ctx.lineTo(42, -92);
|
||||
ctx.lineTo(-42, -92);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = "#111827";
|
||||
ctx.fillRect(-42, -74, 84, 10);
|
||||
ctx.fillRect(-42, 74, 84, 10);
|
||||
ctx.fillStyle = "rgba(239,68,68,0.92)";
|
||||
ctx.fillRect(-42, -22, 84, 30);
|
||||
|
||||
ctx.fillStyle = "#111827";
|
||||
ctx.font = "900 30px serif";
|
||||
ctx.textAlign = "center";
|
||||
ctx.fillText("DF-5C", 0, 50);
|
||||
ctx.fillStyle = "#fef3c7";
|
||||
ctx.font = "900 20px serif";
|
||||
ctx.fillText("★", 0, -1);
|
||||
|
||||
ctx.fillStyle = "#334155";
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-42, 102);
|
||||
ctx.lineTo(-104, 166);
|
||||
ctx.lineTo(-42, 152);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(42, 102);
|
||||
ctx.lineTo(104, 166);
|
||||
ctx.lineTo(42, 152);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
|
||||
ctx.strokeStyle = "rgba(255,255,255,0.42)";
|
||||
ctx.lineWidth = 3;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-20, -112);
|
||||
ctx.lineTo(-20, 130);
|
||||
ctx.stroke();
|
||||
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制测试 HUD 文案。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} w 画布宽度
|
||||
* @param {number} h 画布高度
|
||||
* @param {number} progress 播放进度
|
||||
* @param {string} title 入场标题
|
||||
* @param {string} userInfo 用户身份信息
|
||||
*/
|
||||
function drawHud(ctx, w, h, progress, title, userInfo) {
|
||||
const enter = Math.min(1, Math.max(0, (progress - 0.1) / 0.18));
|
||||
const leave = Math.min(1, Math.max(0, (1 - progress) / 0.14));
|
||||
const alpha = easeInOutCubic(enter) * leave;
|
||||
const y = h * 0.16 - (1 - enter) * 20;
|
||||
|
||||
ctx.save();
|
||||
ctx.globalAlpha = alpha;
|
||||
ctx.textAlign = "center";
|
||||
ctx.fillStyle = "rgba(15,23,42,0.68)";
|
||||
ctx.strokeStyle = "rgba(248,113,113,0.72)";
|
||||
ctx.lineWidth = 2;
|
||||
roundRect(ctx, w * 0.5 - 350, y - 56, 700, 120, 18);
|
||||
ctx.fill();
|
||||
ctx.stroke();
|
||||
ctx.shadowColor = "rgba(248,113,113,0.95)";
|
||||
ctx.shadowBlur = 22;
|
||||
ctx.fillStyle = "#fee2e2";
|
||||
ctx.font = "700 16px serif";
|
||||
ctx.fillText("DF-5C STRATEGIC LAUNCH PREVIEW", w * 0.5, y - 24);
|
||||
ctx.fillStyle = "#fecaca";
|
||||
ctx.font = "700 18px serif";
|
||||
ctx.fillText(userInfo, w * 0.5, y + 8, 640);
|
||||
ctx.fillStyle = "#ffffff";
|
||||
ctx.font = "900 34px serif";
|
||||
ctx.fillText(title, w * 0.5, y + 45, 640);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制圆角矩形路径。
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx Canvas 上下文
|
||||
* @param {number} x 左上角 x
|
||||
* @param {number} y 左上角 y
|
||||
* @param {number} w 宽度
|
||||
* @param {number} h 高度
|
||||
* @param {number} r 圆角半径
|
||||
*/
|
||||
function roundRect(ctx, x, y, w, h, r) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y);
|
||||
ctx.lineTo(x + w - r, y);
|
||||
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
|
||||
ctx.lineTo(x + w, y + h - r);
|
||||
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
|
||||
ctx.lineTo(x + r, y + h);
|
||||
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
|
||||
ctx.lineTo(x, y + r);
|
||||
ctx.quadraticCurveTo(x, y, x + r, y);
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动东风-5C洲际导弹发射预览特效。
|
||||
*
|
||||
* @param {HTMLCanvasElement} canvas 全屏特效画布
|
||||
* @param {Function} onEnd 结束回调
|
||||
* @param {object} options 特效附加参数
|
||||
* @returns {{cancel: Function}}
|
||||
*/
|
||||
function start(canvas, onEnd, options = {}) {
|
||||
const ctx = canvas.getContext("2d");
|
||||
const w = canvas.width;
|
||||
const h = canvas.height;
|
||||
const particles = createParticles(120);
|
||||
const title = String(options.effect_title || "东风-5C 洲际导弹 升空").trim() || "东风-5C 洲际导弹 升空";
|
||||
const userInfo = String(options.effect_user_info || "").trim();
|
||||
const startTime = performance.now();
|
||||
let animId = null;
|
||||
let finished = false;
|
||||
|
||||
/**
|
||||
* 统一结束动画,手动取消时只清理不回调。
|
||||
*
|
||||
* @param {boolean} canceled 是否为手动取消
|
||||
*/
|
||||
function finish(canceled) {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
|
||||
finished = true;
|
||||
if (animId) {
|
||||
cancelAnimationFrame(animId);
|
||||
}
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
if (!canceled) {
|
||||
onEnd();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐帧绘制发射动画。
|
||||
*
|
||||
* @param {number} now 当前高精度时间
|
||||
*/
|
||||
function animate(now) {
|
||||
const progress = Math.min(1, (now - startTime) / DURATION);
|
||||
const launch = easeInOutCubic(Math.min(1, progress / 0.78));
|
||||
const launchX = w * (0.18 + launch * 0.66);
|
||||
const launchY = h * (0.78 - launch * 0.95);
|
||||
const scale = Math.min(1.08, Math.max(0.7, w / 1240));
|
||||
const tailX = launchX - Math.sin(0.62) * 168 * scale;
|
||||
const tailY = launchY + Math.cos(0.62) * 168 * scale;
|
||||
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
drawBackdrop(ctx, w, h, progress);
|
||||
drawLaunchPad(ctx, w, h, progress);
|
||||
drawExhaust(ctx, particles, tailX, tailY, progress);
|
||||
drawMissile(ctx, launchX, launchY, scale, progress);
|
||||
drawHud(ctx, w, h, progress, title, userInfo);
|
||||
|
||||
if (progress < 1) {
|
||||
animId = requestAnimationFrame(animate);
|
||||
} else {
|
||||
finish(false);
|
||||
}
|
||||
}
|
||||
|
||||
animId = requestAnimationFrame(animate);
|
||||
|
||||
return {
|
||||
cancel() {
|
||||
finish(true);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { start };
|
||||
})();
|
||||
|
||||
window.Df5cEffect = Df5cEffect;
|
||||
@@ -3,7 +3,7 @@
|
||||
*
|
||||
* 统一管理全屏 Canvas 特效的入口、防重入和资源清理。
|
||||
* 播放期间用户点击屏幕任意位置可立即结束当前全屏特效。
|
||||
* 使用方式:EffectManager.play('fireworks' | 'rain' | 'lightning' | 'snow' | 'sakura' | 'meteors' | 'gold-rain' | 'hearts' | 'confetti' | 'fireflies')
|
||||
* 使用方式:EffectManager.play('fireworks' | 'rain' | 'lightning' | 'snow' | 'sakura' | 'meteors' | 'gold-rain' | 'hearts' | 'confetti' | 'fireflies' | 'j35' | '99a' | 'df5c' | 'fujian')
|
||||
*/
|
||||
|
||||
const EffectManager = (() => {
|
||||
@@ -22,6 +22,10 @@ const EffectManager = (() => {
|
||||
hearts: { key: "hearts", load: () => import("./hearts.js") },
|
||||
confetti: { key: "confetti", load: () => import("./confetti.js") },
|
||||
fireflies: { key: "fireflies", load: () => import("./fireflies.js") },
|
||||
j35: { key: "j35", load: () => import("./j35.js") },
|
||||
"99a": { key: "99a", load: () => import("./99a.js") },
|
||||
df5c: { key: "df5c", load: () => import("./df5c.js") },
|
||||
fujian: { key: "fujian", load: () => import("./fujian.js") },
|
||||
};
|
||||
// 特效模块 Promise 缓存,同类型重复触发时复用同一次加载
|
||||
const _effectModulePromises = new Map();
|
||||
@@ -217,9 +221,9 @@ const EffectManager = (() => {
|
||||
}
|
||||
|
||||
if (playNext) {
|
||||
const nextType = _dequeueNextType();
|
||||
if (nextType) {
|
||||
play(nextType);
|
||||
const nextEffect = _dequeueNextType();
|
||||
if (nextEffect) {
|
||||
play(nextEffect.type, nextEffect.options || {});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -228,8 +232,9 @@ const EffectManager = (() => {
|
||||
* 将特效加入有限队列,同类型短时间重复触发时只保留一份。
|
||||
*
|
||||
* @param {string} type 待播放特效类型
|
||||
* @param {object} options 特效附加参数
|
||||
*/
|
||||
function _enqueue(type) {
|
||||
function _enqueue(type, options = {}) {
|
||||
const existingIndex = _queue.findIndex((item) => item.type === type);
|
||||
if (existingIndex !== -1) {
|
||||
_queue.splice(existingIndex, 1);
|
||||
@@ -237,6 +242,7 @@ const EffectManager = (() => {
|
||||
|
||||
_queue.push({
|
||||
type,
|
||||
options,
|
||||
queuedAt: Date.now(),
|
||||
keepUntilPlayed: type === "wedding-fireworks",
|
||||
});
|
||||
@@ -248,7 +254,7 @@ const EffectManager = (() => {
|
||||
/**
|
||||
* 取出下一个仍然有效的排队特效。
|
||||
*
|
||||
* @returns {string|null}
|
||||
* @returns {{type: string, options: object}|null}
|
||||
*/
|
||||
function _dequeueNextType() {
|
||||
const now = Date.now();
|
||||
@@ -256,7 +262,7 @@ const EffectManager = (() => {
|
||||
while (_queue.length > 0) {
|
||||
const next = _queue.shift();
|
||||
if (next.keepUntilPlayed || now - next.queuedAt <= QUEUED_EFFECT_TTL) {
|
||||
return next.type;
|
||||
return next;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,23 +332,25 @@ const EffectManager = (() => {
|
||||
* @param {HTMLCanvasElement} canvas 全屏特效画布
|
||||
* @param {Function} finishCurrent 当前特效结束回调
|
||||
* @param {string} startMethod 启动方法名称
|
||||
* @param {object} options 特效附加参数
|
||||
* @returns {boolean} 是否成功找到并启动特效
|
||||
*/
|
||||
function _startEffect(effectObject, canvas, finishCurrent, startMethod = "start") {
|
||||
function _startEffect(effectObject, canvas, finishCurrent, startMethod = "start", options = {}) {
|
||||
if (!effectObject || typeof effectObject[startMethod] !== "function") {
|
||||
return false;
|
||||
}
|
||||
|
||||
_bindEffectController(effectObject[startMethod](canvas, finishCurrent));
|
||||
_bindEffectController(effectObject[startMethod](canvas, finishCurrent, options));
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 播放指定特效
|
||||
*
|
||||
* @param {string} type 特效类型:fireworks / rain / lightning / snow / sakura / meteors / gold-rain / hearts / confetti / fireflies
|
||||
* @param {string} type 特效类型:fireworks / rain / lightning / snow / sakura / meteors / gold-rain / hearts / confetti / fireflies / j35 / 99a / df5c / fujian
|
||||
* @param {object} options 特效附加参数
|
||||
*/
|
||||
function play(type) {
|
||||
function play(type, options = {}) {
|
||||
if (document.hidden) {
|
||||
return;
|
||||
}
|
||||
@@ -354,19 +362,20 @@ const EffectManager = (() => {
|
||||
|
||||
// 防重入:同时只允许一个特效
|
||||
if (_current) {
|
||||
_enqueue(type);
|
||||
_enqueue(type, options);
|
||||
return;
|
||||
}
|
||||
|
||||
_play(type);
|
||||
_play(type, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载模块后播放指定特效。
|
||||
*
|
||||
* @param {string} type 特效类型
|
||||
* @param {object} options 特效附加参数
|
||||
*/
|
||||
async function _play(type) {
|
||||
async function _play(type, options = {}) {
|
||||
_current = type;
|
||||
const token = _playToken;
|
||||
|
||||
@@ -434,6 +443,18 @@ const EffectManager = (() => {
|
||||
case "fireflies":
|
||||
started = _startEffect(window.FirefliesEffect, canvas, finishCurrent);
|
||||
break;
|
||||
case "j35":
|
||||
started = _startEffect(window.J35Effect, canvas, finishCurrent, "start", options);
|
||||
break;
|
||||
case "99a":
|
||||
started = _startEffect(window.Type99AEffect, canvas, finishCurrent, "start", options);
|
||||
break;
|
||||
case "df5c":
|
||||
started = _startEffect(window.Df5cEffect, canvas, finishCurrent, "start", options);
|
||||
break;
|
||||
case "fujian":
|
||||
started = _startEffect(window.FujianEffect, canvas, finishCurrent, "start", options);
|
||||
break;
|
||||
default:
|
||||
console.warn(`[EffectManager] 未知特效类型:${type}`);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user