コード例 #1
0
def main():
    pg.init()
    pg.font.init()

    #TEMP: hardcoded keymaps.
    inputs = [
        #InputManager({
        #    'x_axis': (pg.K_j, pg.K_l),
        #    'y_axis': (pg.K_k, pg.K_i),
        #    'brake': pg.K_SPACE,
        #}),
        InputManager({
            'thrust': pg.K_UP,
            'brake': pg.K_DOWN,
            'turn_direction': (pg.K_LEFT, pg.K_RIGHT),
        }),
        InputManager({
            'thrust': pg.K_PERIOD,
            'brake': pg.K_e,
            'turn_direction': (pg.K_o, pg.K_u),
        }),
    ]

    env = Environment(inputs)
    disp = Display(env, SCREENSIZE)
    env.load_level(
        levels.inelastic_collision_bug)  # TEMP, hardcoded level selection.

    main_loop(env, disp)

    pg.quit()
コード例 #2
0
ファイル: game.py プロジェクト: renton/card-rogue
    def __init__(self):
        pygame.init()

        self.clock = pygame.time.Clock()
        self.fps = SETTINGS['default_fps']

        # fullscreen on/off
        if SETTINGS['fullscreen_mode']:
            self.screen = pygame.display.set_mode((
                                                    SETTINGS['window_x_size'],
                                                    SETTINGS['window_y_size']
                                                    ),
                                                    pygame.FULLSCREEN
                                                )
        else:
            self.screen = pygame.display.set_mode((
                                                    SETTINGS['window_x_size'],
                                                    SETTINGS['window_y_size']
                                                ))

        # load resource manager
        self.rm = ResourceManager()

        # load input manager
        self.im = InputManager()

        # state setup
        self.cur_state = BoardState(self.screen,self.rm)

        # gui
        self.gui = PGui(self)
コード例 #3
0
ファイル: op_pi.py プロジェクト: carlesp-onielfa/OP-Pi
 def start_input_thread(self):
     self.input_queue = Queue()
     im = InputManager()
     input_thread = Process(target=im.input_loop,
                            args=(self.input_queue, ),
                            daemon=True)
     input_thread.start()
コード例 #4
0
ファイル: input_database.py プロジェクト: uuay/wc-data
def main():
    connection = get_connection()
    manager = InputManager(connection)
    sql = ("INSERT INTO facilities (name, type, address, tel_number, top_district_id, createdAt, updatedAt)"
                "VALUES (%s, %s, %s, %s, '%s', %s, %s ) ")
    current_time = datetime.now()

    print('start')
    try:
        print('read csv')
        f = open('new.csv', 'r', encoding="euc-kr")  # csv 파일 오픈
        print('create reader')
        rdr = csv.reader(f)
        for line in rdr:
            if line[0] == '기관코드': continue
            data = (line[5], 'resident', line[8], line[6], disitricts.index(line[3]) + 1, current_time, current_time)
            manager.csv_into_db(sql, data)  # DB저장
            time.sleep(0.01)
        connection.close()

    except Exception as ex:
        print('exception! stop input')
        connection.close()

    print('done')
    return
コード例 #5
0
 def __init__(self, mode, config):
   self.is_running = True
   self.window = None
   self.input_manager = InputManager()
   self.reload_mode(mode)
   self.config = config
   self.network = Network(self)
   self.register_mode = None
コード例 #6
0
 def __init__(self, director: Director) -> None:
     super().__init__(director)
     self.level = 1
     self.terrain = Terrain()
     self.terrain.generate(self.level)
     self.player = Player(self.terrain.data)
     self.input_manager = InputManager()
     self.gradation_render = GradationRender()
コード例 #7
0
class Manager:
    ##Screen
    width, height = 950, 600
    size = width, height
    
    screen  = pygame.display.set_mode(size)

    pygame.display.set_caption("SpaceInvaders")        
    
    #InputManager
    inputManager = InputManager()

    #Introduction state
    state = StateGameIntro(0, screen, inputManager)
    client = start_client()
    
    #Game started check
    game_started = False
    #Main Loop
    def _run(self):
        self.gameOn = True
        
        while self.gameOn:
            dt = fpsClock.tick(30)
            run()
            #Inputs
            self.inputManager.update()
            
            if self.game_started == False:
                if self.state.start == 100:
                    self.set_state(StateGame(self.screen, self.inputManager, self.client))
                    self.game_started = True
            
            #Updates
            self.update(dt)
                
            #Renders, put in the screen
            self.render()
        
    
    #Update
    def update(self, dt):
        #state updates
        new_state = self.state.update(dt)
        if (new_state == 0):
            return
       
    def set_state(self, state):
        self.state.destroy()
        self.state = state
    
    #Render
    def render(self):
        #state renders
        self.state.render()
        
        #updates the display
        pygame.display.update()
コード例 #8
0
 def __init__(self, mode, config):
     self.is_running = True
     self.window = None
     self.input_manager = InputManager()
     self.reload_mode(mode)
     self.config = config
     self.network = Network(self)
     self.register_mode = None
     self.last_registered = 0
     self.parsed_sequence: Union[Sequence, None] = None
コード例 #9
0
class Manager:

    ##Screen
    width, height = 950, 600
    size = width, height

    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("SpaceInvaders")

    #Server
    server = start_server()

    #InputManager
    inputManager = InputManager()

    #Introduction state
    state = StateGameServer(screen, inputManager)

    #Main Loop
    def _run(self):
        self.gameOn = True

        while self.gameOn:
            run()
            dt = fpsClock.tick(30)

            #Inputs
            self.inputManager.update()

            #Updates
            self.update(dt)

            #Renders, put in the screen
            self.render()

    #Update
    def update(self, dt):
        #state updates
        new_state = self.state.update(dt)
        if (new_state == 0):
            return

    def set_state(self, state):
        self.state.destroy()
        self.state = state

    #Render
    def render(self):
        #state renders
        self.state.render()

        #updates the display
        pygame.display.update()
