Currently I have a game that I am building in Netbeans, and have been able to create a board, place the pieces and allow them to be moved anywhere using mouseveent's
But now I have ran into a problem when trying to code the pieces on the board to only do allowed actions.
The problem I am having is that every piece is still allowed to be moved but now when it is moved the selected piece disappears from the board completely ingorning all the new function in the mouse release event
The code I am trying to add is for the WhitePawn which is the only piece that should be allowed to move right now
The rest if they are tried to move should just return to there set positions regardless of where they are dragged. I have removed all code not relevant to the question and ran the debugger. From that I know a fact that the problem is somewhere in the mouse release event code, I just cant find it.
public void mouseReleased(MouseEvent e) {
if (chessPiece == null) {
return;
}
chessPiece.setVisible(false);
Boolean success = false;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
String tmp = chessPiece.getIcon().toString();
String pieceName = tmp.substring(0, (tmp.length() - 4));
Boolean validMove = false;
//Pawn Moves
//White Pawn
if (pieceName.equals("WhitePawn")) {
if (startY == 1) {
if ((startX == (e.getX() / 75)) && ((((e.getY() / 75) - startY) == 1) || ((e.getY() / 75) - startY) == 2)) {
if ((((e.getY() / 75) - startY) == 2)) {
if ((!piecePresent(e.getX(), (e.getY()))) && (!piecePresent(e.getX(), (e.getY() + 75)))) {
validMove = true;
} else {
validMove = false;
}
} else {
if ((!piecePresent(e.getX(), (e.getY())))) {
validMove = true;
} else {
validMove = false;
}
}
} else {
validMove = false;
}
} else {
int newY = e.getY() / 75;
int newX = e.getX() / 75;
if ((startX - 1 >= 0) || (startX + 1 <= 7)) {
if ((piecePresent(e.getX(), (e.getY()))) && ((((newX == (startX + 1) && (startX + 1 <= 7))) || ((newX == (startX - 1)) && (startX - 1 >= 0))))) {
if (checkWhiteOponent(e.getX(), e.getY())) {
validMove = true;
if (startY == 6) {
success = true;
}
} else {
validMove = false;
}
} else {
if (!piecePresent(e.getX(), (e.getY()))) {
if ((startX == (e.getX() / 75)) && ((e.getY() / 75) - startY) == 1) {
if (startY == 6) {
success = true;
}
validMove = true;
} else {
validMove = false;
}
} else {
validMove = false;
}
}
} else {
validMove = false;
}
}
}
if (!validMove) {
int location = 0;
if (startY == 0) {
location = startX;
} else {
location = (startY * 8) + startX;
}
String pieceLocation = pieceName + ".png";
pieces = new JLabel(new ImageIcon(getClass().getResource(pieceLocation)));
panels = (JPanel) chessBoard.getComponent(location);
panels.add(pieces);
} else {
if (success) {
int location = 56 + (e.getX() / 75);
if (c instanceof JLabel) {
Container parent = c.getParent();
parent.remove(0);
pieces = new JLabel(new ImageIcon(getClass().getResource("WhiteQueen.png")));
parent = (JPanel) chessBoard.getComponent(location);
parent.add(pieces);
} else {
Container parent = (Container) c;
pieces = new JLabel(new ImageIcon(getClass().getResource("WhiteQueen.png")));
parent = (JPanel) chessBoard.getComponent(location);
parent.add(pieces);
}
} else {
if (c instanceof JLabel) {
Container parent = c.getParent();
parent.remove(0);
parent.add(chessPiece);
} else {
Container parent = (Container) c;
parent.add(chessPiece);
}
chessPiece.setVisible(true);
}
}
}
Image showing the folder layout of My build in case I have you can see somewhere that is not linked probably
Hopefully someone can see where I am going wrong, as I just want to get one piece moving before I split the pieces away from the board.java file completely into a new java file
I've looked through some of your code, again there's too much for me to go through in its entirety, but please let me give you some suggestions.
This is brittle/dangerous code:
JLabel awaitingPiece = (JLabel) c1;
String tmp1 = awaitingPiece.getIcon().toString();
if (((tmp1.contains("White")))) {
You're using an object's toString() representation as part of your code logic which is something you should never do. You're also doing String manipulations on the String returned, and again using the returned String for code logic,
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
String tmp = chessPiece.getIcon().toString();
String pieceName = tmp.substring(0, (tmp.length() - 4));
Boolean validMove = false;
again something that is dangerous to do.
Instead, you could get the Icon and compare for Icon equality via the equals(...) method. Even better though is to get your logic out of your GUI and into the Model section of your program. If you can fully separate concerns, you'll stand a much better chance of having smaller units of code that are much easier to debug for both you and for us.
Otherwise, to get a better more complete answer, you're still going to want to first work to isolate the error, and for that, I still recommend that you use an MCVE.
Also I see that you're checking if an Icon is named "WhitePawn"
chessPiece.setVisible(false);
Boolean success = false;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
String tmp = chessPiece.getIcon().toString();
String pieceName = tmp.substring(0, (tmp.length() - 4));
Boolean validMove = false;
//Pawn Moves
//White Pawn
if (pieceName.equals("WhitePawn")) {
When in actuality I'll bet that it's named something quite differently. Since your Strings are playing a key role in your program (too great a role, I fear) are you debugging your String values to see why the code doesn't work?
For instance, a few println's could do wonders:
chessPiece.setVisible(false);
Boolean success = false;
Component c = chessBoard.findComponentAt(e.getX(), e.getY());
String tmp = chessPiece.getIcon().toString();
String pieceName = tmp.substring(0, (tmp.length() - 4));
System.out.println("pieceName is: " + pieceName); // ******* Added ********
Boolean validMove = false;
Myself, I'd not use Strings for this but rather would use enums, something you know will be stable and will be exactly what you assume it to be.
Related
I'm writing a little program for a school project. The theme is "objective Coding" so there's the "main Tab" where the draw method and setup method is. In other tabs, I wrote other classes and functions.
So in the my "main Tab" there's the function void draw and it looks like this:
void draw() {
background();
h1.displayH();
steuerungH();
t1.displayT();
}
The three methods background();, h1.displayH(); and t1.displayT(); worked without a problem. I tried writing the code like:
...
...
h1.streuerungH();
...
h1 is an object, a rectangle I try to move with the function void steuerungH();, but there's always an error saying:
The function steuerungH() does not exist.
Im not sure what the problem exactly is, because the class in which I wrote the function void steuerungH(); looks exacltly like the others
float gravity = 0.1;
float speed = 0;
class Steuerung {
void steuerungH(){
if (key == UP|| key == 'w') {
playerYPosition = playerYPosition +speed;
speed = speed + gravity;
if (playerYPosition >= 30); {
speed = speed *-1;
}
} else if (key == DOWN ||key == 's') {
/*Duck methode muss noch geschrieben werden*/
} else if (key == RIGHT || key == 'd') {
playerXPosition = playerXPosition +10;
} else if (key == LEFT ||key == 'a') {
playerXPosition = playerXPosition -10;
}
}
}
First of all you should think about playerXPosition and playerYPosition. Wouldn't it be better to create a class Player with the attributes playerXPosition and playerYPosition and a method streuerungH?
class Player {
float gravity = 0.1;
float speed = 0;
float playerXPosition;
float playerYPosition;
// [...]
void steuerungH(){
if (key == UP|| key == 'w') {
playerYPosition = playerYPosition +speed;
speed = speed + gravity;
if (playerYPosition >= 30); {
speed = speed *-1;
}
} else if (key == DOWN ||key == 's') {
/*Duck methode muss noch geschrieben werden*/
} else if (key == RIGHT || key == 'd') {
playerXPosition = playerXPosition +10;
} else if (key == LEFT ||key == 'a') {
playerXPosition = playerXPosition -10;
}
}
}
Anyway, if you want to keep your current designe, then you have to options to solve the issue:
Create an instance of Steuerung. e.g.
Steuerung s = new Steuerung();
void draw() {
// [...]
s.streuerungH();
// [...]
}
The other option is:
Since Processing provides functions in global namespace, you can turn steuerungH to a function:
float gravity = 0.1;
float speed = 0;
void steuerungH(){
// [...]
}
void draw() {
// [...]
streuerungH();
// [...]
}
You have to create a new Steuerung object like this
Steuerung steuerung = new Steuerung();
Then you can call the method with
steuerung.steuerungH();
When you simply do
steuerungH();
Java will be looking for a steuerungH() method in your Main class which doesn't exist and therefor throws an error.
I am attempting to modify the pacman game from the Mason 19 website. What I have to do is make pacman run on its own and traverse any board given as fast as possible. So far I have achieved making pacman running on its own but it gets stuck in a loop at the top of the board. What I want to know is what would be the best way to make it work and not get stuck in a loop.
The program I am using code from comes from Mason19 https://cs.gmu.edu/~eclab/projects/mason/
The code I have modified is inside the Pac.java and the doPolicyStep class.
protected void doPolicyStep(SimState state)
{
if(lastAction == NOTHING)
{
if(isPossibleToDoAction(Pac.E))
{
pacman.actions[0] = Pac.E;
performAction(Pac.E);
}
else if(isPossibleToDoAction(Pac.S))
{
pacman.actions[0] = Pac.S;
performAction(Pac.S);
}
else if(isPossibleToDoAction(Pac.N))
{
pacman.actions[0] = Pac.N;
performAction(Pac.N);
}
else
{
pacman.actions[0] = Pac.W;
performAction(Pac.W);
}
}
else if(lastAction == Pac.E)
{
if(isPossibleToDoAction(Pac.E))
{
pacman.actions[0] = Pac.E;
performAction(Pac.E);
}
else if(isPossibleToDoAction(Pac.S))
{
pacman.actions[0] = Pac.S;
performAction(Pac.S);
}
else if(isPossibleToDoAction(Pac.N))
{
pacman.actions[0] = Pac.N;
performAction(Pac.N);
}
else
{
pacman.actions[0] = Pac.W;
performAction(Pac.W);
}
}
else if(lastAction == Pac.S)
{
if(isPossibleToDoAction(Pac.S))
{
pacman.actions[0] = Pac.S;
performAction(Pac.S);
}
else if(isPossibleToDoAction(Pac.W))
{
pacman.actions[0] = Pac.W;
performAction(Pac.W);
}
else if(isPossibleToDoAction(Pac.E))
{
pacman.actions[0] = Pac.E;
performAction(Pac.E);
}
else
{
pacman.actions[0] = Pac.N;
performAction(Pac.N);
}
}
else if(lastAction == Pac.W)
{
if(isPossibleToDoAction(Pac.W))
{
pacman.actions[0] = Pac.W;
performAction(Pac.W);
}
else if(isPossibleToDoAction(Pac.N))
{
pacman.actions[0] = Pac.N;
performAction(Pac.N);
}
else if(isPossibleToDoAction(Pac.S))
{
pacman.actions[0] = Pac.S;
performAction(Pac.S);
}
else
{
pacman.actions[0] = Pac.E;
performAction(Pac.E);
}
}
else if(lastAction == Pac.N)
{
if(isPossibleToDoAction(Pac.N))
{
pacman.actions[0] = Pac.N;
performAction(Pac.N);
}
else if(isPossibleToDoAction(Pac.W))
{
pacman.actions[0] = Pac.W;
performAction(Pac.W);
}
else if(isPossibleToDoAction(Pac.E))
{
pacman.actions[0] = Pac.E;
performAction(Pac.E);
}
else
{
pacman.actions[0] = Pac.S;
performAction(Pac.S);
}
}
int nextAction = pacman.getNextAction(tag);
/** The Method isPossibleToDoAction() Determines if the agent can move with the given action (N/W/S/E/NOTHING) without bumping into a wall. */
public boolean isPossibleToDoAction(int action)
{
if (action == NOTHING)
{
return false; // no way
}
IntGrid2D maze = pacman.maze;
int[][] field = maze.field;
// the Agents grid is discretized exactly on 1x1 boundaries so we can use floor rather than divide
// the agent can straddle two locations at a time. The basic location is x0, y0, and the straddled location is x1, y1.
// It may be that x0 == y0.
int x0 = (int) location.x;
int y0 = (int) location.y;
int x1 = location.x == x0 ? x0 : x0 + 1;
int y1 = location.y == y0 ? y0 : y0 + 1;
// for some actions we can only do the action if we're not straddling, or if our previous action was NOTHING
if ((x0 == x1 && y0 == y1) || lastAction == NOTHING)
{
switch (action)
{
// we allow toroidal actions
case N:
return (field[maze.stx(x0)][maze.sty(y0 - 1)] == 0);
case E:
return (field[maze.stx(x0 + 1)][maze.sty(y0)] == 0);
case S:
return (field[maze.stx(x0)][maze.sty(y0 + 1)] == 0);
case W:
return (field[maze.stx(x0 - 1)][maze.sty(y0)] == 0);
}
} // for other actions we're continuing to do what we did last time.
// assuming we're straddling, this should always be allowed unless our way is blocked
else if (action == lastAction)
{
switch (action)
{
// we allow toroidal actions
case N: // use y0
return (field[maze.stx(x0)][maze.sty(y0)] == 0);
case E: // use x1
return (field[maze.stx(x1)][maze.sty(y0)] == 0);
case S: // use y1
return (field[maze.stx(x0)][maze.sty(y1)] == 0);
case W: // use x0
return (field[maze.stx(x0)][maze.sty(y0)] == 0);
}
} // last there are reversal actions. Generally these are always allowed as well.
else if ((action == N && lastAction == S) ||
(action == S && lastAction == N) ||
(action == E && lastAction == W) ||
(action == W && lastAction == E))
{
return true;
}
return false;
}
I believe I need to use something like a BFS search to find the shortest path, I just have no idea how to do that.
I'm creating a small application where a user can take a Box and arrange it on a Pallet. I've managed to get it working using a 50x100 Box and making it snap to a grid by rounding the mouse position to the closest 50 value.
The problem is that when I use an odd sized Box, e.g. 50x110, the boxes will overlap or have gaps, since I am forcing them to move to the closest 50 value. If I increase this value I get gaps between the boxes and if I make it too small, it becomes hard for a user to align the boxes so there is no gap between them
I was wondering if anyone had anyway to approach this problem of getting the boxes to snap/align themselves with each other regardless of the size and ratio?
Here is part of the code that generates and places the buttons onto the pallet, explanation of the missing functions at the bottom
int package_width = 60;
int package_height = 100;
int snap_size = 50; //snap everything into 5 pixel limits
int count = 0;
int pallet_width = 400;
int pallet_height = 400;
JButton package_left = new JButton("<");
package_left.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Selector.selected = "<";
}
});
JPanel pallet = new JPanel();
pallet.setLayout(null);
pallet.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if(Selector.selected != "" && Selector.selected != null) {
Point position = e.getPoint();
JButton pack = new JButton(Selector.selected + Selector.count);
int x_pos = -1;
int y_pos = -1;
int pack_height = -1;
int pack_width = -1;
if(Selector.selected == "<" || Selector.selected == ">") {
pack_width = package_height;
pack_height = package_width;
}else {
pack_width = package_width;
pack_height = package_height;
}
pack.setSize(pack_width, pack_height);
//snap using the height and width
x_pos = (int)((int)(position.x-pack_width/2)/(pack_width/2))*pack_width/2;
y_pos = (int)((int)(position.y-pack_height/2)/(pack_height/2))*pack_height/2;
pack.setLocation(x_pos, y_pos);
if(collision(pack.getLocation(), snap_size)) {
x_pos = -1;
y_pos = -1;
}
//If the position failed to set, its overlapping
if (x_pos != -1 && y_pos != -1) {
Selector.point_list.add(pack.getLocation());
if(Selector.selected == "<" || Selector.selected == ">") {
Selector.point_list.add(new Point(pack.getLocation().x+snap_size, pack.getLocation().y));
}else{
Selector.point_list.add(new Point(pack.getLocation().x, pack.getLocation().y+snap_size));
}
pallet.add(pack);
main_page.repaint();
Selector.selected = "";
}
}
}
}
Collision Function
public static boolean collision(Point pack, int snap_size) {
Iterator<Point> it = Selector.point_list.iterator();
Point next;
while(it.hasNext()) {
next = it.next();
if(pack.x == next.x && pack.y == next.y) {
return true;
}
if(Selector.selected == "<" || Selector.selected == ">") {
if(pack.x+snap_size == next.x && pack.y == next.y) {
return true;
}
}else {
if(pack.x == next.x && pack.y+snap_size == next.y) {
return true;
}
}
}
return false;
}
The class Selector holds 2 static variables. One is the point_list which holds a list of all the points that have a button in them already. The other is selected which is used to determine the orientation of the button based on if the first button pressed has ^,v,< or > on it.
public boolean onTouch(View paramView, MotionEvent paramMotionEvent)
{
ImageView localImageView = (ImageView)paramView;
dumpEvent(paramMotionEvent);
switch (0xFF & paramMotionEvent.getAction())
{
}
for (;;)
{
localImageView.setImageMatrix(this.matrix);
return true;
this.savedMatrix.set(this.matrix)
this.start.set(paramMotionEvent.getX(), paramMotionEvent.getY());
Log.d("Touch", "mode=DRAG");
this.mode = 1;
continue;
this.oldDist = spacing(paramMotionEvent);
Log.d("Touch", "oldDist=" + this.oldDist);
if (this.oldDist > 10.0F)
{
this.savedMatrix.set(this.matrix);
midPoint(this.mid, paramMotionEvent);
this.mode = 2;
Log.d("Touch", "mode=ZOOM");
continue;
this.mode = 0;
Log.d("Touch", "mode=NONE");
continue;
if (this.mode == 1)
{
this.matrix.set(this.savedMatrix);
this.matrix.postTranslate(paramMotionEvent.getX() - this.start.x, paramMotionEvent.getY() - this.start.y);
}
else if (this.mode == 2)
{
float f1 = spacing(paramMotionEvent);
Log.d("Touch", "newDist=" + f1);
if (f1 > 10.0F)
{
this.matrix.set(this.savedMatrix);
float f2 = f1 / this.oldDist;
this.matrix.postScale(f2, f2, this.mid.x, this.mid.y);
}
}
}
}
}
}
As you can see, I'm using the matrix method to be able to scroll and zoom images in the app.
However, I'm getting the error Unreachable code, in the part(the first time this statement appears)
this.savedMatrix.set(this.matrix)
Any suggestions? Thx.
because of this line..
return true;
You are returning the value..without performing any operation..so the code below your return statement is not execute any more..
so add this at the bottom of the method..
return true;
Im doing a pacman game. The following code is for ghosts movement and it works correctly. But I have to include a another check. The problem is that I always ruin the logic.
Current code:
public void moveGhost(Tiles target) {
if(specialIntersections()){
direction = direction; //keeps going in the same direction
}
else{
int oppDir;
if(direction == UP){
oppDir = DOWN;
}
else if(direction == DOWN){
oppDir = UP;
}
else if(direction == LEFT){
oppDir = RIGHT;
}
else{
oppDir=LEFT;
}
double minDist = 10000.0;
Tiles potentialNext;
for(int i=0; i<4; i++){
if(i!=oppDir){
potentialNext = maze.nextTile(getCurrentPos(), i);
if(!(potentialNext.wall()) && check(potentialNext)){
if(calculateDistance(target, potentialNext) < minDist){
minDist = calculateDistance(target, potentialNext);
futureDirection = i;
}
}
}
}
}
changeDirection();
timer++;
increment();
x += xinc;
y += yinc;
tunnel();
}
Another check I need to include:
//if the door is a wall (closed) the object cannot go through it
if(DoorIsWall()){
if(!(potentialNext.wall()) && !(potentialNext.door()) && check(potentialNext)){
I generally write a new method when my conditions start to get unruly:
if (isTileValid(potentialNext)) {
// do stuff
}
private boolean isTileValid(TileObject someTile) {
if (someTile.wall()) {
return false;
}
if (someTile.door()) {
return false;
}
if (! check(someTile)) {
return false;
}
return true;
}