class Wife(BaseGameEntity):
    def __init__(self, name='wife', wid=None, location=Location.shack):
        super().__init__()

        if wid != None:
            #override the assigned id
            self.id = wid

        self.name = name
        self.location = location
        self.cooking = False
        self.state_machine = StateMachine(self)
        self.state_machine.current_state = DoHouseWork.instance()
        self.state_machine.global_state = WifeGlobalState.instance()

    def change_location(self, new_location):
        self.location = new_location

    def update(self):
        self.state_machine.update()

    def handle_message(self, msg):
        return self.state_machine.handle_message(msg)

    def __repr__(self):
        return self.name
Beispiel #2
0
    def __init__(self, username):
        self.username = username
        self._server_protocol = None
        self._print_buffer = ''
        self._game_list = []
        self._waiting_for_list = False
        self._waiting_for_join = False
        self._waiting_for_start = False
        self._in_game = False
        self.client = client.Client()
        self.game_id = None
        self._update_interval = 15
        self.pump_return = None

        self.fsm = StateMachine()

        self.fsm.add_state('START', None, lambda _: 'MAINMENU')
        self.fsm.add_state('MAINMENU', self._main_menu_arrival,
                           self._main_menu_transition)
        self.fsm.add_state('SELECTGAME', self._select_game_arrival,
                           self._select_game_transition)
        self.fsm.add_state('END', None, None, True)

        self.fsm.set_start('START')
        self.fsm.pump(None)
Beispiel #3
0
    def __init__(self, username):
        self.username = username
        self._server_protocol = None
        self._print_buffer = ''
        self._game_list = []
        self._waiting_for_list = False
        self._waiting_for_join = False
        self._waiting_for_start = False
        self._in_game = False
        self.client = client.Client()
        self.game_id = None
        self.pump_return = None

        self._gui = CursesGUI()
        self._gui.choice_callback = self.handle_choice_input
        self._gui.command_callback = self.handle_command_input
        self._gui.help_callback = self.print_help

        self.fsm = StateMachine()

        self.fsm.add_state('START', None, lambda _ : 'MAINMENU')
        self.fsm.add_state('MAINMENU',
                self._main_menu_arrival, self._main_menu_transition)
        self.fsm.add_state('SELECTGAME',
                self._select_game_arrival, self._select_game_transition)
        self.fsm.add_state('END', None, None, True)

        self.fsm.set_start('START')
        self.fsm.pump(None)
    def __init__(self,name='wife',location=Location.shack):
        super().__init__()

        self.name = name
        self.location = location
        self.state_machine = StateMachine(self)
        self.state_machine.current_state = DoHouseWork.instance()
        self.state_machine.global_state = WifeGlobalState.instance()
    def __init__(self,name='anonymous'):
        super().__init__()

        self.location = Location.shack
        self.gold_carried = 0
        self.money_in_bank = 0
        self.thirst = 0
        self.fatigue = 0
##        self.current_state = GoHomeAndSleepTilRested.instance()
        self.name = name
        self.state_machine = StateMachine(self)
        self.state_machine.current_state = GoHomeAndSleepTilRested.instance()
Beispiel #6
0
def find_strings(char_stream):
    fsm = StateMachine(TRANSITIONS, State.DEFAULT, State.LOOK_FOR_STRING)

    for state, action, ch in fsm.process(char_stream):
        if action == State.IGNORE:
            continue
        elif action == State.START_NEW_STRING:
            result = []
        elif action == State.ADD_CURRENT_TO_STRING:
            result.append(ch)
        elif action == State.FINISH_CURRENT_STRING:
            yield "".join(result)
    def __init__(self, name='wife', wid=None, location=Location.shack):
        super().__init__()

        if wid != None:
            #override the assigned id
            self.id = wid

        self.name = name
        self.location = location
        self.cooking = False
        self.state_machine = StateMachine(self)
        self.state_machine.current_state = DoHouseWork.instance()
        self.state_machine.global_state = WifeGlobalState.instance()
    def __init__(self, name='anonymous', mid=None):
        super().__init__()

        if mid != None:
            #override the assigned id if the user passes one in
            self.id = mid

        self.name = name
        self.location = Location.saloon
        self.gold_carried = 0
        self.money_in_bank = 0
        self.thirst = 0
        self.fatigue = 0
        self.state_machine = StateMachine(self)
        self.state_machine.current_state = GoHomeAndSleepTilRested.instance()
Beispiel #9
0
    def __init__(self,
                 image,
                 pitch,
                 team,
                 home,
                 heading,
                 model=model.initial_model,
                 **kwargs):
        super().__init__('redshirt0')  #image,  **kwargs)

        self.max_turn_rate = model.player_max_turn_rate
        self.max_force = model.player_max_force
        self.max_speed = model.player_max_speed

        #register with the entity_manager
        model.entity_manager.register(self)

        self.home = Vector2(home)
        self.pos = Vector2(home)
        self.mass = model.player_mass
        # self.velocity = Vector2()
        # self.heading = Vector2(heading)
        _, self.angle = Vector2(heading).as_polar()

        print('...creating player{}: @ position {}, angle {}'.format(
            self.id, self.pos, self.angle))

        # in case the velocity is zero
        if self.speed < 0.00001:
            self.angle = 0.0
            # self.set_orientation(Vector2(heading))

        self.model = model
        self.max_speed_with_ball = model.player_max_speed_with_ball
        self.receiving_range = model.ball_within_receiving_range
        self.role = None
        self.pitch = pitch
        self.team = team

        self.steering = SteeringBehaviors(self)
        self.steering.separation_on()

        self.state = PState.wait
        self.fsm = StateMachine(self)
        self.fsm.current_state = self.state
        self.fsm.previous_state = self.state
        self.fsm.global_state = PState.global_player
        self.fsm.current_state.enter(self)
    def __init__(self,
                 side,
                 pitch,
                 display_model=model.initial_model,
                 entity_manager=model.initial_model.entity_manager,
                 dispatcher=model.initial_model.dispatcher):
        # self.model = model
        self.pitch = pitch
        self.view = View(display_model)
        self.view.model = self
        self.side = side
        self._entity_manager = entity_manager
        self._dispatcher = dispatcher

        if side == HOME:
            self.color = pg.Color('red')
            self.goal = self.pitch.home_goal
            self.opponent_goal = self.pitch.away_goal
            self.init_heading = Vector2(-1, 0)

        elif side == AWAY:
            self.color = pg.Color('blue')
            self.goal = self.pitch.away_goal
            self.opponent_goal = self.pitch.home_goal
            self.init_heading = Vector2(1, 0)

        else:
            raise ValueError("side must be either 'HOME' or 'AWAY' ")

        self.players = self.create_players()
        self.opponent = None

        self._controlling_player = None
        self._supporting_player = None
        self._receiving_player = None
        self.player_closest_to_ball = None

        self.dist_sq_to_ball_from_closest_player = sys.float_info.max
        self.support_spot_calculator = SupportSpotCalculator()

        self.fsm = StateMachine(self)
        self.fsm.current_state = TeamState.defending
        self.fsm.previous_state = TeamState.defending
        self.fsm.global_state = None
