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

如何在足球阵容达到11人后禁止添加更多球员?

足球阵容创建器:实现总人数11人限制

我正在开发一款足球阵容创建器,用户可选择门将、后卫、3种不同类型的中场及前锋,各位置最大人数限制已正常生效。但我希望当阵容球员总数达到11人时,禁止用户继续添加球员。

当前尝试的方案存在问题:用while循环包裹代码后无法添加任何球员;添加if (homeTeam.squad.length === 11)判断时,会出现无需输入球员姓名即可添加的问题。

解决思路

  1. 准确计算总人数:squad是对象不是数组,不能直接用length,需手动统计:门将存在则算1人,其他位置取对应数组长度求和。
  2. 调整校验顺序:先检查阵容是否已满,再验证球员姓名,避免逻辑冲突。
  3. 优化状态更新:仅在球员添加成功时更新球衣号码,避免无效递增。

修改后的代码

const [error, setError] = useState(null);
const [homeTeam, setHomeTeam] = useState(
    localStorage.getItem("homeTeam") === null
        ? {
          squad: {
            gk: null,
            df: [],
            cdm: [],
            cm: [],
            cam: [],
            fw: []
          },
          style: {
            color: `#${state.homeTeamColor}`,
            numberColor: `#${state.homeTeamNumberColor}`,
            nameColor: `#${state.nameColor}`
          }
        }
        : JSON.parse(localStorage.getItem("homeTeam"))
    );

// 计算当前阵容总人数
const getTotalPlayers = () => {
  let total = 0;
  if (homeTeam.squad.gk) total += 1;
  total += homeTeam.squad.df.length;
  total += homeTeam.squad.cdm.length;
  total += homeTeam.squad.cm.length;
  total += homeTeam.squad.cam.length;
  total += homeTeam.squad.fw.length;
  return total;
};

const addPlayer = () => {
    setError(null);
    const totalPlayers = getTotalPlayers();

    // 先检查阵容是否已满
    if (totalPlayers >= 11) {
      setError("阵容已满,无法添加更多球员!");
      return;
    }

    // 再检查球员姓名是否为空
    if (playerName === "") {
      setError("必须输入球员姓名!");
      return;
    }

    // 创建球员对象
    let playerObj = {
      id: nanoid(),
      number: number,
      name: playerName,
      color:
        playerTeam === "homeTeam"
          ? `#${state.homeTeamColor}`
          : `#${state.awayTeamColor}`,
      numberColor:
        playerTeam === "homeTeam"
          ? `#${state.homeTeamNumberColor}`
          : `#${state.awayTeamNumberColor}`,
      namecolor: `#${state.nameColor}`
    };

    // 按位置添加球员
    if (playerTeam === "homeTeam") {
      if (playerPosition === "gk") {
        if (homeTeam.squad.gk !== null) {
          setError("门将位置已满!");
        } else {
          playerObj.onClick = () => playerRemove("homeTeam", "gk", playerObj.id);
          setHomeTeam((homeTeam) => ({
            ...homeTeam,
            squad: { ...homeTeam.squad, gk: playerObj }
          }));
          setNumber(number + 1);
        }
      } else if (playerPosition === "df") {
        if (homeTeam.squad.df.length === 5) {
          setError("后卫位置已满!");
        } else {
          playerObj.onClick = () => playerRemove("homeTeam", "df", playerObj.id);
          setHomeTeam((homeTeam) => ({
            ...homeTeam,
            squad: {
              ...homeTeam.squad,
              df: [...homeTeam.squad.df, playerObj]
            }
          }));
          setNumber(number + 1);
        }
      }
      // 其他位置逻辑可按此格式补充
    }
};

关键说明

  • 用getTotalPlayers函数准确统计人数,解决原代码中直接访问对象length的错误。
  • 校验失败后用return终止函数,避免后续无效代码执行。
  • 将setNumber(number + 1)移到每个位置添加成功的分支内,避免添加失败时号码仍递增。

内容的提问来源于stack exchange,提问作者Zaid Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:33:31