使用二維陣列,實作五子棋功能
//使用二維陣列,實作五子棋功能.
//⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑如下圖
public static void main(String[] args) {
String[][] a = new String[15][15];
String[] c = {"⒈", "⒉", "⒊", "⒋", "⒌", "⒍", "⒎", "⒏", "⒐", "⒑", "⒒", "⒓", "⒔", "⒕", "⒖"};
//初始化棋盤
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
//若判斷為棋盤最后一列,則需要將行號c[i]賦值給對應位置,即在最后一列給出行號
//若判斷為棋盤最后一行,則需要將列號c[i]賦值給對應位置,即在最后一行給出列號
//其余位置放置為"十"即可
if (j == a.length - 1) {
a[i][a.length - 1] = c[i];
} else if (i == a.length - 1) {
a[a.length - 1][j] = c[j];
} else {
a[i][j] = "十";
}
System.out.print(a[i][j]);
}
System.out.println();
}
//雙方開始下棋,每下一顆棋子都必須同步更新一次棋盤.
while (true) {
Scanner input = new Scanner(System.in);
for (int i = 0; i <= 1; i++) {
//黑棋先走,即奇數時為黑方下棋,偶數時為白方下棋.
if (i % 2 == 0) {
System.out.println("請黑棋下,他的位置是:");
} else {
System.out.println("請白棋下,他的位置是:");
}
int x = input.nextInt();
int y = input.nextInt();
//判斷用戶目前輸入的位置是否有棋子,若已有棋子則需要重新選擇位置.
if (a[x - 1][y - 1] == "★" || a[x - 1][y - 1] == "☆") {
System.out.println("此處已有棋子,請重新選擇位置");
}
//黑方下的棋子輸出顯示為"★",白方下的棋子輸出顯示為"☆".
if (i % 2 == 0) {
a[x - 1][y - 1] = "★";
} else {
a[x - 1][y - 1] = "☆";
}
//更新列印棋盤.
for (int j = 0; j < a.length; j++) {
for (int k = 0; k < a.length; k++) {
System.out.print(a[j][k]);
}
System.out.println();
}
}
}
}
總結:
用戶的輸贏功能暫時未實作,還需繼續完善.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/225843.html
標籤:java
上一篇:淺談static用法