class Wife(BaseGameEntity):
    
    def __init__(self,name='wife',location=Location.shack):
        super().__init__()

        self.name = name
        self.location = location
        self.state_machine = StateMachine(self)
        self.state_machine.current_state = DoHouseWork.instance()
        self.state_machine.global_state = WifeGlobalState.instance()

    def change_location(self, new_location):
        self.location = new_location

    def update(self):
        self.state_machine.update()

    def __repr__(self):
        return self.name
Beispiel #12
0
def main():
    global encodedLine, insCounter, lineCounter, repeatFlag, isC
    global repeatBuffer, writeRepeat, writeLineFlag, repetitions
    F = open("asm.txt", "r")
    try:
        os.remove("instructionsOut.txt")
    except:
        pass
    F2 = open("instructionsOut.txt", "a+")
    FLines = F.readlines()

    #Initializing the state machine
    m = StateMachine()

    m.add_state("Start", startState)

    m.add_state("OperandState", OperandState)
    m.add_state("regDestState", regDestState)
    m.add_state("regSrc1State", regSrc1State)
    m.add_state("immSrc1State", immSrc1State)
    m.add_state("regSrc2State", regSrc2State)
    m.add_state("immSrc2State", immSrc2State)

    m.add_state("doneState", None, end_state=1)
    m.add_state("ErrorState", ErrorState)
    m.set_start("Start")

    print(FLines)
    line = 1
    lineCounter = 1
    for l in FLines:
        print("Instruction")
        print(lineCounter)
        print("Line")
        print(line)
        print(l)
        if m.run(l):
            if writeLineFlag:
                F2.write(encodedLine + "\r")
                if repeatFlag:
                    repeatBuffer = repeatBuffer + encodedLine + "\r"
            if writeRepeat:
                while repetitions > 0:
                    F2.write(repeatBuffer)
                    repetitions -= 1
                writeRepeat = False
                repeatBuffer = ""

            encodedLine = "0000000000000000"
            insCounter = 0
            lineCounter += 1
            line += 1
            writeLineFlag = True
            isC = False
    if repeatFlag:
        print("Repeate cycle not closed")
    F.close()
Beispiel #13
0
class TerminalGUI(object):

    def __init__(self, username):
        self.username = username
        self._server_protocol = None
        self._print_buffer = ''
        self._game_list = []
        self._waiting_for_list = False
        self._waiting_for_join = False
        self._waiting_for_start = False
        self._in_game = False
        self.client = client.Client()
        self.game_id = None
        self.pump_return = None

        self._gui = CursesGUI()
        self._gui.choice_callback = self.handle_choice_input
        self._gui.command_callback = self.handle_command_input
        self._gui.help_callback = self.print_help

        self.fsm = StateMachine()

        self.fsm.add_state('START', None, lambda _ : 'MAINMENU')
        self.fsm.add_state('MAINMENU',
                self._main_menu_arrival, self._main_menu_transition)
        self.fsm.add_state('SELECTGAME',
                self._select_game_arrival, self._select_game_transition)
        self.fsm.add_state('END', None, None, True)

        self.fsm.set_start('START')
        self.fsm.pump(None)

    def set_log_level(self, level):
        """Set the log level as per the standard library logging module.

        Default is logging.INFO.
        """
        self._gui.set_log_level(level)
        logging.getLogger('gtr.game').setLevel(level)
        logging.getLogger('gtr').setLevel(level)

    def set_server_protocol(self, p):
        """Set the protocol interface to the server. This should be a
        NetstringReceiver object.
        """
        self._server_protocol = p

    def _input_choice(self, choice):
        """Provides an input for the state machine. This function
        potentially returns a GameAction object, which is a command
        to be sent to the server.
        """
        # Convert from 1-indexed in the UI to the 0-indexed choices_list
        self.fsm.pump(int(choice)-1)
        return self.pump_return

    def print_help(self):
        lg.warn('Help! (q to quit)')

    def handle_command_input(self, command):
        lg.debug('Handling command input : ' + str(command))
        if command in ['help', 'h', '?']:
            self.print_help()
            return

        elif command in ['restart', 'r']:
            self.client.restart_command()
            return

        elif command in ['refresh', 'f']:
            self.send_command(GameAction(message.REQGAMESTATE))
            return

        elif command in ['quit', 'q']:
            lg.error('Quitting game')
            self._server_protocol.loseConnection()
            self._gui.quit()
            return

        if self._in_game and not self.client.builder:
            lg.error("It's not your turn")
            return

    def handle_choice_input(self, choice):
        """Handles an input choice (integer, 1-indexed).
        """
        try:
            choice = int(choice)
        except ValueError:
            lg.warn('Invalid choice: {0}\n'.format(choice))
            return

        lg.debug('Selection is ' + str(choice))
        if self._in_game:
            self.client.make_choice(choice)
            action = self.client.check_action_builder()

            if action is None:
                lg.debug('More input is required, updating choices list')
                self.update_choices()
            else:
                lg.debug('Sending to server: ' + str(action))
                self.client.builder = None
                self.send_command(action)

        else:
            game_action = self._input_choice(choice)
            if game_action:
                lg.debug('Sending to server: ' + str(game_action))
                self.send_command(game_action)

    
    def _main_menu_arrival(self):
        choices = ['List games', 'Join game', 'Create game', 'Start game']
        self.choices = [Choice(desc, desc) for desc in choices]

    def _main_menu_transition(self, choice):
        choice = self.choices[choice].item
        if choice == 'List games':
            self.pump_return = GameAction(message.REQGAMELIST)
            self._waiting_for_list = True
            return 'MAINMENU'

        elif choice == 'Join game':
            if len(self._game_list) == 0:
                lg.info('No games listed. Getting game list first.')
                self.pump_return = GameAction(message.REQGAMELIST)
                self._waiting_for_list = True
                return 'MAINMENU'
            else:
                return 'SELECTGAME'

        elif choice == 'Create game':
            lg.info('Creating new game.')
            self.pump_return = GameAction(message.REQCREATEGAME)
            self._waiting_for_join = True
            return 'MAINMENU'

        elif choice == 'Start game':
            lg.info('Requesting game start.')
            self.pump_return = GameAction(message.REQSTARTGAME)
            self._waiting_for_start = True
            return 'MAINMENU'

        else:
            return 'END'

    def _select_game_arrival(self):
        # we only get here if the game list is populated
        self.choices = [Choice(i, str(game)) for i, game in enumerate(self._game_list)]
        self._show_choices()

    def _select_game_transition(self, choice):
        game_id = self.choices[choice].item
        self._waiting_for_join = True
        self.pump_return = GameAction(message.REQJOINGAME, game_id)
        return 'MAINMENU'
        

    def _show_choices(self, prompt=None):
        """Returns the index in the choices_list selected by the user or
        raises a StartOverException or a CancelDialogExeption.

        The choices_list is a list of Choices.
        """
        i_choice = 1
        choices_list = []
        if not self.choices:
            self.choices.append(Choice(None, "(none)"))

        for c in self.choices:
            line = ''
            if c.selectable:
                line = '  [{0:2d}] {1}'.format(i_choice, c.description)
                i_choice+=1
            else:
                line = '       {0}'.format(c.description)

            choices_list.append(line)

        self._gui.update_choices(choices_list)

        if prompt is None:
            prompt = 'Please make a selection: '

        self._gui.update_prompt(prompt)

    def send_command(self, game_action):
        self._server_protocol.send_command(self.username, self.game_id, game_action)

    def update_game_list(self, game_list):
        self._game_list = game_list

        if self._waiting_for_list:
            self._waiting_for_list = False

        game_list = ['Available games']
        

        for record in self._game_list:
            game_list.append('  ' + str(record))

        self._gui.update_state('\n'.join(game_list))
        self._show_choices()

    def update_game_state(self, game_state):
        if game_state is None:
            return

        player_index = None
        for p in game_state.players:
            if p.name == self.username:
                player_index = game_state.players.index(p)
                self.client.player_id = player_index
                break

        if self._waiting_for_start or game_state.is_started:
            self._waiting_for_start = False
            self._in_game = True

        old_gs = self.client.game.game_state
        old_game_id = old_gs.game_id if old_gs else None
        new_game_id = game_state.game_id

        if old_game_id is None or old_game_id != new_game_id:
            self.client.update_game_state(game_state)
            action = self.client.check_action_builder()
            if action:
                lg.debug('Action is complete without requiring a choice.')
                self.send_command(action)
            else:
                lg.debug('Action requires user input. Displaying game state.')
                display = GameStateTextDisplay(game_state, game_state.players[player_index])
                self._gui.update_state('\n'.join(display.public_text_string()))
                self._gui.update_game_log('\n'.join(game_state.game_log))
                self.update_choices()

    def update_choices(self):
        choices = self.client.get_choices()

        if choices is None:
            lg.error('Choices list is empty')
            import pdb; pdb.set_trace()
            lines = ['   [1] ERROR! Choices list is empty']
        else:
            lines = []
            i_choice = 1
            for c in choices:
                if c.selectable:
                    lines.append('  [{0:2d}] {1}'.format(i_choice, c.description))
                    i_choice+=1
                else:
                    lines.append('       {0}'.format(c.description))

        self._gui.update_choices(lines)


    def set_player_id(self, i):
        self.client.player_id = i

    def join_game(self, game_id):
        lg.info('Joined game {0:d}.'.format(game_id))
        self.game_id = game_id
        self._waiting_for_join = False
        self._show_choices()
