Game logic - Add score only once after passing obstacle - java

I'm creating a game with a score system similar to the one in Flappy Bird.
if you didn't get it
When the player successfully passes the right and left
obstacle I want my score variable to increase by 1. I don't know the logic behind it though.
Right now I have (this is inside a for loop checking every obstacle in an update method):
'over' making sure the score only increases by 1.
if (bird.getPosition().y > obstacle.getPosLeft().y) {
if (!over) {
over = true;
score++;
}
and when the obstacle gets off the screen (yes, y is 0 at the bottom, not the top):
if (obstacle.getPosLeft().y + Obstacle.OBSTACLE_HEIGHT < 0){
obstacle.reposition(obstacle.getPosLeft().y + (OBSTACLE_SPACING + Obstacle.OBSTACLE_HEIGHT)* OBSTACLE_COUNT);
over = false;
}
The problem is that you can pass 2 obstacle pairs before the first one gets re-positioned which means that you only get the 2nd point after reposition() is called for obstacle 1.
How would you fix this problem?

Just make a "obstacle.over" boolean so that each has its own state.

Related

Obstacles are removed faster than the bullet animation passes

Situation: The tank has a Shot() method and a code that checks if the bullet hits the obstacle after being fired. The bullet flies up the X-coordinate. The do...while loop checks how far the bullet can travel without obstacles. After that, the animation of the bullet flight itself takes place through TranslateTransition. And the last loop goes through all the game obstacles and checks for contact through intersects and, if successful, removes the obstacle.
do {
y = (int) (bulletObj.getImageBullet().getTranslateX() + register) / PlayField.BRICK_SIZE;
x = (int) bulletObj.getImageBullet().getTranslateY() / PlayField.BRICK_SIZE;
line = LevelData.LevelOne[x][y];
register += 1;
} while (line.equals("0"));
System.out.println(System.currentTimeMillis()); // 1643642047472 ms.
bulletTranslate = new TranslateTransition();
bulletTranslate.setFromX(bulletObj.getImageBullet().getTranslateX());
bulletTranslate.setToX(bulletObj.getImageBullet().getTranslateX() + register - 18);
bulletTranslate.setNode(bulletObj.getImageBullet());
bulletTranslate.setDuration(Duration.millis(register)); // Let register = 300 мs.
bulletTranslate.play();
System.out.println(System.currentTimeMillis()); // 1643642047474 ms.
bulletObj.getImageBullet().setTranslateX(bulletObj.getImageBullet().getTranslateX() + register - 18);
for (GameObject platform: PlayField.platforms) {
if (platform.getImage().getBoundsInParent().intersects(bulletObj.getImageBullet().getBoundsInParent()))
{
System.out.println(System.currentTimeMillis()); // 1643642047474 ms.
tankRoot.getChildren().remove(platform.getImage());
PlayField.platforms.remove(platform);
LevelData.LevelOne[x][y] = "0";
break;
}
}
Everything works as expected, but there is only one problem.
The problem is that the obstacle objects are removed faster than the animation bullets pass.
And it is necessary that after contact they are deleted simultaneously.
How to solve the problem?
Before the shot
After the shot, the object disappeared during the flight of the bullet
P.S Sorry, I used google translate.
As #jewelsea suggested, you need to supply a minimal reproducible example to get some proper help.
Having said that, based on the code you provided, below is my initial analysis. Note that this is a rough analysis by reading the code.. so everything is just an assumption ;)
The first part of the code (do-while) is to determine the distance the bullet needs to travel (determining the value of register)
The second part is to initiate animation of bullet to translate from its current position (using the register value).
The third part is to set the final translate value to the bullet and the final part is to check if the bounds are intersected and delete the node.
I think the thrid part (below line of code) is not needed and could be the cause for your issue. You are updating the value to the end value and immediately checking if it is intersected.. which will be true and will delete instantly.
bulletObj.getImageBullet().setTranslateX(bulletObj.getImageBullet().getTranslateX() + register - 18);
Try moving your 'for' loop code to onFinished of translation. Something like..
bulletTranslate = new TranslateTransition();
bulletTranslate.setFromX(bulletObj.getImageBullet().getTranslateX());
bulletTranslate.setToX(bulletObj.getImageBullet().getTranslateX() + register - 18);
bulletTranslate.setNode(bulletObj.getImageBullet());
bulletTranslate.setDuration(Duration.millis(register)); // Let register = 300 мs.
bulletTranslate.setOnFinished(e->{
for (GameObject platform: PlayField.platforms) {
if (platform.getImage().getBoundsInParent().intersects(bulletObj.getImageBullet().getBoundsInParent()))
{
tankRoot.getChildren().remove(platform.getImage());
PlayField.platforms.remove(platform);
LevelData.LevelOne[x][y] = "0";
break;
}
}
});
bulletTranslate.play();

how do i organise this function so it works as i intend it to

