门实例代码展示-----五子棋(面向对象版)
程序员文章站
2022-07-04 21:22:30
...
门实例代码展示-----五子棋(面向对象版)
1.建立Gobang对象
package com.Xu.Gobang;
public class Gobang {
public static final String BAI = "○";
public static final String HEI = "●";
public static final String XX = "+";
static String[] nums = {" ","⒈","⒉","⒊","⒋","⒌","⒍","⒎","⒏","⒐","⒑","⒒","⒓","⒔","⒕","⒖","⒗","⒘","⒙","⒚","⒛"};
//初始化,载入棋盘初始数据
public void getGobang(String[][] a){
for(int i=0;i<15;i++){
for(int j=0;j<15;j++) {
if(i==0) {
a[i][j]=nums[j];
}
else if(j==0&&i!=0) {
a[i][j]=nums[i];
}
else a[i][j]=XX;
}
}
}
//判断落子位置是否符合规则
public boolean islocation(boolean flag,int x,int y,String[][] a)
{
if(x<1||y<1||x>=15) {
System.out.print("坐标不存在\n");
return false;
}
else if(a[x][y]!=XX) {
System.out.print("坐标已被占用\n");
return false;
}
else return true;
}
//刷新棋盘,打印棋盘
public void printGobang(String[][] a) {
for(int i=0;i<15;i++)
{
for(int j=0;j<15;j++)
System.out.print(" "+a[i][j]);
System.out.print("\n");
}
}
//确定落子颜色
public void Move(boolean flag,int x,int y,String[][] a)
{
if(flag)
a[x][y]=HEI;
else
a[x][y]=BAI;
}
//判断是否分出了胜负
public boolean isVictory(int x,int y,String[][] a)
{
System.out.print("已输入"+a[x][y]);
System.out.print("\n");
int p=1;
int max=x,may=y;
while(max>=1&&a[x][y]==a[--max][may])
{
p++;
}
max=x;
while(max<15&&a[x][y]==a[++max][may])
p++;
max=x;
if(p>=5) return true;
else p=1;
//xxxxxxx
while(a[x][y]==a[max][--may]&&may>=1)
p++;
may=y;
while(a[x][y]==a[max][++may]&&may<15)
p++;
may=y;
if(p>=5) return true;
else p=1;
//yyyyyyyy
while(a[x][y]==a[--max][--may]&&max>=1&&may>=1)
p++;
max=x;
may=y;
while(a[x][y]==a[++max][++may]&&max<15&&may<15)
p++;
max=x;
may=y;
if(p>=5) return true;
else p=1;
//xxxxxyyyyy
while(a[x][y]==a[--max][++may]&&max>=1&&may<15)
p++;
max=x;
may=y;
while(a[x][y]==a[++max][--may]&&max<15&&may>=1)
p++;
max=x;
may=y;
if(p>=5) return true;
else p=1;
//yyyyyxxxxx
return false;
}
}
2.写测试类运行Gobang对象
package com.Xu.Gobang;
import java.util.Scanner;
public class Test {
boolean isBlack = true;
public static void main(String[] args)
{
Gobang gobang = new Gobang();
int sum=16;
String a[][]=new String[sum][sum];
Scanner reader=new Scanner(System.in);
//初始化棋盘
gobang.getGobang(a);
System.out.print("游戏开始\n");
//打印棋盘
gobang.printGobang(a);
int x,y;//记录输入坐标
boolean flag=true;
while(true)
{
System.out.println("请"+(flag?"黑":"白")+"棋落子");
System.out.print("请输入落子坐标X,输入-1结束游戏");
x=reader.nextInt();
System.out.print("请输入落子坐标y,输入-1结束游戏");
y=reader.nextInt();
if(x==-1||y==-1) break;
if(gobang.islocation(flag,x,y,a)) {
gobang.Move(flag,x,y,a);
if(gobang.isVictory(x,y,a)) {
gobang.printGobang(a);
System.out.print(((flag)?"黑":"白")+"棋获胜!!游戏结束!\n");
break;
}
else {
flag=!flag;
gobang.printGobang(a);
}
}
else{
continue;
}
}
}
}
上一篇: mysql concat 坑记录 mysqloracle
下一篇: php代码