private void AssignActions() { actions = new Action[4, 5]; actions[0, 0] = new Action(AddAuthor); actions[1, 0] = new Action(ReadAuthors); actions[2, 0] = new Action(UpdateAuthor); actions[3, 0] = new Action(DeleteAuthor); actions[0, 1] = new Action(AddCategory); actions[1, 1] = new Action(ReadCategories); actions[2, 1] = new Action(UpdateCategory); actions[3, 1] = new Action(DeleteCategory); actions[0, 2] = new Action(AddComic); actions[1, 2] = new Action(ReadComics); actions[2, 2] = new Action(UpdateComic); actions[3, 2] = new Action(DeleteComic); actions[0, 3] = new Action(AddPublishingHouse); actions[1, 3] = new Action(ReadPublishingHouses); actions[2, 3] = new Action(UpdatePublishingHouse); actions[3, 3] = new Action(DeletePublishingHouse); actions[0, 4] = new Action(AddCountry); actions[1, 4] = new Action(ReadCountries); actions[2, 4] = new Action(UpdateCountry); actions[3, 4] = new Action(DeleteCountry); statistics = new Action[4]; statistics[0] = new Action(ComicsPerCategory); statistics[1] = new Action(ComicsPerAuthor); statistics[2] = new Action(LongestComics); statistics[3] = new Action(AuthorsPerNationality); }
private OrbitOrderWindow(EntityState entity, bool smMode = false) { OrderingEntity = entity; _smMode = smMode; IsActive = true; _displayText = "Orbit Order: " + OrderingEntity.Name; _tooltipText = "Select target to orbit"; CurrentState = States.NeedsTarget; if (OrderingEntity.Entity.HasDataBlob <OrbitDB>()) { //_orbitWidget = new OrbitOrderWiget(OrderingEntity.Entity.GetDataBlob<OrbitDB>()); //_state.MapRendering.UIWidgets.Add(_orbitWidget); if (_moveWidget == null) { _moveWidget = new TranslateMoveOrderWidget(_state, OrderingEntity.Entity); _state.MapRendering.UIWidgets.Add(_moveWidget); } } fsm = new Action[4, 4] { //selectEntity selectPos clickAction altClick { DoNothing, DoNothing, DoNothing, AbortOrder, }, //needsEntity { TargetSelected, DoNothing, DoNothing, GoBackState, }, //needsTarget { DoNothing, InsertionPntSelected, DoNothing, GoBackState, }, //needsApopapsis //{DoNothing, PeriapsisPntSelected, DoNothing, GoBackState, }, //needsPeriapsis { DoNothing, DoNothing, ActionCmd, GoBackState, } //needsActoning }; }
public Actions() { var srw = 1f; var trw = 1f; var steeringwidth = 2f; var tourquewidth = 2f; var steeringcount = (int)Math.Ceiling(steeringwidth / srw) + 1; var tourquecount = (int)Math.Ceiling(tourquewidth / trw) + 1; ActionTable = new Action[steeringcount, tourquecount]; for (var s = 0; s < steeringcount; s++) { for (var t = 0; t < tourquecount; t++) { ActionTable[s, t] = new Action() { SteeringAngle = srw * s - 1, Tourque = trw * t - 1, TourqueNumber = t, SteeringNumber = s, SteeringCount = steeringcount, TourgueCount = tourquecount }; } } }
public Scanner() { ActionTable = new Action[, ] { // Ready Identifier Number Delimiter Assignment CommentBegin Comment CommentEnd { /* Letter */ () => {}, null, AddNumber, AddDelimiter, Error2, Error0, null, null }, { /* Digit */ () => {}, null, null, AddDelimiter, Error2, Error0, null, null }, { /* Delimiter */ () => {}, AddIdentifier, AddNumber, AddDelimiter, Error2, Error0, null, null }, { /* Colon */ () => {}, AddIdentifier, AddNumber, AddDelimiter, Error2, Error0, null, null }, { /* Equality */ Error1, Error1, Error1, Error1, null, Error0, null, null }, { /* LeftBracket */ null, AddIdentifier, AddNumber, AddDelimiter, Error2, Error0, null, null }, { /* RightBracket */ Error1, Error1, Error1, Error1, Error2, Error0, null, null }, { /* Asterisk */ Error1, Error1, Error1, Error1, Error2, null, null, null }, { /* Whitespace*/ null, AddIdentifier, AddNumber, AddDelimiter, Error2, Error0, null, null }, { /* Other */ Error1, Error1, Error1, Error1, Error2, Error0, null, null }, { /* EndOfFile */ null, Error3, Error3, AddDelimiter, Error3, Error3, Error3, Error3 } }; #region Define table of attributes for (var c = 0; c < attributes.Length; c++) { attributes[c] = Attribute.Other; } for (var c = '0'; c <= '9'; c++) { attributes[c] = Attribute.Digit; } for (var c = 'A'; c <= 'Z'; c++) { attributes[c] = attributes[char.ToLower(c)] = Attribute.Letter; } attributes['+'] = attributes['-'] = attributes[';'] = attributes['.'] = Attribute.Delimiter; attributes[':'] = Attribute.Colon; attributes['='] = Attribute.Equality; attributes['*'] = Attribute.Asterisk; attributes['('] = Attribute.LeftBracket; attributes[')'] = Attribute.RightBracket; attributes[' '] = attributes['\t'] = attributes['\n'] = attributes['\r'] = Attribute.Whitespace; #endregion #region Define keywords foreach (string token in Keywords) { identifiers[token] = identifier++; } #endregion #region Define long delimiters longDelimiters.Add(":=", longDelimiter++); #endregion }
public StateMachineBasic() { this.fsm = new Action[3, 3] { //EnemyInSight, HPLow, NoEnemyInSight, { this.DoNothing, this.Run, this.Roam }, //Attacking { this.DoNothing, this.DoNothing, this.Roam }, //Running { this.Attack, this.DoNothing, this.DoNothing } //Roaming }; }
public FiniteStateMachine() { this.fsm = new Action[3, 4] { //PlugIn, TurnOn, TurnOff, RemovePower { this.PowerOn, this.DoNothing, this.DoNothing, this.DoNothing }, //start { this.DoNothing, this.StandbyWhenOff, this.DoNothing, this.PowerOff }, //standby { this.DoNothing, this.DoNothing, this.StandbyWhenOn, this.PowerOff } }; //on }
public FiniteStateMachine() { this.transition = new Action[4, 6] { //hasTarget, //noTarget //ramable //notRamable //lowEnergy //highEnergy { this.toAttack, this.toStart, this.toRam, this.toAttack, this.toFlee, this.toStart }, //start { this.toAttack, this.toStart, this.toRam, this.toAttack, this.toFlee, this.toAttack }, //attack { this.toRam, this.toStart, this.toRam, this.toAttack, this.toFlee, this.toRam }, //ram { this.toFlee, this.toStart, this.toFlee, this.toFlee, this.toFlee, this.toAttack } //flee }; }
public DoorTable() { currState = DoorState.Close; this.fsm = new Action[4, 4] { { null, null, null, this.PerformClose }, //Opened { this.PerformStop, null, null, this.PerformClose }, { null, null, this.PerformOpen, null }, { null, this.PerformStop, this.PerformOpen, null } }; }
public FiniteStateMachine() { // Upon instantiation of this FiniteStateMachine class the Action 2D array (fsm) gets populated // with all of the transitions(methods) for each input X for each state. this.fsm = new Action[3, 4] { //PlugIn, TurnOn, TurnOff, Unplug { this.PowerOn, null, null, null }, //off { null, this.StandbyWhileOff, null, this.PowerOff }, //standby { null, null, this.StandbyWhileOn, this.PowerOff } }; //on }
public Scanner() { ActionTable = new Action[,] { // Ready Identifier Number Delimiter Assignment CommentBegin Comment CommentEnd {/* Letter */ () => {}, null, AddNumber, AddDelimiter, Error2, Error0, null, null }, {/* Digit */ () => {}, null, null, AddDelimiter, Error2, Error0, null, null }, {/* Delimiter */ () => {}, AddIdentifier, AddNumber, AddDelimiter, Error2, Error0, null, null }, {/* Colon */ () => {}, AddIdentifier, AddNumber, AddDelimiter, Error2, Error0, null, null }, {/* Equality */ Error1, Error1, Error1, Error1, null, Error0, null, null }, {/* LeftBracket */ null, AddIdentifier, AddNumber, AddDelimiter, Error2, Error0, null, null }, {/* RightBracket */ Error1, Error1, Error1, Error1, Error2, Error0, null, null }, {/* Asterisk */ Error1, Error1, Error1, Error1, Error2, null, null, null }, {/* Whitespace*/ null, AddIdentifier, AddNumber, AddDelimiter, Error2, Error0, null, null }, {/* Other */ Error1, Error1, Error1, Error1, Error2, Error0, null, null }, {/* EndOfFile */ null, Error3, Error3, AddDelimiter, Error3, Error3, Error3, Error3 } }; #region Define table of attributes for (var c = 0; c < attributes.Length; c++) attributes[c] = Attribute.Other; for (var c = '0'; c <= '9'; c++) attributes[c] = Attribute.Digit; for (var c = 'A'; c <= 'Z'; c++) attributes[c] = attributes[char.ToLower(c)] = Attribute.Letter; attributes['+'] = attributes['-'] = attributes[';'] = attributes['.'] = Attribute.Delimiter; attributes[':'] = Attribute.Colon; attributes['='] = Attribute.Equality; attributes['*'] = Attribute.Asterisk; attributes['('] = Attribute.LeftBracket; attributes[')'] = Attribute.RightBracket; attributes[' '] = attributes['\t'] = attributes['\n'] = attributes['\r'] = Attribute.Whitespace; #endregion #region Define keywords foreach (string token in Keywords) identifiers[token] = identifier++; #endregion #region Define long delimiters longDelimiters.Add(":=", longDelimiter++); #endregion }
public LockFSM(State initialState) { state = initialState; actionDelegates = new Dictionary <string, Action>(); fsm = new Action[, ] { // All Events and States of FSM and possible transitions // Engage, Contact, Slip, Lock, Disengage, Unlock, Release Break { Engage, null, null, null, null, null, null, Break }, // Idle { null, Lock, null, null, Disengage, null, null, Break }, // Ready { null, null, Slip, Locked, Disengage, null, null, Break }, // Locking { null, null, null, null, null, Unlock, null, Break }, // Locked { null, null, null, null, null, null, Unlocked, Break }, // Unlocking { null, null, null, null, null, null, null, null } // Broken }; }
public int Start() { IsFlashInProgress = 0; queueStatusSync = Queue.Synchronized(usedQueue); vUpdateStatus((int)bootlogicState.Init); if (Interface.Equals("TCP/IP")) { TCP_Communication cominterface = new TCP_Communication(); cominterface.ipaddress = _ipaddress; cominterface.port = _TCPport; ComObjet = cominterface; } else if (Interface.Equals("UART")) { SerialCommunication cominterface = new SerialCommunication(); cominterface.BaudRate = _SerialBaudrate; cominterface.portname = _serialportname; ComObjet = cominterface; } else { } vUpdateStatus((int)bootlogicState.Connect); if (ComObjet.Connect() != 0) { return(-1); } vUpdateStatus((int)bootlogicState.Connected); oThread = new Thread(new ThreadStart(Bootlogic_Thread)); oThread.Start(); _stateAction = new Action[6, 2] { //Next Success, Next Fail { Erase, TargetDisconnectFailure }, // Hookup State { Write, TargetDisconnectFailure }, // Erase State { Check, TargetDisconnectFailure }, // Write State { Jump, TargetDisconnectFailure }, // Check State { TargetDisconnectSuccess, TargetDisconnectFailure }, // Jump state { null, null }, // Target Disconnect Failure State }; return(0); }
public void Start() { menus = new Menus(this); context = new ComicsContext(); AssignActions(); Location = MenuLocation.MainMenu; do { UpdateContext(); switch (Location) { case MenuLocation.MainMenu: exit = menus.MainMenu(); break; case MenuLocation.TableMenu: menus.TableMenu(); break; case MenuLocation.ActionMenu: actions[(int)menus.mainMenuSelection, (int)menus.tableSelection](); context.SaveChanges(); Location = MenuLocation.MainMenu; break; case MenuLocation.StatisticsMenu: menus.StatisticsMenu(); break; case MenuLocation.StatisticViewer: statistics[(int)menus.statisticSelection](); Location = MenuLocation.MainMenu; break; default: exit = true; break; } Console.Clear(); } while (!exit); context.Dispose(); }
/// <summary> /// Creates a new instance with the given dimensions. /// </summary> /// <param name="state_count">The number of states.</param> /// <param name="terminal_count">The number of <see cref="TerminalSymbol"/>s.</param> /// <param name="grammatical_count">The number of <see cref="GrammaticalSymbol"/>s.</param> /// <exception cref="ArgumentOutOfRangeException"> if any of the parameters is not positive.</exception> public ParserTable( int state_count, int terminal_count, int grammatical_count ) { if( state_count <= 0 ) throw new ArgumentOutOfRangeException("state_count"); if( terminal_count <= 0 ) throw new ArgumentOutOfRangeException("terminal_count"); if( grammatical_count <= 0 ) throw new ArgumentOutOfRangeException("grammatical_count"); this.state_count = state_count; this.terminal_count = terminal_count; this.grammatical_count = grammatical_count; this.actions = new Action[state_count, terminal_count]; for( int i = 0; i < state_count; ++i ) for( int j = 0; j < terminal_count; ++j ) this.actions[i, j] = Action.Error(); this.gotos = new int[state_count, grammatical_count]; }
private WarpOrderWindow(EntityState entityState, bool smMode = false) { _flags = ImGuiWindowFlags.AlwaysAutoResize; OrderingEntityState = entityState; _smMode = smMode; _displayText = "Warp Order: " + OrderingEntityState.Name; _tooltipText = "Select target to orbit"; CurrentState = States.NeedsTarget; //TargetEntity = new EntityState(Entity.InvalidEntity) { Name = "" }; if (OrderingEntityState.Entity.HasDataBlob <OrbitDB>()) { //_orbitWidget = new OrbitOrderWiget(OrderingEntity.Entity.GetDataBlob<OrbitDB>()); //_uiState.MapRendering.UIWidgets.Add(_orbitWidget); if (_moveWidget == null) { _moveWidget = new WarpMoveOrderWidget(_uiState, OrderingEntityState.Entity); _uiState.SelectedSysMapRender.UIWidgets.Add(nameof(_moveWidget), _moveWidget); } } if (OrderingEntityState.Entity.HasDataBlob <NewtonThrustAbilityDB>()) { var newtDB = OrderingEntityState.Entity.GetDataBlob <NewtonThrustAbilityDB>(); _maxDV = (float)newtDB.DeltaV; } fsm = new Action[4, 4] { //selectEntity selectPos clickAction altClick { DoNothing, DoNothing, DoNothing, AbortOrder, }, //needsEntity { TargetSelected, DoNothing, DoNothing, GoBackState, }, //needsTarget { DoNothing, InsertionPntSelected, DoNothing, GoBackState, }, //needsApopapsis //{DoNothing, PeriapsisPntSelected, DoNothing, GoBackState, }, //needsPeriapsis { DoNothing, DoNothing, ActionCmd, GoBackState, } //needsActoning }; }
public ParseTable(int states, int tokens) { _actions = new Action[states, tokens + 1]; }
public LR1Table(Grammar g, string miniflex) { lexer = LexerGenerator.Generate(miniflex); _grammar = g; //consider building a new grammar, not just stealing the pointer (as LL1). _grammar.GenerateFirstAndFollow(); _terminalLookup = new Dictionary <Symbol, int>(); _gotoLookup = new Dictionary <Tuple <Symbol, int>, int>(); _lr1 = new LR1(g); //Get terminal symbols from grammar var terminals = (_grammar.Symbols.Where(x => x.IsTerminal())).ToArray(); var nonTerminals = (_grammar.Symbols.Where(x => x.IsNonTerminal())).ToArray(); _acceptanceState = _lr1.AutomataStates.Keys.Count - 1; var maxState = _acceptanceState; for (var i = 0; i < terminals.Length; i++) { _terminalLookup.Add(terminals[i], i); } _terminalLookup.Add(new Symbol(Symbol.SymTypes.EOS, "$"), terminals.Length); //add the end of string symbol _table = new Action[_terminalLookup.Count, maxState + 1]; //generate Action lookUp table //Construct the table with the provided automaton for (var i = 0; i < maxState; i++) { var focusState = _lr1.AutomataStates[i]; //get the nth state //set reduce Actions var reduceRule = focusState.RuleToReduce; if (reduceRule != null) { reduceRule.Caret = 0; //reset the caret for (var j = 0; j < _grammar.ProductionRules.Count; j++) { if (!_grammar.ProductionRules[j].Equals(reduceRule)) { continue; } foreach (var follow in g.FollowSets[focusState.Header.Header]) { _table[_terminalLookup[follow], focusState.StateName] = new Action(ActionTypes.Reduce, j); } break; } } //set shift Actions foreach (var term in _terminalLookup.Keys.Where(term => focusState.PublicTransitions.ContainsKey(term))) { _table[_terminalLookup[term], focusState.StateName] = new Action(ActionTypes.Shift, focusState.PublicTransitions[term]); } //set goto lookup foreach (var nonTerm in nonTerminals.Where(nonTerm => focusState.PublicTransitions.ContainsKey(nonTerm))) { _gotoLookup[new Tuple <Symbol, int>(nonTerm, focusState.StateName)] = focusState.PublicTransitions[nonTerm]; } } }
public void Parse() { for (;;) { int state = state_stack.Peek(); if (!input_token_type_queue.Any()) { break; } int input_token_type = input_token_type_queue.Peek(); string input_token_value = input_token_value_queue.Peek(); Action[,] actions = parse_table.Actions; Action action = actions[state, input_token_type]; ActionType action_type = action.ActionType; if (action_type == ActionType.Shift) { input_token_type_queue.Dequeue(); input_token_value_queue.Dequeue(); int new_state = action.ActionParameter; state_stack.Push(new_state); token_type_stack.Push(input_token_type); token_value_stack.Push(input_token_value); parse_tree.Push(new Node { Children = new List <Node>(), token_type = input_token_type, token_value = input_token_value }); } else if (action_type == ActionType.Reduce) { int ap = action.ActionParameter; // ap is the production number. if (ap == 0 && input_token_type == 0) { break; // accept. } Production production = parser_generator.Productions[ap]; int rhs_count = production.Right.Count(); // Create tree node. Node node = new Node() { Children = new List <Node>() }; List <Node> reverse = new List <Node>(); // Pop off RHS. for (int i = 0; i < rhs_count; ++i) { state_stack.Pop(); int tt = token_type_stack.Pop(); string tv = token_value_stack.Pop(); Node pt = parse_tree.Pop(); node.Children.Insert(0, pt); } int new_state = state_stack.Peek(); int lhs = production.Left; lhs++; Action goto_action = actions[new_state, lhs]; token_type_stack.Push(lhs); if (lhs >= 1) { token_value_stack.Push(parser_generator.Grammar.Tokens[lhs - 1]); } else { token_value_stack.Push("ouch"); } node.token_type = production.Left; node.token_value = parser_generator.Grammar.Tokens[lhs - 1]; state_stack.Push(goto_action.ActionParameter); parse_tree.Push(node); } else if (action_type == ActionType.Error) { break; } else if (action_type == ActionType.Accept) { break; } else { throw new Exception("Unknown action."); } } ComputeStartEnd(); }
/// <summary> /// Criar e correr um jogo de Poker /// </summary> static void Example1() { //Criar um objeto do tipo Game, no inicio de cada jogo, com as regras do jogo atual. Game game = new Game(); //escolher tipo de jogo: limit ou nolimit game.BettingType = BettingType.NoLimit; //número de cartas de mesa que são adicionadas em cada ronda. no limit é sempre: game.NumBoardCards = new byte[] { 0, 3, 1, 1 }; //mesmo para cartas do jogador game.NumHoleCards = 2; //número máximo de raises em cada ronda. no no-limit texas hold'em não há limite... vamos colocar o máximo possível game.MaxRaises = new byte[] { 255, 255, 255, 255 }; //tamanho dos raises em cada ronda. não interessa para o no-limit poker game.RaiseSize = new int[] {}; //configurar o baralho. sempre igual game.NumRanks = 13; game.NumSuits = 4; //número de rondas game.NumRounds = 4; ///////////////////////// //// NOTA: Até aqui a configuração das regras é fixa! A partir das instruções abaixo, depende //// das condições iniciais do jogo específico!! //////////////////////// //indicar o numero de joadores //os jogadores são numerados de 0 a N-1 //não deves considerar os seats vazios! game.NumPlayers = 5; //escolher a estrutura de blinds por assento. //neste exemplo os jogadores na posicao 1 e na posicao 2 pagaram respetivamente 10 e 20. //nota que os valores sao sempre inteiros (considera a representacao em centimos de dolar) game.Blind[1] = 10; game.Blind[2] = 20; //indicar qual dos jogadores é o primeiro a jogar em cada ronda. //fiz uma função para auxiliar a atribuição para o no limit poker. //neste caso o primeiro jogador seria o que está na posição 2. game.FirstPlayer = GetFirstPlayerNoLimit(2, game.NumPlayers); //preencher os valores iniciais de dinheiro de cada jogador. preencher em centimos //jogador 0 tem 10 euros, jogador 1 tem 15 euros, jogador 2 tem 5 euros, jogador 3 tem 9.50 e jogador 4 tem 2 euros game.Stack = new[] { 1000, 1500, 500, 950, 200 }; ///////////////////////// //// NOTA: O jogo está agora configurado. Podes iniciar a simulação! //////////////////////// //Inicar um state para o jogo. O argumento handid (1337) é só um identificador para o estado, podes colocar o que quiseres //o argumento viewingPlayer (2) indica a posição na mesa do teu bot MatchState matchState = new MatchState(new State(1337, game), 2); //para modificar o estado do jogo é necessário ocorrer ações //as acções são executadas sequencialmente, e o estado do jogo é automáticamente modificado //não é necessário indicar quem realizou a ação //raise de 2 euros matchState.state.doAction(game, new Action(ActionType.Raise, 200)); //fold matchState.state.doAction(game, new Action(ActionType.Fold, 0)); //call matchState.state.doAction(game, new Action(ActionType.Call, 0)); //é possível verificar se determinada ação é válida //o segundo argumento booleano indica se a acção será corrigida para o valor mais próximo, //isto é, se a acção não for possível (ex: o valor exceder a stack do jogador), o valor da //acção é corrigido para o valor mais próximo possível Action action = new Action(ActionType.Raise, 500); matchState.state.IsValidAction(game, true, action); //deves preencher informação sobre as cartas assim que as detetares: //exemplo, as cartas do jogador 2 são Ás de ouros e Reis de Paus matchState.state.HoleCards[2, 0] = LIACC.Poker.Cards.Card.MakeCard("Ad"); // ou Cards.Card.AceDiamonds.Value matchState.state.HoleCards[2, 1] = LIACC.Poker.Cards.Card.MakeCard("Kc"); // ou Cards.Card.KingClubs.Value //preencher também as cartas em cada ronda //exemplo de River round matchState.state.BoardCards[0] = LIACC.Poker.Cards.Card.TwoClubs.Value; matchState.state.BoardCards[1] = LIACC.Poker.Cards.Card.TwoDiamonds.Value; matchState.state.BoardCards[2] = LIACC.Poker.Cards.Card.TwoHearts.Value; matchState.state.BoardCards[3] = LIACC.Poker.Cards.Card.TwoSpades.Value; matchState.state.BoardCards[4] = LIACC.Poker.Cards.Card.AceSpades.Value; //os seguintes dados do estado do jogo são disponibilizados // The hand's unique identifier uint a = matchState.state.HandId; // Largest bet so far, including all previous rounds int b = matchState.state.MaxSpent; // Minimum number of chips a player must have spend in total to raise // only used for noLimitBetting games int c = matchState.state.MinNoLimitRaiseTo; // Spent[ p ] gives the total amount put into the pot by player p int[] d = matchState.state.Spent; //Action[ r,i ] gives the i'th action in round r Action[,] e = matchState.state.Action; // ActingPlayer[ r,i ] gives the player who made action i in round r // we can always figure this out from the actions taken, but it's // easier to just remember this in multiplayer (because of folds) byte[,] f = matchState.state.ActingPlayer; // NumActions[ r ] gives the number of actions made in round r byte[] g = matchState.state.NumActions; // current round: a value between 0 and game.numRounds-1 // a showdown is still in numRounds-1, not a separate round var h = matchState.state.Round; // Indicates if the game is over bool i = matchState.state.Finished; //PlayerFolded[ p ] is non-zero if and only player p has folded bool[] j = matchState.state.PlayerFolded; }