Java數組實現五子棋功能


package ch4;
import java.io.*;

/**
 * Created by Jiqing on 2016/11/9.
 */
public class Gobang {
    // 定義棋盤的大小
    private static int BOARD_SIZE = 15;
    // 定義一個二維數組來充當棋盤
    private String[][] board;
    public void initBoard()
    {
        // 初始化棋盤數組
        board = new String[BOARD_SIZE][BOARD_SIZE];
        // 把每個元素賦為"╋",用於在控制台畫出棋盤
        for (int i = 0 ; i < BOARD_SIZE ; i++)
        {
            for ( int j = 0 ; j < BOARD_SIZE ; j++)
            {
                board[i][j] = "╋";
            }
        }
    }
    // 在控制台輸出棋盤的方法
    public void printBoard()
    {
        // 打印每個數組元素
        for (int i = 0 ; i < BOARD_SIZE ; i++)
        {
            for ( int j = 0 ; j < BOARD_SIZE ; j++)
            {
                // 打印數組元素后不換行
                System.out.print(board[i][j]);
            }
            // 每打印完一行數組元素后輸出一個換行符
            System.out.print("\n");
        }
    }
    public static void main(String[] args) throws Exception
    {
        Gobang gb = new Gobang();
        gb.initBoard();
        gb.printBoard();
        // 這是用於獲取鍵盤輸入的方法
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String inputStr = null;
        // br.readLine():每當在鍵盤上輸入一行內容按回車,用戶剛輸入的內容將被br讀取到。
        while ((inputStr = br.readLine()) != null)
        {
            // 將用戶輸入的字符串以逗號(,)作為分隔符,分隔成2個字符串
            String[] posStrArr = inputStr.split(",");
            // 將2個字符串轉換成用戶下棋的座標
            int xPos = Integer.parseInt(posStrArr[0]);
            int yPos = Integer.parseInt(posStrArr[1]);
            // 把對應的數組元素賦為"●"。
            gb.board[yPos - 1][xPos - 1] = "●";
			/*
			 電腦隨機生成2個整數,作為電腦下棋的座標,賦給board數組。
			 還涉及
				1.座標的有效性,只能是數字,不能超出棋盤范圍
				2.如果下的棋的點,不能重復下棋。
				3.每次下棋后,需要掃描誰贏了
			 */
            gb.printBoard();
            System.out.println("請輸入您下棋的座標,應以x,y的格式:");
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM