java - 将程序代码转换为面向对象的技巧

标签 java eclipse oop

我一直在以程序化的方式构建四子棋游戏。有人可以就如何将这段代码转换为面向对象的状态提出一些建议吗?这将是我第一次尝试面向对象,因此将不胜感激任何建议/提示。

我知道我需要将代码分成不同的类以使其面向对象,所以我正在考虑创建一个 Board 和 Main 类。这足够了还是我应该考虑更多的类(class)?

我一直在阅读有关界面的内容,并且也在考虑为游戏玩家(人类玩家和计算机玩家)使用一个界面,但我不确定执行此操作的最佳方法。

ConnectFourGame.java:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

public class ConnectFourGame {

int totalPlayed;
int[][] gameBoard;
final int widthOfBoard=7;
final int heightOfBoard=7;

public ConnectFourGame(){
    gameBoard = new int[widthOfBoard][widthOfBoard];
    totalPlayed=0;
}

public static void main(String args[])throws IOException{
    
    ConnectFourGame Connect4 = new ConnectFourGame();
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
    System.out.println("Welcome to Connect 4");
    System.out.println("There are 2 players red and yellow");
    System.out.println("Player 1 is Red, Player 2 is Yellow");
    System.out.println("To play the game type in the number of the boardColumn you want to drop you counter in");
    System.out.println("A player wins by connecting 4 counters in a row - vertically, horizontally or diagonally");
    System.out.println("");
    Connect4.printBoard();
    outer:
        
    while(true){
        
        int boardColumn = 0;
        
        //Player One Logic
        while(true){
        System.out.println("");
        System.out.println("Player 1, please select your column:");
        boardColumn = Integer.parseInt(br.readLine());
            if(Connect4.canMakeMove(boardColumn)){
                if(Connect4.placeCounter(boardColumn, 1)){
                    Connect4.printBoard();
                    System.out.println("\n\nPlayer 1 wins!!!");
                    break outer;
                }
                break;
            }
            else
                System.out.println("Column "+boardColumn+" is already full!!");
        }
        Connect4.printBoard();
        
        //PLAYER 2.    
        while(true){
        System.out.println("");
        System.out.println("Player 2, please select your column");
        
        Random r = new Random();
        int num = r.nextInt(7);
        
        boardColumn=num;
        
        
            if(Connect4.canMakeMove(boardColumn)){
                if(Connect4.placeCounter(boardColumn, 2)){
                    Connect4.printBoard();
                    System.out.println("\n\nPlayer 2 wins!!!");
                    break outer;
                }
                break;
            }
            else
                System.out.println("Column "+boardColumn+" is already full!!");
        }
        Connect4.printBoard();
        
        if(Connect4.gameTied()){
            System.out.print("The game has ended in a draw. Please start the game again.");
            break;
        }
    }
}
            
public void printBoard(){
    for(int i=0;i<gameBoard.length;i++){
        for(int j=0;j<gameBoard[0].length;j++){
            if(gameBoard[i][j] == 0)
                System.out.print(".  ");
            else
                System.out.print(gameBoard[i][j]+"  ");
        }
        System.out.println("");
    }
    System.out.println("*  *  *  *  *  *  *");
    System.out.println("0  1  2  3  4  5  6");
}

public boolean placeCounter(int boardColumn, int playerNum){
    int i=0;
    for(i=0;i<widthOfBoard;i++){
        if(gameBoard[i][boardColumn] == 1 || gameBoard[i][boardColumn] == 2){
            gameBoard[i-1][boardColumn]=playerNum;
            break;
        }
    }
    if(i == widthOfBoard)
        gameBoard[i-1][boardColumn]=playerNum;
    
    totalPlayed++;
    return isConnected(i-1,boardColumn);
}

public boolean canMakeMove(int boardColumn){
    return gameBoard[0][boardColumn] == 0; 
}

public boolean gameTied(){
    return totalPlayed == widthOfBoard*widthOfBoard;
}

public void isHorizontal() {
    
}

public boolean isConnected(int x, int y){
    int num=gameBoard[x][y];
    int count=0;
    int i=y;
    
    //HORIZONTAL.
    while(i<widthOfBoard && gameBoard[x][i] == num){
        count++;
        i++;
    }
    i=y-1;
    while(i>=0 && gameBoard[x][i] == num){
        count++;
        i--;
    }
    if(count == 4)
        return true;
    
    //VERTICAL.
    count=0;
    int j=x;
    while(j<widthOfBoard && gameBoard[j][y] == num){
        count++;
        j++;
    }
    if(count == 4)
        return true;
    
    //SECONDARY DIAGONAL.
    count=0;
    i=x;
    j=y;
    while(i<widthOfBoard && j<widthOfBoard && gameBoard[i][j] == num){
        count++;
        i++;
        j++;
    }
   
    if(count == 4)
        return true;
    
    //LEADING DIAGONAL.
    count=0;
    i=x;
    j=y;
    while(i<widthOfBoard && j>=0 && gameBoard[i][j] == num){
        count++;
        i++;
        j--;
    }
   
    if(count == 4)
        return true;
    
    return false;
}
}

最佳答案

Board 类将是一个很好的开始。它可以有将圆盘放入具有特定颜色的柱中的方法。

Player 类可以跟踪玩家名称和颜色。

两种颜色的 Color 枚举。

Game 类可以跟踪哪些玩家以及轮到谁,并且可以检查棋盘是否获胜或平局。

游戏

private Board board;
private Player[] players;
private Player currentPlayer;

void reset();  // Resets game
Player getCurrentPlayer();
Player isGameWon();  // Returns player that won, or null if nobody won
boolean isGameOver();  // Returns true if no more moves can be made

// Places a disc, throws exception if it is not players turn.
// This delegates to the Board class, and advances the turn.
void placeDisc(Player player, int column);        

董事会

private Color[][] squares;

void clear();
void placeDisc(Color color, int column);  // Place a disc, throws exception if column full
boolean isColumnFull(int column);  // Could come in handy...
Color getDiscAt(int x, int y);  // Returns coloe of disc at location, or null if none

颜色

An enum (RED, YELLOW) ?

public enum Color {RED, YELLOW}

玩家

private String name;
private Color color;

String getName();
Color getColor();

关于java - 将程序代码转换为面向对象的技巧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55991888/

相关文章:

java web start 无法在第二次运行时启动

java,通过扫描仪方法输入double值,带小数的数字返回错误

python - 概括类方法,根据条件执行略有不同的操作

每次都接受一个随机参数的 JavaScript 函数

java - 对象可以通过注释扩展功能吗? (SugarORM 示例)

java - 重试 asynctask 的最佳 java 实践 (android)

java - Eclipse 调试器,为特定(!)对象的字段设置观察点

eclipse - 线程 "main"java.lang.NoClassDefFoundError : com/google/common/base/Preconditions 中的异常

eclipse - 如何将 Google 的 Guava 添加到 eclipse 以便我可以阅读源代码

java - 在 Eclipse 中设置 Android 开发工具