数组综合应用(五子棋)
package com.qf.test;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int length = 20;
String[][] gobang = new String[length][length];
String[] nums = {"⒈","⒉","⒊","⒋","⒌","⒍","⒎","⒏","⒐","⒑","⒒","⒓","⒔","⒕","⒖","⒗","⒘","⒙","⒚","⒛"};
String add = "┼";
String black = "●";
String white = "○";
for (int i = 0; i < gobang.length; i++) {
for (int j = 0; j < gobang[i].length; j++) {
if(j == length-1){
gobang[i][j] = nums[i];
}else if(i == length-1){
gobang[i][j] = nums[j];
}else{
gobang[i][j] = add;
}
}
}
for (String[] strings : gobang) {
for (String str : strings) {
System.out.print(str);
}
System.out.println();
}
Scanner scan = new Scanner(System.in);
boolean flag = true;
while(true){
System.out.println("请" + ((flag)?"黑":"白") + "子输入坐标:");
int x = scan.nextInt() - 1;
int y = scan.nextInt() - 1;
if(x<0 || x>length-2 || y<0 || y>length-2){
System.out.println("坐标错误 - 坐标超出棋盘范围,请重新输入");
continue;
}
if(!gobang[x][y].equals(add)){
System.out.println("坐标错误 - 坐标上已有棋子,请重新输入");
continue;
}
String piece = (flag)?black:white;
gobang[x][y] = piece;
for (String[] strings : gobang) {
for (String str : strings) {
System.out.print(str);
}
System.out.println();
}
boolean leftAndRight = leftAndRight(x, y, piece, gobang, length);
if(leftAndRight){
System.out.println(((flag)?"黑":"白") + "子赢");
break;
}
flag = !flag;
}
}
public static boolean leftAndRight(int x,int y,String piece,String[][] gobang,int length){
int count = 1;
while(y > 0){
y--;
if(gobang[x][y].equals(piece)){
count++;
}else{
break;
}
}
while(y < length-2){
y++;
if(gobang[x][y].equals(piece)){
count++;
}else{
break;
}
}
if(count >= 5){
return true;
}
return false;
}
}