返回

从无到有:用 JavaScript 创建五子棋游戏

前端

引言

五子棋是一种令人着迷的策略游戏,需要玩家运用策略和技巧来实现目标。通过本教程,我们将深入了解五子棋的原理,并使用 JavaScript 构建一个功能齐全的游戏版本。

分析

五子棋的玩法是在一个 15x15 的棋盘上进行的,玩家轮流放置黑子和白子。目标是成为第一个将五个自己的棋子连成一线的玩家。棋子可以水平、垂直或对角线相连。

实施

1. 创建棋盘

const board = new Array(15).fill(0).map(() => new Array(15).fill(0));

2. 轮流下棋

let turn = 'black';

function handleClick(row, col) {
  if (board[row][col] !== 0) {
    return;
  }

  board[row][col] = turn;

  if (turn === 'black') {
    turn = 'white';
  } else {
    turn = 'black';
  }
}

3. 检查胜利

function checkVictory() {
  for (let i = 0; i < 15; i++) {
    for (let j = 0; j < 15; j++) {
      if (
        board[i][j] !== 0 &&
        checkHorizontal(i, j) ||
        checkVertical(i, j) ||
        checkDiagonal1(i, j) ||
        checkDiagonal2(i, j)
      ) {
        return board[i][j];
      }
    }
  }

  return false;
}

function checkHorizontal(row, col) {
  let count = 0;

  for (let i = col; i < 15; i++) {
    if (board[row][i] === board[row][col]) {
      count++;
    } else {
      break;
    }
  }

  if (count >= 5) {
    return true;
  }

  return false;
}

// 其他检查方向的函数类似...

增强功能

1. AI 对手

function aiMove() {
  // 查找最佳位置
  let bestMove = null;
  let bestScore = -Infinity;

  for (let i = 0; i < 15; i++) {
    for (let j = 0; j < 15; j++) {
      if (board[i][j] === 0) {
        board[i][j] = 'black';
        let score = minimax(board, 0, false);
        board[i][j] = 0;

        if (score > bestScore) {
          bestScore = score;
          bestMove = { row: i, col: j };
        }
      }
    }
  }

  // 下棋
  handleClick(bestMove.row, bestMove.col);
}

function minimax(board, depth, maximizingPlayer) {
  // 检查胜利
  const winner = checkVictory();
  if (winner !== false) {
    if (winner === 'black') {
      return 10 - depth;
    } else {
      return depth - 10;
    }
  }

  // 递归遍历所有可能的走法
  let bestScore;
  if (maximizingPlayer) {
    bestScore = -Infinity;
    for (let i = 0; i < 15; i++) {
      for (let j = 0; j < 15; j++) {
        if (board[i][j] === 0) {
          board[i][j] = 'black';
          let score = minimax(board, depth + 1, false);
          board[i][j] = 0;
          bestScore = Math.max(bestScore, score);
        }
      }
    }
  } else {
    bestScore = Infinity;
    for (let i = 0; i < 15; i++) {
      for (let j = 0; j < 15; j++) {
        if (board[i][j] === 0) {
          board[i][j] = 'white';
          let score = minimax(board, depth + 1, true);
          board[i][j] = 0;
          bestScore = Math.min(bestScore, score);
        }
      }
    }
  }

  return bestScore;
}

2. 棋盘自定义

// 创建一个自定义棋盘背景
const backgroundImage = new Image();
backgroundImage.src = 'chessboard.png';

// 覆盖棋子
const blackPiece = new Image();
blackPiece.src = 'black_piece.png';

const whitePiece = new Image();
whitePiece.src = 'white_piece.png';

结论

通过本教程,您已经了解了如何使用 JavaScript 从头开始创建五子棋游戏。从原理分析到功能实施,您已经掌握了构建此类游戏的核心概念。继续探索游戏开发的世界,解锁更多激动人心的可能性。