编写“线围棋”程序-3-可提子

只能接收落子和显示棋局状态还不能支持对局。

要支持对局就要能自动判断死子,然后自动体走死的子。

在Game类中增加一个AutoPick方法和相关的调用子方法,就简便地实现了自动提子的功能。

这部分程序如下:

Function TGame.AutoPick(APos : Integer) : Integer;  //测试自动提子或自杀提子
  begin
    Result := 0; //返回提子数
    if APos > 0 then
      if (FPosStatus[APos -1] <> 0) and (FPosStatus[APos -1] <> FPosStatus[APos]) then
        Result := TestLeftPick(APos -1);   //只有遇到左边的棋是对方的棋时,才测试提左边的子
    if APos < MaxP then
      if (FPosStatus[APos +1] <> 0) and (FPosStatus[APos +1] <> FPosStatus[APos]) then
        Result := TestRightPick(APos +1);  //只有遇到右边的棋是对方的棋时,才测试提右边的子
    if Result = 0 then
       Result := TestSucide(APos);         //测试是否导致自杀
  end;

Function TGame.LeftBoard(APos : Integer) : Integer;  //查找左邻相异位
  begin
    Result := APos - 1;
    While Result >= 0 do
      begin
        if (FPosStatus[Result] <> FPosStatus[APos]) then //发现不同状态相邻位
           Exit;
        Result := Result -1;               //是相同状态相邻位,就继续查找相邻位
      end;
  end;

Function TGame.RightBoard(APos : Integer) : Integer; //查找右邻相异位
  begin
    Result := APos + 1;
    While Result <= MaxP do
      begin
        if (FPosStatus[Result] <> FPosStatus[APos]) then //发现不同状态相邻位
           Exit;
        Result := Result +1;               //是相同状态相邻位,就继续查找相邻位
      end;
  end;

Function TGame.TestSucide(APos : Integer) : Integer;   //测试是否自杀
  var
    i,LB,RB : Integer;
    B1,B2 : Boolean;
  begin
    Result := 0;
    LB := LeftBoard(APos);
    RB := RightBoard(APos);
    B1 := ((LB >=0) and (FPosStatus[LB] = 3- FPosStatus[APos])) or (LB <0);
    B2 := ((RB <= MaxP ) and (FPosStatus[RB] = 3- FPosStatus[APos])) or (RB > MaxP);
    if B1 and B2 then
      begin
        //for i := LB + 1 to RB - 1 do
        //  begin
        //    FPosStatus[i] := 0;
        //  end;
        Result := LB - RB + 1; //返回负值表示自杀子数
      end;
  end;

Function TGame.TestLeftPick(APos : Integer) : Integer;   //测试左侧提子
  var
    i, P : Integer;
  begin
    Result := 0;
    P := LeftBoard(APos);
    if ((P >=0) and (FPosStatus[P]<>0)) or (P < 0) then  //发现不是空,一定是对方位.没气了
      begin
        For i := P + 1 to APos  do     //提掉没气的子
          begin
            FPosStatus[i] := 0;
          end;
          Result := APos - P;
      end;
  end;

Function TGame.TestRightPick(APos : Integer) : Integer;   //测试右侧提子
  var
    i, P : Integer;
  begin
    Result := 0;
    P := RightBoard(APos);
    if ((P < MaxP) and (FPosStatus[P]<>0)) or (P > MaxP) then  //发现不是空,一定是对方位.没气了
      begin
        For i := APos to P - 1 do     //提掉没气的子
          begin
            FPosStatus[i] := 0;
          end;
          Result := P - APos;
      end;

  end;

 

在走棋处理时改成这样就可以真正下线围棋了。千万不要小看咯,线围棋也不是那么好下的咯。

Procedure TGame.SetPos(APos : Integer);  //走棋
  begin
    FPosStatus[APos] := FCurPlayer;
    if AutoPick(APos) >= 0 then      //判断自动提子
      FCurPlayer := 3 - FCurPlayer  //换边走棋
     else
      FPosStatus[APos] := 0;      //不允许自杀
  end;

下一步就要增加对打劫的判断了。

posted on 2008-10-08 15:50  巴不得飞  阅读(247)  评论(0编辑  收藏  举报