java悔棋代码 java实现悔棋思路( 二 )


select.addActionListener(this);
dialog.getContentPane().add(choice_menu, BorderLayout.NORTH);
dialog.getContentPane().add(select_menu, BorderLayout.CENTER);
setIconImage(title);
setResizable(false);
setSize(300, 335);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String[] arg)
{
Gobang application = new Gobang();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event)
{
if( event.getSource().equals(command[0]) )
{
if(steps.size()!=0)
undo();
}
else if(event.getSource().equals(command[1]) )
Save();
else if(event.getSource().equals(command[2]) )
Load();
else if(event.getSource().equals(command[3]) )
ReStart();
else
{
if(choice[1].isSelected())
{
temp=white;
white=black;
black=temp;
}
dialog.dispose();
}
}
public void WinCheck()
{
check = turn? Player: AI;
direction=oblique_1;
WinCheck2();
}
public void WinCheck2()
{
count=1;
switch(direction)
{
case oblique_1: displace_x=1;
displace_y=-1;
direction=oblique_2;
break;
case oblique_2: displace_x=displace_y=1;
direction=horizontal;
break;
case horizontal: displace_x=1;
displace_y=0;
direction=vertical;
break;
case vertical: displace_x=0;
displace_y=1;
direction=nil;
break;
}
x=locX+displace_x;
y=locY+displace_y;
while(x=0xlengthy=0ylengthgrid[x][y]==check)
{
count=count+1;
x=x+displace_x;
y=y+displace_y;
}
x=locX-displace_x;
y=locY-displace_y;
while(x=0xlengthy=0ylengthgrid[x][y]==check)
{
count=count+1;
x=x-displace_x;
y=y-displace_y;
}
if(count=5)
{
game_state=End;
winner=check;
ThreadStart();
}
else if(direction!=nil)
WinCheck2();
}
public void ReStart()
{
for(int i=0; ilength; i++)
for(int j=0; jlength; j++)
grids[i][j].Initial();
winner=0;
steps.clear();
game_state=Playing;
}
public void gobangRandom()
{
displace_y=0;
do
{
displace_x=(int)(Math.random()*8);
x =locX+dir[displace_x][0];
y =locY+dir[displace_x][1];
if(!dir2[displace_x])
{
displace_y=displace_y+1;
dir2[displace_x]=true;
}
}while((x0 || x=length || y0 || y=length || grid[x][y]!=0)displace_y8);
for(int i=0; i8; i++)
dir2[i]=false;
if(x=0xlengthy=0ylengthgrid[x][y]==0)
setMark(x, y);
else
gobangRandom2();
}
private void gobangRandom2()
{
do
{
x=(int)(Math.random()*length);
y=(int)(Math.random()*length);
}while(grid[x][y]!=0);
setMark(x, y);
}
private void gobangAI()
{
boolean play=true;
for(int i=2; i0; i--)
{
play=!play;
gobangAI4(play);
if(turn)
return;
}
for(int i=7; i=4; i--)
{
play=!play;
step=i/2;
gobangAI2(play);
if(turn)
return;
}
gobangAI5();
if(!turn)
gobangRandom();
}
private void gobangAI2(boolean player)
{
check = player? Player: AI;
for(int i=0; ilength; i++)
for(int j=0; jlength; j++)
{
if(turn)
break;
if(grid[i][j] == check)
{
count=1;
direction=oblique_1;
gobangAI3(i, j);
}
}
}
private void gobangAI3(int x, int y)
{
if(count==1)
{
locX=x;
locY=y;
}
switch(direction)
{
case oblique_1: displace_x=1;
displace_y=-1;

推荐阅读