コード例 #10
0
	def __init__(self):
		self.socket_object = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.socket_object.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)

		self._connect()

		self.input_service = InputManager()
		self.sender_service = Sender()
		self.protocol = Client2Server()
		self.receiver_service = Receiver()

		self.username = None
		self.is_authenticated = False
		self._authenticate()
コード例 #11
0
ファイル: game.py プロジェクト: frostblooded/1d_game
    def start():
        PixelsManager.setup()
        Map.setup()
        GameEnder.setup()
        TimeManager.setup()
        InputManager()
        Player.get_instance()
        Spawner()
        print("Starting game")

        GameManager.get_instance().run()

        print("Ending game")
        TimeManager.destroy()
        Player.destroy_instance()
        ObjectsHolder.objects.clear()
コード例 #12
0
ファイル: zm_applet.py プロジェクト: MarkoHoe/zm-applet
    def __init__(self):
        def get_input_handlers(controller, app_config):
            handlers = [PygameInputHandler(controller, app_config)]
            try:
                from pi_input_handler import PiInputHandler

                handlers.append(PiInputHandler(controller, app_config))
            except ImportError:
                print('Unable to import raspberrypi input handler')
            return handlers

        def get_zoneminder_client(app_config):
            zm_client = ZoneMinderClient(app_config.config[SERVER_HOST],
                                         app_config.config[SERVER_PORT],
                                         app_config.config[ZM_WEB_PATH],
                                         app_config.config[USER_NAME],
                                         app_config.config[PASSWORD],
                                         app_config.config[ZMS_WEB_PATH])
            return zm_client

        config = AppConfig()
        event_bus = EventBus()
        client = get_zoneminder_client(config)
        self.app_state = AppState()
        self.app_context = AppContext(config, client, event_bus)

        self.display = PygameDisplay(config)
        self.display.init()
        self.app_context.display_size = self.display.get_display_size()

        zm_stream_component = MonitorStreamComponent(self.app_context)
        group_selector_component = GroupSelectorComponent(self.app_context)
        monitor_selector_component = MonitorSelectorComponent(self.app_context)
        shutdown_prompt_component = ShutdownPromptSelector(self.app_context)
        menu_selector = MenuSelector(self.app_context)
        startup_component = StartUpComponent(self.app_context)
        self.component_manager = AppComponentManager(
            self.display, event_bus, startup_component, zm_stream_component, [
                group_selector_component, monitor_selector_component,
                shutdown_prompt_component, menu_selector
            ])
        self.input_manager = InputManager(get_input_handlers(
            event_bus, config))
        self.app_controller = AppController(self.app_context,
                                            self.input_manager, self.app_state)
        self.task_manager = TaskManager(event_bus)
コード例 #13
0
    def __init__(self, mode: Mode, connection: Network,
                 application_state: CurrentState, data_manager: DataManager):
        """Inits the manager

        Args:
            mode (Mode): Mode in which the application is running
            connection (Network): Network connection
            application_state (CurrentState): Current application state
            data_manager (DataManager): Data management object
        """
        self.mode = mode
        self.connection = connection
        self.application_state = application_state
        self.data_manager = data_manager

        self.key = InputManager(data_manager, mode)
        self.gui = Gui()
コード例 #14
0
    def __init__(self, lcd, flow_meters):
        StopableThread.__init__(self, "CisternUI")

        self.lcd = lcd
        self.flow_meters = flow_meters

        self.ui_lock = threading.Lock()
        self.lcd_lock = threading.Lock()

        # initialize the pages
        self.pages = self.create_pages(self.lcd, self.flow_meters)
        self.page_num = 0

        # initialize the input manager
        self.input_manager = InputManager(self.lcd)

        # bind inputs
        self.input_manager.up_button.on_pressed_callback = self.on_up_pressed
        self.input_manager.down_button.on_pressed_callback = self.on_down_pressed
コード例 #15
0
Creates:
  /output/predictions.csv: a CSV with columns ['lab_id', 'survival']
