Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

j2me simple game -out of memory error

Posted on 2005-05-10
5
Medium Priority
?
2,104 Views
Last Modified: 2013-11-23
Starting to create a  game simular to frogger in j2me  basically it can be slow at times and eventually i get out of memory error.

obviously the game is unfinished but will welcome any design hints etc :)

but want to solve the out of memory error though

sorry about the lots of code.....


****************Trafficmidlet code
import java.io.IOException;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public class TrafficMIDlet
    extends MIDlet
    implements CommandListener {
  private TrafficCanvas mTrafficCanvas;

  public void startApp() {
    if (mTrafficCanvas == null) {
      try {
        mTrafficCanvas = new TrafficCanvas();
        mTrafficCanvas.start();
        Command exitCommand = new Command("Exit", Command.EXIT, 0);
        mTrafficCanvas.addCommand(exitCommand);
        mTrafficCanvas.setCommandListener(this);
      }//end try
      catch (IOException ioe) {
        System.out.println(ioe);
      }//end catch
    }//end if

    Display.getDisplay(this).setCurrent(mTrafficCanvas);
  }//end startapp

  public void pauseApp() {}

  public void destroyApp(boolean unconditional) {
    if (mTrafficCanvas != null)
      mTrafficCanvas.stop();
  }

  public void commandAction(Command c, Displayable s) {
    if (c.getCommandType() == Command.EXIT) {
      destroyApp(true);
      notifyDestroyed();
    }
  }
}


*******************TrafficCanvas


import java.io.IOException;

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;

public class TrafficCanvas
    extends GameCanvas
    implements Runnable {

 int myInitialGameTicks = 950;
  private volatile boolean mTrucking;
  int lastLeftcar;
    private frog mfrog;
  private TiledLayer mRoad;
  private LayerManager mLayerManager;
 car[] myLeftcars;
  public TrafficCanvas() throws IOException {
    super(true);
     mfrog=createFrog();

    mRoad = createRoad();

    mLayerManager = new LayerManager();
           mLayerManager.append(mfrog);
      mLayerManager.append(mRoad);

  }

 private frog createFrog() throws IOException {
    Image image = Image.createImage("/tank.png");
    return new frog(image, 32, 32);
  }

 private car createcar() throws IOException {
    Image image = Image.createImage("/tank.png");
    return new car(image, 32, 32);
  }

  private TiledLayer createRoad() throws IOException {
    Image image = Image.createImage("/board.png");
    TiledLayer tiledLayer = new TiledLayer(10, 10, image, 16, 16);

    int[] map = {
       1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
      0 , 0,  0,  0,  0,  0,  0,  0,  0,  0,
       0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
       1,  1,  1,  1,  1,  1,  1,  1,  1,  1
    };

    for (int i = 0; i < map.length; i++) {
      int column = i % 10;
      int row = (i - column) / 10;
      tiledLayer.setCell(column, row, map[i]);
    }

    return tiledLayer;
  }

  public void start() {
    mTrucking = true;
    Thread t = new Thread(this);
    t.start();
  }

  public void run() {
    Graphics g = getGraphics();

    int timeStep = 80;

    while (mTrucking) {

      try {

      long start = System.currentTimeMillis();
            if(myLeftcars != null) {
                   System.out.println(myLeftcars.length);
                  for(int i = 0; i < myLeftcars.length; i++) {
                System.out.println(myLeftcars.length);
                 boolean dontbother =false;
              int ret =myLeftcars[i].advance(200,true,0,getWidth()-64,dontbother);
              if (ret==1)
              {
                    if (myLeftcars[lastLeftcar].collidesWith(myLeftcars[i], true)){
                    myLeftcars[i].setVisible(false);}
                    else {
                    lastLeftcar=i;
                    dontbother=true;//dont even bother creating a new car as it will collide
                             }//end else

                                 }//end if



        }//end for
             }//end if cars not null
      tick();
      input();
      render(g);

      long end = System.currentTimeMillis();
      int duration = (int)(end - start);

      debug(g, duration * 100 / timeStep);

      if (duration < timeStep) {
        try { Thread.sleep(timeStep - duration); }
        catch (InterruptedException ie) { stop(); }
      }
      }//end try
              catch(Exception e){
                    System.out.println("nootr");
                    System.out.println(myLeftcars.length);
                    e.getMessage();
                    e.getClass();
                                          }//end catch
    }//end while

  }//end run

  private void tick() {
        if(myLeftcars != null) {
         for(int i = 0; i < myLeftcars.length; i++) {
                            if (mfrog.collidesWith(myLeftcars[i], true))
                                   System.out.println("ohh my god i died");
                                  }//end for
                     }//end if
  }//end tick

  private void input() {
    int keyStates = getKeyStates();
    if ((keyStates & LEFT_PRESSED) != 0) mfrog.left();
    else if ((keyStates & RIGHT_PRESSED) != 0) mfrog.right();
     else if ((keyStates & UP_PRESSED) != 0) mfrog.up();
    else if ((keyStates & DOWN_PRESSED) != 0) mfrog.down();

  }

  private void render(Graphics g) {
    int w = getWidth();
    int h = getHeight();
    g.setColor(0xffffff);
    g.fillRect(0, 0, w, h);
    int x = (w - 160) / 2;
    int y = (h - 160) / 2;
System.out.println("x" + x + "y" +y);
    mLayerManager.paint(g, x, y);
    g.setColor(0x000000);
    g.drawRect(x, y, 160, 160);
//if the cars objects have not been created
if(myLeftcars == null) {
      myLeftcars = new car[10];
      for(int i = 0; i < myLeftcars.length; i++) {
              try{
              myLeftcars[i] = createcar();
        }
        catch(Exception e){
              System.out.println("noo render");
              System.out.println(i);
              System.out.println(myLeftcars.length);
              e.getMessage();
              e.getClass();

        }
      mLayerManager.append(myLeftcars[i]);
      }

}

    flushGraphics();
  }

  private void debug(Graphics g, int percent) {
    int w = getWidth();
    int h = getHeight();

    StringBuffer sb = new StringBuffer();
    sb.append(Integer.toString(percent));
    sb.append('%');
    String s = sb.toString();

    Font font = g.getFont();
    int sw = font.stringWidth(s) + 2;
    int sh = font.getHeight();

    // Draw the render capacity.
    g.setColor(0xffffff);
    g.fillRect(w - sw, h - sh, sw, sh);
    g.setColor(0x000000);
    g.drawRect(w - sw, h - sh, sw, sh);
    g.drawString("" + percent + "%", w, h,
        Graphics.RIGHT | Graphics.BOTTOM);

    flushGraphics();
  }

  public void stop() {
    mTrucking = false;
  }
}





