实现人机版石头剪子布游戏,三局两胜。

用户界面
--------
 0.石头
 1.剪刀
 2.布
--------

人机随机出
用户输入0,人机随机出剪刀打印:

user:石头  
computer:剪刀
第一局  你胜了

--------
 0.石头
 1.剪刀
 2.布
--------
人机随机出
用户输入0,人机随机出剪刀打印:

user:石头  
computer:剪刀
第二局  你胜了

--------
 0.石头
 1.剪刀
 2.布
--------
人机随机出
用户输入0,人机随机出布打印:

user:石头  
computer:布
第三局  你输了

打印:你胜利了
询问是否继续,输入Y 继续 输入N 退出程序

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int count = 1;				//第几局,引入计数
int score[2] = { 0 };
void printMenu() 
{
	printf("----------------------\n");
	printf("\t0.石头  \n");    //key<computer
	printf("\t1.剪刀  \n");
	printf("\t2.布	   \n");
	printf("----------------------\n");
}
void printInfo(int key,const char* info)
{
	switch (key)
	{
	case 0:
		printf("%s:石头\n",info);
		break;
	case 1:
		printf("%s:剪刀\n",info);
		break;
	case 2:
		printf("%s:布\n", info);
		break;
	}
}
void printResult(const char* info) 
{
	//你赢了
	switch (count)
	{
	case 1:
		printf("第一局  %s\n", info);
		break;
	case 2:
		printf("第二局  %s\n", info);
		break;
	case 3:
		printf("第三局  %s\n", info);
		break;
	}
}
void keyDown()
{
	//char userKey = getchar();	//很容易跳过现象
	int userKey = 0;
	scanf_s("%d", &userKey);
	printInfo(userKey, "user");
	int computer = rand() % 3;	//[0,2]
	printInfo(computer, "computer");
	//描述比较
	if (userKey == 0 && computer == 2)
	{
		//电脑赢了
		printResult("你输了");
		score[1] += 1;
	


	}
	else if (userKey == 2 && computer == 0) 
	{
		//你赢了
		printResult("你赢了");
		score[0] += 1;
	}
	else  if (userKey > computer)  //2:布 0:石头
	{
		//电脑赢了
		printResult("你输了");
		score[1] += 1;
		

	}
	else if (userKey == computer)
	{
		//平局
		printResult("平局");
	}
	else 
	{
		printResult("你赢了");
		score[0] += 1;
		

	}
	count++;
	//三局两胜
	//赢1次  2平
	//赢2次
	//赢3次
	//只要赢了2次或者赢的次数大于机器的次数就可以了
}
int main()
{
	srand((unsigned int)time(NULL));	
	while (1) 
	{
		printMenu();
		keyDown(count);
		if (count == 4) 
		{
			if (score[0] > score[1]) 
			{
				printf("你赢了!\n");
			}
			else if(score[0] == score[1])
			{
				printf("平局!\n");
			}
			else 
			{
				printf("你输了!\n");
			}
			printf("是否继续(Y/N):");
			while (getchar() != '\n');
			int userkey = getchar();
			if (userkey == 'y' || userkey == 'Y') 
			{
				count = 1;
				score[0] = 0;
				score[1] = 0;
				system("cls");
				continue;
			}
			else 
			{
				break;
			}
		}
		system("pause");
		system("cls");
	}
	return 0;
}

注:读者可适当的进行优化,比如一方已经赢了两局,那么可以提前结束了!

 

 

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

兴趣使然的Qsiri

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值