Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, January 11, 2011

Facebook Hacker Cup: A Geometric Approach to Double Squares Problem

Given an integer N, we need to find the number of integral pairs (x, y) such that x^2 + y^2 = N.
n can range from [0, 2147483647] and there can be a max of 100 such numbers in the input file.

From elementary geometry, we know that x^2 + y^2 = r represents a circle centered at (0,0) with a radius r. Therefore, x^2 + y^2 = n represents a circle with radius n. This is illustrated in figure 1. Now the problem is to find all possible solutions to this equation (in the first quadrant) where x, y are integers.

Figure 1

Bruteforcing all possible integral pairs of (x, y) upto n is equivalent to searching within the geometric space (grey rectangle) illustrated in fig 2.

Figure 2
Algorithmically this approach takes O(n^2) time.Consider the sample input as shown below (this was the file I received)
20
1105
65
2147483646
1257431873
25
1000582589
1148284322
5525
0
1475149141
858320077
1022907856
1041493518
3
1215306625
372654318
160225
5928325
2147483643
1538292481
On my machine, brute force approach takes approx 14 hours (!!!) to solve this input. Obviously Facebook wasnt kidding when it hinted: "Too hard to bruteforce, switching to dp". Clearly, we are exploring a lot of unwanted points. One obvious way to improve this is to explore points bounded by the circle as shown by blue shaded rectangle in fig 3.


Figure 3

This is equivalent to looping x and y from 0 to n. This makes sense because x or y can never exceed . For example, with n = 25, if x = 5, y = 0 and vice versa. This reduces the complexity from O(n^2) to O(n) reducing execution time from 14 minutes to 80.5 sec!

