2D array that player can move around - java

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

Related

How do I populate a three-dimensional array with randomly placed predefined integers?

I am new to programming and I have an assignment in Java that asks the user to navigate a 10X10X10 cubic maze, where there must be 500 monsters randomly generated, 499 open cells, and 1 treasure chest. The treasure chest must also be randomly generated, but it cannot occur within the same spot as a monster. The program I have to write asks for user input to check a cell in the array to see if its the treasure chest. If the cell is empty, I have to give a hint as to where the treasure chest is (how many cells away and if you're in the same row, column, or page). The user gets three tries to find the treasure chest. At the end of the three tries, or if they hit a monster, the user loses and is told in what cell the chest was placed. For the purposes of the assignment, an empty cell = 0, the only cell with the treasure chest = 1, and the monster cell = 2.
I am having trouble populating the cells with only 500 monsters and one chest. My code below populates all the cells with a random amount of 0's, 1's and 2's. I need to limit the 2's to five-hundred instances, the 1's to one instance (and check beforehand to make sure a monster isn't in the cell), and keep the rest 0. I also need to make sure I'm not populating the same cell with more than one monster. This is as far as I've got:
import java.util.Random;
public class FindTheCheese
{
public static void main(String args[ ])
{
int size = 10;
int[][][] maze = new int[10][10][10];
Random gen = new Random();
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++) {
for(int k = 0; k <10; k++) {
maze[i][j][k] = gen.nextInt(3);
System.out.print(maze[i][j][k] + ", "); // this won't be part of the final code, just used to check if I'm populating correctly
}
System.out.println();
}
}
}//closing main
}//closing class FindTheCheese
Create a one-dimensional array of length 1000 to hold all the values to go into the maze. Set 500 elements to 2 (the monsters), one element to 1 (the treasure chest) and 499 elements to 0 (the free cells).
Shuffle the array using Collections.shuffle(Arrays.asList(yourOneDimArray)).
Now fill the values from the shuffled array into your 3-dimensional matrix in turn. Underway when you encounter the chest, record its coordinates in the maze. You will need this for reporting back to the user.
When you first create the maze, all cells will be zero by default. Next, add the single treasure to a random spot. Finally, pick a random cell and see if it's empty. If it isn't, pick another random cell. If it is, place a monster. Repeat that 500 times with a for loop:
public static void main(String[] args) {
int size = 10;
int[][][] maze = new int[10][10][10]; // every cell is zero by default!
Random gen = new Random();
// place the treasure
maze[gen.nextInt(size)][gen.nextInt(size)][gen.nextInt(size)] = 1;
// place 500 monsters
for(int monsters = 1; monsters <= 500; monsters++) {
int i, j, k;
do {
i = gen.nextInt(size);
j = gen.nextInt(size);
k = gen.nextInt(size);
} while (maze[i][j][k] != 0);
maze[i][j][k] = 2;
}
// display the results
for(int i = 0; i < size; i++){
for(int j = 0; j < size; j++) {
for(int k = 0; k < size; k++) {
System.out.print(maze[i][j][k] + " ");
}
System.out.println();
}
}
}

PacMan Grid 2D Array 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.

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.

Chutes and Ladders Game Random Placement Issue

