c语言代码24点游戏
时间: 2023-07-29 08:07:31 浏览: 63
24点游戏是一个非常经典的纸牌游戏,下面是一个使用C语言实现的24点游戏代码示例:
```c
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAX 4 //定义牌的数量
#define TARGET 24 //目标数为24
int card[MAX]; //存储牌
int getRand(int n) //生成1~n之间的随机数
{
return rand() % n + 1;
}
void shuffle() //洗牌
{
int i, j, k;
for(i=0; i<MAX; i++)
{
card[i] = getRand(13); //生成1~13之间的随机数,代表A~K
if(card[i] > 10) //将A~K转换为1~11
card[i] = 10;
else if(card[i] == 1)
card[i] = 11;
}
for(i=0; i<MAX; i++) //随机交换牌的位置
{
j = getRand(MAX);
k = card[i];
card[i] = card[j];
card[j] = k;
}
}
int cal(int a, int b, int op) //计算a和b之间的运算结果
{
switch(op)
{
case 0: return a + b; //加法
case 1: return a - b; //减法
case 2: return a * b; //乘法
case 3: return a / b; //除法
}
return 0;
}
int dfs(int cur, int val) //搜索满足条件的表达式
{
int i, tmp;
if(cur == MAX) //已经到达最后一个牌
{
if(val == TARGET) //找到满足条件的表达式
return 1;
else
return 0;
}
for(i=0; i<4; i++) //枚举四种运算符
{
tmp = dfs(cur+1, cal(val, card[cur], i)); //递归搜索
if(tmp)
return 1;
}
return 0;
}
void printCard() //输出牌
{
int i;
for(i=0; i<MAX; i++)
{
if(card[i] == 11)
printf("A ");
else if(card[i] == 12)
printf("J ");
else if(card[i] == 13)
printf("Q ");
else if(card[i] == 14)
printf("K ");
else
printf("%d ", card[i]);
}
printf("\n");
}
int main()
{
srand(time(NULL)); //初始化随机数种子
while(1)
{
shuffle(); //洗牌
printCard(); //输出牌
if(dfs(1, card[0])) //搜索满足条件的表达式
printf("Success!\n");
else
printf("Failed!\n");
printf("Press any key to continue or press 'q' to quit.\n");
if(getchar() == 'q') //退出游戏
break;
}
return 0;
}
```
在这个代码中,我们使用了dfs算法来搜索满足条件的表达式,其中cur表示当前搜索到的牌的位置,val表示当前搜索到的表达式的值。我们枚举了四种运算符,并递归搜索下一个牌,直到找到满足条件的表达式或者到达最后一个牌。如果找到了满足条件的表达式,就返回1,否则返回0。我们可以通过多次洗牌来进行多次游戏,直到玩家选择退出游戏。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)