[C] C语言编写的简单石头剪刀布游戏 →→→→→进入此内容的聊天室

来自 Idiotic Hummingbird, 2024-03-06, 写在 C, 查看 11 次.
URL http://www.code666.cn/view/135714a6
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. int getComputerChoice() {
  6.     int choices[] = {1, 2, 3}; // 1代表石头,2代表剪刀,3代表布
  7.     int randomIndex = rand() % 3;
  8.     return choices[randomIndex];
  9. }
  10.  
  11. int getPlayerChoice() {
  12.     int choice;
  13.     printf("请输入你的选择(1-石头,2-剪刀,3-布):");
  14.     scanf("%d", &choice);
  15.     while (choice < 1 || choice > 3) {
  16.         printf("输入无效,请重新输入(1-石头,2-剪刀,3-布):");
  17.         scanf("%d", &choice);
  18.     }
  19.     return choice;
  20. }
  21.  
  22. void determineWinner(int playerChoice, int computerChoice) {
  23.     if (playerChoice == computerChoice) {
  24.         printf("平局!\n");
  25.     } else if ((playerChoice == 1 && computerChoice == 2) ||
  26.                (playerChoice == 2 && computerChoice == 3) ||
  27.                (playerChoice == 3 && computerChoice == 1)) {
  28.         printf("你赢了!\n");
  29.     } else {
  30.         printf("你输了!\n");
  31.     }
  32. }
  33.  
  34. int main() {
  35.     srand(time(NULL)); // 初始化随机数种子
  36.  
  37.     int playerChoice, computerChoice;
  38.  
  39.     do {
  40.         playerChoice = getPlayerChoice();
  41.         computerChoice = getComputerChoice();
  42.  
  43.         printf("电脑选择了:");
  44.         switch (computerChoice) {
  45.             case 1:
  46.                 printf("石头\n");
  47.                 break;
  48.             case 2:
  49.                 printf("剪刀\n");
  50.                 break;
  51.             case 3:
  52.                 printf("布\n");
  53.                 break;
  54.         }
  55.  
  56.         determineWinner(playerChoice, computerChoice);
  57.  
  58.         printf("再玩一轮?(1-是,0-否):");
  59.         int playAgain;
  60.         scanf("%d", &playAgain);
  61.     } while (playAgain == 1);
  62.  
  63.     printf("游戏结束。\n");
  64.  
  65.     return 0;
  66. }

回复 "C语言编写的简单石头剪刀布游戏"

这儿你可以回复上面这条便签

captcha