本文主要是介绍【游戏中的算法】取火柴游戏算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- 一、取火柴游戏算法:
- 二、C/C++实现代码:
- 1、模拟两个人随机取火柴:
- 2、电脑随机取火柴,用户输入取火柴:
一、取火柴游戏算法:
取火柴游戏是一个非常简单有趣的小游戏,只要计算好步骤就可以做到常胜将军;
- 基本规则:总共有n根火柴,每人每次最多能取4根,最少取1根火柴,谁取到最后一根火柴就算输。
- 关键:当火柴少于等于5根的时候,只要把火柴取为剩下一根就可以保证对方输(这里只给出随机取火柴,最后小于5时取剩余数减1根火柴的代码)。
二、C/C++实现代码:
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;elserand_num = random(1, 4);//printf("rand: %d\n", rand_num);num -= rand_num;times++;}if(1 == times%2)return g1;elsereturn 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;}elserand_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;
}
运行结果
—— 2018-11-29 ——
这篇关于【游戏中的算法】取火柴游戏算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!