I'm tasked with creating a program in java which shows falling snow in a console that was given to us from university. I started with creating random snowflakes at the top of the screen, which are supposed to move downwards until they hit the bottom of the console.
My idea was to create a two-dimensional boolean array which represents the console-fields (80x25) and then looping through it via nested for-loops and printing "*" every time a field is true and then setting the current field to false and the next one (vertical) to true, so that it looks like the snowflake is moving downwards.
Unfortunately though it only shows one snowflake at a time which runs from top to bottom into an OutOfBoundsException.
It is supposed to spawn one snowflake, move it down 2 or 3 lines and then spawning the next one etc.
I've been trying to figure it out for at least 2 days but I just can't get it to work :/
import java.awt.*;
public class Snow {
public static final int WIDTH = 80;
public static final int HEIGHT = 25;
public static void checkSnowflakes(boolean[][] snow) {
for (int i = 0; i < WIDTH; i++) {
for (int j = 0; j < HEIGHT; j++) {
if (snow[i][j]) {
Console.gotoXY(i, j);
Console.write("*");
Console.wait(50);
snow[i][j + 1] = true;
}
snow[i][j] = false;
if (!snow[i][j]) {
Console.gotoXY(i, j);
Console.write(" ");
}
}
}
}
public static void main(String[] args) {
boolean[][] snow = new boolean[WIDTH][HEIGHT];
Console.showCursor(false);
Console.setBackground(Color.black);
// run endlessly
while (true) {
// Generate new Snowflakes at the top of the console
int rnd = (int) (Math.random() * 80);
snow[rnd][0] = true;
checkSnowflakes(snow);
}
}
}
Aucun commentaire:
Enregistrer un commentaire