Can we do any better? Why are we even exploring the blue rectangular region? Its sufficient if we examine all points on the arc of the circle in the first quadrant. i.e., we can increment x = 0 to x' (if x' is irrational number, its safe to use ceil(x')) and examine if the corresponding y points on the circle is an integer. y can be calculated using sqrt(n - x^2). Y is an integer if floor(y) == y. As illustrated in figure 4, all the points to the left of the line y=x is the mirror image of the points to the right. i.e, if we find a point, say (3, 4) to the left of y=x, then we will find a mirror image at (4, 3). Since the problem doesn't differentiate between these two. It is sufficient if we iterate x until the point x'. x' is given by .

Figure 4

With this, the complete algorithm in JAVA is listed below:

private static int getNumSumSquares(int n) 
{
if(n==0)
return 1;

int iterations = (int) Math.ceil(Math.sqrt((n * 1.0)/2));
double y;
int count = 0;
for(int x=0; x <= iterations; x++)
{
y = Math.sqrt(n - (x*x));
//check if y = int.
if(Math.floor(y) == y)
count++;
}
return count;
}
This algorithm works in O(sqrt(n/2)) ~ O(sqrt(n)). This is a huge improvement over the naive approach. With these improvements, it just takes 0.047 secs to execute!

Friday, September 24, 2010

Adding class attributes at runtime :O

The use is kind of hard to describe. In some situations, it makes more sense to add attributes to an instance at runtime. One example would be to perform optimizations at runtime (Maybe I'll describe a solid example at a latter time).

The trick is to use a HashMap to store property name and value pair. For ease of use, I defined a class 'Bufferable' with this capability. Any class extending 'Bufferable' should inherit dynamic attribute feature.

/**
* A Utility class to support addition of new properties to a java bean
* at the runtime. Extend your class with this to make it bufferable. It is
* useful if you want to associate certain properties with an object and
* maintain the OOP nature of your code.
*
*

This class extends AbstractSerializableBean
* for serialization and property change support.
*
* @author Ragha
* @see AbstractSerializableBean
* @version 1.0
*/
public class Bufferable extends AbstractSerializableBean
{
private static final long serialVersionUID = 506835437375346326L;

/**
* This map is used to store property name and object as key-value pairs.
*/
private HashMap buffer = new HashMap();

/**
* This method is used as a getter for the associated property in the
* buffer.
*
*

You must typically create the property using
* {@link #createPropertyInBuffer(java.lang.String) createPropertyInBuffer(...)} method
* before using this method.
*
* @param property The property to be used
* @return The value of the property.
* @throws java.lang.IllegalArgumentException If there is no such property.
*/
public Object getValueFromBuffer(String property)
throws IllegalArgumentException
{
if(buffer.containsKey(property))
return buffer.get(property);
else
{
throw new IllegalArgumentException("Property: '"+property+"' " +
"does not exist...");
}
}

/**
* This method can be used as a setter for the associated property.
* in the buffer.
*
*

You must typically create the property using
* {@link #createPropertyInBuffer(java.lang.String) createPropertyInBuffer(...)} method
* before using this method.
*
* @param property The property value to be set
* @param Value The value to be set
* @throws java.lang.IllegalArgumentException If there is no such property
*/
public void putValueInBuffer(String property, Object Value)
throws IllegalArgumentException
{
if(buffer.containsKey(property))
buffer.put(property, Value);
else
{
throw new IllegalArgumentException("Property: '"+property+"' " +
"does not exist...");
}
}

/**
* Creates a new property in the buffer. Once the property is created,
* it can be get or set using the
* {@link #putValueInBuffer(java.lang.String, java.lang.Object) putValueInBuffer(...)} and
* {@link #getValueFromBuffer(java.lang.String) getValueFromBuffer(...)} methods
*
*

It is recommended that you use Classname-property name as property
* string to avoid conflicts with other existing property names...
*
* @param property The property name to be associated with the buffer.
* @throws java.lang.IllegalArgumentException If the property name already exists.
*/
public void createPropertyInBuffer(String property)
throws IllegalArgumentException
{
if(buffer.containsKey(property))
{
throw new IllegalArgumentException("Property: '"+property+"' " +
"already exists...");
}
else
{
buffer.put(property, new Object());
}
}

/**
* This method can be used to check if a given property already exists.
* @param property The property to be checked.
* @return true, if the property exists.
*/
public boolean isPropertyInBuffer(String property)
{
return buffer.containsKey(property);
}

@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Bufferable other = (Bufferable) obj;
if (this.buffer != other.buffer && (this.buffer == null || !this.buffer.equals(other.buffer))) {
return false;
}
return true;
}

@Override
public int hashCode() {
int hash = 3;
hash = 79 * hash + (this.buffer != null ? this.buffer.hashCode() : 0);
return hash;
}
}

Everything should look pretty obvious except for why i am extending my class with AbstractSerializableBean. Well, this is done in order to make the class Serializable. The code for AbstractSerializableBean should make things clearer.

/**
* This subclass enhances {@code AbstractBean} by implementing the
* {@code Serializable} interface. {@code AbstractSerializableBean} correctly
* serializes all {@code Serializable} listeners that it contains. Implementors
* that need to extends {@code AbstractBean} or one of its subclasses and
* require serialization should use this class if possible. If it is not
* possible to extend this class, the implementation can guide implementors on
* how to properly serialize the listeners.
*
* @see AbstractBean
* @author Ragha
*/
public class AbstractSerializableBean extends AbstractBean implements Serializable
{
private static final long serialVersionUID = -3459406004204097480L;

protected AbstractSerializableBean()
{
super();
}

private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();

for (PropertyChangeListener l : getPropertyChangeListeners()) {
if (l instanceof Serializable) {
s.writeObject(l);
}
}
s.writeObject(null);
}

private void readObject(ObjectInputStream s) throws ClassNotFoundException,
IOException {
s.defaultReadObject();

Object listenerOrNull;
while (null != (listenerOrNull = s.readObject())) {
if (listenerOrNull instanceof PropertyChangeListener) {
addPropertyChangeListener((PropertyChangeListener) listenerOrNull);
}
}
}
}
That's it...pretty straight forward isn't it..

Saturday, June 13, 2009

LookupListener problem?

