最近在看C程序设计与项目实践这本书,决定把出现的一些例子记录下来。
/**
*项目名称:模拟石头剪刀布游戏
*开发日期:2015/5/16
*作 着:***
*版 本:V1.0
*/
#include <stdio.h>
#include <stdlib.h>
int pscore; //玩家的得分
int cscore; //计算机的得分
int count; //对战次数
void init();
int pshowFist();
int cshowFist();
void judge(int,int);
void getScore();
int main(int argc, char *argv[]) {
char con; /*玩家是否继续游戏*/
int pFist; /*玩家出的拳*/
int cFist; /*电脑出的拳*/
init();
scanf("%c",&con);
fflush(stdin);/*清空缓冲区*/
while( con=='y')
{
/*出拳*/
pFist=pshowFist();
cFist=cshowFist();
judge(pFist,cFist);
count++;
printf("是否进行下一轮 (y/n):");
fflush(stdin);
scanf("%c",&con);
}
getScore();
return 0;
}
/**
*模块名:init
*功 能:游戏初始化,出现游戏界面
*输 入:无
*返回值:无
*/
void init()
{
pscore=0;
cscore=0;
count=0;
printf("********欢迎进入游戏的世界********\n");
printf("\n********************************\n");
printf("\n************猜拳开始************\n");
printf("\n********游戏规则:1.剪刀 2.石头 3.布\n");
printf("是否继续开始游戏?(y/n)");
}
/**
*模块名:cshowFist
*功 能 :电脑出拳(随机产生)
*输 入 :无
*返回值:电脑出的拳(1.剪刀 2.石头 3.布)
*/
int cshowFist()
{
int show;
srand(time(NULL));
show = rand()%3+1; /*产生随机数,表示电脑出拳*/
switch(show)
{
case 1:
printf("\n电脑出剪刀");
break;
case 2:
printf("\n电脑出石头");
break;
case 3:
printf("\n电脑出布");
break;
}
return show;
}
/**
*模块名:pshowFist
*功 能:玩家出拳(从键盘输入)
*输 入:无
*输 出:玩家出的拳 (1.剪刀 2.石头 3.布)
*/
int pshowFist()
{
int show;
printf("请出拳:1.剪刀\t2.石头\t3.布\t(请出拳):");
scanf("%d",&show);
switch(show)
{
case 1:
printf("\n你出剪刀");
break;
case 2:
printf("\n你出石头");
break;
case 3:
printf("\n你出布");
break;
}
return show;
}
/**
*模块名:judge
*功 能:进行一轮的胜负评判,直接输出评判结果
*输 入: 玩家出的拳pFist,电脑出的拳cFist;
*返回值:无
*/
void judge( int pFist, int cFist)
{
/*裁决*/
if(pFist==cFist)
{
printf("\n结果:和局\n");
}
else if((pFist==1 && cFist==3) || (pFist==2 && cFist==1) || (pFist==3 && cFist==2))
{
printf("\n恭喜你,你赢了!");
pscore++;
}
else
{
printf("\n忧桑,你输了...\n");
cscore++;
}
}
/**
*模块名:getScore
*功 能:进行游戏总的胜负的评判
*输 入:无
*返回值:无
*/
void getScore()
{
/*显示最终结果*/
printf("\n对战%d次,你赢了 %d 次\t计算机赢了%d次\t平了%d次!",count,pscore,cscore,count-pscore-cscore);
if(pscore>cscore)
{
printf("\n结果:恭喜恭喜啊,你赢了~~");
}
else if(pscore<cscore)
{
printf("\n结果:what a pity~你输了,下次加油!");
}
else
{
printf("\n结果:打成平手,下次再战!!");
}
}