Base Library

I may participate in the competition, so I wanted to declare that I have a template for making simple games (I code in Java and OpenGL) that I’ve made for myself which includes the following classes:

Main.java:

package me.taien;

import static org.lwjgl.opengl.GL11.*;
//import static org.lwjgl.openal.AL10.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.imageio.ImageIO;
import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
//import org.lwjgl.openal.AL;
import org.lwjgl.util.WaveData;
import org.newdawn.slick.TrueTypeFont;
import org.newdawn.slick.openal.Audio;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;

public class Main {

public static Random rand = new Random();
//private static Game game;\

//private static int buffer;
public static final String version = “Alpha v0.1.0”;
public static final DecimalFormat twodecimals = new DecimalFormat(“0.00”);
public static Map<String,Texture> texturemap;
public static Map<String,Audio> audiomap;
public static Map<String,TrueTypeFont> fontmap;
public static ArrayList<DisplayMode>modes;
public static float se_volume;
public static float music_volume;

public static IntBuffer buffer;
public static IntBuffer source;

public static FloatBuffer sourcePos;
public static FloatBuffer sourceVel;
public static FloatBuffer listenerPos;
public static FloatBuffer listenerVel;
public static FloatBuffer listenerOri;

public static void main(String[] args)
{
if (args.length == 1) setupDisplay(false);
else setupDisplay(true);
setupGL();

loadGameData();

//titlescreen = new TitleScreen();
//titleLoop();

//game = new Game(titlescreen.getName(),titlescreen.getLevel(),titlescreen.isCheating());

//gameLoop();
shutdown();
}

public static void testEncrypt() { //TODO turn this into saving/loading code using a key generated the first time someone logs in on their computer; this code is saved in encrypted format as well so people have more difficulty hacking save files
try {
String s = “Hello there. How are you? Have a nice day.”;
// Generate key
KeyGenerator kgen = KeyGenerator.getInstance(“AES”);
kgen.init(128);
SecretKey aesKey = kgen.generateKey();

// Encrypt cipher
Cipher encryptCipher = Cipher.getInstance(“AES/CBC/PKCS5Padding”);
encryptCipher.init(Cipher.ENCRYPT_MODE, aesKey);

// Encrypt
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptCipher);
cipherOutputStream.write(s.getBytes());
cipherOutputStream.flush();
cipherOutputStream.close();
byte[] iv = encryptCipher.getIV();
byte[] encryptedBytes = outputStream.toByteArray();

// Decrypt cipher
Cipher decryptCipher = Cipher.getInstance(“AES/CBC/PKCS5Padding”);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);

// Decrypt
outputStream = new ByteArrayOutputStream();
ByteArrayInputStream inStream = new ByteArrayInputStream(encryptedBytes);
CipherInputStream cipherInputStream = new CipherInputStream(inStream, decryptCipher);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = cipherInputStream.read(buf)) >= 0) {
outputStream.write(buf, 0, bytesRead);
}

System.out.println(“Result: ” + new String(outputStream.toByteArray()));

}
catch (Exception ex) {
ex.printStackTrace();
}
}

