package com.coffeerpg.engine;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import com.coffeerpg.audio.MusicPlayer;
import com.coffeerpg.camera.GameCamera;
import com.coffeerpg.map.GameMap;
import com.coffeerpg.npc.NPC;
import com.coffeerpg.player.Player;
public class Main extends Applet implements Runnable, KeyListener {
/**
* Required field
*/
private static final long serialVersionUID = 1L;
/** Configuration options **/
public static final int WINDOW_WIDTH = 600, WINDOW_HEIGHT = 500;
// double buffering variables
private Graphics bufferGraphics;
private Image offscreen;
// FPS values
private int FPS = 30;
private int targetTime = 1000 / FPS;
// World map
public static GameMap mainMap;
// Player & NPCS
public static Player p;
public static NPC npc;
// Camera
private GameCamera gameCamera;
// Music & Audio
private static MusicPlayer music;
public void init() {
// load all of the images
new GraphicsLoader(Main.this);
// init the main screen vars
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
offscreen = createImage(getSize().width, getSize().height);
bufferGraphics = offscreen.getGraphics();
/* init the player */
p = new Player(360, 300);
/* init the other GUI elements */
npc = new NPC(690, 420);
/* init the map */
mainMap = new GameMap(this);
addKeyListener(this);
addKeyListener(p);
// load music
music = new MusicPlayer();
gameCamera = new GameCamera(p);
Main.this.requestFocusInWindow();
}
// start the game loop
public void start() {
Thread th = new Thread(this);
th.start();
}
public void destroy() {
//TODO: close
}
public void run() {
long startTime;
long urdTime;
long waitTime;
// lower ThreadPriority
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
// run a long while (true) this means always
while (true) {
startTime = System.nanoTime();
// repaint the applet();
repaint();
urdTime = (System.nanoTime() - startTime) / 1000000;
waitTime = targetTime - urdTime;
try {
Thread.sleep(waitTime);
} catch (Exception e) {
}
// set ThreadPriority to maximum value
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
public void update(Graphics g) {
// update instances
paint(g);
}
public void paint(Graphics g) {
bufferGraphics = offscreen.getGraphics();
// note: center the camera to the player's current location and translate the graphics
gameCamera.centerCamera(p);
bufferGraphics.translate(-gameCamera.getCamX(), -gameCamera.getCamY());
bufferGraphics.clearRect(0, 0, getSize().width, getSize().height);
bufferGraphics.setColor(Color.BLACK);
bufferGraphics.fillRect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
mainMap.update(bufferGraphics);
g.drawImage(offscreen, 0, 0, this);
}
/*********************************************************************/
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_M:
music.setMute();
break;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}