Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (481)
Games in Android Showcase (110)
games submitted by our members
Games in WIP (548)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Ways around using lots of booleans....?  (Read 1515 times)
0 Members and 1 Guest are viewing this topic.
Offline wreed12345

JGO Knight


Medals: 24
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Posted 2013-03-02 00:30:59 »

Hi guys heres just a little question i have while working on my most recent WIP game. Well here is the code to start off:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
   boolean rockD[] = { true, true, true, true, true, true, true };
   int resourceWidth[] = { 64, 64, 64, 64, 64, 64, 64 };
   int resourceHeight[] = { 58, 58, 58, 58, 58, 58, 58 };
   float resourceTimer = 0;

   public void resource(SpriteBatch apples, int x, int y, int id) {
                //to see if the method should even do the below stuff
     if (rockD[id]) {
         apples.draw(material, levelX + x, levelY + y, resourceWidth[id],
               resourceHeight[id]);
                        // my little distance formula....
        if ((Math.sqrt((levelX + x - middleX) * (levelX + x - middleX)
               + (levelY + y - middleY) * (levelY + y - middleY)) < distanceFromMaterial)) {
            font.draw(batch, "Press B to Pick up the Stone", 50, 50);
                               //starts making the image of the "resource" smaller as b is held down
           if (Gdx.input.isKeyPressed(Keys.B)) {
               // amountOfStone += 4;
              // rockD[id] = false;
              resourceTimer += Gdx.graphics.getDeltaTime();
               if (resourceTimer > 1 && resourceTimer < 2) {
                  resourceWidth[id] = (int) (64 * .8);
                  resourceHeight[id] = (int) (58 * .8);
               }
               if (resourceTimer > 2 && resourceTimer < 3) {
                  resourceWidth[id] = (int) (64 * .6);
                  resourceHeight[id] = (int) (58 * .6);
               }
               if (resourceTimer > 3 && resourceTimer < 4) {
                  resourceWidth[id] = (int) (64 * .4);
                  resourceHeight[id] = (int) (58 * .4);
               }
               if (resourceTimer > 4 && resourceTimer < 5) {
                  resourceWidth[id] = (int) (64 * .2);
                  resourceHeight[id] = (int) (58 * .2);
               }
               if (resourceTimer > 5) {
                  amountOfStone += 1;
                  resourceTimer = 0;
                  rockD[id] = false;
               }
                                //if b is depressed then reset values to defaults
           } else {
               resourceTimer = 0;
               resourceWidth[id] = 64;
               resourceHeight[id] = 58;
            }
         }
      }
   }

Ok, just to explain this all I use a distance formula to detect if the character is within range to pick it up, then as you hold b to pick it up the "resource" gets smaller. I know this code may need to be further organized possibly into some type of MVC, but I will use it for now. So here is my question; how can I call this method without requiring all these booleans / int's ? This is what it looks like calling this method

1  
2  
3  
4  
5  
6  
//resource(SpriteBatch, xPos,yPos, ID)
        resource(batch, 800, 800, 0);
         resource(batch, 1200, 1200, 1);
         resource(batch, 800, 1200, 2);
         resource(batch, 1200, 800, 3);
         resource(batch, 500, 1000, 4);


