// Returns a new Gamestate without the given Token with new reference // Removes the Token from the given GameState if it is on the Gamestate // otherwise the given GameState will be returned with new reference // (only has to check the peeks because the covered Tokens are ignored by GetAvailableTokensForGameState) private static StringState RemoveTokenFromGameState(StringState state, string token) { // Deep clone the given state without reference StringState resultState = TypeConverter.DeepCloneState(state); // Iterate through all available fields of the state foreach (var field in state) { // Check if the token is on the peek of the field if (field.Value.Peek() == token) { // When the field has more than one token if (field.Value.Count > 1) { // Remove the highest token from the field resultState[field.Key].Pop(); } // When the token is the only token on the field else { // Remove the field from the state resultState.Remove(field.Key); } } } return(resultState); }
/***** TEST CASES *****/ // The following functions serves as Test Case for Special states // Usement: call in first alpha beta call instead of param // The User win is inevitable no matter which move the ai uses // Expected: There will be no move result. // The UI Controller shows player win announcment directly // Previous Behaviour: Exception private static StringState UserWinInevitable() { StringState testState = new StringState(); Stack <string> stringStack1 = new Stack <string>(); stringStack1.Push("MediumCross1"); testState.Add(Field.TopLeft, stringStack1); Stack <string> stringStack2 = new Stack <string>(); stringStack2.Push("LargeCross1"); testState.Add(Field.Middle, stringStack2); Stack <string> stringStack3 = new Stack <string>(); stringStack3.Push("LargeCross2"); testState.Add(Field.TopRight, stringStack3); Stack <string> stringStack4 = new Stack <string>(); stringStack4.Push("MediumCross2"); stringStack4.Push("LargeCircle1"); testState.Add(Field.MiddleLeft, stringStack4); Stack <string> stringStack5 = new Stack <string>(); stringStack5.Push("LargeCircle2"); testState.Add(Field.BottomLeft, stringStack5); return(testState); }
// The ai is able to win with the next move and should prioritize this // Expected: Set Medium Circle 1 to Top Right Field (previous peek SmallCross1) // Previous Behaviour: Move Large Circle 1 to Top Right Field and loose // Used ai depth: 3 // LX1 - SX1 => MO1 // LX2 LO2 - // LO1 - - private static StringState WinPriority2() { StringState testState = new StringState(); Stack <string> stringStack1 = new Stack <string>(); stringStack1.Push("LargeCross1"); testState.Add(Field.TopLeft, stringStack1); Stack <string> stringStack2 = new Stack <string>(); stringStack2.Push("LargeCross2"); testState.Add(Field.MiddleLeft, stringStack2); Stack <string> stringStack3 = new Stack <string>(); stringStack3.Push("SmallCross1"); stringStack3.Push("LargeCircle1"); testState.Add(Field.BottomLeft, stringStack3); Stack <string> stringStack4 = new Stack <string>(); stringStack4.Push("LargeCircle2"); testState.Add(Field.Middle, stringStack4); Stack <string> stringStack5 = new Stack <string>(); stringStack5.Push("SmallCross2"); testState.Add(Field.TopRight, stringStack5); return(testState); }
// Returns the allowed player Tokennames for the given Gamestate on a specific Field on the GameField // = The Tokens that are allowed to be placed on the Field which have to be Bigger than the current highest Token on the Field // @param availableTokens All available tokens of the Player for the GameState private static List <string> GetAllowedTokensForField(StringState state, Field field, List <string> availableTokens) { List <string> allowedTokens = new List <string>(); // Is already a Token on the Field? if (state.ContainsKey(field)) { // Iterate through available Tokens foreach (string token in availableTokens) { // Is the available Token "bigger" than the Token on the Field? if (TypeConverter.GetValueForTokenName(token) > TypeConverter.GetValueForTokenName(state[field].Peek())) { // Token is allowed allowedTokens.Add(token); } } } else { // No Token on the Field = all available Tokens are allowed allowedTokens = availableTokens; } return(allowedTokens); }
// Return a new state with the given move on the given state with new reference private static StringState GetStateWithMove(StringState state, MoveString move) { // Deep clone previous state StringState resultState = TypeConverter.DeepCloneState(state); // Remove the token from the previous field (if already placed) resultState = RemoveTokenFromGameState(resultState, move.Token); // If the field already has a token if (resultState.ContainsKey(move.Field)) { Stack <string> tokenStack = new Stack <string>(resultState[move.Field]); tokenStack.Push(move.Token); // Place the allowed Token above the old Token resultState.Remove(move.Field); resultState.Add(move.Field, tokenStack); } else { // Otherwise add the Field with a new Stack with the allowed Token Stack <string> tokenStack = new Stack <string>(); tokenStack.Push(move.Token); resultState.Add(move.Field, tokenStack); } return(resultState); }
/***** ALPHA BETA *****/ // Starts the Alpha Beta Algorithm for every first move (root) by the start parameters // (The Player to start is the ai player) private static MoveString AlphaBetaRoot(int depth, StringState state, Player player) { // Start with the lowest possible value int bestValue = int.MinValue; // The best move result MoveString bestMove = new MoveString(); // Get all first moves List <MoveString> possibleMoves = GetPossibleMoves(state, player); // Iterate through all possible moves foreach (MoveString move in possibleMoves) { // Execute the move on a new reference of the main state StringState moveState = GetStateWithMove(state, move); // Get the value for this route by alpha beta algorithm int value = AlphaBeta(depth - 1, moveState, player, int.MinValue, int.MaxValue); // Is the value for this route better than the previos value? if (value >= bestValue) { // Overwrite the best value bestValue = value; // Save the appropriate move bestMove = move; } } // Return only the best move without the value return(bestMove); }
/***** DEBUG *****/ // Debug function for the state // Debugs all fields with the peek token private static void DebugState(StringState state) { foreach (var field in state) { Debug.Log("field: " + field.Key); Debug.Log("peek token: " + field.Value.Peek()); } }
public MeScanner (XamlParserContext context, string text, int lineNumber, int linePosition) { this._context = context; this._inputText = text; this._lineNumber = lineNumber; this._startPosition = linePosition; this._idx = -1; this._state = StringState.Value; }
public MeScanner(XamlParserContext context, string text, int lineNumber, int linePosition) { this._context = context; this._inputText = text; this._lineNumber = lineNumber; this._startPosition = linePosition; this._idx = -1; this._state = StringState.Value; }
public MeScanner(XamlParserContext context, string text, int lineNumber, int linePosition) { _context = context; _inputText = text; _lineNumber = lineNumber; _startPosition = linePosition; _idx = -1; _state = StringState.Value; _currentParameterName = null; _currentSpecialBracketCharacters = null; }
public IToken Next(IScanner scanner) { var state = new StringState(scanner); if (scanner.MoveNext()) { return(state.Normal()); } return(state.Error()); }
public Lexer(InputString inputString) { _inputString = inputString; _currentSymbol = _inputString.GetNextSymbol(); _idState = new IdState(); _symbolState = new SymbolState(); _charState = new CharState(); _stringState = new StringState(); _commentState = new CommentState(); _digitState = new DigitState(); _verbatinState = new VerbatinState(); }
// Deep Clones the given StringState to a new StringState with other Reference public static StringState DeepCloneState(StringState gameState) { StringState stringState = new StringState(); foreach (var field in gameState) { Stack <string> tokenStringStack = new Stack <string>(field.Value); stringState.Add(field.Key, tokenStringStack); } return(stringState); }
public IToken Next(IScanner scanner) { var literal = scanner.Current == CharacterTable.At; var state = new StringState(scanner, _tokenizer, literal); if (literal) { scanner.MoveNext(); } if (scanner.MoveNext()) { return(state.Normal()); } return(state.Error()); }
protected virtual IState GetState(HashSet <string> sensations) { //creates list of stimuli sorted alphabetically var stimuliList = new List <string>(sensations); stimuliList.Sort(); var stateStr = (stimuliList.Count == 0) ? string.Empty : stimuliList.Aggregate( (current, stimulus) => $"{current}{STATE_SEPARATOR}{stimulus}"); //checks for new state if (!this.stringStates.ContainsKey(stateStr)) { var stringState = new StringState(stateStr); this.stringStates[stateStr] = stringState; } return(this.stringStates[stateStr]); }
public StringParser(StringState state) { _state = state; switch (state) { case StringState.ReadyForChar: NextChar(StructuralChar.StringEscapeMarker, () => new StringParser(StringState.Escaping)); NextChar(StructuralChar.UnescapedStringBody, () => new StringParser(StringState.ReadyForChar)); NextChar(StructuralChar.StringDelimiter, () => new StringParser(StringState.Completed)); break; case StringState.Escaping: NextChar(StructuralChar.SingleEscapedChar, () => new StringParser(StringState.ReadyForChar)); NextChar(StructuralChar.UnicodeEscapeMarker, () => new StringParser(StringState.EscapingUnicodeOne)); break; case StringState.Completed: break; case StringState.EscapingUnicodeOne: NextChar(StructuralChar.UnicodeEscapedChar, () => new StringParser(StringState.EscapingUnicodeTwo)); break; case StringState.EscapingUnicodeTwo: NextChar(StructuralChar.UnicodeEscapedChar, () => new StringParser(StringState.EscapingUnicodeThree)); break; case StringState.EscapingUnicodeThree: NextChar(StructuralChar.UnicodeEscapedChar, () => new StringParser(StringState.EscapingUnicodeFour)); break; case StringState.EscapingUnicodeFour: NextChar(StructuralChar.UnicodeEscapedChar, () => new StringParser(StringState.ReadyForChar)); break; default: throw new ArgumentOutOfRangeException(nameof(state), state, null); } }
// Returns a List of all possible moves for the given player on the given state private static List <MoveString> GetPossibleMoves(StringState state, Player player) { List <MoveString> result = new List <MoveString>(); // Get all available tokens for the state List <string> availableTokens = GetAvailableTokensForGameState(state, player); // Iterate through all Fields of the Gamefield foreach (Field field in Enum.GetValues(typeof(Field))) { // Get the allowed Tokens to place on this Field List <string> allowedTokens = GetAllowedTokensForField(state, field, availableTokens); // Iterate through all allowed Tokens for this Field foreach (string token in allowedTokens) { result.Add(new MoveString(token, field)); } } return(result); }
// Returns the evaluation value for three Fields on the given State for the given Player // (Used an array as fields parameter for iteration) private static int EvaluateThreeFields(StringState state, Player player, Field[] fields) { int res = 0; int currentValue = 0; // Count the tokens for each player int playerTokenCounter = 0; int opponentTokenCounter = 0; // Iterate through all three fields foreach (Field field in fields) { // Get the tokenString on the peek of the field or use an empty string string tokenString = state.ContainsKey(field) ? state[field].Peek() : ""; // Evaluate the tokens on the field currentValue = EvaluateToken(player, tokenString); // The result is positive for the players token if (currentValue > 0) { // Inc player token counter playerTokenCounter++; res += currentValue * (playerTokenCounter + 1); } // The result is negative for opponent token else if (currentValue < 0) { // Inc opponent counter opponentTokenCounter++; // Add current Value * opponent counter res += currentValue * (opponentTokenCounter + 1); } // Otherwise no change of res } return(res); }
/***** Private Functions *****/ // Returns a List of available Tokennames for the given state and player // (All Player Tokens including the Tokens on the Peek of the Fields // but without the covered Tokens) private static List <string> GetAvailableTokensForGameState(StringState state, Player player) { // Direct Init of all Tokennames for the Player List <string> allTokens = player == Player.Cross ? CrossTokenNames : CircleTokenNames; List <string> coveredTokens = new List <string> (); List <string> availableTokens = new List <string>(); // Iterate through all Fields with Tokens on the Gamefield foreach (Stack <string> field in state.Values) { // Iterate through all Tokens on the Field foreach (string token in field) { // When Token is not the highest Token on the Field if (token != field.Peek()) { // The Token is covered // => add to covered tokens coveredTokens.Add(token); } } } // Iterate through all Tokens of the Player foreach (string token in allTokens) { // When Token is not covered if (!coveredTokens.Contains(token)) { // The Token is available // => add to available tokens availableTokens.Add(token); } } return(availableTokens); }
// Evaluate the given State for the given Player // Calls the Evaluation for each possible three field combination private static int EvaluateState(StringState state, Player player) { int res = 0; int fieldIndex = 0; // Check Horizontal for (fieldIndex = 0; fieldIndex < 8; fieldIndex += 3) { res += EvaluateThreeFields(state, player, new[] { (Field)fieldIndex, (Field)fieldIndex + 1, (Field)fieldIndex + 2 }); } // Check Vertical for (fieldIndex = 0; fieldIndex < 3; fieldIndex++) { res += EvaluateThreeFields(state, player, new[] { (Field)fieldIndex, (Field)fieldIndex + 3, (Field)fieldIndex + 6 }); } // Check Diagonal res += EvaluateThreeFields(state, player, new[] { Field.TopLeft, Field.Middle, Field.BottomRight }); res += EvaluateThreeFields(state, player, new[] { Field.TopRight, Field.Middle, Field.BottomLeft }); return(res); }
// Converts the given GameState with GameObjects to a StringState with Strings public static StringState ConvertState(GameState gameState) { StringState stringState = new StringState(); foreach (var field in gameState) { // NOTE: this is a string stack and can't be initialized directly with gameObject stack Stack <string> tokenStringStack = new Stack <string>(); // Convert Stack to Array to access not only the peek or pop the peek // NOTE: the stack may not be destructed (reference to current GameState) GameObject[] tokenGameObjectArray = field.Value.ToArray(); // Iterate backwards to push in the right order for (int i = tokenGameObjectArray.Length - 1; i >= 0; i--) { tokenStringStack.Push(tokenGameObjectArray[i].name); } stringState.Add(field.Key, tokenStringStack); } return(stringState); }
private string ReadString() { bool flag = false; char ch = '\0'; bool flag2 = true; bool flag3 = false; uint num = 0; StringBuilder builder = new StringBuilder(); while (!this.IsAtEndOfInput) { char currentChar = this.CurrentChar; if (flag) { builder.Append('\\'); builder.Append(currentChar); flag = false; goto Label_016E; } if (ch != '\0') { if (currentChar == '\\') { flag = true; goto Label_016E; } if (currentChar != ch) { builder.Append(currentChar); goto Label_016E; } currentChar = this.CurrentChar; ch = '\0'; break; } bool flag4 = false; switch (currentChar) { case '{': num++; builder.Append(currentChar); goto Label_014C; case '}': if (num != 0) { goto Label_0100; } flag4 = true; goto Label_014C; case '\\': flag = true; goto Label_014C; case '=': this._state = StringState.Property; flag4 = true; goto Label_014C; case ' ': if (this._state != StringState.Type) { break; } flag4 = true; goto Label_014C; case '"': case '\'': if (!flag2) { throw new XamlParseException(this, System.Xaml.SR.Get("QuoteCharactersOutOfPlace")); } ch = currentChar; flag3 = true; goto Label_014C; case ',': flag4 = true; goto Label_014C; default: builder.Append(currentChar); goto Label_014C; } builder.Append(currentChar); goto Label_014C; Label_0100: num--; builder.Append(currentChar); Label_014C: if (flag4) { if (num > 0) { throw new XamlParseException(this, System.Xaml.SR.Get("UnexpectedTokenAfterME")); } this.PushBack(); break; } Label_016E: flag2 = false; this.Advance(); } if (ch != '\0') { throw new XamlParseException(this, System.Xaml.SR.Get("UnclosedQuote")); } string str = builder.ToString(); if (!flag3) { str = str.TrimEnd(KnownStrings.WhitespaceChars).TrimStart(KnownStrings.WhitespaceChars); } return(str); }
public void Read() { bool flag = false; bool flag2 = false; this._tokenText = string.Empty; this._tokenXamlType = null; this._tokenProperty = null; this._tokenNamespace = null; this.Advance(); this.AdvanceOverWhitespace(); if (this.IsAtEndOfInput) { this._token = MeTokenType.None; } else { switch (this.CurrentChar) { case '{': this._token = MeTokenType.Open; this._state = StringState.Type; break; case '}': this._token = MeTokenType.Close; this._state = StringState.Value; break; case '=': this._token = MeTokenType.EqualSign; this._state = StringState.Value; break; case ',': this._token = MeTokenType.Comma; this._state = StringState.Value; break; case '"': case '\'': if (this.NextChar == '{') { flag = true; } flag2 = true; break; default: flag2 = true; break; } if (flag2) { string longName = this.ReadString(); this._token = flag ? MeTokenType.QuotedMarkupExtension : MeTokenType.String; switch (this._state) { case StringState.Type: this._token = MeTokenType.TypeName; this.ResolveTypeName(longName); break; case StringState.Property: this._token = MeTokenType.PropertyName; this.ResolvePropertyName(longName); break; } this._state = StringState.Value; this._tokenText = RemoveEscapes(longName); } } }
public new bool EvaluateToken(string token) { if (EvaluateAllToken(token)) return true; // Strings if (token.StartsWith("\"")) { CurrentMachine = new StringState("\""); if (!CurrentMachine.EvaluateToken(token)) { var ss = CurrentMachine as StringState; Core.Queue.Enqueue(ss.ResultString); CurrentMachine = null; } return true; } // Conditionals if (token.ToLower() == "if") { CurrentMachine = new ConditionalState(Core); return true; } if (EvaluateSuperToken(token)) { return true; } // Floats double floatVal; if (double.TryParse(token, out floatVal)) { if (token.Contains(".")) { Core.Queue.Enqueue(floatVal); return true; } } // Integers int intVal; if (int.TryParse(token, out intVal)) { Core.Queue.Enqueue(intVal); return true; } // Symbols if (Core.Variables.Contains(token)) { Core.Queue.Enqueue(new MuftecStackItem(token, MuftecAdvType.Variable, Core.LineNumber)); return true; } if (Core.Functions.ContainsKey(token)) { Core.Queue.Enqueue(new MuftecStackItem(token, MuftecAdvType.Function, Core.LineNumber)); return true; } // OpCodes - assume any remaining value is an opcode, don't need to check Core.Queue.Enqueue(new MuftecStackItem(token, MuftecAdvType.OpCode, Core.LineNumber)); return true; }
private string ReadString() { bool escaped = false; char quoteChar = NullChar; bool atStart = true; bool wasQuoted = false; uint braceCount = 0; // To be compat with v3 which allowed balanced {} inside of strings StringBuilder sb = new StringBuilder(); char ch; while (!IsAtEndOfInput) { ch = CurrentChar; // handle escaping and quoting first. if (escaped) { sb.Append('\\'); sb.Append(ch); escaped = false; } else if (quoteChar != NullChar) { if (ch == Backslash) { escaped = true; } else if (ch != quoteChar) { sb.Append(ch); } else { ch = CurrentChar; quoteChar = NullChar; break; // we are done. } } // If we are inside of MarkupExtensionBracketCharacters for a particular property or position parameter, // scoop up everything inside one by one, and keep track of nested Bracket Characters in the stack. else if (_context.CurrentBracketModeParseParameters != null && _context.CurrentBracketModeParseParameters.IsBracketEscapeMode) { Stack <char> bracketCharacterStack = _context.CurrentBracketModeParseParameters.BracketCharacterStack; if (_currentSpecialBracketCharacters.StartsEscapeSequence(ch)) { bracketCharacterStack.Push(ch); } else if (_currentSpecialBracketCharacters.EndsEscapeSequence(ch)) { if (_currentSpecialBracketCharacters.Match(bracketCharacterStack.Peek(), ch)) { bracketCharacterStack.Pop(); } else { throw new XamlParseException(this, SR.Get(SRID.InvalidClosingBracketCharacers, ch.ToString())); } } else if (ch == Backslash) { escaped = true; } if (bracketCharacterStack.Count == 0) { _context.CurrentBracketModeParseParameters.IsBracketEscapeMode = false; } if (!escaped) { sb.Append(ch); } } else { bool done = false; switch (ch) { case Space: if (_state == StringState.Type) { done = true; // we are done. break; } sb.Append(ch); break; case OpenCurlie: braceCount++; sb.Append(ch); break; case CloseCurlie: if (braceCount == 0) { done = true; } else { braceCount--; sb.Append(ch); } break; case Comma: done = true; // we are done. break; case EqualSign: _state = StringState.Property; done = true; // we are done. break; case Backslash: escaped = true; break; case Quote1: case Quote2: if (!atStart) { throw new XamlParseException(this, SR.Get(SRID.QuoteCharactersOutOfPlace)); } quoteChar = ch; wasQuoted = true; break; default: // All other character (including whitespace) if (_currentSpecialBracketCharacters != null && _currentSpecialBracketCharacters.StartsEscapeSequence(ch)) { Stack <char> bracketCharacterStack = _context.CurrentBracketModeParseParameters.BracketCharacterStack; bracketCharacterStack.Clear(); bracketCharacterStack.Push(ch); _context.CurrentBracketModeParseParameters.IsBracketEscapeMode = true; } sb.Append(ch); break; } if (done) { if (braceCount > 0) { throw new XamlParseException(this, SR.Get(SRID.UnexpectedTokenAfterME)); } else { if (_context.CurrentBracketModeParseParameters?.BracketCharacterStack.Count > 0) { throw new XamlParseException(this, SR.Get(SRID.MalformedBracketCharacters, ch.ToString())); } } PushBack(); break; // we are done. } } atStart = false; Advance(); } if (quoteChar != NullChar) { throw new XamlParseException(this, SR.Get(SRID.UnclosedQuote)); } string result = sb.ToString(); if (!wasQuoted) { result = result.TrimEnd(KnownStrings.WhitespaceChars); result = result.TrimStart(KnownStrings.WhitespaceChars); } if (_state == StringState.Property) { _currentParameterName = result; _currentSpecialBracketCharacters = GetBracketCharacterForProperty(_currentParameterName); } return(result); }
public void Read() { bool isQuotedMarkupExtension = false; bool readString = false; _tokenText = string.Empty; _tokenXamlType = null; _tokenProperty = null; _tokenNamespace = null; Advance(); AdvanceOverWhitespace(); if (IsAtEndOfInput) { _token = MeTokenType.None; return; } switch (CurrentChar) { case OpenCurlie: if (NextChar == CloseCurlie) // the {} escapes the ME. return the string. { _token = MeTokenType.String; _state = StringState.Value; readString = true; // ReadString() will strip the leading {} } else { _token = MeTokenType.Open; _state = StringState.Type; // types follow '{' } break; case Quote1: case Quote2: if (NextChar == OpenCurlie) { Advance(); // read ahead one character if (NextChar != CloseCurlie) // check for the '}' of a {} { isQuotedMarkupExtension = true; } PushBack(); // put back the read-ahead. } readString = true; // read substring" break; case CloseCurlie: _token = MeTokenType.Close; _state = StringState.Value; break; case EqualSign: _token = MeTokenType.EqualSign; _state = StringState.Value; _context.CurrentBracketModeParseParameters.IsConstructorParsingMode = false; break; case Comma: _token = MeTokenType.Comma; _state = StringState.Value; if (_context.CurrentBracketModeParseParameters.IsConstructorParsingMode) { _context.CurrentBracketModeParseParameters.IsConstructorParsingMode = ++_context.CurrentBracketModeParseParameters.CurrentConstructorParam < _context.CurrentBracketModeParseParameters.MaxConstructorParams; } break; default: readString = true; break; } if (readString) { if (_context.CurrentType.IsMarkupExtension && _context.CurrentBracketModeParseParameters != null && _context.CurrentBracketModeParseParameters.IsConstructorParsingMode) { int currentCtrParam = _context.CurrentBracketModeParseParameters.CurrentConstructorParam; _currentParameterName = _context.CurrentLongestConstructorOfMarkupExtension[currentCtrParam].Name; _currentSpecialBracketCharacters = GetBracketCharacterForProperty(_currentParameterName); } string str = ReadString(); _token = (isQuotedMarkupExtension) ? MeTokenType.QuotedMarkupExtension : MeTokenType.String; switch (_state) { case StringState.Value: break; case StringState.Type: _token = MeTokenType.TypeName; ResolveTypeName(str); break; case StringState.Property: _token = MeTokenType.PropertyName; ResolvePropertyName(str); break; } _state = StringState.Value; _tokenText = RemoveEscapes(str); } }
private string ReadString () { bool flag = false; char ch = '\0'; bool flag2 = true; bool flag3 = false; uint num = 0; StringBuilder builder = new StringBuilder(); while (!this.IsAtEndOfInput) { char currentChar = this.CurrentChar; if (flag) { builder.Append('\\'); builder.Append(currentChar); flag = false; goto Label_016E; } if (ch != '\0') { if (currentChar == '\\') { flag = true; goto Label_016E; } if (currentChar != ch) { builder.Append(currentChar); goto Label_016E; } currentChar = this.CurrentChar; ch = '\0'; break; } bool flag4 = false; switch (currentChar) { case '{': num++; builder.Append(currentChar); goto Label_014C; case '}': if (num != 0) { goto Label_0100; } flag4 = true; goto Label_014C; case '\\': flag = true; goto Label_014C; case '=': this._state = StringState.Property; flag4 = true; goto Label_014C; case ' ': if (this._state != StringState.Type) { break; } flag4 = true; goto Label_014C; case '"': case '\'': if (!flag2) { throw new XamlParseException(this, SR.Get("QuoteCharactersOutOfPlace")); } ch = currentChar; flag3 = true; goto Label_014C; case ',': flag4 = true; goto Label_014C; default: builder.Append(currentChar); goto Label_014C; } builder.Append(currentChar); goto Label_014C; Label_0100: num--; builder.Append(currentChar); Label_014C: if (flag4) { if (num > 0) { throw new XamlParseException(this, SR.Get("UnexpectedTokenAfterME")); } this.PushBack(); break; } Label_016E: flag2 = false; this.Advance(); } if (ch != '\0') { throw new XamlParseException(this, SR.Get("UnclosedQuote")); } string str = builder.ToString(); if (!flag3) { str = str.TrimEnd(KnownStrings.WhitespaceChars).TrimStart(KnownStrings.WhitespaceChars); } return str; }
public void Read () { bool flag = false; bool flag2 = false; this._tokenText = string.Empty; this._tokenXamlType = null; this._tokenProperty = null; this._tokenNamespace = null; this.Advance(); this.AdvanceOverWhitespace(); if (this.IsAtEndOfInput) { this._token = MeTokenType.None; } else { switch (this.CurrentChar) { case '{': if (this.NextChar != '}') { this._token = MeTokenType.Open; this._state = StringState.Type; } else { this._token = MeTokenType.String; this._state = StringState.Value; flag2 = true; } break; case '}': this._token = MeTokenType.Close; this._state = StringState.Value; break; case '=': this._token = MeTokenType.EqualSign; this._state = StringState.Value; break; case ',': this._token = MeTokenType.Comma; this._state = StringState.Value; break; case '"': case '\'': if (this.NextChar == '{') { this.Advance(); if (this.NextChar != '}') { flag = true; } this.PushBack(); } flag2 = true; break; default: flag2 = true; break; } if (flag2) { string longName = this.ReadString(); this._token = flag ? MeTokenType.QuotedMarkupExtension : MeTokenType.String; switch (this._state) { case StringState.Type: this._token = MeTokenType.TypeName; this.ResolveTypeName(longName); break; case StringState.Property: this._token = MeTokenType.PropertyName; this.ResolvePropertyName(longName); break; } this._state = StringState.Value; this._tokenText = RemoveEscapes(longName); } } }
/***** Public Function *****/ // Returns the best AI Move for the given state public static MoveString GetBestMove(StringState state) { // Execute the Alpha Beta Search with the appropriate params and return the best move directly as a MoveString return(AlphaBetaRoot(Constants.AI_DEPTH, state, Constants.AI_PLAYER)); }
public bool ScanTokenAndProvideInfoAboutIt(TokenInfo tokenInfo, ref int state) { Token token = null; if (tokenizer.IsEndOfFile) { return(false); } switch (state) { case 0: token = tokenizer.Next(); break; default: if (state <= (int)StringState.Max) { StringState strState = (StringState)state; token = tokenizer.ContinueString( (strState & StringState.SingleQuote) != 0 ? '\'' : '"', (strState & StringState.RawString) != 0, (strState & StringState.UnicodeString) != 0, (strState & StringState.LongString) != 0 ); } break; } state = 0; tokenInfo.Trigger = TokenTriggers.None; switch (token.Kind) { case TokenKind.Error: case TokenKind.NewLine: goto default; case TokenKind.Indent: case TokenKind.Dedent: tokenInfo.Trigger = TokenTriggers.MatchBraces; goto default; case TokenKind.Comment: tokenInfo.Type = TokenType.LineComment; tokenInfo.Color = TokenColor.Comment; break; case TokenKind.Dot: tokenInfo.Trigger = TokenTriggers.MemberSelect; goto case TokenKind.Assign; case TokenKind.LeftParenthesis: tokenInfo.Trigger = TokenTriggers.MatchBraces | TokenTriggers.ParameterStart; goto case TokenKind.Assign; case TokenKind.RightParenthesis: tokenInfo.Trigger = TokenTriggers.MatchBraces | TokenTriggers.ParameterEnd; goto case TokenKind.Assign; case TokenKind.LeftBracket: tokenInfo.Trigger = TokenTriggers.MatchBraces; goto case TokenKind.Assign; case TokenKind.RightBracket: tokenInfo.Trigger = TokenTriggers.MatchBraces; goto case TokenKind.Assign; case TokenKind.LeftBrace: tokenInfo.Trigger = TokenTriggers.MatchBraces; goto case TokenKind.Assign; case TokenKind.RightBrace: tokenInfo.Trigger = TokenTriggers.MatchBraces; goto case TokenKind.Assign; case TokenKind.Comma: tokenInfo.Trigger = TokenTriggers.ParameterNext; goto case TokenKind.Assign; case TokenKind.Colon: case TokenKind.BackQuote: case TokenKind.Semicolon: case TokenKind.Assign: case TokenKind.Twiddle: case TokenKind.LessThanGreaterThan: tokenInfo.Type = TokenType.Delimiter; tokenInfo.Color = TokenColor.Text; break; case TokenKind.Add: case TokenKind.AddEqual: case TokenKind.Subtract: case TokenKind.SubtractEqual: case TokenKind.Power: case TokenKind.PowerEqual: case TokenKind.Multiply: case TokenKind.MultiplyEqual: case TokenKind.FloorDivide: case TokenKind.FloorDivideEqual: case TokenKind.Divide: case TokenKind.DivEqual: case TokenKind.Mod: case TokenKind.ModEqual: case TokenKind.LeftShift: case TokenKind.LeftShiftEqual: case TokenKind.RightShift: case TokenKind.RightShiftEqual: case TokenKind.BitwiseAnd: case TokenKind.BitwiseAndEqual: case TokenKind.BitwiseOr: case TokenKind.BitwiseOrEqual: case TokenKind.Xor: case TokenKind.XorEqual: case TokenKind.LessThan: case TokenKind.GreaterThan: case TokenKind.LessThanOrEqual: case TokenKind.GreaterThanOrEqual: case TokenKind.Equal: case TokenKind.NotEqual: tokenInfo.Type = TokenType.Operator; tokenInfo.Color = TokenColor.Text; break; case TokenKind.KeywordAnd: case TokenKind.KeywordAssert: case TokenKind.KeywordBreak: case TokenKind.KeywordClass: case TokenKind.KeywordContinue: case TokenKind.KeywordDef: case TokenKind.KeywordDel: case TokenKind.KeywordElseIf: case TokenKind.KeywordElse: case TokenKind.KeywordExcept: case TokenKind.KeywordExec: case TokenKind.KeywordFinally: case TokenKind.KeywordFor: case TokenKind.KeywordFrom: case TokenKind.KeywordGlobal: case TokenKind.KeywordIf: case TokenKind.KeywordImport: case TokenKind.KeywordIn: case TokenKind.KeywordIs: case TokenKind.KeywordLambda: case TokenKind.KeywordNot: case TokenKind.KeywordOr: case TokenKind.KeywordPass: case TokenKind.KeywordPrint: case TokenKind.KeywordRaise: case TokenKind.KeywordReturn: case TokenKind.KeywordTry: case TokenKind.KeywordWhile: case TokenKind.KeywordYield: tokenInfo.Type = TokenType.Keyword; tokenInfo.Color = TokenColor.Keyword; break; case TokenKind.Name: tokenInfo.Type = TokenType.Identifier; tokenInfo.Color = TokenColor.Identifier; // To show the statement completion for the current name we have to // set the MemberSelect trigger on the token, but we don't want to do // it too often to avoid to show the completion window also after the // user dismiss it, so we set the trigger only if the name is 1 char long // that is close enough to the condition that the user has just started // to type the name. if (tokenizer.EndLocation.Column <= tokenizer.StartLocation.Column + 1) { tokenInfo.Trigger = TokenTriggers.MemberSelect; } break; case TokenKind.Constant: ConstantValueToken ctoken = (ConstantValueToken)token; if (ctoken.Constant is string) { tokenInfo.Type = TokenType.String; tokenInfo.Color = TokenColor.String; } else { tokenInfo.Type = TokenType.Literal; tokenInfo.Color = TokenColor.Number; } IncompleteStringToken ist = ctoken as IncompleteStringToken; if (ist != null) { StringState strState = StringState.IncompleteString; if (ist.IsRaw) { strState |= StringState.RawString; } if (ist.IsUnicode) { strState |= StringState.UnicodeString; } if (ist.IsTripleQuoted) { strState |= StringState.LongString; } if (ist.IsSingleTickQuote) { strState |= StringState.SingleQuote; } state = (int)strState; } break; default: tokenInfo.Type = TokenType.Unknown; tokenInfo.Color = TokenColor.Text; return(false); } tokenInfo.StartIndex = tokenizer.StartLocation.Column; tokenInfo.EndIndex = tokenizer.EndLocation.Column > tokenizer.StartLocation.Column ? tokenizer.EndLocation.Column - 1 : tokenizer.EndLocation.Column; return(true); }
// Check the GameField for Three same tokens in a Row // Return the winner or null public static Player?CheckWinner(StringState GameField) { int fieldIndex = 0; Player?winner = null; // Check Horizontal Winner for (fieldIndex = 0; fieldIndex < 8; fieldIndex += 3) { // Check if fields are available (if they are they contain at least one token) if (GameField.ContainsKey((Field)fieldIndex) && GameField.ContainsKey((Field)fieldIndex + 1) && GameField.ContainsKey((Field)fieldIndex + 2)) { // Check the parent name (= Player Name) of the peek (= highest Token) on the Fields winner = ComparePlayerOnFields(GameField[(Field)fieldIndex].Peek(), GameField[(Field)fieldIndex + 1].Peek(), GameField[(Field)fieldIndex + 2].Peek()); // return winner directly when detected if (winner != null) { return(winner); } } } // Check Vertical Winner for (fieldIndex = 0; fieldIndex < 3; fieldIndex++) { // Check if fields are available (if they are they contain at least one token) if (GameField.ContainsKey((Field)fieldIndex) && GameField.ContainsKey((Field)fieldIndex + 3) && GameField.ContainsKey((Field)fieldIndex + 6)) { // Check the parent name (= Player Name) of the peek (= highest Token) on the Fields winner = ComparePlayerOnFields(GameField[(Field)fieldIndex].Peek(), GameField[(Field)fieldIndex + 3].Peek(), GameField[(Field)fieldIndex + 6].Peek()); // return winner directly when detected if (winner != null) { return(winner); } } } // Check Diagonal Winner if (GameField.ContainsKey(Field.TopLeft) && GameField.ContainsKey(Field.Middle) && GameField.ContainsKey(Field.BottomRight)) { // Check the parent name (= Player Name) of the peek (= highest Token) on the Fields winner = ComparePlayerOnFields(GameField[Field.TopLeft].Peek(), GameField[Field.Middle].Peek(), GameField[Field.BottomRight].Peek()); // return winner directly when detected if (winner != null) { return(winner); } } if (GameField.ContainsKey(Field.TopRight) && GameField.ContainsKey(Field.Middle) && GameField.ContainsKey(Field.BottomLeft)) { // Check the parent name (= Player Name) of the peek (= highest Token) on the Fields winner = ComparePlayerOnFields(GameField[Field.TopRight].Peek(), GameField[Field.Middle].Peek(), GameField[Field.BottomLeft].Peek()); } // return winner or null when no winner detected return(winner); }
internal static string?EscapeString(string?unescaped, char[] toEscape) { if (Strings.IsNullOrWhiteSpace(unescaped)) { return(unescaped); } bool ShouldEscape(char c) { foreach (char escapeChar in toEscape) { if (escapeChar == c) { return(true); } } return(false); } StringState currentState = StringState.NormalCharacter; var finalBuilder = PooledStringBuilder.GetInstance(); foreach (char currentChar in unescaped) { switch (currentState) { case StringState.NormalCharacter: // If we're currently not in a quoted string, then we need to escape anything in toEscape. // The valid transitions are to EscapedCharacter (for a '\', such as '\"'), and QuotedString. if (currentChar == '\\') { currentState = StringState.EscapedCharacter; } else if (currentChar == '"') { currentState = StringState.QuotedString; } else if (ShouldEscape(currentChar)) { finalBuilder.Append('^'); } break; case StringState.EscapedCharacter: // If a '\' was the previous character, then we blindly append to the string, escaping if necessary, // and move back to NormalCharacter. This handles '\"' if (ShouldEscape(currentChar)) { finalBuilder.Append('^'); } currentState = StringState.NormalCharacter; break; case StringState.QuotedString: // If we're in a string, we don't escape any characters. If the current character is a '\', // then we move to QuotedStringEscapedCharacter. This handles '\"'. If the current character // is a '"', then we're out of the string. Otherwise, we stay in the string. if (currentChar == '\\') { currentState = StringState.QuotedStringEscapedCharacter; } else if (currentChar == '"') { currentState = StringState.NormalCharacter; } break; case StringState.QuotedStringEscapedCharacter: // If we have one slash, then we blindly append to the string, no escaping, and move back to // QuotedString. This handles escaped '"' inside strings. currentState = StringState.QuotedString; break; default: // We can't get here. throw new InvalidOperationException(); } finalBuilder.Append(currentChar); } return(finalBuilder.ToStringAndFree()); }
// The recursive alpha beta function // Checks every possible move for every recursion step (depth) // Stops the search by the alpha and beta cap value // Optimization: Checks for win or loose when depth is not reached yet // Returns the value for the root move, calculated by the evaluation function private static int AlphaBeta(int depth, StringState state, Player player, int alpha, int beta) { // Optimization: Checks for win or loose when depth is not reached yet // It is not necessary to look any further if win or loose // The earlier the detection the higher the value if (depth > 0) { // Check for the winner (may be empty) Player?winner = WinDetection.CheckWinner(state); // Has the ai won the game? if (winner == Constants.AI_PLAYER) { // Return high value (like 1000) // The higher the left recursion count the better the value return(1000 * Constants.AI_DEPTH); } // Has the ai lost the game? if (winner == TypeConverter.GetOpponent(Constants.AI_PLAYER)) { // Return low value (like -1000) // The higher the left recursion count the lower the value return(-1000 * Constants.AI_DEPTH); } } // Otherwise the depth is reached (last recursion step) else { // Evaluate the leaf return(EvaluateState(state, player)); } // Switch player after win detection // After evaluation this won't be necessary anymore // But eval has to be calculated for the player for which the current recursion call was made player = TypeConverter.GetOpponent(player); // Get all possible moves for the current state and player List <MoveString> possibleMoves = GetPossibleMoves(state, player); // If the Player is the ai the vale will be maxed if (player == Constants.AI_PLAYER) { // Start with lowest possible value int bestValue = int.MinValue; // Iterate through each possible move foreach (MoveString move in possibleMoves) { // Generate a new reference state with the move on the previous state StringState moveState = GetStateWithMove(state, move); // Check for the highest value in the recursion bestValue = Math.Max(bestValue, AlphaBeta(depth - 1, moveState, player, alpha, beta)); // Alpha beta Pruning alpha = Math.Max(alpha, bestValue); if (beta <= alpha) { return(bestValue); } } return(bestValue); } // Otherwise the value will be minned for the opponent else { // Start with highest possible value int bestValue = int.MaxValue; // Iterate through each possible move foreach (MoveString move in possibleMoves) { // Generate a new reference state with the move on the previous state StringState moveState = GetStateWithMove(state, move); // Check for the lowest value in the recursion bestValue = Math.Min(bestValue, AlphaBeta(depth - 1, moveState, player, alpha, beta)); // Alpha beta Pruning beta = Math.Min(beta, bestValue); if (beta <= alpha) { return(bestValue); } } return(bestValue); } }