C#开发井字棋游戏如何防止玩家覆盖已填充的棋盘位置
C# 井字棋禁止覆盖已占用位置实现方案
核心修改逻辑
你当前的代码仅对玩家输入做了数值范围校验,缺少对目标位置是否已被填充的判断,按以下步骤修改即可实现需求:
1. 新增位置占用校验方法
在Board类中添加公共校验方法,将玩家输入的1-9位编号转换为二维数组坐标后判断是否为空:
public bool IsPositionEmpty(int pos) { int row = (pos - 1) / 3; int col = (pos - 1) % 3; // char类型默认值为\0,代表位置未被填充 return gamee[row, col] == '\0'; }
2. 优化玩家输入校验逻辑
修改Player类中的GetPlayer1、GetPlayer2方法,新增位置占用校验规则,同时修正原有范围校验的边界错误(原规则允许输入0,实际可选位置为1-9):
修改后的GetPlayer1方法
public int GetPlayer1(Board board) { while (true) { Console.Write("Player 1,chose from the above numbers to Print X on the specific position: "); player1 = int.Parse(Console.ReadLine()); if (player1 < 1 || player1 > 9) { Console.WriteLine("Try again and enter a valid number (1-9)"); } else if (!board.IsPositionEmpty(player1)) { Console.WriteLine("This position is already occupied, please choose another one"); } else { break; } } return player1; }
修改后的GetPlayer2方法
public int GetPlayer2(Board board) { while (true) { Console.Write("Player 2,chose from the above numbers to Print O on the specific position: "); player2 = int.Parse(Console.ReadLine()); if (player2 < 1 || player2 > 9) { Console.WriteLine("Try again and enter a valid number (1-9)"); } else if (!board.IsPositionEmpty(player2)) { Console.WriteLine("This position is already occupied, please choose another one"); } else { break; } } return player2; }
3. 可选优化
你原有Main方法中的循环仅执行6次,且胜负判定后未终止流程,可修改为无限循环,触发胜负/平局条件后直接跳出:
static void Main(string[] args) { Board board = new Board(); Board.BoardNumbers(); while(true) { if(WinCondition.IsDraw(board)) { Console.WriteLine("Draw"); break; } board.GetStateOfFirstPlayer(board); board.PrintBoard(); if(WinCondition.IsFirstPlayerWon(board)) { Console.WriteLine("First Player Won"); break; } if(WinCondition.IsDraw(board)) { Console.WriteLine("Draw"); break; } board.GetStateOfSecondPlayer(board); board.PrintBoard(); if (WinCondition.IsSecondPlayerWon(board)) { Console.WriteLine("Second Player Won"); break; } } }
内容的提问来源于stack exchange,提问作者Amr Ali
相关产品推荐
相关产品推荐