public static Texture loadPNGTexture(String key)
{
try {
return TextureLoader.getTexture(“png”, new FileInputStream(new File(“res/” + key + “.png”)));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}

public static WaveData loadWAV(String key)
{
try {
return WaveData.create(new FileInputStream(new File(“res/” + key + “.wav”)));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}

/*private static int loadALData(String key)
{
AL10.alGenBuffers(buffer);
if (AL10.alGetError() != AL10.AL_NO_ERROR)
return AL10.AL_FALSE;

WaveData waveFile;
try {
waveFile = WaveData.create(new FileInputStream(new File(“res/” + key + “.wav”)));
System.out.println(buffer.get(0));
System.out.println(waveFile.format);
AL10.alBufferData(buffer.get(0), waveFile.format, waveFile.data, waveFile.samplerate);
waveFile.dispose();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

AL10.alGenSources(source);
if (AL10.alGetError() != AL10.AL_NO_ERROR)
return AL10.AL_FALSE;

AL10.alSourcei(source.get(0), AL10.AL_BUFFER, buffer.get(0));
AL10.alSourcef(source.get(0), AL10.AL_PITCH, 1f);
AL10.alSourcef(source.get(0), AL10.AL_GAIN, 1f);
AL10.alSource(source.get(0), AL10.AL_POSITION, sourcePos);
AL10.alSource(source.get(0), AL10.AL_VELOCITY, sourceVel);

if (AL10.alGetError() == AL10.AL_NO_ERROR)
return AL10.AL_TRUE;
else
return AL10.AL_FALSE;
}*/

/*private static void setListenerValues()
{
AL10.alListener(AL10.AL_POSITION, listenerPos);
AL10.alListener(AL10.AL_VELOCITY, listenerVel);
AL10.alListener(AL10.AL_ORIENTATION, listenerOri);
}

private static void clearBuffers()
{
AL10.alDeleteSources(source);
AL10.alDeleteBuffers(buffer);
}*/

public static void setupDisplay(boolean windowed)
{
Main.modes = new ArrayList<DisplayMode>();
try {
for (DisplayMode m:Display.getAvailableDisplayModes()) modes.add(m);
DisplayMode cur = Display.getDesktopDisplayMode();
Display.setDisplayMode(cur);
Display.setFullscreen(windowed);
Display.setTitle(“Hyperdrive ” + version);
Display.create();
Display.setVSyncEnabled(true);
Keyboard.create();
Mouse.create();
//AL.create();
//buffer = alGenBuffers();

} catch (LWJGLException e) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
e.printStackTrace();
}
}

public static void setupGL()
{
int i = 4;
for (i = 4; i <6; i++)
{
//blah
}
System.out.println(i);
glEnable(GL_TEXTURE_2D);
glMatrixMode(GL_PROJECTION); //projection mode (stretches stuff)
glLoadIdentity(); //clear projection matrix
glOrtho(0,Display.getWidth(),Display.getHeight(),0,-1,1); //orthographic view (2d) …x,width,y,height,z,depth
glMatrixMode(GL_MODELVIEW); //modelview mode (draws shapes)
glLoadIdentity(); //clear model matrix
glClearColor(0f,0f,0f,1f); //sets transparency color to full black
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST); //disregards information pertinent to 3D only
}

private static void loadGameData()
{

se_volume = 1;
music_volume = 1;

/*texturemap = new HashMap<String,Texture>();
texturemap.put(“loading”, loadPNGTexture(“loading”));

glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();

Draw.rect2D(Display.getWidth()/2, Display.getHeight()/2, 512, 512, texturemap.get(“loading”));

Display.update();
Display.sync(60);*/

//LOAD FONTS
/*GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
Font font;
font = Font.createFont(Font.TRUETYPE_FONT, new File(“res/Hyperspeed.ttf”));
ge.registerFont(font);
font = Font.createFont(Font.TRUETYPE_FONT, new File(“res/Infinite.ttf”));
ge.registerFont(font);
font = Font.createFont(Font.TRUETYPE_FONT, new File(“res/Akashi.ttf”));
ge.registerFont(font);
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}

TrueTypeFont loadfont = new TrueTypeFont(new Font(“Infinite Justice”,Font.PLAIN,32), true);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();

Draw.rect2D(Display.getWidth()/2, Display.getHeight()/2, 512, 512, texturemap.get(“loading”));

loadfont.drawString(Display.getWidth()/2, Display.getHeight()/2 + 256f, “Setting Up Fonts…”, Color.red);

Display.update();
Display.sync(60);

fontmap = new HashMap<String,TrueTypeFont>();

Font font = new Font(“Infinite Justice”,Font.BOLD,20);
fontmap.put(“ij20bold”,new TrueTypeFont(font, true));*/

//LOAD TEXTURES

//player
/*texturemap = new HashMap<String,Texture>();
*texturemap.put(“player”, loadPNGTexture(“player”));*/
/*for (int i = 1; i <= 8; i++)texturemap.put(“playergib” + i, loadPNGTexture(“playergib” + i));*/
//SETUP SOUND

/*audiomap = new HashMap<String,Audio>();

try {
audiomap.put(“activate”,AudioLoader.getAudio(“WAV”, ResourceLoader.getResourceAsStream(“res/” + “activate” + “.wav”)));
} catch (IOException e1) {
e1.printStackTrace();
}*/

//loading done
}

