import javax.swing.*; import java.awt.*; import java.util.*; // a snow flake is a simple game object which can move around and be drawn class Flake { // position and speed are now doubles private double x, y, dx, dy; // position the snow flake randomly public Flake() { Random r = new Random(); x = r.nextFloat() * 500; y = r.nextFloat() * 500; // these are now pixels / second instead of pixels per frame dx = r.nextFloat() * 50 - 25; dy = r.nextFloat() * 50 + 100; } // draw the snow flake at its position casted as an int public void draw(Graphics g) { g.fillRect((int) x, (int) y, 3, 3); } // update takes the seconds since the last update public void update(double dt) { x += (dx * dt); y += (dy * dt); if (y < 0) { y = 500; } if (y > 500) { y = 0; } if (x < 0) { x = 500; } if (x > 500) { x = 0; } } } class GameWorld extends JComponent { // the array of snow flakes private ArrayList snow; // the time the last time the update runs private long last_time; // build the game world with a certain number of flakes public GameWorld(int count) { // store the current time last_time = new Date().getTime(); // initialize snow flakes snow = new ArrayList<>(count); for (int i = 0; i < count; i++) { snow.add(new Flake()); } } @Override public void paintComponent(Graphics g) { // set the color to light blue and draw the sky g.setColor(new Color(100, 150, 255)); g.fillRect(0, 0, 500, 500); // draw each of the snow flakes to the screen g.setColor(Color.white); for (Flake f : snow) { f.draw(g); } // calculate the number of seconds since the last update long time_now = new Date().getTime(); long elapsed_ms = time_now - last_time; double dt = elapsed_ms / 1000.0; // update each flake with this elapsed time for (Flake f : snow) { f.update(dt); } // save the current time as the last time last_time = time_now; // force an update revalidate(); repaint(); } } public class Snow { public static void main(String args[]) { // create and set up the window. JFrame frame = new JFrame("Snow!"); // make the program close when the window closes frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // add the GameWorld component frame.add(new GameWorld(250)); // display the window. frame.setSize(500, 500); frame.setVisible(true); } }