Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (491)
Games in Android Showcase (112)
games submitted by our members
Games in WIP (555)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1] 2
  ignore  |  Print  
  [SOLVED] Loading an Image only once and using it in multiple objects  (Read 5018 times)
0 Members and 1 Guest are viewing this topic.
Offline jonjava
« Posted 2011-10-07 15:54:56 »

Hi.

I have an object that is able to draw itself ( A loaded BufferedImage ) with the help of a method. The object reads a *.png image from a specific destination into its own BufferedImage variable each time it is instantiated.

I use a lot of these objects at the same time.

I then have a JPanel iterate through all of these objects ( with the help of List<object> ) and have them invoke their own paintMe() method within a JPanel graphics. This allows the objects to "handle" their own drawing in their respective places ( they are scattered around the screen ).

This is inefficient.. becaue I'm loading the same image into memory n times for n amount of objects even though they all use the exact same *.png file.

Is there a better way to load images in java so that you won't need to load the same image twice, but just use the one you already have in memory?

(NOTE: I'm not looking for a SPECIFIC fix ie. Not to make the BufferedImage static for the object. Because the object should be able to load any *.png file ( ie the same instance of the class can have any kind of image representing itself ) and still not be forced to load a specific image twice.

thanks,
Jon

Offline Z-Man
« Reply #1 - Posted 2011-10-07 16:18:45 »

Put the images into a static HashMap, then when the object is instantiated check if the image is loaded already if it is move on, if it isn't load it and put it in the HashMap.
Offline jonjava
« Reply #2 - Posted 2011-10-09 11:37:40 »

I looked into the HashMap class and found a way to load images with it so that no image is loaded twice. Thanks:)

Here's my implementation for those interested.
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  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
/*
 * SpriteBank class
 * Desc: Handles the loading of images/sprites.
 * Other objects use this class to access/load their images
 * so that no image is loaded twice and that all images are handled
 * neatly and seperately.
 *
 * NOTE: Is a Singleton object! ( Can be instantiated once, and only once ).
 */

 
 import java.util.*; // for List and HashMap
