数组实例——实现棋盘落子

五子棋、连连看、俄罗斯方块、扫雷等常见小游戏,都可以通过二维数组实现。

棋盘落子效果图:

 

     

 

源码:

 1 package my_package;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 
 7 public class Gobang {
 8     //定义棋盘大小为15*15
 9     private static int BOARD_SIZE=15;
10     //定义一个二维数组来充当棋盘
11     private static String[][] board;
12 
13     //初始化棋盘数组
14     public void  initBoard(){
15         board=new String[BOARD_SIZE][BOARD_SIZE];
16         //把每个元素赋为“十”
17         for(int i=0;i<15;i++){
18             for(int j=0;j<15;j++){
19                 board[i][j]="十";
20             }
21         }
22     }
23 
24     //在控制台打印棋盘
25     public void printBoard(){
26         for(int i=0;i<15;i++){
27             for(int j=0;j<15;j++){
28                 System.out.print(board[i][j]);
29             }
30             //打印完一行后换行
31             System.out.print("\n");
32         }
33     }
34 
35     public static void main(String[] args) throws IOException {
36         Gobang gb=new Gobang();
37         gb.initBoard();
38         gb.printBoard();
39 
40         //接收控制台输入棋盘坐标
41         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
42         String str=null;
43         System.out.println("请输入落子点的坐标:");
44         while((str=br.readLine()) !=  null){
45             String[] arr=str.split(",");
46             int x=Integer.parseInt(arr[0]);
47             int y=Integer.parseInt(arr[1]);
48 
49             //需要先判断该点是否已有子,若已有子,则不能再落子。此处省略
50 
51             board[x-1][y-1]="●";
52             //刷新
53             gb.printBoard();;
54 
55             //每次落子后需判断输赢,进行4次循环扫描,横、竖、左斜、右斜,看是否有5子连着,没有就接着下。此处省略
56 
57             System.out.println("请输入落子点的坐标:");
58         }
59     }
60 
61 
62 }

猜你喜欢

转载自www.cnblogs.com/chy18883701161/p/10852248.html