Turning around at edges of a world - java

For a project I am supposed to write code that will have an actor have a chance to turn left or right 25% and then move 50% and then it is also supposed to avoid running out of bounds. The following code is what I have so far but I am not sure what isn't working because i am still having problem keeping the actor inbounds. Thanks
/**
* Creates a new Food object.
*/
public Food()
{
super();
}
//~ Methods ...............................................................
// ----------------------------------------------------------
/**
* Take one step, either forward or after turning left or right.
*/
public void act()
{
int x = Random.generator().nextInt(100);
this.changeDirection();
if (x < 25)
{
this.turn(LEFT);
}
else if ((25 < x) && ( x < 50))
{
this.turn(RIGHT);
}
else
{
this.move();
}
}
public void turnAround()
{
this.turn(RIGHT);
this.turn(RIGHT);
}
public void changeDirection()
{
if ((this.getGridY() == this.getWorld().getHeight() ||
this.getGridX() == this.getWorld().getWidth()))
{
this.turnAround();
this.move();
}
else if ((this.getGridY() == 0 || this.getGridX() == 0))
{
this.turnAround();
this.move();
}
else if ((this.getGridY() == this.getWorld().getHeight()) &&
this.getGridX() == this.getWorld().getWidth())
{
this.turnAround();
this.move();
}
else if ((this.getGridY() == 0) && (this.getGridX() == 0))
{
this.turnAround();
this.move();
}
}

Related

How to make the movement of my object smoother and behave more like a vehicle

