Exemplo n.º 1
0
    def __init__(self, trigger):
        State.__init__(self)
        players = [p.PlayerLich(None), p.PlayerDemon(None), p.PlayerSmith(None), p.PlayerFungus(None)]
        enemies = [Enemies.Goblin(), Enemies.Goblin(), Enemies.Goblin(), Enemies.Goblin()]
        self.data = {
                     'battleStatus':'setup',
                     'battleComplete':False,
                     'elapsedTime':0,
                     'players_living':[x for x in players if x.Alive],
                     'players_dead':[x for x in players if not x.Alive],
                     'enemies_living':[x for x in enemies if x.Alive],# Enemies.Goblin(), Enemies.Goblin(), Enemies.Goblin(), Enemies.Goblin(), Enemies.Goblin()],
                     'enemies_dead':[x for x in enemies if not x.Alive],
                     'background': pg.transform.scale(pg.image.load(os.path.join('resources','battle','background.bmp')), (640,480))
                     }
        self.data['players'] = self.data['players_living'] + self.data['players_dead']
        self.data['enemies'] = self.data['enemies_living'] + self.data['enemies_dead']

        self.observer = Observable()
        self.observer.Subscribe(trigger)
        
        #arrange players
        for key, value in enumerate(self.data['players']):
            value.Position.SetPos((500, 30 + (20+64)*key))
        #arrange enemies
        for key, value in enumerate(self.data['enemies']):
            value.Position.SetPos((50 + 70*math.floor(key/3), 70 + (26+64)*(key%3)))  
        
        self.observer.Fire(self, type="loading", status="completed", battledata=self.data)
Exemplo n.º 2
0
 def __init__(self):
     State.__init__(self)
     self.image = pg.Surface((640,480))
     self.stateMachine = StateMachine()
     self.actions = [] #list of lists; contains [actor, action, target]
     self.selectIndex = 0
     self.battleData = None
     SetupBattle(self)
Exemplo n.º 3
0
 def __init__(self, battleData, trigger):
     State.__init__(self)
     self.battleData = battleData
     self.image = pg.Surface((640,480), pg.SRCALPHA, 32).convert_alpha()
     labellist = [Menu.MenuItem("Fight", 15), Menu.MenuItem("Magic", 15), Menu.MenuItem("Item", 15), Menu.MenuItem('Run', 15)]
     self.healthMenu = Menu.HealthDisplayMenu(battleData)
     self.actionSelectMenu = Menu.Menu(labellist, (506, 340), (128, 140), True, c.images['action_select_pane.bmp'], 4, 1, (0,10,0,10))
     self.actionsMenu = None
     self.visibleMenus = [self.healthMenu, self.actionSelectMenu]
     self.activeMenu = self.actionSelectMenu
     self.observer = Observable()
     self.observer.Subscribe(trigger)
     self.currentMenu = 'selectAction'
Exemplo n.º 4
0
    def __init__(self, vk, peer):
        self.state = State()

        self.rooms = Data.getRooms()
        self.locations = Data.getLocations()

        self.peer = str(peer)
        self.vk = vk

        self.duty: Duty = None
        self.new_duty: Duty = None
        self.old_duty: Duty = None

        # Remind Duty
        self.CURRENT_LOCATION = ''
        self.CURRENT_COMMENT = ''

        # Update Duty
        self.CURRENT_DUTY = []
        self.CURRENT_ROOMS = []
        self.CURRENT_LOCS = []
from numpy import sign

from rlbot.agents.base_agent import SimpleControllerState

from CowBotVector import Vec3
from GameState import Orientation
from Maneuvers import GroundTurn, NavigateTo
from StateMachine import State
import Strategy.TransitionBackFolder.MidBoost as MidBoost
import Strategy.TransitionBackFolder.BackBoost as BackBoost
import Strategy.TransitionBackFolder.BoostPad as BoostPad
import Strategy.TransitionBackFolder.Goal as Goal

MidBoostState = State(
    lambda game_info, next_states, sub_sm: MidBoost.transition(
        game_info, next_states, sub_sm),
    lambda game_info: MidBoost.startup(game_info),
    lambda game_info, sub_state_machine: MidBoost.get_controls(
        game_info, sub_state_machine), "MidBoost", True)
BackBoostState = State(
    lambda game_info, next_states, sub_sm: BackBoost.transition(
        game_info, next_states, sub_sm),
    lambda game_info: BackBoost.startup(game_info),
    lambda game_info, sub_state_machine: BackBoost.get_controls(
        game_info, sub_state_machine), "BackBoost", True)
BoostPadState = State(
    lambda game_info, next_states, sub_sm: BoostPad.transition(
        game_info, next_states, sub_sm),
    lambda game_info: BoostPad.startup(game_info),
    lambda game_info, sub_state_machine: BoostPad.get_controls(
        game_info, sub_state_machine), "BoostPad", True)
