com.telinc1.rpjg.Game.java Source code

Java tutorial

Introduction

Here is the source code for com.telinc1.rpjg.Game.java

Source

/*
 * Copyright 2015-2016 Telinc1
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.telinc1.rpjg;

import java.io.File;
import java.io.IOException;

import org.lwjgl.LWJGLException;
import org.lwjgl.LWJGLUtil;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
import org.pmw.tinylog.Configurator;
import org.pmw.tinylog.Logger;
import org.pmw.tinylog.writers.ConsoleWriter;

import com.telinc1.rpjg.inventory.EnumItemType;
import com.telinc1.rpjg.inventory.item.Item;
import com.telinc1.rpjg.map.Map;
import com.telinc1.rpjg.map.event.player.Player;
import com.telinc1.rpjg.module.Module;
import com.telinc1.rpjg.module.ModuleManager;
import com.telinc1.rpjg.module.ModuleMap;
import com.telinc1.rpjg.reference.ControlKeys;
import com.telinc1.rpjg.reference.ExitCodes;
import com.telinc1.rpjg.reference.GameOptions;
import com.telinc1.rpjg.script.ScriptEngine;
import com.telinc1.rpjg.script.message.EnumMessageType;
import com.telinc1.rpjg.script.message.Message;
import com.telinc1.rpjg.texture.TextureLoader;

public class Game {
    private Player player;
    private Map currentMap;
    private Message openMessage;
    private String lastMap;

    private boolean isRunning;

    private static int lastMouseX;
    private static int lastMouseY;

    private static int mouseX;
    private static int mouseY;

    private static Game instance;

    static {
        System.setProperty("org.lwjgl.librarypath",
                new File(GameOptions.NATIVES_LOCATION + LWJGLUtil.getPlatformName()).getAbsolutePath());
    }

    public static void main(String[] args) throws IOException {
        Game.getGame().start();
    }

    public static Game getGame() {
        if (Game.instance == null) {
            Game.instance = new Game();
        }

        return Game.instance;
    }

    public void start() {
        // Start logging.
        Configurator.defaultConfig().writer(new ConsoleWriter())
                .formatPattern("[{date:yyyy-MM-dd HH:mm:ss}] [{level}] [{class_name}] {message}").activate();
        Logger.info("Creating and initializing game.");

        // Create the display.
        try {
            Display.setTitle(GameOptions.GAME_NAME);
            Display.setResizable(false);
            Display.setDisplayMode(new DisplayMode(640, 360));
            Display.setVSyncEnabled(true);
            Display.setFullscreen(false);

            Display.create();
        } catch (LWJGLException e) {
            e.printStackTrace();
            System.exit(ExitCodes.INIT_DISPLAY);
        } finally {
            this.isRunning = true;
            Logger.info("Finished display creation.");
        }

        // Initialize OpenGL.
        GL11.glEnable(GL11.GL_TEXTURE_2D);
        GL11.glShadeModel(GL11.GL_SMOOTH);
        GL11.glDisable(GL11.GL_DEPTH_TEST);
        GL11.glDisable(GL11.GL_LIGHTING);

        GL11.glClearColor(0f, 0f, 0f, 0f);
        GL11.glClearDepth(1);

        GL11.glEnable(GL11.GL_BLEND);
        GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);

        GL11.glViewport(0, 0, Display.getWidth(), Display.getHeight());
        GL11.glMatrixMode(GL11.GL_MODELVIEW);

        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        GL11.glOrtho(0, Display.getWidth(), Display.getHeight(), 0, 1, -1);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);

        // Load all textures.
        TextureLoader.initialize();

        // Initialize the game.
        this.initialize();

        // Load the default map.
        this.loadMap("dungeon");
        ModuleManager.getInstance().openModule(new ModuleMap());

        // Main game loop
        while (this.isRunning() && !Display.isCloseRequested()) {
            // Clear the screen from the previous frame.
            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);

            this.loop();
            this.draw();
            this.collectInput();

            // Sync and update the display.
            Display.update();
            Display.sync(GameOptions.FRAME_RATE);
        }

        // Free up all resources and exit.
        Logger.info("Close requested!");

        TextureLoader.destroy();
        Display.destroy();

        Logger.info("Resources destroyed - exiting.");
        System.exit(ExitCodes.CLOSE_REQUESTED);
    }

    private void registerItems() {
        new Item(0, "Stick", EnumItemType.NORMAL);
        new Item(1, "Potion", EnumItemType.NORMAL);
        new Item(2, "Potent Potion", EnumItemType.NORMAL);
        new Item(3, "Moste Potente Potion", EnumItemType.NORMAL);
        new Item(4, "Ether", EnumItemType.NORMAL);
        new Item(5, "Potent Ether", EnumItemType.NORMAL);
        new Item(6, "Moste Potente Ether", EnumItemType.NORMAL);
        new Item(7, "King's Crown", EnumItemType.KEY);
    }

    private void initialize() {
        // Register the tiles and the items that are used in the game.
        this.registerItems();

        // Initialize variables.
        Game.mouseX = Game.mouseY = Game.lastMouseX = Game.lastMouseY = 0;
        this.player = new Player(1, 1);
        ScriptEngine.variables[ScriptEngine.PLAYER_FACING] = (short) this.player.getFacingDirection()
                .getDirection();
    }

    public Player getPlayer() {
        return this.player;
    }

    public Map getMap() {
        return this.currentMap;
    }

    public String getLastMapName() {
        return this.lastMap;
    }

    public void loadMap(Map map) {
        this.currentMap = map;
    }

    public void loadMap(String map) {
        this.loadMap(Map.loadMap(map));
    }

    public void openMessage(Message message) {
        if (this.getOpenMessage() != null && message != null) {
            if (this.getOpenMessage().getType().getPriority() > message.getType().getPriority()) {
                return;
            }

            this.getOpenMessage().getGUI().close();
        }

        this.openMessage = message;

        if (this.openMessage != null) {
            this.openMessage.open();
        }
    }

    public void openMessage(String message, EnumMessageType type) {
        this.openMessage(new Message(message, type));
    }

    public void openMessage(String message) {
        this.openMessage(new Message(message, EnumMessageType.BLOCKING));
    }

    public Message getOpenMessage() {
        return this.openMessage;
    }

    public void requestClose() {
        this.isRunning = false;
    }

    public boolean isRunning() {
        return this.isRunning;
    }

    private void loop() {
        ScriptEngine.update();

        if (ModuleManager.getInstance().isModuleActive()) {
            ModuleManager.getInstance().getActiveModule().update();
        }
    }

    private void draw() {
        GL11.glColor4f(1f, 1f, 1f, 1f);
        ModuleManager.getInstance().renderModules();
    }

    private void resize() {
        GL11.glOrtho(0, Display.getWidth(), Display.getHeight(), 0, 1, -1);
    }

    private void collectInput() {
        Game.lastMouseX = Game.mouseX;
        Game.lastMouseY = Game.mouseY;

        Game.mouseX = Mouse.getX();
        Game.mouseY = Display.getHeight() - Mouse.getY();

        int input = 0;

        if (Keyboard.isKeyDown(ControlKeys.MOVE_LEFT))
            input |= 1;
        if (Keyboard.isKeyDown(ControlKeys.MOVE_DOWN))
            input |= 2;
        if (Keyboard.isKeyDown(ControlKeys.MOVE_RIGHT))
            input |= 4;
        if (Keyboard.isKeyDown(ControlKeys.MOVE_UP))
            input |= 8;
        if (Keyboard.isKeyDown(ControlKeys.CONFIRM))
            input |= 16;
        if (Keyboard.isKeyDown(ControlKeys.CANCEL))
            input |= 32;
        if (Keyboard.isKeyDown(ControlKeys.MENU))
            input |= 64;

        ScriptEngine.variables[ScriptEngine.PLAYER_INPUT] = (short) input;

        if (ModuleManager.getInstance().isModuleActive()) {
            Module activeModule = ModuleManager.getInstance().getActiveModule();

            if (Game.mouseX != Game.lastMouseX || Game.mouseY != Game.lastMouseY) {
                activeModule.mouseMoved(Game.mouseX, Game.mouseY);
            }

            if (Keyboard.next()) {
                if (Keyboard.getEventKeyState()) {
                    activeModule.keyPressed(Keyboard.getEventKey());
                } else {
                    activeModule.keyReleased(Keyboard.getEventKey());
                }
            }

            if (Mouse.next()) {
                if (Mouse.getEventButtonState()) {
                    activeModule.mousePressed(Mouse.getEventX(), Display.getHeight() - Mouse.getEventY(),
                            Mouse.getEventButton());
                } else {
                    activeModule.mouseReleased(Mouse.getEventX(), Display.getHeight() - Mouse.getEventY(),
                            Mouse.getEventButton());
                }
            }
        }
    }
}