"""

import pandas

from input_manager import InputManager
from input_manager import RawInputs
from model import Model

if __name__ == "__main__":
    # Loading input files.
    raw_inputs = RawInputs('/input')
    raw_inputs.load()
    im = InputManager(raw_inputs)
    im.prepInputs()
    im.printStats()

    # Loading model params.
    model = Model('/model')
    model.load()

    lab_ids = im.getAllSpecimens()

    survivals = []
    for lab_id in lab_ids:
        survivals.append(model.predictSurvival(im, lab_id))

    pandas.DataFrame({
        'lab_id': lab_ids,
コード例 #16
0
ファイル: droidbot.py プロジェクト: husam88/DroidbotX
    def __init__(self,
                 app_path=None,
                 device_serial=None,
                 is_emulator=False,
                 output_dir=None,
                 env_policy=None,
                 policy_name=None,
                 random_input=False,
                 script_path=None,
                 event_count=None,
                 event_interval=None,
                 timeout=None,
                 keep_app=None,
                 keep_env=False,
                 cv_mode=False,
                 debug_mode=False,
                 profiling_method=None,
                 grant_perm=False,
                 enable_accessibility_hard=False,
                 master=None,
                 humanoid=None,
                 ignore_ad=False,
                 replay_output=None):
        """
        initiate droidbot with configurations
        :return:
        """
        logging.basicConfig(
            level=logging.DEBUG if debug_mode else logging.INFO)

        self.logger = logging.getLogger('DroidBot')
        DroidBot.instance = self

        self.output_dir = output_dir
        if output_dir is not None:
            if not os.path.isdir(output_dir):
                os.makedirs(output_dir)
            html_index_path = pkg_resources.resource_filename(
                "droidbot", "resources/index.html")
            stylesheets_path = pkg_resources.resource_filename(
                "droidbot", "resources/stylesheets")
            target_stylesheets_dir = os.path.join(output_dir, "stylesheets")
            if os.path.exists(target_stylesheets_dir):
                shutil.rmtree(target_stylesheets_dir)
            shutil.copy(html_index_path, output_dir)
            shutil.copytree(stylesheets_path, target_stylesheets_dir)

        self.timeout = timeout
        self.timer = None
        self.keep_env = keep_env
        self.keep_app = keep_app

        self.device = None
        self.app = None
        self.droidbox = None
        self.env_manager = None
        self.input_manager = None
        self.enable_accessibility_hard = enable_accessibility_hard
        self.humanoid = humanoid
        self.ignore_ad = ignore_ad
        self.replay_output = replay_output

        self.enabled = True

        try:
            self.device = Device(
                device_serial=device_serial,
                is_emulator=is_emulator,
                output_dir=self.output_dir,
                cv_mode=cv_mode,
                grant_perm=grant_perm,
                enable_accessibility_hard=self.enable_accessibility_hard,
                humanoid=self.humanoid,
                ignore_ad=ignore_ad)
            self.app = App(app_path, output_dir=self.output_dir)

            self.env_manager = AppEnvManager(device=self.device,
                                             app=self.app,
                                             env_policy=env_policy)
            self.input_manager = InputManager(
                device=self.device,
                app=self.app,
                policy_name=policy_name,
                random_input=random_input,
                event_count=event_count,
                event_interval=event_interval,
                script_path=script_path,
                profiling_method=profiling_method,
                master=master,
                replay_output=replay_output)
        except Exception:
            import traceback
            traceback.print_exc()
            self.stop()
            sys.exit(-1)
コード例 #17
0
import re
import os
import configuration
import sys
# read in user configurations
user_config = configparser.ConfigParser()
user_config.read(getcwd() + '/pox.ini')

# URL for Poem Server
poem_server = configuration.get_server(user_config)
print(poem_server)
# Create an Twilio client
twilio_client = Client(configuration.get_account_sid(user_config),
                       configuration.get_auth_token(user_config))

inputs = InputManager('/dev/ttyACM0', 9600)

dials = configuration.get_dial_values(user_config)
dialPins = configuration.get_pins(user_config)

counter = 0
print(dialPins)
print(dials)

for dial in sorted(dials.items()):
    print(dial[0])
    inputs.add_input(dialPins[counter], list(dials[dial[0]]), dial[0], 1024)
    counter += 1

button = ButtonManager(go_pin=18,
                       reset_pin=23,
コード例 #18
0
    def __init__(self):
        self.inputManager = InputManager()
        self.outputManager = OutputManager()

        self.created_backup = False
        self.terminal = False
コード例 #19
0
ファイル: lilly.py プロジェクト: AppLoidx/telebot
class Lilly:
    def __init__(self):

        self.queue = Queue()
        # Для парсинга сайтов
        self.parser = parser.Parser()
        self.schedule = ScheduleFromFile()
        # Для работы с датами
        self.date = date.Date()
        # Мобильная версия отличается тем, что команды выполниемые на компьютере посылает их через сокеты
        self.mobileVersion = True
        # Вопросы про Java OOP
        self.get_question_of_java = GetQuestion()
        # IP - адресс соединения  с компьютером
        self.sc = server_client.ServerClient('192.168.43.212', 9090)
        # Приветственное сообщение было отправлено во время сеанса
        self.WELCOME_MSG_SEND = False
        # Режим суперпользователя
        self.SUPER_USER = True
        # Рецептов просмотрено во время сеанса
        self.RECIPE_WATCHED = 0

        # TODO: convert it to file or sql data base
        # Исполняемые команды. Команды в одном массиве однотипные
        self.COMMANDS = [
            ["РАСПИСАНИЕ", "РАСПИСАНИЕ ЗАВТРА"],  # 0
            ["ТВОЙ СОЗДАТЕЛЬ", "КТО ТЫ?"],  # 1
            ["СПАСИБО", "THX", "THANKS", "THANK YOU", " СПАСИБКИ", "СПС"],  # 2
            ["ADMIN"],  # 3
            ["ЗАПУСТИ МУЗЫКУ", "MUSIC"],  # 4
            ["ОТКРОЙ ВК", "VK"],  # 5
            ["ПОГОДА"],  # 6
            ["HELIOS"],  # 7
            ["ПРИВЕТ", "ЗДАРОВА"],  # 8
            ["ЗАВТРАК", "ЧТО ПРИГОТОВИТЬ НА ЗАВТРАК", "ЕДА НА ЗАВТРАК"],  # 9
            ["HELP", "ПОМОЩЬ"],  # 10
            ["JAVA OOP", "ВОПРОС ПРО JAVA OOP", "ЗАДАЙ ВОПРОС ПРО JAVA"],  # 11
            ["СОЗДАЙ ОЧЕРЕДЬ"],  # 12
            ["ОЧЕРЕДЬ", "РЕДАКТИРОВАТЬ ОЧЕРЕДЬ"]  # 13
        ]

        # TODO: convert it to file or sql data base
        # Различные вариации ответа на неопознанную команду
        self.IDONTKNOW_COMMANS = [
            "Не могу распознать", "Прости, но я тебя не понимаю...",
            "Что это за слово? Меня ему еще не учили...",
            "Попробуй написать это по-другому, может тогда я смогу распознать его!",
            "Не знаю... Прости..."
        ]

        # Исполняемая команда, по умолчанию get_command
        # Может меняться в методе update_screen()
        self.NEXT_INPUT = "get_command"

        # Используется для ответа не неопознанные команды
        self.UNKNOWN_COMMANDS = 0

    def get_welcome_msg(self, user_id: any) -> str:
        """ Возвращает приветственное сообщение с именем пользователя
        @:param user_id - id пользователя которому присылается сообщение
        @:return "Привет + $ИМЯ_ПОЛЬЗОВАТЕЛЯ" """

        if self.parser.LAST_USER_NAME is None:
            user_name = self.parser.get_user_name_from_vk_id(user_id)
        else:
            user_name = self.parser.LAST_USER_NAME
        self.WELCOME_MSG_SEND = True
        return "Привет, " + user_name.split()[0] + "!"

    # TODO: Rewrite to class
    def get_command(self, command):
        """
        Получает команду, затем обрабатывает её со списоком команд используя метод compare
        и выполняет соответветсвующую команду

        Если команда должна выполниться на компьютере, то через сокеты передает команду на сервер компьютера.
        Перед применением необходимо, чтобы компьютер и телефон были в одной вай-фай сети и получить значение
        IP-адреса через ipconfig.

        :param command: команда переданная польщователем
        :return: Возвращает текст, который следует вывести в сообщении
        """

        # Расписание
        if self.compare(command.split(" ")[0], self.COMMANDS[0]):
            command = command.split(" ")
            if len(command) > 1:
                if self.compare(command[1], ["ЗАВТРА"]):
                    return self.schedule.get_schedule(1)

                else:
                    try:
                        return self.schedule.get_schedule(int(command[1]))
                    except ValueError:
                        return "Вы неправильно ввели данные, поэтому я не смогла их прочитать." \
                               "Я выведу сегодняшнее расписание:\n" + self.schedule.get_schedule()

            return self.schedule.get_schedule()

        # TODO: convert ask to file text
        # About assistant
        elif self.compare(command, self.COMMANDS[1]):
            return "Меня создал Артур. Сейчас я не сильно умею различать получаемые сообщения, но он пообещал " \
                   "мне в будущем расширить мои функции. Как-то он мне говорил, что я написана на питоне." \
                   "Не знаю, что это значит...но так сказал мой создатель."

        # Ответ на благодарность
        elif self.compare(command, self.COMMANDS[2]):
            return "Рада помочь!"

        # TODO: realize it
        # Авторизация супер пользователя
        elif self.compare(command, self.COMMANDS[3]):
            self.NEXT_INPUT = "admin_login"
            return "Введите логин и пароль отдельными сообщениями"

        # Отправление погоды сообщением
        elif self.compare(command, self.COMMANDS[6]):
            return self.parser.get_weather_today()

        # TODO: reformat couples with computer
        # Запуск музыки на комп
        elif self.compare(command, self.COMMANDS[4]):
            print(self.sc.send(b"launchYoutubeMusic"))
            return "Запускаю музыку..."

        # Запуск ВК на комп
        elif self.compare(command, self.COMMANDS[5]):
            print(self.sc.send(b"launchVK"))
            return "Запускаю ВК на компьютер"

        # Открытие helios...
        elif self.compare(command, self.COMMANDS[7]):
            print(self.sc.send(b"launchHelios"))
            return "Запускаю Helios"

        # Повторное приветствие
        elif self.compare(command, self.COMMANDS[8]):
            return "Привет))"

        # Рецепт завтрака
        elif self.compare(command, self.COMMANDS[9]):
            self.RECIPE_WATCHED = 0
            return self.get_breakfast_recipe()

        # TODO: reformat to input from file
        # Вывести документацию
        elif self.compare(command, self.COMMANDS[10]):
            return self.DOCUMENTATION

        # Задать вопрос про Java ООП
        elif self.compare(command, self.COMMANDS[11]):
            return self.java_questions_mode()

        elif self.compare(command, self.COMMANDS[12]):
            self.queue.new_queue()
            result = ""
            persons = self.queue.get_queue()
            for person_id in range(len(persons)):
                result += f"{str(person_id + 1)} {persons[person_id].get_name()} ({persons[person_id].get_id()})\n"
            return str(result)

        elif self.compare(command, self.COMMANDS[13]):
            self.NEXT_INPUT = "queue_edit_mode"
            self.im.set_next_method("queue_edit_mode")
            return self.queue_edit_mode(None)

        # Команда не распознана
        else:

            self.UNKNOWN_COMMANDS += 1

            if self.UNKNOWN_COMMANDS == 1:
                return "Извините, но такой команды я пока не знаю." \
                       "Пожалуйста, напишите моему создателю, чтобы он его добавил..."
            elif self.UNKNOWN_COMMANDS == 2:
                return "Такой команды я тоже не знаю... Простите..."
            elif self.UNKNOWN_COMMANDS == 3:
                return "Может вы как-то неправильно пишете команду?"
            elif self.UNKNOWN_COMMANDS == 4:
                return "Не могу распознать команду!"
            else:
                return self.IDONTKNOW_COMMANS[random.randint(
                    0, len(self.IDONTKNOW_COMMANS))]

    # TODO: Rewrite to class
    def java_questions_mode(self, command="@#"):  # @# - если это первый вызов
        """ Переходит в режим вопросов по теме Java. Имеет свои команды взаимодействия."""

        # Следующий ввод перенаправляем в этот метод
        self.NEXT_INPUT = "java_questions_mode"
        self.im.set_next_method("java_questions_mode")
        if command == "@#":
            return ("Теперь я в режиме вопросов :)\n"
                    "Доступные команды:\n"
                    "вопрос - случайный вопрос\n"
                    "вопрос <номер> - вопрос по номеру\n"
                    "ответ - ответ на предыдущий вопрос, если я знаю))\n"
                    "закончить - выйти из режима вопросов((\n"
                    "очистить - очистить историю вопросов\n"
                    "хелп - вывести доступные команды\n")

        elif command.upper() == "ВОПРОС":
            return self.get_question_of_java.get_question()[1]

        elif command.upper().split(" ")[0] == "ВОПРОС" and len(command) > 7:
            try:
                return self.get_question_of_java.get_question(
                    int(command.split(" ")[1]) - 2)[1]
            except IndexError:
                return "Простите, не нашла такого вопроса... Задайте другой параметр"
        elif self.compare(command.upper(), ["ОТВЕТ"]):
            return self.get_question_of_java.get_question(
                self.get_question_of_java.get_last_question())[2]

        elif self.compare(command.upper(), ["ОЧИСТИТЬ"]):
            self.get_question_of_java.reset_wasted_questions()
            return "История очистена!"

        elif self.compare(command.upper(), ["ХЕЛП"]):
            return ("Доступные команды:\n"
                    "вопрос - случайный вопрос\n"
                    "вопрос <номер> - вопрос по номеру\n"
                    "ответ - ответ на предыдущий вопрос, если я знаю))\n"
                    "закончить - выйти из режима вопросов((\n"
                    "очистить - очистить историю вопросов\n"
                    "хелп - вывести доступные команды\n")

        elif self.compare(command.upper(), ["ЗАКОНЧИТЬ"]):
            self.NEXT_INPUT = "get_command"
            self.im.set_next_method("get_command")
            return "Режим вопросов закончен"
        else:
            return "Не поняла вашего ответа, пожалуйста повторите"

    def queue_edit_mode(self, input_value):
        if input_value is None:
            return "Режим редактирования очереди:\n" \
                   "●Поменять <номер Ису> <номер ИСУ>\n" \
                   "●Добавить <номер ИСУ>\n" \
                   "●Добавить <номер ИСУ> в <позиция в очереди>\n" \
                   "●Удалить <номер ИСУ>\n" \
                   "●Прошел\n" \
                   "●Следющий\n" \
                   "●Прыдыдущий\n" \
                   "●Сейчас\n" \
                   "●История\n"
        else:
            if self.compare(input_value.split()[0], ["Поменять"]):
                self.queue.swap(input_value.split()[1], input_value.split()[2])
                return f"Поменялись местами {input_value.split()[1]} {input_value.split()[2]}"

            elif self.compare(input_value.split()[0], ["Добавить"]):
                if len(input_value.split()) > 2:
                    self.queue.add_person(input_value.split()[1],
                                          int(input_value.split()[3]))
                else:
                    self.queue.add_person(input_value.split()[1])
                return f"{input_value.split()[1]} был добавлен в очередь"

            elif self.compare(input_value.split()[0], ["Удалить"]):
                self.queue.delete_person(input_value.split()[1])
                return f"{input_value.split()[1]} был удален из очереди"

            elif self.compare(input_value, ["Прошел"]):
                self.queue.person_passed()
                return f"{self.queue.get_last_person_in_queue().get_name()} прошел очередь\n" \
                       f"Следующий: {self.queue.get_current_person_in_queue().get_name()}"

            elif self.compare(input_value, ["Следующий"]):
                return self.queue.get_next_person_in_queue().get_name()

            elif self.compare(input_value, ["Предыдущий"]):
                return self.queue.get_last_person_in_queue().get_name()

            elif self.compare(input_value, ["Сейчас"]):
                return self.queue.get_current_person_in_queue().get_name()

            elif self.compare(input_value, ["История"]):
                result = ""
                for history in self.queue.history.get_history():
                    result += history + "\n"

                return result

            elif self.compare(input_value, ["Выйти", "Закончить"]):
                self.NEXT_INPUT = "get_command"

                self.im.set_next_method("get_command")

                return "Вы вышли из режима очереди"

            else:
                return self.get_command(input_value)

    def get_schedule(self, tomorrow="no"):

        # TODO: Rewrite it to class Day
        days = [
            "понедельник", "вторник", "среда", "четверг", "пятница", "суббота",
            "воскресенье"
        ]

        # Файлы с разными кодрировками
        sh_filename = "schedule/sh.txt"

        today_day = self.date.get_day_of_week().strip()

        # Получение следующего дня
        if tomorrow == "tomorrow":
            for i in range(len(days)):
                if days[i] == today_day:
                    if i + 1 == len(days):
                        today_day = days[0]
                        break
                    else:
                        today_day = days[i + 1]
                        break

        week_parity = self.date.get_week_parity()
        return self.schedule.get_schedule_from_file(sh_filename, today_day,
                                                    week_parity)

    # TODO: Rewrite to class Recipe
    def get_breakfast_recipe(self, amount: int = 0) -> str:
        """
        Парсит рецепты с раздела завтрак с помощью класса Recipe из файла recipe.py

        :param amount: количество рецептов, которое нужно вывести
        :return: рецепты
        """

        gr = Recipe()
        recipes = gr.get_breakfast()
        if amount == 0:

            self.NEXT_INPUT = "get_breakfast_recipe"
            return "Введите количество рецептов которое нужно вывести (Максимум: 6 )"
        else:
            try:
                amount = int(amount)
            except ValueError:
                self.NEXT_INPUT = "get_breakfast_recipe"
                return "Я не смогла распознать ваше число. Пожалуйста введите целое число."

            if amount < 1:
                return "Эмм... Не шутите со мной пожалуйста! Введите еще раз. Только сейчас по нормальному!"
            elif amount > 6:
                return "Ммм... я не смогу вывести столько рецептов, простите. Может какое-нибудь число поменьше?))"
            else:
                ret = ""
                temp = 0  # Counter
                for i in range(amount):
                    ret += "Название: " + recipes[self.RECIPE_WATCHED + amount - i][0] + \
                           "\n Ссылка: " + recipes[self.RECIPE_WATCHED + amount - i][1]
                    ret += "\n---------------\n"
                    temp += 1

                self.NEXT_INPUT = "breakfast_more_check"

                self.im.set_next_method("breakfast_more_check")

                self.RECIPE_WATCHED += temp
                return "Вот что я нашла: \n" + ret

    im = InputManager()
    im.set_methods(java_questions_mode, get_command, get_breakfast_recipe,
                   queue_edit_mode)
    im.set_next_method("get_command")

    def update_scr(self, input_value):
        self.im.update(input_value)

    # TODO: Rewrite it to class CommandManager
    def update_screen(self, input_value):
        """
        Метод для управления выполнением других методов. С помощью параметра NEXT_INPUT вызывает соответствующий
        метод. Это нужно, чтобы делать повторный ввод или вызвать определенную последовательность команд
        :param input_value: вводмое значение пользователся, которое передстся определенному методу.
        :return: возвращает метод, определенный в параметре NEXT_INPUT
        """

        print(self.NEXT_INPUT)

        if self.NEXT_INPUT == "java_questions_mode":
            return self.java_questions_mode(input_value)

        if self.NEXT_INPUT == "get_command":
            return self.get_command(input_value)

        if self.NEXT_INPUT == "admin_login":
            self.NEXT_INPUT = "admin_pwd"
            return self.admin_login(input_value)

        if self.NEXT_INPUT == "admin_pwd":
            self.NEXT_INPUT = "get_command"
            return self.admin_pwd(input_value)

        if self.NEXT_INPUT == "get_breakfast_recipe":
            return self.get_breakfast_recipe(input_value)

        if self.NEXT_INPUT == "breakfast_more_check":
            if self.compare(input_value.upper(), ["ЕЩЕ"]):
                return self.get_breakfast_recipe()
            else:
                self.NEXT_INPUT = "get_command"
                return self.get_command(input_value)
        if self.NEXT_INPUT == "queue_edit_mode":
            return self.queue_edit_mode(input_value)

    def admin_login(self, login):
        self.NEXT_INPUT = "admin_pwd"

    def admin_pwd(self, pwd):
        if pwd == "123":
            self.SUPER_USER = True

    # TODO: Rewrite it to class Compare and upgrade algorithm

    @staticmethod
    def compare(name: str, array: list, upper: bool = True) -> bool:
        """
        Сравнивает значение переданного слова со значениями массива. Так же учитваются возможные опечатки,
        но только позиционно. То есть каждая позиция проверяется с соответвующей.

        :param name: проверяемое слово
        :param array: массив, где хранятся возможные значения слова
        :param upper: если истина, то не обращает внимания на регистр, иначе различает
        :return: если хотя бы одно значение с массива совпадает со словом, возращает True, иначе False
        """
        if upper:
            name = name.upper()
            for i in range(len(array)):
                array[i] = array[i].upper()

        for i in array:
            k = 0  # считывание разницы в символах (посимвольно, позиционно)
            if len(i) > len(name):
                for j in range(len(name)):
                    if name[j] == i[j]:
                        pass
                    else:
                        k = k + 1
            else:
                for j in range(len(i)):
                    if i[j] == name[j]:
                        pass
                    else:
                        k = k + 1

            k = k + abs(len(i) -
                        len(name))  # добавление разницы в недостающих символах

            # Обработка возможной опечатки
            if 7 > len(name) > 4 and k < 3:
                return True
            elif 7 <= len(name) < 12 and k < 5:
                return True
            elif len(name) > 11 and k < 7:
                return True
            elif len(name) <= 4 and k < 1:
                return True

        return False

    DOCUMENTATION = """
