上機題目(初級)- 下雪球執行個體代碼(Java)

來源:互聯網
上載者:User

上機題目(初級)- 下雪球執行個體代碼(Java)

上一節實現了滾雪球的代碼,這一節實現下雪球的代碼,簡單考慮,製造一個迴圈,產生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;@Overridepublic 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);}}@Overridepublic 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);}}@Overridepublic void paint(Graphics g) {g.setColor(Color.WHITE);for (int i = 0; i < x.length; i++) {g.fillOval(x[i], y[i], 20, 20);}}@Overridepublic 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();}}}

運行如下:

 

這時就是不亂了。還有其他創意可以加入,讀者自行設計。
 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.