PacMan Grid 2D Array JAVA - java

I'm supposed to make a simple type text PacMan game in Java and for the board I have to use a 2D array to make the grid. Here are the exact directions: At program startup, constructs and displays a 2-dimensional grid using standard array(s) (no collection classes allowed) with the size dynamically specified by the user (X and Y sizes can be different). Places the PacMan in the upper-left corner of the grid facing left All grid cells should have the empty cell character of ‘.’
This is my code so far, but I keep getting errors and I'm not sure how to fix it:
public class myPacMan {
public static void main(String[] args){
Scanner input = new Scanner (System.in);
System.out.print("Choose an x value:");
int x = input.nextInt();
System.out.print("Choose a y value:");
int y = input.nextInt();
int grid [][] = new int [x][y];
int i, j = 0;
for(i=0; i<x; i++);
for(j=0; j<y; j++);
System.out.print(grid[x][y] + ".");
}
}

Two things. First, remove the semicolons after your for loops. Second, your print statement should use i and j, instead of x and y. X and Y will always be one more than your array, so you'll get an index out of bounds exception.

Related

Java battleships program: string index out of range error when converting integer to array of digits

I have to write a battleships program, where the user inputs the size of the board, which is always square, and the number of ships that there will be. They then input their board, using 0 to represent water and 1 to represent a boat, and the program has to return whether the board they have entered is correct - i.e. there are the correct number of boats, and none of the boats are touching diagonally.
I have written code which aims to let the user input each line one by one (so for example, if it is a 5x5 grid, the user will have to put in 5 different numbers of 5 digits each) and each line will be put into my bidimensional array board[][]. I will then use this to check if the board is correct.
However I keep getting a string index out of range error. I know this error occurs when the code tries to access something at an index larger than the string, but I can't work out why this is happening as I have used the 'size' variable, in which the size of the grid is stored.
Here is my code:
public static void main(String[] args) {
int ships_num;
Scanner sc;
int size;
int[][] board;
sc = new Scanner(System.in);
do {
System.out.println("Please enter the number of boats. The maximum number is 10: ");
ships_num = sc.nextInt();
} while (ships_num > 10);
System.out.println("Number of boats: " + ships_num);
do {
System.out.println("Please enter the size of the board. This value is for both the length and width: ");
size = sc.nextInt();
} while (size > 20);
System.out.println("Size of board: " + size);
board = new int[size][size];
for (int y = 0; y < size; ) {
for (int x = 0; x < size; x++) {
System.out.println("Please enter the values for the first line. Values must either be 1, to represent a boat, or 0, to represent water");
String temp = Integer.toString(sc.nextInt());
for (int i = 0; i < size;i++) {
board[y][x]=temp.charAt(i);
}
if (x == (size-1)) {
x = 0;
y++;
}
}
}
}
The specific error I keep getting is: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4. This occurs when I enter size as 5, and then put in the number 01110 for the first line.
Thank you in advance :)

2D array that player can move around

I am confused on how to print the location of the player in this array and have it update every time an input is plugged in for the direction it is moving? Currently I only get the - symbol in a 10 by 10 pattern but would like (0,0) to be an X where the player starts.
private final static int SIZEX = 10; // Board size
private final static int SIZEY = 10; // Board size
int[][] gameboard = new int[SIZEX][SIZEY];
for(int i=0; i<gameboard.length; i++)
{
for(int j=0; j<gameboard.length; j++)
{
System.out.print("-");
}
System.out.println("");
}
Use an if statement (or ternary operator) in your inner loop to print X if i and j match the x and y coordinate of the player
You could add a KeyListener to your games Component and set the x and y if the input matches the one required to move the player arround and print the position once the key is released.
To really answer your question we would need some sort of fields you have that hold the current players position

Matrix filler block

