sudoku.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. <template>
  2. <view class="game-container">
  3. <view class="game-header">
  4. <text class="game-title">🔳 数独</text>
  5. <view class="game-stats">
  6. <text>时间: {{ time }}秒</text>
  7. </view>
  8. </view>
  9. <view class="difficulty-select" v-if="!isPlaying">
  10. <button
  11. v-for="level in levels"
  12. :key="level.value"
  13. class="level-btn"
  14. :class="{ active: selectedLevel === level.value }"
  15. @click="selectedLevel = level.value"
  16. >
  17. {{ level.label }}
  18. </button>
  19. </view>
  20. <view class="board">
  21. <view class="row" v-for="(row, rowIndex) in board" :key="rowIndex">
  22. <view
  23. class="cell"
  24. v-for="(cell, colIndex) in row"
  25. :key="colIndex"
  26. :class="{
  27. fixed: cell.fixed,
  28. selected: isCellSelected(rowIndex, colIndex),
  29. error: cell.error
  30. }"
  31. @click="selectCell(rowIndex, colIndex)"
  32. >
  33. {{ cell.value || '' }}
  34. </view>
  35. </view>
  36. </view>
  37. <view class="number-pad" v-if="isPlaying">
  38. <button
  39. v-for="n in 9"
  40. :key="n"
  41. class="num-btn"
  42. @click="fillNumber(n)"
  43. >
  44. {{ n }}
  45. </button>
  46. <button class="num-btn clear" @click="fillNumber(0)">清空</button>
  47. </view>
  48. <view class="controls" v-if="!isPlaying">
  49. <button class="start-btn" @click="startGame">开始游戏</button>
  50. </view>
  51. <view class="result-modal" v-if="showResult">
  52. <view class="result-content">
  53. <text class="result-title">🎉 数独完成!</text>
  54. <text class="result-score">用时: {{ time }}秒</text>
  55. <text class="result-score">获得积分: {{ score }}</text>
  56. <button class="restart-btn" @click="resetGame">再来一局</button>
  57. </view>
  58. </view>
  59. </view>
  60. </template>
  61. <script>
  62. import config from '@/config.js'
  63. import { completeMiniGame, getChildren } from '../../utils/api.js'
  64. // 简单的数独生成算法
  65. function generateSudoku(level) {
  66. // 基础数独解决方案
  67. const base = [
  68. [1,2,3,4,5,6,7,8,9],
  69. [4,5,6,7,8,9,1,2,3],
  70. [7,8,9,1,2,3,4,5,6],
  71. [2,3,4,5,6,7,8,9,1],
  72. [5,6,7,8,9,1,2,3,4],
  73. [8,9,1,2,3,4,5,6,7],
  74. [3,4,5,6,7,8,9,1,2],
  75. [6,7,8,9,1,2,3,4,5],
  76. [9,1,2,3,4,5,6,7,8]
  77. ]
  78. // 根据难度挖空
  79. const holes = { easy: 30, medium: 40, hard: 50 }
  80. const count = holes[level] || 30
  81. // 复制并打乱
  82. let board = JSON.parse(JSON.stringify(base))
  83. // 随机交换行和列来打乱
  84. for (let i = 0; i < 10; i++) {
  85. const r1 = Math.floor(Math.random() * 3) * 3
  86. const r2 = r1 + Math.floor(Math.random() * 3)
  87. ;[board[r1], board[r2]] = [board[r2], board[r1]]
  88. }
  89. for (let i = 0; i < 10; i++) {
  90. const c1 = Math.floor(Math.random() * 3) * 3
  91. const c2 = c1 + Math.floor(Math.random() * 3)
  92. board.forEach(row => {
  93. [row[c1], row[c2]] = [row[c2], row[c1]]
  94. })
  95. }
  96. // 挖空
  97. let cells = []
  98. for (let r = 0; r < 9; r++) {
  99. for (let c = 0; c < 9; c++) {
  100. cells.push({ r, c })
  101. }
  102. }
  103. // 随机打乱
  104. for (let i = cells.length - 1; i > 0; i--) {
  105. const j = Math.floor(Math.random() * (i + 1))
  106. ;[cells[i], cells[j]] = [cells[j], cells[i]]
  107. }
  108. for (let i = 0; i < count; i++) {
  109. const { r, c } = cells[i]
  110. board[r][c] = 0
  111. }
  112. return board
  113. }
  114. function checkSolution(board) {
  115. for (let r = 0; r < 9; r++) {
  116. for (let c = 0; c < 9; c++) {
  117. if (board[r][c] === 0) return false
  118. }
  119. }
  120. // 检查每行
  121. for (let r = 0; r < 9; r++) {
  122. const nums = new Set(board[r])
  123. if (nums.size !== 9) return false
  124. }
  125. // 检查每列
  126. for (let c = 0; c < 9; c++) {
  127. const nums = new Set()
  128. for (let r = 0; r < 9; r++) {
  129. nums.add(board[r][c])
  130. }
  131. if (nums.size !== 9) return false
  132. }
  133. // 检查3x3宫格
  134. for (let boxRow = 0; boxRow < 9; boxRow += 3) {
  135. for (let boxCol = 0; boxCol < 9; boxCol += 3) {
  136. const nums = new Set()
  137. for (let r = boxRow; r < boxRow + 3; r++) {
  138. for (let c = boxCol; c < boxCol + 3; c++) {
  139. nums.add(board[r][c])
  140. }
  141. }
  142. if (nums.size !== 9) return false
  143. }
  144. }
  145. return true
  146. }
  147. export default {
  148. data() {
  149. return {
  150. board: [],
  151. solution: [],
  152. selectedCell: null,
  153. isPlaying: false,
  154. time: 0,
  155. timer: null,
  156. showResult: false,
  157. score: 0,
  158. selectedLevel: 'easy',
  159. levels: [
  160. { label: '简单', value: 'easy' },
  161. { label: '中等', value: 'medium' },
  162. { label: '困难', value: 'hard' }
  163. ],
  164. memberId: null,
  165. taskId: null,
  166. pointsEarned: 0,
  167. newBalance: 0
  168. }
  169. },
  170. onLoad(options) {
  171. if (options.taskId) {
  172. this.taskId = parseInt(options.taskId)
  173. }
  174. if (options.memberId) {
  175. this.memberId = parseInt(options.memberId)
  176. }
  177. this.loadChildId()
  178. },
  179. onUnload() {
  180. if (this.timer) clearInterval(this.timer)
  181. },
  182. methods: {
  183. async loadChildId() {
  184. try {
  185. if (!this.memberId) {
  186. const res = await getChildren()
  187. if (res.data && res.data.length > 0) {
  188. this.memberId = res.data[0].id
  189. }
  190. }
  191. } catch (e) {
  192. console.error('获取孩子ID失败', e)
  193. }
  194. },
  195. isCellSelected(row, col) {
  196. return this.selectedCell && this.selectedCell.row === row && this.selectedCell.col === col
  197. },
  198. initBoard(data) {
  199. return data.map(row => row.map(val => ({
  200. value: val === 0 ? '' : val,
  201. fixed: val !== 0,
  202. error: false
  203. })))
  204. },
  205. startGame() {
  206. const puzzle = generateSudoku(this.selectedLevel)
  207. this.solution = puzzle
  208. this.board = this.initBoard(puzzle)
  209. this.isPlaying = true
  210. this.time = 0
  211. this.showResult = false
  212. this.timer = setInterval(() => {
  213. this.time++
  214. }, 1000)
  215. },
  216. selectCell(row, col) {
  217. if (!this.board[row][col].fixed) {
  218. this.selectedCell = { row, col }
  219. }
  220. },
  221. fillNumber(num) {
  222. if (!this.selectedCell) return
  223. const { row, col } = this.selectedCell
  224. this.board[row][col].value = num === 0 ? '' : num
  225. // 检查是否完成
  226. if (this.checkWin()) {
  227. this.finishGame()
  228. }
  229. },
  230. checkWin() {
  231. const current = this.board.map(row => row.map(cell => parseInt(cell.value) || 0))
  232. return checkSolution(current)
  233. },
  234. finishGame() {
  235. clearInterval(this.timer)
  236. this.isPlaying = false
  237. this.showResult = true
  238. // 分数计算:基础分 + 时间加成
  239. const baseScore = { easy: 60, medium: 75, hard: 90 }
  240. const base = baseScore[this.selectedLevel] || 60
  241. // 用时越短加成分越高
  242. const timeBonus = Math.max(40 - Math.floor(this.time / 10), 0)
  243. this.score = base + timeBonus
  244. // 调用API记录积分
  245. if (this.memberId) {
  246. this.submitScore()
  247. }
  248. },
  249. async submitScore() {
  250. try {
  251. const token = uni.getStorageSync('token')
  252. // 如果有taskId,说明是从任务跳转来的,使用任务完成接口
  253. if (this.taskId) {
  254. const res = await uni.request({
  255. url: config.api(`/api/tasks/${this.taskId}/complete-minigame`),
  256. method: 'POST',
  257. header: {
  258. 'Authorization': token ? `Bearer ${token}` : '',
  259. 'Content-Type': 'application/json'
  260. },
  261. data: {
  262. memberId: this.memberId,
  263. completionTime: this.time,
  264. score: this.score
  265. }
  266. })
  267. if (res.data && res.data.code === 200) {
  268. this.pointsEarned = res.data.data.pointsEarned
  269. this.newBalance = res.data.data.newBalance
  270. uni.showToast({
  271. title: `获得${this.pointsEarned}积分!`,
  272. icon: 'success'
  273. })
  274. }
  275. } else {
  276. // 普通小游戏完成
  277. const res = await completeMiniGame(this.memberId, 'sudoku', this.time, this.score)
  278. if (res.code === 200) {
  279. this.pointsEarned = res.data.pointsEarned
  280. this.newBalance = res.data.newBalance
  281. uni.showToast({
  282. title: `获得${this.pointsEarned}积分!`,
  283. icon: 'success'
  284. })
  285. }
  286. }
  287. } catch (e) {
  288. console.error('提交成绩失败', e)
  289. }
  290. },
  291. resetGame() {
  292. this.isPlaying = false
  293. this.showResult = false
  294. this.board = []
  295. this.selectedCell = null
  296. }
  297. }
  298. }
  299. </script>
  300. <style scoped>
  301. .game-container {
  302. min-height: 100vh;
  303. background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
  304. padding: 30rpx;
  305. }
  306. .game-header {
  307. text-align: center;
  308. margin-bottom: 30rpx;
  309. }
  310. .game-title {
  311. display: block;
  312. font-size: 48rpx;
  313. font-weight: bold;
  314. color: #FFE66D;
  315. }
  316. .game-stats {
  317. margin-top: 20rpx;
  318. color: #fff;
  319. font-size: 32rpx;
  320. }
  321. .difficulty-select {
  322. display: flex;
  323. justify-content: center;
  324. gap: 20rpx;
  325. margin-bottom: 30rpx;
  326. }
  327. .level-btn {
  328. background: #2a2a4a;
  329. color: #fff;
  330. padding: 15rpx 40rpx;
  331. border-radius: 30rpx;
  332. border: none;
  333. }
  334. .level-btn.active {
  335. background: #4ECDC4;
  336. color: #1a1a2e;
  337. }
  338. .board {
  339. background: #2a2a4a;
  340. padding: 10rpx;
  341. border-radius: 10rpx;
  342. display: inline-block;
  343. }
  344. .row {
  345. display: flex;
  346. }
  347. .cell {
  348. width: 70rpx;
  349. height: 70rpx;
  350. display: flex;
  351. align-items: center;
  352. justify-content: center;
  353. font-size: 36rpx;
  354. color: #fff;
  355. border: 1rpx solid rgba(255,255,255,0.1);
  356. cursor: pointer;
  357. }
  358. .cell.fixed {
  359. color: #4ECDC4;
  360. font-weight: bold;
  361. }
  362. .cell.selected {
  363. background: rgba(78, 205, 196, 0.3);
  364. }
  365. .cell.error {
  366. color: #F97316;
  367. }
  368. .number-pad {
  369. display: flex;
  370. flex-wrap: wrap;
  371. justify-content: center;
  372. gap: 15rpx;
  373. margin-top: 40rpx;
  374. }
  375. .num-btn {
  376. width: 80rpx;
  377. height: 80rpx;
  378. background: #2a2a4a;
  379. color: #fff;
  380. border-radius: 10rpx;
  381. display: flex;
  382. align-items: center;
  383. justify-content: center;
  384. font-size: 36rpx;
  385. border: none;
  386. }
  387. .num-btn.clear {
  388. background: #F97316;
  389. }
  390. .controls {
  391. text-align: center;
  392. margin-top: 40rpx;
  393. }
  394. .start-btn {
  395. background: linear-gradient(135deg, #2196F3, #4CAF50);
  396. color: #fff;
  397. padding: 20rpx 60rpx;
  398. border-radius: 50rpx;
  399. border: none;
  400. }
  401. .result-modal {
  402. position: fixed;
  403. top: 0;
  404. left: 0;
  405. right: 0;
  406. bottom: 0;
  407. background: rgba(0,0,0,0.8);
  408. display: flex;
  409. align-items: center;
  410. justify-content: center;
  411. }
  412. .result-content {
  413. background: #2a2a4a;
  414. padding: 60rpx;
  415. border-radius: 20rpx;
  416. text-align: center;
  417. }
  418. .result-title {
  419. display: block;
  420. font-size: 48rpx;
  421. color: #FFE66D;
  422. margin-bottom: 30rpx;
  423. }
  424. .result-score {
  425. display: block;
  426. color: #fff;
  427. font-size: 32rpx;
  428. margin-bottom: 20rpx;
  429. }
  430. .restart-btn {
  431. background: #4ECDC4;
  432. color: #1a1a2e;
  433. padding: 20rpx 60rpx;
  434. border-radius: 50rpx;
  435. border: none;
  436. margin-top: 30rpx;
  437. }
  438. </style>