目录
一:案例要求:
二:代码:
三:结果:
一:案例要求:
实现一个控制台下五子棋的程序。用一个二维数组模拟一个15*15路的五子棋棋盘,把每个元素赋值位“┼”可以画出棋盘, “○”代表该交叉点下了一颗白棋子,“●”代表该交叉点下了一颗黑棋子。每次用户输入要下棋的坐标,然后程序显示出下完后的棋盘,默认黑子先行。(选做)
二:代码:
package ceshi;import java.util.Scanner;public class test {static Scanner sc =new Scanner(System.in);public static void main(String[] args) {char[][] qipan=new char[15][15];origin(qipan);//初始化menu(qipan);//打印棋盘int flag=1;int a=-10;int [] a1;char s;while (true) {a1=xia(qipan, flag);//下棋操作(flag)决定下黑棋还是白棋s=flag==1?'●':'○';a=judge(qipan,a1,s);//判断下棋位置是否已有棋子和是否获胜if(a==1){System.out.println("黑棋获胜");break;}if(a==-1){System.out.println("白棋获胜");break;}flag*=-1;}}private static int judge(char[][] qipan,int[] a1,char s) {//判断下棋位置是否已有棋子和是否获胜int n=0,n1=1;int f1=-1,f2=-1;int sizelie=1,sizehang=1,sizexie=1,sizexie1=1;int i=a1[0];int j=a1[1];while(n<5){//列if(i<=0){f1=0;} else if (i==14) {f2=0;}if(f1!=0){if(qipan[i+n1][j]==s){sizelie++;}else{f1=0;}}if(f2!=0){if(qipan[i-n1][j]==s){sizelie++;}else{f2=0;}}if(sizelie>=5){return 1;}n++;n1++;}n=0;n1=1;f1=f2=-1;while(n<5){//行if(j<=0){f1=0;} else if (j==14) {f2=0;}if(f1!=0){if(qipan[i][j-n1]==s){sizehang++;}else{f1=0;}}if(f2!=0){if(qipan[i][j+n1]==s){sizehang++;}else{f2=0;}}if(sizehang>=5){return 1;}n++;n1++;}n=0;n1=1;f1=f2=-1;while(n<5){//斜着if(j<=0||i==0){f1=0;} else if (j==14||i==14) {f2=0;}if(f1!=0){if(qipan[i-n1][j-n1]==s){sizexie++;}else{f1=0;}}if(f2!=0){if(qipan[i+n1][j+n1]==s){sizexie++;}else{f2=0;}}if(sizexie>=5){return 1;}n++;n1++;}n=0;n1=1;f1=f2=-1;while(n<5){//斜着fanif(j==14||i==0){//右上f1=0;} else if (j==0||i==14) {f2=0;}if(f1!=0){if(qipan[i-n1][j+n1]==s){sizexie1++;}else{f1=0;}}if(f2!=0){if(qipan[i+n1][j-n1]==s){sizexie1++;}else{f2=0;}}if(sizexie1>=5){return 1;}n++;n1++;}return 0;}private static int[] xia(char[][] qipan,int flag) {//下棋操作(flag)决定下黑棋还是白棋char s=flag==1?'●':'○';if(s=='●'){System.out.print("请选择'●'的坐标:");}else {System.out.print("请选择'○'的坐标:");}int x=0,y=0;while (true) {x=sc.nextInt();y=sc.nextInt();if(qipan[x][y]!='┼'){System.out.println("该位置已有棋子,请重新输入:");}else{break;}}qipan[x][y]=s;menu(qipan);int[] a={x,y};return a;}private static void menu(char[][] qipan) {System.out.print(" ");for (int i = 0; i < 15; i++) {System.out.print((i+1)+" ");}System.out.println();for(int i=0;i<15;i++){if(i<9)System.out.print(i+1+" ");elseSystem.out.print(i+1+" ");for(int j=0;j<15;j++){System.out.print(qipan[i][j]+" ");}System.out.println();}}private static void origin(char[][] qipan) {//初始化for(int i=0;i<15;i++){for(int j=0;j<15;j++){qipan[i][j]='┼';}}}}