コード例 #20
0
ファイル: run_manager.py プロジェクト: TheoTomalty/colossus
 def __init__(self):
     self.input_manager = InputManager()
     self.display_manager = DisplayManager()
コード例 #21
0
    def __init__(self,
                 app_path=None,
                 device_serial=None,
                 output_dir=None,
                 env_policy=None,
                 policy_name=None,
                 no_shuffle=False,
                 script_path=None,
                 event_count=None,
                 event_interval=None,
                 timeout=None,
                 keep_app=None,
                 dont_tear_down=False,
                 quiet=False,
                 with_droidbox=False,
                 use_hierarchy_viewer=False,
                 profiling_method=None,
                 grant_perm=False):
        """
        initiate droidbot with configurations
        :return:
        """
        logging.basicConfig(level=logging.WARNING if quiet else logging.INFO)

        self.logger = logging.getLogger('DroidBot')
        DroidBot.instance = self

        self.output_dir = output_dir
        if output_dir is not None:
            if not os.path.isdir(output_dir):
                os.mkdir(output_dir)

        self.timeout = timeout
        self.timer = None
        self.dont_tear_down = dont_tear_down
        self.keep_app = keep_app

        # if device_serial is None:
        #     # Dirty Workaround: Set device_serial to Default='.*', because com/dtmilano/android/viewclient.py
        #     #  set serial to an arbitrary argument. IN connectToDeviceOrExit(..) line 2539f.
        #     # FIXED by requiring device_serial in cmd
        #     device_serial = '.*'

        self.device = None
        self.app = None
        self.droidbox = None
        self.env_manager = None
        self.input_manager = None

        self.enabled = True

        try:
            self.device = Device(device_serial=device_serial,
                                 output_dir=self.output_dir,
                                 use_hierarchy_viewer=use_hierarchy_viewer,
                                 grant_perm=grant_perm)
            self.app = App(app_path, output_dir=self.output_dir)

            if with_droidbox:
                self.droidbox = DroidBox(droidbot=self, output_dir=self.output_dir)

            self.env_manager = AppEnvManager(device=self.device,
                                             app=self.app,
                                             env_policy=env_policy)
            self.input_manager = InputManager(device=self.device,
                                              app=self.app,
                                              policy_name=policy_name,
                                              no_shuffle=no_shuffle,
                                              event_count=event_count,
                                              event_interval=event_interval,
                                              script_path=script_path,
                                              profiling_method=profiling_method)
        except Exception as e:
            self.logger.warning("Something went wrong: " + e.message)
            import traceback
            traceback.print_exc()
            self.stop()
            sys.exit(-1)
