Archive for the ‘java’ Category

A new Project is started

February 14, 2012 Leave a comment

I’ve always wanted to develop a game, though the lack of time, art skill and game ideas always stopped me. Recently i made up my mind and decided to get it started. I settled for making a small rpg dungeon crawler, though i have yet to define the fine detail specifics.

I started this project as a hobby, a way to have some fun doing something i like and as a learning instrument. Through out this project i will make many mistakes and end up refactoring the code base, i have already done a lot of that and i have yet to scratch the surface of the game.

Currently this is what i have

Ignore the game name, i just felt the whole path would be filled with trials and tribulations. As of this time i have managed to generate the dungeon, a simple 60×30 array of floor, water and wall tiles. I also have player movement and wall collision setup.

The art you see above is a placeholder for something i intend to make further down the road (as i said no art skill) and can be found here.


It took me more time than it should’ve to decide what language and framework to use for this little hobby. I looked at python and pygame, ruby, xna, c++, java. Ended up choosing java, because it allows me to avoid relearning the other languages. For framework i chose Slick2D, which is  set of tools wrapped around the LWJGL OpenGL binding for Java.

Dungeon Generation

I decided early on that the dungeons needed to be procedurally generated so I set out to learn how to do just that. I found the Procedural Content Generation Wiki and thanks to them i ended up settling on a Cellular Automata method that would allow me to generate cave like levels.

During generation i just place tiles that end up living or dying during the 3 generations i allow them. I place two types of tile, wall and water. All the other tiles are automatically considered to be floor. This is a simplistic approach that i will need to refine, for instance you will easily find isolated water tiles inside walls or even situations like you see on the screen above where there are just a couple of tiles that bring nothing to the dungeon.

Rendering Art

After generating the tiles its time to draw them. My first attempt slowed down my screen to a crawl. The reason was twofold: rendering all the map and using the wrong api from Slick2D.

At first i was simply iterating all the map and drawing images to the screen with SpriteSheet.getSprite(x, y).

SpriteSheet is a wrapper for an image that contains all your tiles. when you do getSprite it creates an Image object with the appropriate tile. A good explanation taken from StackOverflow:

There is a SpriteSheet class in Slick that does exactly this.

SpriteSheets, in Slick, are large images made up of a series of uniformly sized tiles. Each tile is typically an animation frame in a Sprite. In the SpriteSheet constructor you specify the image (which has all the tiles), and the width/height of the tiles in the sheet, along with any spacing and margin, if you have/need that.

Finally, the getSprite(x, y) method allows you to retrieve the specified tile, as if it were an element in a 2D array. In other words, if you have a SpriteSheet of 16 tiles, that are arranged in a 4×4 grid of tiles, then to get the tile in column 3, row 2, you would call getSprite(3, 2);

I believe the indexes in getSprite(x, y) are zero-based, just like arrays in Java.

Unfortunately this solution has really bad performance when you are rendering a tile map iteratively. The best option is to use the renderInUse method of the spritesheet, you can see a simple example bellow.

