How to move an object back and forth? - java

I'm trying to move an object back and forth. This is what i have tried, but it just moves right and stops but doesn't go back.
public void moveBug()
{
bugX++;
if (bugX > 400){
bugX--;
}
if (bugX < 0){
bugX++;
}
}
I also have this piece of code from my lecturer but I'm not sure how to apply it to the code.
if ((frameCount % 60) == 0)
{
// Do something
}

Your code unconditionally runs bugX++ every time it's called which causes the bug to always move right. You'll need another variable to keep track of the direction the bug is moving. You need to do different things based on whether it's moving right or left..
If it's moving right, increment x: bugX++.
If it's moving left, decrement x: bugX--.
If it reaches the right side, switch the direction to left.
If it reaches the left side, switch the direction to right.

Related

How to get old position of snake body parts in Java

I will try my best to explain the issue. So basically I have come to the point in my snake game which I feared the most - the array. So I what I have done is an ArrayList full of Rectangles.
I then add a Rectangle each time I eat the food and I am now at the "looping" part where I have to loop the different rectangles.
I succeded with adding one rectangle to the snake - I just took the old head.x location and the head.y location and but it into the snakeParts.get(0).setLocation.
The problem I am having is drawing the rest of the array (which would be index nr 1 to infinity).
I can't seem to get the rest of the ArrayLists's old positions. For example: I want snakeParts.get(1) to get snakeParts.get(0)'s old position but I can't seem to figure out how to do that logic. I wonder if any of you could give me a hand?
Here is the part of the code that is affected:
repaint();
//Test
for(int z = 0; z < snakeParts.size(); z++) {
System.out.println(z); //Test printing
if(z == 0) {
snakeParts.get(z).setLocation(head.x, head.y); //Printing index 0
}
else {
snakeParts.get(z).setLocation(snakeParts.get(z - 1).getLocation());
//Takes all the indexes and puts them where the snakeParts.get(0) is. I want them to get longer - like the Snake game
}
//Loop different might solve the issue?
}
head.x += speedx;
head.y += speedy;
I am doing this in JPanel and my ArrayList is an array of the Rectangle class which can be found here: Rectangle Class
If you want the entire code - please ask! I thought it would be easier to just show you guys this code sample because it's the only part that affects what I am trying to achieve.
Thanks in advance!
Start from the end and go towards the head, get last part, set its position to where last-1 is.
Then go, for last-1, set its position to where last-2 is.
Repeat that until you reach second part, once you set its position to head, then move your head.
Edit.
Here is how does forward vs backward loop look like:
for(int z = 0; z < snakeParts.size(); z++) {}
for(int z = snakeParts.size() - 1; z >= 0; z--){}
First one starts at 0, goes to size of snake parts by increases of 1.
Second one starts at size of snakeparts - 1 (we decrease by 1 because snakeParts are counted from 0, not from 1), works as long as z is greater-equal to 0, and at each step it reduces z by 1.
Hope that helps :)
In your code you should make sure you are not trying to access indices smaller or larger than the array.

Slick2d Java reversing the moving direction of an object

I'm working on this game using Java and slick2d library and I'm supposed to reverse the direction of some moving vehicles (eg:bikes) when they reach a certain x-coordinate.
Logic seems simple enough, yet some of them move right past the x-coordinate, while some reverses the direction. Confused as to why. Any help would be appreciated.
Here's my code in the update() method. getX() returns the x location from superclass as a float. BIKE_SPEED is a float, delta being the milliseconds passed since last frame.
#Override
public void update(Input input, int delta) {
if ((int)getX() == 24 || (int)getX() == 1000) {
moveRight = !moveRight;
}
move(BIKE_SPEED * delta * (moveRight ? 1 : -1), 0);
}
I'm not familiar with slick2d, but in general, it's better to use >= or <= instead of == in cases like this. The object (bike) may "jump" right past the boundaries, without triggering your change of direction condition.

If statement seems to run some code but not all in java

