C基础 07_综合案例《猜拳游戏》
-
需求:
- 本游戏是一款单机游戏,人机交互
-
规则:
- 需要双方出拳:石头、剪刀、布
- 赢:
- 石头 → 剪刀
- 剪刀 → 布
- 布 → 石头
- 平:
- 两边出拳相等
- 输:
- …
-
实现:
- 选择对手
- 玩家出拳
- 对手出拳
- 判断胜负
- 游戏退出
-
代码:
#include <stdio.h> #include <stdlib.h> #include <time.h>int main(int argc,char *argv[]) {// 初始化随机种子srand((unsigned)time(NULL));// 游戏主循环控制(默认可以重复玩)int game_running = 1;// 游戏头设置printf("=======================================\n");printf("== 猜拳游戏 v1.0 ==\n");printf("== 作者: LXB ==\n");printf("=======================================\n");// 主循环while (game_running){// 1.选择对手// 创建一个变量,用来存储对手对应的序号int opponent;while(1){printf("\n选择对手:【1】兔子 【2】毛熊 【3】鹰酱\n");// 处理非法输入if (scanf("%d",&opponent) != 1){// 清空输入缓冲区非法字符while(getchar() != '\n');printf("请输入角色所代表的数字!\n");continue;}// 验证输入范围if (opponent >= 1 && opponent <= 3) break;printf("选择无效,请重新输入!\n"); }// 显示对手信息,使用const修饰的变量还是变量,只不过不能再次改变const char *opponent_name = opponent == 1 ? "兔子" : opponent == 2 ? "毛熊" : "鹰酱";printf("对手,%s\n",opponent_name);// 2.玩家出拳printf("---玩家出拳---\n");// 创建一个变量,用来存储玩家自己出拳的序号int player_gesture;while(1){printf("\n请出拳:【1】石头 【2】剪刀 【3】布\n");// 非法输入校验if (scanf("%d",&player_gesture) != 1){// 清空输入缓冲区所有字符while(getchar() != '\n');printf("请输入数字1~3!\n");continue;}// 输入范围校验if (player_gesture >= 1 && player_gesture <= 3) break;printf("无效输入,请重新输入!\n");}// 显示玩家出拳信息const char* player_gesture_name = player_gesture == 1 ? "石头" : player_gesture == 2 ? "剪刀" : "布";printf("您出:%s\n",player_gesture_name);// 3.对手出拳printf("\n--对手出拳---\n");// 创建一个变量,作为对手的出拳序号,这个序号需要随机生成1~3int computer_gesture = rand() % 3 + 1;const char* computer_gesture_name = computer_gesture == 1 ? "石头" : computer_gesture == 2 ? "剪刀" : "布";// 显示对手出拳信息printf("%s出: %s\n",opponent_name,computer_gesture_name);// 4.判断胜负printf("\n---判断胜负---\n");// 创建一个变量,用来存储比较的结果int result = (player_gesture - computer_gesture + 3 ) % 3;printf("战况:");// 比较if (result == 0)printf("平局!\n");else if(result == 2)printf("您赢了!\n");else printf("您输了!\n");// 5.游戏退出printf("\n---游戏退出---\n");printf("继续游戏?【Y/N】");// 清空输入缓冲区while(getchar() != '\n');// 获取控制台输入char choice = getchar(); // 等价于 char choice; scanf("%c",&choice);// 修改循环状态game_running = choice == 'Y' || choice == 'y' ? 1 : 0;}printf("\n游戏结束!\n");return 0; }
-
运行效果: