I have a problem. I'm creating this maze game using java for the very first time,
and I have lots and lots of graphics(g) drawings/objects drawn through their own class.
What I want to get is the X and Y coordinate out of one of them.
public static int seems too hard to use in this case, without created an equal number of integers as there are drawings.
So, I need something to use instead of getY():
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
for (int i=0; i<=42; i++) {
if(cx != rektangel[i].getY()) // I tried "getY()" with fail(kind of dumb since it's used for mouselistener?
cirkel[0].move(-10, 0);
this.cx += -10;
repaint();
}
}
Information you might need to know in this code:
rektangel(the name) = rectangle in english.
cirkel is one object/drawing ==> I simply used a static int cx & cy for this guy to see it's coordinates.
Where it says i<42; ==> shows that it's ALOT of drawn objects. (static int won't be optimal)
=============ANSWERED======ANSWERED=======ANSWERED=======ANSWERED==========
Sorry, but for some reason I can't comment your answers. The result is ridiculously laughable. I'm currently staying up late to finish my code for a homework I have. Thanks for your solution, and MadProgrammers comment. Here's my rectangle-class:
public class Rektangel {
private int width,height;
private int x,y; <---this row private
Color c;
public static int karta = 1;
public static int rx = 0;
public static int ry = 0;
}
The easiest thing in the world.. I had tried using rectangle[i].x in the previous code, but didn't work. Know why? Because I wrote private instead of public x & y. Sorry for the inconvenience and once again, Thanks!
You should maintain the position and size of each object within itself and provide a getX, getY and getWidth and getHeight method for each, this way, they become self managing, knowing where they are and how big they should be...
Related
I have a 2D rocket, the rocket is a collection of 3 objects, a nose(triangle), body(square) and a jet(circle), all together they make the rocket.
I have to set the body(square) relative to the nose(triangle), so that they align with each other.
So far I have this;
public Rocket(Triangle t, Square s, Circle c) {
this.nose = t;
this.body = s;
this.jet = c;
this.nose.setXPos(50);//initial positions of the nose X
this.nose.setYPos(300);//initial positions of the nose Y
this.body.setXPos(getBodyXPos());//sets the body relative to the nose X
this.body.setYPos(getBodyYPos());//sets the body relative to the nose Y
I also have the methods;
private int getBodyXPos()
{
return this.xPos;
}
private int getBodyYPos()
{
return this.yPos;
}
private int getJetXPos()
{
return this.xPos;
}
private int getJetYPos()
{
return this.yPos;
}
I am not aloud to use fixed number, but need to use the helper method in some way to make the shapes appear in the correct place on the screen.
I have been stuck on this for a few days and would love some help. Many thanks in advance.
you simply set the position of the various parts relative to each other with the appropriate offset
int rocketx = 50;
int rockety = 300;
this.nose.setXPos(rocketx);
this.nose.setYPos(rockeyy);
this.body.setXPos(rocketx);
this.body.setYPos(rockety+this.nose.height());
this.jet.setXPos(rocketx);
this.jet.setYPos(rockety+this.nose.height()+this.body.height());
instead of fixed values for height, you might have a method on nose and body to find out their height, and use that instead. If your rocket is flying horizontal, then you will need to do the same for X and NOT for Y.
class anyName
{
int Tcol = 0;
int fc = 0;
int x = 0;
float randx = (random(1, 1000));
float randy = (random (0, 600));
int Tsizes = 1;
{
if (fc >= x) { //Random Ellipse 3
stroke (Tcol);
fill (Tcol);
ellipse (randx, randy, Tsizes, Tsizes);
}
}
}
anyName ranx1 = new anyName();
ranx1.x = 100;
Hi, I am trying to add a class/object to my code and it is not working. This is the class I have so far, but when I instantiate one object from that class (ranx1), and then try change one of the variables inside it (x), it says there is a error. Is there anything I need to change? I would really appreciate any help.
Since I instantiated an object from that class, how would I change the variables for the new object? For example, if in the class x = 0, then I made a copy and this time I want x to = 100, but all the other variables such as Tcol and fc to stay the same. I know this is possible because my teacher taught it, but it is not working right now for me.
I am a really newby programmer, so I think this should be easy for someone to answer.
If you want the entire code, please put your email in the answer, so that I can email the entire thing to you.
ranx1.x = 100;
You need a setter in your anyName-class. And then you call the setter:
public void setX(int x) {
this.x = x;
}
and
ranx1.setX(100) for example.
In order to make this program run, I have to import the "derp" method out of the Shape class and into the rectangle class. But no matter what myself or the tutors try, we cannot make it work. What I actually need to accomplish is that the "derp" method from Shape needs to be able to work in Rectangle. However, the task of importing the method has us stumped.
public abstract class shape{
shape(){
}
shape(int length, int width, int thing ){
length = 0;
width = 0;
}
public int derp(int thing, int length) {
thing = (int) Math.random() * 9 ;
length = thing;
return length;
}
}
public class Rectangle extends shape {
public static void main(String args[])
{
shape.getLength(Length, Width);
//r1 will take all default value
Rectangle r1 = Rectangle();
//r2 will take all supplied value
Rectangle r2 = Rectangle(4, 5);
//r3 will take supplied length. width will take default value
Rectangle r3 = Rectangle(10);
//r4 will take the same value of r2
Rectangle r4= r2;
//the rest of the code
}
private static void Rectangle(int width2, int length2) {
// TODO Auto-generated method stub
}
}
It seems to me like you should reverse the inheritance. It should be Rectangle extending shape, since a rectangle is a shape
EDIT 1
When you reverse the inheritance you should be able to call the derp method on Rectangle.
RectAngle r = new Rectangle();
r.derp(thing, length);
EDIT 2
You shouldn't really hardcode your variables into your Shape instance either. Thats not a really usefull way to do it. There is two ways you can do it. Either let The shape class have variables which is protected (means it will be be inherited). Then you shape class should look like:
public abstract class shape{
protected int length;
protected int width;
shape(){
}
shape(int length, int width){
this.lenght = length;
this.width = width;
}
public int derp() {
int thing = (int) Math.random() * 9 ;
length = thing;
return length;
}
}
Or if you dont wanna make this big change to your class you can just pass the parameters directly into the method like
r.derp(1, 100);
But I do agree with tieTYT that you should spend some time learning some more java syntax. Since this is a very wierd way of doing your calls :).
Rectangle should be extending Shape, not the other way around.
Also remove this line
Rectangle.derp(int thing, int length, int width);
You don't import methods out of classes into other classes. Logically you'd want Rectangle to extend shape (also should be Shape in accordance with naming conventions), but you're doing the other way around.
However there are many things that don't make sense in your code, so you might want to explain in clear English what you're trying to accomplish.
There is no way, this could work, since you are trying to access a Method of the child-class from the superclass. the superclass dont know its children. You either can use the Methods of the superclass from the subclass or place the method from the subclass into the superclass to use it there.
Rectangle.derp(int thing, int length, int width);
This is not a method declaration. This syntax is all wrong. Are you trying to declare derp as a method you can use, or are you trying to call derp? As a reader, that is unclear.
Logically, Rectangle should extend Shape, not the other way around.
This doesn't do anything:
shape(int length, int width, int thing ){
length = 0;
width = 0;
}
You're just assigning parameters to different values.
Take a break and spend some time learning the syntax of Java.
Ok..so your class Shape extends Rectangle...we will ignore that unusual logic.
Rectangle.derp(int thing, int length, int width);// wrong
First of all you cannot call method derp by declaring parameters inside call. You could have a call like this for example:
int thing = 1, length = 2, width = 3;
Rectangle.derp(thing, length, width);//with condition that derp method
//declaration to be public static
Rectangle r1 = Rectangle();//wrong
That is the class constructor. You declare it as public unless you want to make your class a Singleton ..but I doubt. An you instantiate it with the 'new' keyord like this:
Rectangle r1 = new Rectangle();
Same for the one with 1 and 2 parameters.
Complete code for the Rectangle class here:
public class Rectangle {
public Rectangle(int width2, int length2) {
// TODO: Process width and length here
}
public Rectangle() {
// TODO: process default values here
}
public Rectangle(int value) {
// TODO: Process value here
}
public static void derp(int thing, int length, int width) {
}
public static void main(String args[]) {
int thing = 1, length = 2, width = 3;
Rectangle.derp(thing, length, width);
// r1 will take all default value
Rectangle r1 = new Rectangle();
// r2 will take all supplied value
Rectangle r2 = new Rectangle(4, 5);
// r3 will take supplied length. width will take default value
Rectangle r3 = new Rectangle(10);
// r4 will take the same value of r2
Rectangle r4 = r2;
// the rest of the code
}
}
I am creating a program that displays several bases and the amount of troops each base has. There are two types of bases, friendly and enemy bases. Each Base extends GCompound and consists of a GRect and a GLabel(to display the number of troops). Two arrays are used to keep track of the bases, one for friendly, one for enemy.
I want the user to be able to press the mouse down on one friendly base and release on a different friendly base, causing the troop amount to be transferred from the first base to the second one.
My problem currently is I am only able to detect the base the user presses the mouse down on, and not the base that the mouse is released on. I am using the method getElementAt from the ACM library to return the GObject that a mouse action takes place on.
Code for the mouse press:
public void mousePressed(MouseEvent e){
int mouseX = e.getX();
int mouseY = e.getY();
for(int i = 0; i < PlayerBaseArray.length; i++){
if(getClickedObject(mouseX, mouseY) == PlayerBaseArray[i]){ //Checks to see if the clicked base is in the Array of friendly bases.
pressedIndex = i;
pressedBaseTroopCount = PlayerBaseArray[pressedIndex].getTroopCount();
}
}
}
Code for the mouse release:
public void mouseReleased(MouseEvent m){
int mouseX = m.getX();
int mouseY = m.getY();
for(int i = 0; i < PlayerBaseArray.length; i++){
if(getClickedObject(mouseX, mouseY) == PlayerBaseArray[i]){ // This is always false for some reason.
PlayerBaseArray[i].changeTroopCount(pressedBaseTroopCount);
PlayerBaseArray[pressedIndex].changeTroopCount(-pressedBaseTroopCount);
}
}
}
Method to see what object is clicked:
private GObject getClickedObject(int x, int y){
GObject clicked = getElementAt(x, y);
if(clicked == null) return null;
else return clicked;
}
For some reason the if statement in mouseReleased() is never true, even though it works properly in mousePressed(). Any idea on why the if statement in mouseReleased() does not work?
I've tried researching the problem to no avail, and instead of wasting another night on it I thought I would ask here. Thanks!
You shouldn't use the == operator to compare Objects. You should use the .equals() method:
if (getClickedObject(mouseX, mouseY).equals(PlayerBaseArray[i]))
Put simply, you can only use == only when comparing java primitives (eg int, long etc).
For all "normal" objects, always use objecta.equals(objectb).
This article discusses this issue in more detail.
Attention anal retentives:
Yes, you are right, under some circumstances you can safely use == between objects such as String contants, Integers between -128 and 127, etc, etc. But this guy needed a clear answer and not to be confused. Please resist the temptation to comment about this.
I'm working on to do my assignment. It is a chess design(AI, GUI not required), I have piece class. The piece class has two variables: color and name. So far I have a "move method" like this in this class.
`
public void move(Piece piece,int x,int y)
{
int a=0;
int b=0;
for(int i=0;i<Board.grid.length;i++) {
for(int r=0;r<Board.grid[i].length;r++) {
if(Board.grid[i][r]==piece)
a=i;
b=r;
if(Board.getisnull(x, y)){
Board.grid[a][b]=null;
Board.grid[x][y]=piece;
}
}
}
Board.grid[u][t]=null;
}
`
In this code, I want to find an index which is the old index of the piece I want to move, then moving it then setting its old index to null but this is not working. I can see the name on screen but not the color. Also, old index is not set to null. How to do it? I started to think using an object(piece) array but how?
Just a small hint:
//finds the piece equal to name and color of our piece.so
if(Board.grid[i][y].equals(name) || Piece.color.equals(color))
This doesn't fit together, since the check is "equal to name OR equal color". I think you want to change it to: if(Board.grid[i][y].equals(name) && Piece.color.equals(color))
Piece.setColor(color);//set this piece's color
Huh? What are you doing that for? Shouln't Piece keep its color all the time?
if(Board.getisnull(x, y)==true)
You're redefining y in your loop so y is not the parameter you passed in to the method.
Basically, I'd redefine the method (to keep is as close to the OP as possible, note that OOP wise there could be even better design, subclassing Piece etc.):
//Board.grid[][] should be a 'Piece[8][8]';
//edit: rename parameters for clarity
public void move( Piece piece,int targetX,int targetY)
{
if( Board.getisnull(targetX, targetY) )//method in other class checks the indexes if null
{
//remove the piece from the field/index
Board.grid[piece.x][piece.y]=null;
//add the piece to the target field and update its position
piece.x = targetX;
piece.y = targetY;
Board.grid[targetX][targetY]=piece;
}
else
{
//handle that case, e.g. by throwing an exeption
}
}
Now you'd get the piece you want to move (which knows its index), calculate the target position and call move(piece, targetX, targetY);