class Miner(BaseGameEntity):
    COMFORT_LEVEL = 5
    MAX_NUGGETS = 3
    THIRST_LEVEL = 5
    TIREDNESS_THRESHOLD = 5

    def __init__(self, name='anonymous', mid=None):
        super().__init__()

        if mid != None:
            #override the assigned id if the user passes one in
            self.id = mid

        self.name = name
        self.location = Location.saloon
        self.gold_carried = 0
        self.money_in_bank = 0
        self.thirst = 0
        self.fatigue = 0
        self.state_machine = StateMachine(self)
        self.state_machine.current_state = GoHomeAndSleepTilRested.instance()

    def change_state(self, new_state):
        self.current_state.exit(self)
        self.current_state = new_state
        self.current_state.enter(self)

    def add_to_gold_carried(self, val):
        self.gold_carried += val
        self.gold_carried = max(0, self.gold_carried)

    def add_to_wealth(self, val):
        self.money_in_bank += val
        self.money_in_bank = max(0, self.money_in_bank)

    def thirsty(self):
        return self.thirst >= self.THIRST_LEVEL

    def fatigued(self):
        return self.fatigue >= self.TIREDNESS_THRESHOLD

    def pockets_full(self):
        return self.gold_carried >= self.MAX_NUGGETS

    def buy_and_drink_whiskey(self):
        self.thirst = 0
        self.money_in_bank -= 2

    def change_location(self, new_location):
        self.location = new_location

    def increase_fatigue(self):
        self.fatigue += 1

    def decrease_fatigue(self):
        self.fatigue -= 1

    def wealth(self):
        return self.money_in_bank

    def update(self):
        self.thirst += 1
        self.state_machine.update()

    def handle_message(self, msg):
        return self.state_machine.handle_message(msg)

    def __repr__(self):
        return self.name
