如何在棋盘非相邻单元格放置玩家对象,确保间距至少1格?
嘿,我来帮你搞定玩家之间至少间隔一个单元格的需求!核心思路是在放置每个玩家时,不仅要检查和武器不重叠,还要验证新位置和所有已放置的玩家位置都保持足够的间距——也就是不能相邻(包括斜向相邻)。
下面是修改后的完整代码,我会在关键部分加上注释:
var question = prompt('how many players'); var numOfPlayers = parseInt(question); class Game { constructor(row, col) { this.gameBoard = []; // 初始化空棋盘 for (var i = 0; i < row; i++) { this.gameBoard[i] = []; for (var j = 0; j < col; j++) { this.gameBoard[i][j] = 'empty'; } } this.players = []; // 存储已放置玩家的位置信息 this.weapons = []; // 存储已放置武器的位置信息 } // 放置武器(保留你已实现的无重叠逻辑) placeWeapons(numWeapons) { for (let i = 0; i < numWeapons; i++) { let randomRow, randomCol; do { randomRow = Math.floor(Math.random() * this.gameBoard.length); randomCol = Math.floor(Math.random() * this.gameBoard[0].length); } while (this.gameBoard[randomRow][randomCol] !== 'empty'); this.gameBoard[randomRow][randomCol] = 'weapon'; this.weapons.push({ row: randomRow, col: randomCol }); } } // 改进后的放置玩家方法:确保玩家间距至少1个单元格 placePlayers(numPlayers) { for (let i = 0; i < numPlayers; i++) { let randomRow, randomCol; let isValidPosition; do { isValidPosition = true; // 生成随机位置 randomRow = Math.floor(Math.random() * this.gameBoard.length); randomCol = Math.floor(Math.random() * this.gameBoard[0].length); // 第一步:检查是否和武器/已放置玩家重叠(棋盘位置为空) if (this.gameBoard[randomRow][randomCol] !== 'empty') { isValidPosition = false; continue; } // 第二步:检查和所有已放置玩家的间距 for (const player of this.players) { const rowDiff = Math.abs(randomRow - player.row); const colDiff = Math.abs(randomCol - player.col); // 如果行差和列差都<=1,说明两个位置相邻(包括斜向),不合法 if (rowDiff <= 1 && colDiff <= 1) { isValidPosition = false; break; // 只要有一个玩家相邻,就不用继续检查了 } } } while (!isValidPosition); // 直到找到合法位置才退出循环 // 标记玩家位置并记录到数组 this.gameBoard[randomRow][randomCol] = `player${i + 1}`; this.players.push({ row: randomRow, col: randomCol }); } } } // 示例使用:创建8x8棋盘,放置4个武器,再放置用户指定数量的玩家 const game = new Game(8, 8); game.placeWeapons(4); game.placePlayers(numOfPlayers);
关键逻辑说明
- 位置合法性检查:分为两层,先确保位置未被武器或其他玩家占用,再验证与已有玩家的间距。
- 间距判断条件:
rowDiff <=1 && colDiff <=1会覆盖所有相邻情况(上下左右、斜对角),只要满足这个条件,就说明两个玩家离得太近,需要重新生成位置。 - 存储玩家位置:用
this.players数组记录每个玩家的坐标,方便后续快速检查间距。
另外要注意:如果你的棋盘尺寸太小(比如2x2棋盘放2个玩家),会陷入无限循环,所以可以额外加个容错判断,比如在循环次数超过一定阈值后提示用户棋盘尺寸不足。
内容的提问来源于stack exchange,提问作者KT-mongo
相关产品推荐
相关产品推荐