コード例 #22
0
import game
import pygame
from pygame import *
import variables as var
from input_manager import InputManager

pygame.init()
InputManager()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((var.SCREEN_WIDTH, var.SCREEN_HEIGHT))
running = True

while running:

    frame_time = clock.get_time()

    screen.fill((0, 0, 0))
    # EVENT LOOP
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # CAMERA SCROLLING
        if event.type == pygame.MOUSEMOTION:
            x, y = event.pos
            if x > var.SCREEN_WIDTH - var.SCROLLING_CONST:
                var.scroling_X_Inc = True
            else:
                var.scroling_X_Inc = False
            if x < var.SCROLLING_CONST:
                var.scroling_X_Dec = True
            else:
コード例 #23
0
ファイル: main.py プロジェクト: richtarj/LudumDare32
from level import Level
from character import Character
from input_manager import InputManager, Actions
from physics_manager import PhysicsManager

TILESIZE = 10

config_handle = open("settings.cfg", "r")
config = json.load(config_handle)
config_handle.close()

USER_MOTION_SPEED, USER_JUMP_SPEED = config["user_motion_speed"], config["user_jump_speed"]

level1 = Level("{0}/first.lvl".format(config["levels_dir"]))
mainChar = Character.genMainCharacter()
inputs = InputManager()
physics = PhysicsManager(level1.width, level1.height)

