Stumped in a space invader tutorial: why are these code for?

EDIT: Hi thanks to those who viewed my post and attempted to help. I found the answer, it's called double buffering.
Anyway if you guys want to make additional infos or add something feel free to do so. Because I don't fully understand what's going on. (like what kind of graphic does getGraphics() return?)
Thanks again!
Hi, I'm following a tutorial about creating a space invaders game and it doesn't really explain much the objects and methods.
Here's what I've done so far:
import java.awt.Canvas;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Invaders extends Canvas{
     static final int WIDTH = 800;
     static final int HEIGHT = 600;
     static final int SPEED = 10;
     HashMap sprites;
     int posX, posY, vX;
     BufferedImage buffer;
     Invaders(){
          sprites = new HashMap();
          posX = WIDTH/2;
          posY = HEIGHT/2;
          vX = 2;
          buffer = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
          JFrame ventana = new JFrame("Space Invaders");
          JPanel panel = (JPanel)ventana.getContentPane();
          setBounds(0, 0, WIDTH, HEIGHT);
          panel.setPreferredSize(new Dimension(WIDTH,HEIGHT));
          panel.setLayout(null);
          panel.add(this);
          ventana.setBounds(0, 0, WIDTH, HEIGHT);
          ventana.setVisible(true);
          ventana.addWindowListener(new WindowAdapter(){@Override
          public void windowClosing(WindowEvent e) {
               // TODO Auto-generated method stub
               super.windowClosing(e);
          ventana.setResizable(false);
          ventana.setIgnoreRepaint(true);
     public BufferedImage loadImage(String name) {
          URL url = null;
          try {
               url = getClass().getClassLoader().getResource(name);
               return ImageIO.read(url);
          } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
               return null;
     BufferedImage getSprite(String name){
          BufferedImage img = (BufferedImage)sprites.get(name);
          if (img == null){
               img = loadImage("res/"+name);
               sprites.put(name, img);
          return img;
     public void paintWorld(){
          Graphics g = buffer.getGraphics();
          g.setColor(getBackground());
          g.fillRect(0, 0, getWidth(), getHeight());
          g.drawImage(getSprite("bicho.gif"), posX, posY, this);
          getGraphics().drawImage(buffer, 0, 0, this);
     public void paint(Graphics g){}
     public void update(Graphics g) {}
     public void updateWorld() {
          posX += vX;
          if (posX < 0 || posX > WIDTH) vX = -vX;
     public void game(){
          while (isVisible()){
               updateWorld();
               paintWorld();
               paint(getGraphics());
               try {
                    Thread.sleep(SPEED);
               } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
      * @param args
     public static void main(String[] args) {
          // TODO Auto-generated method stub
          Invaders inv = new Invaders();
          inv.game();
}I tried reading the Java API but I don't get what it's saying for these:
buffer = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB); //what is the meaning of TYPE_INT_RGB?
ventana.setIgnoreRepaint(true); //why ignore repaint?
public void paintWorld() {
Graphics g = buffer.getGraphics();
g.setColor(getBackground());
g.fillRect(0,0,getWidth(),getHeight());
g.drawImage(getSprite("bicho.gif"), posX, posY,this);
getGraphics().drawImage(buffer,0,0,this); //why add this line?
}and lastly:
      public void game() {
        while (isVisible()) {
         updateWorld();
         paintWorld();
         paint(getGraphics()); //why call paint here?
         try {
            Thread.sleep(SPEED);
         } catch (InterruptedException e) {}
     }I understand the rest of the code, it's just the parts that I've mentoined that I can't really understand.
I'd appreciate any help. Thanks! :)
Edited by: ajushi on Dec 16, 2007 2:38 PM
Edited by: ajushi on Dec 16, 2007 2:43 PM
Edited by: ajushi on Dec 16, 2007 2:52 PM

I got the sucker to draw but now it won't stop! You have to kill it's JVM with taskManager... and I haven't got a clue how to fix it.
package forums;
import java.util.Map;
import java.util.HashMap;
import java.awt.Canvas;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Container;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.io.IOException;
public class SpaceInvaders extends JFrame
  private static final long serialVersionUID = 0L;
  private static final int WIDTH = 800;
  private static final int HEIGHT = 600;
  private static final int SPEED = 100;
  private int posX = WIDTH/2;
  private int posY = HEIGHT/2;
  private int vX = 5;
  private BufferedImage buffer = null;
  private Container pane = null;
  private BufferedImage image = null;
  SpaceInvaders() {
    super("Space SpaceInvaders");
    super.setBounds(0, 0, WIDTH, HEIGHT);
    super.setResizable(false);
    super.setIgnoreRepaint(true);
    super.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    super.setLayout(null);
    this.addWindowListener(
      new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
          super.windowClosing(e);
    pane = super.getContentPane();
    pane.setPreferredSize(new Dimension(WIDTH,HEIGHT));
    pane.setLayout(null);
    try {
      image = ImageIO.read(new URL("file:///c:/java/home/src/krc/games/bomb.jpg"));
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException("failed to load image: "+e.toString());
    buffer = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    super.setVisible(true);
  public void paintWorld() {
    Graphics g = buffer.getGraphics();
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    g.drawImage(image, posX, posY, this);
    this.getGraphics().drawImage(buffer, 0, 0, this);
  public void paint(Graphics g){}
  public void update(Graphics g){}
  public void updateWorld() {
    posX += vX;
    if (posX < 0 || posX > WIDTH) {
      vX = -vX;
  public void play() {
    while (super.isVisible()){
      updateWorld();
      paintWorld();
      Thread.currentThread().yield();
      try{Thread.sleep(SPEED);}catch(InterruptedException eaten){}
  public static void main(String args[]) {
    try {
      java.awt.EventQueue.invokeLater(
        new Runnable() {
          public void run() {
            SpaceInvaders game = new SpaceInvaders();
            game.play();
    } catch (Exception e) {
      e.printStackTrace();
}

Similar Messages

  • Why are you asking for my Visa card information when I have a balance on my iTunes gift card?

    Why are you asking for my Visa card information when I have a balance on my iTunes gift card?

    Either because you're trying to buy some sort of gift, or the iTunes Store servers are checking the validity of your account and won't charge the card, or there's a problem at Apple's end.
    (99821)

  • ADOBE DPS tutorial downloads - are there any for indesign CS6?

    ADOBE DPS tutorial downloads - are there any for indesign CS6?
    I am in need of tutorial downloads for indesign to learn more on Adobe DPS. I see the many videos online - but would love to download files and construct the files I see. Can anyone help and advise please.
    thanks: Daryl

    If you want good quality exercise files get a subscription to Lynda.com.
    This link will get you a one week trial to see if it's good for you. You'll
    have to pay for the subscription to get the files: http://bit.ly/RS0GXs

  • Why are the terms for adobe flash player appear to be written in arabic?

    Why are the terms for adobe flash player appear to be written in arabic?

    It opens on the English page for me:
    Some of your systems settings may be incorrect, so it opens on the first (Arabic) page.  But you can always click on the English bookmark to go to the English section.

  • Why are these Webservices not supported in VC ?

    Hi all,
    I am using NW04s SP9, and I plan to make MDM-Application with VC.
    Therefore I introduced MDM-WebService into NW and defined it on VC.
    but "searchRecords" of "MDMSearchRecords" was displayed with "Not supported"
    in the right frame .
    Mmm...
    So I decided to think from a beginning.
    [http://www.27seconds.com/Holidays/US/USHolidayService.asmx?wsdl|http://www.27seconds.com/Holidays/US/USHolidayService.asmx?wsdl]
    I defined above it on VC and I used "Getholidaydate" .
    Good! .
    However,,, "Getholidaysforyear" was also "Not supported".
    Why are these methods "Not supported" ? .
    and how will come to be usable these methods in VC? .
    Thanx in advance.
    Regards,
    k.sugimoto.

    Hi
    Visual Composer supports Web services that are compliant with the Basic Profile 1 standard of the Web Services Interoperability (WS-I) Organization (http://help.sap.com/saphelp_nw70/helpdata/en/e0/92583ab4da4b9cb524f61ba4267d25/content.htm)
    Best regards
    Vincenzo

  • Why are the options for "When Firefox starts" NOT clickable in Firefox 5? I want to choose "Windows and tabs that where opened last time you accessed the net" but Firefox won't let me.

    In the previous version of Firefox one could choose to save tabs so that when Firefox opened, all the tabs from the previous sessions appeared. This was done in Settings > Options > General > Startup. In the menu for the "When Firefox Starts" one had the option for "Windows and tabs that where opened last time you accessed the net." in Firefox 5.0, this menu is gray and not clickable. Help, please?

    ''Why are the options for "When Firefox starts" NOT clickable in Firefox 5?"
    Possibly you are not saving your "browsing history" which is what the session history is tied into.
    '''Not saving History''' -- check your settings for '''Tools > options > Privacy'''', make sure you are not clearing more than just cache in "Settings for Clearing History"
    * http://img232.imageshack.us/img232/4928/clearcachew.png
    * clearing your history at end of session, cache is the only one you would want to clear at end of session, if you don't want to lose things
    There are several things that are related to private browsing and not saving History
    * Private Browsing Ctrl+Shift+P
    * You selected "Never remember history" in first drop-down of Tools > Options Privacy and all of the check marks disappear (See picture above)
    * "Permanent private browsing mode" was check-marked under "Use custom settings for history" in the first drop-down of Tools > options > Privacy (see picture above)

  • TS4337 Why are the colors for my calendar reseting to a color I never chose?

    Why are the colors for my calendar in iCal reseting to a color I never chose?  It won't stay blue when I choose that color and keeps changing to a custom lavendar color on its own....  Incredibly annoying...

    There doesn't seem to be a one-size-fits-all answer, because what works for one printer doesn't necessarily work for another, and I don't have your printer so I can't advise on specifics...
    However, perhaps we can discover a set of settings that will work...
    If you File - Print, choose Photoshop Manages Colors, in the Printer Profile section do you see profiles specific to your printer (e.g., with the name Kodak in them)?
    If so, choose one of them that seems appropriate given the paper you're using.
    If not, try choosing sRGB IEC61966-2.1.
    Now, before you continue, press the [Print Settings...] button.  This brings up the printer driver dialog.  You may have to go through [Advanced] buttons or whatever, but what you're looking to do here is to disable the printer driver's color management logic.  In other words, if you can find a color-management / ICC profile handling section, set it to "no color management" or equivalent.  OK back out to Photoshop's print dialog, then press [Print].
    The key here is that if Photoshop manages the color transforms, the printer driver should not be set to do so - or vice versa.
    If you're presented with the printer driver's dialog again, double check that the settings you chose above are still set, for good measure, and try a test print.
    -Noel

  • F14, F15, F16 -- why are these keys on my Mac Keyboard ?

    *** !!
    Why are these keys added to my Macintosh Keyboard [circa September 2006] if the **** operating system won't allow us to use them ?
    What the **** Apple ??

    My 5+ year old keyboard has the F13 F14 F15 keys sitting all by their lonesome above the help, home, page up block of keys, and I set them to do the three Expose functions, so the system will use them (at least if you have the right hack). All the F keys used to be handier though, back in the OS 9 days, when I assigned them to do all sort of things.
    Francine
    Francine
    Schwieder

  • HT4864 Thank you! This may sound lame but are these instructions for the blackberry? I'm receiving iCloud emails without problems on my MacBook Pro and I'd rather not mess w/ settings there.

    Thank you! This may sound lame but are these instructions for my blackberry? I'm receiving iCloud emails without problems on my MacBook Pro and I'd rather not mess w/ settings there. Thanks again!

    You don't need to start a new thread to continue a conversation, you can just tack onto the original one. The settings I referred you to are for the Blackberry, since that's the device which is not receiving mail: anything which is working can be left alone.

  • What are these files for ACCFinderBundleLoader_64 and ACCFinderBundleLoader_32? They appear in my Launchpad!

    What are these files for ACCFinderBundleLoader_64 and ACCFinderBundleLoader_32? They appear in my Launchpad!
    I am thinking to delete them because they disturb me when they have a place in the Launchpad among my applications.

  • HT4088 This article was no where near the question or problem I had... Are these techs for real? unbeleivable - never mind

    This article was no where near the question or problem I had... Are these techs for real? unbeleivable - never mind

    What are you talking about?

  • Why are there databases for two websites in my appdata roaming firefox default profile folder?

    C:\Users\user\appdata\Roaming\Mozilla\Firefox\Profiles\i4unw84s.default\databases\http_www.fling.com_
    C:\Users\user\appdata\Roaming\Mozilla\Firefox\Profiles\i4unw84s.default\databases\https_cashier.bovada.lv_
    Both of these website databases have 64 KB and are io_temp.sqlite files. I want to know how they were created and what information is being stored there. I know my boyfriend goes on the bovada site alot but want to know if he has personal login info stored for both of these sites. I know they aren't cookies because I saw the list of cookies and deleted them and these files are still there. I really want to know if the only way the websites could be in the folder is because he intentionally saved info stored on those sites and if not, then why are they part of his roaming profile?

    hello, i could find no documentation whatsoever on what the ''databases'' folder within the profile or a ''io_temp.sqlite''-file would do in the context of firefox (maybe this was an early version of ''dom storage'' or ''indexeddb'').
    if you are having questions about the usage of these sites by your boyfriend, you should probably speak with him directly about this, instead of finding an answer this way...

  • Why are people asking for certain model numbers

    why are people asking question such as this ? Hi I was wondering if you could send me the model number of this item I am looking for a specific Model and want to make sure before I bid. The model I'm looking for is G3 the model number will start like this CGN5

    Go to this link and you will see that WRT54G/GS models from version 1 to version 5 are diferent if you look at the amount of RAM and Flash they contain.
    More RAM and Flash is better of course.
    Click here.
    (Mod note: Link edited to prevent the page from stretching.)
    Message Edited by surix on 08-08-2006 06:23 AM
    Message Edited by twenty3 on 08-08-2006 06:30 AM

  • Why are these words not acceptable?

    Following up from another question regarding the frustrating password validation, you answered back that these following words were not acceptable in one's password:
    1234
    4321
    qwert
    test
    skype
    myspace
    password
    abc123
    123abc
    abcdef
    iloveyou
    letmein
    ebay
    paypal
    I understand that it'd be a problem if someone used one of those alone without any prefix or suffix with it, but WHY are you blocking it altogether? Why not allow it at least in middle of a cryptic word, like !@#$skype**&& , or ()()skype<><> ?
    It seems your password validation rules just check for an occurance of those words (some of which are questionable as to why it's blocked in the first place) anywhere in the string.
    Why are you making it hard for your users to come up with a password they can remember?Pretty much every other services (gmail, facebook, twitter, etc.) are equally as important and used (if not more important/used than Skype, on a daily basis) and don't enforce as much password rules and blocked words.
    It would be nice to see Skype go in the direction of 2-step verification like Gmail has.
    Use a simple password, bind a Cell-Phone number to it, get your temporary code via txt-message (if it's your first time on that computer / non-cached in browser), Simple!

    Hi
    Visual Composer supports Web services that are compliant with the Basic Profile 1 standard of the Web Services Interoperability (WS-I) Organization (http://help.sap.com/saphelp_nw70/helpdata/en/e0/92583ab4da4b9cb524f61ba4267d25/content.htm)
    Best regards
    Vincenzo

  • SnippetPreview$.htm - Why are these not being deleted?

    I have the following files in my project folder:
    SnippetPreview$.htm
    SnippetPreview1$.htm
    SnippetPreview2$.htm
    SnippetPreview3$.htm
    SnippetPreview4$.htm
    I noticed them because they are not in Visual SourceSafe so they appear when I go to add files to VSS when I create new snippets. They contain the text of snippets I've created.
    I know they are harmless, but why are they not being automatically deleted from RH when no longer needed?
    Is this a setting or preference I can set?

    Sometimes temporary files are left behind. These are just files created on previewing a snippet and like any other temporary files are not deleted. Just delete them.
      The RoboColum(n)
      @robocolumn
      Colum McAndrew

Maybe you are looking for