黑白棋(未完成)
更新日期:
无影冬瓜写了个黑白棋,所以我也写了个黑白棋有些代码照搬了冬瓜的代码。
初稿,无说明,只有源码。
冬瓜的代码链接!黑白棋。
CDF
代码
Manipulate[Deploy@Row[{Graphics[{
Table[With[{i = i, j = j}, Button[{Disk[{j, 9 - i} - 0.5, .4]}, set[i, j]]], {i, 8}, {j, 8}],
{RGBColor[0, .5, 0], Rectangle[{0, 0}, {8, 8}]},
{Thick, Line[Table[{ {i, 0}, {i, 8}}, {i, 0, 8}]]},
{Thick, Line[Table[{ {0, i}, {8, i}}, {i, 0, 8}]]},
drawchess[chess],
{If[color == 1, Black, White], Orange, PointSize[0.03], Point[{# 2, 9 - # 1} - 0.5 & @@@
FindSetable[chessmat, color][[All, 2]]]},
Dynamic@{If[color == 1, Black, White], Opacity[.5],
Disk[MousePosition[{"Graphics", Graphics}, {-2, -2}], .4]},
}, ImageSize -> 300, PlotRange -> { {0, 8}, {0, 8}}],
Column[{
Column[{Graphics[{Black, AbsolutePointSize[18], Point[{0, 0}],
Text[Dynamic@Style[Count[chess, 1, 2], 18, Bold], {4, 0}]}, ImageSize -> {80, 20}],
Graphics[{White, AbsolutePointSize[18], Point[{0, 0}],
Text[Dynamic@Style[Count[chess, -1, 2], 18, Bold], {4, 0}]},ImageSize -> {80, 20}]},
Alignment -> Left, ItemSize -> {8, 2}],
RadioButtonBar[Dynamic[type], # 1 -> Style[# 2, 16, Bold] & @@@ { {2,
"双人对弈"}, {1, "人机对弈"}}, Appearance -> "Vertical"],
Button[Style["重新开始", 16, Bold], initialize[], ImageSize -> Automatic]
}, ItemSize -> {8, 8}, Alignment -> {Center, Center}]},
Background -> Brown, Alignment -> {Center, Center},
Frame -> True], { {type, 2}, {}, ControlType -> None},
Initialization :> {
initialize[] := {
chessmat = Array[{# 1, # 2, 0} &, {8, 8}];
(chessmat[[# 1, # 2, 3]] = # 3) & @@@ { {4, 4, 1}, {4, 5, -1}, {5, 4, -1}, {5, 5, 1}};
color = 1;
};
chess := chessmat[[All, All, 3]];
initialize[];
drawchess[mat_] :=
Join[{Black, Disk[{# 2, 9 - # 1} - 0.5, .4]} & @@@ Position[mat, 1],
{White, Disk[{# 2, 9 - # 1} - 0.5, .4]} & @@@ Position[mat, -1]];
FindSetable[mat_, c_] :=
SequenceCases[# , { {i1_, j1_, c}, {_, _, -c} .., {i2_, j2_,
0}} | { {i2_, j2_, 0}, {_, _, -c} .., {i1_, j1_,
c}} :> { {i1, j1}, {i2, j2}}] & /@ (Join @@ {mat,
Transpose@mat, Diagonal[mat, # ] & /@ Range[-5, 5],
Diagonal[Reverse@mat, # ] & /@ Range[-5, 5]}) // Join @@ # &;
GetTurnPosition[{p1 : {i1_, j1_}, p2 : {i2_, j2_}}] :=
NestList[# + Sign[p2 - p1] &, p1, Max[Abs /@ {i2 - i1, j2 - j1}]];
set[i_, j_] := Module[{pos},
If[(pos = Cases[FindSetable[chessmat, color], { {_, _}, {i, j}}]) != {},
(chessmat[[# 1, # 2, 3]] = color) & @@@ (Join @@ GetTurnPosition /@ pos);
color *= -1;
];
WinQ[];
If[type == 1 && color == -1, AISet[]]
];
WinQ[] := If[FindSetable[chessmat, color] == {} || FreeQ[chess, 0],
CreateDialog[{Style["游戏结束," <> Switch[Total[chess, 2], _?(# > 0 &), "黑方胜", _?(# < 0 &),
"白方胜", _, "平局"], 16, Bold],
ChoiceButtons[{"再来一局", "取消"}, {initialize[];
DialogReturn[], DialogReturn[]}]}]
];
AISet[] := set @@ Last@RandomChoice@FindSetable[chessmat, color];
}]

