I am creating a game using a 10x10 2D array. The player starts at the top left hand corner indicated as "P" and the objective is to get the player to avoid obstacles to get to the treasure indicated as "T" located in the lower right corner.
How would I go about making the player move about the grid using commands Up/Down/Left/Right?
Would I use a for loop to count through the elements in the array to designate the move?
Here is what I have so far:
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++) {
double random = Math.random();
if(random <=.05) {
grid[i][j]='*';
}
else if(random > .06 && random <= .15) {
grid[i][j]='X';
}
else {
grid[i][j]='.';
}
grid[0][0]='P';
grid[9][9]='T';
System.out.print(grid[i][j]);
}
System.out.println("");
}
System.out.print("Enter your move (U/D/L/R)>");
}
}
you should keep track of the current position of the player and just update those variables.
initial values would be (0,0) as you said.
int px = 0;
int py = 0;
when a move is made, update the variables accordingly:
grid[px][py] = <empty cell>;
switch (move) {
case 'u': py += 1; break;
case 'r': px += 1; break;
...
}
grid[px][py] = 'P';
of course you shouldn't just updated the values "blindly", you should insert some validation logic to follow the rules of the game:
if (grid[px][py] != <obstacle> )
// update player coordinates...
Looks like you're using row-major ordering, judging from the way your board prints out. Based on that, here's what you'll need to do:
First, you need to store the player's position somewhere. Right now it's hardcoded to 0,0.
Second, you need to read in the player's move. That will have to happen in a loop, where you get a move, check if the move is allowed, perform the move, and display the results.
Third, you need to be able to calculate the new position based on the move. Up means row -= 1. Right means column += 1. Etc.
Given the new coordinates, you need to make sure the move is valid. At the very least, you have to stop them from walking off the board, but you may also prevent them from entering a square with an obstacle, etc.
Once you know that the move is valid, you have to update the variables you're storing the current coordinates in.
At the end of the loop, you'll need to redraw the board.
That's the basic gist of it. Right now you are doing everything in main(), and that's okay, but if it were me I would start to split things out into separate methods, like InitializeBoard(), GetNextMove(), CheckIfMoveIsValid(int r, int c), and so on. That way, main() becomes a high-level view of your game loop, and the guts of the different operations are compartmentalized and more easy to deal with. This will require storing off things like your game board into class variables rather than local variables, which should actually make things like obstacle detection easier than it would be currently.
All of the above answers are great. Here are a few suggestions I would make:
Instead of a char two-dimensional array, I would make a custom object, such as Space, and define a two-dimensional array of Spaces (eg, Space[][]). There are a few reasons for this:
You can define a space in a variety of ways (rather than just 1 character). For example, Space[i][j].hasTreasure() can return a boolean to let you know whether or not you found the treasure.
If you want to add functionality later, its as easy as adding an attribute to your Space class. Again, you are not limited to one character here.
More to your question of movement, I would also recommend a few things. Similar to redneckjedi's suggestion of a CheckIfMoveIsValid() method, I would pass the grid and move direction as parameters and return a boolean. To ensure that you do not end up with ArrayIndexOutOfBounds issues, I would also suggest adding a row/column of walls on each side. I would widen the grid out to 12x12 and put a strip of obstacle-type blocks around the outside. This will ensure that you cannot step outside of the grid as hitting a wall will always return 'false' on a valid move.
Related
I am a beginner and I am making a space shooter game in Netbeans. I want if the spacecraft's bullet hits the enemy's bullet that the 2 bullets are removed. I have created an Arraylist of bullets and bulletsEnemy. Then I created a method hitByBullet that should ensure that I can search for the bullets that collided. Then in the method bulletsHit (), the bullets should be removed.
My enemies shoot in a loop and don't move. My problem is that the bullets go through each other. The radius of the bullets is 5.
These is the 2 methods that I have written
'''
public int hitByBullet(){
for(int i=0; i<bullets.size(); i++){
for(int j= 0;j< bulletsEnemy.size(); j++){
if( bullets.get(i).getY() - bulletsEnemy.get(j).getY()<= 5)
if(bullets.get(i).getX() -bulletsEnemy.get(j).getX()<= 5){
return i;
}
}
}
return -1;
}
'''
public boolean bulletsHit(){
if (hitByBullet()!= -1){
bullets.remove(this); //with 'this' I refer too 'i'
bulletsEnemy.remove(this);
return true;
}
return false;
}
'''
[This is how it looks like] (https://i.stack.imgur.com/4XsCR.png)
I will try to answer in a way to let you find your way to implement what you want. There are several frameworks out there which will help you with this and as you are new to programming there are a lot of things you could change/do better. But I will ignore these things.
I think your are trying to check if one 5x5 bullet intersects with another 5x5 bullet.
To make it easy let us asume your bullets are squares:
In your hitByBullet you should check your square centers (i asume that are x,y of your bullets) distance in both dimensions:
Sth. like this should check the collision:
if(Math.abs(bullets.get(i).getY() - bulletsEnemy.get(j).getY()) < 5 &&
Math.abs(bullets.get(i).getX() - bulletsEnemy.get(j).getX()) < 5) {
return i;
}
Depending of the size of your bullets you need to change the distance check ( <=5). If your bullets have a size of 5 px it should be < 10. If your bullets are 10x10 you should check against < 20 ...
Regarding a more realistic scenario, that your bullets are circles (e.g. resulting of a 5x5 square px or a radius r=5):
You need to check if the distance between your two bullet centers is smaller than the bullet radius * 2.
That will bring you to use the theorem of pythagoras:
https://en.wikipedia.org/wiki/Pythagorean_theorem
The distance between your bullet centers is c. a is the distance in dimensional x and b the distance in dimensional y. You don't need to take care about negative dimensional values cause you need pow them by 2 which will always give you a positive value.
To check for collision you should calculate the distance c as follows:
c = SquareRootOf(a^2+b^2)
Math.sqrt(Math.pow(bullets.get(i).getX() - bulletsEnemy.get(j).getX()),2) + Math.pow(bullets.get(i).getY() - bulletsEnemy.get(j).getY(),2)) < 10
I think you should read basics about collision detection and geometry. Just two possible points of information:
An easy to start example with code:
https://zetcode.com/javagames/collision/
Circle intersection:
https://www.geeksforgeeks.org/check-two-given-circles-touch-intersect/
Regarding the removal of the bullets I asume you have some kind of game loop in which you frequently draw the bullets and calculate the collision (call the bulletsHit method):
I will make an assumption to make things easier: The movement speed of your bullets is not faster than one pixel per loop. Otherwise I think you need to take care of your loop circle time and calculate the positions of all elements and also take care about bullets that won't intersect in one loop circle because they could have passed by from one loop circle to the next loop circle. I'm not familiar with game dev, so maybe there are more things to cover.
Regarding this you should change things:
The method hitByBullet() will only return one collision per call.
You could store your collidedBullets in two sets and after removing them from your bullets and bulletsEnemy list clear these temporary sets.
I don't understand what you are doing with "this" and your result of
hitByBullet.
I would do it like this
public void hitByBullet(){
for(int i=0; i<bullets.size(); i++){
for(int j= 0;j< bulletsEnemy.size(); j++){
if( Math.sqrt(Math.pow(bullets.get(i).getX() - bulletsEnemy.get(j).getX()),2) + Math.pow(bullets.get(i).getY() - bulletsEnemy.get(j).getY(),2)) < 10){
bulletsToDelete.add(bullets.get(i));
bulletsEnemyToDelete.add(bulletsEnemy.get(j));
}
}
}
}
public boolean bulletsHit(){
hitByBullet();
bulletsToDelete.forEach(bullet -> bullets.remove(bullet);
bulletsEnemyToDelete.forEach(bullet -> bulletsEnemy.remove(bullet);
boolean bulletsHit = !bulletsToDelete.isEmpty();
bulletsToDelete.clear();
bulletsEnemyToDelete.clear();
return bulletsHit;
}
As I mentioned before there are a lots of things you should improve:
general structure of your code
naming of your method (e.g. bulletsHit sounds like only checking if bullets are hit but you are also removing them)
double checking of bullets
Greetings
I am currently making a tower defence game.
Simply put it works like this: green circles (enemies) move across the screen. By clicking, you can place a tower. The enemy has a rectangle hidden underneath it, and the tower has a large opaque rectangle around it indicating its hit range. If they are colliding, the enemy starts to lose health, until it dies.
Before, I used this test to see if the enemy was within range of the tower:
for(int i=0;i<enemy.length; i++) //Runs for the total amount of enemies
{
for(int j=0; j<boxes.length;j++) //Runs for the total amount of towers placed
{
if(enemy[i].getEBox().intersects(boxes[j])) //boxes[j] is the towers' range box
{
enemy.setHealth(enemy.getHealth()-1);
}
}
}
However, I would like the towers to only be able to shoot one enemy at a time, most preferably the enemy at the front. To do this I need java to detect that there are multiple enemies colliding with the rectangle and only damage the front enemy.
Here is the test I ran to do this (The enemies array value go backwards so the first one to appear is enemy[0] and the last enemy[10] for example):
for(int i=1;i<enemy.length; i++)
{
for(int j=0; j<boxes.length;j++)
{
if(enemy[i].getEBox().intersects(boxes[j])&&!(enemy[i-1].getEBox().intersects(boxes[j])))
{
enemy.setHealth(enemy.getHealth()-1);
}
}
}
however, the second condition always returns a positive. How can I change my if statement to conduct a successful test?
To make a tower only shoot at one enemy, flip the loops and break the inner loop when shooting starts.
for(int j=0; j<boxes.length;j++) //Runs for the total amount of towers placed
{
for(int i=0;i<enemy.length; i++) //Runs for the total amount of enemies
{
if(enemy[i].getEBox().intersects(boxes[j])) //boxes[j] is the towers' range box
{
enemy[i].setHealth(enemy[i].getHealth()-1);
break; // skip remaining enemies, since towers has used
// up it's shooting capability for this round
}
}
}
If a tower can prioritize which enemy to shoot at, loop through all the enemies to find the best candidate, then shoot at it.
for (int j=0; j<boxes.length; j++) //Runs for the total amount of towers placed
{
int enemyToShootIdx = -1;
for (int i=0; i<enemy.length; i++) //Runs for the total amount of enemies
if (enemy[i].getEBox().intersects(boxes[j])) //boxes[j] is the towers' range box
if (enemyToShootIdx == -1 || betterCandidate(boxes[j], enemy[i], enemy[enemyToShootIdx]))
enemyToShootIdx = i;
if (enemyToShootIdx != -1)
enemy[enemyToShootIdx].setHealth(enemy[enemyToShootIdx].getHealth()-1);
}
Now you just have to implement the betterCandidate() method.
You could store the enemies in the order you detect them so you will know which is the closest. Like an ArrayList for detected enemies or an ID kind of variable for each enemy object, which initialized when detected. Im pretty sure there are a lot ways like this, so storing an order somehow could work. Once you have an order you can attack only that one and there is no need to test the detected objects anymore while still looking for coming enemies and keep storing them so on.
In your case
if(enemy[i].getEBox().intersects(boxes[j])&&!(enemy[i- 1].getEBox().intersects(boxes[j])))
I don't really see (or maybe just too tired) why you need these conditions to attack. If your array of enemies is already in order why dont you just attack the first? If inRange && isAlive if not you go on the next one.
I hope i did not misunderstand anything and probably could help a bit. :)
i am using the import becker.robots file for this assignment!
I must create a class DistributeBot (extended RobotSE) which will put down a number of 'things' in the shape of 2 squares.
When the main method is then created, a single call to a method (which i must create myself using stepwise refinement and also contains a parameter) called this.putThings();
The method i am to create should have a single variable parameter to define the size of the squares! ie a parameter of (4) will make a 4x4 square of 'Things'.
The robot should set out the Things one line at a time from left to right! (once one line is displayed, it should move back to the LHS before displaying the next line)
I think i will be able to complete the scenario without problem whenever i am certain on how to create the method with the parameter i have specified.
Assumptions.
1. Starting position of the robot will always be the same. ie starting at 1, 1.
2. There will always be enough 'things' in the robots backpack to display the two squares.
Anyone have an idea how I would go about setting up this method initially with the variable parameter?
If you have your method starting
Public void MakeSquare(int size)
{
for(int i = 0; i < size; i++)
{
for(int x = 0; x < size; x++)
{
//drop thing
//move right
}
for(int y = 0; y < size; y++)
{
//move left
}
//move up
}
}
Whilst reading the question you should try and break it down into its simplest parts.
start with Build a square that is the most abstract form of the scenario and so makes your method, then break it down
//I want to move up until I hit size limit
for each number in "the size you want"
//I want to move right and drop a thing, until I hit size limit
for each number in "the size you want"
drop a thing
move one right
endloop
//I want to move back to the LHS until I hit size limit
for each number in "the size you want"
move one left
endloop
//then make the move up
move up
endlood
If you make this method and call it twice you will make the 2 squares as required)
Here is the algorithm (not working) Please let me know where the error is
Thanks
private void checkSouth(Location point, int player) {
//Loop through everything south
boolean isthereAnOppositePlayer=false;
int oppositePlayer=0;
//Set opposite player
if (player==1) {
oppositePlayer=2;
}else{
oppositePlayer=1;
}
for (int i = point.getVertical(); i < 8; i++) {
//Create a location point with the current location being compared
MyLocation locationBeingChecked= new MyLocation();
locationBeingChecked.setHorizontal(point.getHorizontal());
locationBeingChecked.setVertical(i);
int value = board[locationBeingChecked.getVertical()][locationBeingChecked.getHorizontal()];
//If the first checked is the opposite player
if (value==oppositePlayer) {
//Then potential to evaluate more
isthereAnOppositePlayer=true;
}
//If it isn't an opposite player, then break
if(!isthereAnOppositePlayer && value!=0){
break;
}
//If another of the player's piece found or 0, then end
if (isthereAnOppositePlayer && value==player || isthereAnOppositePlayer && value==0) {
break;
//end
}
//Add to number of players to flip
if(isthereAnOppositePlayer && value==oppositePlayer && value!=0){
//add to array
addToPiecesToTurn(locationBeingChecked);
}
}
}
It looks like the locations that got rotated back to the other player are the exact same as those rotated during the first move. I would guess that the array being populated by addToPiecesToTurn is perhaps not being cleared out between each move, so all the previous locations are still in there.
If you are storing the pieces to be turned in an ArrayList, you can use the clear() method to erase the contents of the collection between each turn.
Another possible problem is that you are checking for the opposite player, and then instantly beginning to populate addToPiecesToTurn. However, the pieces in that direction are not necessarily valid to be rotated unless they are "sandwiched" in by a second location containing the current player's piece. I don't think your code is properly checking for that case; when that happens, you'll want to somehow skip flipping those pieces to the other player, such as clearing out the array of piecesToTurn.
Edit: Looking at your current solution where you are implementing every direction separately, you are going to have a lot of duplicated code. If you think about what it means to walk along a certain direction, you can think of it as adjusting the x/y value by a "step" amount. The step amount could be -1 for backwards, 0 for no move, or 1 for forwards. Then you could create a single method that handles all directions without duplicating the logic:
private void checkDirection(Location point, int player, int yStep, int xStep) {
int x = point.getHorizontal() + xStep;
int y = point.getVertical() + yStep;
MyLocation locationBeingChecked = new MyLocation();
locationBeingChecked.setHorizontal(x);
locationBeingChecked.setVertical(y);
while (isValid(locationBeingChecked)) {
// do the logic here
x += xStep;
y += yStep;
locationBeingChecked = new MyLocation();
locationBeingChecked.setHorizontal(x);
locationBeingChecked.setVertical(y);
}
}
You would need to implement isValid to check that the location is valid, i.e., in the board. Then you could call this method for each direction:
// north
checkDirection(curPoint, curPlayer, -1, 0);
// north-east
checkDirection(curPoint, curPlayer, -1, 1);
// east
checkDirection(curPoint, curPlayer, 0, 1);
// etc
This is the sort of problem that is ripe for some unit testing. You could very easily set up a board, play a move, and validate the answer, and the test results would give plenty of insight into where your expectations and reality diverge.
why didn't you use a 2d array ?
each cell would contain an enum : EMPTY, PLAYER_1, PLAYER_2 .
then, in order to go over the cells, you simply use loops for each direction.
for example, upon clicking on a cell , checking to the right would be:
for(int x=pressedLocation.x+1;x<cells[pressedLocation.y].length;++x)
{
Cell cell=cells[pressedLocation.y][x];
if(cell==EMPTY||cell==currentPlayerCell)
break;
cells[pressedLocation.y][x]=currentPlayerCell;
}
checking from top to bottom would be:
for(int y=pressedLocation.y+1;y<cells.length;++y)
{
Cell cell=cells[y][pressedLocation.x];
if(cell==EMPTY||cell==currentPlayerCell)
break;
cells[y][pressedLocation.x]=currentPlayerCell;
}
here's the deal, I have to make a game that resembles PacMan, with a map, points, ghosts, etc.
The whole thing works as an array[8][8], it reads the positions of walls and the initial position of ghosts from a .txt file, PacMan starts at a fixed location and Fruits are random. Any blank space at the beginning of the game gets filled with a simple point pellet.
I've got the map done, it shows it and everything, but I can't seem to come up with a method that allows the player to control PacMan with the keyboard... This is what I've tried so far...
In the Player class
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String mov = read.readLine();
if (mov.equals("w"))
{
PacMan.MoveU();
}
It then repeats that for the other movement keys.
The individual Move methods in PacMan class look like this
public static void MoverR()
{
for (int i=0;i<Tablero.length;i++)
{
for (int j=0;j<Tablero.length;j++)
{
if (Tablero[i][j] instanceof PacMan)
Tablero[i][j]=null;
Tablero[i][j+1]=new PacMan();
}
}
}
}
This obviously isn't working, so I'm wondering if anyone can help me with a more efficient way to do this? I really don't mind starting these two classes from scratch...
Thanks.
It always gives me an ArrayOutOfBounds Exception
The ArrayOutOfBounds Exception is caused by Tablero[i][j+1]=new PacMan(); when j == 7, because you try to access to an invalid position (Tablero[i][8]).
anyone can help me with a more efficient way to do this?
You don't need to check the whole array to find out the position of Pacman, you could store the position as a private variable of Pacman, but in that case you shouldn't create a new instance of Pacman every time you need to move it, like you are doing with your current implementation.
One reason why you get ArrayOutOfBoundsException is the fact that in your loop you're moving PacMan to position [i][j +1], where j + 1 may be greater than array length.
You need to check if j + 1 < Tablero.length when you're 'moving' PacMan.
Also you can simply move the same instance of PacMan instead of creating a new one:
...
if (Tablero[i][j] instanceof PacMan) {
if (j + 1 < Tablero.length) {
Tablero[i][j+1] = Tablero[i][j];
Tablero[i][j] = null;
}
}