Space Invaders.
Hi, could you please try my game Space Invaders, to see if you can find any bugs etc? Let me know...
http://www.geocities.com/ajbasic/SpaceInvaders.html
the ability to die should definitely be the last thing you code ;) It's so cool to play an early staged game without ever being able to die.
OK, so my comments:
The pictures, if you're going to allow them to overlap, as you do now, give them some transparency.
Also, right now, the ships will go all the way to the bottom and through the bottom of the screen.... that's bad.
Anything else I'd think would be immediately obvious. Keep going with it and I hope to see some origional twists that you come up with
Similar Messages
-
How do i remove an Object (aliens/ bullets) from my Space Invaders game??
Creating Space Invaders game and im getting confused on removing objects from my game. How do you actually remove an object (i.e bullets and aliens).
I know this isnt the right way to do it, but for the bullets i had an array of the Objects bullets[] and set the x and y coordinates off screen so u cant see then wen they are painted you cant see them, then wen the player fires them, the x and y coordinates change so they come from the players ship till it hits an alien or goes off screen, then i reset the coordinates so they are pasted off screen again. Im relatively new to this so i would appreciate any help. Im going to have to do the same with aliens wen a collision is detected. Is there a way of actually removing an object?
Here is sum code incase you need to see it:
public void checkCollision()
Rectangle playerRec = new Rectangle(player1.getBoundingBox());
for(int i=0; i<alienRow; i++)
for(int j=0; j<alienCol; j++){
if(playerRec.intersects(aliens[i][j].getBoundingBox()))
collisionDetected();
for(int k=0; k<bulletNum; k++){
Rectangle bulletRec = new Rectangle(bullets[k].getBoundingBox());
if(bulletRec.intersects(aliens[i][j].getBoundingBox()))
removeBullet(bullets[k]);
collisionDetected();
public static void collisionDetected()
System.out.println("COLLISION");
private void removeBullet(Bullets bullet){
bullet.fired=false;
bullet.setX(-10);
bullet.setY(-10);
}Edited by: deathwings on Nov 25, 2009 8:20 AMdeathwings wrote:
I was thinking bout that arraylist angle before, but it makes sense now so i think that will work ok. Thx kevin.Not a problem.
Taking the List idea one step further, you could have a parent Object/Interface that all of your game objects extend/implement. Let's call it GameObject.
A GameObject would have a draw(Graphics g) function that you call from your paintComponent( ) method, and for example an act( ) function as well.
You'd have a single List of GameObjects that you add everything in your game into. Now painting is simply a matter of looping over a single List. And in your game logic loop, you could do a similar thing with the act( ) function: your bullet's act( ) would simply move it forward and check for collisions and going off screen. An alien's act( ) function would move it around and maybe shoot a weapon every so often.
Just an idea. -
Need Help with Java Space Invaders Game!
Hi, im new to these forums so forgive if i dont follow the right way on laying things out. Im trying to create space invaders game but im stuck when im trying to create multiple aliens/ invaders. I have a class called Aliens (which is the invaders), and i can create an instance of an Alien. But when I try to create multiple instances they are not showing up on screen. I am not getting any error message though (which im hoping is a good sign, lol).
GamePanel is where all the action is and Alien is the alien (invaders) class.
Here is the code:
import java.awt.; import javax.swing.; import java.awt.Image; import java.awt.event.KeyListener; import java.awt.event.KeyEvent;
public class GamePanel extends JComponent implements KeyListener { SpaceInvaders game; static Player player1; Aliens alien1; static public Image spaceship2R; static public Image spaceship2L;
public GamePanel(SpaceInvaders game)
this.game = game;
player1 = new Player(this);
player1.start();
///// trying to create multiple instances of aliens here
for(int i=0; i<4; i++)
alien1 = new Aliens(this);
alien1.setX(i*100);
alien1.start();
this.setFocusable(true);
this.addKeyListener(this);
public void paintComponent(Graphics g)
Image pic1 = player1.getImage();
Image pic2 = alien1.getImage();
super.paintComponent(g);
g.drawImage(pic1, player1.getX(), player1.getY(), 50, 50,this);
g.drawImage(pic2, alien1.getX(), alien1.getY(), 50, 50,this);
}//end class
import java.awt.Image; import java.awt.*;
class Aliens extends Thread { //variables GamePanel parent; private boolean isRunning; private int xPos = 0, yPos = 0; Thread thread; static char direction = 'r'; Aliens alien; static public Image alien1; static public Image alien2;
public Aliens(GamePanel parent)
this.parent = parent;
isRunning = true;
public void run()
while(isRunning)
Toolkit kit = Toolkit.getDefaultToolkit();
alien1 = kit.getImage("alien1.gif");
alien2 = kit.getImage("alien2.gif");
try
thread.sleep(100);
catch(InterruptedException e)
System.err.println(e);
updateAliens();
parent.repaint();
public static Image getImage()
Image alienImage = alien1;
switch(direction){
case('l'):
alienImage = alien1;
break;
case('r'):
alienImage = alien1;
break;
return alienImage;
public void updateAliens()
if(direction=='r')
xPos+=20;
if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
yPos+=50;
xPos-=20;
direction='l';
else
xPos-=20;
if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
yPos+=50;
xPos+=20;
direction='r';
public void setDirection(char c){ direction = c; }
public void setX(int x){ xPos = x; }
public void setY(int y){ yPos = y; }
public int getX(){ return xPos; }
public int getY(){ return yPos; }
}//end classEdited by: deathwings on Oct 19, 2009 9:47 AM
Edited by: deathwings on Oct 19, 2009 9:53 AMMaybe the array I have created is not being used in the paint method, or Im working with 2 different objects as you put it? Sorry, Im just learning and I appreciate your time and help. Here is my GamePanel Class and my Aliens class:
import java.awt.*;
import javax.swing.*;
import java.awt.Image;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
public class GamePanel extends JComponent implements KeyListener
SpaceInvaders game;
static Player player1;
static Bullets bullet;
//static public Image spaceship2R;
//static public Image spaceship2L;
private BufferStrategy strategy;
static int alienNum =0;
static Aliens[] aliens;
public GamePanel(SpaceInvaders game)
this.game = game;
player1 = new Player(this);
player1.start();
Aliens[] aliens = new Aliens[10];
for(int i=0; i<4; i++)
aliens[i] = new Aliens(this);
aliens.setX(i*100);
aliens[i].start();
alienNum++;
initialiseGame();
this.setFocusable(true);
this.addKeyListener(this);
public void paintComponent(Graphics g)
Image pic1 = player1.getImage();
Image pic2 = aliens[0].getImage();
Image bulletPic = bullet.getImage();
super.paintComponent(g);
g.drawImage(pic1, player1.getX(), player1.getY(), 50, 50,this);
for ( int i = 0; i < alienNum; i++ )
g.drawImage(pic1, aliens[0].getX(), aliens[0].getY(), 50, 50,this);
//if (bullet.fired==true){
// g.drawImage(bulletPic, bullet.getX(), bullet.getY(), 20, 20,this);
public void keyPressed(KeyEvent k)
switch (k.getKeyCode()) {
case (KeyEvent.VK_KP_DOWN):
case (KeyEvent.VK_DOWN):
player1.setDirection('d');
break;
case (KeyEvent.VK_KP_UP):
case (KeyEvent.VK_UP):
player1.setDirection('u');
break;
case (KeyEvent.VK_KP_RIGHT):
case (KeyEvent.VK_RIGHT):
player1.setDirection('r');
break;
case (KeyEvent.VK_KP_LEFT):
case (KeyEvent.VK_LEFT):
player1.setDirection('l');
break;
case (KeyEvent.VK_SPACE):
fireBullet();
break;
public void keyTyped(KeyEvent k) {}//empty
public void keyReleased(KeyEvent k)
player1.setDirection('n');
public void initialiseGame()
public static void checkCollision()
Rectangle playerRec = new Rectangle(player1.getBoundingBox());
for(int i=0; i<alienNum; i++)
//if(playerRec.intersects(aliens[i].getBoundingBox()))
//collisionDetected();
public static void collisionDetected()
System.out.println("COLLISION");
public void fireBullet()
Bullets bullet = new Bullets(player1.getX(),player1.getY());
bullet.fired=true;
}//end GamePanelimport java.awt.Image;
import java.awt.*;
class Aliens extends Thread
//variables
GamePanel parent;
private boolean isRunning;
private int xPos = 0, yPos = 0;
Thread thread;
static char direction = 'r';
Aliens alien;
static public Image alien1;
static public Image alien2;
public Aliens(GamePanel parent)
this.parent = parent;
isRunning = true;
public void run()
while(isRunning)
Toolkit kit = Toolkit.getDefaultToolkit();
alien1 = kit.getImage("alien1.gif");
//alien2 = kit.getImage("alien2.gif");
try
thread.sleep(100);
catch(InterruptedException e)
System.err.println(e);
updateAliens();
parent.repaint();
public static Image getImage()
Image alienImage = alien1;
switch(direction){
case('l'):
alienImage = alien1;
break;
case('r'):
alienImage = alien1;
break;
return alienImage;
public void updateAliens()
if(direction=='r')
xPos+=20;
if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
yPos+=50;
xPos-=20;
direction='l';
else
xPos-=20;
if(xPos >= SpaceInvaders.WIDTH-50||xPos < 0)
yPos+=50;
xPos+=20;
direction='r';
public Rectangle getBoundingBox()
return new Rectangle((int)xPos, (int)yPos, 50, 50);
public void setDirection(char c){ direction = c; }
public void setX(int x){ xPos = x; }
public void setY(int y){ yPos = y; }
public int getX(){ return xPos; }
public int getY(){ return yPos; }
}//end class -
Controlling fire in Space Invaders game
Hi again,
still working through the tutorial on Space Invaders in Flash
MX 2004 (bit out of date, I know).
I've got the player craft under mouse control. What I don't
like about the game is that you can fire as rapidly as you wan't,
though the number of bullets is limited. You can change this limit
in the variable - I would rather have it though that you can only
have a set number of bullets in play at a time (at the moment, if
you go over the limit, the uppermost bullets just disapear).
Here is the code:
// when the mouse cliks
onClipEvent(mouseDown)
// duplicate the bullet mc
_root.bullet.duplicateMovieClip("bullet"+bulletNum,bulletNum);
// set the coords to the mouse clik
eval("_root.bullet" + bulletNum)._x = this._x;
eval("_root.bullet" + bulletNum)._y = this._y;
// increment the bullet number
bulletNum++;
// if more than 50 bullets , start again at 0
if(bulletNum>50)
bulletNum = 0;
What code could I use to have it so that you can only have,
say, 3 bullets in play at once, and you can't fire again until
they've hit / left the screen?
regards,
gHi again,
thanks for that. Another way would be to use code like the
following:
var enableInterval:Number;
var allowFire:Boolean;
function tempDisableFire():Void {
allowFire = false;
enableInterval = setInterval(enableFire, 500); // 500
millisecond delay
function enableFire():Void {
allowFire = true;
clearInterval(enableInterval);
I am unsure though whether to insert this within my existing
code, or to use this starting from scratch. If it was inside an
onClipEvent tag (the event being the mouse click), I could then use
it to control the fire. I'm not sure if I would do this with an "if
/ then" statement.
Any suggestions on this method? I know it may be asking a bit
much, but if you could even complete this piece of code that would
be magic!
cheers,
g -
Help with KeyDown (space invaders game)
I'm making a space invaders type game for school using Greenfoot (new Java IDE). Whenever I press space, a bullet will fire. However, multiple bullets are being created when I press space once, and when I hold space, a long stream of bullets are being made. I want one bullet to be created when I press space. Tried using KeyPress, but apparently Greenfoot does not recognize java.awt? Thanks in advance.
public class Ship extends Vehicle {
* Constructor for objects of class Shuttle
public Bullet B;
boolean canFire = false;
public Ship() {
GreenfootImage ship = new GreenfootImage("spaceship.gif");
this.setImage(ship);
//Create a bullet
public void fire(){
B = new Bullet();
getWorld().addObject(B,getX(),getY()-60);
public boolean collision(){
Actor enemy = getOneIntersectingObject(null);
return (enemy!=null) ? true : false;
public void act(){
// move with keys
if (this.canMove())
move();
if(Greenfoot.isKeyDown("space")){
fire();
else if(collision()){
getWorld().removeObject(this);
}Make a Class Variable to use as a flag indicating that a key was pressed... check to see if the flag is set, and if it is not, then fire a bullet and then set the flag. Reset the flag when they keyReleased action fires.
This way only one bullet can be fired for each time a key is pressed, provided your act() is being polled, but if a keyPressed fires act(), but not a keyRelease too, then it will not work. If it does not work, then you'll need to go to a regular KeyListener.
//Your code make these changes
public class Ship extends Vehicle {
* Constructor for objects of class Shuttle
public Bullet B;
boolean canFire = false;
public Ship() {
GreenfootImage ship = new GreenfootImage("spaceship.gif");
this.setImage(ship);
//Create a bullet
public void fire(){
B = new Bullet();
getWorld().addObject(B,getX(),getY()-60);
public boolean collision(){
Actor enemy = getOneIntersectingObject(null);
return (enemy!=null) ? true : false;
public void act(){
// move with keys
if (this.canMove())
move();
if(!GreenFoot.isKeyDown("space")) canFire = true; //add this
if(Greenfoot.isKeyDown("space") and canFire){
fire();
canFire = false; //add this
else if(collision()){
getWorld().removeObject(this);
} -
Firing bullets in space invaders game
hey guys,
I am trying to work out the logic and the code required for firing a bullet in a space invaders style game.
I have a space ship on a stage that moves around freely using the arrow keys and I want to use the space bar to release a bullet.
So far my thinking is as follows:
when the space bar is pressed a bullet is released from the players space ship.
so I need to think about:
- the speed of the bullet
- the position of the spaceship when the bullet is fired
- being able to fire multiple bullets one after the other
- the bullet should move from the bottom of the screen to the top of the screen
- the consequence of a bullet hitting a target
I do not know how many scripts I would need to tackle this? how many behaviours per script and more importantly the code required....
I am desperate for any help and support you can provide...
thank youthank you for your support
at this current time it would be a waste of time to understand how things work that did not benefit my game, sure knowledge would give me power but at the moment Id rather concentrate on gaining the appropriate knowledge as per the mechanics of my game and not going off in the opposite direction
having had a look at your space invaders game and the code and logic you provided it is different to the game I am building because:
- you use the move for movement and fire whereas I use cursor keys and a space bar
- you have limited the amount of ammuntion, I have not
- there are no explosions or changing of cast members on intersection.
I understand the aim of you posting the guide however I am of the thinking it would be better to follow a tutorial that is in line with what I require rather then learning a particular style and then again having to work out how to amend it again to be used in my game...
So if anyone can help me understand or provide code as per my initial message , I would be so grateful
thank you -
Help! trying to create 'space invaders'
hi. im a high school student with a little knowledge of java. im am currently working on a class assignment where each student has to create their own program. i decided to create the classic game of 'Space Invaders'. But i have a problem; i can't figure out how i will get the characters to move.
does anyone if there is a method that will allow the user to move a character? for example, in C++ there is a conio.h library that has a goto(x,y) function. is there one for java as well? thanks alot!This is another way
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Si extends JFrame
Timer ta;
myView view = new myView();
public Si()
setBounds(3,10,765,350);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent ev)
{ dispose();
System.exit(0);
getContentPane().add("Center",view);
setVisible(true);
ta = new Timer(45, new ActionListener()
{ public void actionPerformed(ActionEvent e)
view.move();
ta.start();
public class myView extends JComponent
Point invs[] = new Point[15];
Color invc[] = new Color[15];
Color color[] = new Color[]{
Color.blue, Color.cyan, Color.green, Color.magenta,
Color.orange, Color.pink, Color.red, Color.yellow};
public myView()
for (int p=0; p < invs.length; p++)
int x = (int)(Math.random()*600)+33;
int y = (int)(Math.random()*200)+33;
invs[p] = new Point(x,y);
int c = (int)(Math.random()*8);
invc[p] = color[c];
public void move()
for (int p=0; p < invs.length; p++)
repaint(invs[p].x-1,invs[p].y-1,20,18);
int x = (int)(Math.random()*3)-1;
int y = (int)(Math.random()*3)-1;
invs[p].translate(x,y);
repaint(invs[p].x-1,invs[p].y-1,20,18);
public void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
for (int p=0; p < invs.length; p++)
g.setColor(invc[p]);
g.fillOval(invs[p].x,invs[p].y,17,13);
public static void main (String[] args)
new Si();
} Noah -
[FLMX] ayuda con tutorial space invaders
Hola a todos.
estoy tratando de hacer una modificación de un FLA del
space invaders
que me bajé en:
http://www.flashkit.com/movies/Games/Full_Game_Source/Space_In-Paul_Nea-8765/index.php
Este jueguecillo incluye un PHP que guarda los records en
unos txt.
La cuestión es que no tengo mucha idea de
programación y no me funcionan
los records.
¿alguien podria ayudarme?
gracias mil
Juan -
Making my enemies drop bombs in space invaders
Hi all,
I'm in the process of learning flash just now and am
completing an online tutorial on Space Invaders. Thing is, the
bombs drop from a random location on the screen. I want them to
drop from a random enemy (I'm not too bothered just now about
making it one on the bottom row or one with no other enemies before
them).
At the moment, here is the AS that makes them drop (the
frequency is determined elsewhere):
eval("_root.alienBomb" + alienBombNum)._x =random(700);
eval("_root.alienBomb" + alienBombNum)._y =
300*Math.random();
An I can modify it to get a certain one to drop:
eval("_root.alienBomb" + alienBombNum)._x
=_root.alienClip2_2._x;
eval("_root.alienBomb" + alienBombNum)._y =
_root.alienClip2_2._y;
I can' t get it to randomly choose one - I know I have to use
the random function, but don't know how to implement this.
Can anyone help?
regards,
gThe code you're using is really old...back to Flash 5, I'd
guess, which makes this rather more complicated than it need be.
Since you seem to be in AS1, I'll keep it that way. Try
using:
xGridNum = Math.round(Math.random() * 7);
yGridNum = Math.round(Math.random() * 7);
var bomb = _root["alienBomb"+alienBombNum];
var alien = _root["alien"+xGridNum+"_"+yGridNum];
bomb._x = alien._x;
bomb._y = alien._y;
The above isn't the best way to do this, but it's simple and
not far from what you've referenced. The sevens above assume 8 rows
and 8 columns of aliens (numbered alien0_0 to alien7_7).
Hope that helps. -
Space invaders! I need some help...!
Hello,
i'm trying to program a very simple version of space invaders. I'm drawing my moving objects (spaceship, rockets, aliens) with drawstring but I'm getting these compiling error: illegal start of expression.
Also I want to move the spaceship with translate is this OK to do so!?
Can somebody help me? Thanks for your help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Graphics2D;
//in deze klasse teken ik het ruimteschip en kan het links/rechts bewegen
public class Ruimteschip
//ruimteschip
Ruimteschip roderikschip = new Ruimteschip();
public void paint(Graphics ruimteschip)
{ //Ruimteschip weergeven
Graphics2D ruimteschip2D = (Graphics2D)ruimteschip;
String ruimteschip = "ruimteschip";
ruimteschip2D.drawString("ruimteschip", x, y,);
//beweegmethod
public void beweegRechts()
{ //teken opnieuw 1 coordinaat rechts
roderikschip.translate(1, 0);
ruimteschip2D.drawString("ruimteschip", x, y);
//beweegmethod
public void beweegLinks()
{ //teken opnieuw 1 coordinaat links
roderikschip.translate(-1, 0);
ruimteschip2D.drawString("ruimteschip", x, y);
}Hi and thanks for your replies.
I know drawString isn't the most beautiful way, but I'm making this game for an assignment, and I have to use drawString.
Still i'm getting "illegal start of expression" in my paint method...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Graphics2D;
//in deze klasse teken ik het ruimteschip en kan het links/rechts bewegen
public class Ruimteschip
//ruimteschip
Ruimteschip ruimteschip = new Ruimteschip();
public void paint(Graphics ruimteschip)
{ //Ruimteschip weergeven
Graphics2D ruimteschip2D = (Graphics2D)ruimteschip;
String s = "ruimteschip";
*ruimteschip2D.drawString(s, x, y,);*
//beweegmethod
public void beweegRechts()
{ //teken opnieuw 1 coordinaat rechts
s.translate(1, 0);
ruimteschip.drawString(s, x, y);
//beweegmethod
public void beweegLinks()
{ //teken opnieuw 1 coordinaat links
s.translate(-1, 0);
ruimteschip.drawString(s, x, y);
} Edited by: Roddy on May 1, 2008 8:28 AM -
Yet another Space Invaders game...
Yes, here is my first Java game:
www.fnfconsulting.no
Feel free to check it out. No registration necessary.
Comments&Questions are welcome.
Halhaha coded only using your right hand. nice . this
kicks your games to mars and back malo ;) 1 word
SOUND! and good sound :P good stuff although it doesnt
use 1.1 so your audience is limited (its like
developing for linux .. very limited) most people (i
know) wont bother downloading the plug in. very nice
thoughThanks. I dont think I understand all your comments, but I'll give it a try.
Firstly, the game has sound, and personally I think it's the coolest part of the game. The sounds are samples from the movies. I use standard AudioClip, no fancy stuff.
When you mention 1.1, do you mean JVM 1.1, the old stuff that was released with IE 5.0 or something? I think nowadays most people that develop Java games uses "Java 2" which as I understand it is Java SDK 1.2 and up. And most people playing Java games downloads some kind of JRE, often the newest version, 1.4.2.X.
Correct me if I'm wrong :) -
Comparing coordinates for space invaders clone
thanks a lot! The buttons now work! I have updated my code, but now my problem is to compare the position of the bullet with the position of the ufo. I have marked the part where I wrote my solution, but it doesn't really work, do you have any suggestions?
Thanks.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Animation extends JPanel implements ActionListener{
JButton button=new JButton("links");
JButton button2=new JButton("rechts");
int xpos=60;
int xpos2=0;
int height=15;
int width=60;
int dx=3;
int dxshooter=3;
int shoot=300;
int ykogel=0;
int dxkogel=6;
int number=12;
int xposkogel;
int yposkogel;
int ovalx1=xpos,ovalx2=xpos+100,ovalx3=xpos+200,ovalx4=xpos+300,ovalx5=xpos+400,ovalx6=xpos+500;
int ovaly1=15,ovaly2=15,ovaly3=15,ovaly4=15,ovaly5=15,ovaly6=15;
int ovalxb1=xpos+19,ovalxb2=xpos+19+100,ovalxb3=xpos+19+200,ovalxb4=xpos+19+300,ovalxb5=xpos+19+400,ovalxb6=xpos+19+500;
int ovalyb1=5,ovalyb2=5,ovalyb3=5,ovalyb4=5,ovalyb5=5,ovalyb6=5;
Timer fastTicker;
Animation(){
fastTicker=new Timer(25,this);
void start(){
Listener ear = new Listener();
this.add(button);
button.setSize(100,50);
button.move(0,320);
button.addActionListener(ear);
this.add(button2);
button2.setSize(100,50);
button2.move(600,320);
button2.addActionListener(ear);
fastTicker.start();
class Listener implements ActionListener{
public void actionPerformed(ActionEvent b)
Object o =b .getSource();
if (o == button){
if(dxshooter==3){
dxshooter=-3;}
if (o == button2){
if(dxshooter==-3){
dxshooter=3;}
public void actionPerformed(ActionEvent e){
yposkogel=312-ykogel;
ovalx1=xpos;
ovalx2=xpos+100;
ovalx3=xpos+200;
ovalx4=xpos+300;
ovalx5=xpos+400;
ovalx6=xpos+500;
ovalxb1=xpos+19;
ovalxb2=xpos+19+100;
ovalxb3=xpos+19+200;
ovalxb4=xpos+19+300;
ovalxb5=xpos+19+400;
ovalxb6=xpos+19+500;
//bolletjesanimatie
if(e.getSource()==fastTicker){
ykogel+=dxkogel;
xposkogel=xpos2;
xpos2+=dxshooter;
if(ykogel>=3){
xposkogel=xposkogel;}
//schietding
if (xpos2>240){
dxshooter=-3;}
if(xpos2<-210){
dxshooter=3;}
//kogelanimatie
if(ykogel>310){
ykogel=0;}
//COMPARING THE POSITION OF THE BULLET WITH THE UFO's
if(yposkogel<=15){
if(xposkogel>=ovalx6&&xposkogel<=ovalx6+60){
ovaly6=1500;
ovalyb6=1500;}
if(xposkogel>=ovalx5&&xposkogel<=ovalx5+60){
ovaly5=1500;
ovalyb5=1500;}
if(xposkogel>=ovalx4&&xposkogel<=ovalx4+60){
ovaly4=1500;
ovalyb4=1500;}
if(xposkogel>=ovalx3&&xposkogel<=ovalx3+60){
ovaly3=1500;
ovalyb3=1500;}
if(xposkogel>=ovalx2&&xposkogel<=ovalx2+60){
ovaly2=1500;
ovalyb2=1500;}
if(xposkogel>=ovalx1&&xposkogel<=ovalx1+60){
ovaly1=1500;
ovalyb1=1500;}
this.repaint();
public void paintComponent(Graphics g){
super.paintComponent(g);
//ufo's
g.setColor(Color.black);
g.fillOval(ovalxb1,ovalyb1, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx1,ovaly1,width,height);
g.setColor(Color.black);
g.fillOval(ovalxb2,ovalyb2, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx2,ovaly2,width,height);
g.setColor(Color.black);
g.fillOval(ovalxb3,ovalyb3, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx3,ovaly3,width,height);
g.setColor(Color.black);
g.fillOval(ovalxb4,ovalyb4, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx4,ovaly4,width,height);
g.setColor(Color.black);
g.fillOval(ovalxb5,ovalyb5, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx5,ovaly5,width,height);
g.setColor(Color.black);
g.fillOval(ovalxb6,ovalyb6, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx6,ovaly6,width,height);
//schietding
g.fillRect(xpos2+350-17,317,6,40);
g.setColor(Color.green);
g.fillOval(xpos2+350-30,330,30,30);
g.setColor(Color.black);
g.fillRect(xpos2+350-40,350,50,height);
//kogel
g.fillRect(xposkogel+350-16,yposkogel,5,5);
public class AnimationDemo{
JFrame frame;
Animation animation;
void demo(){
frame=new JFrame("**Spees Inveeders** All rights reserved (Dave Senden and Joeri Oomen)");
animation=new Animation();
frame.getContentPane().add(animation);
frame.setSize(700,400);
frame.setVisible(true);
animation.start();
public static void main(String[] args){
AnimationDemo animationDemo=new AnimationDemo();
animationDemo.demo();thanks a lot! The buttons now work! I have updated my code, but now my problem is to compare the position of the bullet with the position of the ufo. I have marked the part where I wrote my solution, but it doesn't really work, do you have any suggestions?
Thanks.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Animation extends JPanel implements ActionListener{
JButton button=new JButton("links");
JButton button2=new JButton("rechts");
int xpos=60;
int xpos2=0;
int height=15;
int width=60;
int dx=3;
int dxshooter=3;
int shoot=300;
int ykogel=0;
int dxkogel=6;
int number=12;
int xposkogel;
int yposkogel;
int ovalx1=xpos,ovalx2=xpos+100,ovalx3=xpos+200,ovalx4=xpos+300,ovalx5=xpos+400,ovalx6=xpos+500;
int ovaly1=15,ovaly2=15,ovaly3=15,ovaly4=15,ovaly5=15,ovaly6=15;
int ovalxb1=xpos+19,ovalxb2=xpos+19+100,ovalxb3=xpos+19+200,ovalxb4=xpos+19+300,ovalxb5=xpos+19+400,ovalxb6=xpos+19+500;
int ovalyb1=5,ovalyb2=5,ovalyb3=5,ovalyb4=5,ovalyb5=5,ovalyb6=5;
Timer fastTicker;
Animation(){
fastTicker=new Timer(25,this);
void start(){
Listener ear = new Listener();
this.add(button);
button.setSize(100,50);
button.move(0,320);
button.addActionListener(ear);
this.add(button2);
button2.setSize(100,50);
button2.move(600,320);
button2.addActionListener(ear);
fastTicker.start();
class Listener implements ActionListener{
public void actionPerformed(ActionEvent b)
Object o =b .getSource();
if (o == button){
if(dxshooter==3){
dxshooter=-3;}
if (o == button2){
if(dxshooter==-3){
dxshooter=3;}
public void actionPerformed(ActionEvent e){
yposkogel=312-ykogel;
ovalx1=xpos;
ovalx2=xpos+100;
ovalx3=xpos+200;
ovalx4=xpos+300;
ovalx5=xpos+400;
ovalx6=xpos+500;
ovalxb1=xpos+19;
ovalxb2=xpos+19+100;
ovalxb3=xpos+19+200;
ovalxb4=xpos+19+300;
ovalxb5=xpos+19+400;
ovalxb6=xpos+19+500;
//bolletjesanimatie
if(e.getSource()==fastTicker){
ykogel+=dxkogel;
xposkogel=xpos2;
xpos2+=dxshooter;
if(ykogel>=3){
xposkogel=xposkogel;}
//schietding
if (xpos2>240){
dxshooter=-3;}
if(xpos2<-210){
dxshooter=3;}
//kogelanimatie
if(ykogel>310){
ykogel=0;}
//COMPARING THE POSITION OF THE BULLET WITH THE UFO's
if(yposkogel<=15){
if(xposkogel>=ovalx6&&xposkogel<=ovalx6+60){
ovaly6=1500;
ovalyb6=1500;}
if(xposkogel>=ovalx5&&xposkogel<=ovalx5+60){
ovaly5=1500;
ovalyb5=1500;}
if(xposkogel>=ovalx4&&xposkogel<=ovalx4+60){
ovaly4=1500;
ovalyb4=1500;}
if(xposkogel>=ovalx3&&xposkogel<=ovalx3+60){
ovaly3=1500;
ovalyb3=1500;}
if(xposkogel>=ovalx2&&xposkogel<=ovalx2+60){
ovaly2=1500;
ovalyb2=1500;}
if(xposkogel>=ovalx1&&xposkogel<=ovalx1+60){
ovaly1=1500;
ovalyb1=1500;}
this.repaint();
public void paintComponent(Graphics g){
super.paintComponent(g);
//ufo's
g.setColor(Color.black);
g.fillOval(ovalxb1,ovalyb1, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx1,ovaly1,width,height);
g.setColor(Color.black);
g.fillOval(ovalxb2,ovalyb2, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx2,ovaly2,width,height);
g.setColor(Color.black);
g.fillOval(ovalxb3,ovalyb3, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx3,ovaly3,width,height);
g.setColor(Color.black);
g.fillOval(ovalxb4,ovalyb4, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx4,ovaly4,width,height);
g.setColor(Color.black);
g.fillOval(ovalxb5,ovalyb5, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx5,ovaly5,width,height);
g.setColor(Color.black);
g.fillOval(ovalxb6,ovalyb6, 25,25);
g.setColor(Color.orange);
g.fillOval(ovalx6,ovaly6,width,height);
//schietding
g.fillRect(xpos2+350-17,317,6,40);
g.setColor(Color.green);
g.fillOval(xpos2+350-30,330,30,30);
g.setColor(Color.black);
g.fillRect(xpos2+350-40,350,50,height);
//kogel
g.fillRect(xposkogel+350-16,yposkogel,5,5);
public class AnimationDemo{
JFrame frame;
Animation animation;
void demo(){
frame=new JFrame("**Spees Inveeders** All rights reserved (Dave Senden and Joeri Oomen)");
animation=new Animation();
frame.getContentPane().add(animation);
frame.setSize(700,400);
frame.setVisible(true);
animation.start();
public static void main(String[] args){
AnimationDemo animationDemo=new AnimationDemo();
animationDemo.demo(); -
Hi!
My awful version of space invaders is almost ready. I only have problems programming the method where I check whether a rocket hits an alien. This method is called 'controleerHit' in Spel.
Thanks for your help!
import java.applet.*;
import java.awt.*;
import javax.swing.Timer;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.Object;
import java.util.ArrayList;
import java.util.Random;
//een simpel schietspel van 15 seconden waarbij het ruimteschip dmv raketten bewegende aliens
//moet zien te raken en dmv bewegen zijn positie kan bepalen
public class Spel extends Applet
//Timers
Timer nieuwePositieTimer;
Timer nieuweAlienTimer;
Timer stopSpelTimer;
//een nieuwe arraylist bewegendedelen
ArrayList<BewegendeDelen> bewegendedelenarray = new ArrayList<BewegendeDelen>();
Ruimteschip ruimteschip = new Ruimteschip();
Raket raket = null;
public void init()
setBackground(Color.white);
//nieuwepositielistener
ActionListener nieuwePositieListener = new nieuwePositieListener();
//interval van 1/4 seconde
final int nieuwepositieDELAY = 250;
//nieuwe positie timer
Timer nieuwePositieTimer = new Timer(nieuwepositieDELAY, nieuwePositieListener);
this.nieuwePositieTimer = nieuwePositieTimer;
//start de nieuwe positietimer
nieuwePositieTimer.start();
//nieuwe alien listener
ActionListener nieuweAlienListener = new nieuweAlienListener();
//interval van 4 seconden
final int nieuwealienDELAY = 4000;
//nieuwe alientimer
Timer nieuweAlienTimer = new Timer(nieuwealienDELAY, nieuweAlienListener);
this.nieuweAlienTimer = nieuweAlienTimer;
//start de nieuwe alientimer
nieuweAlienTimer.start();
//stop het spel listener
ActionListener stopSpelListener = new stopSpelListener(15);
//1 seconde interval
final int stopspelDELAY = 1000;
//nieuwe timer stop het spel
stopSpelTimer = new Timer(stopspelDELAY, stopSpelListener);
//start de timer
stopSpelTimer.start();
//bewegendedelenarray.add(alien);
bewegendedelenarray.add(ruimteschip);
//bewegendedelenarray.add(raket);
//tekenen
public void paint(Graphics g)
{ //print uit bewegendedelenarray obj van het type BewegendeDelen
for(BewegendeDelen obj : bewegendedelenarray)
{ //teken de bewegende delen (ruimteschip, aliens en raketten)
System.out.println(obj);
obj.paint(g);
//als teller op nul staat game over!
if (count <= 0)
g.drawString("Game over!", 250, 250);
//laat de score zien als de teller op nul staat
if (count <= 0)
g.drawString("Je score is: " + score + "!", 250, 300);
//pijltjes toetsen indrukken om te bewegen en spatie om te schieten
public boolean keyDown(Event e, int key)
{ //naar links
if(key == Event.LEFT)
{ if (ruimteschip.getX() > 10)
ruimteschip.beweegLinks();
System.out.println("links");
repaint();
else
//naar rechts
if(key == Event.RIGHT)
{ if (ruimteschip.getX() < 450)
ruimteschip.beweegRechts();
repaint();
else
//schieten
if (key == 32)
raket = new Raket(ruimteschip.getX(), ruimteschip.getY());
bewegendedelenarray.add(raket);
raket.beweeg();
repaint();
return true;
//als er sprake is van een hit, roep dan de method aan
public void controleerHit()
{ //zolang er een raket is
//vergelijk, voor ieder object, of een ander object dezelfde coordinaten heeft
for(BewegendeDelen obj : bewegendedelenarray)
//vergelijk de coordinaten
if(raket != null && obj.checkHit(raket.getX(), raket.getY()))
//verwijderen, opnieuw tekenen en score ophogen
bewegendedelenarray.remove(obj);
bewegendedelenarray.remove(raket);
//raket = null;
repaint();
score++;
//iedere 1/4 seconden krijgen de aliens een nieuwe positie
class nieuwePositieListener implements ActionListener
public void actionPerformed(ActionEvent event)
{ System.out.println("nieuwe pos");
Random generator = new Random();
//laat de objecten bewegen
for(BewegendeDelen obj : bewegendedelenarray)
obj.beweeg();
repaint();
controleerHit();
/*if (raket.bestaatNog() )
bewegendedelenarray.remove(raket);
raket = null;
//om de vier seconden een nieuwe alien op het scherm
class nieuweAlienListener implements ActionListener
public void actionPerformed(ActionEvent event)
{ //voeg een nieuw alien object aan de array toe
System.out.println("nieuwe alien");
bewegendedelenarray.add(new Alien());
repaint();
//na 15 seconden stopt het spel: Game Over!
class stopSpelListener implements ActionListener
public stopSpelListener(int initialCount)
count = initialCount;
public void actionPerformed(ActionEvent event)
{ count--;
//als de teller op 0 staat is het spel voorbij
if (count == 0)
nieuwePositieTimer.stop();
nieuweAlienTimer.stop();
stopSpelTimer.stop();
else
System.out.println("time left: " + count);
//instantievariabelen
private int count;
private int score;
private boolean geraakt;
} import java.awt.*;
import java.awt.Graphics2D;
//superclass met gezamenlijke eigenschappen van de bewegende delen ruimteschip, alien en raket
public class BewegendeDelen
public void paint(Graphics g)
{ //weergave drawstring met x en y positie
Graphics2D g2D = (Graphics2D)g;
g.drawString(weergave, x, y);
//zet de x positie
public void setX(int xPos)
x = xPos;
//en y positie
public void setY(int yPos)
y = yPos;
public void setWeergave(String deWeergave)
weergave = deWeergave;
public String getWeergave()
return weergave;
public int getX()
return x;
public int getY()
return y;
//beweegmethod rechts
public void beweegRechts()
{ //verschuif rechts
x = x + 25;
//beweegmethod links
public void beweegLinks()
{ //verschuif links
x = x - 25;
public void beweeg()
public String toString()
return weergave + ": (" + x + ", " + y +")";
//geef de breedte terug
public int getWidth()
return width;
public boolean checkHit(int rx, int ry)
return true;
public boolean bestaatNog()
return true;
//instantievariabelen
public int x;
public int y;
public String weergave;
public int width;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.Graphics2D;
//subklasse van "bewegendedelen" die eigenschappen ervan erft, en met beweegmethods
public class Ruimteschip extends BewegendeDelen
public Ruimteschip()
weergave = "<<=>>";
x = 250;
y = 500;
import java.awt.*;
import java.awt.image.*;
import java.applet.Applet;
//de alien class
public class Alien extends BewegendeDelen
public Alien()
weergave = "^^^";
y = 25;
public void beweeg()
x= x+10;
public boolean checkHit(int rx, int ry)
if((rx >= getX() && rx <= (x+weergave.length()*10)) && ry == getY())
geraakt = true;
return false;
public boolean geraakt;
import java.awt.*;
import java.awt.image.*;
import java.applet.Applet;
public class Raket extends BewegendeDelen
public Raket(int x, int y)
weergave = "|";
setX(x+17);
setY(y);
//schietmethod, verticaal omhoog bewegen
public void beweeg()
y = y - 40;
//een lege string als weergave
public void verwijder()
weergave = "";
//als de raket uit het scherm is dan bestaat hij niet meer
/* public boolean bestaatNog()
if (getY()<0)
{return false;}
else return true;
} Edited by: Roddy on Oct 22, 2008 4:28 AMRoddy wrote:
Hi!
My awful version of space invaders is almost ready. I only have problems programming the method where I check whether a rocket hits an alien. This method is called 'controleerHit' in Spel.
Thanks for your help!And what is wrong with it? Have you tried putting some debug code in the method to see what is going on? -
Need help making pace invaders in java
So here is my code:
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.*;
import javax.swing.JPanel;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
public class invaders extends Canvas {
public static final int Width = 800;
public static final int Height = 600;
public invaders() {
JFrame openspace = new JFrame("Space Invaders");
JPanel window = (JPanel)openspace.getContentPane();
setBounds(0,0,Width,Height);
window.setPreferredSize(new Dimension(Width,Height));
window.setLayout(null);
window.add(this);
openspace.setBounds(0,0,Width,Height);
openspace.setVisible(true);
openspace.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
public void paint(Graphics graph) {
// graph.setColor(Color.red);
// graph.fillOval( Width/2-10, Height/2-10,20,20);
// spacealien = loadImage("spaceAlien.jpg");
// graph.drawImage(spaceAlien, 50, 50, this);
public static void main(String[] args) {
invaders spaceinvaders = new invaders();
I am trying to add pictures into the JFrame but I don't know how. I am following this tutorial http://www.planetalia.com/cursos/Java-Invaders/JAVA-INVADERS-04.tutorial but I get confused when they talk about how to add in an image.
This is their Code:
1 package version04;
2 /**
3 * Curso B?sico de desarrollo de Juegos en Java - Invaders
4 *
5 * (c) 2004 Planetalia S.L. - Todos los derechos reservados. Prohibida su reproducci?n
6 *
7 * http://www.planetalia.com
8 *
9 */
10
11
12 import java.awt.Canvas;
13 import java.awt.Dimension;
14 import java.awt.Graphics;
15 import java.awt.event.WindowAdapter;
16 import java.awt.event.WindowEvent;
17 import java.awt.image.BufferedImage;
18 import java.net.URL;
19
20 import javax.imageio.ImageIO;
21 import javax.swing.JFrame;
22 import javax.swing.JPanel;
23
24 public class Invaders extends Canvas {
25 public static final int WIDTH = 800;
26 public static final int HEIGHT = 600;
27
28
29 public Invaders() {
30 JFrame ventana = new JFrame("Invaders");
31 JPanel panel = (JPanel)ventana.getContentPane();
32 setBounds(0,0,WIDTH,HEIGHT);
33 panel.setPreferredSize(new Dimension(WIDTH,HEIGHT));
34 panel.setLayout(null);
35 panel.add(this);
36 ventana.setBounds(0,0,WIDTH,HEIGHT);
37 ventana.setVisible(true);
38 ventana.addWindowListener( new WindowAdapter() {
39 public void windowClosing(WindowEvent e) {
40 System.exit(0);
41 }
42 });
43 }
44
45 public BufferedImage loadImage(String nombre) {
46 URL url=null;
47 try {
48 url = getClass().getClassLoader().getResource(nombre);
49 return ImageIO.read(url);
50 } catch (Exception e) {
51 System.out.println("No se pudo cargar la imagen " + nombre +" de "+url);
52 System.out.println("El error fue : "+e.getClass().getName()+" "+e.getMessage());
53 System.exit(0);
54 return null;
55 }
56 }
57
58
59 public void paint(Graphics g) {
60 BufferedImage bicho = loadImage("res/bicho.gif");
61 g.drawImage(bicho, 40, 40,this);
62 }
63
64 public static void main(String[] args) {
65 Invaders inv = new Invaders();
66 }
67 }
68
I know there must be an easier way. Please help, thanks!!!!One way to add an image to a user interface is to use a JLabel with an ImageIcon: [http://java.sun.com/docs/books/tutorial/uiswing/components/label.html]
-
Game Heap Space - Out Of Memory Error
Hi there,
Ive completed my pacman/space invaders hybrid game- which has a main game and two playable videos. Its all fine, but when I go to run it it says;
Exception in thread "Image Fetcher 1" java.lang.OutOfMemoryError: Java heap space
Exception in thread "Image Fetcher 2" java.lang.OutOfMemoryError: Java heap space
Ive come to realise that this error is from the amount of data used to make up the game/video with there being around 150 images for the videos. Ive temporarily corrected this problem by making each video 26 images long (2.6secs each) but to get the full experience the user need to see around 75images.
After a bit of research I found that i needed to increase my 'heap space'- and I attempted to do this thru cmd, attemptin to increase it to 512mb.
The problem is the game doesnt have a main, or at least not one that I nor the computer can locate. And to get the heap space to increase it needs a main?!
I honestly dont know what I am doing here- but could anyone tell me how I can increase my heap space or locate a main? Im really confused!
Any help appreciated
Senor-CojonesThanks for your help ArikArikArik, the problem with that method is.... 1. im not too sure how to use it :P and 2. In my original code the images are added to the tracker which waits from all the images to be loaded before it continues.
import javax.swing.*;
import java.applet.AudioClip;
import java.awt.*;
public class ICGGSApplet extends JApplet implements Runnable {
// constants describing possible game states
private static final int SHOW_MOVIE = 1;
private static final int PLAY_GAME = 2;
private static final int STOPPED = 3;
private static final int SHOW_MOVIE2 = 4;
private int gameState; // the current game state
private String name; // the player's name
private long frameStartTime; // the time the last frame was displayed
private Thread gameLoop; // thread to run the game and movie
// associated objects
private Movie theMovie; // Panel to display the movie
private MonsterGame theGame; // Panel to display the game
private ICGGSPanel currentPanel; // the currently displayed Panel (can be null)
private Movie2 theMovie2; // Panel to display the second movie
* Called when applet is first loaded
* sets up the attributes, load media, creates game objects
* and sets up interface
public void init() {
// neither the movie nor the game is currently playing
currentPanel = null;
gameState = STOPPED;
name = "";
// load up the audio files
AudioClip theAudio = getAudioClip(getDocumentBase(), "../media/shock.wav");
AudioClip theAudio2 = getAudioClip(getDocumentBase(), "../media/applause.wav");
AudioClip theAudio3 = getAudioClip(getDocumentBase(), "../media/bomb.wav");
AudioClip theAudio4 = getAudioClip(getDocumentBase(), "../media/cashtill.wav");
AudioClip theAudio5 = getAudioClip(getDocumentBase(), "../media/pacman.wav");
// create a media tracker to monitor the loading of the images
MediaTracker theTracker = new MediaTracker(this);
// load up the images for the movie
Image movieImages[] = new Image[25];
for (int i=0; i<movieImages.length; i++) {
movieImages[i] = getImage(getDocumentBase(), "../media/movie" + (i+1) + ".jpg");
theTracker.addImage(movieImages, i);
// load up the images for the second movie
Image movieImages2[] = new Image[25];
for (int i=0; i<movieImages2.length; i++) {
movieImages2[i] = getImage(getDocumentBase(), "../media/firingGun" + (i+1) + ".jpg");
theTracker.addImage(movieImages2[i], i);
// load up the images for the munchies
Image image1 = getImage(getDocumentBase(), "../media/munchie1.gif");
theTracker.addImage(image1, 4);
Image image2 = getImage(getDocumentBase(), "../media/munchie2.gif");
theTracker.addImage(image2, 5);
Image image3 = getImage(getDocumentBase(), "../media/munchie3.gif");
theTracker.addImage(image3, 6);
// wait for all the images to be loaded
try {
theTracker.waitForAll();
} catch (InterruptedException e) {
// create the movie object
theMovie = new Movie(movieImages);
theMovie2 = new Movie2(movieImages2);
// create the game object
theGame = new MonsterGame(image1, image2, image3, theAudio, theAudio2, theAudio3, theAudio4, theAudio5);
this.getContentPane().setBackground(Color.WHITE);
// Initialise key-input functionality
addKeyListener(new Input()); // add keyboard listener to applet
* Called when the Applet is ready to start executing
public void start() {
// ask the user for their name
name = JOptionPane.showInputDialog(this, "What is your name?");
// start running the movie/game animation
if (gameLoop == null) {
gameLoop = new Thread(this);
gameLoop.start();
* Called when the gameLoop thread is started
* loops continuously until user quits
public void run() {
int input = Input.NONE;
// game loop
while (input != Input.QUIT) {
// what is the current time?
frameStartTime = System.currentTimeMillis();
input = checkInput();
if (gameState != STOPPED) // only necessary if the movie or game is showing
currentPanel.processInput(input);
currentPanel.update();
currentPanel.repaint();
} else
showStatus("Press 'G' to start game, 'M' to show movie or 'F' to show the second movie");
frameDelay(100);
* called when the Applet is stopped
* stops the gameLoop thread
public void stop() {
if (gameLoop != null) {
gameLoop.interrupt(); // stops the animation thread
gameLoop = null;
* called from the gameLoop
* checks for the last key stroke input by the user
* @return int - Input class constant representing user input
public int checkInput() {
int input = Input.checkUserInput();
switch (input) // how the input is handled depends on the current game state
case Input.GAME:
// the user wants to play the game
if (gameState == STOPPED) // not currently playing a game or movie
// display the panel showing the game
currentPanel = theGame;
this.getContentPane().add(BorderLayout.CENTER, currentPanel);
this.validate();
// set up a new game
theGame.resetGame();
gameState = PLAY_GAME;
showStatus("Use arrow keys to move Monster, S key to stop");
} // otherwise ignore
break;
case Input.MOVIE:
// the user wants to see the movie
if (gameState == STOPPED) // not currently playing a game or movie
// display the panel showing the movie
currentPanel = theMovie;
this.getContentPane().add(BorderLayout.CENTER, currentPanel);
this.validate();
gameState = SHOW_MOVIE;
showStatus("Press S key to stop");
} // otherwise ignore
break;
case Input.MOVIE2:
// the user wants to see the second movie
if (gameState == STOPPED) // not currently playing a game or movie
// display the panel showing the movie
currentPanel = theMovie2;
this.getContentPane().add(BorderLayout.CENTER, currentPanel);
this.validate();
gameState = SHOW_MOVIE2;
showStatus("Press S key to stop");
} // otherwise ignore
break;
case Input.STOP:
// the user wants to stop the movie or game being shown
if (gameState == SHOW_MOVIE ) {
this.getContentPane().remove(currentPanel);
currentPanel = null;
JOptionPane.showMessageDialog(this,
"OK " + name + " I've stopped the movie");
} else if (gameState == PLAY_GAME) {
this.getContentPane().remove(currentPanel);
currentPanel = null;
JOptionPane.showMessageDialog(this,
"OK " + name + " I've stopped the game");
} else if (gameState == SHOW_MOVIE2 ) {
this.getContentPane().remove(currentPanel);
currentPanel = null;
JOptionPane.showMessageDialog(this,
"OK " + name + " I've stopped the movie"); }
gameState = STOPPED;
showStatus("Press 'G' to start game, 'M' to show movie");
break;
Input.reset(); // reset the input module
requestFocus();
this.repaint(); // redisplay the applet
return input; // return for further processing (eg to control movement of Monster)
* called from the gameLoop
* pauses between frames
* @param millis long - minimum frame time
public void frameDelay(long millis) {
long currentTime = System.currentTimeMillis(); // what time is it now?
long elapsedTime = frameStartTime - currentTime; // how long has it been since the start of the frame?
if (elapsedTime < millis) // is it time to showing the new frame yet?
try {
Thread.sleep(millis - elapsedTime); // pause for the remaining time
} catch(Exception e) {
Thats the whole code for the applet- preloadin the image (and also everything that doesnt relate to this problem lol). Ive asked around and the answer I was given I wasnt satisfied with- make the files smaller/delete some- the files are already at their smallest about 10kb each. And also apparently (I didnt know this...) but due to security restirictions I wouldnt be able to increase the heap size anyway (this is to run the applet on my own... and others computers).
So Im really too sure what to do at the minute. Anymore help would be appreciated though.
Thank you!
Senor-Cojones
Maybe you are looking for
-
Is there a way to create multiple map tile layers at once?
Hello experts, I have a small problem. It's mainly a matter of saving some time. I need to create 51 map tile layers in mapviewer, and I would like to this this at one time. I can go to the admin console-->Management-->Manage Map Tile Layers-->Create
-
All of a sudden I'm "Unauthorized" here
In the last few days, I became more active on these forums here, helping out with answers. Everything worked great until now. A couple of answers did not post, then some threads (not all) that I've been involved in are no longer accessible to me. I g
-
I want to know if I can create a page, with a place for an ink signature, and that signature can be then copied onto other pages within the pdf where the same person's signature is needed.
-
Cups-canon-3.00 build issue
Hi, I'm having trouble installing this package cups-canon-3.00 from AUR, here is the entire output http://pastebin.com/Ya1d2u0D . I modified the PGKBUILD from: MODELS=(ip1900 ip3600 ip4600 mp190 mp240 mp540 mp630) to MODELS=(mp240) to build only for
-
I have a database running on 11.1.0.7 in HPUX ia64 environment! It is running from 11.1.0.7 OH. But when I query the dba_libraries it shows the Oracle Home as different. could you please let me know why is this behavior? [DVDB0124](itmpsh02)/home/ora