c语言编程实现 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.
时间: 2024-02-25 12:58:38 浏览: 173
好的,这是一个比较经典的小游戏,我可以用C语言帮您实现。以下是代码实现:
```c
#include <stdio.h>
int main() {
int sticks = 21; // 初始火柴数
int take, computerTake; // 玩家和计算机取的火柴数
printf("Game begin:\n");
while (sticks > 0) {
printf("%d sticks left in the pile.\n", sticks);
printf("How many sticks do you wish to take (1~4)? ");
scanf("%d", &take);
while (take < 1 || take > 4 || take > sticks) {
printf("Illegal move. Please try again.\n");
printf("How many sticks do you wish to take (1~4)? ");
scanf("%d", &take);
}
sticks -= take;
if (sticks == 0) {
printf("%d sticks left in the pile.\n", sticks);
printf("You have taken the last sticks.\n");
printf("***You lose!\nGame Over.\n");
break;
}
computerTake = (5 - take) % 5;
printf("%d sticks left in the pile.\n", sticks);
printf("Computer take %d sticks.\n", computerTake);
sticks -= computerTake;
if (sticks == 0) {
printf("%d sticks left in the pile.\n", sticks);
printf("Computer has taken the last sticks.\n");
printf("***You win!\nGame Over.\n");
break;
}
}
return 0;
}
```
程序中,我们使用了一个 while 循环,不断进行玩家和计算机的取火柴操作,直到火柴数量为 0。每次玩家取火柴前,都会判断其取的火柴数量是否合法,不合法则要求重新输入。而计算机则根据玩家取的火柴数量,采用一定的策略来取火柴。这里,我们使用了一个简单的策略:让计算机取的火柴数量加上玩家取的火柴数量等于 5。这样,计算机就可以在保证不输的前提下,尽可能地拖延游戏进程,增加玩家输的可能性。
运行程序后,可以按照提示进行游戏。如果您想让计算机更聪明一些,可以尝试采用其他的策略,比如根据当前剩余的火柴数和玩家的取火柴数量,来决定计算机应该取多少火柴。
阅读全文