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:
=={{header|C_sharp|C#}}==
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:
<langsyntaxhighlight lang="csharp">
public class XPathEval : I24MathParser {
public float Evaluate(string expression) {
Line 19 ⟶ 18:
return answer;
}
}</syntaxhighlight>
}
</lang>
 
 
The XPathEval class is implementing this interface to facilitate swapping out Evaluate providers:
<langsyntaxhighlight lang="csharp">
interface I24MathParser {
float Evaluate(string expression);
}
</syntaxhighlight>
</lang>
 
 
Here is a more verbose, native solution - a lightweight math expression parser for evaluating 24 Game user input:
<langsyntaxhighlight lang="csharp">
/// <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 = @"(?:(?<=[+/*\-+]|^)[+-]?)?(?:[0-9]+(?:\.[0-9]*)?)|[/*\-+]";
 
Regex brackets;
Line 164 ⟶ 162:
}
}
</syntaxhighlight>
</lang>
 
 
This is the main class that handles puzzle generation and user interaction
<langsyntaxhighlight lang="csharp">
/// <summary>
/// The Game. Handles user interaction and puzzle generation.
Line 340 ⟶ 338:
}
}
</syntaxhighlight>
</lang>
 
 
9,476

edits