24 game/CSharp: Difference between revisions
m
Fixed syntax highlighting.
m (removed some duplication caused by copy/paste, edited intro text, homogenized open bracket placement) |
m (Fixed syntax highlighting.) |
||
(2 intermediate revisions by 2 users not shown) | |||
Line 1:
The C# language does not directly contain an Eval function for evaluating a string as a math expression, though there are still a number of ways to go about it.
Line 5 ⟶ 4:
Or, while not necessarily a good coding practice, but certainly a short and simple route, you could use System.Xml.XPath.XPathNavigator.Evaluate(string xpath) as shown here:
<
public class XPathEval : I24MathParser {
public float Evaluate(string expression) {
Line 19 ⟶ 18:
return answer;
}
}</syntaxhighlight>
The XPathEval class is implementing this interface to facilitate swapping out Evaluate providers:
<
interface I24MathParser {
float Evaluate(string expression);
}
</syntaxhighlight>
Here is a more verbose, native solution - a lightweight math expression parser for evaluating 24 Game user input:
<
/// <summary>
/// Lightweight math parser - C# does not have an Evaluate function
Line 47 ⟶ 45:
//splits expression into it elements - i.e. "4+-30-4.123" yields {"4", "+", "-30" ,"-", "4.123"}
private const string tokenPattern = @"(?:(?<=[
Regex brackets;
Line 164 ⟶ 162:
}
}
</syntaxhighlight>
This is the main class that handles puzzle generation and user interaction
<
/// <summary>
/// The Game. Handles user interaction and puzzle generation.
Line 340 ⟶ 338:
}
}
</syntaxhighlight>
|