Problem with casting

I’m getting a java.lang.ClassCastException while trying to cast game = (GameManager)a; where gamemanager is the applet class. I have no idea what’s wrong, please help.

public class UFO extends BitmapLoop implements Intersect {
byte state;
// UFO states
static final byte STANDBY = 0;
static final byte ATTACK = 1;
static final byte RETREAT = 2;
static final byte LAND = 3;
static final byte EXPLODE = 4;
// probability of state transitions
static final double STANDBY_EXIT = .95;
static final double ATTACK_EXIT = .95;
static final double RETREAT_EXIT = .95;
static final double LAND_EXIT = .95;
static final double FLIP_X = 0.9;
static final int RETREAT_Y = 33;
// bitmap animations
protected Image ufo[]; // ufo animation
protected Image attack[]; // attack animation
protected Image explode[]; // explosion sequence
// instance vars
int max_x, max_y; // max coords of this UFO
int explosion_counter; // counter for explosion
// bitmaps
UFOManager um;
// class vars
static Intersect target; // refers to the gun
static int gun_y; // the y-coord of gun
static GameManager game; // ptr to game manager
// constructor: initialize image references, instance vars
public UFO(Image ufoImages[],
Image attackImages[],
Image explodeImages[],
int max_x,int max_y,
UFOManager um,
Applet a) {
super(0,0,null,ufoImages,a);
this.max_x = max_x;
this.max_y = max_y;
currentImage = getRand(ufoImages.length);
ufo = ufoImages;
attack = attackImages;
explode = explodeImages;
game = (GameManager)a;
this.um = um;
startStandby();
}

public UFO(Image ufoImages[],
Image attackImages[],
Image explodeImages[],
int max_x,int max_y,
UFOManager um,
int uw,
int uh,
Applet a) {
super(0,0,null,ufoImages,uw,uh,a);
this.max_x = max_x;
this.max_y = max_y;
currentImage = getRand(ufoImages.length);
ufo = ufoImages;
attack = attackImages;
explode = explodeImages;
game = (GameManager)a;
this.um = um;
startStandby();
}

How looks the class definition of GamerManager (“a”)? Would be good to post that, too.

Ok, I’m posting the wole class so here it is enjoy:

public class GameManager extends Applet
implements Runnable {
// animation variables
static final int REFRESH_RATE = 80; // in ms
Thread animation;
Graphics offscreen;
Image image;
private int uw=10;
private int uh=10;
// game variables used when playing
static final int UFO_VALUE = 130; // 130 points
static final int MAX_LANDED = 5; // at most 5 aliens
// can land
static final int MAX_LEVEL = 9; //
static final int MAX_ENERGY = 113; //
private int score;
private int numLanded; // num of aliens landed
Image ufoImages[] = new Image[3]; // 6 ufo Images
Image attackImages[] = new Image[3]; // 6 attack Images
Image explodeImages[] = new Image[4];// 4 explode Images
Image gunImage; // gun image
GunManager gm; // refers to gun manager
UFOManager um; // refers to ufo manager
// state of game
private boolean playing; // if game playing
private int screen; // which screen to show
static final int INTRO = 0; // intro screen
static final int GAME_OVER = 1; // game over screen
AudioClip expsound; // explosion sound
// fonts
Font smallFont = new Font(“Helvetica”,Font.BOLD,12);
Font mediumFont = new Font(“Helvetica”,Font.BOLD,14);
Font bigFont = new Font(“Helvetica”,Font.BOLD,18);
FontMetrics fm; // use to center string
int width, height; // applet dimensions
// strings
String scoreString = "Score: ";
String ufoLandedString = "UFOs Landed: ";
String gameOverString = " GAME OVER ";
String clickString = “Shift-Click to Continue”;
String alienLandingString = “Alien Landing”;
int stringWidth;
String introString[] = new String[8];
public void init() {
showStatus(“Loading Images – WAIT!”);
setBackground(Color.black); // applet background
width = bounds().width; // set applet dimensions
height = bounds().height;
loadImages();
try {
expsound = getAudioClip(getCodeBase(),“Explosion.au”);
}
catch (Exception e) { }
um = new UFOManager(2,MAX_LEVEL,width,height,ufoImages,
attackImages,explodeImages,
uw,uh,
this,expsound);
gm = new GunManager(MAX_ENERGY,5,width,height,gunImage,
um.getUFO(),
this);
um.initialize(gm); // initialize gun parameters
playing = false; // not playing
screen = INTRO; // show intro screen
image = createImage(width,height); // make offscreen buffer
offscreen = image.getGraphics();
offscreen.setFont(bigFont); // font for intro
fm = offscreen.getFontMetrics(bigFont); // font metrics
stringWidth = fm.stringWidth(alienLandingString);
introString[0] = “You are Humanity’s last hope!”;
introString[1] = “Destroy the green Alien Landers”;
introString[2] = “by using the Mouse to Move”;
introString[3] = “your Missile Launcher. Click”;
introString[4] = “to Fire Missile. If 5 Aliens”;
introString[5] = “Land, or Energy Runs Out,”;
introString[6] = “Humans will be Eaten Alive!”;
introString[7] = “Click to start Game”;
}
// load all images used in game
public void loadImages() {
MediaTracker t = new MediaTracker(this);
gunImage = getImage(getCodeBase(),“image/gun.gif”);
t.addImage(gunImage,0);
for (int i=0; i<ufoImages.length; i++) {
ufoImages[i] = getImage(getCodeBase(),
“image/land” + i + “.gif”);
t.addImage(ufoImages[i],0);
}
for (int i=0; i<attackImages.length; i++) {
attackImages[i] = getImage(getCodeBase(),
“image/attack” + i + “.gif”);
t.addImage(attackImages[i],0);
}
for (int i=0; i<explodeImages.length; i++) {
explodeImages[i] = getImage(getCodeBase(),
“image/explode” + i + “.gif”);
t.addImage(explodeImages[i],0);
}
// wait for all images to finish loading //
try {
t.waitForAll();
} catch (InterruptedException e) {
}
// check for errors //
if (t.isErrorAny()) {
showStatus(“Error Loading Images”);
}
else if (t.checkAll()) {
showStatus(“Images successfully loaded”);
}
}
// initialize params for new game
public void newGame() {
score = 0; // no score
numLanded = 0; // no aliens landed
gm.newGame(); // call newGame in
um.newGame(); // manager classes
offscreen.setFont(smallFont); // set font in game
}
// handle mouse events //
public boolean mouseMove(Event e,int x,int y) {
if (playing) {
gm.moveGun(x);
}
return true;
}
public boolean mouseDrag(Event e,int x,int y) {
if (playing) {
gm.moveGun(x);
}
return true;
}
public boolean mouseDown(Event e,int x,int y) {
if (playing) {
gm.fireMissile(x);
}
else if (screen == INTRO) { // start game for mouse
// down on intro screen
playing = true;
newGame();
}
else if (screen == GAME_OVER) { // else go back to intro
if (e.shiftDown()) { // if shift-click
screen = INTRO;
}
}
return true;
}
// start the Video Game Loop
public void start() {
showStatus(“Starting Game!”);
animation = new Thread(this);
if (animation != null) {
animation.start();
}
}
// update managers. only update gun if playing
public void updateManagers() {
if (playing) {
gm.update();
}
um.update();
}
// override update so it doesn’t erase screen
public void update(Graphics g) {
paint(g);
}
// paint the applet depending on mode of game
public void paint(Graphics g) {
if (playing) {
offscreen.setColor(Color.black);
offscreen.fillRect(0,0,width,height); // clear buffer
// draw status info
offscreen.setColor(Color.cyan);
offscreen.drawString(scoreString+score,width - 113,13);
offscreen.drawString(ufoLandedString+numLanded,
width - 113,27);
// tell UFOManager and GunManager to paint
um.paint(offscreen);
gm.paint(offscreen);
g.drawImage(image,0,0,this);
}
else if (screen == INTRO) {
offscreen.setColor(Color.black);
offscreen.fillRect(0,0,width,height); // clear buffer
offscreen.setFont(smallFont);
offscreen.setColor(Color.cyan);
offscreen.drawString(scoreString+score,width - 113,13);
offscreen.drawString(ufoLandedString+numLanded,
width - 113,27);
um.paint(offscreen);
offscreen.setFont(bigFont);
offscreen.setColor(Color.green);
offscreen.drawString(alienLandingString,
(width-stringWidth)/2,
height/6);
offscreen.setColor(Color.magenta);
offscreen.setFont(mediumFont);
// draw instructions
for (int i=0; i<introString.length-1; i++) {
offscreen.drawString(introString[i],13,(3+i)height/12);
}
offscreen.setColor(Color.green);
offscreen.drawString(introString[7],
(width-stringWidth)/2,
height
11/12);
g.drawImage(image,0,0,this);
}
else if (screen == GAME_OVER) {
offscreen.setColor(Color.black);
offscreen.fillRect(0,0,width,height); // clear buffer
// draw status info
offscreen.setFont(smallFont);
offscreen.setColor(Color.cyan);
offscreen.drawString(scoreString+score,width - 113,13);
offscreen.drawString(ufoLandedString+numLanded,
width - 113,27);
um.paint(offscreen);
gm.paint(offscreen);
offscreen.setFont(bigFont);
offscreen.setColor(Color.red);
offscreen.drawString(gameOverString,
(width-stringWidth)/2,
height/2);
offscreen.setFont(mediumFont);
offscreen.setColor(Color.green);
offscreen.drawString(clickString,
(width-stringWidth-17)/2,
height*11/12);
g.drawImage(image,0,0,this);
}
}
// the Video Game Loop
public void run() {
while (true) {
repaint();
updateManagers();
Thread.currentThread().yield();
try {
Thread.sleep (REFRESH_RATE);
} catch (Exception exc) { };
}
}
// stop animation
public void stop() {
showStatus(“Game Stopped”);
if (animation != null) {
animation.stop();
animation = null;
}
}
// increase score
public void incrementScore() {
score += UFO_VALUE;
}
// count number of ufo’s landed
public void alienLanded() {
numLanded++;
if (numLanded == MAX_LANDED) {
gameOver();
}
}
// handle game over
public void gameOver() {
if (playing) {
playing = false;
screen = GAME_OVER;
}
}
}

Still doesn’t show how a UFO is created!?

Ok

private UFO ufo[]; // array of ufos
int ufosKilled; // count ufos killed
int level; // the level
// (i.e. #ufos on screen)
int startLevel;
int maxLevel;
boolean playSound = false; // initially no sound
AudioClip expsound; // sound clip of explosion
// kill 13 ufos until next level
static final int KILL_FOR_NEXT_LEVEL = 13;
static int width, height; // applet dimensions
// constructor
public UFOManager(int startLevel,int maxLevel,int width,int height,
Image ufoImages[],
Image attackImages[],
Image explodeImages[],
Applet a, AudioClip exp) {
this.startLevel = startLevel;
this.maxLevel = maxLevel;
this.width = width;
this.height = height;
ufo = new UFO[maxLevel];
for (int i=0; i<ufo.length; i++) {
ufo[i] = new UFO(ufoImages,attackImages,explodeImages,
width,height,this,a);
}
expsound = exp;
newGame();
}

public UFOManager(int startLevel,int maxLevel,int width,int height,
Image ufoImages[],
Image attackImages[],
Image explodeImages[],
int uw,
int uh,
Applet a, AudioClip exp) {
this.startLevel = startLevel;
this.maxLevel = maxLevel;
this.width = width;
this.height = height;
ufo = new UFO[maxLevel];
for (int i=0; i<ufo.length; i++) {
ufo[i] = new UFO(ufoImages,attackImages,explodeImages,
width,height,this,uw,uh,a);
}
expsound = exp;
newGame();
}

From the code so far (which I think sucks both in design and style) I cannot see where the problem might be. Looks okay.

Just place a breakpoint on the line in question and see what you actually get!

Most of the code is from Black book of java game programming so I know the code is a bit outdated, but I’m new game programming and that book is still one of the best that’s available.

Anyway by removing the casting the game runs, but the reason gamemanager was sent to the ufo class was because, that when an ufo is hit it could call updatescore() from the gamemanager class.

Now because casting gamemanager doesn’t work for no apparent reason, I need a way of working around the problem, any suggestions?

Hey, don’t give up that easily!! This code HAS to work! Must be one stupid detail somewhere. What does the debugger tell you?

Hi,

I’d suggest you change the line:

public UFO(Image ufoImages[], Image attackImages[], Image explodeImages[], int max_x,int max_y, UFOManager um, Applet a)

Change the “Applet a” into “Gamemanager a” and eliminate the cast.

If the UFO class is specific to your applet, you don’t need it to handle any applet.

have fun

It actually says process complete, but when I run it it says:
java.lang.ClassCastException
at aliengame.UFO.(UFO.java:52)
at aliengame.UFOManager.(UFOManager
at GameManager.init(GameManager.java:72)
at sun.applet.AppletPanel.run(AppletPanel
at java.lang.Thread.run(Thread.java:536)

I know this probably doesn’t tell you alot since you can’t look at what’s on line 52 and etc, but maybe I can mail it to you and you can look at the whole code?

To Petr_Stedry
The applet a is used lower in the hiarchy(sp?) in a bitmap loop class to get the width and height of the bitmap, so that wouldn’t work. (It was the first thing I tried)

[quote]To Petr_Stedry
The applet a is used lower in the hiarchy(sp?) in a bitmap loop class to get the width and height of the bitmap, so that wouldn’t work. (It was the first thing I tried)
[/quote]
???

GameManager IS_A Applet. So this cannot make any difficulties!

Well,

  1. I know, that it is a subclass, but where is the point creating a class (UFO) specifically for the purpose of being handled by a GameManager, that needs to cast a parameter to a GameManager, that will every time be a GameManager.

  2. If you use the workaround I suggested, the “error” will move somewhere else, where it can (hopefully) be easily identifed and removed.

The error that occured then is:

java.lang.NoSuchMethodError: aliengame.UFOManager.(IIII[Ljava/awt/Image;[L
java/awt/Image;[Ljava/awt/Image;Ljava/applet/Applet;Ljava/applet/AudioClip;)V
at GameManager.init(GameManager.java:72)

Which is weird to say the least since line 72 is:
expsound = getAudioClip(getCodeBase(),“Explosion.wav”);

NoSuchMethodError - recompile!!

What IDE do you use???

It is compiled with the new modifications, so thats not the problem. I’m currently usin jcreator 2.50 LE, but i can’t understand that it has a problem in loading basic audio, espesialy since I’ve done it before.