1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
| import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Main extends Canvas implements Runnable {
private static final long serialVersionUID = 1L; public Thread thread; public int width = 150, height = (width / 10) * ((10 / 3) * 2), scale = 6; public static String title = "Pixels[][]"; public boolean run = false; public int finalFrames = 0; public int[][] pixels; public Render r; public BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
public Main() { setPreferredSize(new Dimension(width * scale, height * scale)); pixels = new int[width][height]; for (int x = 0; x < pixels.length; x++) { for (int y = 0; y < pixels[0].length; y++) { pixels[x][y] = 0xffffff; } } r = new Render(this, pixels, scale); }
public void tick() { r.tick(); pixels = r.getPixels(); for (int x = 0; x < pixels.length; x++) { for (int y = 0; y < pixels[0].length; y++) { img.setRGB(x, y, pixels[x][y]); } } }
public void render(Graphics g) { g.drawImage(img, 0, 0, getWidth(), getHeight(), null); }
public void draw() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); return; }
Graphics g = bs.getDrawGraphics(); g.clearRect(0, 0, getWidth(), getHeight()); render(g); g.setFont(new Font("Arial", Font.BOLD, 12)); g.setColor(Color.BLACK); g.drawString("FPS : " + finalFrames, 0, 10);
bs.show(); g.dispose(); }
public void run() { long lastTime = System.nanoTime(); final double amountOfTicks = 60.0; double ns = 1000000000 / amountOfTicks; double delta = 0; int ticks = 0; int frames = 0; long timer = System.currentTimeMillis();
while (run) { long now = System.nanoTime(); delta += (now - lastTime) / ns; lastTime = now; if (delta >= 1) { tick(); ticks++; delta--; } draw(); frames++; if (System.currentTimeMillis() - timer > 1000) { timer += 1000; finalFrames = frames; frames = 0; ticks = 0; } } }
public synchronized void start() { run = true; thread = new Thread(this); thread.start(); }
public synchronized void stop() { run = false; try { thread.join(); } catch (InterruptedException e) { System.out.println("ERROR can not stop the thread!"); } System.exit(0); }
public static void main(String[] args) { JFrame jf = new JFrame(); Main m = new Main(); jf.add(m); jf.pack(); jf.requestFocus(); jf.setTitle(title); jf.setVisible(true); jf.setResizable(false); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setLocationRelativeTo(null); m.start(); } } |