import java.awt.Image;
 import java.awt.image.BufferedImage;
 import java.awt.*;
 import java.awt.image.*;
 import javax.imageio.*;
 import java.io.*;
 
 public class SpriteBank {
   
   // HashMap - used to store the imagesuniquely as to prevent
  // loading the same image twice.
  //private HashMap<String,BufferedImage> //HashMap<K,V>
  //               hm = new HashMap<String,BufferedImage>();
  private HashMap<String,BufferedImage> //HashMap<K,V>
                 hm = new HashMap<String,BufferedImage>();
   ////
  private String path = "gfx/";
   
      //Singleton code -+-+-+-+-+-+-+-+-+-+-++-+-+-+-+-+-+-+-+-+-+-+-
  // Used to holds a reference to ourself (Singleton design)
  private static SpriteBank ref = null;
   
   // private Constructor ( Singleton method )
  private SpriteBank() {
      /* No code required here
       * - we just want to make sure that no one can instantiate this class
       *   without our (itselfs) permission
       */

   }
   
   public static synchronized
         SpriteBank start() {
      // Start/Instantiate the SpriteBank class
     if (ref == null) {
         // Make sure this class is only instantiated once
        // and that it afterwards only references itself
        ref = new SpriteBank();
         }
      // return ref which now points to the instance of SpriteBank we just made
     return ref;
      }
   
   @Override
   public Object clone()
         throws CloneNotSupportedException {
      // Override the generic clone method ( inherited from Object )
     // to prevent cloning ( so there can't be more SpriteBanks than 1
     // , not even clones )
     throw new CloneNotSupportedException();
      // If you try to clone() you'll get tazered with an exception! :P
  }
      //Singleton code end -+-+-+-+-+-+-+-+-+-+-++-+-+-+-+-+-+-+-+-+-+-+-
  // normal code
 
   private synchronized BufferedImage loadSprite(String sprName) {
      // Attempts to load sprite sprName
     BufferedImage spr = null;
      try {
         spr = ImageIO.read(new File(path+sprName));
      } catch (IOException e) {
         // Error occured
        return null;
      }
      return spr;
   }
   private boolean sprExists(String sprName) {
      // checks if a sprite has already been added/loaded
     // into the hash map
     boolean b = hm.containsKey(sprName);
      return b;
   }
   
   
   
   public synchronized BufferedImage getSprite(String sprName) {
      // used by other objects to load/get their image
     // that represents their sprite name.
     if(sprExists(sprName)) {
         // Sprite already loaded.
        return hm.get(sprName);
      } else {
         // Sprite hasn't been loaded yet.
        BufferedImage spr;
         spr = loadSprite(sprName);
         if(spr == null) {
            // An error occured, couldn't load sprite.
           return null;
         } // else move on
          /* transform the loaded sprite into an image
            * with the top left pixel color as transparent */

         spr =
            imageToBufferedImage(  makeColorTransparent(spr)  );
         
         // save the loaded sprite (and now transparent) into the hashmap
        hm.put(sprName, spr);
         // and then return the sprite
        return spr;
      }
   }
   
   // Transforms a BufferedImage with a transparent color
  // into an Image ( use imagetoBufferedImage(Image imgage) method
  // to turn it back into a BufferedImage.
  private Image
            makeColorTransparent(BufferedImage img) {
               final Color c =  new Color(img.getRGB(0,0)); /* The color to turn transparent
                                   * is in the top left corner
                                   * of the image */

               ImageFilter filter = new RGBImageFilter() {
                  // the color to turn into transparent (opaque)
                 int markerRGB = c.getRGB() | 0xFF000000;
                 
                  public final int filterRGB(int x, int y, int rgb) {
                     if( (rgb | 0xFF000000) == markerRGB) {
                        // Mark the alpha bits as zero - transparent
                       return 0x00FFFFFF & rgb;
                     } else {
                        //do nothing
                       return rgb;
                     }
                  }
               };
               
               ImageProducer ip = new FilteredImageSource(img.getSource(), filter);
               return Toolkit.getDefaultToolkit().createImage(ip);
   }
   
   // Turn an Image into a BufferedImage
  private BufferedImage imageToBufferedImage(Image image) {
       BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
       Graphics2D g2 = bufferedImage.createGraphics();
       g2.drawImage(image, 0, 0, null);
       g2.dispose();
       return bufferedImage;
      /* Source code
      http://stackoverflow.com/questions/665406/how-to-make-a-color-transparent-in-a-bufferedimage-and-save-as-png
      */

    }
   
   public synchronized int size() {
      // return the number of images loaded into memory
     return hm.size();
   }
   
 }

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

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #3 - Posted 2011-10-09 11:39:59 »

Ugh. There is absolutely no reason to make that into a singleton other than lazyness. Angry

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline jonjava
« Reply #4 - Posted 2011-10-09 11:51:23 »

I was going to PM you but I can't find a PM button anywhere - either I'm blind or could someone tell me?

I was going to ask why not to use a SingleTone? The only other way would be to make the whole object Static? And why would it be lazy to make a Singletone? Making the object static sound more lazy to me.. Is there another better way to accomplish this? I'd be interested to hear it.

Thanks,
Jon

Offline Cero
« Reply #5 - Posted 2011-10-09 12:08:15 »

Click a user and then there is a link "Send this member a personal message."

I never use singletons, only static classes...

Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #6 - Posted 2011-10-09 13:03:10 »

I was going to ask why not to use a SingleTone? The only other way would be to make the whole object Static? And why would it be lazy to make a Singletone? Making the object static sound more lazy to me.. Is there another better way to accomplish this? I'd be interested to hear it.
How about neither of those? Just use it like a regular class, make a single object and pass that into the objects that need to use it.

Using it as a singleton hides important dependances, makes resource management harder and more error prone and gives you no advantages other than a little less typing.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline jonjava
« Reply #7 - Posted 2011-10-09 15:15:37 »

So I can basically achieve the same thing by just making the HashMap variable static, as well as the getSprite() metod static ( the method other objects use to get/load their sprites through my class)? What you said about hidden dependencies is pretty enlightening.  Pointing

The reason I fell into using a singleton is because I was looking for a way to have 1 single class handle the loading and distribution of images throughout my objects. And because in order to use a HashMap I needed to instantiate the class which made me worried about accidentally instantiating the class twice (or more) and mess up the whole idea of having 1 single class handle the images.