Beispiel #15
0
class BasePlayer(MovingEntity):
    # max_speed_with_ball = None
    # receiving_range = None

    # @classmethod
    # def initialize_class_parameters(cls,**kwargs):
    #       cls.max_speed_with_ball = kwargs['max_speed_with_ball']
    #       cls.receiving_range = kwargs['receiving_range']

    def __init__(self,
                 image,
                 pitch,
                 team,
                 home,
                 heading,
                 model=model.initial_model,
                 **kwargs):
        super().__init__('redshirt0')  #image,  **kwargs)

        self.max_turn_rate = model.player_max_turn_rate
        self.max_force = model.player_max_force
        self.max_speed = model.player_max_speed

        #register with the entity_manager
        model.entity_manager.register(self)

        self.home = Vector2(home)
        self.pos = Vector2(home)
        self.mass = model.player_mass
        # self.velocity = Vector2()
        # self.heading = Vector2(heading)
        _, self.angle = Vector2(heading).as_polar()

        print('...creating player{}: @ position {}, angle {}'.format(
            self.id, self.pos, self.angle))

        # in case the velocity is zero
        if self.speed < 0.00001:
            self.angle = 0.0
            # self.set_orientation(Vector2(heading))

        self.model = model
        self.max_speed_with_ball = model.player_max_speed_with_ball
        self.receiving_range = model.ball_within_receiving_range
        self.role = None
        self.pitch = pitch
        self.team = team

        self.steering = SteeringBehaviors(self)
        self.steering.separation_on()

        self.state = PState.wait
        self.fsm = StateMachine(self)
        self.fsm.current_state = self.state
        self.fsm.previous_state = self.state
        self.fsm.global_state = PState.global_player
        self.fsm.current_state.enter(self)

        # TODO: implement and test regulator
        # self.kick_limiter = Regulator(self.model.player_kick_frequency)

    def update(self, dt):
        self.fsm.update()
        self.steering.calculate()

        #apply braking if there is no steering force but there is velocity
        if self.steering.steering_force.length() < 0.0001 and (
                self.velocity.length_squared() > 0.001):
            braking_rate = 0.8
            self.velocity *= braking_rate

        # first calculate the speed change due to the force

        #FORWARD COMPONENT CALC
        # get the components now because updating the angle and
        # velocity will change the computations
        forward_component = self.steering.forward_component()
        side_component = self.steering.side_component()

        # first calculate the velocity change due to turning

        dAngle = (side_component * self.max_turn_rate)
        # this will adjust the heading...
        self.angle -= dAngle

        speed = abs(forward_component) * self.max_speed
        self.velocity = (speed / self.mass) * self.heading

        #FORWARD COMPONENT CALC
        # accel = self.heading *  forward_component/ self.mass
        # self.velocity += accel

        # self.exact_pos += self.velocity

        # self.exact_pos +=  speed * self.heading #self.velocity
        self.exact_pos = self.exact_pos + self.velocity

        # if debug_output:
        #       print('   prevPos = {}  position={}'.format(self.prev_pos, self.exact_pos))
        #       print('---END UPDATE\n\n')

    def draw(self, screen):
        super().draw()

        #
        # Show Rendering Aids - Steering_Force
        #

        #DEBUG
        screen.draw.circle(self.home, 10, (255, 0, 0))
        # if self.at_home():

        #print ID
        screen.draw.text(str(self.id), self.exact_pos + Vector2(0, -20))

        if self.model.show_steering_force:
            screen.draw.line(
                self.exact_pos,
                self.exact_pos + self.model.steering_force_display_length *
                self.steering.steering_force, (200, 0, 0))

        if self.model.show_player_states:
            states = ""
            if self.steering.is_seek_on():
                states += "S"
            if self.steering.is_arrive_on():
                states += "A"
            if self.steering.is_separation_on():
                states += "Sp"
            if self.steering.is_pursuit_on():
                states += "P"
            if self.steering.is_interpose_on():
                states += "I"

            if len(states) > 0:
                offset = self.exact_pos + (self.heading * 5) + Vector2(0, 5)
                screen.draw.text(states, offset)

        if self.model.show_heading:
            screen.draw.line(self.exact_pos,
                             self.exact_pos + 50 * self.heading, (0, 255, 0))
            screen.draw.line(self.exact_pos, self.exact_pos + 50 * self.side,
                             (0, 0, 255))

    def ball_within_receiving_range(self):
        return self.exact_pos.distance_to(self.ball()) < self.receiving_range

    def track_ball(self):
        return self.rotate_heading_to_face_position(self.ball())

    def is_controlling_player(self):
        return False

    def at_home(self):
        return self.at_target(self.home)
        # return self.exact_pos.distance_to(self.home) < 0.001

    def at_target(self, target):
        if self.id == 1:
            print('[FieldPlayer.at_target] pos: {}, target: {}, dist: {} '.
                  format(self.exact_pos, target,
                         self.exact_pos.distance_to(Vector2(target))))
            print('    vel= {}, speed= '.format(self.velocity, self.speed))
        return self.exact_pos.distance_to(Vector2(target)) < 1.0

    def arrive_on(self):
        self.steering.on(BehaviorType.ARRIVE)

    def arrive_off(self):
        self.steering.off(BehaviorType.ARRIVE)

    @property
    def tagged(self):
        return self.steering.tagged

    @property
    def ball(self):
        return self.pitch.ball

    def __repr__(self):
        if 'GoalKeeper' in str(type(self)):
            position = '*'
        else:
            position = ''
        return '{{[player{}{}] {}}}'.format(self.id, position, self.exact_pos)
Beispiel #16
0
        newState = "error_state"
    return (newState, txt)

def not_state_transitions(txt):
    splitted_txt = txt.split(None,1)
    word, txt = splitted_txt if len(splitted_txt) > 1 else (txt,"")
    if word in positive_adjectives:
        newState = "neg_state"
    elif word in negative_adjectives:
        newState = "pos_state"
    else:
        newState = "error_state"
    return (newState, txt)

def neg_state(txt):
    print("Hallo")
    return ("neg_state", "")

if __name__== "__main__":
    m = StateMachine()
    m.add_state("Start", start_transitions)
    m.add_state("Python_state", python_state_transitions)
    m.add_state("is_state", is_state_transitions)
    m.add_state("not_state", not_state_transitions)
    m.add_state("neg_state", None, end_state=1)
    m.add_state("pos_state", None, end_state=1)
    m.add_state("error_state", None, end_state=1)
    m.set_start("Start")
    m.run("Python is great")
    m.run("Python is difficult")
    m.run("Perl is ugly")
Beispiel #17
0
 def __init__(self, initial, states=[]):
   StateMachine.__init__(self, initial, states)
from fsm import StateMachine, State
import time
traffic_light = StateMachine("LIGHT_GREEN")

light_green = State()
light_yellow = State()
light_red = State()

traffic_light["LIGHT_GREEN"] = light_green
traffic_light["LIGHT_YELLOW"] = light_yellow
traffic_light["LIGHT_RED"] = light_red


@light_green.transition
def switch():
    return "LIGHT_YELLOW"


@light_yellow.transition
def switch():
    return "LIGHT_RED"


@light_red.transition
def switch():
    return "LIGHT_GREEN"


if __name__ == "__main__":
    while True:
        print("Current State: " + traffic_light.state)
Beispiel #19
0
from signals import SignalProcessing
from timer_class import TimerClass
from comm import USBCommunication
from fsm import StateMachine

import time

# signal_interval, signal_history_window, state_interval, state_history_window in sec
timer_class = TimerClass(0.05, 10.0, 1.0, 100)  # for timer data
fsm_class = StateMachine(timer_class)  # for updating the stage of sleep

# create the comm class and start it to read values from the COM port
# set fake to false if you want to connect to the microcontroller
comm_class = USBCommunication('/dev/cu.usbmodem146131',
                              115200,
                              fake=False,
                              write_to_csv=True,
                              delay=0.001)

# create the signal processing class to manage the comm data
# USBCommunication() class, SignalTimer() class
signal_class = SignalProcessing(comm_class, timer_class)

# updates for both the raw sensor readings and the fsm
sensor_update_last_time = timer_class.get_time()
fsm_update_last_time = timer_class.get_time()

# plotting help
import matplotlib.pyplot as plt

