Paso 4: A partir de simples
Ahora comenzaremos a programar! * y hubo mucho regocijo * (disculpen el humor casposo de Monty Python)
Vamos a empezar con la construcción de la clase principal, que llamé TopClass, y construiremos apenas el esqueleto como ven a continuación. Todo esto lo hace hasta ahora es crear un marco de pantalla completa con ningún contenido.
El método principal simplemente crea un nuevo subproceso desde que funciona la creación de GUI y general función del juego. Necesita ejecutar el juego en otro hilo para permitir que la GUI que permanezca funcional. Si no haces esto, el bucle de juego encerrar la interfaz, que no permite al usuario cerrar el programa mientras jugaba el juego.
Los comentarios deben explicar el resto del código.
import java.awt.Dimension; import java.awt.Image; import java.awt.Toolkit; import javax.swing.*; public class TopClass { //global constant variables private static final int SCREEN_WIDTH = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth(); private static final int SCREEN_HEIGHT = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight(); //global variables //global swing objects private JFrame f = new JFrame("Flappy Bird Redux"); //other global objects private static TopClass tc = new TopClass(); /** * Default constructor */ public TopClass() { } /** * Main executable method invoked when running .jar file * args */ public static void main(String[] args) { //build the GUI on a new thread javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { tc.buildFrame(); //create a new thread to keep the GUI responsive while the game runs Thread t = new Thread() { public void run() { //in here we will call a function to start the game } }; t.start(); } }); } /** * Method to construct the JFrame and add the program content */ private void buildFrame() { Image icon = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/blue_bird.png")); f.setContentPane(createContentPane()); //adds the main content to the frame f.setResizable(true); //true, but game will not function properly unless maximized! f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setAlwaysOnTop(false); f.setVisible(true); f.setMinimumSize(new Dimension(SCREEN_WIDTH*1/4, SCREEN_HEIGHT*1/4)); //set to prevent collapse to tiny window upon resizing f.setExtendedState(JFrame.MAXIMIZED_BOTH); //maximize the JFrame f.setIconImage(icon); //set the icon } private JPanel createContentPane() { topPanel = new JPanel(); //top-most JPanel in layout hierarchy return topPanel; //return a blank panel } }