samedi 5 mars 2016

How do I populate an array with randomly distributed symbols?

Newbie programmer here, using Java 8. I'm trying to build a PacMan game and am working on the method that builds the grid. My opening comments for the program tell you everything you need to know. I'm stuck on trying to connect the random # generator's variable to printing an equal # of cookies ("O"), and fill the rest of the array with dots (".").

/**
* 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




Aucun commentaire:

Enregistrer un commentaire