physics.add_actor(mainChar, has_gravity=True)

pygame.init()
surface = pygame.display.set_mode((level1.width*TILESIZE,level1.height*TILESIZE))

clock = pygame.time.Clock()


pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=4096)
userSounds = SoundManager()

while True:
コード例 #24
0
ファイル: droidbot.py プロジェクト: naseemakhtar994/droidbot
    def __init__(self,
                 app_path=None,
                 device_serial=None,
                 output_dir=None,
                 env_policy=None,
                 policy_name=None,
                 random_input=False,
                 script_path=None,
                 event_count=None,
                 event_interval=None,
                 timeout=None,
                 keep_app=None,
                 keep_env=False,
                 debug_mode=False,
                 with_droidbox=False,
                 use_hierarchy_viewer=False,
                 profiling_method=None,
                 grant_perm=False):
        """
        initiate droidbot with configurations
        :return:
        """
        logging.basicConfig(
            level=logging.DEBUG if debug_mode else logging.INFO)

        self.logger = logging.getLogger('DroidBot')
        DroidBot.instance = self

        self.output_dir = output_dir
        if output_dir is not None:
            if not os.path.isdir(output_dir):
                os.mkdir(output_dir)
            import pkg_resources, shutil
            html_index_path = pkg_resources.resource_filename(
                "droidbot", "resources/index.html")
            stylesheets_path = pkg_resources.resource_filename(
                "droidbot", "resources/stylesheets")
            target_stylesheets_dir = os.path.join(output_dir, "stylesheets")
            if os.path.exists(target_stylesheets_dir):
                shutil.rmtree(target_stylesheets_dir)
            shutil.copy(html_index_path, output_dir)
            shutil.copytree(stylesheets_path, target_stylesheets_dir)

        self.timeout = timeout
        self.timer = None
        self.keep_env = keep_env
        self.keep_app = keep_app

        # if device_serial is None:
        #     # Dirty Workaround: Set device_serial to Default='.*', because com/dtmilano/android/viewclient.py
        #     #  set serial to an arbitrary argument. IN connectToDeviceOrExit(..) line 2539f.
        #     # FIXED by requiring device_serial in cmd
        #     device_serial = '.*'

        self.device = None
        self.app = None
        self.droidbox = None
        self.env_manager = None
        self.input_manager = None

        self.enabled = True

        try:
            self.device = Device(device_serial=device_serial,
                                 output_dir=self.output_dir,
                                 use_hierarchy_viewer=use_hierarchy_viewer,
                                 grant_perm=grant_perm)
            self.app = App(app_path, output_dir=self.output_dir)

            if with_droidbox:
                self.droidbox = DroidBox(droidbot=self,
                                         output_dir=self.output_dir)

            self.env_manager = AppEnvManager(device=self.device,
                                             app=self.app,
                                             env_policy=env_policy)
            self.input_manager = InputManager(
                device=self.device,
                app=self.app,
                policy_name=policy_name,
                random_input=random_input,
                event_count=event_count,
                event_interval=event_interval,
                script_path=script_path,
                profiling_method=profiling_method)
        except Exception as e:
            self.logger.warning("Something went wrong: " + e.message)
            import traceback
            traceback.print_exc()
            self.stop()
            sys.exit(-1)
