使用二维数组,实现五子棋功能
使用二维数组生成如下图:
在控制台通过Scanner输入黑白棋坐标),使用实心五角星和空心五角星表示黑白棋子.
输入后重新输出棋盘如下图:
黑白棋依次重复输入下棋,当任意一方构成五子相连时提示胜利,结束游戏.
代码入下:
public class WuZiqi {
static int i,j;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int num = 15;
int [][] a = new int[num][num];
int b=0;
while (true){
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] == 0) {
System.out.print("十");
}else if (a[i][j] == 1) {
System.out.print("★");
}else if (a[i][j] == 2){
System.out.print("☆");
}
}
System.out.println();
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] == 1 &&a[i][j+1] == 1 &&a[i][j+2] == 1 &&a[i][j+3] == 1 &&a[i][j+4] == 1) {
System.out.println("黑棋胜");
return;
}else if (a[i][j] == 2&&a[i][j+1] == 2 &&a[i][j+2] == 2 &&a[i][j+3] == 2 &&a[i][j+4] == 2) {
System.out.println("白棋胜");
return;
}
if (a[i][j] == 1 &&a[i+1][j] == 1 &&a[i+2][j] == 1 &&a[i+3][j] == 1 &&a[i+4][j] == 1) {
System.out.println("黑棋胜");
return;
}else if (a[i][j] == 2 &&a[i+1][j] == 2 &&a[i+2][j] == 2 &&a[i+3][j] == 2 &&a[i+4][j] == 2){
System.out.println("白棋胜");
return;
}
if (a[i][j] == 1 &&a[i+1][j+1] == 1 &&a[i+2][j+2] == 1 &&a[i+3][j+3] == 1 &&a[i+4][j+4] == 1) {
System.out.println("黑棋胜");
return;
}else if(a[i][j] == 2 &&a[i+1][j+1] == 2 &&a[i+2][j+2] == 2 &&a[i+3][j+3] == 2 &&a[i+4][j+4] == 2){
System.out.println("白棋胜");
return;
}
if (i>3&&a[i][j] == 1 &&a[i-1][j+1] == 1 &&a[i-2][j+2] == 1 &&a[i-3][j+3] == 1 &&a[i-4][j+4] == 1) {
System.out.println("黑棋胜");
return;
}else if(i>3&&a[i][j] == 2 &&a[i-1][j+1] == 2 &&a[i-2][j+2] == 2 &&a[i-3][j+3] == 2 &&a[i-4][j+4] == 2){
System.out.println("白棋胜");
return;
}
}
}
b++;
A:if (b%2 == 1) {
System.out.println("请黑棋下子");
i =sc.nextInt();
j =sc.nextInt();
if (i>num||j>num||a[i-1][j-1]==1||a[i-1][j-1]==2){
System.out.println("您下子的位置有问题");
b--;
break A;
}else {
a[i - 1][j - 1] = 1;
}
}else{
System.out.println("请白棋下子");
i =sc.nextInt();
j =sc.nextInt();
if (i>num||j>num||a[i-1][j-1]==1||a[i-1][j-1]==2){
System.out.println("您下子的位置有问题");
b--;
break A;
}else {
a[i - 1][j - 1] = 2;
}
}
}
}
}
结果如下:
十十十十十十★十十十十十十十十
十★★十★十十十十十十十十十十
十十十十十十★十十十十十十十十
十十十十十十十十十十十十十十十
十十十☆☆☆☆☆十十十十十十十
十十十十十十十十十十十十十十十
十十十十十十十十十十十十十十十
十十十十十十十十十十十十十十十
十十十十十十十十十十十十十十十
十十十十十十十十十十十十十十十
十十十十十十十十十十十十十十十
十十十十十十十十十十十十十十十
十十十十十十十十十十十十十十十
十十十十十十十十十十十十十十十
十十十十十十十十十十十十十十十
白棋胜
最后,觉得有用的话,可以点赞、收藏,加关注哟,要不下次就找不见了哟!