本文主要是介绍五子棋(二维数组),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
五子棋(二维数组)
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;//true-黑子 false-白子while(true){//输入坐标System.out.println("请" + ((flag)?"黑":"白") + "子输入坐标:");int x = scan.nextInt() - 1;//-1是因为用户看到的界面是坐标(从1开始),数组是下标(从0开始)int y = scan.nextInt() - 1;//-1是因为用户看到的界面是坐标(从1开始),数组是下标(从0开始)//判断下标是否在棋盘范围内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;}}
这篇关于五子棋(二维数组)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!