コード例 #25
0
	def __init__(self):
		"""Initialized the game system."""
		
		# Checks if the game is currently active.
		self.is_active = True
		
		# The current time elapsed in milliseconds.
		self.delta_time = 0.0
		
		# The pygame clock for limiting the framerate.
		self.pygame_clock = None
		
		# The backbuffer being rendered to.
		self.backbuffer = None
		
		# The input manager for managing keyboard and mouse input.
		self.input_manager = InputManager(self)
		
		# The game object factory for creating the game objects.
		self.object_factory = None
		
		# The settings object for managing the gameplay code.
		self.settings = None
		
		# The game objects for the game. Keys are the game object ids.
		self.game_objects = {}
		
		# The test object references.
		self.test_objects = {}
		
		# The GUI tile objects.
		self.gui_tile_objects = {}
		
		# The GUI text objects.
		self.gui_text_objects = {}
		
		# The tetronimos falling. This is updated every frame from objects gathered from 
		# the game_objects dictionary.
		self.tetronimos_falling = {}
		
		# The tetronimo blocks created by the tetronimos falling. Also includes blocks 
		# that have already landed.
		self.tetronimo_blocks = {}
		
		# The tetronimo displays.
		self.tetronimo_displays = {}
		
		# The pygame sprite images.
		self.pygame_sprites = {}
		
		# The fonts for the text boxes.
		self.fonts = {}
		
		# Create the settings object.
		self.settings = Settings()
		
		# Create the game object factory.
		self.object_factory = ObjectFactory(self.game_objects, self.pygame_sprites, 
				self.fonts)
				
		# Attach all the objects to each other.
		self.settings.object_factory = self.object_factory
		self.settings.tetronimos_falling = self.tetronimos_falling
		self.settings.tetronimo_blocks = self.tetronimo_blocks
		self.settings.input_manager = self.input_manager
		self.settings.game_system = self
		
		self.object_factory.settings = self.settings
		self.object_factory.input_manager = self.input_manager
