You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

井字棋玩家胜次追踪、分数持久化与棋盘重置功能实现求助

井字棋游戏功能优化实现方案

问题分析

原代码存在两个核心问题:

  1. 分数存储共用同一个localStorage键,导致统计混乱,且页面刷新后未加载本地存储的分数
  2. 缺少页面内重置棋盘的功能,只能通过刷新页面重置

解决方案及修改代码

1. 修复分数持久化逻辑

  • 为两个玩家分别分配独立的localStorage存储键:player1Score和player2Score
  • 页面初始化时读取本地存储的分数并渲染到页面
  • 优化scoreCleaner函数,仅清空对应分数键而非整个localStorage

2. 添加「Restart Game」功能

编写重置函数,恢复游戏初始状态并清空棋盘内容

修改后的完整代码

HTML部分(需添加对应按钮)
<!-- 假设你的页面已有棋盘,添加以下按钮与分数展示区域 -->
<div class="controls">
  <button onclick="restartGame()">Restart Game</button>
  <button onclick="scoreCleaner()">Clean Score</button>
</div>
<div class="scores">
  Player 1 Score: <span id="player1Score">0</span>
  <br>
  Player 2 Score: <span id="player2Score">0</span>
</div>
JavaScript部分
let board = ["", "", "", "", "", "", "", "", ""];
let playerTime = 0;
let gameOver = false;

let symbols = ["o", "x"];

let winStates = [
  [0,1,2],
  [3,4,5],
  [6,7,8],
  [0,3,6],
  [1,4,7],
  [2,5,8],
  [0,4,8],
  [2,4,6]
];

function handleMove(position) {
  if (gameOver) {
    return;
  }

  if (board[position] === "") {
    board[position] = symbols[playerTime];
    gameOver = isWin();

    if (!gameOver) {
      playerTime = playerTime === 0 ? 1 : 0;
    }
  }
  return gameOver;
}

function isWin() {
  for (let i = 0; i < winStates.length; i++) {
    let seq = winStates[i];
    let pos1 = seq[0];
    let pos2 = seq[1];
    let pos3 = seq[2];

    if (board[pos1] === board[pos2] && board[pos1] === board[pos3] && board[pos1] !== "") {
      return true;
    }
  }
  return false;
}
document.addEventListener("DOMContentLoaded", ()=>{
  // 页面加载时初始化显示分数
  initScores();

  let squares = document.querySelectorAll(".square");
  squares.forEach((square) => {
    square.addEventListener("click", handleClick);
  });
});

function handleClick(event) {
  let square = event.target;
  let position = square.id;

  if (handleMove(position)) {
    setTimeout(()=> {
      alert(`Game is Over. Player ${playerTime + 1} wins.`);
    }, 10);

    // 根据获胜玩家更新对应分数
    if (playerTime === 0) {
      count1();
    } else {
      count2();
    }
  }
  updateSquare(position);
}

function updateSquare(position) {
  let square = document.getElementById(position.toString());
  let symbol = board[position];
  square.innerHTML = symbol ? `<div class='${symbol}'></div>` : "";
}

// 初始化页面分数显示
function initScores() {
  const p1Score = localStorage.getItem("player1Score") || 0;
  const p2Score = localStorage.getItem("player2Score") || 0;
  document.getElementById("player1Score").textContent = p1Score;
  document.getElementById("player2Score").textContent = p2Score;
}

// 玩家1分数统计
function count1() {
  let currentScore = Number(localStorage.getItem("player1Score")) || 0;
  currentScore += 1;
  localStorage.setItem("player1Score", currentScore);
  document.getElementById("player1Score").textContent = currentScore;
}

// 玩家2分数统计
function count2() {
  let currentScore = Number(localStorage.getItem("player2Score")) || 0;
  currentScore += 1;
  localStorage.setItem("player2Score", currentScore);
  document.getElementById("player2Score").textContent = currentScore;
}

// 清空分数
function scoreCleaner() {
  localStorage.removeItem("player1Score");
  localStorage.removeItem("player2Score");
  document.getElementById("player1Score").textContent = 0;
  document.getElementById("player2Score").textContent = 0;
}

// 重置游戏
function restartGame() {
  // 重置游戏状态
  board = ["", "", "", "", "", "", "", "", ""];
  playerTime = 0;
  gameOver = false;

  // 清空所有棋盘格子内容
  document.querySelectorAll(".square").forEach(square => {
    square.innerHTML = "";
  });
}

关键修改说明

  1. 分数存储优化:用player1Score和player2Score两个独立键存储分数,避免统计冲突;页面加载时调用initScores读取本地分数并显示,解决刷新后分数归零问题。
  2. 重置游戏功能:restartGame函数重置游戏核心变量,同时遍历清空所有棋盘格子的内容,实现页面内重置。
  3. 细节优化:删除了原代码中无用的c1、c2变量;修改获胜提示为更清晰的Player X wins;updateSquare函数处理空值情况,避免渲染空的div。

内容的提问来源于stack exchange,提问作者Benolísio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 17:33:25