• 刽子手游戏(Hangman Judge)


    题目:

    刽子手游戏是一款猜单词游戏。

    游戏规则如下:计算机想一个单词让你猜,你每次可以猜一个字母。

    如果单词里有那个字母,所有该字母会显示出来

    如果没有那个字母,则计算机会在一副刽子手画上填一笔。

    这幅画一共需要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.

    分析:

    只需要在猜错6次之内,猜出答案中的所有字母即可。不必对应顺序。

    但是,注意,猜一个已经猜过的字母也算错。

    c实现

    #include<stdio.h>
    #include<string.h>
    #define maxn 100
    
    char s[maxn],s2[maxn];//s存答案,s2存猜想 
    int left,chance; //还需要猜left个位置,错chance次之后会输 
    int win,lose; //win=1表示赢,lose=1表示输 
    
    int main(){
        int rnd;
        while(scanf("%d%s%s",&rnd,s,s2)==3&&rnd!=-1){
            printf("Round: %d
    ",rnd);
            win = lose = 0; 
            left = strlen(s);
            chance=7;
            for(int i=0;i<strlen(s2);i++){
                //bad用来标记有没有在答案中找到该字符:找到为0,没找到为1,则机会减一 
                int bad=1;
                for(int j=0;j<strlen(s);j++){
                    if(s[j]==s2[i]){
                        left--;
                        s[j]=' ';//为了能让,猜已经猜过的字母也算错:这里把猜对的单词改为空格
                        bad = 0;
                    }
                }
                if(bad) chance--;
                if(!chance) lose=1;
                if(!left) win=1;
                
                if(win||lose) break;
            }
            
            //根据结果进行输出
            if(win) printf("You win.
    ") ;
            else if(lose) printf("You lose.
    ");
            else printf("You chickened out.
    ");
        } 
        return 0;
    }

    也可以把猜字母的过程提取到函数中

    void guess(char ch){
        //bad用来标记有没有在答案中找到该字符:找到为0,没找到为1,则机会减一 
        int bad=1;
        for(int j=0;j<strlen(s);j++){
            if(s[j]==ch){
                left--;
                s[j]=' ';
                bad = 0;
            }
        }
        if(bad) chance--;
        if(!chance) lose=1;
        if(!left) win=1;
    }
  • 相关阅读:
    基于IFC的建筑工地模拟
    IfcProcedureTypeEnum
    IfcSimplePropertyTemplate
    IfcRelDefinesByObject
    ubuntu 安装 Protobuf3 日志
    IfcDistributionElement
    IfcTypeResource
    Github上很酷的项目汇总
    Simulink模块库分类
    利用Simulink设计一个简单的模型
  • 原文地址:https://www.cnblogs.com/Vincent-yuan/p/13089386.html
Copyright © 2020-2023  润新知