So I’ve been making 2D java games with the same setup for a long time but i don’t understand how it works
Here’s the code
package com.dazkins.alone;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.util.Random;
import javax.swing.JFrame;
public class AloneComponent extends Canvas implements Runnable{
private static final int WIDTH = 256;
private static final int HEIGHT = 256;
private static final int SCALE = 3;
private boolean running = false;
private BufferedImage img = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
private int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
public static void main(String args[]){
AloneComponent c = new AloneComponent();
JFrame frame = new JFrame("Alone");
frame.add(c);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
c.start();
}
public AloneComponent(){
Dimension d = new Dimension(WIDTH*SCALE,HEIGHT*SCALE);
setPreferredSize(d);
setMaximumSize(d);
setMinimumSize(d);
}
public void start(){
running = true;
Thread t = new Thread(this);
t.start();
}
public void stop(){
running = false;
}
public void tick(){
}
public void render(){
BufferStrategy bs = getBufferStrategy();
if(bs==null){
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
for(int i=0;i<pixels.length;i++){
pixels[i] = new Random().nextInt(0x0000FF) << 16;
}
g.drawImage(img, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
public void run() {
while(running){
tick();
render();
}
}
}
My question is about that the array of pixels that is used to store colour data for each pixel. I understand how it represents colours, but i don’t understand atall at what part in the code that pixel array is asigned to the BufferedImage or rendered to the screen