Looking at it now I find it quite redundant and potentially harmful.  Lips Sealed

Offline Z-Man
« Reply #8 - Posted 2011-10-09 15:26:16 »

I have a static SpriteList class that stores my sprites  for me, so all I have to do when I need a Sprite is call SpriteList.get("SpriteName"); works pretty well for me and it just eliminates having to pass around a Sprite, or a SpriteList object. Err... scratch that... I refactored my code so that it uses a non-static non-singleton SpriteList and I like it more x). I just pass either a specific Sprite/set of Sprites around or a reference to the SpriteList. Grin
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #9 - Posted 2011-10-09 16:14:12 »

So I can basically achieve the same thing by just making the HashMap variable static, as well as the getSprite() metod static ( the method other objects use to get/load their sprites through my class)?
No no. Banish *all* thoughts of anything being static. Nothing here needs to be static. Your SpriteBank class stays as it is, but without the singleton bits. Then, somewhere in your Game or App class (whatever is near the top) you create one SpriteBank, and pass it in as an argument (probably in the c'tor) to your Map or Level or Player or whatever needs to actually call getSprite().

And you'll probably find too many places calling getSprite(), which is almost certainly an indication that you've got *too much* code that talks about graphics-y stuff that really shouldn't. So there's more possibilities for refactoring there too.

Very, very few bits of mutable state actually need to be static in a game. I actually can't remember a time when I added mutable global/static state and didn't later refactor it to be non-static and found the result to be simpler and more flexible.

I also can't remember the last time I actually made or needed a singleton. But once you get stuck in a mindset of making things singletons, suddenly *everything* becomes a singleton and you're pretty screwed.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline jonjava
« Reply #10 - Posted 2011-10-09 16:27:39 »

So I can basically achieve the same thing by just making the HashMap variable static, as well as the getSprite() metod static ( the method other objects use to get/load their sprites through my class)?
No no. Banish *all* thoughts of anything being static. Nothing here needs to be static. Your SpriteBank class stays as it is, but without the singleton bits. Then, somewhere in your Game or App class (whatever is near the top) you create one SpriteBank, and pass it in as an argument (probably in the c'tor) to your Map or Level or Player or whatever needs to actually call getSprite().

And you'll probably find too many places calling getSprite(), which is almost certainly an indication that you've got *too much* code that talks about graphics-y stuff that really shouldn't. So there's more possibilities for refactoring there too.

Very, very few bits of mutable state actually need to be static in a game. I actually can't remember a time when I added mutable global/static state and didn't later refactor it to be non-static and found the result to be simpler and more flexible.

But if I load a sprite seperately for every object I will end up with hundreds of objects that have loaded the exact same image into memory multiple times. I don't see how without a static variable this can be achieved... Well, unless like you said you create one SpriteBank class and pass its reference around.. but that would mean I'd have to do something like Game.getSpriteClass().getSprite() or Game.sprClass.getSprite(); - Rather just have them talk directly to the SpriteBank class. I see the minimum amount of 'static' use would be to make the HashMap static since at least then, even if there are multple SpriteBank instances around, they will all check with the Static HashMap if a certain image has already been loaded into memory.

Wouldn't you agree?

Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #11 - Posted 2011-10-09 16:57:28 »

Wouldn't you agree?

Not really. Put simply you're Doing It Wrong.

You keep trying to inject or reach out to global state where none is required. Think about something along these lines:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
class Game
{
  public static void main(String[] args)
  {
    Game game = new Game();
    game.run();
  }

  private void run()
  {
     SpriteBank spriteBank = new SpriteBank();
     Map map = new Map(spriteBank);
     Player player = new Player(spriteBank);

     while (gameRunning)
     {
        map.update();
        player.update();

        map.draw();
      }
  }
}


You create your sprite bank, pass it into the objects that need it, and they call getSprite() as needed. Obviously lots missing from the example code but no global or static data is needed (or desired).

Perhaps if you posted some of your code we'd be able to give you some more specific hints.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline jonjava
« Reply #12 - Posted 2011-10-09 17:46:03 »

I made a small mashup with my excellent MS Paint skills http://i.imgur.com/14SyM.png

All of my classes are in separate files.

What happens is that whenever I instantiate a Block class ( which is a subclass of the abstract ISOObject ) it gives SpriteBank its String sprName variable. The SpriteBank class determines if this sprName points to a valid image file and (loads the image the first time) and references it back to the Block object.

The drawing of the ISOObjects start from the JPanel class (which creates the "Map" (ISORoom room = new ISORoom();) that holds a sorted ArrayList<ISOObject> of ALL ISOObjects that exist in the room). The JPanel  calls the room.paintAll() method. The room.paintAll() method iterates through its ArrayList<ISOObject> variables, invoking each ISOObjects paint() method. The ISOObjects.paint() method uses the drawImage() method to draw its image on the JPanel's Graphics "screen".


Are there any significant reasons why NOT to make the class/HashMap static?

Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #13 - Posted 2011-10-09 18:37:27 »

Are there any significant reasons why NOT to make the class/HashMap static?

The evils of singletons and global mutable state are well documented by people more expressive and smarter than me, so you should probably just google that. You could certainly start with singletons are evil. But largely they're hard to test, cause dependancy nightmares and generally make code more brittle.

For your code, why not just create a single SpriteBank in ISOFrame and hold it as a member variable there? Then you'd pass it down to ISORoom and ISOObject via their constructors are required. Then if (for example) different rooms needed different sprite banks (say, one room was darker and all sprites needed to be made darker when being loaded) you could do that without any further changes. With a singleton that'd be a much messier thing to implement.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline sproingie

JGO Kernel


Medals: 202



« Reply #14 - Posted 2011-10-09 19:09:46 »

Singletons are not evil per se -- this SpriteBank class is a singleton, for example.  What's evil is static singletons, where their "singletonicity", to coin a fancy new term, is maintained by static members instead of some container object.  MyClass.getInstance() is doing singletons wrong; Spring and Guice do singleton right (and for games, I'd recommend Guice -- Spring is kinda "enterprisey"). 
Online theagentd
« Reply #15 - Posted 2011-10-09 20:14:10 »

Jeez. I think it does make sense to keep it static, or at least separate from the game state. The underlying file system could be considered "static" in a way, so I think a resource cache should also be static in my opinion. It would be a little bit simpler to not have to pass around an instance of SpriteBank all the time, and it works, so why overcomplicate things?

Myomyomyo.
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #16 - Posted 2011-10-09 20:41:14 »

A file system isn't static, nor is it a singleton, nor is a SpriteBank a file system. That analogy doesn't really work for me I'm afraid.

Secondly, passing around a reference is simpler than implementing a singleton. Passing around reference is what we do when we program. Singletons subvert a large amount of the structure that programs (and languages) attempt to build.

More practically, the constraints for a singleton (only a single one must *ever* exist, and it *must* be globally accessible) are very, very rarely met. Sometimes one or the other is, but both must be satisfied for a singleton to be reasonably justified. Should a sound mixer have global, unfettered access to a sprite bank? Should a keyboard input device have access to a sprite bank? I don't think you can make a reasonable case for this.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline sproingie

JGO Kernel


Medals: 202



« Reply #17 - Posted 2011-10-09 22:53:18 »

If you need to pass around a ready-made instance of your singleton whenever you create a new instance pass that depends on it, and that instance maybe needs an instance of some other object and so forth, your job gets a lot easier when you have a class factory that keeps track of these dependencies, creates them on demand, and injects them into new objects.  This is exactly what Dependency Injection (DI) containers like Spring and Guice do.  You're not stuck with globals, you don't have to worry about making them threadsafe (the container does that), and you can special-case some classes to inject a different instance instead of your singleton when you need it (such as for testing). 
Online theagentd
« Reply #18 - Posted 2011-10-10 00:47:04 »

A file system isn't static, nor is it a singleton, nor is a SpriteBank a file system. That analogy doesn't really work for me I'm afraid.

Secondly, passing around a reference is simpler than implementing a singleton. Passing around reference is what we do when we program. Singletons subvert a large amount of the structure that programs (and languages) attempt to build.

More practically, the constraints for a singleton (only a single one must *ever* exist, and it *must* be globally accessible) are very, very rarely met. Sometimes one or the other is, but both must be satisfied for a singleton to be reasonably justified. Should a sound mixer have global, unfettered access to a sprite bank? Should a keyboard input device have access to a sprite bank? I don't think you can make a reasonable case for this.
What I meant was for a resource loader+cache, not necessarily a SpriteBank. Such a class could be used in many places (textures, sound, input key bindings), but I realize that this isn't even a smart idea (having such a cache I mean), and that it hardly applies to this case in the first place, so you're right.

Myomyomyo.
Offline jonjava
« Reply #19 - Posted 2011-10-10 07:03:07 »

I'd like to thank everyone for their input even though I derailed the issue slightly off-topic. I've learned more than expected.

As a new programmer the big picture is still blurred to say the least but I think I can at least sniff some of the aromas of less static and non-singleton design.

I have refactored my code to not use singleton or static design - I'm too much of a newbie to have a valid opinion on this but I have a feeling I'd later in life adhere to it. Tongue

Thanks again,
jon

Offline Cero
« Reply #20 - Posted 2011-10-10 16:29:57 »

I don't really get your beef with static classes / singletons but stuff like a SpriteBank, in my case a ContentManager shall never ever be instantiated twice.
Your not going to load content twice from file to RAM. And it would be bad if someone did =D

sure Input classes for example don't need access to this class, but they can't do any harm really.

My ContentManager is the only class that accesses content/assets in file form directly, and whoever needs content and get it from here.
A centralized class to load, manage and IO content.

Audio is also there, which means, yeah, you can play a sound whenever the inputHandler finds a new device... but it could be that you would actually wanna do this

In any case this access cannot really break anything.

Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #21 - Posted 2011-10-10 17:01:52 »

The issues with global mutable state are, as I mentioned, heavily documented so I don't want to get into it here (and I've posted big posts on this board previously if you're really interested). But I will say that it could be that you don't see the problems with it because you're working alone on a small, single person project. You can get away with all sorts of software engineering horrors if it's just you and the compiler. Smiley If you genuinely have the discipline to get away with that kind of thing then go for it, but I'd rather do things cleanly because it means I've got less to think about when I develop and debug.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline drakesword

Junior Member


Medals: 1



« Reply #22 - Posted 2011-10-11 02:03:20 »

+1

Also it doesnt matter if you are not doing the work for someone else. When its just you and YOUR project remember its YOUR project. You are the boss. Quite personally I switch back and fourth between singleton and objects. Both of them have their places otherwise one or the other would be missing from java as the language in large.
Offline jonjava
« Reply #23 - Posted 2011-10-29 19:04:58 »

I came upon an interesting Google Tech Talk video about Singletons* and Global state - and why they are bad. Made me think of this thread so I thougth I'd share it with those interested. Note, it's a lengthy 50 min video, but Singletons in particular are quite well established at the 30 min mark and a good good question is asked at the 31 min mark!

http://www.youtube.com/watch?v=-FRm3VPhseI

*I.e. Singletons with private constructors ( like my SpriteBank class ).

Offline Cero
« Reply #24 - Posted 2011-10-29 20:20:28 »

watched it.

Obviously when you write APIs/Code other people should use, you gotta do it in a way people will understand.
But in my code, which only I and maybe my team has to understand and use, choose 1 or 2 singletons/static classes when is makes sense, instead of having a gazillion pointers and methods with those parameters...

Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #25 - Posted 2011-10-30 12:55:19 »

But in my code, which only I and maybe my team has to understand and use, choose 1 or 2 singletons/static classes when is makes sense, instead of having a gazillion pointers and methods with those parameters...

"These well thought out arguments and points by intelligent people make sense, but somehow don't apply to me".

Good luck with that. Roll Eyes

Also, if you've got "a gazillion pointers and parameters", you're doing it wrong. This was addressed in the Q&A at the end if you'd actually been paying attention.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Online theagentd
« Reply #26 - Posted 2011-10-30 13:18:59 »

I only watched about half of it, but I'm not fully understanding the words he uses (and he speaks so quickly T_T) as English isn't my native language. I mean, I get why you want to avoid global state, but what was his proposed solution to the problem he was talking about? Factory classes? If someone could explain it really quickly (preferably with some code =S) that would be awesome. I feel like design patterns and the likes  are the one thing I need to get better at at the moment. Let's get this discussion started! =D

Myomyomyo.
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #27 - Posted 2011-10-30 13:25:48 »

I only watched about half of it, but I'm not fully understanding the words he uses (and he speaks so quickly T_T) as English isn't my native language. I mean, I get why you want to avoid global state, but what was his proposed solution to the problem he was talking about? Factory classes? If someone could explain it really quickly (preferably with some code =S) that would be awesome. I feel like design patterns and the likes  are the one thing I need to get better at at the moment. Let's get this discussion started! =D

There's very little to understand, and no magic patterns going on. Start at 25:20 to see the fixed version of the code. It's just removing the singletons and hidden dependancies, and making them explicit by passing required objects as constructor params. You end up with code that's more explicit, simpler and easier to understand.

The 'problem' that most people have is that it's too simple. They don't get to point to their code and say "I used four different design patterns here". It's not sexy and new and buzzword compliant. But it's much better code.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline Cero
« Reply #28 - Posted 2011-10-30 16:33:49 »

I only watched about half of it, but I'm not fully understanding the words he uses (and he speaks so quickly T_T) as English isn't my native language. I mean, I get why you want to avoid global state, but what was his proposed solution to the problem he was talking about? Factory classes? If someone could explain it really quickly (preferably with some code =S) that would be awesome. I feel like design patterns and the likes  are the one thing I need to get better at at the moment. Let's get this discussion started! =D

If you develop a whole game, you will run into this problem eventually

you dont want all the code in one class, so you split it - but then the other parts depend on parts which are now in other classes
so you either have a lot of pointers or methods which many parameters, which are also pointers

the better your design, the less you encounter this problem

but sometimes you cannot know in advance if and when a class gets too big (unless you have it all planned out) - and then if you split it, you have to look how to do it, so that it is efficient, easy to understand/use and not error prone

Online theagentd
« Reply #29 - Posted 2011-10-30 19:33:49 »

I only watched about half of it, but I'm not fully understanding the words he uses (and he speaks so quickly T_T) as English isn't my native language. I mean, I get why you want to avoid global state, but what was his proposed solution to the problem he was talking about? Factory classes? If someone could explain it really quickly (preferably with some code =S) that would be awesome. I feel like design patterns and the likes  are the one thing I need to get better at at the moment. Let's get this discussion started! =D

If you develop a whole game, you will run into this problem eventually

you dont want all the code in one class, so you split it - but then the other parts depend on parts which are now in other classes
so you either have a lot of pointers or methods which many parameters, which are also pointers

the better your design, the less you encounter this problem

but sometimes you cannot know in advance if and when a class gets too big (unless you have it all planned out) - and then if you split it, you have to look how to do it, so that it is efficient, easy to understand/use and not error prone
I know... It's hard to figure everything out before you start though, as you basically have to "write" the whole game inside your head...

I only watched about half of it, but I'm not fully understanding the words he uses (and he speaks so quickly T_T) as English isn't my native language. I mean, I get why you want to avoid global state, but what was his proposed solution to the problem he was talking about? Factory classes? If someone could explain it really quickly (preferably with some code =S) that would be awesome. I feel like design patterns and the likes  are the one thing I need to get better at at the moment. Let's get this discussion started! =D

If you develop a whole game, you will run into this problem eventually

you dont want all the code in one class, so you split it - but then the other parts depend on parts which are now in other classes
so you either have a lot of pointers or methods which many parameters, which are also pointers

the better your design, the less you encounter this problem

but sometimes you cannot know in advance if and when a class gets too big (unless you have it all planned out) - and then if you split it, you have to look how to do it, so that it is efficient, easy to understand/use and not error prone
... which is why I'm kind of stuck at the moment. It's not like I have a real problem to solve, it's just that I don't really dare to continue out of fear of just having to redo everything when I realize the puzzle pieces don't fit in the end.

Myomyomyo.
Pages: [1] 2
  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.

Nickropheliac (14 views)
2014-08-31 22:59:12

TehJavaDev (23 views)
2014-08-28 18:26:30

CopyableCougar4 (29 views)
2014-08-22 19:31:30

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

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

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

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

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

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

BurntPizza (48 views)
2014-08-09 21:09:32
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!