test/Game.java

Wed, 10 Jul 2013 18:12:13 +0200

author
Mike Becker <universe@uap-core.de>
date
Wed, 10 Jul 2013 18:12:13 +0200
changeset 18
5085b57e3fd6
parent 17
7ea86024aef0
permissions
-rw-r--r--

fixed highlighting for java

package de.uapcore.threelittlestars;

import java.awt.BorderLayout;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import de.uapcore.threelittlestars.entities.Player;
import de.uapcore.threelittlestars.entities.Player.PlayerCharacter;
import de.uapcore.threelittlestars.managers.AssetManager;
import de.uapcore.threelittlestars.managers.InputManager;
import de.uapcore.threelittlestars.managers.WorldManager;
import de.uapcore.threelittlestars.renderers.GameRenderer;


public class Game implements Runnable {
   
   public static final int TICK_RATE = 32;

   private InputManager im;
   private AssetManager am;
   private WorldManager wm;
   
   private MainFrame frame;
   private MainPanel canvas;

   public Game(MainFrame frame, PlayerCharacter playerCharacter) {

      this.frame = frame;
      canvas = new MainPanel();
      
      am = new AssetManager(canvas);
      wm = new WorldManager(am);
      im = new InputManager();
      
      canvas.setRenderer(new GameRenderer(wm));
      canvas.addKeyListener(im);
      
      frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
      frame.add(canvas, BorderLayout.CENTER);
      frame.pack();
      canvas.requestFocusInWindow();

      try {
         startGame(playerCharacter);
      } catch (IOException e) {
         JOptionPane.showMessageDialog(frame, "Die Weltdaten sind beschÃĪdigt.",
               frame.getTitle(), JOptionPane.ERROR_MESSAGE);
         System.exit(1);
      }
   }
   
   public void startGame(PlayerCharacter character) throws IOException {
      Player.setCharacter(character);
      
      // TODO: asset / savegame loading
      wm.loadAsset("testworld"); // just testing here
      
      new Thread(this).start();
   }
   
   @Override
   public void run() {
      long lastTick = System.currentTimeMillis();
      do {
         long currentTick = System.currentTimeMillis();
         if (currentTick - lastTick >= TICK_RATE) {
            lastTick += TICK_RATE;
            
            // Deliver buffered input events
            im.deliverEvents(wm);
            
            // Call updates
            wm.update();
            
            // Catch other key events
            if (im.isEscapePressed()) {
               frame.setVisible(false);
            }
            
            
            // Repaint canvas
            canvas.repaint();
         }
         Thread.yield();
      } while (frame.isVisible());
      
      // Cleanup stuff
      frame.dispose();
      System.exit(0);
   }

}

mercurial