《猜拳游戏》
综合案例《猜拳游戏》
-
需求:
本游戏是一款单机游戏,人机交互
-
规则:
-
需要双方出拳:石头、剪刀、布
- 赢:
- 石头 → 剪刀
- 剪刀 → 布
- 布 → 石头
- 平:
- 两边出拳相等
- 输:
- …
- 赢:
-
实现:
- 选择对手
- 玩家出拳
- 对手出拳
- 判断胜负
- 游戏退出
-
代码
/*************************************************************************> File Name: demo01.c> Author: 彭波钛> Description: > Created Time: 2025年05月12日 星期一 09时40分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("== 作者:AAA ==\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("请输入数字1-3!\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.玩家出拳头=//创建以一个变量,用来存储玩家自己的出拳的序号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.对手出拳//创建一个变量,作为对手的出拳序号,这个序号需要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.判断胜负(双方PK)//创建一个变量,用来存储比比较的结果int result = (player_gesture - computer_gesture + 3) % 3;printf("战况:");if(result == 0) printf("平局!\n");else if (result == 1) printf("您输了!\n");else printf("您赢了!\n");//5.游戏退出printf("\n继续游戏?[Y/N] ");//清理输入缓冲区,防止之前遗留的\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; }
-
运行效果