**********************frog
t javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;

public class frog
    extends Sprite {
  private int mDirection;
  private int mKX, mKY;

  private int mLastDelta;
  private boolean mLastWasTurn;

 
  public frog(Image image, int frameWidth, int frameHeight) {
    super(image, frameWidth, frameHeight);
    defineReferencePixel(frameWidth / 2, frameHeight / 2);
    mKX=100;
    mKY=100;
    setPosition(100,100);
    mDirection = 0;
  }


  public void left(){
         mKX = Math.max(0, mKX - 10);
  setPosition(mKX , mKY );

}

 public void right(){
       mKX = Math.min(200, mKX + 10);
                setPosition(mKX , mKY );
}

 public void up(){
         mKY = Math.max(0, mKY - 10);
                  setPosition(mKX , mKY );

}

public void down(){
        mKY = Math.min(200, mKY + 10);
                 setPosition(mKX , mKY );
}


}//end frog



**************car
import java.util.Random;

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;


public class car extends Sprite {

  static int WIDTH = 16;
    int myY=100;
Random myRandom = new Random();
private int mDirection;
boolean myLeft;//what side it comes from

  public car(Image image, int frameWidth, int frameHeight) {
     super(image, frameWidth, frameHeight);
     defineReferencePixel(frameWidth / 2, frameHeight / 2);
      setPosition(0,myY);
     mDirection = 0;
  }

   int advance(int tickCount, boolean left,
            int currentLeftBound, int currentRightBound, boolean dontbother) {
    int retVal = 0;
   if((getRefPixelX() + WIDTH <= currentLeftBound) ||
         (getRefPixelX() + WIDTH*2 >= currentRightBound)) {
        setVisible(false);
    }

    if(!isVisible() && dontbother==false) {

            int rand = getRandomInt(100);
            if(rand == 3) {
            // when the car comes back into play,
            // we reset the values to what they should
            // be in the active state:

            setVisible(true);
            retVal=1;

            if(myLeft) {
              setRefPixelPosition(currentRightBound, myY);
              move(-1, 0);
                   } else {
              setRefPixelPosition(currentLeftBound, myY);
              move(1, 0);
            }
            }
          } else {

            if(left) {
                  move(3, 0);
                        }
      }

return(retVal);
}//end advance


   public int getRandomInt(int upper) {
          int retVal = myRandom.nextInt() % upper;
          if(retVal < 0) {
            retVal += upper;
          }
          return(retVal);
  }
  }//end car

thanks for your help

0
Comment
Question by:koksracing
  • 2
3 Comments
 
LVL 13

Expert Comment

by:petmagdy
ID: 13972112
well,

try to set the image variables to null so it is eligible to GC when closing the TrafficCanvas
0
 

Author Comment

by:koksracing
ID: 13974135
sorry could you explian in laymans terms?

Learning as i go here :)
0
 
LVL 13

Accepted Solution

by:
petmagdy earned 2000 total points
ID: 13977751
ok, the classes that has member fields of Type Image, make sure to make the instances of those classes are freed when the canvas closes, for example when the user closes the TrafficCanvas, call a method like this:

public void close() {
  memberFieldObjectThatHasImageAsMember = null;
}

this will make those objects elligable for garbage collection to be freed from memory.

U can apply this to whenever object that is a member field in a class and consumes memory, because member fields unlike local variables has a longer life time
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month20 days, 15 hours left to enroll

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question