Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
I have an enum Direction which shows legal walking directions. With the helper-method turnLeft
I want to change the value of the called enum Variable, but it does not work: The value of the enum Variable directionis the same after the call of the method.
enum Direction{
UP, RIGHT, DOWN, LEFT
}
private Direction direction = Direction.DOWN;
public void turnLeft(Direction direction) {
switch(direction) {
case UP: this.direction = Direction.LEFT; break;
case RIGHT: this.direction = Direction.UP; break;
case DOWN: this.direction = Direction.RIGHT; break;
case LEFT: this.direction = Direction.DOWN; break;
}
}
What am I doing wrong?
You can add the turnLeft/ turnRight methods directly inside the enum.
enum Direction{
UP, RIGHT, DOWN, LEFT;
public Direction turnLeft() {
switch(this) {
case UP: return LEFT;
case RIGHT: return UP;
case DOWN: return RIGHT;
default: return DOWN; // if you leave the LEFT case, you still need to return something outside the block on some Java versions
}
}
}
and then whenever you want to make a turn, you can assign the "left" value to the direction variable.
private Direction direction = Direction.DOWN;
public void turnAndPrint() {
direction = direction.turnLeft();
System.out.println(direction.name()); // will print RIGHT when called the first time
}
Related
*I am working on a game that's played on a chess like board with only pawns. A pawn can move, or take an opponents piece. To move it goes one tile forward, to take it goes one tile forward and one to the side.
As the move action is also part of every take action I was wondering if I can somehow combine those two. I tried to integrate the move method in my take method, but it didn't work, supposedly because the method doesn't know which piece it is associated with.
Both methods alter the attributes (x-coordinate and y-coordinate) of my piece to mark it's location on the board.
Can I do it in some other way?
/*
* move action
* differentiates between Black and White pieces, so both use the same method to move
*/
public void move() {
switch(color) {
case "White":
this.yCo = this.yCo+1;
break;
case "Black":
this.yCo = this.yCo-1;
break;
}
}
/*
* take action
* moves one tile forward and one tile to either left or right and removes an opponents piece on that tile
*/
public void takeRight() {
this.move();
this.xCo = this.xCo+1;
}
```*
public void move(int xShift) {
switch(color) {
case "White":
this.yCo = this.yCo+1;
break;
case "Black":
this.yCo = this.yCo-1;
break;
}
this.xCo += xShift;
}
this.xCo += xShift is short for this.xCo = this.xCo + xShift. You may also remove the dedundant this
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am new to java learning java from home using udacity.com and they fave given a question which i am stuck and cant get it working.
project is just to check if player move is not out of bound in chess game and then to see if Queen's move is valid or not. we have to see these 3 thing should work.
In the Queen class, override the isValidMove method
First call the parent's isValidMove to check for the boundaries.
Add more code to check for the Queen's specific move validity.
I have Main class, Game class, Position class, Piece class(Parent class) Queen class(child).
I got 1 and 3 working but can't understand how to get 2nd working it gives me error if i try calling Piece.isValidMove in main before Queen.isValidMove.
my codes as follows
Main.java
public class Main {
public static void main(String[] args) {
Piece piece = new Piece();
Queen queen = new Queen();
Position testPosition = new Position(3,7);
if(queen.isValidMove(testPosition)){
System.out.println("Yes, I can move there.");
}
else {
System.out.println("Nope, can't do!");
}
}
}
Game.java
public class Game {
Piece [][] board;
// Constructor creates an empty board
Game(){
board = new Piece[8][8];
}
}
Position.java
public class Position {
int row;
int column;
// Constructor using row and column values
Position(int r, int c){
this.row = r;
this.column = c;
}
}
Piece.java
public class Piece {
Position position;
boolean isValidMove(Position newPosition){
if(position.row>0 && position.column>0
&& position.row<8 && position.column<8){
return true;
}
else{
return false;
}
}
}
Queen.java
public class Queen extends Piece {
int row;
int column;
boolean isValidMove(Position newPosition){
if(newPosition.column == this.column || newPosition.row == this.row|| Math.abs(newPosition.column - this.column) == Math.abs(newPosition.row - this.row)){
return true;
}
else{
return false;
}
}
}
Thank you.
but can't understand how to get 2nd working it gives me error if i try calling Piece.isValidMove in main before Queen.isValidMove
The task says you need to call the parent's isValidMove in Queen.isValidMove, not in Main. And the syntax you need is super.isValidMove. So in Queen.java, do
boolean isValidMove(Position newPosition){
// combine super.isValidMove(newPosition) and your current code
}
You don't need to change Main.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
i'm having trouble making some java code i have work with android studio, the main problems i'm having is turning keyboard inputs into swipes and presses from the user, this is my current code for keyboard inputs:
class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e) {
if (!isStarted || curPiece.getShape() == foodShapes.NoShape) {
return;
}
int keycode = e.getKeyCode();
if (keycode == 'p' || keycode == 'P') {
pause();
return;
}
if (isPaused)
return;
switch (keycode) {
case KeyEvent.VK_LEFT:
tryMove(curPiece, curX - 1, curY);
break;
case KeyEvent.VK_RIGHT:
tryMove(curPiece, curX + 1, curY);
break;
case KeyEvent.VK_DOWN:
tryMove(curPiece.rotateRight(), curX, curY);
break;
case KeyEvent.VK_UP:
tryMove(curPiece.rotateLeft(), curX, curY);
break;
case KeyEvent.VK_SPACE:
dropDown();
break;
case 'd':
oneLineDown();
break;
case 'D':
oneLineDown();
break;
}
any help would be appreciated, thankyou.
This page is available within the android documentation and tutorials....
public class MainActivity extends Activity {
...
// This example shows an Activity, but you would use the same approach if
// you were subclassing a View.
#Override
public boolean onTouchEvent(MotionEvent event){
int action = MotionEventCompat.getActionMasked(event);
switch(action) {
case (MotionEvent.ACTION_DOWN) :
Log.d(DEBUG_TAG,"Action was DOWN");
return true;
case (MotionEvent.ACTION_MOVE) :
Log.d(DEBUG_TAG,"Action was MOVE");
return true;
case (MotionEvent.ACTION_UP) :
Log.d(DEBUG_TAG,"Action was UP");
return true;
case (MotionEvent.ACTION_CANCEL) :
Log.d(DEBUG_TAG,"Action was CANCEL");
return true;
case (MotionEvent.ACTION_OUTSIDE) :
Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
"of current screen element");
return true;
default :
return super.onTouchEvent(event);
}
}
I would suggest, however, that you use Google in the future, before seeking assistance on stack overflow. The attached link was located via Google on the first page of results for "android - detect input gestures within your app". In addition, I believe that I have come across a question that was directly related to this and it was answered in full.
Please remember; Stack Overflow is not here so that you can be lazy - its here so that you can seek assistance when it is actually required..
This question already has answers here:
Java KeyListener stutters
(3 answers)
Closed 9 years ago.
Okay, so I am making a 2D side scroller game for school. It is pretty much just like Mario (well, that is my hope for when I finish.) When I press the right arrow key to move my player along the map, he moves once, pauses, and then begins to smoothly move a lot. I think this is because of the pause that is in all apple laptops when you hold a key down, but I do not know how to get around this for my game. Any advice? Thank you.
One solution is to set boolean keyUP = true inside the keypressed method and keyUP = false inside the keyreleased method. This way once the key has been pressed your game registers this as "keep moving up" until you release the key, instead of "Up was pressed move up, up was pressed move up....". This removes that initial lag (very noticable on linux) on input.
From our game:
private boolean up, down, left, right;
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_S:
down = false;
break;
case KeyEvent.VK_W:
up = false;
break;
case KeyEvent.VK_A:
left = false;
break;
case KeyEvent.VK_D:
right = false;
break;
}
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_S:
down = true;
break;
case KeyEvent.VK_W:
up = true;
break;
case KeyEvent.VK_A:
left = true;
break;
case KeyEvent.VK_D:
right = true;
break;
Although you have not sent any code snippet I can assume the following. I think that you have implemented key listener that does something when key is pressed. If user remains pressing the key your program gets the second event after some delay and then starts getting the events faster.
This is not what you need. You probably should hold some kind of application state keyIsPressed that is changed only once when the key is down (not pressed) first time. Then turn this variable off only when key is up. When key is down first time start background thread that moves your object and checks the flag keyIsPressed periodically to know when to stop.
Good luck to become a competitor of Mario... :)
If this is a Swing GUI, then use Key Bindings, not a key listener,
start a Swing Timer on key press
and stop it on key release.
All KeyEvents are integers, so you can make boolean[] which will store all changes in KeyEvents. For Java2d am using something like this:
import java.awt.KeyEventDispatcher;
import java.awt.event.KeyEvent;
public final class Keyboard implements KeyEventDispatcher {
public static boolean[] keyPressed = new boolean[256];
public static boolean[] keyHold = new boolean[256];
public static boolean[] keyReleased = new boolean[256];
public static void update() {
for (int i=0; i<128; i++) {
keyPressed[i] = false;
keyReleased[i] = false;
}
}
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID()==KeyEvent.KEY_PRESSED) {
keyHold[e.getKeyCode()] = true;
keyPressed[e.getKeyCode()] = true;
}
else if (e.getID()==KeyEvent.KEY_RELEASED) {
keyHold[e.getKeyCode()] = false;
keyReleased[e.getKeyCode()] = true;
}
return false;
}
}
I am calling update() after each frame.
[UPDATE] i changed the order a bit so i call the super.act(delta) at the end of the method and it seems to help a bit! But not that sure about it yet.
I got a square system for my map. So its an 2D array and i i make one move the figure does move from one square to the next. While that it's not possible to "stop" the figure between 2 squares. When my characters made one move i check if the Touchpad is touched and if yes i start the next move. While that it seems to lag sometimes and i dont know why!? I really hope you may find the "lag". Here is how i calculate the next move inside the act()of my Actor Character:
#Override
public void act(float delta) {
super.act(delta); // so the actions work
if (moveDone) {
if (screen.gameHud.pad.isTouched()) {
// check in which direction is the touchcontroller
if (screen.gameHud.pad.getKnobPercentX() < 0
&& Math.abs(screen.gameHud.pad.getKnobPercentY()) < Math
.abs(screen.gameHud.pad.getKnobPercentX())) {
// checkt if the |x|>|y|
if (checkNextMove(Status.LEFT)) {
this.status = Status.LEFT;
move(Status.LEFT);
this.screen.map.mapArray[(int) (this.mapPos.x)][(int) this.mapPos.y] = Config.EMPTYPOSITION;
this.screen.map.mapArray[(int) (this.mapPos.x - 1)][(int) this.mapPos.y] = Config.CHARSTATE;
this.mapPos.x--;
moveDone = false;
}
} else if //.... rest is the same just with other directions
else{ //if touchpad isnt touched!
setIdle();
}
updateSprite(delta); //just change the textureRegion if its time for that
} //methode end
Okay so you need some more informations i am sure. Checkmoves like this:
case LEFT:
if (this.mapPos.x - 1 >= 0)
if (this.screen.map.mapArray[(int) (this.mapPos.x - 1)][(int) this.mapPos.y] == Config.EMPTYPOSITION)
return true;
break; //same for all other just direction changin
And the last you need to know is the move(_) i guess. It does add an moveTo Action to my figures.
public void move(Status direction) {
switch (direction) {
case LEFT:
this.addAction(Actions.sequence(
Actions.moveTo((getX() - Config.BLOCK_SIZE), getY(), speed),
moveDoneAction));
break;
moveDoneAction is a simple RunnableAction that set the boolean moveDone to true if its done moving.
i really hope you can help. If you need some more informations please let me know as comment!
There are better tools than StackOverflow for optimizing Android code. Use a profiler and see what is actually happening. Specifically, the traceview profiler: how to use traceview in eclipse for android development? (If you're not using Eclipse, you can use traceview directly via the ADT.)