新手程序员在这里,使用Java 8.我正在尝试构建一个PacMan游戏并正在研究构建网格的方法。我对该计划的开场评论告诉您需要知道的一切。我一直试图将随机#generator的变量连接到打印相同数量的cookie(" O"),并用点填充数组的其余部分(" ;"。)
/**
* This program is meant to get dimensions for a 2D array from the player.
* A grid is then displayed to player's specs filled with dots and cookies.
* The cookies must compose 20% of the total grid and be randomly
* distributed. The user will then be offered a menu of options to either
* turn left or right, or move, or exit the game. The player's choice moves
* "PacMan" around grid to eat cookies. The grid must be displayed throughout
* the game showing changes as player continues moves. If a cookie is eaten,
* a statement is printed that indicates a cookie was eaten and adds 1 to
* your score. At the end of the game, it tracks the number of moves it took
* to eat all the cookies.
*/
import java.util.Scanner;
public class PacManGame
{
public static void main(String[] args)
{
int X, Y; //Variables for number of grid rows X, and columns Y
Scanner input = new Scanner( System.in );
System.out.println();
System.out.print( "Enter the number of rows you would like in your game grid: " );
X = input.nextInt();
System.out.println();
System.out.print( "Enter the number of columns you would like in your game grid: " );
Y = input.nextInt();
System.out.println();
buildGrid(X, Y); // Calls buildGrid method
} // Closes main method
public static void buildGrid(int X, int Y) // Method for actually building the grid
{
int gameGrid [][] = new int [X][Y]; // Array built from user's input for dimensions
int totalGridSize = X * Y; // Gets the total grid size
double cookieTotal = totalGridSize * (.2); // Calculates the 20% of cookies that will be on grid
int theCookies = (int)(cookieTotal*Math.random())+1; //Assigns the randomly generated number
int i, j, k = 0; // Initialize loop counters
for (i = 0; i < X; i++)
{
for (j = 0; j < Y; j++)
{
gameGrid[X][Y] = k;
k++;
System.out.print("." + ("O" * theCookies)); // I know I can't do this, but how to fix?
}
}
} // Closes buildGrid method
} // Closes PacManGame class
答案 0 :(得分:2)
交换数组坐标会更好,因此首先Y
,然后是X
。您可以在数组1中保留cookie,其余为0。要放置cookieTotal
个Cookie,您可以使用以下代码:
new Random().ints(0, totalGridSize).distinct().limit(cookieTotal)
.forEach(pos -> gameGrid[pos/X][pos%X] = 1);
我们在此处生成从0
到totalGridSize-1
的随机数,并使cookieTotal
与其不同。之后,我们将这些数字转换为坐标并设置相应的数组元素。
要打印游戏区域,您需要将0翻译为'.'
,将1翻译为"O"
:
for (int[] row : gameGrid)
System.out.println(IntStream.of(row).mapToObj(val -> val == 1 ? "O" : ".")
.collect(Collectors.joining()));
这是buildGrid
的完整正文:
int gameGrid[][] = new int[Y][X];
int totalGridSize = X * Y;
int cookieTotal = totalGridSize / 5;
new Random().ints(0, totalGridSize).distinct().limit(cookieTotal)
.forEach(pos -> gameGrid[pos / X][pos % X] = 1);
for (int[] row : gameGrid)
System.out.println(IntStream.of(row).mapToObj(val -> val == 1 ? "O" : ".")
.collect(Collectors.joining()));