[Java] Java二维数组写一个超级简单的扫雷游戏,适合新手

时间:2024-03-28 17:29:13

直接上代码
 

[Java] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

//随机生成地雷数

int numOfMines=10;

//地图尺寸

int mapSize=9;

Random r=new Random();

//用二位数组做地图

int [][] map=new int[mapSize][mapSize];

//地雷周围的偏移量

int[]around={-1,0,1};

//开始生成

for (int i=0;i<numOfMines;i++){

    int x,y;

    do {

        x=r.nextInt(mapSize);

        y=r.nextInt(mapSize);

    }while(map[x][y]>=100);

    //埋雷

    map[x][y]=100;

    //周围的提示

    for (int dy:around){

        for (int dx:around){

            if (dx==0 && dy==0){

                continue;

            }

            if ((x+dx)>=0

                    && (x+dx)<mapSize

                    && (y+dy)>=0

                    && (y+dy)<mapSize){

                try {

                    map[x+dx][y+dy]++;

                } catch (Exception e) {

                    System.out.println(x+dx+"  "+y+dy);

                    e.printStackTrace();

                }

            }

        }

    }

}

for (int y=0;y<mapSize;y++){

    for (int x=0;x<mapSize;x++){

        if (map[x][y]>=100){

            System.out.print("[*]");

        }else if (map[x][y]==0){

            System.out.print("[ ]");

        }else {

            System.out.print("["+map[x][y]+"]");

        }

    }

    System.out.println();

}



[Java] Java二维数组写一个超级简单的扫雷游戏,适合新手