Description

This is the matrix-rain-screensaver from the "Matrix" movie in Java. I solved it in 66 lines of code using only the default Java libraries.


Source Code

import javax.swing.JFrame; import java.awt.Color; import java.awt.image.BufferedImage; import java.awt.Graphics2D; import java.awt.Toolkit; import java.awt.Point; public class Matrix extends JFrame { private static Graphics2D g; private BufferedImage frame; private final int cx = Toolkit.getDefaultToolkit().getScreenSize().width, cy = Toolkit.getDefaultToolkit().getScreenSize().height; public static void main(String[] args) { Matrix m = new Matrix(); } public Matrix() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setExtendedState(JFrame.MAXIMIZED_BOTH); setUndecorated(true); getContentPane().setBackground(Color.BLACK); getContentPane().setCursor(Toolkit.getDefaultToolkit().createCustomCursor(new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB), new Point(0, 0), "")); setVisible(true); frame = new BufferedImage(cx, cy, BufferedImage.TYPE_INT_RGB); // TYPE_3BYTE_BGR is slow g = (Graphics2D)frame.getGraphics(); run(); } public void run() { double st; int th=14, tw=12, br, n=-255, f=30; // text height and width in pixels, current sign brightness, rain density, number of randomly flipped signs per frame char[][] m = new char[(cx-tw)/tw+1][(cy-th)/th+1]; float[] b = new float[(cx-tw)/tw+1], s = new float[(cx-tw)/tw+1]; for(int x=0; x<m.length; x++) { b[x] = (float)(Math.random()*(255-n)+n); s[x] = (float)(Math.random()*3+1); for(int y=0; y<m[0].length; y++) m[x][y] = (char)(Math.random()*(19893-13318)+13318); } while(true) { st = time(); for(int x=0; x<m.length; x++) { b[x] -= s[x]; if(b[x] < n) b[x] = 255; for(int y=0; y<m[0].length; y++) { br = (int)b[x] + 3*y; if(br > 255) br -= (255-n); if(br>=253&&br<=255) { m[x][y] = (char)(Math.random()*(19893-13318)+13318); g.setColor(new Color(200, 255, 200)); } else g.setColor(new Color(0, br>0?br:0, 0)); g.drawString("" + m[x][y], x*tw, (y+1)*th); } } for(int i=0; i<f; i++) m[(int)(Math.random()*m.length)][(int)(Math.random()*m[0].length)] = (char)(Math.random()*(19893-13318)+13318); this.getGraphics().drawImage(frame, 0, 0, null); g.clearRect(0, 0, cx, cy); pause(1.0/60.0-time()+st); } } public double time() { return System.nanoTime()*1E-9; } public void pause(double s) { if(s > 0) { try { Thread.sleep((int)(s*1E3)); } catch(Exception e) {} } } }

Download

Matrix.jar