資源簡介
下棋屬于一種博弈游戲,博弈過程可以用樹(博弈樹)來表示。假設游戲由兩個人( A 和 B )玩,開始由某個人從根結點開始走,兩個人輪流走棋,每次只能走一步, 下一步棋只能選擇當前結點的孩子結點,誰先走到葉子結點為勝。例如,對于下圖所示的博弈樹,若 A 先走,可以選 f , B 若選 h ,則 A 選 j 勝。
編寫一程序,讓計算機和人下棋。當計算機走下一步時,可以根據以下情況決定下一步:
(1) 若存在可以確保取勝的一個孩子結點,則選擇該結點作為下一步;
(2) 若存在多個可以確保取勝的孩子結點,則選擇其中高度最小的結點作為下一步(若有多個選擇,則選最左邊的結點);
(3) 若不存在可以確保取勝的一個孩子結點,則選擇高度最大的孩子結點作為下一步(若有多個選擇,則選最左邊的結點);
例: (下面的黑體為輸入)
(a,(b,(x)),(c,(d),(e,(g),(h)),(f)))
a
b
x
c
d
e
g
h
f
Who play first(0: computer; 1: player )?
1
player:
c
computer: d
Sorry, you lost.
Continue(y/n)?
y
Who play first(0: computer; 1: player )?
1
player:
x
illegal move.
player:
b
computer: x
Sorry, you lost.
Continue(y/n)?
y
Who play first(0: computer; 1: player )?
0
computer: c
player:
f
Congratulate, you win.
Continue(y/n)?
n
代碼片段和文件信息
#include
#include
#include
char?tree[200]IllegalMove[20];
typedef?struct?ChildList*?Child;
typedef?struct?NODE
{
char?Name;
char?Pure;?//高度是否純奇數?或?純偶數。
int?Height;?//該樹的高度
struct?NODE?*?Father;?//父節點
Child?List;?//孩子節點
}*Tree;
struct?ChildList
{
Tree?SubTree;
Child?Next;
};
Tree?PeoVsBot;
void?AddASubTree(Tree?father?Tree?child)
{
Child?TempCell;
TempCell?=?(Child)malloc(sizeof(struct?ChildList));
TempCell->SubTree?=?child;
TempCell->Next?=?father->List;
father->List?=?TempCell;
}
Tree?CreateTree(char?name?Tree?Father)
{
Tree?ATree;
ATree?=?(Tree)malloc(sizeof(struct?NODE));
ATree->Father?=?Father;
ATree->Height?=?0;
ATree->List?=?NULL;
ATree->Name?=?name;
ATree->Pure?=?1;
if?(Father?!=?NULL)
{
AddASubTree(Father?ATree);
}
return?ATree;
}
void?PrintStr(char?s[])
{
int?len?i;
len?=?strlen(s);
for?(i?=?0;?i? {
if?(s[i]?==?‘?‘)?putchar(NULL);
else?printf(“%c“?s[i]);
}
printf(“\n“);
}
int?PrintTree(int?father?int?height?Tree?GrandFather)//當前節點(下標)是father,GrandFather是當前節點的父節點地址
{
int?i;
for?(i?=?0;?i? {
putchar(NULL);
putchar(NULL);
putchar(NULL);
putchar(NULL);
}
printf(“%c\n“?tree[father]);
Tree?CurrentNode;
CurrentNode?=?CreateTree(tree[father]?GrandFather);
if?(height?==?0)
{
PeoVsBot?=?CurrentNode;
}
for?(i?=?father?+?1;?1;?i++)
{
if?(tree[i]?==?‘)‘)
{
//修改grandfather的heightpure?//樹的根沒有father
if?(CurrentNode->Father?!=?NULL)
{
if?(CurrentNode->Father->Height?==?0)
{
CurrentNode->Father->Height?=?CurrentNode->Height?+?1;
}
else
{
if?(CurrentNode->Father->Pure?==?1?&&?((CurrentNode->Height+1)?%?2?!=?CurrentNode->Father->Height?%?2))
{
CurrentNode->Father->Pure?=?0;
}
if?(CurrentNode->Height?+?1?>?CurrentNode->Father->Height)
{
CurrentNode->Father->Height?=?CurrentNode->Height?+?1;
}
}
}
return?i;//返回這課樹的結束的下標
}
else?if?(tree[i]?==?‘(‘)//還要判斷輸入是不不是標準的。即函數判斷()之間是否有節點
{
i?=?PrintTree(i?+?1?height?+?1?CurrentNode);//子樹??得到返回值?i
}
}
}
Tree?Bot(Tree?father)//計算機操作
{
Child?Temp?=?father->List;
Tree?SureStep?=?NULL?NotSureStep?=?NULL;
while?(Temp?!=?NULL)
{
if?(Temp->SubTree->Pur
- 上一篇:模糊控制算法的c語言實現
- 下一篇:vc自動更新源碼
評論
共有 條評論