如何在Java中使用数组创建一个游戏棋盘?

huangapple go评论75阅读模式
英文:

How to create a game board with arrays in Java?

问题

我目前正在处理一个任务,要在Java中创建一个类似Connect 4的游戏。代码的大部分部分已经在多个不同的类中提供,并且我们需要根据提供的代码注释来构建游戏。游戏板的列是在一个类中创建的数组,然后游戏板将在另一个类中创建为由列对象填充的数组。我对Java相当新,不太确定创建游戏板的最佳方法是什么。我们还需要在网格中显示游戏板,每列都由管道边界包围,列从底部到顶部读取1-6,行从左到右读取1-7(第一列的第一个元素在左下角,最后一列的最后一个元素在右上角)。

游戏板应该如下所示:

    1 2 3 4 5 6 7 
 * ---------------
 * | | | | | | | |
 * | | | | | | | |
 * | | | | | | | |
 * | | | | | | | |
 * | |X| | | |O| |
 * |O|O|X| |X|O| |	 
 * ---------------
 *  1 2 3 4 5 6 7 

目前最迫切的问题是创建游戏板本身,但对两者都需要的帮助将不胜感激。以下是Board和Column类的内容:

public class Board {
    
    /** 棋盘的行数 */
    private final static int NUM_ROWS = 6;
    
    /** 棋盘的列数 */
    private final static int NUM_COLS = 7;
    
    /** 包含标记值的Column对象数组 */
    private Column[] board = new Column[NUM_COLS];
    
    /**
     * 遍历棋盘数组,将每个元素实例化为一个新的Column并初始化。
     */
    public Board() {
        //TODO 创建游戏板
    }
    
    /**
     * 验证列号,如果无效则输出错误消息并返回false。
     * 尝试将标记放在指定列的棋盘上,如果失败则输出错误消息并返回false。
     * 
     * @param column 要放置标记的列,有效值为1-7。
     * @param token 要放在棋盘上的标记字符,X或O。
     * @return 如果成功将标记放在列上,则返回true,否则返回false。
     */
    public boolean makeMove(int column, char token) {
        //TODO 创建放置标记的方法
    }
    
    /**
     * 通过查找完整的垂直和水平nibbles来检查计算机是否获胜。
     * 
     * @return 如果在棋盘上找到任何O的nibbles,则返回true,否则返回false。
     */
    public boolean checkVictory() {
        
        // TODO 遍历每列以检查是否获胜。
        // 提示:一旦任何列都有nibble,就可以返回true并停止进一步检查。
        
        
        // TODO:遍历每行以查找水平的nibbles
        for (int row = 1; row <= NUM_ROWS; row++) {
            // TODO:在行中遍历每列以检查列和行的值。
            // 使用计数器来跟踪找到的X或O的数量。
            // 提示:可能需要在某些时候重置计数器。
            
            
            // TODO:如果找到nibble,则返回true
            
        }
        
        // 返回false
        return false;
    }
    
    /**
     * 检查每一列,看看是否至少有4个以上的O值可以放置。
     * 检查最后一行,看看是否至少有4个O(非X)值的空间。
     * @return 如果计算机没有更多的安全走法,则返回true,否则返回false。
     */
    public boolean isFull() {
        //TODO 检查棋盘是否包含任何可能的走法
    }
    
    /**
     * 显示每列编号,以空格分隔。
     * 在网格中显示每列的每行中包含的内容。
     * 在底部再次显示列编号。
     * 示例:
     *
     *  1 2 3 4 5 6 7 
     * ---------------
     * | | | | | | | |
     * | | | | | | | |
     * | | | | | | | |
     * | | | | | | | |
     * | |X| | | |O| |
     * |O|O|X| |X|O| |	 
     * ---------------
     *  1 2 3 4 5 6 7 
     *
     *
     */
    public void display() {
        final String numDisplay = " 1 2 3 4 5 6 7 ";
        final String hr = "---------------";
        
        System.out.println(numDisplay);
        System.out.println(hr);
        
        //TODO 在这里显示游戏板
        
        System.out.println(hr);
        System.out.println(numDisplay);
    }
    
}
public class Column {

    private static final int MAX_HEIGHT = 6;
    private int height = 0;
    private char[] column;
    
    /**
     * 默认构造函数 - 初始化列数组和列数组的每个元素以包含空格。
     */
    public Column() {
        column = new char[MAX_HEIGHT];
        Arrays.fill(column, ' ');
    }
    
    /**
     * 返回指定行中的值。
     * 
     * @param row 指定的行。有效值为1-6。
     * @return 指定行中的字符,如果请求了无效的行,则为空格。
     */
    public char get(int row) {
        char foundChar;
        
        if (row >= 1 && row <= 6) {
            foundChar = column[row - 1];
        } else {
            foundChar = ' ';
        }
        return foundChar;
    }
    
