I think I have found my new favorite Java game boilerplate (starting template).
Here is it in all it’s glory:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.util.Random; import javax.swing.JFrame; public class Game extends Canvas implements Runnable { private static final long serialVersionUID = 1L; public static final String NAME = "untitled"; public static final int HEIGHT = 160; public static final int WIDTH = HEIGHT * 16 / 9; public static final int SCALE = 4; private BufferedImage image = new BufferedImage( WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB ); private int[] pixels = ( ( DataBufferInt ) image.getRaster().getDataBuffer() ).getData(); private boolean running = false; public void start () { running = true; new Thread( this ).start(); } public void stop () { running = false; } public void run() { while ( running ) { render(); } } public void render () { Random rand = new Random(); BufferStrategy bs = getBufferStrategy(); if ( bs == null ) { createBufferStrategy( 3 ); return; } // for loop not part of boilerplate... It makes some nice static though for ( int i = 0; i < pixels.length; i++ ) { pixels[i] = rand.nextInt() & 0xffffff; } Graphics g = bs.getDrawGraphics(); g.drawImage( image, 0, 0, getWidth(), getHeight(), null ); g.dispose(); bs.show(); } public static void main ( String[] args ) { Game game = new Game(); game.setMinimumSize( new Dimension ( WIDTH * SCALE, HEIGHT * SCALE ) ); game.setMaximumSize( new Dimension ( WIDTH * SCALE, HEIGHT * SCALE ) ); game.setPreferredSize( new Dimension ( WIDTH * SCALE, HEIGHT * SCALE ) ); JFrame frame = new JFrame( Game.NAME ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.setLayout( new BorderLayout() ); frame.add( game, BorderLayout.CENTER ); frame.pack(); frame.setLocationRelativeTo( null ); frame.setResizable( false ); frame.setVisible( true ); game.start(); } } |