Beispiel #20
0
def first_window_attempt():
    """
    The first attempt at creating a gui.

    :return None:
    """
    class InitialState(BaseState):
        """
        Initial state for the SimpleGUI.
        """
        def _on_enter(self, gui):
            """
            Construct the buttons upon entering the state.

            :return:
            """
            print("In initial state.")
            '''Create label'''
            self.label = tk.Label(gui.root, text="First GUI")
            self.label.pack()
            '''Create buttons'''
            gui.pack_button = tk.Button(gui.root,
                                        text="Buttons",
                                        command=self.adjust_buttons(gui),
                                        font=Font(size=50))
            gui.pack_button.pack()
            gui.greet_button = tk.Button(gui.root,
                                         text="Greet",
                                         command=self._greet,
                                         font=Font(size=50))
            gui.close_button = tk.Button(gui.root,
                                         text="Close",
                                         command=gui.root.quit,
                                         font=Font(size=50))
            gui.update()

        def adjust_buttons(self, gui):
            """
            Adjust the buttons.

            :return:
            """
            def _adjust_buttons():
                print("\tButton clicked.")
                if gui.buttons_on.get():
                    print("\t\tDetected buttons are on.")
                    self._remove_buttons(gui)
                else:
                    print("\t\tDetected buttons are off.")
                    self._add_buttons(gui)

            return _adjust_buttons

        def _add_buttons(self, gui):
            """
            Add buttons to the view.

            :return:
            """
            gui.greet_button.pack()
            gui.close_button.pack()
            gui.buttons_on.set(True)

        def _remove_buttons(self, gui):
            """
            Remove buttons from the view.

            :return:
            """
            gui.greet_button.pack_forget()
            gui.close_button.pack_forget()
            gui.buttons_on.set(False)

        def _greet(self, gui):
            """

            :param gui:
            :return:
            """

        def _on_exit(self, gui):
            """
            Return the next state.

            :param gui:
            :return:
            """
            gui.update()
            return ButtonsOff()

    class ButtonsOn(BaseState):
        """
        State for having buttons on.
        """
        def _on_enter(self, gui):
            """

            :param gui:
            :return:
            """
            print("In buttons on state.")

        def _state_main(self, gui):
            """
            The main code for the ButtonsOn state.

            :param gui:
            :return:
            """
            gui.pack_button.wait_variable(gui.buttons_on)

        def _on_exit(self, gui):
            if gui.program_running:
                gui.update()
                return ButtonsOff()
            else:
                return None

    class ButtonsOff(BaseState):
        """
        State for having buttons off.
        """
        def _on_enter(self, gui):
            """

            :param gui:
            :return:
            """
            print("In buttons off state.")

        def _state_main(self, gui):
            """
            The main code for the ButtonsOn state.

            :param gui:
            :return:
            """
            gui.pack_button.wait_variable(gui.buttons_on)

        def _on_exit(self, gui):
            if gui.program_running:
                gui.update()
                return ButtonsOn()
            else:
                return None

    class SimpleGUI:
        """
        Object for a simple gui.
        """
        def __init__(self, root):
            """
            Initializing the SimpleGUI object.
            """
            self.root = root
            w, h = root.winfo_screenwidth(), self.root.winfo_screenheight()
            self.root.geometry("%dx%d+0+0" % (w, h))
            self.root.protocol("WM_DELETE_WINDOW", self.end_program)
            self.buttons_on = tk.BooleanVar()
            self.buttons_on.set(False)
            self.program_running = True

        def update(self):
            """
            Update the GUI.

            :return:
            """
            self.root.update_idletasks()
            self.root.update()
            return self.root

        def end_program(self):
            """
            Ends the program.

            :return:
            """
            self.buttons_on.set(not self.buttons_on.get())
            self.root.destroy()
            self.program_running = False

    '''Initialize and run GUI object'''
    root = tk.Tk()
    # Maximize window while maintaining title bar
    gui = SimpleGUI(root)
    state_machine = StateMachine(initial_state=InitialState())
    state_machine.run(gui)
Beispiel #21
0
class TerminalGUI(object):
    def __init__(self, username):
        self.username = username
        self._server_protocol = None
        self._print_buffer = ''
        self._game_list = []
        self._waiting_for_list = False
        self._waiting_for_join = False
        self._waiting_for_start = False
        self._in_game = False
        self.client = client.Client()
        self.game_id = None
        self._update_interval = 15
        self.pump_return = None

        self.fsm = StateMachine()

        self.fsm.add_state('START', None, lambda _: 'MAINMENU')
        self.fsm.add_state('MAINMENU', self._main_menu_arrival,
                           self._main_menu_transition)
        self.fsm.add_state('SELECTGAME', self._select_game_arrival,
                           self._select_game_transition)
        self.fsm.add_state('END', None, None, True)

        self.fsm.set_start('START')
        self.fsm.pump(None)

    def set_server_protocol(self, p):
        """Set the protocol interface to the server. This should be a
        NetstringReceiver object.
        """
        self._server_protocol = p

    def _input_choice(self, choice):
        """Provides an input for the state machine. This function
        potentially returns a GameAction object, which is a command
        to be sent to the server.
        """
        # Convert from 1-indexed in the UI to the 0-indexed choices_list
        self.fsm.pump(int(choice) - 1)
        return self.pump_return

    def handle_client_input(self, command):
        """Handle input from client.
        """
        if command in ['help', 'h', '?']:
            self.print_help()
            return

        elif command in ['restart', 'r']:
            self.client.restart_command()
            return

        elif command in ['refresh', 'f']:
            self.send_command(GameAction(message.REQGAMESTATE))
            return

        elif command in ['quit', 'q']:
            lg.info('Quitting game')
            self._server_protocol.loseConnection()
            from twisted.internet import reactor
            reactor.stop()
            return

        if self._in_game and not self.client.builder:
            lg.info("It's not your turn")
            return

        try:
            choice = int(command)
        except ValueError:
            sys.stderr.write('Invalid choice: {0}\n'.format(command))
            self.print_help()
            return

        if self._in_game:
            action = self.client.make_choice(choice)

            if action is not None:
                print 'doing action ' + repr(action)
                self.send_command(action)

        else:
            game_action = self._input_choice(choice)
            if game_action:
                self.send_command(game_action)

    def _main_menu_arrival(self):
        choices = ['List games', 'Join game', 'Create game', 'Start game']
        self.choices = [Choice(desc, desc) for desc in choices]

    def _main_menu_transition(self, choice):
        choice = self.choices[choice].item
        if choice == 'List games':
            self.pump_return = GameAction(message.REQGAMELIST)
            self._waiting_for_list = True
            return 'MAINMENU'

        elif choice == 'Join game':
            if len(self._game_list) == 0:
                lg.info('No games listed. Getting game list first.')
                self.pump_return = GameAction(message.REQGAMELIST)
                self._waiting_for_list = True
                return 'MAINMENU'
            else:
                return 'SELECTGAME'

        elif choice == 'Create game':
            lg.info('Creating new game...')
            self.pump_return = GameAction(message.REQCREATEGAME)
            self._waiting_for_join = True
            return 'MAINMENU'

        elif choice == 'Start game':
            lg.info('Requesting game start...')
            self.pump_return = GameAction(message.REQSTARTGAME)
            self._waiting_for_start = True
            return 'MAINMENU'

        else:
            return 'END'

    def _select_game_arrival(self):
        # we only get here if the game list is populated
        self.choices = [
            Choice(i, str(game)) for i, game in enumerate(self._game_list)
        ]
        self._show_choices()

    def _select_game_transition(self, choice):
        game_id = self.choices[choice].item
        self._waiting_for_join = True
        self.pump_return = GameAction(message.REQJOINGAME, game_id)
        return 'MAINMENU'

    def _show_choices(self, prompt=None):
        """Returns the index in the choices_list selected by the user or
        raises a StartOverException or a CancelDialogExeption.

        The choices_list is a list of Choices.
        """
        i_choice = 1
        for c in self.choices:
            if c.selectable:
                lg.info('  [{0:2d}] {1}'.format(i_choice, c.description))
                i_choice += 1
            else:
                lg.info('       {0}'.format(c.description))

        if prompt is not None:
            lg.info(prompt)
        else:
            lg.info('Please make a selection:')

    def send_command(self, game_action):
        self._server_protocol.send_command(self.username, self.game_id,
                                           game_action)

    def update_game_list(self, game_list):
        self._game_list = game_list

        if self._waiting_for_list:
            self._waiting_for_list = False

            print 'List of games:'
            for record in self._game_list:
                print '  ' + str(record)
            print

            self._show_choices()

    def update_game_state(self, game_state):
        if game_state is None:
            return

        for p in game_state.players:
            if p.name == self.username:
                player_index = game_state.players.index(p)
                self.client.player_id = player_index

        if self._waiting_for_start or game_state.is_started:
            lg.info('Starting game ...')
            self._waiting_for_start = False
            self._in_game = True

        old_gs = self.client.game.game_state
        old_game_id = old_gs.game_id if old_gs else None
        new_game_id = game_state.game_id

        if old_game_id is None or old_game_id != new_game_id:
            self.client.update_game_state(game_state)

    def set_player_id(self, i):
        self.client.player_id = i

    def join_game(self, game_id):
        lg.info('Joined game {0:d}, waiting to start...'.format(game_id))
        self.game_id = game_id
        self._waiting_for_join = False
        self._show_choices()
        #self.routine_update()

    def routine_update(self):
        """Updates the game state routinely.
        """
        self.send_command(GameAction(message.REQGAMESTATE))

        from twisted.internet import reactor
        reactor.callLater(self._update_interval, self.routine_update)
