Hi,
Got something working in simulation I’ve done in Swing - hope this helps somebody else, seems ok, of course cannot do real water simulation
as would take some much cpu time up and I’ve not got the math/physics brain for that! Code checked but still could have some bugs in it, anybody improve
it, please let me know!
Thanks
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.*;
public class MainAc extends JFrame {
static final int WATER = 8;
static final int AIR = 0;
static final int ROCK = 1;
static final int WIDTH = 12;
static final int HEIGHT = 12;
static final int FRAME = 1 * 400;
static int[][] map = {
{ 1, 8, 0, 0, 0, 0, 0, 0, 0, 8, 0, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1 },
{ 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
};
public static void main(String[] args) {
new MainAc();
}
public MainAc() {
super("Water fluid simulation attempt 1");
setSize(800,800);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
while (true) {
try {
Thread.sleep(FRAME);
} catch (InterruptedException e) {
e.printStackTrace();
}
moveWater();
repaint();
}
}
public void paint(Graphics g) {
super.paint(g);
drawMap(g);
}
private void moveWater() {
for (int y = HEIGHT-1; y >= 0; y--) {
for (int x = 0; x < WIDTH-1; x++) {
if (map[y][x] == WATER) {
if (map[y + 1][x] == AIR) {
map[y][x] = AIR;
map[y + 1][x] = WATER;
}
else if (map[y][x-1] == AIR) {
map[y][x] = AIR;
map[y][x-1] = WATER;
}
else if (map[y][x+1] == AIR) {
map[y][x] = AIR;
map[y][x+1] = WATER;
}
}
else
{ // air to the right and water left
if( (map[y][x+1]==AIR) && (map[y][x]==WATER)) {
map[y][x]=AIR;
map[y][x+1]=WATER;
}
else if ( x > 0) {
if( (map[y][x-1]==AIR) && (map[y][x]==WATER)) {
map[y][x]=AIR;
map[y][x-1]=WATER;
}
}
}
}
}
}
private void drawMap(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
for (int y = 0; y < HEIGHT; y++)
for (int x = 0; x < WIDTH; x++) {
switch (map[y][x]) {
case ROCK:
g2d.setColor(Color.orange);
g2d.fillRect(x * 50, 50 + y * 50, 49, 49);
break;
case WATER:
g2d.setColor(Color.blue);
g2d.fillRect(x * 50, 50 + y * 50, 49, 49);
break;
case AIR:
g2d.setColor(Color.BLACK);
g2d.fillRect(x * 50, 50 + y * 50, 49, 49);
break;
}
}
}
}