今日分享——石头、剪刀、布,猜拳游戏

猜拳游戏
具体功能需求:

  1. 输入你要同电脑玩的局数
  2. 具有计分功能
  3. 运行一次程序,完成输入局数的游戏
  4. 每次游戏,电脑随机选择石头、剪刀、布
  5. 每局游戏结束,程序自动判断胜负
  6. 所有局数结束,显示总比分

分析比较简单,此处略去。
代码如下:

#include <stdio.h>
#include <stdlib.h>
int main()
{
	int i, n, a, b, c, d=0, x=0, y=0;
	char w;
	printf("Starting the CPSC 1011 Rock,Paper, Scissors Game!\n");

	printf("Enter the number of matches yo play: ");
	scanf("%d", &n);
	getchar();
	printf("\n");
	
	for(i=0; i<n; i++)
	{
		printf("\tMatch %d: Enter R for rock, P for paper, or S for scissors: ", i+1);
		scanf("%c", &w);
		getchar();
		switch(w)
		{
			case 'R': a=2;break;
			case 'S': a=1;break;
			case 'P': a=0:break;
		}

		b = rand() % 3;
		switch(b)
		{
			case 2: printf("\tThe computer chose rock. "); break;
			case 1: printf("\tThe computer chose scissors. "); break;
			case 0: printf("\tThe computer chose paper. "); break;
		}
		
		c = b-a;
		switch(c)
		{
			case -1:
			case 2: x+=1;printf("You win!\n"); break;
			case -2:
			case 1: y+=1;printf("You lose.\n"); break;
			case 0: d+=1;printf("You tied.\n"); break;
		}
		
		printf("\tScores: ");
		if(x!=0) printf("You -%d ", x);
		if(y!=0) printf("Computer-%d ",y);
		if(d!=0) printf("Ties-%d", d);
		printf("\n\n");
	}

	printf("The game of %d matches is complete. The final scores are :\n", n);
	printf("You:\t  %d\n", x);
	printf("Computer: %d\n", y);
	printf("Ties:\t  %d\n", d);
	return 0;
}

需要注意的是:
scanf()后加的getchar(),这种用法值得学习!

猜你喜欢

转载自blog.csdn.net/weixin_44566432/article/details/90297767