java - 我将如何在我的代码中使用抽象类或接口来减少重复?
问题描述
我目前正在尝试为基本的连接四游戏重构我的代码。
我注意到我的 play.java 文件中有很多重复,关于知道哪个玩家在水平或垂直方向创建了获胜模式。
由于水平和垂直的获胜标准保持不变,我将如何创建抽象类或接口以最大程度地减少代码重复?
播放.java
public class play {
private Connect4Game connect;
public play(Connect4Game connect) {
this.connect=connect;
}
public void playGame() {
System.out.println("Welcome to Connect 4");
System.out.println("To play the game type in the number of the column you want to drop you counter in");
System.out.println("Player One = r Player 2 = y");
System.out.println("");
board boardObj = new board(connect);
boardObj.printBoard();
boolean win = false;
while(!win){
// player 1
String userInput = getUserInput();
int move = Integer.parseInt(userInput);
counter counterObj = new counter(connect);
counterObj.placeCounter('r', move);
boolean hasWon = false;
int count = 0;
// check horizontal
for(int i=0; i<connect.board.length; i++){
for(int j=0; j<connect.board[i].length; j++){
if(connect.board[i][j] == 'r'){
count = count + 1;
if(count == 4){
hasWon = true;
}
}
else{
count = 0;
}
}
}
// check vertical
count = 0;
for(int i=0; i<connect.board[0].length; i++){
for(int j=0; j<connect.board.length; j++){
if(connect.board[j][i] == 'r'){
count = count + 1;
if(count >= 4){
hasWon = true;
}
}
else{
count = 0;
}
}
}
boardObj.printBoard();
if(hasWon){
win = true;
System.out.println("You Have Won!!!");
}
else {
//player 2
userInput = getUserInput();
move = Integer.parseInt(userInput);
counterObj.placeCounter('y',move);
hasWon = false;
count = 0;
// check horizontal
for(int i=0; i<connect.board.length; i++){
for(int j=0; j<connect.board[i].length; j++){
if(connect.board[i][j] == 'y'){
count = count + 1;
if(count >= 4){
hasWon = true;
}
}
else{
count = 0;
}
}
}
// check vertical
count = 0;
for(int i=0; i<connect.board[0].length; i++){
for(int j=0; j<connect.board.length; j++){
if(connect.board[j][i] == 'y'){
count = count + 1;
if(count >= 4){
hasWon = true;
}
}
else{
count = 0;
}
}
}
boardObj.printBoard();
if(hasWon){
win = true;
System.out.println("You Have Won!!!");
}
}
}
}
public String getUserInput(){
String toReturn = null;
try{
toReturn = connect.input.readLine();
}
catch(Exception e){
}
return toReturn;
}
}
解决方案
在这种情况下,两者都无济于事。抽象类将用于建立大多数子类支持的预定方法。它还将包括方法的方法签名,这些方法在实现可能不同的情况下很有用,具体取决于该类的使用方式。即使这样,也可以根据需要覆盖预定义的方法。
接口通过签名(抽象方法声明)简单地形式化所需的方法,以便类实现以强制用户和类之间的合同。
由于您没有创建多个类,因此没有任何好处。
我可以推荐的最好的方法是将您的水平和垂直检查合并到方法中,并根据需要添加其他方法以减少重复代码。
推荐阅读
- javascript - 数组中的初始化程序,但我想用变量控制数组中的每个对象
- ssl - C# SDK - ASP.NET Core 2.1 - 无法建立 SSL 连接
- python - 在 Exchange 中设置 is_read 而不读取整个对象
- python - 已定义函数中未解析的引用
- excel - 是否有以下解决方案:我的 vbscript 出现错误:“Microsoft Excel:范围类的自动过滤方法失败”
- swift - 在锁定屏幕上使用 PushKit 和 CallKit 在后台启动应用程序时连接到 WebRTC 后没有声音
- reactjs - 在 ReactJS 中设置状态时如何渲染子组件或并行组件?
- sql - 描述适用于一个表但不适用于其他表的命令
- android - 透明的 AppBarLayout
- oracle - 如何解决 FRM 41003 :- 打开表单时无法在此处执行此功能?