Beispiel #22
0
l = Luring()
t = Trapping()
h = Holding()
q = Quit()

wTable = {"appear":l, "quit": q}
lTable = {"enter":t, "runaway":w, "quit":q}
tTable = {"trapped":h, "escape":w, "quit":q}
hTable = {"removed":w, "quit":q}

w.tableRegister(wTable)
l.tableRegister(lTable)
t.tableRegister(tTable)
h.tableRegister(hTable)

sm = StateMachine(w)

def main():
    
    clearScreen()

    while True:
        printInfo(sm)
        newEvent = getUserInput(sm)
        clearScreen()
        sm.eventHandler(newEvent)
        input("hit a key..")
        clearScreen()
if __name__ == "__main__":
    main()
Beispiel #23
0
 def __init__(self, nfa):
   # stores a map of states-key -> state while we build the DFA
   known_states = {}
   initial = self.__processNFAState([nfa.initial], known_states)
   StateMachine.__init__(self, initial, known_states.values())
class SoccerTeam:
    def __init__(self,
                 side,
                 pitch,
                 display_model=model.initial_model,
                 entity_manager=model.initial_model.entity_manager,
                 dispatcher=model.initial_model.dispatcher):
        # self.model = model
        self.pitch = pitch
        self.view = View(display_model)
        self.view.model = self
        self.side = side
        self._entity_manager = entity_manager
        self._dispatcher = dispatcher

        if side == HOME:
            self.color = pg.Color('red')
            self.goal = self.pitch.home_goal
            self.opponent_goal = self.pitch.away_goal
            self.init_heading = Vector2(-1, 0)

        elif side == AWAY:
            self.color = pg.Color('blue')
            self.goal = self.pitch.away_goal
            self.opponent_goal = self.pitch.home_goal
            self.init_heading = Vector2(1, 0)

        else:
            raise ValueError("side must be either 'HOME' or 'AWAY' ")

        self.players = self.create_players()
        self.opponent = None

        self._controlling_player = None
        self._supporting_player = None
        self._receiving_player = None
        self.player_closest_to_ball = None

        self.dist_sq_to_ball_from_closest_player = sys.float_info.max
        self.support_spot_calculator = SupportSpotCalculator()

        self.fsm = StateMachine(self)
        self.fsm.current_state = TeamState.defending
        self.fsm.previous_state = TeamState.defending
        self.fsm.global_state = None

        #force the state enter logic to run for initial state
        # self.fsm.current_state.enter(self)

    def __call__(self):
        return self.players

    def create_players(self):
        players = []

        if self.home_team:
            regions = [
                self.pitch.pos_from_region(region)
                for region in [11, 16, 15, 4, 2]
            ]
        else:
            regions = [
                self.pitch.pos_from_region(region)
                for region in [1, 6, 8, 3, 5]
            ]

        # goal keeper
        if self.side == HOME:
            image_file = 'redshirt'
        else:
            image_file = 'blueshirt'

        print('create_players(): image_file, pitch = ', image_file, self.pitch,
              self, regions[0], self.init_heading)
        goalkeeper = GoalKeeper(image_file + '0',
                                self.pitch,
                                team=self,
                                home=regions[0],
                                heading=self.init_heading)

        print(' goalkeeper velocity = ', goalkeeper.velocity)
        players.append(goalkeeper)

        # rest of the team
        for idx, region in enumerate(regions[1:]):
            player = FieldPlayer(image_file + str(idx),
                                 self.pitch,
                                 team=self,
                                 home=region,
                                 heading=self.init_heading)

            players.append(player)

        return players

    def calculate_closest_player_to_ball(self):
        closest_so_far = sys.float_info.max
        distances = [
            p.exact_pos.distance_to(self.pitch.ball()) for p in self.players
        ]

        return min(distances)

    def draw(self, screen):
        for player in self.players:
            player.draw(screen)

        # self.view.draw(screen)

    def update(self, dt):
        #calculate this once per frame
        self.calculate_closest_player_to_ball()

        #the team state machine switches between attack/defense behavior. It
        #also handles the 'kick off' state where a team must return to their
        #kick off positions before the whistle is blown
        self.fsm.update()

        for player in self.players:
            player.update(dt)

    def return_all_field_players_home(self):
        for player in self.players:
            dispatcher.dispatch_message(Message.SEND_MSG_IMMEDIATELY, -1,
                                        player.id, Message.GO_HOME, None)

    def can_shoot(self, ball_pos, power, shot_target=Vector2()):
        pass

    def find_pass(self, passer, receiver, pass_target, power,
                  min_passing_distance):
        pass

    def get_best_pass_to_receiver(self, passer, receiver, pass_target, power):
        pass

    def is_pass_safe_from_opponent(self, phrom, target, receiver, opp,
                                   passing_force):
        pass

    def is_pass_safe_from_all_opponents(self, phrom, target, receiver,
                                        passing_force):
        pass

    def is_opponent_within_radius(self, pos, radius):
        pass

    def request_pass(self, requester):
        pass

    def determine_best_supporting_attacker(self):
        pass

    def get_support_spot(self):
        ##        return self.support_spot_calculater.get_best_spot()
        pass

    def get_player_from_id(self, player_id):
        pass

    def set_player_home_region(self, player, region):
        pass

    def determine_best_supporting_position(self):
        return self.support_spot_calculator.determine_best_supportin
        pass

    def update_targets_of_waiting_players(self):
        pass

    def all_players_at_home(self):
        return all([p.at_home for p in self.players])

    def change_state(self, nextState):
        self.fsm.change_state(nextState)

    @property
    def home_team(self):
        return self.side == HOME

    @property
    def away_team(self):
        return self.side == AWAY

    @property
    def in_control(self):
        return self.controlling_player != None

    @property
    def receiving_player(self):
        return self._receiving_player

    @receiving_player.setter
    def receiving_player(self, player):
        self._receiving_player = player

    @property
    def controlling_player(self):
        return self._controlling_player

    @controlling_player.setter
    def controlling_player(self, player):
        self._controlling_player = player

    @property
    def supporting_player(self):
        return self._supporting_player

    @supporting_player.setter
    def supporting_player(self, player):
        self._supporting_player = player
        self.opponent.lost_control()

    def __repr__(self):
        if self.color == 'red':
            return 'Red'
        else:
            return 'Blue'
