Created
March 20, 2018 16:51
-
-
Save demodude4u/09e9093173f9a73ffbbd95c5f925fac8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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