Also in the code bellow you can see that i fixed the my other problem (rendering all the map), initially i was rendering the whole 60×30 array independently of whether or not the map could be seen on the screen. The trick was to determine the view area of the map and only render those tiles.

    for (int i = startingY; i < endingY; i++) {
        String[] columns = map[i];
        for (int j = startingX; j < endingX; j++) {
            int xp = (int) x + ((j - startingX) * 32);
            int yp = (int) y + ((i - startingY) * 32);
            if (columns[j].equals("#")) {
                sh.renderInUse(xp, yp, 8, 3);
            } else if (columns[j].equals("$")) {
                sh.renderInUse(xp, yp, 1, 2);
            } else {
                sh.renderInUse(xp, yp, 4, 3);

A little warning, this method of drawing does not play well if you try and do other things in between (GL calls, drawing other images not in this sprite).

That is it for now, i will probably put player movement and collision in it’s own post. For now i will say it gave me much more trouble i ever expected it to.

Since this is a pet project and i’m using it to learn i don’t really have a pre defined path of what i will code next. I go with what i feel like doing, as of now i figure the next steps will be:

  • Fog of War
  • New Art
  • Mob Spawning

Extreme Exception Programming – Catch Every Exception and Work Around It

October 10, 2010 Leave a comment
I was reviewing the commit log from the last week commits and found this gem:
list = (ArrayList<MyObject1>)session.getAttribute(TEMPORARY_LIST);
}catch (ClassCastException e){
if(add.getMyObjectCurrentItem()) != -1)
list = add.getOtherList().get(add.getMyObjectList()).getMyObjectList();
} catch(IndexOutOfBoundsException e2){
list = add.getOtherList().get(add.getMyObjectList()-1).getMyObjectList();<
} catch(IndexOutOfBoundsException e3){
//Move On

Only thing that came to mind was WTF, after Showing it to my boss he called it : Extreme Exception Programming.
I tweeted before about how in Enterprise we end up coding for every possible chance, but this is going too far.
Categories: java, WTF Tags: , , ,

Oracle Number to Java Object

January 19, 2010 Leave a comment

Recently i needed to know what should be the JAVA Object to use when mapping against an oracle database.

You can easily find alot of documentation on these mappings by searching google, but if you need to convert data types in the form of Number(p,s) (where p is precision and s is scale) you will have alot more trouble.

I ended up finding a reference to some old bea documentation(which got thrown offline when oracle took over bea) in an objectmix thread. So i put it here if anyone ever needs it:

Column Definition Returned by getObject()
NUMBER(P <=3D 9)

NUMBER(P <=3D 18)

NUMBER(P >=3D 19)

NUMBER(P <=3D16, S > 0)

NUMBER(P >=3D 17, S > 0)

Links :

Categories: java, oracle Tags: ,

Why I Hate Weblogic Integration

December 22, 2009 1 comment

This is a running post, as i go along with my current task of trying to use WLI i’m pretty sure i will be adding items to this list:

  • WorkShop – What a bloated and buggy piece of crap. This is probably the worst part till now.
    • I guess its too much to ask for a software to give reasons for not working but eh, here are some i have found:
      • Don’t put your workspace on a path with spaces or strange letters(like ó)
      • If trying to create to create a task plan workshop refuses to responde to next your trying to create the plan in the wrong folder
  • Transformations – grrrrrr… trying to debug these things is the worst thing i’ve had to do. want to know why? because i can’t…
  • It’s really hard to understand why we should even use this crap, and why do people around the world actually consider this as added value….

Extending EJB3 Objects

December 2, 2009 Leave a comment

Small and fast tip.

In order to be able to extend an EJB Entity object (be it a main object or a primary key embbedable) you need to write the MappedSuperclass anotation in the super class.

The following is taken from hibernate documentation :

public class BaseEntity {
    public Date getLastUpdate() { ... }
    public String getLastUpdater() { ... }

@Entity class Order extends BaseEntity {
    @Id public Integer getId() { ... }

Some other notes taken from the documentation :

  • Properties from superclasses not mapped as @MappedSuperclass are ignored;
  • The access type (field or methods), is inherited from the root entity, unless you use the Hibernate annotation @AccessType;
  • Any class in the hierarchy non annotated with @MappedSuperclass nor @Entity will be ignored.

Read the documentation to understand it fully : chapter

Please note that even though i’ve used the Hibernate documentation as a reference this anotation also exists in javax.persistence so it can be used with JPA

Categories: ejb3, java Tags: , ,

NoContainer Dependency Injection

August 6, 2009 Leave a comment

I recently needed to find out a way to define an interface on one side, and define the implementation on the other. I went to StackOverflow with a poorly written question and the overflowers there ended up giving me the answer.

One of the answers given mentioned the solution could be providing the implementation through the constructor(thx to palyndrom for the answer):

class A implements EventHandlerForB {
public class B {
  private EventHandlerForB eventHandler;
  public void registerEventHandler(EventHandlerForB eventHandler) {
     this.eventHandler = eventHandler;
public interface EventHandlerForB {

This didn’t work for me since i had no intention of instantiating the class. Then dfa mentioned java.util.ServiceLoader(for JDK 6). This was a perfect fit. ServiceLoader involves creating an interface and then using a properties file to define the implementation on the client side.

For a ServiceLoader tutorial see Tim Boudreau’s Blog post.

Unfortunately for me i couldn’t use it since i wasn’t programming for jdk 6. I needed a custom solution. A little side note, another solution, also mentioned by an overflower, would be to use Guice or another Dependency Injection framework. I took a quick look at it but didn’t spend much time over it. It seem to be pretty powerfull, but by now i wanted a simpler solution than Guice.

I ended up looking up how ServiceLoader did things and found a link that gave me this solution.

Basicly you define your Interface A on Application A, and in there you call your interface using a simple factory. On application B you implement Interface A and create a property file in your classpath. And your done. The wizardry here is all done by the Factory object :

public class EventHandlerFactory {

 public EventHandler buildEventHandler() {

     try {
          InputStream propertyFile = getClass().getClassLoader().getResourceAsStream("");
          Properties properties = new Properties();
          Class eventImpl = Class.forName(properties.getProperty("EventHandler-Implementation"));
          if (EventHandler.class.isAssignableFrom(eventImpl)) {
             return (EventHandler) eventImpl.newInstance();
          } else
             throw new RuntimeException("No Implementation For EventHandler found!!!");
      } catch (IOException e) {
         throw new RuntimeException("Cannot Find propertyes File");
      } catch (InstantiationException e) {
         throw new RuntimeException("Problem Instantiating class for EventHandler implementation",e);
      } catch (IllegalAccessException e) {
         throw new RuntimeException("Problem Instantiating class for EventHandler implementation",e);
      } catch (ClassNotFoundException e) {
         throw new RuntimeException("Problem Instantiating class for EventHandler implementation",e);

The code above is far from robust or reusable, first it forces the properties name file (ServiceLoader takes the property name file from the Interface complete name) and it forces you to use a hard coded property when that could’ve been infered from the interface name too. But changing the code to do as you please should be relatively trivial.

Another thing ServiceLoader does is allow you to define several different implementation classes for a given interface, then on the server side you can for through them all and call your method, the above code assumes there is only one implementation for that interface. Again changing this should be relatively trivial.

The property file should be located in your sourcepath and have the name :, the following property should be defined


To call the object on the Application A side you do the following:

EventHandlerFactory factory = new EventHandlerFactory();
EventHandler evt = factory.buildEventHandler();

Hope this helps

How to access a private field in java

This was a question posted in StackOverflow.
I didn’t know this was possible, so i am posting the answer provided by oxbow_lakes as is:

In order to access private fields, you need to get them from the class’s declared fields and then make them accessible:

Field f = obj.getClass().getDeclaredField(“stuffIWant”); //NoSuchFieldException
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException

EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value will all throw Exceptions, although the only checked exceptions you need to be mindful of are commented above.

The NoSuchFieldException would be thrown if you asked for a field by a name which did not correspond to a declared field.

obj.getClass().getDeclaredField(“misspelled”); //will throw NoSuchFieldException

The IllegalAccessException would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true) line.

The RuntimeExceptions which may be thrown are either SecurityExceptions (if the JVM’s SecurityManager will not allow you to change a field’s accessibility), or IllegalArgumentExceptions, if you try and access the field on an object not of the field’s class’s type:

f.get(“BOB”); //will throw IllegalArgumentException, as String is of the wrong type

I advise you to go read the question and the answers at SO :

Categories: java Tags: ,