    /** 将指定的标记字符放在列的顶部,增加高度,并返回true。
     * 
     * @param token 要放在棋盘上的标记字符,X或O。
     * @return 如果列中有

<details>
<summary>英文:</summary>

I am currently working on an assignment to create a Connect 4 style game in Java. A large section of the code has been provided in several different classes and we are required to build the game based on the comments for the code that is provided. The columns for the board are created as an array in one class, then the game board is to be created as an array that is populated by column objects in another class. I&#39;m quite new to Java and I am not sure what the best way to create the board is. We are also required to display the board in a grid with each column bordered by pipes with the columns reading 1-6 from bottom to top and rows reading 1-7 from left to right (first element of first column in the bottom left corner and last element of last column in the top right).

The board should look like this:

        1 2 3 4 5 6 7 
	 * ---------------
	 * | | | | | | | |
	 * | | | | | | | |
	 * | | | | | | | |
	 * | | | | | | | |
	 * | |X| | | |O| |
	 * |O|O|X| |X|O| |	 
	 * ---------------
	 *  1 2 3 4 5 6 7 

Creating the game board itself is the most pressing issue right now, but help with both would be greatly appreciated. The Board and Column classes are attached below:

    public class Board {
    	
    	/** Number of rows on the board */
    	private final static int NUM_ROWS = 6;
    	
    	/** Number of columns on the board */
    	private final static int NUM_COLS = 7;
    	
    	/** Array of Column objects, which contain token values */
    	private Column[] board = new Column[NUM_COLS];
    	
    	/**
    	 * Loop through the board array, to instantiate and initialize each element as a new Column.
    	 */
    	public Board() {
    		//TODO create game board
    	}
    	
    	/**
    	 * Validate the column number, output an error message and return false if its invalid.
    	 * Try to put the token in the specified column of the board. Output an error message and return false if it does not work.
    	 * 
    	 * @param column The column in which to place the token, valid values are 1 - 7.
    	 * @param token Token character to place on the board, an X or an O.
    	 * @return True if putting the token on the column is successful, else false.
    	 */
    	public boolean makeMove(int column, char token) {
    		//TODO create method to make a move
    	}
    	
    	/**
    	 * Checks for Computer&#39;s victory by looking for complete vertical and horizontal nibbles.
    	 * 
    	 * @return True if any nibbles of O&#39;s are found on the board, otherwise false.
    	 */
    	public boolean checkVictory() {
    		
    		// TODO Loop through each column to check for victory.
    		// hint: as soon as any column has a nibble, you can return true and stop checking further.
    		
    		
    		// TODO: Loop through each row to look for horizontal nibbles
    		for (int row = 1; row &lt;= NUM_ROWS; row++) {
    			// TODO: Loop through each column in the row to check the value of the column and row.
    			// Use a counter to track the number of X&#39;s or O&#39;s found.
    			// hint: you may need to reset the counter to 0 at some point.
    			
    			
    			// TODO: if a nibble is found, return true
    			
    		}
    		
    		// return false
    		return false;
    	}
    	
    	/**
    	 * Checks each column to see if there is room enough for at least 4 more O values.
    	 * Checks final row to see if there is room enough for at least 4 O (non-X) values.
    	 * @return True if the computer has no more safe moves, else false.
    	 */
    	public boolean isFull() {
    	    //TODO check if board contains any possible moves
    	}
    	
    	/**
    	 * Displays each column number, divided by spaces.
    	 * Displays, in a grid, the contained in each column of each row.
    	 * Displays the column numbers again at the bottom.
    	 * Example:
    	 *
    	 *  1 2 3 4 5 6 7 
    	 * ---------------
    	 * | | | | | | | |
    	 * | | | | | | | |
    	 * | | | | | | | |
    	 * | | | | | | | |
    	 * | |X| | | |O| |
    	 * |O|O|X| |X|O| |	 
    	 * ---------------
    	 *  1 2 3 4 5 6 7 
    	 *
    	 *
    	 */
    	public void display() {
    	    final String numDisplay = &quot; 1 2 3 4 5 6 7 &quot;;
    	    final String hr = &quot;---------------&quot;;
    	    
    	    System.out.println(numDisplay);
    	    System.out.println(hr);
    	    
    	    //TODO display game board here
    	    
    	    System.out.println(hr);
    	    System.out.println(numDisplay);
    	}
    	
    }