There are many unanswered threads to this question. The common issue is that the resultChanged(...) method is never triggered!! Here is a proper use-case scenario (note the comments, they provide tips to avoid common loopholes)
public SomeClass extends LookupListener
{
//It is important that you hold a reference to Lookup.Result
//so that it doesn't get garbage collected. This also applies to Lookup.Template
private Lookup.Result result = lookup.getDefault().lookupResult(MyInterface.class);

public SomeClass()
{
result.addLookupListener(this);

//It is important to call this method once...otherwise
//resultChanged(...) method is never triggered!!
resultchanged(new LookupEvent(result));
}

public void resultChanged(LookupEvent ev)
{
//do your stuff here...
}
}
If you still have problems, then check the META-INF/services folder of your implementation, there is probably a typo in the flat file. Its better to use @Service annotation to avoid such mistakes.

Plugin manager for standalone swing apps

Lookup API provides more features than the typical ServiceLoader mechanism introduced in JDK 6. It allows you to listen to changes using LookupListener. If your not aware of Lookup API, please read about it here before continuing any further. For a more comprehensive tutorial on the subject, check out this screencast

Lookup API provides amazing decoupling capabilities to your application, even in standalone and non visual applications. The problem comes when you have to install or remove modules from your applications (implementations of an interface). In Netbeans platform the plugin manager would automatically do this for you. To utilize the benefits of LookupListener, one has to add the module jar files to the classpath (at run time).

This however cannot be achieved directly, here's a reflection hack to get it done:
/**
* Rescans the given folder and adds all the Jar files (plugins)
* to class path...simply ignores if a jar file is already added...
*
* @param path The folder containing plugins...
* @throws java.io.IOException
*/
public void rescan(String path) throws IOException
{
File pluginFolder = new File(path);
File plugins[] = pluginFolder.listFiles(new FileFilter()
{
public boolean accept(File pathname)
{
if(pathname.getPath().endsWith(".jar"))
return true;
else
return false;
}
});

for(File f : plugins)
{
addPlugin(f.toURI().toURL());
}
}

/**
* The url (preferably jar) to be added to the classpath.
* This is like an install plugin thingy...
* Must be used in place of {@link #rescan(java.lang.String) rescan} method
* if a single new plugin is to be installed...gives good performance ups
*
* @param url The url to be added to classpath
*/
public void addPlugin(URL url) throws IOException
{
addURLToClassPath(url);
}

/**
* To avoid un-necessary object creation on method calls...
*/
private static final Class[] parameters = new Class[]{URL.class};
/**
* Adds a URL, preferably a JAR file to classpath. If URL already exists,
* then this method simply returns...
*
* @param u The URL t be added to classpath
* @throws java.io.IOException
*/
private void addURLToClassPath(URL u) throws IOException
{
URLClassLoader sysloader = URLClassLoader)ClassLoader.getSystemClassLoader();

boolean isAdded = false;
for(URL url : sysloader.getURLs())
{
if(url.equals(u))
isAdded = true;
}
if(isAdded)
return;

Class sysclass = URLClassLoader.class;
try
{
Method method = sysclass.getDeclaredMethod("addURL",parameters);
method.setAccessible(true);
method.invoke(sysloader, new Object[]{ u });
}
catch (Throwable t)
{
t.printStackTrace();
throw new IOException("Error, could not add URL to system classloader");
}
}
In the above code we are adding a URL (typically pointing to a jar file) to the system classloader by invoking its private method via reflection.

In your plugin manager...all you have to do is paste the jar file to a certain folder (say user.dir/plugins), then execute the following code to add jars to classpath:

/**
* Rescans the given folder and adds all the Jar files (plugins)
* to class path...simply ignores if a jar file is already added...
*
* @param path The folder containing plugins...
* @throws java.io.IOException
*/
public void rescan(String path) throws IOException
{
File pluginFolder = new File(path);
File plugins[] = pluginFolder.listFiles(new FileFilter()
{
public boolean accept(File pathname)
{
if(pathname.getPath().endsWith(".jar"))
return true;
else
return false;
}
});

for(File f : plugins)
{
addPlugin(f.toURI().toURL());
}
}

/**
* The url (preferably jar) to be added to the classpath.
* This is like an install plugin thingy...
* Must be used in place of {@link #rescan(java.lang.String) rescan} method
* if a single new plugin is to be installed...gives good performance ups
*
* @param url The url to be added to classpath
*/
public void addPlugin(URL url) throws IOException
{
addURLToClassPath(url);
}
That's it! the newly registered service providers can be caught in resultChanged(...) method of the LookupListener. Similarly you can remove items from the classpath to deactivate the plugins from your application, i'll leave that as your home work assignment :)

