1024 Java游戏:向随机磁贴添加数字
我是一名java初学者,试图为大学作业实现1024个游戏的代码。我一直在尝试将数字1添加到网格中的两个随机单元格中。游戏有点不同。不打印网格4x4,而是根据用户的偏好打印网格。我下面的代码将数字1添加到每个磁贴,因为它们都是空的,但是如何将数字添加到2个随机磁贴 随后的每一轮,网格中的一个未占用单元都会添加一个“1”平铺,因此,在每轮结束时,我需要列出所有空闲单元,并使用该列表随机选择一个空闲单元 我该怎么做?在我的代码中,我尝试计数每个空单元格,但将“1”添加到2个随机平铺中不起作用1024 Java游戏:向随机磁贴添加数字,java,Java,我是一名java初学者,试图为大学作业实现1024个游戏的代码。我一直在尝试将数字1添加到网格中的两个随机单元格中。游戏有点不同。不打印网格4x4,而是根据用户的偏好打印网格。我下面的代码将数字1添加到每个磁贴,因为它们都是空的,但是如何将数字添加到2个随机磁贴 随后的每一轮,网格中的一个未占用单元都会添加一个“1”平铺,因此,在每轮结束时,我需要列出所有空闲单元,并使用该列表随机选择一个空闲单元 我该怎么做?在我的代码中,我尝试计数每个空单元格,但将“1”添加到2个随机平铺中不起作用 int
int count = 0;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j] == 0) {
++count;
}
if (count == 0) {
return;
}
int location = r.nextInt(count);
int newTile = 1;
board[i][j] = newTile;
}
}
int count=0;
对于(int i=0;i
尝试以下操作:
public class Main
{
public static void main(String[] args) {
//Create random genertor
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
//Get user input
System.out.println("Enter a legth");
int length = input.nextInt();
System.out.println("Enter a width");
int width = input.nextInt();
//Initialize board (4x4)
int[][] board = new int[length][width];
//Segment to generate two different points on the board
int randomCoordinateXOne = randomGenerator.nextInt(length);
int randomCoordinateYOne = randomGenerator.nextInt(width);
int randomCoordinateXTwo = randomGenerator.nextInt(length);
int randomCoordinateYTwo = randomGenerator.nextInt(width);
while (randomCoordinateXOne == randomCoordinateXTwo && randomCoordinateXTwo == randomCoordinateYTwo) {
randomCoordinateXTwo = randomGenerator.nextInt(length);
randomCoordinateYTwo = randomGenerator.nextInt(width);
}
//Iterate through the board
for (int i = 0; i < length; i++) {
for (int j = 0; j < width; j++) {
//If the current space is one of the two selected above, put a 1 in that spot
if ((i == randomCoordinateXOne && j == randomCoordinateYOne) || (i == randomCoordinateXTwo && j == randomCoordinateYTwo)) {
board[i][j] = 1;
}
//Otherwise, put a 0
else {
board[i][j] = 0;
}
//Used to visualize result
System.out.print(board[i][j]);
}
//Used to visualize result
System.out.println();
}
}
}
让我知道这是否有帮助。如果答案正确,请将其标记为正确。代码中有注释,但是如果您有任何问题,请告诉我 我想我解释得不对。您将电路板设置为4x4,但在我的代码中,网格基于用户的输入。(int dimension=in.NextInt())。我还需要计算整个游戏中有多少可用的瓷砖。@IzabellaWnuk不用担心。我会更新代码。应该没那么难。到目前为止还有什么问题吗?@IzabellaWnuk答案已更新。让我知道它是否有效是的,非常感谢。
import java.util.Scanner;
import java.util.Random;