Does this code have to have all of these different objects? (I call them id's in the method). There seems like theres no way to make unlimted objects without defining more booleans / int's... I feel like there may be something silly that I am overlooking or possibly something lacking in my java education. Well I appreciate any suggestions here guys, thanks in advanced

Offline actual

JGO Coder


Medals: 23



« Reply #1 - Posted 2013-03-02 01:29:20 »

I am not sure if the gets you where you want but what I notice most is that you have a series of arrays when what you seem to want is a class. Something like:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
class Resource {

   int width, height;
   int x,y;
  boolean expired;

   public Resource(int x, int y) {
      this.x = x;
      this.y = y;
      width=64;
      height = 58;
      expired = false;
   }


   public boolean isCloseEnoughToGrab(int playerX,int playerY) {
      // Put your distance checking formula here
  }


   public boolean isExpired() {
      return expired;
   }


   public void shrinkBy(float factor) {
      width = (int) (width* factor);
      height = (int) (height*factor);
     if (width <= 0 || height <= 0) expired = true;
   }
}


Then you can just Resources to a list and loop through them to draw and/or process them.
Offline davedes
« Reply #2 - Posted 2013-03-02 01:38:08 »

Three pieces of advice:

1. Use descriptive method and member names. "resource" doesn't tell us what the function does. "drawSprite" or "drawResource" would be more appropriate.

2. Don't write the same code twice. This is a generalization, but if you are seeing duplication in your code, there is probably a better way of organizing it.

3. Learn to use objects and collections.

Let's say you define a class called "Entity" which holds an x, y position. There is no need for an "id" integer.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
public class Entity {
    public int x, y;

    public void render() {
        ... handle input and render the entity ...
    }

    public boolean withinRange(int x, int y) {
        return ... distance formula ...;
    }
}


Now you can use ArrayList<T> or another "growable array" to store an indefinite amount of entities. In LibGDX you are suggested to use their own list, Array<T>, which is more Android-friendly. Now, presumably, you would add your stones/items/whatever in some manner -- i.e. procedurally (like randomly within a certain range) or using predefined locations (like for a tiled map). The latter would need to be parsed somehow from a file. The former might look like this:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
//all of your items
private Array<Entity> items = new Array<Entity>();

//main game loop
public void render() {
    //for example, create a random item on touch
   if (Gdx.input.isTouched()) {
        Entity newEntity = new Entity();
        newEntity.x = (float)(Math.random() * Gdx.graphics.getWidth());
        newEntity.y = (float)(Math.random() * Gdx.graphics.getHeight());
    }

    //render items
   for (int i=0; i<items.size; i++) {
        Entity e = items.get(i);
        if (e.withinRange(xRange, yRange)) {
            e.render();
        }
    }
}


You don't need "id" any more since you are working with objects, and each instance is unique. To change an entity, you interact with its methods.

Ideally your Entity class would have methods like setPosition, getX, getY, setSize, etc.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline wreed12345

JGO Knight


Medals: 24
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #3 - Posted 2013-03-02 04:33:11 »

@actual I'm confused of how multiple instances of that went cause problems using this.x , how can that work with like 6 different x coordinates?

@davedes unfortunately I never actually learned  about array lists so before I give your idea a go I'm going to have to watch some YouTube videos or something.

Offline Jimmt
« League of Dukes »

JGO Kernel


Medals: 128
Projects: 4
Exp: 3 years



« Reply #4 - Posted 2013-03-02 04:50:20 »

@wreed ArrayList is very simple to use, just think of it like it is, a list. first in first out, you can add and delete, adding without an index automatically adds to the end. In ArrayList<T>, T defines what type of object goes in the arraylist, and to access an index instead of
1  
array[i]
it's arrayList.get(i), or you could use an iterator (I prefer get(), however).
Advantage over Array is that the size changes depending on how many elements you have, and the disadvantage is that every time you remove/add something at an index that's not the last everything has to shift.
Offline sproingie

JGO Kernel


Medals: 202



« Reply #5 - Posted 2013-03-02 15:40:17 »

every time you remove/add something at an index that's not the last everything has to shift.

I should also stress that this is an absurdly fast operation you will never notice the cost for the vast majority of the time.
Offline Jimmt
« League of Dukes »

JGO Kernel


Medals: 128
Projects: 4
Exp: 3 years



« Reply #6 - Posted 2013-03-02 16:39:02 »

every time you remove/add something at an index that's not the last everything has to shift.

I should also stress that this is an absurdly fast operation you will never notice the cost for the vast majority of the time.

Right, I'm just saying that shifting is almost always slower than replacing.
Offline wreed12345

JGO Knight


Medals: 24
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #7 - Posted 2013-03-02 19:24:55 »

Thanks jimmt! Now with that in mind does davedes' example using an array list sort of create a new a instance of that entity class so that the x and y ints in the entity class can be used for sort of more an one thing?

Offline davedes
« Reply #8 - Posted 2013-03-02 19:47:36 »

I think you should really pick up a programming book or something... Roll Eyes

Offline wreed12345

JGO Knight


Medals: 24
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #9 - Posted 2013-03-02 19:57:47 »

Thats what I was going to do but jimmt started explaining, ill hit the books latter

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline HeroesGraveDev

JGO Kernel


Medals: 245
Projects: 11
Exp: 2 years


┬─┬ノ(ಠ_ಠノ)(╯°□°)╯︵ ┻━┻


« Reply #10 - Posted 2013-03-02 20:11:43 »

Even just reading through the official Java Tutorials would be a good start.

Offline wreed12345

JGO Knight


Medals: 24
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #11 - Posted 2013-03-02 21:47:26 »

thenewboston has videos for everything! im going to watch the video on array lists soon then hopefully I can continue work on my game

Offline wreed12345

JGO Knight


Medals: 24
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #12 - Posted 2013-03-03 16:10:07 »

Hey davedes, in this example I am just confused, should we be adding something to the arraylist items here? Or im I missing something
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
//all of your items
private Array<Entity> items = new Array<Entity>();

//main game loop
public void render() {
    //for example, create a random item on touch
   if (Gdx.input.isTouched()) {
        Entity newEntity = new Entity();
        newEntity.x = (float)(Math.random() * Gdx.graphics.getWidth());
        newEntity.y = (float)(Math.random() * Gdx.graphics.getHeight());
    }

    //render items
   for (int i=0; i<items.size; i++) {
        Entity e = items.get(i);
        if (e.withinRange(xRange, yRange)) {
            e.render();
        }
    }
}


Also when adding something to this ArrayList what is it that I will be adding?

Offline actual

JGO Coder


Medals: 23



« Reply #13 - Posted 2013-03-03 21:36:06 »

Wreed,

(I hope this doesn't come across as patronizing, it seems like you could use some help in the basics. If anyone else sees problems with what I've got, please chime in. Providing wrong advice is worse than providing no advice at all).

The biggest issue I see with this code is that you are mixing all sorts of things like input, drawing, updating together, and a good part of that reason is you aren't making good use of classes. A significant part of programming in Java involves determining what classes you need, what they look like, and how they interact. Until you understand that better, everything you try to do is going to be that much harder. I am going to walk through a way to think through your problem in hopes that you can better understand how to work with classes. I am not claiming it is the best or only way but I think it is a reasonable one.

Objects are all about behavior. What can you tell them to do(commands)? What questions can you ask of them (queries)? What kinds of things do they need to be notified about? The answers to these questions help define what behavior (and thus what methods) are needed.

So a reasonable way to go is:
1. Decide on what kinds of objects (classes) you might need
2. For each, decide what types of commands/queries they will need to be able to handle (behavior).
3. For the behavior, think about what facts it will need to know in order to carry out the behavior.

The most important thing is to understand that it's an iterative process. You create a few objects, then realize you need a new one. You may add some methods, then realize you don't need them and get rid of them.

A simple way to decide what objects you need is to think of all of the "things" in your game. In your case Resource, Player, and Level come to mind and it makes sense to make a class for each.

As an example, let's take your "resource". A Resource is a "thing" in your game so it is a good candidate for being a class.
1  
2  
3  
class Resource {
   
}


So what is a Resource? From your description and code I see the following:
"A Resource sits in the world, unmoving. If the player is close enough and consumes it for 5 seconds, then it disappears and the player gets stone added to their inventory. If the player stops consuming it before the 5 seconds, it goes back to normal. It shrinks as it gets consumed."

So how does this translate into behavior? It actually helps to think of the Resource as a person. Imagine what kinds of questions would you ask it? What kind of things would you tell it to do? What would you need to let him know is going on?

"Is the player close enough to you, that he could consume you?"
"I want you to draw yourself"
Player: "I am consuming you!"

We can turn each of those into a method.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
class Resource {

   // Are you close enough to the player, that the player could consume it?
  public boolean isCloseEnoughToConsume(int playerX, int playerY) { }

   // I want you to draw yourself
  public draw(SpriteBatch batch) { }

   // Player: "I am consuming you!"
  public void consumedByPlayer() { }
}


This is just a start. The important thing is that you don't have to figure it out all up front. You can write what you need then make changes as needed. So what does a Resource need to know to be able to do what we are asking of it so far?

* To know if the player is close enough, it needs to know its own position and it needs to know how close is "close enough".
* To draw itself, it needs to know its position, its width and height, and the image being used to draw it


1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
class Resource {
   
   // To draw itself and to see if the player is close enough, it needs to know its position.
  public int x, y;

   // To know if the player is close enough, it needs to know what close enough means.
  public int minimumDistance;

   // To draw itself, it needs to know its height and width
  public int height, width;

   // To draw itself, it needs to know which image to use.
  public Image sprite;

   // Are you close enough to the player, that the player could consume you?
  public boolean isCloseEnoughToConsume(int playerX, int playerY) {
      return (playerX - x)*(playerX - x) + (playerY - y) * (playerY - y) < closeEnough * closeEnough;
   }

   // Draw yourself
  public void draw(SpriteBatch batch) {
      batch.draw(sprite,x,y,width,height);
   }
}


We are getting somewhere now but let's look at consuming more carefully. If the player is close enough and holds the button down for 5 seconds, the resource is consumed and the player gets stone added to their inventory. If the player releases the B button before the 5 seconds are up, the resource gets reset. So what other queries/commands/notifications might there be?

Player: "I've started consuming you"
Player: "I've stopped consuming you"
"Is there anything left or are  you all consumed?"

What does the resource need to know to carry these out? It needs to know whether or not its currently being  consumed, and if so, how long it is being consumed for. So we can add the following to the class:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
private float timeConsumed;

private boolean isBeingConsumed;

public void startConsuming() {
   timeConsumed = 0;
   isBeingConsumed = true;
}

public void stopConsuming() {
   isBeingConsumed = false;
}

public boolean isConsumed() {
   timeConsumed > 5;
}

// Added an "update yourself"
public void update(float delta) {
   if (isBeingConsumed) {
      timeConsumed += delta;
   }
}


So putting all of that together, you have a reasonably complete object that represents a Resource. We've pulled out some of the functionality from your original, sprawling method, and have put it where it belongs.
Offline wreed12345

JGO Knight


Medals: 24
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #14 - Posted 2013-03-03 22:48:48 »

Thank you actual, I have never been one to really divide up my code well  although what you have said really helped me understand  why that makes sense to do. I will be sure to take advantage of your post, however I'm still confused about my original question...

Offline Axeman

Senior Member


Medals: 7



« Reply #15 - Posted 2013-03-04 00:28:10 »

Wreed, I think there´s a pretty good answer to what you´re asking in reply#1 by Actual. Turn all those arrays into one array of class "Resource" and you will have a lot less code, it will be easier to read and easier to find errors. It´s all win win. Smiley
Offline wreed12345

JGO Knight


Medals: 24
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #16 - Posted 2013-03-04 01:38:23 »

Would you mind looking at my reply number 12, that is the only question I have left then it will be a true win win, and do you mean post number 2? as I dont see any of that in actual's post number 1...

Offline wreed12345

JGO Knight


Medals: 24
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #17 - Posted 2013-03-04 22:31:51 »

Ok I think I have that part figured out (^) but my last question is involving actuals example, would you recomend creating a "master" method in that Resource class or would I remotely call each method individually?

Offline wreed12345

JGO Knight


Medals: 24
Projects: 2
Exp: 2 years


http://linebylinecoding.blogspot.com/


« Reply #18 - Posted 2013-03-05 01:41:31 »

There's nothing better then the feeling of solving a programming problem:) Well I have figured this one out and am ready for my next one ahhaa thank you guys I truly appreciate your input and help!

Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

atombrot (26 views)
2014-08-19 09:29:53

Tekkerue (24 views)
2014-08-16 06:45:27

Tekkerue (23 views)
2014-08-16 06:22:17

Tekkerue (14 views)
2014-08-16 06:20:21

Tekkerue (22 views)
2014-08-16 06:12:11

Rayexar (60 views)
2014-08-11 02:49:23

BurntPizza (39 views)
2014-08-09 21:09:32

BurntPizza (30 views)
2014-08-08 02:01:56

Norakomi (37 views)
2014-08-06 19:49:38

BurntPizza (67 views)
2014-08-03 02:57:17
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!