I'm making a 2d platformer in libgdx with box2d. The below is the update method for one of my enemies. It's an extension of the 'Enemy' class, which is what 'super.update' refers to. I want the enemy to run when the player is behind it or far away and to stop and shoot when the player is close to it and in front of it.
I try to achieve this by setting the speed (velocity.x) initially [depending on the enemy's direction], then setting whether or not it's shooting afterwards.
The problem I have at the moment is that the enemy doesn't run when the player is behind it. As you can see, I printed out a lot of strings to console to see when the velocity.x gets changed back to 0. According to the console, it happens in the last if/else pair of statements which are supposed to check how far away the player is and which direction the enemy is running. However, the console strings within those statements, the ones that say 'Shoot Left' or 'Shoot Right', don't get printed out. Despite this, the line that changes velocity.x must get run because the it's value changes according to the string output in the next line. The if statements at the top which check direction must get run as well because the console outputs within those statements get printed, and the output that says the velocity says the correct velocity (either 2 or -2).
What is going on? It seems like the IDE is running only one of the lines in the if statement. That's impossible so what am I missing here?
Thanks for any help.
public void update (float dt, Player player){
super.update(dt, player);
if (b2body.isActive()){
System.out.println(b2body.getPosition().x - player.b2body.getPosition().x);
System.out.println("After Enemy code: " + velocity.x);
if (getRunningRight()) {
System.out.println("Right");
velocity.x = 2;
}
else if (!getRunningRight()) {
System.out.println("Left");
velocity.x = -2;
}
System.out.println("After checking direction: " + velocity.x);
if ((b2body.getPosition().x - player.b2body.getPosition().x <= 2 &&
b2body.getPosition().x - player.b2body.getPosition().x >= 0) && !getRunningRight()){
velocity.x = 0;
System.out.println("Shoot left");
}
else if ((b2body.getPosition().x - player.b2body.getPosition().x >= -2 &&
b2body.getPosition().x - player.b2body.getPosition().x < 0) && getRunningRight()){
System.out.println("Shoot right");
velocity.x = 0;
}
System.out.println("After shooting: " + velocity.x);
}
}
In your first set of ifs, you evaluate getRunningRight() after you have already determined that it will be false (by the initial if failing), so there is no need to evaluate it again.
If you think you are doing the same thing in the second block, you are not; the expression in the inner if is not the opposite of the first one. That is, (A && B) && C is not the opposite of (!A && !B) && !C. Thus, it is possible for both expressions to be false.

How to correctly write a maze algorithm using loops

I am writing a code for a class assignment to get a character through a maze. I have been working on this for hours and I can't figure out what I am doing wrong. The character moves left to right and right to left. Except when I add the code to have the character move around a block if (maze.moveRight() == false), it causes the character to move up and down at the end of each row a bunch of times before it moves the other direction. Also it messes up my count as the character moves across the rows. I feel like I am making it much more complicated than it should be. Can someone help?
Algorithm
The student always starts at the top left corner, that is row and column zero.
The Java logo can be anywhere in the maze, which also contains obstacles shown as "Wrong Way" signs.
You must traverse every row in the maze from top to bottom according to the rules below, until you find the Java logo.
Row and column numbers are zero based, so the first row and column is index 0. the second row and column is index 1, and so on. The number zero is even.
On even rows, you must move left to right using maze.moveRight(), on odd rows, you must move right to left using maze.moveLeft().
After completing each row, use maze.moveDown() to proceed to the next row, until you reach the last row or find the Java logo.
You can detect that you have encountered an obstacle by checking the return value from move methods in the Maze object, true means no obstacle, false means obstacle.
If you run into an obstacle when when moving left to right: Move down, right, right, and up.
Adjustment the loop counter for the extra move right!
If you run into an obstacle when when moving right to left: Move down, left, left, and up. Adjustment the loop counter for the extra move left!
Every time you move left or right, not including when avoiding an obstacle, you must call maze.isDone() to see if you have found the Java logo.
When you find the Java logo, you must immediately break out of all loops, and exit the program.
There are mazes that cannot be solved using the algorithm, but we will not test your program with any of them.
public static void main(String[] args) {
// Create maze
String fileName = args[1];
Maze maze = new Maze(fileName);
System.out.println("Maze name: " + fileName);
// Get dimensions
int mazeWidth = maze.getWidth();
int mazeHeight = maze.getHeight();
// Print maze size
System.out.println("Maze width: " + mazeWidth);
System.out.println("Maze height: " + mazeHeight);
int r = 0;
int c = 0;
// Move commands
while (c < maze.getWidth() - 1 && r % 2 == 0 && maze.isDone() == false)
{
maze.moveRight();
maze.isDone();
c++;
if (maze.moveRight() == false && maze.isDone() == false){
maze.moveDown();
maze.moveRight();
maze.moveRight();
maze.moveUp();
}
if (maze.isDone() == true){
System.exit(1);
}
}
while (c == maze.getWidth() - 1 && r % 2 == 0 && maze.isDone() == false)
{
maze.moveDown();
maze.isDone();
r++;
}
while (c != 0 && c <= maze.getWidth() -1 && r % 2 != 0
&& maze.isDone() == false){
maze.moveLeft();
maze.isDone();
c--;
if (maze.moveLeft() == false && maze.isDone() == false) {
maze.moveDown();
maze.moveLeft();
maze.moveLeft();
maze.moveUp();
}
if (maze.isDone() == true){
System.exit(1);
}
}
}
I'm having a hard time following what your intent is and thus what the problem is. Perhaps it's due to lack of understanding of how this maze is set up. I also don't know the scope of the class so I don't know if this is above your current level or not, but here goes how I would personally implement a maze solver:
For each position in a maze that I find myself, I would create a maze "space" object. This object will keep track of remaining options of directions to be traversed and whether or not I have visited that space. If I can turn left and right, I would create new spaces for both, pick one direction, and mark only that one direction to say I've been there. When I reach a dead end, I will turn around until I find a choice of direction to go. If I've not visited a direction, I'd take that. Otherwise, If I've visited all ways, I would call a recursive function to determine if there are any directions available along down any of the paths I've taken previously.
So it's creating objects, using recursion, and flagging an object for whether or not I've been there. (you'd also need a flag to indicate if your recursive algorithm has checked a square as well lest you find yourself in an infinite loop).
Hopefully that's within the constraints of the assignment! Otherwise, we may need more information as to what the limitations are and the true scope of the assignment.
Ok so a few problems you are only moving down on the right wall.
You aren't updating your row column counters when you are navigating hazards.
You should be testing the results of every move and isDone method call and breaking or updating your counters accordingly.
Also you shouldn't be updating your counters as you do outside an if statement associated with a move test method call.

Java Array Index out of Bounds

OK so I seem to be getting an Array Index out of Bounds error in a part of my code. Specifically in lines 85-102...
My code: http://www.sosos.pastebin.com/f0JQBWui
I just want it to check for blocked tiles AHEAD of time that way my sprite doesn't move in the direction it can't. This exception only happens when I am on the RIGHT or BOTTOM corners of my map.
My GUESS of why this error happens if because when I am on the corner.. it checks for the tiles to the RIGHT and BOTTOM of it which are not there...
1) The way you implemented blocked(tx,ty), it only accepts legal board coordinates (0<=tx<=12 and 0<=ty<=8). Otherwise it checks an illegal array position, producing an ArrayIndexOutOfBoundsException. Are you sure this is your intention? I think it makes sense to consider off board tiles as blocked.
2) In lines 85-102 there seems to be many errors. I think you meant something like:
if (spawnX == 0 || blocked(spawnX - 1, spawnY)) {
left = false;
System.out.println("You can't go left!");
}
if (spawnX == 12 || blocked(spawnX + 1, spawnY)) {
right = false;
System.out.println("You can't go right!");
}
if (spawnY ==0 || blocked(spawnX, spawnY - 1)) {
up = false;
System.out.println("You can't go up!");
}
if (spawnY == 8 || blocked(spawnX, spawnY + 1)) {
down = false;
System.out.println("You can't go down!");
}
Anyway, if you fix (1) as I suggested, the extra bound condition per direction is unecessary.
3) isInBound(r,c) is implemented incorrectly. It always returns false, due to the conditions on c.
4) There are many other problems with the code, but I will not enter into details. As a principle, try to make your design simple and make sure the code does not repeat itself.
You're going to have to do some bounds-checking in your blocked() function. Make sure that the coordinates they're giving you actually exist and return some "blocked" value if they don't.
The description of getting the error at the bottom or right would seem to suggest that you need to test if the value exceeds the array bounds. Have a look at Array.length

Categories