赛事生成器开发问题:同一轮次单队参赛次数限两次以内
解决方案:限制单轮次队伍参赛次数不超过两次
你的赛事生成器当前的核心问题是原编排逻辑会让同一队伍在单轮次中重复参赛多次(比如队伍A会在第一轮里和所有其他队伍配对),完全不符合单轮次参赛不超两次的要求。下面是修复后的代码,同时优化了赛事编排的合理性:
修改后的完整代码
const btn = document.querySelector('#submitbtn') const section = document.querySelector('#containertimes') btn.addEventListener("click", function(event){ event.preventDefault() const numTimes = parseInt(document.querySelector('#js-input-times').value) section.innerHTML = '' for(let i = 1; i <= numTimes; i++){ const input = document.createElement("input") input.type = "text" input.id = "nome-time-" + i // 修复原代码ID重复问题 input.name = "time-" + i input.placeholder = "Nome do time " + i input.required = true section.appendChild(input) } const submitButton = document.createElement("button") submitButton.type = "submit" submitButton.innerText = "Gerar Jogos" submitButton.addEventListener('click', gerarJogos) section.appendChild(submitButton) }) function shuffle(array) { let currentIndex = array.length, randomIndex; while (currentIndex != 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; [array[currentIndex], array[randomIndex]] = [ array[randomIndex], array[currentIndex]]; } return array; } function gerarJogos() { const nomeTime = Array.from(document.querySelectorAll("[name^='time-']")).map(input => input.value.trim()); const totalTimes = nomeTime.length; // 处理奇数队伍:添加虚拟轮空队伍,保证每轮对阵数量匹配 let times = [...nomeTime]; if (totalTimes % 2 !== 0) { times.push('轮空'); } const adjustedTotal = times.length; const totalRodadas = adjustedTotal - 1; let todasRodadas = []; // 生成每一轮的对阵组合 for (let rodada = 0; rodada < totalRodadas; rodada++) { const rodadaAtual = []; const usedTeams = new Set(); for (let i = 0; i < adjustedTotal; i++) { if (usedTeams.has(times[i])) continue; // 找到当前队伍的有效配对对手 let opponentIndex = (i + rodada + 1) % adjustedTotal; while (usedTeams.has(times[opponentIndex]) || opponentIndex === i) { opponentIndex = (opponentIndex + 1) % adjustedTotal; } // 添加对阵记录,标记已使用的队伍 rodadaAtual.push(`${times[i]} x ${times[opponentIndex]}`); usedTeams.add(times[i]); usedTeams.add(times[opponentIndex]); } // 随机打乱本轮对阵顺序 todasRodadas.push(shuffle(rodadaAtual)); } // 生成最终展示的HTML内容 let resultado = ''; todasRodadas.forEach((rodada, index) => { resultado += `<strong>Rodada ${index + 1}</strong><br>`; rodada.forEach(jogo => { // 优化轮空显示格式 resultado += jogo.replace(' x 轮空', ' (轮空)').replace('轮空 x ', '') + '<br>'; }); resultado += '<br><br>'; }); section.innerHTML = resultado; }
关键修改说明
- 核心逻辑重构:替换原有的错误配对逻辑,采用循环赛标准编排方式,确保每轮每个队伍最多参赛1次(完全满足“参赛次数不超两次”的要求)
- 奇数队伍兼容:自动处理队伍数量为奇数的情况,添加轮空机制保证赛事编排合理性
- DOM元素修复:修正原代码中所有输入框ID重复的问题,避免潜在DOM操作冲突
- 体验优化:随机打乱每轮对阵顺序,同时优化轮空队伍的显示格式,更贴合赛事习惯
内容的提问来源于stack exchange,提问作者Roger Woellner
相关产品推荐
相关产品推荐

