上一節實現了滾雪球的代碼,這一節實現下雪球的代碼,簡單考慮,制造一個循環,產生30個隨機數,代碼如下:
import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.Panel; public class SnowBall { public static void main(String[] args) { Frame frame=new Frame(); frame.setBackground(Color.BLACK); frame.setSize(1024, 768); MyPanel myPanel=new MyPanel(); frame.add(myPanel); Thread thread=new Thread(myPanel); thread.start(); frame.show(); } } class MyPanel extends Panel implements Runnable{ int y=0; @Override public void paint(Graphics g) { g.setColor(Color.WHITE); for (int i = 0; i < 30; i++) { y=(int)(Math.random()*768); int x=(int)(Math.random()*1024); g.fillOval(x, y, 20, 20); } } @Override public void run() { for (int i = 0; i < 30; i++) { while (true) { y++; if(y>768){ y=0; } repaint(); try { Thread.sleep(700); } catch (InterruptedException e) { e.printStackTrace(); } } } } }這時運行實例:
這時發現不是下雪球,而是滿屏幕亂散。思考一下問什麼,原因是每次paint都會在全新的300個位置畫雪球。因此我們必須要實現准備30個隨機坐標。
代碼如下:
import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.Panel; public class SnowBall { public static void main(String[] args) { Frame frame = new Frame(); frame.setBackground(Color.BLACK); frame.setSize(1024, 768); MyPanel myPanel = new MyPanel(); frame.add(myPanel); Thread thread = new Thread(myPanel); thread.start(); frame.show(); } } class MyPanel extends Panel implements Runnable { int x[] = new int[30]; int y[] = new int[30]; public MyPanel() { for (int i = 0; i < 30; i++) { x[i] = (int) (Math.random() * 1024); y[i] = (int) (Math.random() * 768); } } @Override public void paint(Graphics g) { g.setColor(Color.WHITE); for (int i = 0; i < x.length; i++) { g.fillOval(x[i], y[i], 20, 20); } } @Override public void run() { while (true) { for (int i = 0; i < 30; i++) { y[i]++; if (y[i] > 768) { y[i] = 0; } try { Thread.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } } repaint(); } } }
這時就是不亂了。還有其他創意可以加入,讀者自行設計。