游戏规则是这样的:计算机想一个单词让你猜,你每次可以猜一个字母。 如果单词里有那个字母,所有该字母会显示出来;如果没有那个字母,则计算机会在一幅“刽子手”画上填一笔。 这幅画一共需要7笔就能完成,因此你最多只能错6次。 注意,猜一个已经猜过的字母也算错。
在本题中,你的任务是编写一个“裁判”程序,输入单词和玩家的猜测,判断玩家赢了(You win.)、 输了(You lose.)还是放弃了(You chickened out.)。 每组数据包含3行,第1行是游戏编号(-1为输入结束标记),第2行是计算机想的单词,第3行是玩家的猜测。 后两行保证只含小写字母。
样例输入:
1
cheese
chese
2
cheese
abcdefg
3
cheese
abcdefgij
-1
样例输出:
Round 1
You win.
Round 2
You chickened out.
Round 3
You lose.
#include<stdio.h>
#include<string.h>
int main()
{
char ans[21];
char gus[28];
int times,yes;
int chances = 7;
int win = 0;
int lose = 0;
scanf("%d",×);
while(times != -1)
{
printf("Round %d\n",times);
scanf("%s\n%s",ans,gus);
yes = 0;
win = 0,lose = 0,chances = 7;
for(int i = 0;i < strlen(gus);i ++)
{
int flag = 0;
for(int j = 0;j < strlen(ans);j ++)
{
if(ans[j] == gus[i])
{
yes ++;
flag = 1; //找到之后不退出,因为有一个单词有相同的字母
}
}
if(flag == 0)
{
chances --;
}
if(chances == 0)
{
lose = 1;
printf("You lose.\n");
break;
}
else if(yes == strlen(ans))
{
win = 1;
printf("You win.\n");
break;
}
}
if(win != 1 && lose != 1)
{
printf("You chickened out.\n");
}
scanf("%d",x);
}
return 0;
}
或
#include <stdio.h>
#include <string.h>
#define maxn 100
int win, lose,left,chance;
char s[maxn], s2[maxn];
void guess(char ch);
int main()
{
int rnd;
while(scanf("%d%s%s", &rnd, s,s2) == 3 && rnd != -1)
{
printf("Round %d:\n", rnd);
left = strlen(s);
chance = 7;
for(int i = 0; i < strlen(s2); i++)
{
guess(s2[i]);
if(win || lose)
break;
}
if(win)
printf("You win.\n");
else if(lose)
printf("You lose.\n");
else
printf("You chickened out.\n");
}
return 0;
}
void guess(char ch)
{
int bad = 1;
for(int i = 0; i < strlen(s); i++)
{
if(ch == s[i])
{
left--;
s[i]= ' ';
bad = 0;
}
if(bad)
chance--;
if(!chance)
lose = 1;
if(!left)
win = 1;
}
}