Wednesday, June 10, 2009

lookup third party service impl of an interface

If you have a jar file containing implementations of an interface that you want to be discovered by lookup...here's what you do:

1) Use library wrapper wizard in Netbeans to create a jar module wrapper.
2) Create a folder META-INF/services in the wrapper module.
3) Create a file in META-INF/services named after the fully qualified name of the interface containing the fully qualified names of the implementations (one per line)

That's it!
Third party service implementations to now be discovered by the global lookup on startup.

Saturday, June 6, 2009

Unnecessary object creation...

Most of you might already know about this. I just found this out while working on my open source project JNeuralNet.

I had this situation:


loop
{
Double d = someclass.compute();
}
When i ran the profiler. I noticed that the major portion of CPU was going into Double object creation. That's when i realized that its the classloader overload everytime the object is being created..so this is what i did:

//init variable...
Double d = 0.0;
loop
{
d = someclass.compute();
}
This simple optimization reduced a lot of CPU overload! Also if u have situations such as:

loop
{
Obj o = new Obj();
}
If feasible...try using:

Obj o = new Obj();
loop
{
//use o...
o.set(abc);
}
This approach is not always feasible...especially if you intend to use the reference of the object elsewhere, my point is, to reduce object creation wherever feasible.

Wednesday, May 27, 2009

My ideal desktop recipe

Don't know about others, but i sure am confused by the vast ocean of frameworks and libraries available out there to help aid in java desktop applications.

This blog is not about frameworks and libraries that offer the best functionality and power, but those that do with a faster learning curve.

Typically, these are the pain points you'll encounter (sooner or later) in a large desktop application.

  • Validation
  • Binding Pojo's with GUI
  • Database Management
  • Cool and sleek GUI
  • Code complexity
  • Packaging and deployment
  • Creating Trialware's

1) Validation

I never paid much attention initially, but validation is one aspect that tends to get laborious. There are popular validation frameworks out there to help you with it. But as a beginner you'll want to learn it quick and easy. I'd prefer the Simple Validation Api by Tim Boudreau. Powerful and simple at the same time. Hardly takes 10 minutes to learn.


2) Binding POJO's with GUI

In my opinion there is no good tool for data binding, its currently unstable and there's no out of the box support for it. Its usually more pain than gain. But if u insist i suggest that you use the Netbeans IDE, it features mattise GUI builder with binding support. It'd be nice if JComponent binds POJO via annotations. In either case be on a look out, some one is probably developing it right now.


3) Database Management

Wouldn't it be nice if you didnt have to write all the plumbing code required to execute a database transaction and just concentrate on the task itself? ORM's typically sheild you from all the database junk. Hibernate will probably be the first result if u ever tried to google. It however has a lot of XML mapping stuff to be done.

In my opinion, ActiveObjects orm by Daniel Spiewak is the easiest to use, i.e., in case u dont have distributed databases to deal with. It conpletely sheilds you from database complexity. The only disadvantage is that u need to create POJO interfaces first to generate the database schema . If you already have a database then you must create the interfaces yourself (no generator tool for now). A great feature worth noting is that it has Database Migrations (useful for maintenance).


4) Cool and sleek GUI

Get substance look and feel by Kirill Grouchnikov is an excellent option to spice up you UI. All you have to do is add one line of code. If you're on MAC OS consider Quaqua lnf. Also check out SwingX, Flamingo, L2fProd, JGoodies for cool swing components.

If you have time to spare and want some extreme GUI with cool animation effects consider using Animated Transitions Api and Timing Framework by Romain Guy and Chet Haase. I also suggest that you read Filthy Rich clients by the same authors.

For a quickie, with almost no learning curve u should use substance look and feel with SwingX components along with mattise in NetbeansIDE.


5) Code Complexity

Be it a small or a large project, a GUI application soon gets out of the hand or you'll find yourself handling messy code or writing lots of plumbing code instead of putting effort into the business logic of the application. There's no point in reinventing the wheel, its always better to reuse a well tested framework instead of making one on your own.

