【问题标题】:How to use sets of string in Pascal?如何在 Pascal 中使用字符串集?
【发布时间】:2009-01-25 22:47:41
【问题描述】:

我正在编写一个小游戏,其中会询问用户的种族和班级。 string[5] 有五种可能的种族,string[9] 有四种可能的类别。

如何将 pascal 编程为 1. 将五个种族和四个类定义为常量, 2. 检查用户输入以查看输入是否在可能的种族和类中 - 不使用多个 IF 语句?

任何提示将不胜感激。

【问题讨论】:

    标签: string set pascal


    【解决方案1】:

    由于您的输入是严格定义的,我的第一个问题是,您必须使用字符串作为用户输入吗?不能不给用户选择吗?说下拉?然后您可以将每个选项映射到一个枚举。

    type
      race = (rcRace0, rcRace1, rcRace2 rcRace3, rcRace4);
    
    
    case race(Input) of  //input is an integer, index of the drop down list for example
      rcRace0 : //perform processing for race 0
      rcRace1 : //perform processing for race 1
      rcRace2 : //perform processing for race 2
      rcRace3 : //perform processing for race 3
      rcRace4 : //perform processing for race 4
    end;
    

    类也一样。

    【讨论】:

      【解决方案2】:

      我会推荐 Steves 解决方案作为起点,但在使用枚举类型和集合方面更进一步......

      type
          TRace = (rcRace0, rcRace1, rcRace2, rcRace3, rcRace4);
      
          TCharacterClass = (ccClass0, ccClass1, ccClass2, ccClass3);
      
          TCharacterClassSet = set of TCharacterClass;
      
      const
          validCombinations : array[TRace] of TCharacterClassSet = (
              [ccClass0, ccClass1, ccClass2, ccClass3],  // race0 can be any class
              [ccClass0, ccClass2],                      // race1 
              [ccClass0, ccClass1, ccClass2],            // race2
              [ccClass0, ccClass3],                      // race3
              [ccClass0]                                 // race4
              );
      

      您还可以为种族名称和角色类别设置常量:

      const
          raceNames : array[TRace] of string = (
              'Race 0',
              'Race 1',
              'Race 2',
              'Race 3',
              'Race 4'
              );
      
          characterClassNames = array[TCharacterClass] of string = (
              'Class 0',
              'Class 1 ',
              'Class 2',
              'Class 3'
              );
      

      现在,如果您使用组合框进行用户输入并将输入映射到这些枚举类型,则检查组合是否有效很简单:

      function ValidRaceAndClass( aRace : TRace; aClass : TCharacterClass ) : Boolean;
          begin
          result := aClass in validCombinations[ aRace ];
          end;
      

      【讨论】:

      • 我同意这个答案。您的数据基本上是枚举而不是字符串。您没有“五个可能的字符串 [5] 种族”。你有“五种可能的种族”。可以显示为字符串[5]。但是然后存储为枚举。
      【解决方案3】:

      我发现您应该遵循 Steves 的解决方案。但是,如果使用字符串是您的方式,您可以使用 TStringList(在 Delphi/可能是 FreePascal 中)。您可以用您的比赛填充它,然后使用 TStringList 的 IndexOf 函数评估玩家的答案。它返回传递的字符串的索引,当传递的字符串不在列表中时返回-1。

      无论如何,我强烈推荐 Steves 解决方案 :)

      【讨论】:

      • 他可能不必自己编写代码,但在底层,IndexOf 正是 OP 想要避免做的事情。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多