コード例 #26
0
ファイル: main.py プロジェクト: anhthuanprobg/pygame_training
import pygame

from game_object import GameObject, add, update, render
from enemy import Enemy
from bullet import PlayerBullet
from player import Player
from input_manager import InputManager

clock = pygame.time.Clock()
pygame.init()
SCREEN_SIZE = (400, 600)
canvas = pygame.display.set_mode(SCREEN_SIZE)

pygame.display.set_caption("Micro-war")

input_manager = InputManager()
player = Player(200, 540, input_manager)
player.image = pygame.image.load("images/images/player/MB-69/player1.png")

e = Enemy(200, 40)
e.image = pygame.image.load("images/enemy/bacteria/bacteria1.png")

add(player)
add(e)

bullets = []

background_image = pygame.image.load("images/background/background.png")

# right_pressed = False
# left_pressed = False
コード例 #27
0
    def __init__(self,
                 app_path=None,
                 device_serial=None,
                 output_dir=None,
                 env_policy=None,
                 policy_name=None,
                 random_input=False,
                 script_path=None,
                 event_count=None,
                 event_interval=None,
                 timeout=None,
                 keep_app=None,
                 keep_env=False,
                 debug_mode=False,
                 profiling_method=None,
                 grant_perm=False):
        """
        initiate droidbot with configurations
        :return:
        """
        logging.basicConfig(
            level=logging.DEBUG if debug_mode else logging.INFO)

        self.logger = logging.getLogger('DroidBot')
        DroidBot.instance = self

        self.output_dir = output_dir
        if output_dir is not None:
            if not os.path.isdir(output_dir):
                os.mkdir(output_dir)
            html_index_path = pkg_resources.resource_filename(
                "droidbot", "resources/index.html")
            stylesheets_path = pkg_resources.resource_filename(
                "droidbot", "resources/stylesheets")
            target_stylesheets_dir = os.path.join(output_dir, "stylesheets")
            if os.path.exists(target_stylesheets_dir):
                shutil.rmtree(target_stylesheets_dir)
            shutil.copy(html_index_path, output_dir)
            shutil.copytree(stylesheets_path, target_stylesheets_dir)

        self.timeout = timeout
        self.timer = None
        self.keep_env = keep_env
        self.keep_app = keep_app

        self.device = None
        self.app = None
        self.droidbox = None
        self.env_manager = None
        self.input_manager = None

        self.enabled = True

        try:
            self.device = Device(device_serial=device_serial,
                                 output_dir=self.output_dir,
                                 grant_perm=grant_perm)
            self.app = App(app_path, output_dir=self.output_dir)

            self.env_manager = AppEnvManager(device=self.device,
                                             app=self.app,
                                             env_policy=env_policy)
            self.input_manager = InputManager(
                device=self.device,
                app=self.app,
                policy_name=policy_name,
                random_input=random_input,
                event_count=event_count,
                event_interval=event_interval,
                script_path=script_path,
                profiling_method=profiling_method)
        except Exception as e:
            self.logger.warning("Something went wrong: " + e.message)
            import traceback
            traceback.print_exc()
            self.stop()
            sys.exit(-1)