For a small scale application its better to use to use your own MVC pattern to separate model, view and control. Major concerns in such application would be to maintain configuration. You'll probably use bean property change listeners...in this case consider using AbstractSerializableBean from swingX project to reduce the amount of boilerplate code for firing property change. It your application still gets out of hand consider using JIDE Application framework...havent really tried it, but looks good and has a moderate learning curve (2-3 days)

For a large application it is best of you use Netbeans Platform, its pretty complex and has a high learning curve, i would'nt recommend it unless you want to reuse netbeans features such as pallete, property sheets and editors etc...but on the bottom line its got great support and excellent documentation. Since its developed by sun, you can expect great support. Moreover NetbeansIDE has lots of code completion features for leveraging a netbeans platform based application.

If you have at least made 5-6 desktop applications and have good knowledge of OOPS, especially the use of interfaces and abstract classes (read this post for information on abstract classes) then you must consider using the Netbeans platform. Start by viewing these excellent screencasts.


6) Packaging and deployment

Consider an application based on java comm api. In such an app, you cant ask your client to copy and paste dll's at different locations, this should instead be done automatically at the deployment time, typically by distributing a setup file. To encash the benefits of cross platform nature of your java code, you'll need to use a cross platform deployer. Again, there are many of them, the easiest one to use and learn is by using PackJacket, a GUI frontend to the IzPack project. It also lets you create runtime scripts to execute custom tasks. whats more, the project is open sourced and is free to use.


7) Creating Trialwares

Depending on your marketing strategy, you might want to create trialware applications that expire after a certain time period.I recommend using TrueLicense library. Will take 1 day to get a hang of it.


Hope the above collection of tools and libs help you be more productive... Please let me know if you find better and easier tools.

Wednesday, October 29, 2008

Understanding frameworks by example...2


Step 3: Check your code so far, revise and optimize


All might seem rosy at the moment but when you try out this code…you’ll notice that

1) Frame rates vary widely, some systems show FPS of up to 150 and some about 30
To ensure frame-rate consistency we’ll add ensureMinFPS() and ensureMaxFPS() functions. This can be done by skipping calls too render() function, also known as frame skipping.

That means we update status like 3 times but only draw it once onto the screen. The result is that the sprite may seem to be moving with large steps and may damage smoothness. But that’s the PC's problem nothing to do with us. Also we could add a convenience method getCurrentFPS(), just to check the performance.

2) For animating a moving object like a man, we’ll have to cycle through a set of images…
This requires some handling which is again redundant. So we’ll add AnimatedSprite class. This class may contain methods such as addFrame(Image img, long persistenceTime);

We’ll extend this class with Renderable.class so that its update and render methods can be utilized by the Game.class when registered with it.
@Override
public void update(long time)
{
Image curFrame = frames.get(curFrameIndex);
animTime += elapsedTime;

if(animTime >= curFrameduration)
{
curFrameIndex++;

//provides roll-over for animTime accurately...
animTime = animTime % curFrame.duration;

if(curFrameIndex == frames.size())
curFrameIndex = 0;
}
}
But sprites can move to...So we could use xSpeed, ySpeed and update them using:
xPos += xSpeed * (elapsedTime);
yPos += ySpeed * (elapsedTime);
this xPos and yPos could be utilized in render()
drawImage(getCurFrame() ,xPos,yPos);

Now re-run your code again. This time when you add sufficient renderable objects to your game, you’ll notice Overlapping.

i.e., the object added first is drawn first…
how will it seem if the graphics of a tree is being drawn after drawing man??


Forgive me for my crappy drawing…that’s the best I can come up with!
The problem occurs because in run() method of Game.class, we use:
for(int i=0 to numRenderable)
{
arrRenderable.get(i).update(curTime - prevTime);
arrRenderable.get(i).render();
}
avoid this we could modify addRenderableObject as
//image with smallest index is drawn 1st…
addRenderableObject (Renderable rend, int index)
{
arrRenderable.add(rend, index);
}
Now that the drawing order can be determined, overlapping won’t be a problem.