I am making a parking game in JavaFX. I am not satisfied with the current movement of my vehicle, but I don't know how I could make it better. If anyone could point me to the right direction or maybe even provide some code i would be really thankful.
Here is my current code for the movement:
Scene scene = new Scene(layout, 1380,720);
stage.setScene(scene);
layout.setStyle("-fx-background-color: green");
DoubleProperty x = new SimpleDoubleProperty(0);
DoubleProperty y = new SimpleDoubleProperty(-3);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent keyEvent) {
if (keyEvent.getCode() == KeyCode.UP) {
ucar.setTranslateY(ucar.getTranslateY() + y.getValue());
ucar.setTranslateX(ucar.getTranslateX() + x.getValue());
} else if (keyEvent.getCode() == KeyCode.DOWN) {
ucar.setTranslateY(ucar.getTranslateY() - y.getValue());
ucar.setTranslateX(ucar.getTranslateX() - x.getValue());
}
else if(keyEvent.getCode() == KeyCode.LEFT){
ucar.setRotate(ucar.getRotate()%360 -45);
}
else if(keyEvent.getCode() == KeyCode.RIGHT){
ucar.setRotate(ucar.getRotate()%360 +45);
double d = x.getValue();
}
if(ucar.getRotate() == 0){
x.setValue(0);
y.setValue(-3);
}
else if(ucar.getRotate() == -90 || ucar.getRotate() == 270) {
x.setValue(-3);
y.setValue(0);
}
else if(ucar.getRotate() == -180 || ucar.getRotate() == 180){
x.setValue(0);
y.setValue(3);
}
else if(ucar.getRotate() == 90 || ucar.getRotate() == -270){
x.setValue(3);
y.setValue(0);
}
else if(ucar.getRotate() == -360 || ucar.getRotate() == 360){
x.setValue(0);
y.setValue(-3);
}
else if(ucar.getRotate() == -45 || ucar.getRotate() == 315) {
x.setValue(-2);
y.setValue(-2);
}
else if(ucar.getRotate() == -135 || ucar.getRotate() == 225) {
x.setValue(-2);
y.setValue(2);
}
else if(ucar.getRotate() == 45 ) {
x.setValue(2);
y.setValue(-2);
}
else if(ucar.getRotate() == 135) {
x.setValue(2);
y.setValue(2);
}
for (int i = 0; i < cars.length; i++) {
if(cars[i] == ucar){
break;
}
if(cars[i].getBoundsInParent().intersects(ucar.getBoundsInParent())){
loseGame(stage);
return;
}
}

make players change after certain time in java

I want to add the following functionality in a tictactoe game: if a player is on turn but he/she doesn't do anything for a certain time (10 seconds), than it's the another player's turn.
In the "GameHub" class (extends a Server class for creating only one game) I have the inner class "GameState", which maintains the current state of the game and passes it as a message to the server (and then it is forwarded to all clients/players).
public class GameHub extends Server {
private GameState state;
public GameHub(int port) throws IOException {
super(port);
state = new GameState();
setAutoreset(true);
}
protected void messageReceived(int playerID, Object message) {
state.applyMessage(playerID, message);
sendToAll(state);
}
protected void playerConnected(int playerID) {
if (getPlayerList().length == 2) {
shutdownServerSocket();
state.startFirstGame();
sendToAll(state);
}
}
protected void playerDisconnected(int playerID) {
state.playerDisconnected = true;
sendToAll(state);
}
public static class GameState implements Serializable {
public boolean playerDisconnected;
public char[][] board;
public boolean gameInProgress;
public int playerPlayingX;
public int playerPlayingO;
public int currentPlayer;
public boolean gameEndedInTie;
public int winner;
public void applyMessage(int sender, Object message) {
if (gameInProgress && message instanceof int[] && sender == currentPlayer) {
int[] move = (int[]) message;
if (move == null || move.length != 2) {
return;
}
int row = move[0];
int col = move[1];
if (row < 0 || row > 2 || col < 0 || col > 2 || board[row][col] != ' ') {
return;
}
board[row][col] = (currentPlayer == playerPlayingX) ? 'X' : 'O';
if (winner()) {
gameInProgress = false;
winner = currentPlayer;
} else if (tie()) {
gameInProgress = false;
gameEndedInTie = true;
}
else {
currentPlayer = (currentPlayer == playerPlayingX) ? playerPlayingO : playerPlayingX;
}
} else if (!gameInProgress && message.equals("newgame")) {
startGame();
}
}
void startFirstGame() {
startGame();
}
private void startGame() {
board = new char[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = ' ';
}
}
int xPlr = (Math.random() < 0.5) ? 1 : 2;
playerPlayingX = xPlr; // Will be 1 or 2.
playerPlayingO = 3 - xPlr; // The other player ( 3 - 1 = 2, and 3 - 2 = 1 )
currentPlayer = playerPlayingX;
gameEndedInTie = false;
winner = -1;
gameInProgress = true;
}
private boolean winner() {
if (board[0][0] != ' '
&& (board[0][0] == board[1][1] && board[1][1] == board[2][2])) {
return true;
}
if (board[0][2] != ' '
&& (board[0][2] == board[1][1] && board[1][1] == board[2][0])) {
return true;
}
for (int row = 0; row < 3; row++) {
if (board[row][0] != ' '
&& (board[row][0] == board[row][1] && board[row][1] == board[row][2])) {
return true;
}
}
for (int col = 0; col < 3; col++) {
if (board[0][col] != ' '
&& (board[0][col] == board[1][col] && board[1][col] == board[2][col])) {
return true;
}
}
return false;
}
private boolean tie() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
}
}
For the time measurement I have the "Countdown" class, which aim is to change the players after the required time elapsed.
public class Countdown {
int timer;
public void counter(int timeFrame) {
timer = timeFrame;
Timer TimerA = new Timer();
TimerTask TaskA = new TimerTask() {
#Override
public void run() {
if (timer >= 0) {
timer--;
}
if (timer == -1) {
currentPlayer = (currentPlayer == playerPlayingX) ? playerPlayingO : playerPlayingX;
TimerA.cancel();
}
}
};
TimerA.schedule(TaskA, 0, 1000);
}
public int getTimer(){
return timer;
}
}
Exactly at that part I'm stuck. In my opinion I need to add and start the timer somewhere in the "GameState" class, but for some reason I can't figure it out where exactly.
int timeFrame = 10;
Countdown C = new Countdown();
C.counter(timeFrame);
I thought it should be started in that "else block"
else {currentPlayer = (currentPlayer == playerPlayingX) ? playerPlayingO : playerPlayingX;
int timeFrame = 10;
Countdown C = new Countdown();
C.counter(timeFrame);}
But it doesn't work properly => it works just for "playerPlayingO" (if he delays 10 seconds, he misses his turn). playerPlayingX is not affected...
May be I'm also missing something else...
If you're using a JavaFX you may use a task for this - Just make the task run something like this:
Thread.sleep(10000); //Wait 10 Secs
if (activePlayer == initialActivePlayer) switchPlayer(); //Better write your own "ShouldWeSwitch"-Condition
You may need to fiddle around with synchronization a little and maybe terminate the tasks when the players trigger the switch but this may work for your game.
PS: If you're not using JavaFX you can simply make your own Task by creating a class that extends Thread