/*private static void titleLoop()
{
while(!Display.isCloseRequested() && !titlescreen.isReady())
{
titlescreen.getInput();
titlescreen.update();

glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
titlescreen.render();
Display.update();
Display.sync(60);

SoundStore.get().poll(0);
}
}*/

/*private static void gameLoop()
{
while(!Display.isCloseRequested())
{
game.getInput();
game.update();

glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
game.render();
Display.update();
Display.sync(60);
}
}*/

public static void shutdown()
{
Display.destroy();
Keyboard.destroy();
Mouse.destroy();
//clearBuffers();
//AL.destroy();
//alDeleteBuffers(buffer);
//AL.destroy();
System.exit(0);
}

public static void takeScreenshot()
{
glReadBuffer(GL_FRONT);
int width = Display.getDisplayMode().getWidth();
int height= Display.getDisplayMode().getHeight();
int bpp = 4; // Assuming a 32-bit display with a byte each for red, green, blue, and alpha.
ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * bpp);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

int shotnum = 1;
File file = new File(System.getProperty(“user.dir”) + “/screenshot1.png”); // The file to save to.
while (file.exists())
{
shotnum++;
file = new File(System.getProperty(“user.dir”) + “/screenshot” + shotnum + “.png”); // The file to save to.
}
String format = “PNG”; // Example: “PNG” or “JPG”
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for(int x = 0; x < width; x++)
for(int y = 0; y < height; y++)
{
int i = (x + (width * y)) * bpp;
int r = buffer.get(i) & 0xFF;
int g = buffer.get(i + 1) & 0xFF;
int b = buffer.get(i + 2) & 0xFF;
image.setRGB(x, height – (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b);
}
try {
ImageIO.write(image, format, file);
} catch (IOException e) { e.printStackTrace(); }
}

}

Draw.java:

package me.taien;

import static org.lwjgl.opengl.GL11.*;

import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;

