# 【游戏中的算法】取火柴游戏算法

1174人阅读 评论(0)

1、模拟两个人随机取火柴：

/************************/
/* name: match.c 		*/
/* auth: tianmt 		*/
/* desc: Match play		*/
/************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define random(min, max) ((rand()%(max-min+1))+(min))

const char * takeMatch(int num, const char *g1, const char *g2){
int times = 0, rand_num = 0;
srand(time(NULL));

while(num > 0){
//printf("remian matches: %d\n", num);
if(1 == num)
break;

if(num <= 5)
rand_num = num - 1;
else
rand_num = random(1, 4);

//printf("rand: %d\n", rand_num);
num -= rand_num;
times++;
}

if(1 == times%2)
return g1;
else
return g2;
}

int main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s num\n", argv[0]);
return -1;
}

const char gamer1[] = "Tom", gamer2[] = "Jack";

printf("WINNER: %s\n", takeMatch(atoi(argv[1]), gamer1 ,gamer2));
return 0;
}


2、电脑随机取火柴，用户输入取火柴：

/****************************/
/* name: match_computer.c 	*/
/* auth: tianmt 			*/
/* desc: Match play			*/
/****************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define random(min, max) ((rand()%(max-min+1))+(min))

void takeMatch(int num){
int take_num = 0, rand_num = 0;
srand(time(NULL));

while(1){
printf("remian matches: %d\n", num);
printf("YOU take matches:\n");

scanf("%d", &take_num);

if(take_num<1 || take_num>4 || take_num>(num-1)){
printf("take error num, please take again\n");
continue;
}

num -= take_num;

if(1 == num){
printf("YOU WIN!\n");
break;
}

if(num <= 5){
rand_num = num - 1;
printf("COMPUTER WIN!\n");
break;
}
else
rand_num = random(1, 4);

printf("COMPUTER takes %d matches!\n", rand_num);
num -= rand_num;
}
}

int main(int argc, char **argv){
if(argc != 2){
printf("Usage: %s num\n", argv[0]);
return -1;
}

takeMatch(atoi(argv[1]));
return 0;
}


1
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：52279次
• 积分：1104
• 等级：
• 排名：千里之外
• 原创：50篇
• 转载：23篇
• 译文：0篇
• 评论：12条
阅读排行
最新评论