diff --git a/app/Enums/CurrencySource.php b/app/Enums/CurrencySource.php index 1c62907..6a04e2a 100644 --- a/app/Enums/CurrencySource.php +++ b/app/Enums/CurrencySource.php @@ -158,6 +158,9 @@ enum CurrencySource: string /** 购买头像框消耗(扣除金币) */ case AVATAR_FRAME_BUY = 'avatar_frame_buy'; + /** 猜成语游戏奖励 */ + case GAME_REWARD = 'game_reward'; + /** * 返回该来源的中文名称,用于后台统计展示。 */ @@ -210,6 +213,7 @@ enum CurrencySource: string self::MSG_TEXT_COLOR_BUY => '文字颜色购买', self::MSG_DECORATION_BUY => '消息装扮购买(旧)', self::AVATAR_FRAME_BUY => '头像框购买', + self::GAME_REWARD => '猜成语奖励', }; } } diff --git a/app/Events/IdiomGameAnswered.php b/app/Events/IdiomGameAnswered.php new file mode 100644 index 0000000..da6eaa8 --- /dev/null +++ b/app/Events/IdiomGameAnswered.php @@ -0,0 +1,59 @@ +roomId), + ]; + } + + public function broadcastWith(): array + { + return [ + 'round_id' => $this->roundId, + 'answer' => $this->answer, + 'winner_username' => $this->winnerUsername, + 'reward_gold' => $this->rewardGold, + 'reward_exp' => $this->rewardExp, + ]; + } +} diff --git a/app/Events/IdiomGameStarted.php b/app/Events/IdiomGameStarted.php new file mode 100644 index 0000000..ae54350 --- /dev/null +++ b/app/Events/IdiomGameStarted.php @@ -0,0 +1,63 @@ +roomId), + ]; + } + + /** + * 广播数据 + */ + public function broadcastWith(): array + { + return [ + 'round_id' => $this->roundId, + 'hint' => $this->hint, + 'reward_gold' => $this->rewardGold, + 'reward_exp' => $this->rewardExp, + 'message' => "🧩 猜成语时间!{$this->hint}", + ]; + } +} diff --git a/app/Http/Controllers/Admin/IdiomController.php b/app/Http/Controllers/Admin/IdiomController.php new file mode 100644 index 0000000..52ca264 --- /dev/null +++ b/app/Http/Controllers/Admin/IdiomController.php @@ -0,0 +1,122 @@ +orderBy('id')->get(); + + return view('admin.idioms.index', compact('idioms')); + } + + /** + * 创建新题目 + */ + public function store(Request $request): RedirectResponse + { + $data = $request->validate([ + 'answer' => 'required|string|max:50', + 'hint' => 'required|string|max:255', + 'sort' => 'required|integer|min:0', + 'is_active' => 'boolean', + ]); + + $data['is_active'] = $request->boolean('is_active', true); + Idiom::create($data); + + return redirect()->route('admin.idioms.index')->with('success', '成语题目已添加!'); + } + + /** + * 更新题目 + */ + public function update(Request $request, Idiom $idiom): RedirectResponse + { + $data = $request->validate([ + 'answer' => 'required|string|max:50', + 'hint' => 'required|string|max:255', + 'sort' => 'required|integer|min:0', + 'is_active' => 'boolean', + ]); + + $data['is_active'] = $request->boolean('is_active'); + $idiom->update($data); + + return redirect()->route('admin.idioms.index')->with('success', "题目「{$idiom->answer}」已更新!"); + } + + /** + * 切换启用/禁用(AJAX) + */ + public function toggle(Idiom $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(Idiom $idiom): RedirectResponse + { + $answer = $idiom->answer; + $idiom->delete(); + + return redirect()->route('admin.idioms.index')->with('success', "题目「{$answer}」已删除!"); + } + + /** + * 保存猜成语游戏参数(仅更新 GameConfig params,不影响其他字段) + */ + public function saveSettings(Request $request): RedirectResponse + { + $data = $request->validate([ + 'reward_gold' => 'required|integer|min:0', + 'reward_exp' => 'required|integer|min:0', + 'auto_start_interval' => 'required|integer|min:0', + ]); + + $config = \App\Models\GameConfig::firstOrCreate( + ['game_key' => 'idiom'], + ['name' => '猜成语', 'icon' => '🧩', 'enabled' => false], + ); + + // 合并现有 params,只覆盖提交的字段,不影响其他已有参数 + $existingParams = $config->params ?? []; + $config->params = array_merge($existingParams, [ + 'reward_gold' => (int) $data['reward_gold'], + 'reward_exp' => (int) $data['reward_exp'], + 'auto_start_interval' => (int) $data['auto_start_interval'], + ]); + $config->save(); + $config->clearCache(); + + return redirect()->route('admin.idioms.index')->with('success', '游戏参数已保存!'); + } +} diff --git a/app/Http/Controllers/IdiomQuizController.php b/app/Http/Controllers/IdiomQuizController.php new file mode 100644 index 0000000..5f3c2b6 --- /dev/null +++ b/app/Http/Controllers/IdiomQuizController.php @@ -0,0 +1,267 @@ +id !== 1 && ! $request->user()?->activePosition)) { + return response()->json(['status' => 'error', 'message' => '无权限'], 403); + } + + $roomId = (int) $request->input('room_id', 0); + if ($roomId <= 0) { + return response()->json(['status' => 'error', 'message' => '缺少房间 ID'], 422); + } + + // 检查是否有进行中的回合 + $activeRound = IdiomGameRound::where('room_id', $roomId) + ->whereIn('status', ['pending', 'active']) + ->first(); + if ($activeRound) { + return response()->json([ + 'status' => 'error', + 'message' => '当前房间已有进行中的猜成语题目,请先结束当前回合。', + ], 400); + } + + // 随机选一道启用的题目 + $idiom = Idiom::where('is_active', true)->inRandomOrder()->first(); + if (! $idiom) { + return response()->json(['status' => 'error', 'message' => '题库中没有可用的题目,请先在后台添加。'], 400); + } + + // 读取游戏配置 + $config = GameConfig::forGame('idiom'); + $params = $config?->params ?? []; + $rewardGold = (int) ($params['reward_gold'] ?? 50); + $rewardExp = (int) ($params['reward_exp'] ?? 30); + + // 创建新回合 + $round = IdiomGameRound::create([ + 'room_id' => $roomId, + 'idiom_id' => $idiom->id, + 'status' => 'active', + 'reward_gold' => $rewardGold, + 'reward_exp' => $rewardExp, + 'started_at' => now(), + ]); + + // 广播到聊天室 + broadcast(new IdiomGameStarted( + roomId: $roomId, + hint: $idiom->hint, + roundId: $round->id, + rewardGold: $rewardGold, + rewardExp: $rewardExp, + )); + + // 同时也推一条 MessageSent 消息(显示在聊天窗口) + $msg = [ + 'id' => $this->chatState->nextMessageId($roomId), + 'room_id' => $roomId, + 'from_user' => '星海小博士', + 'to_user' => '大家', + 'content' => "🧩 猜成语时间!{$idiom->hint}", + 'is_secret' => false, + 'font_color' => '#7c3aed', + 'action' => '', + 'idiom_game_round_id' => $round->id, + 'idiom_reward_gold' => $rewardGold, + 'idiom_reward_exp' => $rewardExp, + 'sent_at' => now()->toDateTimeString(), + ]; + $this->chatState->pushMessage($roomId, $msg); + broadcast(new \App\Events\MessageSent($roomId, $msg)); + + return response()->json([ + 'status' => 'success', + 'data' => [ + 'round_id' => $round->id, + 'hint' => $idiom->hint, + 'reward_gold' => $rewardGold, + 'reward_exp' => $rewardExp, + ], + ]); + } + + /** + * 提交答案(POST) + * + * @param Request $request + * @return JsonResponse + */ + public function answer(Request $request): JsonResponse + { + $user = Auth::user(); + if (! $user) { + return response()->json(['status' => 'error', 'message' => '请先登录'], 401); + } + + $roundId = (int) $request->input('round_id'); + $userAnswer = trim((string) $request->input('answer', '')); + $roomId = (int) $request->input('room_id'); + + if ($roundId <= 0 || $userAnswer === '' || $roomId <= 0) { + return response()->json(['status' => 'error', 'message' => '参数不完整'], 422); + } + + // 查找回合 + $round = IdiomGameRound::with('idiom')->find($roundId); + if (! $round || $round->room_id !== $roomId) { + return response()->json(['status' => 'error', 'message' => '回合不存在'], 404); + } + + if ($round->status !== 'active') { + if ($round->status === 'answered') { + return response()->json([ + 'status' => 'error', + 'message' => "这道题已被「{$round->winner_username}」抢先答对了!", + ], 400); + } + return response()->json(['status' => 'error', 'message' => '该回合已结束'], 400); + } + + // 校验答案(忽略空格和全半角) + $normalizedAnswer = str_replace(' ', '', $userAnswer); + $normalizedCorrect = str_replace(' ', '', $round->idiom->answer); + if (mb_strtolower($normalizedAnswer) !== mb_strtolower($normalizedCorrect)) { + return response()->json([ + 'status' => 'error', + 'message' => '答案不正确,再想想!', + ], 200); + } + + // 答对了!加锁防并发(Redis) + $lockKey = "idiom:answer_lock:{$roundId}"; + if (! \Illuminate\Support\Facades\Redis::setnx($lockKey, 1)) { + return response()->json([ + 'status' => 'error', + 'message' => "这道题已被「{$round->winner_username}」抢先答对了!", + ], 400); + } + \Illuminate\Support\Facades\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, + "猜成语答对「{$round->idiom->answer}」奖励", + $roomId, + ); + } + if ($round->reward_exp > 0) { + $user->exp_num = ($user->exp_num ?? 0) + $round->reward_exp; + $user->save(); + } + + // 广播结果 + broadcast(new IdiomGameAnswered( + roomId: $roomId, + roundId: $round->id, + answer: $round->idiom->answer, + winnerUsername: $user->username, + rewardGold: $round->reward_gold, + rewardExp: $round->reward_exp, + )); + + // 推 MessageSent 系统通知 + $resultMsg = [ + 'id' => $this->chatState->nextMessageId($roomId), + 'room_id' => $roomId, + 'from_user' => '星海小博士', + 'to_user' => '大家', + 'content' => "🎉 恭喜 {$user->username} 率先答对成语「{$round->idiom->answer}」,获得 {$round->reward_gold} 金币、{$round->reward_exp} 经验!", + 'is_secret' => false, + 'font_color' => '#16a34a', + 'action' => '', + 'sent_at' => now()->toDateTimeString(), + ]; + $this->chatState->pushMessage($roomId, $resultMsg); + broadcast(new \App\Events\MessageSent($roomId, $resultMsg)); + + \Illuminate\Support\Facades\Redis::del($lockKey); + + return response()->json([ + 'status' => 'success', + 'message' => "🎉 回答正确!获得 {$round->reward_gold} 金币、{$round->reward_exp} 经验!", + 'data' => [ + 'answer' => $round->idiom->answer, + 'reward_gold' => $round->reward_gold, + 'reward_exp' => $round->reward_exp, + ], + ]); + } + + /** + * 查询当前进行中的回合 + */ + public function current(Request $request): JsonResponse + { + $roomId = (int) $request->input('room_id', 0); + if ($roomId <= 0) { + return response()->json(['status' => 'error', 'message' => '缺少房间 ID'], 422); + } + + $round = IdiomGameRound::with('idiom') + ->where('room_id', $roomId) + ->whereIn('status', ['pending', 'active']) + ->first(); + + if (! $round) { + return response()->json(['status' => 'success', 'data' => null]); + } + + return response()->json([ + 'status' => 'success', + 'data' => [ + 'round_id' => $round->id, + 'hint' => $round->idiom?->hint ?? '', + 'reward_gold' => $round->reward_gold, + 'reward_exp' => $round->reward_exp, + ], + ]); + } +} diff --git a/app/Models/Idiom.php b/app/Models/Idiom.php new file mode 100644 index 0000000..1601aa1 --- /dev/null +++ b/app/Models/Idiom.php @@ -0,0 +1,33 @@ + 'boolean', + 'sort' => 'integer', + ]; + } +} diff --git a/app/Models/IdiomGameRound.php b/app/Models/IdiomGameRound.php new file mode 100644 index 0000000..7ce1c99 --- /dev/null +++ b/app/Models/IdiomGameRound.php @@ -0,0 +1,46 @@ + 'integer', + 'reward_exp' => 'integer', + 'started_at' => 'datetime', + 'ended_at' => 'datetime', + ]; + } + + public function idiom(): BelongsTo + { + return $this->belongsTo(Idiom::class); + } +} diff --git a/database/migrations/2026_04_28_210001_create_idioms_table.php b/database/migrations/2026_04_28_210001_create_idioms_table.php new file mode 100644 index 0000000..fb0f128 --- /dev/null +++ b/database/migrations/2026_04_28_210001_create_idioms_table.php @@ -0,0 +1,41 @@ +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'); + } +}; diff --git a/database/migrations/2026_04_28_210002_create_idiom_game_rounds_table.php b/database/migrations/2026_04_28_210002_create_idiom_game_rounds_table.php new file mode 100644 index 0000000..3771a53 --- /dev/null +++ b/database/migrations/2026_04_28_210002_create_idiom_game_rounds_table.php @@ -0,0 +1,49 @@ +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'); + } +}; diff --git a/database/seeders/GameConfigSeeder.php b/database/seeders/GameConfigSeeder.php index e368428..9f6cb5f 100644 --- a/database/seeders/GameConfigSeeder.php +++ b/database/seeders/GameConfigSeeder.php @@ -169,6 +169,20 @@ class GameConfigSeeder extends Seeder 'super_issue_inject' => 20000, // 超级期系统注入金额上限 ], ], + + // ─── 猜成语 ─────────────────────────────────────────────── + [ + 'game_key' => 'idiom', + 'name' => '猜成语', + 'icon' => '🧩', + 'description' => '管理员手动出题或系统定时自动出题,用户抢答成语,第一个答对的获得金币和经验奖励。', + 'enabled' => false, + 'params' => [ + 'reward_gold' => 50, // 答对奖励金币 + 'reward_exp' => 30, // 答对奖励经验 + 'auto_start_interval' => 0, // 自动出题间隔(分钟,0=手动) + ], + ], ]; foreach ($games as $game) { diff --git a/database/seeders/IdiomSeeder.php b/database/seeders/IdiomSeeder.php new file mode 100644 index 0000000..f887965 --- /dev/null +++ b/database/seeders/IdiomSeeder.php @@ -0,0 +1,30 @@ + $item) { + Idiom::create([ + 'answer' => $item['answer'], + 'hint' => $item['hint'], + 'is_active' => true, + 'sort' => $i, + ]); + } + + $this->command->info('已导入 '.count($idioms).' 条成语题目。'); + } +} diff --git a/resources/js/chat-room.js b/resources/js/chat-room.js index 7d910f9..6b46045 100644 --- a/resources/js/chat-room.js +++ b/resources/js/chat-room.js @@ -291,6 +291,10 @@ import { bindChatInitialStateControls } from "./chat-room/initial-state.js"; // 拍一拍模块 import "./chat-room/pat.js"; +// 猜成语游戏模块 +import "./chat-room/idiom-quiz.js"; +import { bindIdiomQuizControls } from "./chat-room/idiom-quiz.js"; + // 斜杠命令菜单 import { bindSlashCommands, registerSlashCommand } from "./chat-room/slash-commands.js"; @@ -778,4 +782,5 @@ if (typeof window !== "undefined") { bindChatBotControls(); bindGuestbookControls(); bindFeedbackControls(); + bindIdiomQuizControls(); } diff --git a/resources/js/chat-room/chat-events.js b/resources/js/chat-room/chat-events.js index 057e481..3814435 100644 --- a/resources/js/chat-room/chat-events.js +++ b/resources/js/chat-room/chat-events.js @@ -366,6 +366,41 @@ export function bindChatEvents() { } enqueueChatMessage(msg); + // 猜成语消息:追加【答题】按钮 + if (msg.idom_game_round_id || msg.idiom_game_round_id) { + const roundId = msg.idom_game_round_id || msg.idiom_game_round_id; + const hint = msg.content || ""; + const rewardGold = msg.idiom_reward_gold || 0; + const rewardExp = msg.idiom_reward_exp || 0; + + // 延迟等消息渲染完成再追加按钮 + setTimeout(() => { + const containers = [ + document.getElementById("chat-messages-container"), + document.getElementById("chat-messages-container2"), + ]; + containers.forEach((container) => { + if (!container) return; + const lastMsg = container.lastElementChild; + if (!lastMsg || lastMsg.querySelector("[data-idiom-answer-btn]")) return; + if (lastMsg.dataset.fromUser !== "星海小博士") return; + + const btn = document.createElement("button"); + btn.type = "button"; + btn.dataset.idiomAnswerBtn = String(roundId); + btn.dataset.idiomHint = hint; + btn.dataset.idiomGold = String(rewardGold); + btn.dataset.idiomExp = String(rewardExp); + btn.textContent = "🎯 答题"; + btn.style.cssText = + "margin-left:8px;padding:2px 12px;background:linear-gradient(135deg,#7c3aed,#a78bfa);" + + "color:#fff;border:none;border-radius:999px;font-size:11px;cursor:pointer;" + + "font-weight:bold;vertical-align:middle;"; + lastMsg.appendChild(btn); + }); + }, 50); + } + if (msg.action === "vip_presence" && typeof window.showVipPresenceBanner === "function") { window.showVipPresenceBanner(msg); } @@ -470,6 +505,20 @@ export function bindChatEvents() { } }); + // chat:idiom-started — 猜成语出题 + window.addEventListener("chat:idiom-started", (e) => { + if (typeof window.handleIdiomGameStarted === "function") { + window.handleIdiomGameStarted(e); + } + }); + + // chat:idiom-answered — 猜成语答题结果 + window.addEventListener("chat:idiom-answered", (e) => { + if (typeof window.handleIdiomGameAnswered === "function") { + window.handleIdiomGameAnswered(e); + } + }); + // Echo 级监听器(延迟绑定,等待 Echo 就绪) document.addEventListener("DOMContentLoaded", () => { setupScreenClearedListener(); diff --git a/resources/js/chat-room/idiom-quiz.js b/resources/js/chat-room/idiom-quiz.js new file mode 100644 index 0000000..60c9b04 --- /dev/null +++ b/resources/js/chat-room/idiom-quiz.js @@ -0,0 +1,215 @@ +// 猜成语游戏前端模块 +// 监听 IdiomGameStarted / IdiomGameAnswered 事件,提供答题弹窗功能 + +function csrf() { + return document.querySelector('meta[name="csrf-token"]')?.content ?? ""; +} + +let currentRoundId = 0; +let currentRoomId = 0; + +/** + * 收到猜成语出题事件时,在聊天窗口显示提示消息。 + */ +function handleIdiomGameStarted(e) { + const { round_id, hint, reward_gold, reward_exp, message } = e.detail || {}; + if (!round_id || !hint) return; + + currentRoundId = round_id; + currentRoomId = window.chatContext?.roomId || 0; + + // 追加一条聊天室消息(由 MessageSent 事件负责渲染,不重复添加) + // 这里只存储当前回合信息 + console.log(`猜成语开始:${hint},奖励 ${reward_gold}金/${reward_exp}经验`); +} + +/** + * 收到猜成语结果事件。 + */ +function handleIdiomGameAnswered(e) { + const { answer, winner_username, reward_gold, reward_exp } = e.detail || {}; + if (!answer) return; + + currentRoundId = 0; + + // 如果当前用户打开答题弹窗但被别人抢先了,关闭弹窗 + const answerModal = document.getElementById("idiom-answer-modal"); + if (answerModal && answerModal.style.display !== "none") { + answerModal.style.display = "none"; + window.chatToast?.show({ + title: "被抢先了", + message: `${winner_username} 率先答对了「${answer}」,下次加油!`, + icon: "😅", + color: "#f59e0b", + duration: 4000, + }); + } +} + +/** + * 打开答题弹窗。 + */ +function openIdiomAnswerModal(roundId, hint, rewardGold, rewardExp) { + currentRoundId = roundId; + currentRoomId = window.chatContext?.roomId || 0; + + const modal = document.getElementById("idiom-answer-modal"); + if (!modal) return; + + const hintEl = document.getElementById("idiom-answer-hint"); + const rewardEl = document.getElementById("idiom-answer-reward"); + if (hintEl) hintEl.textContent = hint; + if (rewardEl) rewardEl.textContent = `🎁 答对奖励:${rewardGold} 金币 + ${rewardExp} 经验`; + + 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("/idiom-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, + }), + }); + + const data = await response.json(); + + if (data.status === "success") { + feedbackEl.textContent = data.message || "🎉 回答正确!"; + feedbackEl.style.color = "#16a34a"; + input.disabled = true; + + // 延迟关闭弹窗 + setTimeout(() => { + closeIdiomAnswerModal(); + }, 2000); + } else { + feedbackEl.textContent = data.message || "答案不正确"; + feedbackEl.style.color = "#ef4444"; + 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; + + const roundId = parseInt(btn.dataset.idiomAnswerBtn || "0", 10); + const hint = btn.dataset.idiomHint || ""; + const rewardGold = parseInt(btn.dataset.idiomGold || "0", 10); + const rewardExp = parseInt(btn.dataset.idiomExp || "0", 10); + + if (roundId > 0) { + openIdiomAnswerModal(roundId, hint, rewardGold, rewardExp); + } + }); +} + +// ── 挂载到 window ── +window.openIdiomAnswerModal = openIdiomAnswerModal; +window.closeIdiomAnswerModal = closeIdiomAnswerModal; +window.submitIdiomAnswer = submitIdiomAnswer; +window.handleIdiomGameStarted = handleIdiomGameStarted; +window.handleIdiomGameAnswered = handleIdiomGameAnswered; diff --git a/resources/js/chat.js b/resources/js/chat.js index d0d58e8..8e0e614 100644 --- a/resources/js/chat.js +++ b/resources/js/chat.js @@ -269,6 +269,16 @@ export function initChat(roomId) { console.log("拍一拍:", e); window.dispatchEvent(new CustomEvent("chat:pat", { detail: e })); }) + // 监听猜成语出题 + .listen("IdiomGameStarted", (e) => { + console.log("猜成语:", e); + window.dispatchEvent(new CustomEvent("chat:idiom-started", { detail: e })); + }) + // 监听猜成语答题结果 + .listen("IdiomGameAnswered", (e) => { + console.log("猜成语结果:", e); + window.dispatchEvent(new CustomEvent("chat:idiom-answered", { detail: e })); + }) // 监听任命公告(礼花 + 隆重弹窗) .listen("AppointmentAnnounced", (e) => { console.log("任命公告:", e); diff --git a/resources/views/admin/idioms/index.blade.php b/resources/views/admin/idioms/index.blade.php new file mode 100644 index 0000000..55cb0cc --- /dev/null +++ b/resources/views/admin/idioms/index.blade.php @@ -0,0 +1,331 @@ +@extends('admin.layouts.app') + +@section('title', '猜成语题库管理') + +@section('content') + @php require resource_path('views/admin/partials/list-theme.php'); @endphp + + @php + $idiomPayload = $idioms->mapWithKeys( + fn($item) => [ + (string) $item->id => [ + 'id' => $item->id, + 'answer' => $item->answer, + 'hint' => $item->hint, + 'sort' => $item->sort, + 'is_active' => (bool) $item->is_active, + 'update_url' => route('admin.idioms.update', $item->id), + 'toggle_url' => route('admin.idioms.toggle', $item->id), + ], + ], + ); + + $idiomConfig = \App\Models\GameConfig::forGame('idiom'); + $idiomParams = $idiomConfig?->params ?? []; + @endphp + + + +
+ 管理猜成语游戏的题目库,共 {{ $idioms->count() }} 条题目 +
+| 排序 | +成语答案 | +谜语提示 | +状态 | +操作 | +
|---|---|---|---|---|
| {{ $item->sort }} | +{{ $item->answer }} | +{{ $item->hint }} | ++ + | ++ + + | +