题目
21根火柴游戏。现有21根火柴,两人轮流取,每人每次可以取1至4根,不可多取(假如多取或者取走的数量不在合法的范围内,则要求重新输入),也不能不取,谁取最后一根火柴谁输。请编写一个程序进行人机对弈,要求人先取,计算机后取;请设计一种计算机取走火柴的规则,使得计算机一方为常胜将军。 **输入格式要求:“%d” 提示信息:“Game begin:\n” “How many sticks do you wish to take (1~%d)?” **输出格式要求:" %d sticks left in the pile.\n" " You have taken the last sticks.\n" " ***You lose!\nGame Over.\n" “Computer take %d sticks.\n” 程序运行示例如下: Game begin: How many sticks do you wish to take (1~4)?6 How many sticks do you wish to take (1~4)?3 18 sticks left in the pile. Computer take 2 sticks. 16 sticks left in the pile. How many sticks do you wish to take (1~4)?3 13 sticks left in the pile. Computer take 2 sticks. 11 sticks left in the pile. How many sticks do you wish to take (1~4)?3 8 sticks left in the pile. Computer take 2 sticks. 6 sticks left in the pile. How many sticks do you wish to take (1~4)?3 3 sticks left in the pile. Computer take 2 sticks. 1 sticks left in the pile. How many sticks do you wish to take (1~1)?2 How many sticks do you wish to take (1~1)?1 You have taken the last sticks. ***You lose! Game Over.
实现
思路:电脑为后手,其输入只需和人类输入之和凑够5即可,经过4轮之后,最后一个自然落在了人类手上。
#include
#define N 4
int main(){
printf("Game begin:\n");
int left = 21;
while(left > 0){
int numA, numB;
int len = left > N ? N : left;
printf("How many sticks do you wish to take (1~%d)?", len);
scanf("%d", &numA);
while(numA len){
printf("How many sticks do you wish to take (1~%d)?", len);
scanf("%d", &numA);
}
left -= numA;
if(left > 0){
printf(" %d sticks left in the pile.\n", left);
}
if(left > 1){
switch (numA) {
case 1:
numB = 4;
break;
case 2:
numB = 3;
break;
case 3:
numB = 2;
break;
case 4:
numB = 1;
break;
}
left -= numB;
printf("Computer take %d sticks.\n", numB);
printf(" %d sticks left in the pile.\n", left);
fflush(stdout);
} else{ //left == 1
left--;
printf("You have taken the last sticks.\n");
printf(" ***You lose!\nGame Over.\n");
}
}
}
|