萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現拼圖遊戲完整教學:背景定位切圖與碰撞檢測

jQuery 拼圖遊戲核心算法:CSS 背景定位切圖 + 位置校驗

不切圖、不 Canvas,純 CSS background-position 實現拼圖切片,配合 jQuery 動畫與位置校驗,構建流暢的拼圖遊戲。

核心設計思路

  1. 單圖切片:一張大圖 (600×600) 作為背景,通過 background-position 顯示不同區域
  2. 網格座標預計算:生成布局座標陣列 (left/top) 與背景座標陣列 (x/y)
  3. 隨機打亂:Fisher-Yates 洗牌算法隨機分配布局位置
  4. 點擊交換:雙擊選中 → 再次點擊目標 → 動畫交換位置
  5. 勝利判定:當前位置 === 目標位置,所有塊匹配則通關

核心類實現 (GyPuzzleGame)

function GyPuzzleGame(option) {
  this.$target = $(option.target);      // 容器
  this.imgSrc = option.data;            // 大圖路徑
  this.count = option.count || 16;      // 總塊數 (默認 4×4=16)
  this.cols = option.cols || 4;         // 列數
  this.rows = option.rows || 4;         // 行數
  this.pieceSize = 600 / this.cols;     // 單塊尺寸
  this.layout = [];                     // 目標布局座標
  this.bgPos = [];                      // 背景定位座標
  this.$pieces = $();                   // 拼圖塊 jQuery 集合
  this.init();
}

GyPuzzleGame.prototype = {
  init() {
    this.calcPositions();
    this.createPieces();
    this.bindEvents();
  },
  
  // 預計算所有位置
  calcPositions() {
    const coords = [];
    for (let i = 0; i < this.cols; i++) coords.push(-i * this.pieceSize); // [0, -150, -300, -450]
    
    for (let i = 0; i < this.count; i++) {
      const col = i % this.cols;
      const row = Math.floor(i / this.cols);
      // 目標布局位置 (用於勝利判定)
      this.layout[i] = { left: col * (this.pieceSize + 1), top: row * (this.pieceSize + 1) };
      // 背景定位 (用於顯示正確圖片區域)
      this.bgPos[i] = { x: coords[col], y: coords[row], index: i };
    }
  },
  
  // 創建打亂後的拼圖塊
  createPieces() {
    const shuffled = this.shuffle([...this.layout]); // 打亂布局順序
    this.$target.empty();
    
    for (let i = 0; i < this.count; i++) {
      const bg = this.bgPos[i];
      const pos = shuffled[i];
      
      const $piece = $('
') .css({ left: pos.left, top: pos.top, width: this.pieceSize, height: this.pieceSize, 'background-image': `url(${this.imgSrc})`, 'background-position': `${bg.x}px ${bg.y}px`, position: 'absolute', cursor: 'pointer', border: '1px solid #4CAF50', boxSizing: 'border-box' }) .attr('data-target-index', i) // 目標索引 (勝利判定用) .attr('data-current-index', i); // 當前位置索引 this.$target.append($piece); } this.$pieces = this.$target.find('.puzzle-piece'); }, // Fisher-Yates 洗牌 shuffle(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array; }, bindEvents() { const _this = this; let $selected = null; this.$pieces.on('click', function() { const $this = $(this); // 動畫中禁止操作 if (_this.$pieces.is(':animated')) return; if ($selected && $selected[0] === $this[0]) { // 取消選中 $selected.removeClass('selected').find('.selector').remove(); $selected = null; } else if ($selected) { // 交換位置 const fromIdx = _this.$pieces.index($selected); const toIdx = _this.$pieces.index($this); _this.swapPieces($selected, $this, fromIdx, toIdx); $selected = null; } else { // 選中 $selected = $this.addClass('selected').append('
✓
'); } }); }, swapPieces($a, $b, fromIdx, toIdx) { const _this = this; const posA = $a.position(); const posB = $b.position(); // 更新 data-index $a.attr('data-current-index', toIdx); $b.attr('data-current-index', fromIdx); // 動畫交換 $a.css('z-index', 10).animate({ left: posB.left, top: posB.top }, 300); $b.css('z-index', 10).animate({ left: posA.left, top: posA.top }, 300, function() { $a.css('z-index', '').removeClass('selected').find('.selector').remove(); $b.css('z-index', ''); _this.checkWin(); }); }, checkWin() { let correct = 0; this.$pieces.each(function() { const target = parseInt($(this).attr('data-target-index')); const current = parseInt($(this).attr('data-current-index')); if (target === current) correct++; }); if (correct === this.count) { this.$target.append('
恭喜通關!
'); this.options.success && this.options.success(this.$target); } } }; // 使用 new GyPuzzleGame({ target: '#puzzle-container', data: 'images/puzzle.jpg', count: 16, success: ($el) => console.log('勝!') });

關鍵 CSS

#puzzle-container {
  position: relative;
  width: 604px;  /* (150+1)*4 = 604 */
  height: 604px;
  margin: 20px auto;
  border: 2px solid #333;
  overflow: hidden;
}
.puzzle-piece {
  transition: left .3s, top .3s; /* 可選:CSS 動畫替代 jQuery animate */
}
.piece-selected { box-shadow: inset 0 0 0 3px #4CAF50; }
.selector { position: absolute; top: 5px; right: 5px; background: #4CAF50; color: #fff; padding: 2px 6px; border-radius: 3px; }
.win-overlay { position: absolute; inset: 0; background: rgba(0,0,0,.8); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 32px; z-index: 100; }

擴展方向

  • 計時/步數統計:記錄開始時間、移動次數
  • 難度等級:3×3, 4×4, 5×5, 自定義圖片上傳
  • 自動求解:A* 算法演示最優解
  • 觸摸支持:觸摸事件適配移動端
  • 碎片旋轉:增加旋轉角度屬性,點擊旋轉 90°

這個實現展示了「CSS 背景定位 + 絕對定位 + 座標校驗」這一經典拼圖架構的精髓。

copyright © 萬盛學電腦網 all rights reserved