五子棋(二维数组)
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;
int index = y;
while(index > 0){
index--;
if(gobang[x][index].equals(piece)){
count++;
}else{
break;
}
}
index = y;
while(index < length-2){
index++;
if(gobang[x][index].equals(piece)){
count++;
}else{
break;
}
}
index = x;
while(index >0){
index--;
if(gobang[index][y].equals(piece)){
count++;
}else{
break;
}
}
index = x;
while(index < length-2){
index++;
if(gobang[x][index].equals(piece)){
count++;
}else{
break;
}
}
index = x;
int index1= y;
while(index < length-2 && index1 <length-2){
index++;
index1++;
if(gobang[index][index1].equals(piece)){
count++;
}else{
break;
}
}
index = x;
index1= y;
while(index >0 && index1 < length-2 ){
index--;
index1++;
if(gobang[index][index1].equals(piece)){
count++;
}else{
break;
}
}
index = x;
index1= y;
while(index >0 && index1 > 0){
index--;
index1--;
if(gobang[index][index1].equals(piece)){
count++;
}else{
break;
}
}
index = x;
index1= y;
while(index < length-2 && index1 > 0){
index++;
index1--;
if(gobang[index][index1].equals(piece)){
count++;
}else{
break;
}
}
if(count >= 5){
return true;
}
return false;
}
}