In my class we have to make a matrix filler program but I have gotten very confused on how to do so by using the user input and I don't know how to at all. Iv'e tried to start coding but can't get past step 1.
package question4;
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class MatrixFiller {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Size of Matrix: ");
Random ranGen = new Random();
int matrixSize = input.nextInt();
int a = matrixSize * matrixSize;
input.close();
int[][] myMatrix = new int[matrixSize][matrixSize];
for (int x = 0; x < matrixSize; x++) {
for (int y = 0; y < matrixSize; y++) {
myMatrix[x][y] = ranGen.nextInt(a);
System.out.print(Integer.toString(myMatrix[x][y]) + " ");
}
System.out.print("\n");
}
}
}
so i fixed the code and was wandering how can i add the zero inferno of the number like 1 and 2 so it comes out 01 and 02, do i need an if loop so that it only checks numbers less then 10?
By your example code it seems that what you are missing is basic syntax knowledge. Let me refresh your memory on arrays at the most basic level with simple language.
Arrays are like a multi-dimensional list of variables of some type.
You choose the type of variables when you declare the array.
The amount of variables which an array can hold is a constant number (the length of the array) which is defined when is is initialized.
An array can also have more than one dimensions. You set the number of dimensions when you declare the array. Think of a 1 dimensional array as a list, 2 dimensions would turn the list into a matrix. In this case, you need to set the length of each dimension (when you initialize). So, if the length of the 2 dimensions is the same you get a square, otherwise you get a rectangle.
Here is some code to go along with this:
int[] myArray;
Here I declared a 1 dimensional array which holds ints.
myArray = new int[6];
Here I initialized my array and set the length of the dimension to 6.
int[] myArray2 = new int[7];
I can also do them on the same line.
long[][] myMatrix = new long[3][2];
Here I declared a 2 dimensional array which holds longs. The lengths of the dimensions are 3 and 2, so it looks like this when you imagine it:
_ _
_ _
_ _
Now we wan to access the array at a certain position. This is done by specifying the array name and the position in each dimension you want to access, like this:
myMatrix[0][1] = 63;
Remember! The position start counting from 0, so a 2 by 3 array would have the first dimension values 0 and 1; and the second dimension values 0, 1 and 2.
Now let's iterate over an array and put the number 6 in all of its slots:
int[][] exmaple = new int[3][3]; // 2 dim. array of ints with size 3 by 3.
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
example[x][y] = 6;
}
}
Not sure if you need this, but I will mention a few additional notes:
You can initialize an array with values directly and then you don't need to specify the dimensions' lengths:
int[][] array = new int[][] {{1 ,2}, {5, 65}}; // 2 by 2
You can get the length of a dimension of an array by the syntax
array.length;
array[0].length;
array[1].length;
// etc.
These return an int which you can use as a bound when looping:
for (int i = 0; i < array.length; i++) {
// ...
}

Coordinate generation for memory card game

How can I generate (x, y) coordinates for a memory card game? Let's say I can set the number of cards, rows and columns. How would my for loop look like?
My general idea is as follows:
final int ROWS = 4;
final int COLUMNS = 5;
for(int i = 0; i<ROWS; i++){
for(int j = 0; j<COLUMNS; j++){
//calculate X coordinate
int index = some_calculation
MemoryCard memoryCard = new MemoryCard(x, y, index);
}
//calculate y coordinate
}
However, I'm having an issue creating my objects here. The above loop will go 4 times for i and 5 times for j. So, in total I have 20 objects there. But how do I get to my object's index?
Let's say I have an array list of my objects:
private ArrayList<MemoryCard> objects = new ArrayList<MemoryCard>();
//parameters for MemoryCard object are (float x, float y, Texture frontImage)
Is there a way to make this dynamic? To make the program generate proper positions if I set number of ROWS to 3 and COLUMS to 6? Or any other even pair.
you can translate easy...
public int getIndexOf(int x, int y){
return x + y * ROWS;
}
and revert as well...
public int getXFromIndex(int index){
return index%ROWS;
}
public int getYFromIndex(int index){
return index/ROWS;
}
Martin Frank already provided the correct answer to your question, but I'd like to present an alternative solution. Instead of serializing your rows and columns into a 1D array list, why not use a 2D array?
MemoryCard[][] cards = new MemoryCard[ROWS][COLUMNS];
Then you can access your card on row x and column y just like this:
MemoryCard card = cards[x][y];
Sounds like it would be better to use a 2D array which will be easier to maintain and visualize positions, something like
Objects[][] memoryCards;
Then to fill it you just use your loop.

2d array squares initialization and selection

For code optimization purposes, I want to create a 2d array that contains 40 equal squares (10x10px). Each square represents 1\40 of the displayed window (400x400px).
I populate the 2d array with the standard double for-loop methodology.
int col = 40;
int row = 40;
int boxPosition = 0; //Position of the box (coordinates)
Integer[][] boxes = new Integer[40][40];
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
boxes[i][j] = boxPosition;
boxPosition += 10; //Creates a 10px box.
}
boxPosition = 0; //Resets box size for next column
}
There are several circles in this program. We have a ship(circle) that fires missiles(circles) toward enemies(circles).
I want to run collision detection ONLY when there is a bullet + an enemy in one of the squares. This will greatly optimize the code.
The question is... how do I create these squares off of a 2d array? How do I select each square? How do I test if the missiles and the enemies are inside the same square?
Code examples are GREATLY appreicated.
Thanks.
I'm not sure what you're doing with the 2D array or why it contains Integers or why it contains an increasing size in each column, but the general way to do grid-based collision is to have a 2D array of GameObjects. A GameObject in your case could be a Ship, a Missile, or an Enemy.
When one of your GameObjects wants to move, you simply check the 2D array of GameObjects to see what is already in the square you want to move to. If it's empty, you can do the move. If it's not empty, you've got a collision.

Categories