123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471 |
- // 云函数入口文件
- const cloud = require('wx-server-sdk')
- cloud.init({
- env: cloud.DYNAMIC_CURRENT_ENV
- })
- const db = cloud.database()
- const _ = db.command
- const roomCollection = db.collection('rooms')
- const riddleCollection = db.collection('turtle_soup_riddles')
- // 云函数入口函数
- exports.main = async (event, context) => {
- const wxContext = cloud.getWXContext()
- const openid = wxContext.OPENID
-
- if (!openid) {
- return {
- code: 401,
- message: '未能获取到用户OpenID',
- }
- }
-
- const { action, roomId, riddleId, question, clue, answer } = event
-
- try {
- // 获取随机题目
- if (action === 'getRandomRiddle') {
- // 获取所有题目的总数
- const countResult = await riddleCollection.count()
- const total = countResult.total
-
- if (total === 0) {
- return {
- code: 404,
- message: '没有可用的题目',
- }
- }
-
- // 随机选择一个题目
- const random = Math.floor(Math.random() * total)
- const riddleResult = await riddleCollection.skip(random).limit(1).get()
-
- if (riddleResult.data.length === 0) {
- return {
- code: 404,
- message: '获取题目失败',
- }
- }
-
- const riddle = riddleResult.data[0]
-
- return {
- code: 200,
- message: '获取题目成功',
- data: {
- riddleId: riddle._id,
- title: riddle.title,
- description: riddle.description,
- answer: riddle.answer,
- difficulty: riddle.difficulty,
- tips: riddle.tips
- }
- }
- }
-
- // 根据ID获取题目
- else if (action === 'getRiddleById') {
- if (!riddleId) {
- return {
- code: 400,
- message: '缺少必要参数:riddleId',
- }
- }
-
- const riddleResult = await riddleCollection.doc(riddleId).get()
- const riddle = riddleResult.data
-
- return {
- code: 200,
- message: '获取题目成功',
- data: {
- riddleId: riddle._id,
- title: riddle.title,
- description: riddle.description,
- answer: riddle.answer,
- difficulty: riddle.difficulty,
- tips: riddle.tips
- }
- }
- }
-
- // 初始化房间的游戏数据
- else if (action === 'initGameData') {
- if (!roomId || !riddleId) {
- return {
- code: 400,
- message: '缺少必要参数:roomId或riddleId',
- }
- }
-
- // 获取房间信息
- const roomResult = await roomCollection.doc(roomId).get()
- const room = roomResult.data
-
- // 检查是否是房主
- if (room.hostId !== openid) {
- return {
- code: 403,
- message: '只有房主可以初始化游戏数据',
- }
- }
-
- // 获取题目信息
- const riddleResult = await riddleCollection.doc(riddleId).get()
- const riddle = riddleResult.data
-
- // 初始化游戏数据
- const gameData = {
- riddleId: riddle._id,
- title: riddle.title,
- description: riddle.description,
- answer: riddle.answer,
- questions: [],
- clues: [],
- solved: false,
- startedAt: db.serverDate(),
- hostRevealedAnswer: false
- }
-
- // 更新房间游戏数据
- await roomCollection.doc(roomId).update({
- data: {
- gameData,
- updatedAt: db.serverDate()
- }
- })
-
- return {
- code: 200,
- message: '游戏数据初始化成功',
- data: {
- roomId,
- gameData: {
- ...gameData,
- answer: undefined // 不向客户端返回答案
- }
- }
- }
- }
-
- // 提交问题(玩家向主持人提问)
- else if (action === 'submitQuestion') {
- if (!roomId || !question) {
- return {
- code: 400,
- message: '缺少必要参数:roomId或question',
- }
- }
-
- // 获取房间信息
- const roomResult = await roomCollection.doc(roomId).get()
- const room = roomResult.data
-
- // 检查房间状态
- if (room.status !== 'playing') {
- return {
- code: 400,
- message: '游戏尚未开始或已结束',
- }
- }
-
- // 检查是否是玩家(非房主)
- if (room.hostId === openid) {
- return {
- code: 403,
- message: '房主不能提交问题',
- }
- }
-
- // 检查用户是否在房间中
- const playerExists = room.players.some(p => p.userId === openid && p.status === 'active')
- if (!playerExists) {
- return {
- code: 403,
- message: '您不是该房间的成员',
- }
- }
-
- // 获取用户信息
- const playerInfo = room.players.find(p => p.userId === openid)
-
- // 添加问题到游戏数据
- const newQuestion = {
- id: Date.now().toString(),
- content: question,
- askedBy: {
- userId: openid,
- nickName: playerInfo.nickName,
- avatarUrl: playerInfo.avatarUrl
- },
- askedAt: db.serverDate(),
- status: 'pending', // pending, answered, rejected
- answer: '',
- answeredAt: null
- }
-
- const updatedGameData = room.gameData || {}
- updatedGameData.questions = [...(updatedGameData.questions || []), newQuestion]
-
- // 更新房间游戏数据
- await roomCollection.doc(roomId).update({
- data: {
- 'gameData.questions': _.push(newQuestion),
- updatedAt: db.serverDate()
- }
- })
-
- return {
- code: 200,
- message: '问题提交成功',
- data: {
- roomId,
- questionId: newQuestion.id
- }
- }
- }
-
- // 回答问题(主持人回答玩家的问题)
- else if (action === 'answerQuestion') {
- if (!roomId || !event.questionId || !event.answer || !event.status) {
- return {
- code: 400,
- message: '缺少必要参数:roomId、questionId、answer或status',
- }
- }
-
- // 获取房间信息
- const roomResult = await roomCollection.doc(roomId).get()
- const room = roomResult.data
-
- // 检查是否是房主
- if (room.hostId !== openid) {
- return {
- code: 403,
- message: '只有房主可以回答问题',
- }
- }
-
- // 查找问题在数组中的索引
- const questions = room.gameData?.questions || []
- const questionIndex = questions.findIndex(q => q.id === event.questionId)
-
- if (questionIndex === -1) {
- return {
- code: 404,
- message: '问题不存在',
- }
- }
-
- // 更新问题状态和回答
- await roomCollection.doc(roomId).update({
- data: {
- [`gameData.questions.${questionIndex}.status`]: event.status,
- [`gameData.questions.${questionIndex}.answer`]: event.answer,
- [`gameData.questions.${questionIndex}.answeredAt`]: db.serverDate(),
- updatedAt: db.serverDate()
- }
- })
-
- return {
- code: 200,
- message: '回答问题成功',
- data: {
- roomId,
- questionId: event.questionId,
- status: event.status
- }
- }
- }
-
- // 提交线索(主持人提供线索)
- else if (action === 'submitClue') {
- if (!roomId || !clue) {
- return {
- code: 400,
- message: '缺少必要参数:roomId或clue',
- }
- }
-
- // 获取房间信息
- const roomResult = await roomCollection.doc(roomId).get()
- const room = roomResult.data
-
- // 检查是否是房主
- if (room.hostId !== openid) {
- return {
- code: 403,
- message: '只有房主可以提交线索',
- }
- }
-
- // 添加线索到游戏数据
- const newClue = {
- id: Date.now().toString(),
- content: clue,
- providedAt: db.serverDate()
- }
-
- // 更新房间游戏数据
- await roomCollection.doc(roomId).update({
- data: {
- 'gameData.clues': _.push(newClue),
- updatedAt: db.serverDate()
- }
- })
-
- return {
- code: 200,
- message: '线索提交成功',
- data: {
- roomId,
- clueId: newClue.id
- }
- }
- }
-
- // 提交答案(玩家尝试解答)
- else if (action === 'submitAnswer') {
- if (!roomId || !answer) {
- return {
- code: 400,
- message: '缺少必要参数:roomId或answer',
- }
- }
-
- // 获取房间信息
- const roomResult = await roomCollection.doc(roomId).get()
- const room = roomResult.data
-
- // 检查房间状态
- if (room.status !== 'playing') {
- return {
- code: 400,
- message: '游戏尚未开始或已结束',
- }
- }
-
- // 检查是否是玩家(非房主)
- if (room.hostId === openid) {
- return {
- code: 403,
- message: '房主不能提交答案',
- }
- }
-
- // 检查用户是否在房间中
- const playerExists = room.players.some(p => p.userId === openid && p.status === 'active')
- if (!playerExists) {
- return {
- code: 403,
- message: '您不是该房间的成员',
- }
- }
-
- // 获取用户信息
- const playerInfo = room.players.find(p => p.userId === openid)
-
- // 检查答案是否正确
- const isCorrect = room.gameData.answer.toLowerCase().includes(answer.toLowerCase())
-
- // 添加答案尝试到游戏数据
- const answerAttempt = {
- id: Date.now().toString(),
- content: answer,
- submittedBy: {
- userId: openid,
- nickName: playerInfo.nickName,
- avatarUrl: playerInfo.avatarUrl
- },
- submittedAt: db.serverDate(),
- isCorrect
- }
-
- // 更新房间游戏数据
- const updateData = {
- 'gameData.answerAttempts': _.push(answerAttempt),
- updatedAt: db.serverDate()
- }
-
- // 如果答案正确,则更新游戏状态
- if (isCorrect) {
- updateData['gameData.solved'] = true
- updateData['gameData.solvedBy'] = {
- userId: openid,
- nickName: playerInfo.nickName,
- avatarUrl: playerInfo.avatarUrl
- }
- updateData['gameData.solvedAt'] = db.serverDate()
- }
-
- await roomCollection.doc(roomId).update({
- data: updateData
- })
-
- return {
- code: 200,
- message: isCorrect ? '恭喜你,回答正确!' : '答案不正确,请继续尝试',
- data: {
- roomId,
- isCorrect,
- answerId: answerAttempt.id
- }
- }
- }
-
- // 揭晓答案(主持人揭晓答案)
- else if (action === 'revealAnswer') {
- if (!roomId) {
- return {
- code: 400,
- message: '缺少必要参数:roomId',
- }
- }
-
- // 获取房间信息
- const roomResult = await roomCollection.doc(roomId).get()
- const room = roomResult.data
-
- // 检查是否是房主
- if (room.hostId !== openid) {
- return {
- code: 403,
- message: '只有房主可以揭晓答案',
- }
- }
-
- // 更新游戏数据
- await roomCollection.doc(roomId).update({
- data: {
- 'gameData.hostRevealedAnswer': true,
- 'gameData.revealedAt': db.serverDate(),
- updatedAt: db.serverDate()
- }
- })
-
- return {
- code: 200,
- message: '答案已揭晓',
- data: {
- roomId,
- answer: room.gameData.answer
- }
- }
- }
-
- else {
- return {
- code: 400,
- message: '无效的action参数',
- }
- }
- } catch (error) {
- console.error('海龟汤游戏操作失败:', error)
- return {
- code: 500,
- message: '操作失败: ' + error.message,
- }
- }
- }
|