So far we have managed:
- Screen management, ensure min frame rate, a generic Renderable class that can be used with Game class followed by easier Animation handling.

Now imagine that you’re coding the game using THIS framework, suppose the game works on 500 images…you probably will have to load all the images @ startup and show a progress bar like loading or something…Now we’ll integrate this feature into this framework

Lets design a class called ResourceBox, that holds all the images.
public abstract class ResourceBox
{
Private HashMap hm = new HashMap();

//this is where you’ll load all the images…or ne other stuff
Public abstract void init();

Public void add(String id, Image img)
{
hm.put(id, img);
}

//methods such as remove, replace and so on…
//Include a method getImage(String Id)
}
We first create a ResourceBox object as:
ResourceBox rb = new ResourceBox()
{
@Override
Public void init()
{
//Load whatever resources you want…
//Ex – add(“man”, imgMan);
}
}
Remember the Game class…?
How do we register this object with the game class??
Game(ResourceBox rb)
{
//Copy this ref into a private variable within game class
}
This is how the game would run previously:
run()
{
Init();
Game loop
{

}
}
Here we plug in a bit of code:
run()
{
Init();
If(rb != null)
rb.init();
Game loop
{

}
}
Also we’ll add a utility method to game class as:
public ResourceBox getResourceBox();
This method is needed as we could use:
Image man = gameObj.getResourceBox().get(“man”);
Cool eh?

What about the progress bar??
We can’t provide an implementation as it would restrict the user from customizing/ making his own style of progress bar. More-over the user defined Loading screen or whatever must be shown when rb.init() method is called.

We’re gonna try some sort of an event listener kinda thingy. Here goes:

Include a method in ResourceBox.class
public void registerListener(Listener l);

//This is how Listener’s defined
Public class Listener
{
Public abstract void onInit(Graphics g);
}
First of all user’s gotta create an obj of Listener class for which you HAVE TO override the onInit() method
Listener l = new Listener()
{
@Override
Public void onInit(Graphics g)
{
//Draw your stuff on this graphics context…
//Ex = ((Graphics2D)g).do any thing();
}
}
Now we’ll also include a method getRegisteredListener() in ResourceBox.class
We now modify the game class run method as follows:
run()
{
Init();
if(rb != null)
{
Listener l = rb.getRegisteredListener();
If(l != null)
{
// Assuming we have some hypothetical screen management class
Graphics g = ScreenManager.getGraphics();
l.onInit(g);
}
rb.init();
g.dispose();// or clear…
}

Game loop
{

}
}
Now user can show a progress bar or…loading screen with his/her own graphics style…
So here’s a short summary,

- Abstract methods and stuff is absolutely integral in designing a good framework
(Primarily to give user the control of things, just as swing lets us control the shape of a button)

- You might need event listeners in case where your internal handling code needs to call something…like the onInit() we just discussed (swing provides action listeners etc…to a button which are automatically called on mouse click on that component, hope you can associate this with the onInit())

- Let your imagination run wild…experiment, try, you’ll eventually be able to write the top notch code. Okay, enough philosophy I suppose lets move further.

Go back to step 2:

The best way to add new feature(s) to your framework is like I said can be done by imagining the usage. So let’s start with some analysis...how do we integrate sounds? After all any game would suck without sounds…

In my next blog I’ll put up a nice UML diagram of the concepts so far and also discuss sound integration. As always, do comment and help me improve my posts.

Thursday, September 25, 2008

Understanding Frameworks by example...1

You all must have heard about it, .Net, Swing etc.
So what exactly is this ‘framework’?

Simply put, it is a set of properly organized classes and packages with many features to offer.
In case you want to make one, proper planning and design is a must.

lets take the well known ‘swing ‘ in java
To create a frame all we gotta do is:

new JFrame().setVisible();
If I remember correctly, using windows.h in c++ we need to write a 100+ lines of code just to do that. Creating a simple frame involves registering the handleInstance and some other init steps. Moreover its just a simple frame. It we wanted to add a label to it, it’d take another 20-40 lines to do that. In swing its as simple as:
frame.add(new JLabel());
In a sense most of the code is redundant (no one remembers all that init code, they just copy, paste it and modify it at a few places). That’s where a framework is needed. To avoid redundant stuff and provide several layers of abstraction over the inner mess that’s going on.