public class Draw
{
public static void line(float x1, float y1, float x2, float y2, float width, float alpha, float red, float green, float blue)
{
glPushMatrix(); //creates a matrix for this code alone instead of all code being in the same matrix
{
float h = Physics.getDistance(x2 – x1, y2 – y1);

glDisable(GL_TEXTURE_2D);
glEnable(GL_COLOR_MATERIAL);
glTranslatef(x1,y1,0); //shifts drawing
glRotatef(Physics.getRotation(x2 – x1, y2 – y1),0,0,1); //degrees, axes to rotate on
glColor4f(red,green,blue,alpha); //sets color for object (0-1) floating point values

glBegin(GL_QUADS); //being 4 point drawing
{
glVertex2f(-width/2,0);
glVertex2f(-width/2,h);
glVertex2f(width/2,h);
glVertex2f(width/2,0);
}
glEnd(); //end drawing
glDisable(GL_COLOR_MATERIAL);
glEnable(GL_TEXTURE_2D);
}
glPopMatrix(); //populates the matrix into the main matrix
}

public static void rect2D(float x, float y, float w, float h, Texture t)
{
rect2D(x,y,w,h,0,1f,1f,1f,1f,t);
}

public static void rect2D(float x, float y, float w, float h)
{
rect2D(x,y,w,h,0,1f,1f,1f,1f);
}

public static void rect2D(float x, float y, float w, float h, float r, float a, float red, float green, float blue)
{
w /= 2;
h /= 2;
glPushMatrix(); //creates a matrix for this code alone instead of all code being in the same matrix
{
glDisable(GL_TEXTURE_2D);
glEnable(GL_COLOR_MATERIAL);
glTranslatef(x,y,0); //shifts drawing
glRotatef(r,0,0,1); //degrees, axes to rotate on
glColor4f(red,green,blue,a); //sets color for object (0-1) floating point values

glBegin(GL_QUADS); //being 4 point drawing
{
glVertex2f(-w,-h);
glVertex2f(-w,h);
glVertex2f(w,h);
glVertex2f(w,-h);
}
glEnd(); //end drawing
glDisable(GL_COLOR_MATERIAL);
glEnable(GL_TEXTURE_2D);
}
glPopMatrix(); //populates the matrix into the main matrix
}

public static void rect2Dcorner(float x, float y, float w, float h, float r, float a, float red, float green, float blue)
{
glPushMatrix(); //creates a matrix for this code alone instead of all code being in the same matrix
{
glDisable(GL_TEXTURE_2D);
glEnable(GL_COLOR_MATERIAL);
glTranslatef(x,y,0); //shifts drawing
glRotatef(r,0,0,1); //degrees, axes to rotate on
glColor4f(red,green,blue,a); //sets color for object (0-1) floating point values

glBegin(GL_QUADS); //being 4 point drawing
{
glVertex2f(0,0);
glVertex2f(0,h);
glVertex2f(w,h);
glVertex2f(w,0);
}
glEnd(); //end drawing
glDisable(GL_COLOR_MATERIAL);
glEnable(GL_TEXTURE_2D);
}
glPopMatrix(); //populates the matrix into the main matrix
}

public static void rect2D(float x, float y, float w, float h, float r, float a, float red, float green, float blue, Texture t)
{
w /= 2;
h /= 2;

glPushMatrix(); //creates a matrix for this code alone instead of all code being in the same matrix
{
glTranslatef(x,y,0); //shifts drawing
glRotatef(r,0,0,1); //degrees, axes to rotate on
glColor4f(red,green,blue,a); //sets color for object (0-1) floating point values
t.bind();

glBegin(GL_QUADS); //begin 4 point drawing
{
glTexCoord2f(0f,0f);
glVertex2f(-w,-h);
glTexCoord2f(0f,1f);
glVertex2f(-w,h);
glTexCoord2f(1f,1f);
glVertex2f(w,h);
glTexCoord2f(1f,0f);
glVertex2f(w,-h);
}
glEnd(); //end drawing
}
glPopMatrix(); //populates the matrix into the main matrix
}

public static void rect2Dclipped(float x, float y, float w, float h, float r, float a, float red, float green, float blue, Texture t)
{
glPushMatrix(); //creates a matrix for this code alone instead of all code being in the same matrix
{
glTranslatef(x,y,0); //shifts drawing
glRotatef(r,0,0,1); //degrees, axes to rotate on
glColor4f(red,green,blue,a); //sets color for object (0-1) floating point values

t.bind();

float hdiff = t.getImageHeight() – h;
float wpercent = w / t.getImageWidth();
float hpercent = h / t.getImageHeight();
float hpctdiff = 1f-hpercent;

glBegin(GL_QUADS); //begin 4 point drawing
{
glTexCoord2f(0f,hpctdiff);
glVertex2f(0f,hdiff);
glTexCoord2f(0f,1f);
glVertex2f(0f,t.getImageHeight());
glTexCoord2f(wpercent,1f);
glVertex2f(w,t.getImageHeight());
glTexCoord2f(wpercent,hpctdiff);
glVertex2f(w,hdiff);
}
glEnd(); //end drawing
}
glPopMatrix(); //populates the matrix into the main matrix
}

public static void rect2Dclipped(float x, float y, float w, float h, Texture t)
{
glPushMatrix(); //creates a matrix for this code alone instead of all code being in the same matrix
{
glTranslatef(x,y,0); //shifts drawing
glRotatef(0,0,0,1); //degrees, axes to rotate on
glColor4f(1f,1f,1f,1f); //sets color for object (0-1) floating point values

t.bind();

float hdiff = t.getImageHeight() – h;
float wpercent = w / t.getImageWidth();
float hpercent = h / t.getImageHeight();
float hpctdiff = 1f-hpercent;

glBegin(GL_QUADS); //begin 4 point drawing
{
glTexCoord2f(0f,hpctdiff);
glVertex2f(0f,hdiff);
glTexCoord2f(0f,1f);
glVertex2f(0f,t.getImageHeight());
glTexCoord2f(wpercent,1f);
glVertex2f(w,t.getImageHeight());
glTexCoord2f(wpercent,hpctdiff);
glVertex2f(w,hdiff);
}
glEnd(); //end drawing
}
glPopMatrix(); //populates the matrix into the main matrix
}

public static void rect2DclippedCentered(float x, float y, float w, float h, float r, float a, float red, float green, float blue, Texture t)
{
glPushMatrix(); //creates a matrix for this code alone instead of all code being in the same matrix
{
glTranslatef(x,y,0); //shifts drawing
glRotatef(r,0,0,1); //degrees, axes to rotate on
glColor4f(red,green,blue,a); //sets color for object (0-1) floating point values

t.bind();

float hw = w/2;
float hh = h/2;
float hdiff = t.getImageHeight() – h;
float wpercent = w / t.getImageWidth();
float hpercent = h / t.getImageHeight();
float hpctdiff = 1f-hpercent;

glBegin(GL_QUADS); //begin 4 point drawing
{
glTexCoord2f(0f,hpctdiff);
glVertex2f(-hw,hdiff-hh);
glTexCoord2f(0f,1f);
glVertex2f(-hw,t.getImageHeight()-hh);
glTexCoord2f(wpercent,1f);
glVertex2f(hw,t.getImageHeight()-hh);
glTexCoord2f(wpercent,hpctdiff);
glVertex2f(hw,hdiff-hh);
}
glEnd(); //end drawing
}
glPopMatrix(); //populates the matrix into the main matrix
}

public static Color convertToHex(float r, float g, float b)
{
String red = Integer.toHexString((int)(255f * r));
String green = Integer.toHexString((int)(255f * g));
String blue = Integer.toHexString((int)(255f * b));
if (red.length() == 1) red = “0” + red;
if (green.length() == 1) green = “0” + green;
if (blue.length() == 1) blue = “0” + blue;
return Color.decode(“#” + red + green + blue);
}

public static Color getColorByHex(int r, int g, int b)
{
String re;
String gr;
String bl;
re = Integer.toHexString(r);
gr = Integer.toHexString(g);
bl = Integer.toHexString(b);
if (re.length() == 1) re = “0” + re;
if (gr.length() == 1) gr = “0” + gr;
if (bl.length() == 1) bl = “0” + bl;
return Color.decode(“#” + re + gr + bl);
}
}

Physics.java:

package me.taien;

import java.awt.Rectangle;
import java.util.Vector;

import org.lwjgl.util.vector.Vector2f;

public class Physics
{
/*public static boolean checkCollisions(GameObject go1, GameObject go2)
{
Rectangle r1 = new Rectangle((int)go1.getX()-(int)(go1.getWidth()/2), (int)go1.getY()-(int)(go1.getHeight()/2),(int)go1.getWidth(),(int)go1.getHeight());
Rectangle r2 = new Rectangle((int)go2.getX()-(int)(go2.getWidth()/2), (int)go2.getY()-(int)(go2.getHeight()/2),(int)go2.getWidth(),(int)go2.getHeight());

return r1.intersects(r2);
}*/

public static float getRotation(float x, float y)
{
//float hypot =
return ((((float) Math.atan2((double) y, (double) x)) * 57.2957795f) – 90f) % 360f;
//return ((float)Math.atan2(y, x) * 57.2957795f) – 90f;
}

public static float getDistance(float x, float y)
{
return (float)Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
}

public static Vector2f getVector(float x1, float y1, float x2, float y2, float speed)
{
float targetx = x1 – x2;
float targety = y1 – y2;
float speedmod = 0f;
if (Math.abs(targetx) > Math.abs(targety)) speedmod = speed / Math.abs(targetx);
else speedmod = speed / Math.abs(targety);
return new Vector2f(targetx * speedmod, targety * speedmod);
}
}

 

 

 

Comments

12. Dec 2013 · 03:32 UTC
…that’s, uh, a pretty long post. Next time, you might want to post it somewhere else and link to there.
12. Dec 2013 · 05:26 UTC
I added a break in your post as that was a bit too long… Good luck with the LD!