I'm a student, working on a Chutes and Ladders game. I'm using methods to determine how many chutes and ladders should be placed on the game board. I'm specifying 10 for each in main using parameters but I keep getting anywhere from 6 to 11 placed across the board.
Is there something going on with the two methods interfering with each other?
Or is there a problem with the way I set up the for loops for random placement?
I'm new to this site, please let me know if you need more clarification, I didn't want to place the whole program in here. Thanks.
//main
ChutesAndLadders cl = new ChutesAndLadders();
cl.setBoard(new String[100]);
cl.makeChutes(10);
cl.makeLadders(10);
//methods
public String [] board;
private int chutes, ladders;
public int position;
public Random rand = new Random();
//set board
public void setBoard(String [] n){
board = n;
for(int i = 0; i < board.length; i++)
board[i] = " ";
}
//set and place chutes
public void makeChutes(int n){
chutes = n;
for(int i = 0; i <= chutes; i++)
board[rand.nextInt(board.length)] = "C" + chutes;
}
//set and place ladders
public void makeLadders(int n){
ladders = n;
int lcell = 0;
for(int i = 0; i <= ladders; i++)
board[rand.nextInt(board.length)] = "L" + ladders;
Firstly, you wrote:
for(int i = 0; i <= chutes; i++)
board[rand.nextInt(board.length)] = "C" + chutes;
The assignment statement in the loop will run chutes+1 times. (Eleven times in your case.) [Use i < chutes instead.] This is the same in your ladders code. This explains why you might have up to 11 chutes or ladders when the code is done running.
Secondly, you do not take care to prevent the same space being assigned a chute or ladder multiple times. rand.nextInt(board.length) is not guaranteed to generate unique values each time it is run (otherwise it wouldn't really be random.) This explains why you may not see as many as 11 chutes and ladders when the code is done running.
To make this clearer, put a constant value in there:
for(int i = 0; i < chutes; i++)
board[11] = "C" + chutes;
and notice that you end up with one chute (at space eleven)--unless the ladder code overwrites it with a ladder.
Hope that helps.
Good luck!
At first glance my guess is that you are winding up with overlapping entries. Because you generate a random placement and don't check to see if there is already a chute or ladder there, you are likely winding up with overlaps.
It should be fairly straightforward to generate the random position and then check if there is something there prior to placement. If a collision is found, just generate another random and repeat until you can place it.
Also, as an aside, it is always a good practice to avoid for loops and if statements without curly braces. It is very easy to add a second like to the block and wonder why it is not executing as part of the block.
Your for loops have an inclusive upper limit check, 0 .. 10 yields 11 entries.
Like Mike said, the lower number of results are due to collisions, you can prevent those by setting up the board by filling it with the elements needed and then shuffling the board to get the end result, something like:
public void setupBoard(String [] n, int nrLadders, int nrChutes){
board = n;
int index = 0;
while (index < board.length && 0 < nrLadders--) {
board[index++] = "L" + nrLadders;
}
while (index < board.length && 0 < nrChutes--) {
board[index++] = "C" + nrChutes;
}
while (index < board.length) {
board[index++] = " ";
}
board = Collections.shuffle(Arrays.asList(board)).toArray(new String[board.length]);
}
This is like creating a deck of cards containing a number of ladder cards, a number of chute cards, a larger number of empty spot cards and shuffling that deck to get the game board.

Randomizing obstacles for a game board

I want to place obstacles on a game board using a random number generator. 5% of the board will have a pit which is defined as "*", but the asterisk will not show unless the players lands in that spot; 10% of the board will be blocked spots indicated as "X"; the remaining 85% will be open spaces shown as "." The game board is a 10x10 array with the letter "P" at the upper left hand corner as the starting point for the player, and a "T" at the bottom right hand corner for the ending (treasure). So far I've got this, and I been watching video tutorials as well as reading to try and put this all together, but still stuck:
import java.util.Scanner;
import java.util.Random;
public class Adventure {
public static void main(String[] args) {
char grid[][]= new char[10][10];
Scanner move = new Scanner(System.in);
System.out.println("Here is the current game board:");
System.out.println("-------------------------------");
for(int i=0; i<grid.length; i++) {
for(int j=0; j<grid.length; j++) {
grid[i][j]='.';
grid[0][0]='P';
grid[9][9]='T';
System.out.print(grid[i][j]);
}
Random obstacle = new Random();
int obstacleNum;
for(int k=1; k<=100; k++) {
obstacleNum = 1+obstacle.nextInt(100);
}
System.out.println("");
}
System.out.printf("Enter your move (U/D/L/R)>");
}
}
Not sure where to go after "obstacleNum = 1+obstacle.nextInt(100);"
If your game board has 100 spots, then it will have 5 pits, 10 blocks, and 85 open spaces.
Choose 15 random numbers from 1 to 100; the first 5 identify the pits, and the next 10 identify the blocks.
Create a list to keep track of the 15 numbers. Each time you choose a random number, check to see if the number is already present to the list. If it is, discard it and choose a different random number. Otherwise add it to the list and continue until you've chosen all 15 numbers.
As for the actual interactivity, here is an outline:
x = 0; //coordinates of player, location of P
y = 0;
To hide the pits, before printing, stick in and if statement:
if(grid[i][j]=='*') {
System.out.println("."); //looks like ordinary land
} else {
System.out.println(grid[i][j]);
}
Now have this run when it receives input (pseudo)
//following if for moving left
if(grid[y][x+1] isn't out of bounds and right key is pressed and grid[y][x+1]!='X') {
grid[y][x] = '.'; //removes current position
x++; //change location
}
//following if for moving right
if(grid[y][x-1] isn't out of bounds and left key is pressed and grid[y][x-1]!='X') {
grid[y][x] = '.'; //removes current position
x--; //change location
}
//following if for moving down
if(grid[y+1][x] isn't out of bounds and down key is pressed and grid[y+1][x]!='X') {
grid[y][x] = '.'; //removes current position
y++; //change location
}
//following if for moving up
if(grid[y-1][x] isn't out of bounds and up key is pressed and grid[y-1][x]!='X') {
grid[y][x] = '.'; //removes current position
y--; //change location
}
if(grid[y][x] == '*') { //when trapped in a pit
System.out.println("You fell in a pit. Game over.");
} else {
grid[y][x] = 'P'; //update grid
}
Do you need a fixed amount of obstacles? You are better off putting the code in your loop that defines your the board:
for(int i=0; i<grid.length; i++) {
for(int j=0; j<grid.length; j++) {
int random = Math.random();
if (random <.05){
grid[i][j]='*';
}else if (random < .15) {
grid[i][j]='X'
}else {
grid[i][j]='.';
}
System.out.print(grid[i][j]);
}
}
grid[0][0]='P';
grid[9][9]='T';
Also you should put the cod just above define P and T outside the loop afterwards as it seems it only needs to be done once.
EDIT: this method will give you a representation of the game board, to cover the *, you can either change the print method to print them as . Or maintain a display grid, as well as the actual grid (eg make 2 grids)

Categories