Smooth scroll

Thought I’d share the code for my smooth scrolling game loop:



import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.event.KeyListener;

/**
 * Main.java - A smooth scrolling game loop.
 * 
 * @author Mario Gianota
 */
public class Main implements KeyListener {
	/*
	 * Colour palette
	 */
    private static Color[] COLORS = new Color[] {
        Color.red, Color.blue, Color.green, Color.white, Color.black,
        Color.yellow, Color.gray, Color.cyan, Color.pink, Color.lightGray,
        Color.magenta, Color.orange, Color.darkGray };
    
    Frame mainFrame;
    long lastTime;
    int fps;
    int frameCounter;
    long elapsedTime;
    long delayTime = 0;
    Rectangle rect;
    
    public Main(GraphicsDevice device) {
        try {
            // Setup the frame
            GraphicsConfiguration gc = device.getDefaultConfiguration();
            
            mainFrame = new Frame(gc);
            mainFrame.setUndecorated(true);
            mainFrame.setIgnoreRepaint(true);
            mainFrame.setVisible(true);
            mainFrame.setSize(640, 480);
            mainFrame.setLocationRelativeTo(null);
            mainFrame.createBufferStrategy(3);
            mainFrame.addKeyListener(this);
            
            // Cache the buffer strategy and create a rectangle to move
            BufferStrategy bufferStrategy = mainFrame.getBufferStrategy();
            rect = new Rectangle(0, 100, 50, 50);
            
            // Main loop

            while(true) {
                long time = System.nanoTime();
                calculateFramesPerSecond();
                
                // Update rectangle co'ords
                rect.x+=4;
                
                if( rect.x > mainFrame.getWidth() )
                    rect.x = -rect.width;
                
                // Draw
                Graphics g = bufferStrategy.getDrawGraphics();
                drawScreen(g);
                g.dispose();
                
                // Flip the buffer
                if( ! bufferStrategy.contentsLost() )
                    bufferStrategy.show();

                // Delay for a period of time equal to 1/60th of a
                // second minus the elapsed time
                elapsedTime = System.nanoTime() - time;
                delayTime = 1000000000L/60 - elapsedTime;
                time = System.nanoTime();
                while( System.nanoTime() - time <= delayTime)
                    ;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            device.setFullScreenWindow(null);
        }
        
    }
    private void drawScreen(Graphics g) {
        g.setColor(COLORS[1]);
        g.fillRect(0, 0, 640, 480);
        g.setColor(COLORS[3]);
        g.drawString("FPS: "+ fps, 0, 17);
        g.setColor(COLORS[0]);
        g.fillRect(rect.x, rect.y, rect.width, rect.height);
    }
    private void calculateFramesPerSecond() {
        long time = System.nanoTime();
        if( time - lastTime >= 1000000000L ) {
            fps = frameCounter;
            lastTime = time; 
            frameCounter = 0;
        }
        frameCounter++;
    }
    public void keyPressed(KeyEvent e) {
        if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
            System.exit(0);
        }
    }
    public void keyReleased(KeyEvent e) {
        
    }
    public void keyTyped(KeyEvent e) {
        
    }
    public static void main(String[] args) {
        try {
            GraphicsEnvironment env = GraphicsEnvironment.
                getLocalGraphicsEnvironment();
            GraphicsDevice device = env.getDefaultScreenDevice();
            Main test = new Main(device);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Have fun.

–Mario

NB: there is a better place to post shared code : Shared Code Board

u could also make a tutorial :). I think there is a tutorial board

A tutorial!? I’d have to go back to square one, fifteen years ago sitting in a comp sci. computer room drumming my fingers on the desk waiting for the download link for The Java Programming Language to appear. :smiley:

Believe it or not, the smooth scroll code above is very nearly fifteen years old. Because of it’s age it is extremely reliable. The most recent change was made when Javasofct released the system nanotimer. But since then the code has remained largely unchanged.

IMO the best tutorials are those that just show the code interspersed with a few comments. I never read most of the verbiage on the Java tutorial site, I normally go straiight for the section of code I am interested in and copy and paste the chunk into whatever piece of software I happen to be working on.

Oh, just one rather big thing to point out about the smooth scroll code: I’ve never written a full game in Java and released it so feel free to shoot me down in flames.

–Mario

We had a similar topic last year, evaluating few gameloops. What I prefer is a game loop that does not eat 100% CPU. After all most java games a small “flash” games so should behave well.

I run a test through your code, but added Thread.sleep(10) to yield a cpu. Animation was still quite good.