class Miner(BaseGameEntity):
    COMFORT_LEVEL = 5
    MAX_NUGGETS = 3
    THIRST_LEVEL = 5
    TIREDNESS_THRESHOLD = 5
    
    def __init__(self,name='anonymous'):
        super().__init__()

        self.location = Location.shack
        self.gold_carried = 0
        self.money_in_bank = 0
        self.thirst = 0
        self.fatigue = 0
##        self.current_state = GoHomeAndSleepTilRested.instance()
        self.name = name
        self.state_machine = StateMachine(self)
        self.state_machine.current_state = GoHomeAndSleepTilRested.instance()

##    def change_state(self, new_state):
##        self.current_state.exit( self )
##        self.current_state = new_state
##        self.current_state.enter(self)

    def add_to_gold_carried(self, val):
        self.gold_carried += val
        self.gold_carried = max(0, self.gold_carried)

    def add_to_wealth(self, val):
        self.money_in_bank += val
        self.money_in_bank = max(0, self.money_in_bank)

    def thirsty(self):
        return self.thirst >= self.THIRST_LEVEL

    def fatigued(self):
        return self.fatigue >= self.TIREDNESS_THRESHOLD

    def pockets_full(self):
        return self.gold_carried >= self.MAX_NUGGETS

    def buy_and_drink_whiskey(self):
        self.thirst = 0
        self.money_in_bank -= 2

    def change_location(self,new_location):
        self.location = new_location

    def increase_fatigue(self):
        self.fatigue += 1

    def decrease_fatigue(self):
        self.fatigue -= 1

    def wealth(self):
        return self.money_in_bank

    def update(self):
        self.thirst += 1
        self.state_machine.update()
##        if self.current_state:
##            self.current_state.execute(self)

    def __repr__(self):
        return self.name
