Computer Question (Elementary)-Snowball example code (Java)
The previous section implements the snowball code. This section implements the snowball code. To make a loop, 30 random numbers are generated. The Code is as follows:
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();}}}}}Then run the instance:
At this time, it was not a snowball, but a full screen. Think about what to ask, because each painting will draw a snowball at a brand new position. Therefore, we must prepare 30 random coordinates.
The Code is as follows:
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();}}}
Run the following command:
In this case, it will not be messy. Other ideas can be added and designed by the reader.