Also swing manages repaints very cleverly, suppose we have a frame with blue background and a label with green background. Then the background is to be drawn first onto the screen followed by drawing the label. What’s more, it provides a lot of customization which could be achieved by over-ridding a few key methods.

For example to make the button round all you gotta do is over-ride the necessary shaping method that swing calls internally to display a button.

Now if you’re up to it lets try to design a 2D game framework.

Step 1: Identify the requirements


So what could we do to simplify 2D game designing??
Here’s a few that I figured

1) Screen management (change resolution, manage double buffering etc…)
2) Input management (Keyboard polling and mapping)
3) Animations Management (sprite handling)
4) Sound management (sound effect and stuff)

There are many more to it but I’d like to keep it simple

Step 2: Imagine the usage

For a moment let us assume that the framework is designed.
Then how would it help simplifying game programming??

First we’ll discuss a few basics of game programming
This is typically called ‘The game loop’
loop
{
//Update status of the game objects
//Render graphics onto the screen(typically by using double buffering)

//Provide a certain delay…so that the game doesn’t seem to be
//Running like a cheetah
}
As most of you might have already faced, this poses a severe problem...the delay is the villain here. The game runs at different speeds on different processors because of variable instruction execution speed but a fixed delay. To prevent this, we synchronize the events to a global Timer
prevTime = getTimeInNanos();
loop
{
curTime = getTimeInNanos();
//Update status of the game objects using (curTime – prevTime)
//Render graphics onto the screen
prevTime = curTime;
}
getTimeInNanos() returns an arbitrary timer, it can be the bios timer ticks or OS dependent timer. In JAVA one could use System.nanoTime()

And what about pausing and resuming the game??
The threads sleep and notify needs to be handled within the loop itself

Also we should provide a way to handle screen resolution change…
Also to avoid flickering double buffering must be done
Most of this is almost a necessity to be handled and furthermore this stuff is redundant
So we could add all these features into a class, lets call it Game
public abstract class Game extends Thread
{
Public abstract void init();
public void startGame();
public void stopGame();
public void pauseGame();
public void resumeGame();
public void setScreenRes(int width, int height) throws NotSupportedResException
}
init method is supplied as abstract so that user may customize it to his needs. All the Renderable objects (sprites as a few call it) have the update() and render() associated with it. So why not make a class called Renderable as:
public abstract class Renderable
{
//update status calculations here…parameter time is the num of seconds elapsed since
//last call
Public void abstract update(long time);

//all the graphics are to be drawn onto this graphics object…
public void abstract render(Graphics g);
}
Using abstract methods one of the most commonly used techniques in JAVA.
With this you tell the user to over-ride these methods in order to be used…
(Instead of telling them to create a class which HAS TO contain update(long) and render() functions, which would in turn be used for internal purposes)

Then we could do:
game.addRenderableObject(rendObj);
and in the Game class we could use:
private Arraylist arrRenderable;
addRenderableObject(Renderable rend)
{
arrRenderable.add(rend);
}
the run() in Game can be coded to handle thread start,stop,resume,pause and automatically calls all the registered Renderable objects update and render methods…
this is what how run() would look like:
public void run()
{
init();
prevTime = getTimeMillis();

while(!isStopped)
{
curTime = getTimeMillis() - pausedTime;
pausedTime = 0;

for(int i=0 to numItemsRegistered)
{
arrRenderable.get(i).update(curTime - prevTime);
arrRenderable.get(i).render();
}

if(isPaused)
{
pausedTime = getTimeMillis();
while(isPaused)
{
Graphics g = screen.getGraphics();
screen.drawFrameContents(g);
g.dispose();
scr.updateGraphics();
}
pausedTime = getTimeMillis() - pausedTime;
}
prevTime = curTime;
}
}

public void pauseGame()
{
isPaused = true;
}

public void stopGame()
{
isStopped = true;
}
Hope you got the whole picture here…
I suppose that’s enough stuff for now, I’ll add more in my next post. Do comment…