===========================================================================================

    public class Column {
    
    	private static final int MAX_HEIGHT = 6;
    	private int height = 0;
    	private char[] column;
    	
    	/**
    	 * Default constructor - initialize the column array and each element of the column array to contain a blank space.
    	 */
    	public Column() {
    		column = new char[MAX_HEIGHT];
    		Arrays.fill(column, &#39; &#39;);
    	}
    	
    	/**
    	 * Return the value in the specified row.
    	 * 
    	 * @param row The specified row. Valid values are 1 - 6. 
    	 * @return The character in the specified row, or blank if an invalid row was requested.
    	 */
    	public char get(int row) {
    	    char foundChar;
    	    
    		if (row &gt;= 1 &amp;&amp; row &lt;= 6) {
    		    foundChar = column[row - 1];
    		} else {
    		    foundChar = &#39; &#39;;
    		}
    		return foundChar;
    	}
    	
    	/** Put the specified token character at the top of the column, increments the height, and returns true.
    	 * 
    	 * @param token Token character to place on the board, an X or an O.
    	 * @return True if there is room in the column for the token, else false.
    	 */
    	public boolean put(char token) {
    	    boolean placed;
    		if (height &gt;= 0 &amp;&amp; height &lt; 6) {
    		    column[height] = token;
    		    placed = true;
    		    height++;
    		} else {
    		    placed = false;
    		}
    		return placed;
    	}
    	
    	/**
    	 * Check if the column contains a Nibble.
    	 * 
    	 * @return True if the column contains 4 or more consecutive &#39;O&#39; tokens, else false.
    	 */
    	public boolean checkVictory() {
    	    //TODO finish implementing checkVictory 
    		boolean win = false;
    		return win;
    	}
    	
    	/**
    	 * Returns the current height of the Column.
    	 * @return the height of the column
    	 */
    	public int getHeight() {
    		return this.height;
    	}
    }




</details>


# 答案1
**得分**: 3

欢迎来到StackoverflowChewyParsnips

由于这是一个作业问题我不会提供任何代码但我会帮助您解析问题并重新表述一些部分希望能帮助您理解

您有两个问题**如何表示棋盘****如何打印棋盘**

如何表示棋盘
---------------------------

答案在您的文本中

&gt; 棋盘的****是在一个类中创建的**数组**然后棋盘将在另一个类中创建为由**列对象填充的数组**

但我们需要将这个转化成Java

在您的`Column`类中您有`private char[] column`,这是第一个数组

在您的`Board`类中您有`private Column[] board = new Column[NUM_COLS]`,这是准备接收列对象的第二个数组
现在您需要用Column对象填充数组
`Board`构造函数中

    public Board() {
        //TODO 创建游戏棋盘
    }

您需要遍历数组的大小并创建新的`Column`对象
在执行此操作时请注意边界

如何打印棋盘
-----------------------

同样您需要遍历`Board`中的数组但现在还需要遍历`Column`对象中的底层数组
在这里您需要小心如何遍历网格因为您需要打印一行但您的棋盘是基于列的所以在迭代数组时需要改变这种表示方式

进一步考虑
----------------------

虽然Connect Four侧重于将棋子放入列中但可能有意义的是以列为重点构建网格但是您还需要检查行和对角线是否有棋子以及需要打印棋盘这是基于行的因此如果您不受作业结构的限制我建议使用一维数组其中包含多个提供不同视图的方法

<details>
<summary>英文:</summary>

Welcome to Stackoverflow, ChewyParsnips. 

Since this a homework question, I will not give you any code but I&#39;ll help you dissect the question and re-phrase some parts to, hopefully, help with the understanding.

You have two questions: **How to represent the board?** and **How to print the board?**


How to represent the board?
---------------------------

The answer lies in your own text:

&gt; The **columns** for the board are created as an **array** in one class, then the **game board** is to be created as an **array that is populated by column objects** in another class.

But we need to translate this into Java.

In your `Column` class, you have `private char[] column`, which is the first array.

In your `Board` class, you have `private Column[] board = new Column[NUM_COLS]`, which is the second array ready to receive column objects.
Now, you need to populate the array with Column objects.
In the `Board` constructor, i.e.,

    public Board() {
        //TODO create game board
    }

You need to run through the size of the array and make new `Column` objects.
When do this, beware of boundaries. 


How to print the board?
-----------------------

Again, you need to run through the array in the `Board`, but now also the underlying array in the `Column` object.
Here, you need to be careful with how you traverse the grid because you need to print a line but your board is based on columns, so you need to change this representation while iterating the arrays.


Further considerations
----------------------

While Connect Four is focused on dropping pieces down a column, it might make sense to structure the grid with focus on columns. However, you also need to check rows and diagonals for nibbles, and you need to print the board, which works on a row basis. So, if you weren&#39;t locked by the structure of the homework, I&#39;d recommend a one-dimensional array where you present multiple methods that give different views. 

</details>



# 答案2
**得分**: 0

你可以简单地编写
```java
public Board() {
    for(int i=0; i<board.length;i++) {
        board[i] = new Column()
    }
}

这在创建Board实例时初始化数组中的所有值。

英文:

you can simply write

public Board() {
    for(int i=0; i&lt;board.length;i++) {
        board[i] = new Column()
    }
}

This initializes all values in the array when you create an instance of Board.

huangapple
  • 本文由 发表于 2020年8月7日 00:30:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63288000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定