Beispiel #26
0
def drag_and_drop_attempt():
    """
        The first attempt at creating a gui.

        :return None:
        """
    class InitialState(BaseState):
        """
        Initial state for the SimpleGUI.
        """
        def _on_enter(self, gui):
            """
            Construct the buttons upon entering the state.

            :return:
            """
            print("In initial state.")
            '''Create drag and drop window'''
            gui.entry_sv = tk.StringVar()
            gui.drop_box_list = []
            gui.drop_box_items = tk.Listbox(master=gui.root,
                                            listvariable=gui.drop_box_list)
            gui.drop_box_text = tk.StringVar()
            gui.drop_box_text.set("Drop images here")
            gui.entry = tk.Entry(gui.root,
                                 textvar=gui.drop_box_text,
                                 justify='center')
            gui.entry.config(font=("Courier", 44))
            gui.entry.place(x=200, y=200, width=800, height=800)
            #gui.entry.pack()
            gui.entry.drop_target_register(DND_FILES)
            gui.entry.dnd_bind('<<Drop>>', self.drop(gui))
            gui.update()

        def _on_exit(self, gui):
            """
            Return the next state.

            :param gui:
            :return:
            """
            gui.update()
            return WaitForDrop()

        def drop(self, gui):
            def _drop(event):
                files = root.tk.splitlist(event.data)
                gui.entry_sv.set(files)

            return _drop

    class WaitForDrop(BaseState):
        """
        State for having buttons on.
        """
        def _on_enter(self, gui):
            """

            :param gui:
            :return:
            """
            print("In wait for drop state.")

        def _state_main(self, gui):
            """
            The main code for the ButtonsOn state.

            :param gui:
            :return:
            """
            gui.entry.wait_variable(gui.entry_sv)
            '''Clean string'''
            files = literal_eval(gui.entry_sv.get())
            '''Remove previous images'''
            if hasattr(gui, "panel"):
                gui.panel.destroy()
            '''Load each image'''
            for file_name in files:
                file_name = file_name.replace("{", "").replace("}", "")
                # image = tk.PhotoImage(file=file_name)
                if ".CR2" in file_name:
                    '''Rawpy implementation'''
                    file_image = rawpy.imread(file_name)
                    file_image = file_image.postprocess()
                    '''Rawkit implementation'''
                    '''file_image = Raw(file_name)
                    file_image = np.array(file_image.to_buffer())'''
                    '''OpenCV implementation'''
                    '''file_image = cv2.imread(file_name)'''
                else:
                    file_image = Image.open(file_name)
                '''image = file_image.resize((500, 500), Image.ANTIALIAS)
                image = ImageTk.PhotoImage(image)
                gui.panel = tk.Label(gui.root, image=image)
                gui.panel.image = image
                gui.panel.pack()'''
                # panel.grid(row=2)

            image_data = np.array(file_image)
            image_data = cv2.cvtColor(image_data, cv2.COLOR_RGB2GRAY)
            '''print(image_data.shape)
            print(image_data)
            print(len(image_data))
            print(len(image_data[0]))'''
            returned_image = Image.fromarray(image_data)
            '''cv2.imshow("Gray", image_data)
            cv2.waitKey()
            cv2.destroyWindow("Gray")'''
            '''enhanced_contrast = ImageEnhance.Contrast(Image.fromarray(file_image))
            enhanced_image = enhanced_contrast.enhance(255)
            enhanced_data = np.array(enhanced_image)
            plot_functions.imshow(enhanced_image)
            plot_functions.show()'''

            # color_space = cv2.cvtColor(image_data, cv2.COLOR_RGB2HSV)
            # print(color_space)
            '''Create mask for white-ish pixels'''
            '''lower_background = np.array([150, 150, 150])
            upper_background = np.array([255, 255, 255])
            print(image_data)
            white_mask = cv2.inRange(image_data, lower_background, upper_background)
            white_mask = cv2.morphologyEx(white_mask, cv2.MORPH_OPEN, np.ones((3,3),np.uint8))
            white_mask = cv2.morphologyEx(white_mask, cv2.MORPH_DILATE, np.ones((3, 3), np.uint8))
            white_mask = white_mask / 255'''
            '''Create mask for black-ish pixels'''
            '''lower_background = np.array([0, 0, 0])
            upper_background = np.array([25, 25, 25])
            black_mask = cv2.inRange(image_data, lower_background, upper_background)
            black_mask = cv2.morphologyEx(black_mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))
            black_mask = cv2.morphologyEx(black_mask, cv2.MORPH_DILATE, np.ones((3, 3), np.uint8))
            black_mask = black_mask / 255'''
            '''Add masks together'''
            '''background_mask = white_mask
            # Ensure no value is above 1
            background_mask = np.clip(background_mask, 0, 1)'''

            copied_image_data = np.asarray(returned_image).copy()
            # background_mask = np.logical_not(background_mask)
            '''for row_index, [mask_row, image_row] in enumerate(zip(background_mask, copied_image_data)):
                # place black pixel on corresponding masked pixels
                # copied_image_data[row_index] = np.array([image_row[pixel] * int(mask_row[pixel]) for pixel in range(len(mask_row))])
                # make pixel fully white on corresponding masked pixels
                copied_image_data[row_index] = np.array([np.array([255, 255, 255]) if int(mask_row[pixel]) else image_row[pixel] for pixel in range(len(mask_row))])'''
            '''Turn removed pixels red'''
            '''mask_image = Image.fromarray(copied_image_data)
            plot_functions.imshow(mask_image)
            plot_functions.show()'''
            trapezoid_data = copied_image_data.copy()

            enhanced_contrast = ImageEnhance.Contrast(
                Image.fromarray(trapezoid_data))
            enhanced_image = enhanced_contrast.enhance(255)
            trapezoid_data = np.array(enhanced_image)
            '''Detect lines'''
            edges = cv2.Canny(trapezoid_data, 75, 150)
            lines = cv2.HoughLinesP(edges,
                                    1,
                                    np.pi / 180,
                                    100,
                                    maxLineGap=1000)
            # print(lines)
            for line in lines:
                x1, y1, x2, y2 = line[0]
                if y1 == y2:
                    cv2.line(copied_image_data, (x1, y1), (x2, y2),
                             (255, 255, 255), 1)
            '''Trapezoid attempt'''

            # filters image bilaterally and displays it
            bilatImg = cv2.bilateralFilter(trapezoid_data, 5, 175, 175)

            # finds edges of bilaterally filtered image and displays it
            edgeImg = cv2.Canny(bilatImg, 75, 200)

            # gets contours (outlines) for shapes and sorts from largest area to smallest area
            contours, hierarchy = cv2.findContours(edgeImg, cv2.RETR_TREE,
                                                   cv2.CHAIN_APPROX_SIMPLE)
            contours = sorted(contours, key=cv2.contourArea, reverse=True)

            # drawing red contours on the image
            for con in contours:
                cv2.drawContours(trapezoid_data, con, -1, (255, 255, 255), 3)
            '''Detect corners'''
            dst = cv2.cornerHarris(edges, 30, 31, 0.001)
            dst = cv2.dilate(dst, None)
            ret, dst = cv2.threshold(dst, 0.01 * dst.max(), 255, 0)
            dst = np.uint8(dst)

            # find centroids
            ret, labels, stats, centroids = cv2.connectedComponentsWithStats(
                dst)
            # define the criteria to stop and refine the corners
            criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,
                        100, 0.001)
            corners = cv2.cornerSubPix(edges, np.float32(centroids), (5, 5),
                                       (-1, -1), criteria)

            good_corners = []
            for corner in corners:
                if (corner[1] < 1000) & (corner[1] > 650) & (
                        corner[0] > 250) & (corner[0] < 2250):
                    good_corners.append(corner)
                    cv2.circle(edges, (corner[0], corner[1]), 10,
                               (255, 255, 255))

            print(good_corners)
            if len(good_corners) >= 3:
                corner_combos = itertools.combinations(good_corners, 3)
            elif len(good_corners) > 1:
                corner_combos = itertools.combinations(good_corners, 2)

            best_corner_combo = None
            best_coef = np.inf
            for corner_combo in corner_combos:
                regression = LinearRegression().fit(
                    np.array([corner[0]
                              for corner in corner_combo]).reshape(-1, 1),
                    np.array([corner[1] for corner in corner_combo]))
                if np.abs(regression.coef_) < best_coef:
                    best_coef = np.abs(regression.coef_)
                    best_corner_combo = np.array(
                        [corner[1] for corner in corner_combo])

            y_edge = int(round(np.mean(best_corner_combo)))
            edges = edges[y_edge:3000, 200:2200]
            copied_image_data = copied_image_data[y_edge:2500, 200:2200]
            trapezoid_data = trapezoid_data[y_edge:2500, 200:2200]

            # and double-checking the outcome
            cv2.imshow("linesEdges", edges)
            cv2.imshow("linesDetected", copied_image_data)
            cv2.imshow("Contours check", trapezoid_data)
            cv2.waitKey()
            cv2.destroyWindow("Contours check")

            # find the perimeter of the first closed contour
            perim = cv2.arcLength(contours[0], True)
            # setting the precision
            epsilon = 0.02 * perim
            # approximating the contour with a polygon
            approxCorners = cv2.approxPolyDP(contours[0], epsilon, True)
            # check how many vertices has the approximate polygon
            approxCornersNumber = len(approxCorners)

            for corners in approxCorners:
                cv2.circle(trapezoid_data, (corners[0], corners[1]),
                           radius=10,
                           color=(255, 255, 255),
                           thickness=-1)
            cv2.imshow("Vertex position", trapezoid_data)
            cv2.waitKey()
            cv2.destroyWindow("Vertex position")
            cv2.imshow("linesEdges", edges)
            cv2.imshow("linesDetected", copied_image_data)
            cv2.waitKey(0)
            cv2.destroyAllWindows()

        def _on_exit(self, gui):
            if gui.program_running:
                gui.update()
                return WaitForDrop()
            else:
                return None

    class DragAndDropGUI:
        """
        Object for a simple gui.
        """
        def __init__(self, root):
            """
            Initializing the SimpleGUI object.
            """
            self.root = root
            w, h = root.winfo_screenwidth(), self.root.winfo_screenheight()
            self.root.geometry("%dx%d+0+0" % (w, h))
            self.root.protocol("WM_DELETE_WINDOW", self.end_program)
            self.program_running = True

        def update(self):
            """
            Update the GUI.

            :return:
            """
            self.root.update_idletasks()
            self.root.update()
            return self.root

        def end_program(self):
            """
            Ends the program.

            :return:
            """
            if self.entry_sv.get() != " ":
                self.entry_sv.set(" ")
            else:
                self.entry_sv.set("!")
            self.root.destroy()
            self.program_running = False

    '''Initialize and run GUI object'''
    root = tkinterdnd2.Tk()
    # Maximize window while maintaining title bar
    gui = DragAndDropGUI(root)
    state_machine = StateMachine(initial_state=InitialState())
    state_machine.run(gui)