Subscribe to Dogstopper's Code Mania        RSS Feed
***** 2 Votes

Structure Of A Game

Icon Leave Comment
Following the posting of my previous entry, I realized I had not talked about the simple things. My bad. Let me try this again. This tutorial explains the general structure that a Java Game *should* have. On the far outside, there is a JFrame that contains a JPanel. The JFrame manages things like size, location on screen, what happens on close, and general maintenance things like that.

This structure allows for a more smooth transition into managing things like State Machines. Let's look at an example. All it is is a blue background and a blue ball, BUT it will be in the structure that I am trying to impress on you.
JFrame:
public class GameFrame extends JFrame {

	// Have these set up so they can be seen everywhere
	public static final int GAMEWIDTH = 640;
	public static final int GAMEHEIGHT = 480;

	public GameFrame() {
		super("Game Example");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(GAMEWIDTH, GAMEHEIGHT);

		// Add our custom panel
		GamePanel panel = new GamePanel();
		add(panel, BorderLayout.CENTER);

		setVisible(true);
	}

	public static void main(String[] args) {
		new GameFrame();
	}

}



And here is the Panel
class GamePanel extends JPanel {
 
	// This method allows us to paint.
	public void paintComponent(Graphics g) {
		g.setColor(Color.blue);

		// Paint as background
		g.fillRect(0, 0, GameFrame.GAMEWIDTH, GameFrame.GAMEHEIGHT);

		// Paint a circle
		g.setColor(Color.red);
		g.fillOval(30, 30, 200, 200);
	}

}



Now that this structure has been established, adding in extra features is much easier!

0 Comments On This Entry

 

March 2020

S M T W T F S
1234567
891011121314
15161718192021
22232425262728
29 30 31    

Recent Entries

Search My Blog

Recent Comments

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)