【问题标题】:Issue implementing validation rules in game在游戏中实现验证规则的问题
【发布时间】:2021-03-01 03:21:00
【问题描述】:

我正在编写一个倒计时游戏版本(来自英国电视节目),但在实现玩家键入的算术表达式的规则时遇到了问题。我有四个规则,每个都用一个while循环实现(即:输入必须是一个表达式而不仅仅是一个数字,它只能有基本的数学计算(+ - * /)等)

这是我所拥有的简化形式:

while #rule 1 is not respected:
   #ask for another input
   #check again
while #rule 2 is not respected:
   #ask for another input
   #check again
while #rule 3 is not respected:
   #ask for another input
   #check again
while #rule 4 is not respected: 
   #ask for another input
   #check again

问题如下:如果玩家违反了规则 4,并且当被要求输入另一个输入时,它违反了规则 2,则不会检查第二个输入(无论是规则 2 还是之前的任何规则规则 4)。每次玩家输入另一个输入时,我如何检查所有规则?

【问题讨论】:

    标签: python validation math input while-loop


    【解决方案1】:

    您可以使用以下任何一种组合这四个条件:

    • not (.. and ... and ...);
    • (not ...) or (not ...) or (not ...);
    • any(not ...);
    • not all(...)

    下面我用not all(...):

    def rule1(expr):   # expression contains at least one operation
      return any((op in expr) for op in '+-*/')
    
    def rule2(expr):   # expression contains only numbers and operations
      return all(c in '+-*/0123456789 ' for c in expr)
    
    def rule3(expr):   # don't know the rules of Countdown but love 42
      return ('42' in expr)
    
    def rule4(expr):   # addition is okay a little but not too much of it
      return (expr.count('+') < 7)
    
    def input_expr():
      expr = input('Enter your expression: ')
      while not all(rule(expr) for rule in [rule1, rule2, rule3, rule4]):
        expr = input('Expression was not okay. Enter again: ')
      return expr
    

    【讨论】:

      【解决方案2】:

      异常和try/except 块是处理错误检查的好方法,如下所示:

      while True:
         try:
             expr = input("I can has an input? ")
             assert "rule1" in expr, "Input needs to contain 'rule1'!"
             assert len(expr) < 20, "Input must be less than 20 characters!"
             assert len(expr.split) > 2, "Input must be at least 3 words!"
             break # all done!
         except AssertionError as e:
             print(f"Bad input: {e}")  # continue and try again
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-09
        相关资源
        最近更新 更多