Turning around at the edges of a world (Java)

I'm trying to get an object to wander around the world randomly.
This object has a 25% chance of turning left, 25% chance of turning right, and 50% chance of moving straight.
I have to ensure that the random direction chosen is not one that will take the object out of bounds. I used getGridX() and getGridY() to check the current object's coordinate position to determine if it is at the edge. And I've only actively considered 2 of the corners of the world.
However, it keeps getting forced outside the world.
What is my code doing wrong?
import sofia.micro.*;
import sofia.util.Random;
//-------------------------------------------------------------------------
public class Food extends SimpleActor
{
//~ Constructor ...........................................................
/**
* Creates a new Food object.
*/
public Food()
{
super();
}
//~ Methods ...............................................................
// ----------------------------------------------------------
/**
* 25% chance of turning left
* 25% chance of turning right
* 50% chance of moving forward
*/
public void act()
{
int value = Random.generator().nextInt(100);
this.changeDirection();
if (value < 25)
{
this.turn(LEFT);
this.changeDirection();
}
else if (value < 50)
{
this.turn(RIGHT);
this.changeDirection();
}
else
{
this.move();
this.changeDirection();
}
}
/**
* make a U-turn
*/
public void turnAround()
{
this.turn(RIGHT);
this.turn(RIGHT);
}
/**
* detects edge condition and moves away
*/
public void changeDirection()
{
if ((this.getGridY() == this.getWorld().getHeight()) ||
(this.getGridX() == this.getWorld().getWidth()))
{
this.turnAround();
this.move();
}
if ((this.getGridY() == 0) || (this.getGridX() == 0))
{
this.turnAround();
this.move();
}
if ((this.getGridY() == this.getWorld().getHeight()) &&
(this.getGridX() == this.getWorld().getWidth()))
{
this.turnAround();
this.move();
}
if ((this.getGridY() == 0) && (this.getGridX() == 0))
{
this.turnAround();
this.move();
}
}
}
It looks like the following condition is written twice. If you're facing out of bounds, wouldn't you do a 360, instead of a 180? I would remove the latter 2 if statements.
if ((this.getGridY() == this.getWorld().getHeight()) &&
(this.getGridX() == this.getWorld().getWidth()))
{
this.turnAround();
this.move();
}
Assuming that the turn() method is properly implemented (I don't see it in your code), here is one problem I found:
if (value < 25)
{
this.turn(LEFT);
this.changeDirection();
}
else if (value < 50)
{
this.turn(RIGHT);
this.changeDirection();
}
else
{
this.move(); // < --- You shouldn't be using this here
this.changeDirection();
}
Remove that line. Because when this statement is reached, it is possible that your actor is in an edge and facing into emptiness - and you are literally telling it to move forward.
Instead, remove the line and just call changeDirection(), which will cause the actor to turn 180 degrees. I see that changeDirection() will also cause the actor move, so basically your actor will move away from the edge.

Java convert else { if {} } to elseif {}

I'm looking for any existing code or library in java or a similar language to convert given the following (which is not java, but a custom language)
if (i < 0) {
i = 0;
} else {
if (i > 100) {
i = 100;
}
}
into elseif like this:
if (i < 0) {
i = 0;
} else if (i > 100) {
i = 100;
}
This code is not java but I want to convert it using java.
Here is what I tried to acomplish this but it's not working
String elseB = "else {";
int index = output.indexOf(elseB);
while (index != -1) {
output = output.substring(index + 1);
index = output.indexOf(elseB);
if (index != -1) {
int ifAt = index + elseB.length() + 1;
String elseStart = output.substring(ifAt).trim();
if (elseStart.startsWith("if")) {
int closingBracket = findClosingBracket(
output.toCharArray(), index);
int openingBracket = ifAt - 1;
String justBlock = output.substring(openingBracket,
closingBracket).trim();
output = output.substring(0, openingBracket - 1) + justBlock + output.substring(closingBracket);
}
}
}
a more complicated example would be converting this:
if (i == 1) {
} else {
if (i == 2) {
} else {
if (i == 3) {
} else {
if (i == 4) {
} else {
if (i == 5) {
} else {
if (i == 6) {
} else {
if (i == 7) {
} else {
if (i == 8) {
} else {
if (i == 9) {
} else {
if (i == 10) {
} else {
if (i == 22) {
} else {
if (i == 11) {
} else {
if (i == 12) {
} else {
if (i == 25) {
} else {
if (i == 13) {
} else {
if (i == 14) {
} else {
if (i == 15) {
} else {
if (i == 24) {
} else {
if (i == 16) {
} else {
if (i == 17) {
} else {
if (i == 18) {
} else {
if (i == 21) {
} else {
if (i == 19) {
} else {
if (i == 20) {
} else {
if (i == 23) {
} else {
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
into this
if (i == 1) {
} else if (i == 2) {
} else if (i == 3) {
} else if (i == 4) {
} else if (i == 5) {
} else if (i == 6) {
} else if (i == 7) {
} else if (i == 8) {
} else if (i == 9) {
} else if (i == 10) {
} else if (i == 22) {
} else if (i == 11) {
} else if (i == 12) {
} else if (i == 25) {
} else if (i == 13) {
} else if (i == 14) {
} else if (i == 15) {
} else if (i == 24) {
} else if (i == 16) {
} else if (i == 17) {
} else if (i == 18) {
} else if (i == 21) {
} else if (i == 19) {
} else if (i == 20) {
} else if (i == 23) {
} else {
}
I assume you want to change the code, not the compiled bytecode. For that you would look into text replacing. Depending on your editor you can replace all the instances of this text with the elif statement. If your editor can not do it, look into regular expressions. With those you can change the lines in no time.
If trying to test a single value vs various conditions,could try to use switch statemenet instead various if statements.
ie.
switch(i){
case(i <= 0):
i=0;
case(i >= 100):
i=100;
}

Android MultiTouch does not work

#Override
public boolean onTouchEvent(MotionEvent event)
{
synchronized (getHolder())
{
int aktion = event.getAction();
if (aktion == MotionEvent.ACTION_DOWN)
{
touched = true;
bar.shareTouch(event.getX(), event.getY(), touched);
}
else if (aktion == MotionEvent.ACTION_UP)
{
touched = false;
bar.shareTouch(event.getX(), event.getY(), touched);
}
if (aktion == MotionEvent.ACTION_POINTER_DOWN)
{
touched2 = true;
bar.shareTouch2(event.getX(), event.getY(), touched2);
}
else if (aktion == MotionEvent.ACTION_POINTER_UP)
{
touched2 = false;
bar.shareTouch2(event.getX(), event.getY(), touched2);
}
}
return true;
}
This is a Code to chech if first Finger is going onto the screen or leaving it. The same for another finger.
public void shareTouch2(float xTouch2, float yTouch2, boolean touched2)
{
if (xTouch2 <= gameViewWidth/2) {
if (touched2 == true) {
touchedLeft2 = true;
}
else if(touched2 == false) {
touchedLeft2 = false;
}
}
else if (xTouch2 > gameViewWidth/2) {
if (touched2 == true) {
touchedRight2 = true;
}
else if(touched2 == false) {
touchedRight2 = false;
}
}
}
public void shareTouch(float xTouch, float yTouch, boolean touched)
{
if (xTouch <= gameViewWidth/2) {
if (touched == true) {
touchedLeft = true;
}
else if(touched == false) {
touchedLeft = false;
}
}
else if (xTouch > gameViewWidth/2) {
if (touched == true) {
touchedRight = true;
}
else if(touched == false) {
touchedRight = false;
}
}
}
private void moveRight()
{
x += 3;
}
private void moveLeft()
{
x -= 3;
}
private void checkTouch() {
if ((touchedLeft == true && touchedRight2 == false) || (touchedLeft2 == true && touchedRight == false)) {
moveLeft();
}
else if ((touchedLeft == false && touchedRight2 == true) || (touchedLeft2 == false && touchedRight == true)) {
moveRight();
}
else if ((touchedLeft == true && touchedRight2 == true) || (touchedLeft2 == true && touchedRight == true)) {
}
}
The checkTouch() is called in the onDraw() Method. Now if I place a finger on the right side of the screen it moves right. Same for left. But if I touch left and the right without removing the left finger the Object still moves left although it should stop. Now when I leave the left finger it still moves left although it should move right.
I hope you understand my problem.
Hope you can help
You can't just assume the ACTION_POINTER_UP Event will only be sent for the same finger ACTION_POINTER_DOWN was sent.
Just as the ACTION_DOWN event is always fired for the first finger to touch down, the ACTION_UP event is only fired for the last finger to lift (i.e. when there are no more fingers on the screen). All others will get an ACTION_POINTER_UP event, even if it's the finger that started the gesture.
However, the Android documentation does specify
Each pointer has a unique id that is assigned when it first goes down [and] remains valid until the pointer eventually goes up.
So in theory, your first and second finger should still have the same ID, regardless whether the Event that reports them.
The solution is simple, then: Use getPointerCount() and getPointerID() to keep track of your fingers.
This may be easier if you refactor your code to account for more than two fingers by replacing the Booleans touchedLeft and touchedLeft2 with a single counter, e.g. fingersOnLeftSide - which has the neat side effect of only needing one shareTouch() method and otherwise reducing redundancy in your code.
EDIT:
Disclaimer: This is just off the top of my head, untested and written without knowledge of any of your code other than what you posted. Not necessarily the best way to solve your problem, but the shortest I could think of.
This is the Event handler:
public boolean onTouchEvent(MotionEvent event)
{
synchronized (getHolder())
{
int aktion = event.getAction();
if (aktion == MotionEvent.ACTION_DOWN || aktion == MotionEvent.ACTION_POINTER_DOWN
|| aktion == MotionEvent.ACTION_UP || aktion == MotionEvent.ACTION_POINTER_UP)
{
bar.clearTouches();
for (int i = 0; i < event.getPointerCount(); i++) {
bar.shareTouch(event.getX(i)); // we don't need the y coordinate anyway
}
}
}
return true;
}
The rewritten shareTouch() to go along with it, as well as clearTouches() I introduced to make this simpler:
private void shareTouch(float x)
{
if (x < gameViewWidth/2) {
fingersLeft++;
} else {
fingersRight++;
}
}
private void clearTouches()
{
fingersLeft = 0;
fingersRight = 0;
}
And finally, the new checkTouch():
public void checkTouch()
{
if (fingersLeft > fingersRight) {
moveLeft();
} else if (fingersRight > fingersLeft) {
moveRight();
}
}

Categories