用c语言写石头剪刀布小游戏
时间: 2023-10-12 10:05:03 浏览: 162
可以使用如下的代码实现石头剪刀布小游戏:
```
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int player_choice, computer_choice;
int player_score = 0, computer_score = 0;
const char *options[3] = {"Rock", "Paper", "Scissors"};
srand(time(NULL)); // Seed the RNG
printf("Welcome to the Rock, Paper, Scissors Game!\n");
while(1) {
printf("Enter your choice (0 for Rock, 1 for Paper, 2 for Scissors): ");
scanf("%d", &player_choice);
if(player_choice < 0 || player_choice > 2) {
printf("Invalid choice. Try again.\n\n");
continue;
}
computer_choice = rand() % 3;
printf("You chose %s. Computer chose %s.\n", options[player_choice], options[computer_choice]);
// Determine winner
if(player_choice == computer_choice) {
printf("Tie! No one wins.\n\n");
}
else if(player_choice == 0 && computer_choice == 2 ||
player_choice == 1 && computer_choice == 0 ||
player_choice == 2 && computer_choice == 1) {
printf("You win!\n\n");
player_score++;
}
else {
printf("Computer wins.\n\n");
computer_score++;
}
printf("Score: You %d - %d Computer\n\n", player_score, computer_score);
}
return 0;
}
```
这份代码实现了一个基本的石头剪刀布游戏,具体来说:
- 使用rand()函数生成一个0到2之间的随机数,表示电脑出的选项;
- 根据玩家选择和电脑选择的不同,判断当前轮的胜负关系,并更新分数;
- 不断循环,直到玩家选择退出游戏。
阅读全文