一.数组的维数
假象:一维数组
二维数组:数组中的元素是一维数组
二.五子棋游戏
import javax.swing.*;
public class Array06 {
static String[][] matrix = new String[15][15];
static String black = "⚫";
static String white = "⚪";
static boolean blackOrWhite = true; //默认为黑棋
public static void main(String[] args) {
init();
draw();
play();
}
public static void init(){
for (int i = 0;i < 15;i++){
for (int j = 0;j < 15;j++){
matrix[i][j] = "+";
}
}
}
//画出一个棋盘,并将+号存入二维数组
public static void draw(){
for (int i = 0;i < 15;i++){
System.out.print("\t" + i);
}
System.out.println();
for (int i = 0;i < 15;i++){
System.out.print(i);
for (int j = 0;j < 15;j++){
System.out.print("\t" + matrix[i][j]);
}
System.out.println();
}
}
public static void play(){
while (true) {
String player = blackOrWhite ? "黑棋" : "白棋";
String input = JOptionPane.showInputDialog("请" + player + "请输入落子方位(例如[2,3])");
// System.out.println(input);
String[] split = input.split(",");
int x = Integer.parseInt(split[0]);
int y = Integer.parseInt(split[1]);
if (x > 15||y > 15||x < 0||y < 0){
JOptionPane.showMessageDialog(null,"落子方位超出范围");
}
System.out.println("坐标(" + x + "," + y + ")");
matrix[x][y] = blackOrWhite ? black : white;
draw();
System.out.println(horizontalWin(matrix[x][y],x,y));
blackOrWhite = !blackOrWhite;
}
}
public static boolean horizontalWin(String color,int x,int y){
int result = 1;
int left = y;
int right = x;
while (left > 0){
if (result >= 3) return true;
if (matrix[x][--left].equals(color)){
result++;
}
}
while (right < 14){
if (result >= 3) return true;
if (matrix[x][++right].equals(color)){
result++;
}
}
return false;
}