Main.java
Posted in Text, on August 30, 2010 at 13:43
import java.awt.*;
import java.awt.image.*;
import java.util.Random;
import javax.swing.*;
public class Main
{
public JFrame app;
public static Canvas canvas;
public static boolean running;
public static Graphics graphics;
public static Graphics2D g2d;
public static Color background;
public static Random rand;
public static BufferStrategy buffer;
public static BufferedImage bi;
public static GraphicsEnvironment ge;
public static GraphicsDevice gd;
public static GraphicsConfiguration gc;
public void init()
{
app = new JFrame("CwBunny");
canvas = new Canvas();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setUndecorated(false);
app.setSize(800, 600);
app.addKeyListener(new Keyboard());
canvas.setSize(800, 600);
app.add(canvas);
app.pack();
app.setVisible(true);
canvas.createBufferStrategy(2);
buffer = canvas.getBufferStrategy();
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gd = ge.getDefaultScreenDevice();
gc = gd.getDefaultConfiguration();
bi = gc.createCompatibleImage(800, 600);
graphics = null;
g2d = null;
background = Color.BLACK;
rand = new Random();
running = true;
}
public void gameLoop()
{
int fps = 0;
int frames = 0;
long totalTime = 0;
long curTime = System.currentTimeMillis();
long lastTime = curTime;
while(running)
{
lastTime = curTime;
curTime = System.currentTimeMillis();
totalTime += curTime-lastTime;
if(totalTime>1000)
{
totalTime -= 1000;
fps = frames;
frames = 0;
}
frames++;
g2d = bi.createGraphics();
g2d.setColor(background);
g2d.fillRect(0, 0, app.getWidth(), app.getHeight());
for(int i=0;i<20;i++)
{
Color c = new Color(
rand.nextInt(256),
rand.nextInt(256),
rand.nextInt(256)
);
g2d.setColor(c);
Rectangle r = new Rectangle(
rand.nextInt(app.getWidth()/2),
rand.nextInt(app.getHeight()/2),
rand.nextInt(app.getWidth()/2),
rand.nextInt(app.getHeight()/2)
);
g2d.fill(r);
}
g2d.setFont(new Font("Courier New", Font.PLAIN, 12));
g2d.setColor(Color.GREEN);
g2d.drawString("Fps:" + fps, 20, 20);
graphics = buffer.getDrawGraphics();
graphics.drawImage(bi, 0, 0, null);
if(!buffer.contentsLost())
buffer.show();
running = !((Keyboard)app.getKeyListeners()[0]).escape;
}
}
public void stop()
{
if(graphics!=null)graphics.dispose();
if(g2d!=null)g2d.dispose();
if(app!=null)
{
app.setVisible(false);
app.dispose();
}
}
public static void main(String [] args)
{
Main m = new Main();
m.init();
m.gameLoop();
m.stop();
}
}
Share this code
Use the link below to share the code:
http://www.codesend.com/view/d59f75d816ff50e88a7180945933a605/
HTML
<a href="http://www.codesend.com/view/d59f75d816ff50e88a7180945933a605/">Main.java</a>
BBCode
[url=http://www.codesend.com/view/d59f75d816ff50e88a7180945933a605/]Main.java[/url]
© 2010 CodeSend.com - send code quick and easy
Syntax highlighting by Alex Gorbatchev
Syntax highlighting by Alex Gorbatchev
