猜拳游戏
具体功能需求:
- 输入你要同电脑玩的局数
- 具有计分功能
- 运行一次程序,完成输入局数的游戏
- 每次游戏,电脑随机选择石头、剪刀、布
- 每局游戏结束,程序自动判断胜负
- 所有局数结束,显示总比分
分析比较简单,此处略去。
代码如下:
#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(),这种用法值得学习!