im new to android studio and i want this function to loop and create an infinite ball falling loop which will be scored until the two integers do not match but when i try to run it, it will only loop once and if i change streak = 2 in the else statement the app crashes
public void mainGameLoop(){
do {
//sets Balls integer
setColourint();
ball.setVisibility(View.VISIBLE);
//ball fall
float bottomOfScreen = getResources().getDisplayMetrics()
.heightPixels - (ball.getHeight() * 4);
//fall animation
ball.animate()
.translationY(bottomOfScreen)
.setInterpolator(new AccelerateInterpolator())
.setInterpolator(new BounceInterpolator())
.setDuration(9000);
//once animation is complete compares balls variable with current variable
if (colourint == ranint){
//if they are same then +1 score
score = score+1;
scr.setText(Integer.parseInt(String.valueOf(score)));
} else {
//else game is over
streak = 2;
}
//repeat until game is over
} while (streak == 1);
}
once the balls reached the bottom of the relative layout i want the function to check if the setcoulour int and the ran int are the same and then if the are score = score + 1, ball goes back to the top, the setColourInt function is called and the ball falls again(and so on and so on) but if not loop ends and it's game over...i apologise for my blatant incompetence but I can't imagine you guys don't remember when you too, were this naive when it came to coding. many thanks Tom
You have to give the UI a chance to draw what you're doing. The way you have it coded, whichever method (onStart, onCreate, etc) that calls your mainGameLoop will never return because it's stuck in an infinite loop. This is an error.
One way to do this is to create a View and implement your game draw logic in the onDraw method. The UI thread will call your onDraw method when it is time to draw. Here's an article that talks about this approach: http://cjds.github.io/2014/04/28/Creating-a-simple-android-game/

For loop and if statements acting odd

I am making a chess game and so far everything is good and I am writing the rules of each piece now. The problem is that a for loop is acting oddly. Its for the bishop so x is going down and y is going up. At this point it acts oddly whenever I try to add the point to a possible move
for (int i = 0; i < 8; i++) {
Point newLoc = new Point(x-i, y+i);
if(team.equals("white")) {
if(containsPiece(newLoc)) {
if(ChessBoard.black.containsKey(newLoc)) {
possibilities.put(newLoc, rating);
break;
}
else {
break;
}
} else
possibilities.put(newLoc, rating);
}
containsPiece() is working just fine and possibilities is the HashMap I am storing the possible moves in.
The way I see it it should be working perfect because if the tile at newLoc is white it shouldn't add it to the possible moves and stop getting any moves after it in that direction. Does anyone see why it seems to abandon all the previous possible moves added to possibilities
i should start in 1, not 0, since when i==0, newLoc is the position of the bishop ((x-0,y+0)), so you break from the loop, since the bishop is a white tile.

Removing the last object in an array in Java?

A quick overview of my program: I am making the game War. So when the play button is clicked, two new cards show up with random values. Which ever card has the higher value wins, and a rectangle appears in the middle of the window. As the game goes on, who ever wins has more rectangles pushed to their side (either to the left or right depending on which card wins), but the trick is that if for example the card on the left wins the first three, then the card on the right wins 1, a rectangle is removed, meaning only 2 are going to the left. If the right wins again, another is removed, etc.
The rectangle is created in a separate class called Bar, and here is what I have to create an array with a rectangle that goes to the left.
Bar newBar = new Bar(300,250);
counter = d++;
newBar = new Bar(300-(counter*30), 250);
if(numDi >= bars.length){ //You want it to always be higher
Bar[] temp = new Bar[bars.length +1];
for(int i = 0; i < bars.length; i++){
temp[i] = bars[i];
}
bars = temp; //increments bars by 1
}
bars[numDi++] = newBar;
The idea I have is that I could create an if statement which checks who won and also who won the last game. And if the opposing player won the last game, I would need to subtract a rectangle.
But how would I go about subtracting the rectangle?
And as a side note, I can not use any sort of lists.
You can use a single integer counter. When the right side wins increment it by 1 and when the left side wins decrement it by 1. This way you can easily test with an if statement who has been winning lately and control what happens depending on who wins.
If you can't use a list or queue then I would suggest using two separate arrays, one for the left side and one for the right side. You can increment and decrement them according to the overall score counter.

Changing the value of a 2d array every x turns?

Im creating an 'Avoid the Blocks' game, and for this i need to move a character around a grid (2D array) using the keys GHKJ. Every x amount of turns (decreasing as the level increases) a shadow must appear, then that shadow becomes a block and if the player moves into that bloack they lose a life.
Most of this is done for me other than the seemingly simple taski of getting the blocks to appear, here is my code so far for the falling blocks:
public void rocked(){
int rockInit = turn;
if(rockInit > 1){
int save = turn;
System.out.println(turn + " ");
B.board[ran.nextInt(12)][ran.nextInt(12)] = shadow;
if(save == turn - 3){
B.board[rockLocX][rockLocY] = rock;
}
}
}
The system.println is simply for debugging purposes, checking the values are being accesed. Turn is increased by 1 for every move the player makes, ran.nextInt(12) is a randomly generated number between 0 and 11, and B.board is the playing board.
It looks like you're never changing "save" after you initialize it to "turn". So then when you check if(save == turn-3), it will always be false, and so never move the block in. If you want to keep track of how many turns have passed, I would recommend a private instance variable "int turnsPassed" that you can increment each turn. Then for each level, you can check if (turnsPassed % x == 0), where x is as you've described it. Hope that helps!

Categories

Resources