GoalState = State(
Exemplo n.º 6
0
from CowBotVector import Vec3
from StateMachine import State
import Strategy.KickoffFolder.DoKickoffFolder.DiagonalLeft as DiagonalLeft
import Strategy.KickoffFolder.DoKickoffFolder.DiagonalRight as DiagonalRight
import Strategy.KickoffFolder.DoKickoffFolder.OffcenterLeft as OffcenterLeft
import Strategy.KickoffFolder.DoKickoffFolder.OffcenterRight as OffcenterRight
import Strategy.KickoffFolder.DoKickoffFolder.FarBack as FarBack

########################################################################################################
#States for the next level down
########################################################################################################

DiagonalLeftState = State(
    lambda game_info, next_states, sub_sm: DiagonalLeft.transition(
        game_info, next_states, sub_sm),
    lambda game_info: DiagonalLeft.startup(game_info),
    lambda game_info, sub_state_machine: DiagonalLeft.get_controls(
        game_info, sub_state_machine), "DiagonalLeft", False)
DiagonalRightState = State(
    lambda game_info, next_states, sub_sm: DiagonalRight.transition(
        game_info, next_states, sub_sm),
    lambda game_info: DiagonalRight.startup(game_info),
    lambda game_info, sub_state_machine: DiagonalRight.get_controls(
        game_info, sub_state_machine), "DiagonalRight", False)
OffcenterLeftState = State(
    lambda game_info, next_states, sub_sm: OffcenterLeft.transition(
        game_info, next_states, sub_sm),
    lambda game_info: OffcenterLeft.startup(game_info),
    lambda game_info, sub_state_machine: OffcenterLeft.get_controls(
        game_info, sub_state_machine), "OffcenterLeft", False)
OffcenterRightState = State(
Exemplo n.º 7
0
class Bot:
    def __init__(self, vk, peer):
        self.state = State()

        self.rooms = Data.getRooms()
        self.locations = Data.getLocations()

        self.peer = str(peer)
        self.vk = vk

        self.duty: Duty = None
        self.new_duty: Duty = None
        self.old_duty: Duty = None

        # Remind Duty
        self.CURRENT_LOCATION = ''
        self.CURRENT_COMMENT = ''

        # Update Duty
        self.CURRENT_DUTY = []
        self.CURRENT_ROOMS = []
        self.CURRENT_LOCS = []

    def updateDuty(self, duty: Duty):
        self.duty = duty

    @staticmethod
    def createKeyboard(keyboard, list, elements_per_line=1):
        if elements_per_line == 1:
            for element in list[0:-1]:
                keyboard.add_button(element)
                keyboard.add_line()
            keyboard.add_button(list[-1])
            return keyboard
        elif elements_per_line == 2:
            i = 1

            is_odd = len(list) % 2 == 0

            end_point = -2
            if not is_odd:
                end_point = -1

            for element in list[0:end_point]:
                keyboard.add_button(element)
                if i == 2:
                    keyboard.add_line()
                    i = 0
                i += 1

            if is_odd:
                keyboard.add_button(list[-2])
                keyboard.add_button(list[-1])
            else:
                keyboard.add_button(list[-1])

            return keyboard

    def getResponseData(self, args=None):
        keyboard = VkKeyboard()
        message = ''

        # Main Menu State
        if self.state.getType() == States.Menu:
            keyboard = self.__startMenuKeyboard()
            message = 'Выберите действие'

        # Main Remind Duty State
        elif self.state.getType() == States.RemindDuty:
            if self.state.getState() == State.STATE[
                    States.RemindDuty]['ChoiceLocation']:
                keyboard = Bot.createKeyboard(keyboard, self.locations)
                message = 'Выберите локацию'

            if self.state.getState() == State.STATE[
                    States.RemindDuty]['Comment']:
                keyboard = Bot.createKeyboard(keyboard,
                                              ['Отправить без комментария'])
                message = 'Введите комментарий и нажмите отправить'
                self.CURRENT_LOCATION = args

            elif self.state.getState() == State.STATE[
                    States.RemindDuty]['End']:
                self.CURRENT_COMMENT = args
                keyboard = self.__startMenuKeyboard()
                message = self.__RemindDutyEndAction(self.CURRENT_LOCATION,
                                                     self.CURRENT_COMMENT)

                self.CURRENT_LOCATION = ''
                self.CURRENT_COMMENT = ''

        # Main Show duty State
        elif self.state.getType() == States.ShowDuty:
            if self.state.getState() == State.STATE[States.ShowDuty]['End']:
                keyboard = self.__startMenuKeyboard()
                message = self.__ShowDutyEndAction()

        # Main Update Duty State
        elif self.state.getType() == States.UpdateDuty:
            if self.state.getState() == State.STATE[
                    States.UpdateDuty]['SelectLocation']:
                if not Data.isModerator(self.peer):
                    self.state.setStartState()

                    keyboard = Bot.createKeyboard(
                        keyboard, list(State.STATE_TYPES_NAMES.keys()))
                    message = 'У вас недостаточно прав доступа'
                    return {
                        'keyboard': keyboard.get_keyboard(),
                        'message': message
                    }

                if args in State.STATE_TYPES_NAMES.keys():
                    self.CURRENT_ROOMS = [
                        room.rooms_name for room in self.rooms
                    ]
                    self.CURRENT_LOCS = self.locations
                else:
                    self.CURRENT_LOCS.remove(args)
                    self.CURRENT_DUTY.append(args)

                message = 'Выберите место: '
                keyboard = Bot.createKeyboard(keyboard,
                                              self.CURRENT_ROOMS,
                                              elements_per_line=2)

            if self.state.getState() == State.STATE[
                    States.UpdateDuty]['SelectRoom']:
                self.CURRENT_ROOMS.remove(args)
                self.CURRENT_DUTY.append(args)
                print(self.CURRENT_ROOMS)
                message = 'Выберите дежурных: '
                keyboard = Bot.createKeyboard(keyboard,
                                              self.CURRENT_LOCS,
                                              elements_per_line=2)

                if len(self.CURRENT_LOCS) > 0:
                    self.state.currentState -= 2

        else:
            self.state.setStartState()
            return self.getResponseData(args)

        if self.state.isOnLastState():
            self.state.next()

        return {'keyboard': keyboard.get_keyboard(), 'message': message}

    def send(self, args=None):
        self.state.next(args)
        self.logState(args)
        responseData = self.getResponseData(args)

        self.send_message(self.peer, responseData['message'],
                          responseData['keyboard'])

    def logState(self, args=None):
        print('Type: {}\n State: {}\n args: {}\n peer: {}\n\n'.format(
            self.state.getType(), self.state.getState(), args, self.peer))

    def send_message(self, peer, message, keyboard=None, name=None):
        try:
            if keyboard is not None:
                if re.match(r'[\d]+', str(peer)) is not None:
                    self.vk.messages.send(user_id=peer,
                                          random_id=get_random_id(),
                                          message=message,
                                          keyboard=keyboard)
                else:
                    self.vk.messages.send(domain=peer,
                                          random_id=get_random_id(),
                                          message=message,
                                          keyboard=keyboard)
            else:
                if re.match('[\d]+', str(peer)) is not None:
                    self.vk.messages.send(
                        user_id=peer,
                        random_id=get_random_id(),
                        message=message,
                    )
                else:
                    self.vk.messages.send(
                        domain=peer,
                        random_id=get_random_id(),
                        message=message,
                    )
        except ApiError as e:
            print(e.args)
            print(e.values)
            self.send_message(
                self.peer,
                'Кажется, резидент {} с id: {} еще не зарегистрировался.'
                ' \n Пожалуйста, перешлите это сообщение @mistleet'.format(
                    str(name), str(peer)))
            return False
        return True

    def __startMenuKeyboard(self):
        keyboard = VkKeyboard()
        if not Data.isModerator(self.peer):
            keyboard = Bot.createKeyboard(
                keyboard,
                list(State.STATE_TYPES_NAMES.keys())[:-1])
        else:
            keyboard = Bot.createKeyboard(keyboard,
                                          list(State.STATE_TYPES_NAMES.keys()))
        return keyboard

    def __RemindDutyEndAction(self, location, comment):
        room: Room = self.duty.duty[location]

        message = ''

        for name, id in room.room.items():
            result = self.send_message(
                id,
                'Привет, {}, кажется, {} стоит уделить внимание!'.format(
                    Helper.BuildPersonLink(id, name), location) + '\n' +
                Helper.BuildComment(comment),
                name=name)
            if result:
                message += '{} уведомлен(a) \n'.format(name)
            if message == '':
                message = '...'
        return message

    def __ShowDutyEndAction(self):
        message = ''

        for location, room in self.duty.duty.items():
            message += '{} ------ {}\n'.format(room.rooms_name, location)
        return message
Exemplo n.º 8
0
 def __init__(self, Lumberjack):
     State.__init__(self, "Searching")
     self.Lumberjack = Lumberjack
Exemplo n.º 9
0
 def __init__(self, Lumberjack):
     State.__init__(self, "Chopping")
     self.Lumberjack = Lumberjack
from rlbot.agents.base_agent import SimpleControllerState

from StateMachine import State

import Strategy.KickoffFolder.DoKickoffFolder.DiagonalRightFolder.Boost as Boost
import Strategy.KickoffFolder.DoKickoffFolder.DiagonalRightFolder.Jump as Jump
import Strategy.KickoffFolder.DoKickoffFolder.DiagonalRightFolder.FastDodge as FastDodge
import Strategy.KickoffFolder.DoKickoffFolder.DiagonalRightFolder.AerialRotation as AerialRotation
import Strategy.KickoffFolder.DoKickoffFolder.DiagonalRightFolder.Turn as Turn
import Strategy.KickoffFolder.DoKickoffFolder.DiagonalRightFolder.Dodge as Dodge

##########################################################################

BoostState = State(
    lambda game_info, next_states, sub_sm: Boost.transition(
        game_info, next_states, sub_sm),
    lambda game_info: Boost.startup(game_info),
    lambda game_info, sub_state_machine: Boost.get_controls(
        game_info, sub_state_machine), "Boost", True)
JumpState = State(
    lambda game_info, next_states, sub_sm: Jump.transition(
        game_info, next_states, sub_sm),
    lambda game_info: Jump.startup(game_info),
    lambda game_info, sub_state_machine: Jump.get_controls(
        game_info, sub_state_machine), "Jump", True)
FastDodgeState = State(
    lambda game_info, next_states, sub_sm: FastDodge.transition(
        game_info, next_states, sub_sm),
    lambda game_info: FastDodge.startup(game_info),
    lambda game_info, sub_state_machine: FastDodge.get_controls(
        game_info, sub_state_machine), "FastDodge", True)
AerialRotationState = State(
Exemplo n.º 11
0
 def __init__(self, Lumberjack):
     State.__init__(self, "Delivering")
     self.Lumberjack = Lumberjack
Exemplo n.º 12
0
 def __init__(self, Lumberjack):
     State.__init__(self, "Searching")
     self.Lumberjack = Lumberjack
Exemplo n.º 13
0
from rlbot.agents.base_agent import SimpleControllerState

from CowBotVector import Vec3
from StateMachine import State
import Strategy.KickoffFolder.DoKickoff as DoKickoff
import Strategy.KickoffFolder.GetBoost as GetBoost
import Strategy.KickoffFolder.CoverNet as CoverNet

########################################################################################################
#States for the next level down
########################################################################################################

DoKickoffState = State(
    lambda game_info, next_states, sub_sm: DoKickoff.transition(
        game_info, next_states, sub_sm),
    lambda game_info: DoKickoff.startup(game_info),
    lambda game_info, sub_state_machine: DoKickoff.get_controls(
        game_info, sub_state_machine), "DoKickoff", False)
GetBoostState = State(
    lambda game_info, next_states, sub_sm: GetBoost.transition(
        game_info, next_states, sub_sm),
    lambda game_info: GetBoost.startup(game_info),
    lambda game_info, sub_state_machine: GetBoost.get_controls(
        game_info, sub_state_machine), "GetBoost", False)
CoverNetState = State(
    lambda game_info, next_states, sub_sm: CoverNet.transition(
        game_info, next_states, sub_sm),
    lambda game_info: CoverNet.startup(game_info),
    lambda game_info, sub_state_machine: CoverNet.get_controls(
        game_info, sub_state_machine), "CoverNet", True)
Exemplo n.º 14
0
        s.release()
    print("\nStopping")
    for t in threads:
        print("[THD]", t)
        t.join()
    print("Stopped\n")


### MAIN main

actionPreprocessing = ActionPreprocessing(["déroutement", "retour"])

# States and state machine
s = dict()
for kw in actionPreprocessing.keywords:
    s[kw] = State(kw)

s['retour'].addNext(s['déroutement'])
airfields = ['LFCL', 'LFBO', 'LFBR']
for airfield in airfields:
    s[airfield] = State(airfield)
    s['déroutement'].addNext(s[airfield])
    s[airfield].addNext(s['retour'])

stateMachine = StateMachine(s['retour'])

# TTS
talker = ThirstyTalker()

# Threads
fgfsListener = FGFS_Listener()
Exemplo n.º 15
0
from rlbot.agents.base_agent import SimpleControllerState

from CowBotVector import Vec3
from StateMachine import State
import Strategy.KickoffFolder.GetBoostFolder.LeftBoost as LeftBoost
import Strategy.KickoffFolder.GetBoostFolder.RightBoost as RightBoost

##########################################################################

LeftBoostState = State(
    lambda game_info, next_states, sub_sm: LeftBoost.transition(
        game_info, next_states, sub_sm),
    lambda game_info: LeftBoost.startup(game_info),
    lambda game_info, sub_state_machine: LeftBoost.get_controls(
        game_info, sub_state_machine), "LeftBoost", True)
RightBoostState = State(
    lambda game_info, next_states, sub_sm: RightBoost.transition(
        game_info, next_states, sub_sm),
    lambda game_info: RightBoost.startup(game_info),
    lambda game_info, sub_state_machine: RightBoost.get_controls(
        game_info, sub_state_machine), "RightBoost", True)

##########################################################################


def transition(game_info, next_states, sub_state_machine):
    def transition_to_do_kickoff(game_info):
        should_transition = False
        return should_transition, game_info.persistent

    ##########################
Exemplo n.º 16
0
class Token(object):
    """ Class for tokens, as well as the tokenizer.
    
    This class consists of four parts: a set of class constants
    representing different types of tokens, a static initializer for the
    lexical analyzer's state machine, the constructor and instance methods
    for the Token objects, and a class nethod that returns a generator
    object which tokenizes a CharBuffer source, returning the next token
    on each successive call.
    
    """
    # Token types for the lexical analyzer - this type of group return is used
    # as the Python equivalent of an Enum, setting each to a matching number in the
    # returned range.
    EOF, __WSPACE, \
    SEMI, BRACKET, PAREN, COMMA, \
    IDENT, CHARLIT, INTLIT, STRINGLIT, BOOLLIT, \
    MULOP, ADDOP, RELOP, NOTTOK, ASSIGN, \
    BASICTYPETOK, INTCONSTTOK, ARRAYTOK, PROCTOK, \
    BEGINTOK, ENDTOK, \
    IFTOK, THENTOK, ELSETOK, FITOK, \
    WHILETOK, DOTOK, ODTOK, \
    FORTOK, ROFTOK, UNTILTOK, STEPTOK, \
    __COLON, __AND, __OR, __EQUAL, __NEQUAL, \
    __SQUOTE, __DQUOTE, __CHAR, __STRING, __COMMENT = list(range(1, 44))

    # lookup table matching a lexeme to a specific token type. When the state machine
    # finds an identifier token, the tokenizer checks it against this table, and
    # if it matches one of the values, changes the return type to the corresponding
    # token type.
    resWords = {"BEGIN": BEGINTOK, "END": ENDTOK, \
                "INT": BASICTYPETOK, "CHAR": BASICTYPETOK, "INTCONST": INTCONSTTOK, \
                "STRING": BASICTYPETOK, "BOOLEAN": BASICTYPETOK, \
                "NOT": NOTTOK,
                "IF": IFTOK, "THEN": THENTOK, "ELSE": ELSETOK, "FI": FITOK, \
                "WHILE": WHILETOK, "DO": DOTOK, "OD": ODTOK, \
                "FOR": FORTOK, "ROF": ROFTOK, "UNTIL": UNTILTOK, "STEP": STEPTOK, \
                "PROC": PROCTOK, "ARRAY": ARRAYTOK, \
                "TRUE": BOOLLIT, "FALSE":BOOLLIT }

    # A simple lookup table for the names of the different token types. It is
    # probably possible to merge this with the lookup table above, but this
    # was the expedient solution given the long delays in completing the project.
    # Note that these need to align correctly with the enumerated constants, which
    # may cause maintanence problems later.
    token_desc = ['START', 'EOF', 'WSPACE', \
    'SEMI', 'BRACKET', 'PAREN', 'COMMA', \
    'IDENT', 'CHARLIT', 'INTLIT', 'STRINGLIT', 'BOOLLIT', \
    'MULOP', 'ADDOP', 'RELOP', 'NOTTOK', 'ASSIGN', \
    'BASICTYPETOK', 'INTCONSTTOK', 'ARRAYTOK', 'PROCTOK', \
    'BEGINTOK', 'ENDTOK', \
    'IFTOK', 'THENTOK', 'ELSETOK', 'FITOK', \
    'WHILETOK', 'DOTOK', 'ODTOK', \
    'FORTOK', 'ROFTOK', 'UNTILTOK', 'STEPTOK' ]

    # constant string representing the allowable characters in an identifier
    id_chars = ascii_letters + digits + '_'

    # class static initialization

    # Initialize the FSM to the start state, including all transitions out of it.
    fsm = StateMachine(
        State({
            '': EOF,
            whitespace: __WSPACE,
            '#': __COMMENT,
            ascii_letters: IDENT,
            digits: INTLIT,
            "'": __SQUOTE,
            '"': __STRING,
            '()': PAREN,
            '[]': BRACKET,
            ';': SEMI,
            ',': COMMA,
            '+-': ADDOP,
            '*/%': MULOP,
            '<>': RELOP,
            ':': __COLON,
            '&': __AND,
            '|': __OR,
            '=': __EQUAL,
            '!': __NEQUAL,
            State.OTHER: State.ERROR
        }))

    # add the list of states and their transitions to the FSM
    # end of file -> always accept
    fsm.add(EOF, State({State.OTHER: State.ACCEPT}, True, EOF, 0))
    # whitespace -> eat until the next valid input, then push back
    # one and return to start
    fsm.add(__WSPACE,
            State({whitespace: __WSPACE, State.OTHER: State.ACCEPT}, \
            True, __WSPACE, 1))
    # identifier -> eat until the last valid ID char, then accept and push back one
    fsm.add(
        IDENT,
        State({
            id_chars: IDENT,
            State.OTHER: State.ACCEPT
        }, True, IDENT, 1))
    # intlit -> eat all numbers, then accept
    fsm.add(
        INTLIT,
        State({
            id_chars: INTLIT,
            State.OTHER: State.ACCEPT
        }, True, INTLIT, 1))
    # + or - -> accept and push back one
    fsm.add(ADDOP, State({State.OTHER: State.ACCEPT}, True, ADDOP, 1))
    # *, / or % -> accept and push back one
    fsm.add(MULOP, State({State.OTHER: State.ACCEPT}, True, MULOP, 1))
    # > or < -> accept and push back one
    fsm.add(RELOP, State({State.OTHER: State.ACCEPT}, True, RELOP, 1))
    # semicolon -> accept and push back one
    fsm.add(SEMI, State({State.OTHER: State.ACCEPT}, True, SEMI, 1))
    # comma -> accept and push back one
    fsm.add(COMMA, State({State.OTHER: State.ACCEPT}, True, COMMA, 1))
    # parenthesis -> accept and push back one
    fsm.add(PAREN, State({State.OTHER: State.ACCEPT}, True, PAREN, 1))
    # bracket -> accept and push back one
    fsm.add(BRACKET, State({State.OTHER: State.ACCEPT}, True, BRACKET, 1))
    # The following represent intermediate states in compound operators.
    # They are private to the class, unlike the others.
    # colon -> accept of the next char is an equals sign, otherwise fail
    fsm.add(__COLON, State({'=': State.ACCEPT}, True, ASSIGN, 0))
    # ampersand -> accept of the next char is an ampersand, otherwise fail
    fsm.add(__AND, State({'&': State.ACCEPT}, True, MULOP, 0))
    # vertical bar -> accept of the next char is a vertical bar, otherwise fail
    fsm.add(__OR, State({'|': State.ACCEPT}, True, ADDOP, 0))
    # equals sign -> accept of the next char is an equals sign, otherwise fail
    fsm.add(__EQUAL, State({'=': State.ACCEPT}, True, RELOP, 0))
    # exclamation point -> accept if the next char is an equals sign,
    # otherwise fail
    fsm.add(__NEQUAL, State({'=': State.ACCEPT}, True, RELOP, 0))
    # single quote -> continue for any following char except a single quote
    fsm.add(__SQUOTE, State({State.OTHER: __CHAR}))
    # character -> accept of the next char is an signle quote, otherwise fail
    fsm.add(__CHAR, State({"'": State.ACCEPT}, True, CHARLIT, 0))
    # double quote -> accept any number of characters until another double
    # quote is reached
    fsm.add(
        __STRING,
        State({
            '"': State.ACCEPT,
            State.OTHER: __STRING
        }, True, STRINGLIT, 0))
    # hash -> eat all inout to the end of the current line, then go back to start
    fsm.add(
        __COMMENT,
        State({
            '\n': State.ACCEPT,
            State.OTHER: __COMMENT
        }, True, __COMMENT, 0))

    # lock state machine after adding all the states
    fsm.lock()

    def __init__(self, toktype, line, lexeme):
        """ Constructor - create a new Token object.
        
        
       Each Token consists of a token type, the line # on which it
       was found, and the actual text of the lexeme.
       """
        self.__toktype, self.__line, self.__lexeme = toktype, line, lexeme

    @classmethod
    def Tokenizer(cls, buffer, wrng):
        """ Create generator for new tokens from the CharBuffer input.
       
        The class method takes a CharBuffer object and returns a
        generator function which iterates through the input source,
        returning each successive token.
        
        The generator itself begins each call by
       """
        # continue until the end of the file
        global warning
        warning = wrng
        while not buffer.eof():
            final = False  # clear the previous token state
            lexeme = ''

            # read the next character and, if it is not an end of file,
            # feed it to the FSM. If it is an EOF, return an EOF token and
            # break from the loop. Accumulate the read characters into the
            # string 'lexeme'.
            while not final:
                ch = buffer.getChar()
                if ch == '':
                    yield Token(cls.EOF, buffer.line(), '')
                    break
                final, toktype, pb = cls.fsm.transition(ch)
                lexeme += ch

            # If the FSM returns an error, print a warning and
            # go on to the mext token. Note that this has to check for the
            # end of line, as identifiers can be mistakenly reported as
            # errors if there is a newline in them.
            if toktype == State.ERROR and '\n' not in lexeme:
                warning(Token(State.ERROR, buffer.line(), lexeme),
                    "Invalid token " + lexeme + \
                    " on line " + str(buffer.line()))
                buffer.pushback(pb)
                lexeme = ''
                continue

            # if the FSM finds a comment or string of whitespace, push back
            # the first good character and continue to the next token
            if toktype == cls.__WSPACE or toktype == cls.__COMMENT:
                lexeme = ''
                buffer.pushback(pb)
                continue

            # if the token is a string literal, make sure it does not
            # have a newline in it
            if toktype == cls.STRINGLIT and '\n' in lexeme:
                warning(Token(State.ERROR, buffer.line(), lexeme),
                        " incomplete string on line " + str(buffer.line()))
                lexeme = ''
                buffer.pushback(pb)
                continue

            # push back any characters not eaten in the current string
            if (pb > 0):
                lexeme = lexeme[0:-pb]
                buffer.pushback(pb)

            # if the token is recognized as an identifier, check to see if
            # if is a keyword, and if it is, use the keyword token type
            # instead of IDENT
            if toktype == cls.IDENT:
                if lexeme.upper() in cls.resWords:
                    toktype = cls.resWords[lexeme.upper()]

            # return the completed token
            yield Token(toktype, buffer.line(), lexeme)

        # end of file reached - continue returning EOF tokens indefinitely
        while (True):
            yield Token(cls.EOF, buffer.line(), '')

    def __repr__(self):
        """String representation of a Token object.
       
        Just calls str()
       """
        return str(self)

    def __str__(self):
        """Simple string representation of a Token object.
       
       If the token is an ERROR token, return "ERROR".
       If it is a literal or an identifier, return type name and the lexeme,
       Otherwise, return just the name of the type.
       """
        if self.__toktype == State.ERROR:
            return "ERROR"
        elif self.__toktype in [self.CHARLIT, self.INTLIT, self.BOOLLIT, \
                                self.STRINGLIT, self.IDENT, self.BASICTYPETOK]:
            return (self.token_desc[self.__toktype] + '(' + self.__lexeme +
                    ')')
        else:
            return self.token_desc[self.__toktype]

    def line(self):
        """Return the line on which  the token was found."""
        return self.__line

    def type(self):
        """Return a string with the name of the token type."""
        return self.__toktype

    def value(self):
        """Return the token's lexeme."""
        return self.__lexeme
Exemplo n.º 17
0
from StateMachine import State
import Strategy.Kickoff as Kickoff
import Strategy.Attack as Attack
import Strategy.TransitionBack as TransitionBack
import Strategy.Defend as Defend
import Strategy.TransitionForward as TransitionForward
import Strategy.Initialize as Initialize

KickoffState = State(
    lambda game_info, next_states, sub_sm: Kickoff.transition(
        game_info, next_states, sub_sm),
    lambda game_info: Kickoff.startup(game_info),
    lambda game_info, sub_state_machine: Kickoff.get_controls(
        game_info, sub_state_machine), "Kickoff", False)
AttackState = State(
    lambda game_info, next_states, sub_sm: Attack.transition(
        game_info, next_states, sub_sm),
    lambda game_info: Attack.startup(game_info),
    lambda game_info, sub_state_machine: Attack.get_controls(
        game_info, sub_state_machine), "Attack", False)
TransitionBackState = State(
    lambda game_info, next_states, sub_sm: TransitionBack.transition(
        game_info, next_states, sub_sm),
    lambda game_info: TransitionBack.startup(game_info),
    lambda game_info, sub_state_machine: TransitionBack.get_controls(
        game_info, sub_state_machine), "Transition Back", False)
DefendState = State(
    lambda game_info, next_states, sub_sm: Defend.transition(
        game_info, next_states, sub_sm),
    lambda game_info: Defend.startup(game_info),
    lambda game_info, sub_state_machine: Defend.get_controls(
Exemplo n.º 18
0
def forceTransitionEmptyPartial(StateMachine): # add DataSet
    StateMachine.guiWindow.DataSet_NewDataSet_button_function()
    return transitionEmptyPartial(StateMachine)

def forceTransitionPartialRaw(StateMachine): # add DataFile
    StateMachine.guiWindow.DataSet_AddFiles_button_function()
    return transitionPartialRaw(StateMachine)

def forceTansitionRawConverted(StateMachine): # add DataFile
    print(StateMachine.currentState.name)
    StateMachine.guiWindow.convert()
    return True#transitionRawConverted(StateMachine)


### States for state machine

# Allows plotting, fitting and all the fun
converted = State('Converted',nextState=None,enterStateFunction=ConvertedEnabled) 

# Has DataSet, DataFiles but not converded yet
raw = State('Raw',enterStateFunction=RawEnabled,transitionRequirement=transitionRawConverted,
                transitionFunction=forceTansitionRawConverted,nextState=converted)

# Has DataSet but no DataFiles
partial = State('Partial',enterStateFunction=PartialEnabled,transitionRequirement=transitionPartialRaw,
                transitionFunction=forceTransitionPartialRaw,nextState=raw)

# Has no DataSet
empty = State('Empty',enterStateFunction=EmptyEnabled,transitionRequirement=transitionEmptyPartial,
                transitionFunction=forceTransitionEmptyPartial,nextState=partial)
Exemplo n.º 19
0
from GameState import Orientation
from Maneuvers import NavigateTo
from StateMachine import State

import Strategy.DefendFolder.InNet as InNet
import Strategy.DefendFolder.FarPost as FarPost
import Strategy.DefendFolder.FarBoost as FarBoost
import Strategy.DefendFolder.Clear as Clear

########################################################################################################
#States for the next level down
########################################################################################################

FarBoostState = State(
    lambda game_info, next_states, sub_sm: FarBoost.transition(
        game_info, next_states, sub_sm),
    lambda game_info: FarBoost.startup(game_info),
    lambda game_info, sub_state_machine: FarBoost.get_controls(
        game_info, sub_state_machine), "FarBoost", True)
FarPostState = State(
    lambda game_info, next_states, sub_sm: FarPost.transition(
        game_info, next_states, sub_sm),
    lambda game_info: FarPost.startup(game_info),
    lambda game_info, sub_state_machine: FarPost.get_controls(
        game_info, sub_state_machine), "FarPost", True)
InNetState = State(
    lambda game_info, next_states, sub_sm: InNet.transition(
        game_info, next_states, sub_sm),
    lambda game_info: InNet.startup(game_info),
    lambda game_info, sub_state_machine: InNet.get_controls(
        game_info, sub_state_machine), "InNet", True)
ClearState = State(
import Strategy.KickoffFolder.DoKickoffFolder.OffcenterLeftFolder.Start as Start
import Strategy.KickoffFolder.DoKickoffFolder.OffcenterLeftFolder.Turn as Turn
import Strategy.KickoffFolder.DoKickoffFolder.OffcenterLeftFolder.Jump as Jump
import Strategy.KickoffFolder.DoKickoffFolder.OffcenterLeftFolder.FastDodge as FastDodge
import Strategy.KickoffFolder.DoKickoffFolder.OffcenterLeftFolder.Land as Land
import Strategy.KickoffFolder.DoKickoffFolder.OffcenterLeftFolder.PreDodge as PreDodge
import Strategy.KickoffFolder.DoKickoffFolder.OffcenterLeftFolder.Dodge as Dodge

########################################################################################################
#States for the next level down
########################################################################################################

StartState = State(lambda game_info, next_states, sub_sm: Start.transition(game_info,
                                                                                         next_states,
                                                                                         sub_sm),
                          lambda game_info: Start.startup(game_info),
                          lambda game_info, sub_state_machine: Start.get_controls(game_info, sub_state_machine),
                          "Start",
                          True)
TurnState = State(lambda game_info, next_states, sub_sm: Turn.transition(game_info,
                                                                                           next_states,
                                                                                           sub_sm),
                           lambda game_info: Turn.startup(game_info),
                           lambda game_info, sub_state_machine: Turn.get_controls(game_info, sub_state_machine),
                           "Turn",
                           True)
JumpState = State(lambda game_info, next_states, sub_sm: Jump.transition(game_info,
                                                                                           next_states,
                                                                                           sub_sm),
                           lambda game_info: Jump.startup(game_info),
                           lambda game_info, sub_state_machine: Jump.get_controls(game_info, sub_state_machine),
Exemplo n.º 21
0
 def __init__(self, Lumberjack):
     State.__init__(self, "Delivering")
     self.Lumberjack = Lumberjack
Exemplo n.º 22
0
from BallPrediction import ball_contact_binary_search
from CowBotVector import Vec3
from Maneuvers import GroundTurn
from StateMachine import State

import Strategy.AttackFolder.Path as Path
import Strategy.AttackFolder.Challenge as Challenge
import Strategy.AttackFolder.Aerial as Aerial

########################################################################################################
#States for the next level down
########################################################################################################

PathState = State(
    lambda game_info, next_states, sub_sm: Path.transition(
        game_info, next_states, sub_sm),
    lambda game_info: Path.startup(game_info),
    lambda game_info, sub_state_machine: Path.get_controls(
        game_info, sub_state_machine), "Path", True)
ChallengeState = State(
    lambda game_info, next_states, sub_sm: Challenge.transition(
        game_info, next_states, sub_sm),
    lambda game_info: Challenge.startup(game_info),
    lambda game_info, sub_state_machine: Challenge.get_controls(
        game_info, sub_state_machine), "Challenge", True)
AerialState = State(
    lambda game_info, next_states, sub_sm: Aerial.transition(
        game_info, next_states, sub_sm),
    lambda game_info: Aerial.startup(game_info),
    lambda game_info, sub_state_machine: Aerial.get_controls(
        game_info, sub_state_machine), "Aerial", False)
Exemplo n.º 23
0
 def __init__(self, Lumberjack):
     State.__init__(self, "Chopping")
     self.Lumberjack = Lumberjack
Exemplo n.º 24
0
from rlbot.agents.base_agent import SimpleControllerState

from StateMachine import State

import Strategy.AttackFolder.AerialFolder.Ball as Ball
import Strategy.AttackFolder.AerialFolder.Recover as Recover


########################################################################################################
#States for the next level down
########################################################################################################

BallState = State(lambda game_info, next_states, sub_sm: Ball.transition(game_info,
                                                                                   next_states,
                                                                                   sub_sm),
                       lambda game_info: Ball.startup(game_info),
                       lambda game_info, sub_state_machine: Ball.get_controls(game_info, sub_state_machine),
                       "Ball",
                       True)
RecoverState = State(lambda game_info, next_states, sub_sm: Recover.transition(game_info,
                                                                                 next_states,
                                                                                 sub_sm),
                      lambda game_info: Recover.startup(game_info),
                      lambda game_info, sub_state_machine: Recover.get_controls(game_info, sub_state_machine),
                      "Recover",
                      True)

########################################################################################################
#Transition functions
########################################################################################################