Skip to content

Instantly share code, notes, and snippets.

@demodude4u
Created March 20, 2018 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save demodude4u/09e9093173f9a73ffbbd95c5f925fac8 to your computer and use it in GitHub Desktop.
Save demodude4u/09e9093173f9a73ffbbd95c5f925fac8 to your computer and use it in GitHub Desktop.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
public class Java2DGameTemplate {
public static void main(String[] args) throws InterruptedException {
// Initialize the window and canvas
JFrame frame = new JFrame();
Canvas canvas = new Canvas();
canvas.setPreferredSize(new Dimension(512, 512));
frame.getContentPane().add(canvas);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
// Wait for the canvas to be ready
while (canvas.getBufferStrategy() == null) {
canvas.createBufferStrategy(2);
Thread.yield();
}
// TODO Initialize game variables
//int counter = 0; // Example
// Game and Render Loop
while (true) {
// TODO Put game logic here
//counter++; // Example
// Grab a drawing context
BufferStrategy bufferStrategy = canvas.getBufferStrategy();
Graphics g = bufferStrategy.getDrawGraphics();
//Get the width and height of the canvas
int width = canvas.getWidth();
int height = canvas.getHeight();
// Clear the frame with a background color
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
// TODO Put game rendering here
//g.setColor(Color.black); // Example
//g.drawString("Counter: " + counter, 20, 20); // Example
//g.drawLine(counter % width, 0, counter%width, height); //Example
//g.drawRect(width/4, height/4, width/2, height/2); //Example
// Release the drawing context and update the canvas
g.dispose();
bufferStrategy.show();
// Wait the loop so it doesn't go too fast
Thread.sleep(20);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment