Ejemplo n.º 1
0
class GameScene(BaseScene):
    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()

    def update(self) -> None:
        self.player.update()
        self.input_manager.update()
        if self.player.state == "idle":
            move_keys = self.input_manager.move_keys
            if move_keys.left_key:
                self.player.move(Direction.LEFT)
            elif move_keys.right_key:
                self.player.move(Direction.RIGHT)
            elif move_keys.up_key:
                self.player.move(Direction.UP)
            elif move_keys.down_key:
                self.player.move(Direction.DOWN)

    def render(self) -> None:
        self.terrain.render(self.player.transform.draw_position)
        self.player.render()
        self.gradation_render.render(8)
Ejemplo n.º 2
0
    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)
Ejemplo n.º 3
0
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
Ejemplo n.º 4
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()
Ejemplo n.º 5
0
class Manager():
    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()

    def main_loop(self):
        """Main loop for the application. All other functionality is called from this loop.
            In each iteration the current user inputs are checked and the current video stream
            is received. Also the new commands are sent back to the car.
        """
        condition = Command.forward
        prediction = Command.no_command

        while True:

            data = self.connection.receive_image()

            if self.key.quit:
                print("Break")
                break

            if self.mode == Mode.inference:
                prediction = self.application_state.get_last_predicted(
                )["action"]

            action = self.key.get_action()

            condition = self.key.get_condition(condition)

            image = self.gui.transform_image(data)

            self.application_state.set_current(image, condition)

            if action != Command.no_command:
                self.connection.send_command(action)

                if self.key.recording:
                    self.data_manager.append_data(image, action.value,
                                                  condition.value)

            elif self.key.self_driving and prediction != Command.no_command:
                self.connection.send_command(prediction)

            self.gui.show_state(np.copy(image), condition, prediction,
                                self.key.recording, self.key.self_driving)
Ejemplo n.º 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()
Ejemplo n.º 7
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
Ejemplo n.º 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
Ejemplo n.º 9
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()
Ejemplo n.º 10
0
 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()
Ejemplo n.º 11
0
    def on_get_mapping(self):
        self.control_freeze = True

        m = InputManager.get_mapping()
        self.set_value(m.get_args())

        self.queue_events("on_return")
Ejemplo n.º 12
0
    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)
Ejemplo n.º 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()
Ejemplo n.º 14
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()
Ejemplo n.º 15
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
Ejemplo n.º 16
0
class SubmissionManager:
  def __init__(self, config):
    self.config = config
    self.input_manager = InputManager(config)
    
  def run(self):
    files, labels, images = self.input_manager.get_inputs(type='submission', distorted = False, shuffle = False)

    with tf.variable_scope("inference"):    
      logits = self.config.inference(images, testing=True)
        
    # Restore the moving average version of the learned variables for eval.
    variable_averages = tf.train.ExponentialMovingAverage(self.config.training_params.moving_average_decay)
    variables_to_restore = variable_averages.variables_to_restore()
    self.saver = tf.train.Saver(variables_to_restore)
    
    session_manager = SessionManager(self.config)
    global_step, sess = session_manager.restore(self.saver)  
    coord = tf.train.Coordinator()
    try:
      queue_runners = tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS)
      threads_per_qr = map(lambda qr: qr.create_threads(sess, coord=coord, daemon=True, start=True), queue_runners)
      threads = reduce(list.__add__, threads_per_qr)
      num_iter = math.ceil(self.config.dataset.submission_size / self.config.training_params.batch_size)
      
      step = 0
      predictions_ids = []
      predictions = []
      while step < num_iter and not coord.should_stop():
        submission_files, submission_logits = sess.run([files, logits])
        submission_files = list(map(self.config.dataset.retrieve_file_id, submission_files))
        predictions += [submission_logits]
        predictions_ids += submission_files
        step += 1
        
      predictions = np.vstack(predictions)
      predictions = np.float32(predictions)
      predictions += 5e-2
      row_sums = np.reshape(predictions.sum(axis=1), [-1, 1])
      predictions /= row_sums
      
      df = pd.DataFrame(data=predictions)
      cols = list(map(lambda c: 'c' + str(c), range(10)))
      
      df.columns = cols
      df['img'] = predictions_ids
      
      df = df[['img'] + cols]
      df = df.drop_duplicates(subset = ['img'], keep='first')
      df.to_csv('submission.csv', index=False)
      
      coord.request_stop()
      coord.join(threads, stop_grace_period_secs=10)
    except Exception as e:
      coord.request_stop(e)
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()
Ejemplo n.º 18
0
class RunManager(object):
    def __init__(self):
        self.input_manager = InputManager()
        self.display_manager = DisplayManager()

    def start_game(self):
        running = True

        clock = pygame.time.Clock()

        self.display_manager.initialize()

        while running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

            self.input_manager.get_input()
            self.display_manager.update()
            pygame.display.flip()

            clock.tick_busy_loop(flags.frame_rate)
Ejemplo n.º 19
0
    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()
Ejemplo n.º 20
0
Archivo: game.py Proyecto: renton/0g
    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']
     
                                           ))

        # hide mouse cursor
        pygame.mouse.set_visible(False)

        # load resource manager
        self.rm = ResourceManager()

        # load input manager
        self.im = InputManager()

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

        # initialize input buffers
        self.mouse_x,self.mouse_y = (0,0)
        self.mousestate = {}
        self.keystate = {}
Ejemplo n.º 21
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,
Ejemplo n.º 22
0
    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)
Ejemplo n.º 23
0
class DroidBot(object):
    """
    The main class of droidbot
    """
    # this is a single instance class
    instance = None

    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)

    @staticmethod
    def get_instance():
        if DroidBot.instance is None:
            print("Error: DroidBot is not initiated!")
            sys.exit(-1)
        return DroidBot.instance

    def start(self):
        """
        start interacting
        :return:
        """
        if not self.enabled:
            return
        self.logger.info("Starting DroidBot")
        try:
            if self.timeout > 0:
                self.timer = Timer(self.timeout, self.stop)
                self.timer.start()

            self.device.set_up()

            if not self.enabled:
                return
            self.device.connect()

            if not self.enabled:
                return
            self.device.install_app(self.app)

            if not self.enabled:
                return
            self.env_manager.deploy()

            if not self.enabled:
                return
            if self.droidbox is not None:
                self.droidbox.set_apk(self.app.app_path)
                self.droidbox.start_unblocked()
                self.input_manager.start()
                self.droidbox.stop()
                self.droidbox.get_output()
            else:
                self.logger.info("just about to start input manager")
                self.input_manager.start()
                if self.input_manager.policy_name == "gym":
                    self.logger.info("after starting input manager returning ")
                    return
        except KeyboardInterrupt:
            self.logger.info("Keyboard interrupt.")
            pass
        except Exception:
            import traceback
            traceback.print_exc()
            self.stop()
            sys.exit(-1)

        self.stop()
        self.logger.info("DroidBot Stopped")

    def stop(self):
        self.enabled = False
        if self.timer and self.timer.isAlive():
            self.timer.cancel()
        if self.env_manager:
            self.env_manager.stop()
        if self.input_manager:
            self.input_manager.stop()
        if self.droidbox:
            self.droidbox.stop()
        if self.device:
            self.device.disconnect()
        if not self.keep_env:
            self.device.tear_down()
        if not self.keep_app:
            self.device.uninstall_app(self.app)
        if hasattr(self.input_manager.policy, "master") and \
           self.input_manager.policy.master:
            import xmlrpc.client
            proxy = xmlrpc.client.ServerProxy(self.input_manager.policy.master)
            proxy.stop_worker(self.device.serial)
Ejemplo n.º 24
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,
Ejemplo n.º 25
0
class Evaluator:
  def __init__(self, config):
    self.config = config
    self.input_manager = InputManager(config)
    
  def run(self):
    with tf.Graph().as_default() as g:
      tf.set_random_seed(1)
      with tf.variable_scope("eval_inputs"):
        eval_ids,  eval_labels,  eval_images,  eval_add_filters,  eval_features = self.input_manager.get_inputs(type='test', distorted = False, shuffle = False)
      with tf.variable_scope("inference"):
        eval_logits = self.config.inference(eval_images, eval_add_filters, eval_features, testing=True)
        
      self.logits = eval_logits
      self.labels = eval_labels
      
      # Restore the moving average version of the learned variables for eval.
      variable_averages = tf.train.ExponentialMovingAverage(self.config.training_params.moving_average_decay)
      variables_to_restore = variable_averages.variables_to_restore()
      self.saver = tf.train.Saver(variables_to_restore)
   
      try:
        self.evaluate_once()
      except Exception as err:
        print('oHo: {0}'.format(err))            

  def evaluate_once(self):
    session_manager = SessionManager(self.config)
    global_step, sess = session_manager.restore(self.saver)  
    coord = tf.train.Coordinator()
    try:
      queue_runners = tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS)
      threads_per_qr = map(lambda qr: qr.create_threads(sess, coord=coord, daemon=True, start=True), queue_runners)
      threads = reduce(list.__add__, threads_per_qr)
      num_iter = math.ceil(self.config.dataset.set_sizes['test'] / self.config.training_params.batch_size)
      
      step = 0
      acc = []
      
      full_logits = []
      full_labels = []


      while step < num_iter and not coord.should_stop():
        logits, labels = sess.run([self.logits, self.labels])
        full_logits += [logits]
        full_labels += [labels]
        step += 1
      
      logits = np.vstack(full_logits)
      labels = np.vstack(full_labels)
      labels = np.array(labels, np.uint8).reshape((-1))
      
      good_logits = logits[np.arange(logits.shape[0]), labels]
      classirate = good_logits.sum() / logits.shape[0]
      
      print ('Classification rate:',  classirate)        
      coord.request_stop()
      coord.join(threads, stop_grace_period_secs=10)
    except Exception as e:
      coord.request_stop(e)
Ejemplo n.º 26
0
 def __init__(self, config):
   self.config = config
   self.input_manager = InputManager(config)
Ejemplo n.º 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)
Ejemplo n.º 28
0
class DroidBot(object):
    """
    The main class of droidbot
    """
    # this is a single instance class
    instance = None

    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)

    @staticmethod
    def get_instance():
        if DroidBot.instance is None:
            print "Error: DroidBot is not initiated!"
            sys.exit(-1)
        return DroidBot.instance

    def start(self):
        """
        start interacting
        :return:
        """
        if not self.enabled:
            return
        self.logger.info("Starting DroidBot")
        try:
            if self.timeout > 0:
                self.timer = Timer(self.timeout, self.stop)
                self.timer.start()

            self.device.set_up()

            if not self.enabled:
                return
            self.device.connect()

            if not self.enabled:
                return
            self.device.install_app(self.app)

            if not self.enabled:
                return
            self.env_manager.deploy()

            if not self.enabled:
                return
            if self.droidbox is not None:
                self.droidbox.set_apk(self.app.app_path)
                self.droidbox.start_unblocked()
                self.input_manager.start()
                self.droidbox.stop()
                self.droidbox.get_output()
            else:
                self.input_manager.start()
        except KeyboardInterrupt:
            self.logger.info("Keyboard interrupt.")
            pass
        except Exception as e:
            self.logger.warning("Something went wrong: " + e.message)
            import traceback
            traceback.print_exc()
            self.stop()
            sys.exit(-1)

        self.stop()
        self.logger.info("DroidBot Stopped")

    def stop(self):
        self.enabled = False
        if self.timer and self.timer.isAlive():
            self.timer.cancel()
        if self.env_manager:
            self.env_manager.stop()
        if self.input_manager:
            self.input_manager.stop()
        if self.droidbox:
            self.droidbox.stop()
        if self.device:
            self.device.disconnect()
        if not self.keep_env:
            self.device.tear_down()
        if not self.keep_app:
            self.device.uninstall_app(self.app)
Ejemplo n.º 29
0
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:
Ejemplo n.º 30
0
Archivo: game.py Proyecto: renton/0g
class Game():
    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']
     
                                           ))

        # hide mouse cursor
        pygame.mouse.set_visible(False)

        # load resource manager
        self.rm = ResourceManager()

        # load input manager
        self.im = InputManager()

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

        # initialize input buffers
        self.mouse_x,self.mouse_y = (0,0)
        self.mousestate = {}
        self.keystate = {}

    def _step(self):
        # let state handle step
        self.cur_state._step()

    def _draw(self):
        self.screen.fill(SETTINGS['default_bg_color'])

        # let state handle drawing
        self.cur_state._draw()

    def mainloop(self):
        while(1):

            # reset im key events
            self.im.reset_events()

            # event handling
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.display.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    self.im.set_key_event(event.type, event.key)
                if event.type == pygame.JOYBUTTONDOWN:
                    self.im.set_joy_button_event(event.type, event.button)
                if event.type == pygame.MOUSEBUTTONDOWN:
                    self.im.set_mouse_event(event.type, event.button)


            # let state handle input
            self.im.update()
            self.cur_state._input()

            # draw frame
            self._draw()
            self.clock.tick(self.fps)
            pygame.display.flip()

            # step frame
            self._step()
Ejemplo n.º 31
0
class Game():

    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)

    def _step(self):
        self.gui._step()
        self.cur_state._step()

    def _draw(self):
        self.gui._draw()

    def mainloop(self):
        while(1):

            # reset im key events
            self.im.reset_events()

            # event handling
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.display.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    self.im.set_key_event(event.type,event.key)
                if event.type == pygame.MOUSEBUTTONDOWN:
                    self.im.set_mouse_event(event.type,event)

            # let state handle input
            self.im.update()
            self.cur_state._input(self.im)

            # draw frame
            self._draw()
            self.clock.tick(self.fps)
            pygame.display.flip()

            # step frame
            self._step()
Ejemplo n.º 32
0
class GameSystem:
	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
		
	def start_program(self):
		"""Starts off the program, initializing pygame and loading all the
		sprites, sounds and fonts."""
		
		self.setup_pygame()
		self.load_sprites()
		self.load_fonts()
		self.setup_classic_game()
		self.main_loop()
		
	def load_sprites(self):
		"""Loads all of the sprites from the images folder."""
		
		# The image folder url.
		image_folder_url = "../images/"
		
		# The current sprite image being loaded. Not to be confused with the sprite 
		# image class.
		self.load_sprite(image_folder_url, "debug_1.png")
		self.load_sprite(image_folder_url, "debug_2.png")
		self.load_sprite(image_folder_url, "wall_in_up.png")
		self.load_sprite(image_folder_url, "wall_in_down.png")
		self.load_sprite(image_folder_url, "wall_in_left.png")
		self.load_sprite(image_folder_url, "wall_in_right.png")
		self.load_sprite(image_folder_url, "wall_in_upright.png")
		self.load_sprite(image_folder_url, "wall_in_downright.png")
		self.load_sprite(image_folder_url, "wall_in_downleft.png")
		self.load_sprite(image_folder_url, "wall_in_upleft.png")
		self.load_sprite(image_folder_url, "wall_in_center.png")
		self.load_sprite(image_folder_url, "wall_in_hor.png")
		self.load_sprite(image_folder_url, "wall_in_leftT.png")
		self.load_sprite(image_folder_url, "wall_in_rightT.png")
		self.load_sprite(image_folder_url, "wall_out_center.png")
		self.load_sprite(image_folder_url, "wall_out_hor.png")
		self.load_sprite(image_folder_url, "wall_out_vertical_left.png")
		self.load_sprite(image_folder_url, "wall_out_vertical_right.png")
		self.load_sprite(image_folder_url, "wall_out_vertical_left_fade.png")
		self.load_sprite(image_folder_url, "wall_out_vertical_right_fade.png")
		self.load_sprite(image_folder_url, "block_yellow.png")
		self.load_sprite(image_folder_url, "block_skyblue.png")
		self.load_sprite(image_folder_url, "block_orange.png")
		self.load_sprite(image_folder_url, "block_blue.png")
		self.load_sprite(image_folder_url, "block_green.png")
		self.load_sprite(image_folder_url, "block_red.png")
		self.load_sprite(image_folder_url, "block_purple.png")
		self.load_sprite(image_folder_url, "block_grey.png")
		self.load_sprite(image_folder_url, "display_none.png")
		self.load_sprite(image_folder_url, "display_O.png")
		self.load_sprite(image_folder_url, "display_I.png")
		self.load_sprite(image_folder_url, "display_J.png")
		self.load_sprite(image_folder_url, "display_L.png")
		self.load_sprite(image_folder_url, "display_S.png")
		self.load_sprite(image_folder_url, "display_Z.png")
		self.load_sprite(image_folder_url, "display_T.png")
		
	def load_sprite(self, image_folder_url, cur_sprite_image_name):
		"""Loads a single sprite from the images folder."""
		self.pygame_sprites[cur_sprite_image_name] = pygame.image.load( \
			image_folder_url + cur_sprite_image_name)
	
	def load_fonts(self):
		"""Loads all the fonts for the game engine."""
		
		# The fonts url.
		font_url = "../fonts/"
		
		# Load all of the fonts individually.
		self.load_font(font_url, "PressStart2P.ttf", "PressStart2P-small", 12)
		self.load_font(font_url, "PressStart2P.ttf", "PressStart2P-large", 50)
		self.load_font(font_url, "PressStart2P.ttf", "PressStart2P-medium", 32)
	
	def load_font(self, fonts_url, font_file_name, font_key_name, size):
		"""Loads an individual font file."""
		
		# The current font being loaded.
		font1 = pygame.font.Font(fonts_url + font_file_name, size)
		
		self.fonts[font_key_name] = font1
	
	def setup_pygame(self):
		"""Sets up the pygame module."""
		
		# Create the pygame module.
		pygame.init()

		# Get the pygame clock.
		self.pygame_clock = pygame.time.Clock()

		# The backbuffer of the game.
		self.backbuffer = pygame.display.set_mode((640, 800))

		# Set the caption for the game window.
		pygame.display.set_caption("Tetris")
		
	def setup_classic_game(self):
		"""Sets up a classic game of tetris."""
		
		# Load the gameplay game map.
		self.load_map_gameplay()
		
		# The text for the text boxes.
		text = "NEXT:"
		
		# The color of the text for the text boxes.
		color = (0, 0, 0)
		
		# Create all the text boxes for the game gui.
		self.object_factory.create_text_box(80, 32, text, "PressStart2P-small", 
				color, False)
		
		text = "SAVE:"
		self.object_factory.create_text_box(80, 640, text, "PressStart2P-small", 
				color, False)
		
		text = "HIGH SCORE:"
		self.object_factory.create_text_box(565, 32, text, "PressStart2P-small", 
				color, False)
		
		text = "SCORE:"
		self.object_factory.create_text_box(565, 110, text, "PressStart2P-small", 
				color, False)
				
		# Create the tetronimo display objects.
		self.settings.tetronimo_displays.append( \
				self.object_factory.create_tetronimo_display(80, 118))
		self.settings.tetronimo_displays.append( \
				self.object_factory.create_tetronimo_display(80, 262))
		self.settings.tetronimo_displays.append( \
				self.object_factory.create_tetronimo_display(80, 406))
		self.settings.tetronimo_displays.append( \
				self.object_factory.create_tetronimo_display(80, 550))
		self.settings.tetronimo_displays.append( \
				self.object_factory.create_tetronimo_display(80, 726))
		
		self.settings.game_state = 0
		self.settings.reset_tetronimo_assembly()
		
	def load_map_gameplay(self):
		"""Loads the game map for the classic tetris game."""
		
		# First clear the previous game objects.
		self.clear_gameplay_objects()
		
		# Use with to ensure that the file is read entirely.
		with open("map_gameplay.txt", "r") as in_file:
			# The text containing all the characters for the map objects.
			map_text = in_file.read()
				
			# The current x position of the current map object being read from.
			cur_position_x = 8

			# The current y position of the current map object being read from.
			cur_position_y = 8
			
			 # Go through every character and create the correct map object from it.
			for char in map_text:
				if not char == '\n':
				
					# Choose a different sprite based on the character.
					if char == 'C':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_center.png")
					elif char == 'c' or char == ' ':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_out_center.png")
					elif char == 'U':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_up.png")
					elif char == 'D':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_down.png")
					elif char == 'L':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_left.png")
					elif char == 'R':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_right.png")
					elif char == 'H':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_hor.png")
					elif char == 'h':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_out_hor.png")
					elif char == 'l':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_out_vertical_left.png")
					elif char == 'r':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_out_vertical_right.png")
					elif char == ',':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_out_vertical_left_fade.png")
					elif char == '.':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_out_vertical_right_fade.png")
					elif char == '/':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_upleft.png")
					elif char == '\\':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_upright.png")
					elif char == '[':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_downleft.png")
					elif char == ']':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_downright.png")
					elif char == 'T':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_leftT.png")
					elif char == 't':
						self.object_factory.create_gui_wall(
								cur_position_x, cur_position_y, "wall_in_rightT.png")
						
					cur_position_x += 16

					if cur_position_x >= (40 * 16) + 8:
						cur_position_x = 8
						cur_position_y += 16
			
	
	def load_map_game_over(self):
		"""Loads the game over map after the player loses."""
		
		# First clear the previous game objects.
		self.clear_gameplay_objects()
		
		print("Game over!")
		
	def clear_gameplay_objects(self):
		for key in self.game_objects:
			# The current game object being deleted.
			cur_game_obj = self.game_objects[key]
			
			# The tag of the current game object.
			cur_tag = cur_game_obj.tag
			if cur_tag == 0 or cur_tag == 1 or cur_tag == 2 or cur_tag == 3 or \
					cur_tag == 4 or cur_tag == 5:
				cur_game_obj.marked_for_deletion = True
			
	def main_loop(self):
		"""The main loop for updating the game objects and updating all of the engine components."""
		
		# The entrance to the main loop. The game will continue to loop until 
		# is_active is set to false.
		while self.is_active:
			# Manage the frame rate to 60 fps.
			self.pygame_clock.tick(60)
			self.delta_time = self.pygame_clock.get_time()

			# Reset the tapped keys in the input manager.
			self.input_manager.reset_tapped_keys()
			
			# Check the keyboard input events.
			self.input_manager.check_events()
			
			# If the q key is pressed, exit the game.
			if self.input_manager.pressed_q:
				self.is_active = False
			else:
				# Update the game state.
				
				# Gather the game object types.
				self.gather_objects()
				
				# Update the game objects.
				self.settings.update(self.delta_time)
				
				# Update the tetronimos falling.
				for key in self.tetronimos_falling:
					# The current game object being updated.
					cur_object = self.tetronimos_falling[key]
					
					# Only update game objects that are active.
					if cur_object.is_active:
						cur_object.update(self.delta_time)
					
				# Update the tetronimo displays.
				for key in self.tetronimo_displays:
					# The current game object being updated.
					cur_object = self.tetronimo_displays[key]
					
					#Only update game objects that are active.
					if cur_object.is_active:
						cur_object.update(self.delta_time)
					
				self.destroy_objects_marked_for_deletion()
				
				# Update the collision detection.
				self.collision_detection()
				self.destroy_objects_marked_for_deletion()
				self.gather_objects()
				
				# Render the game objects.
				self.render_objects()
				
		# Clean up the game engine when finished.
		self.clean_up()
		
	def destroy_objects_marked_for_deletion(self):
		"""Destroys the game objects that are marked for deletion."""
		
		# The empty keys of the dictionary.
		empty_keys = []
		
		for key in self.game_objects:
		    # The current game object being deleted.
			cur_object = self.game_objects[key]
			
			# If marked for deletion, remove the game object from the game object 
			# dictionary.
			if cur_object.marked_for_deletion:
				self.game_objects[key] = None
				empty_keys.append(key)
				
		# Remove the empty keys.
		for key in empty_keys:
			self.game_objects.pop(key, None)
		
	def collision_detection(self):
		"""Manages the collision detection between certain objects."""
		
		# TODO: For now.
		if self.settings.game_state == 1:
			print("Collision detection.")
		
	def render_objects(self):
		"""Render all the game objects to the screen."""
		# Fill the background with the color black.
		self.backbuffer.fill((0, 0, 0))
		
		# Render every object in the group. Render every object by layer from 0 to 3.
		for x in range (0, 3):
			for key in self.game_objects:
				# The current game object being rendered.
				cur_game_obj = self.game_objects[key]
				
				# Only render game objects that are active.
				if cur_game_obj.is_active:
				
					# The current sprite of the game object being rendered.
					cur_sprite_image = cur_game_obj.cur_sprite_image
					
					# If there is no image, don't render it.
					if cur_sprite_image is not None and \
						cur_sprite_image.image_layer == x and \
						cur_sprite_image.image is not None and \
						cur_sprite_image.image_rect is not None:
						
						# Update the object rect for the rendering process.
						cur_sprite_image.update_image_rect(cur_game_obj.position_x, 
								cur_game_obj.position_y)

						# The current image being rendered.
						cur_image = cur_sprite_image.image

						# The rect of the current image being rendered.
						cur_rect = cur_sprite_image.image_rect

						# Blit the sprite to the backbuffer.
						self.backbuffer.blit(cur_image, cur_rect)
				
		# Swap the backbuffer.
		pygame.display.flip()
		
	def gather_objects(self):
		"""Gathers all of the game objects by tag type for processing."""
		
		# Clear all the previous game object references.
		self.test_objects.clear()
		self.gui_tile_objects.clear()
		self.gui_text_objects.clear()
		self.tetronimos_falling.clear()
		self.tetronimo_blocks.clear()
		self.tetronimo_displays.clear()
		
		# Gather all the game objects and place them in their proper dictionaries.
		for key in self.game_objects:
			# The current game object being examined.
			cur_game_obj = self.game_objects[key]
			
			# The current game object's id.
			object_id = cur_game_obj.object_id
			
			# Check the tag to tell which dictionary to put the object reference in.
			if cur_game_obj.tag == 0:
				self.test_objects[object_id] = cur_game_obj
			elif cur_game_obj.tag == 1:
				self.gui_tile_objects[object_id] = cur_game_obj
			elif cur_game_obj.tag == 2:
				self.gui_text_objects[object_id] = cur_game_obj
			elif cur_game_obj.tag == 3:
				self.tetronimos_falling[object_id] = cur_game_obj
			elif cur_game_obj.tag == 4:
				self.tetronimo_blocks[object_id] = cur_game_obj
			elif cur_game_obj.tag == 5:
				self.tetronimo_displays[object_id] = cur_game_obj
	
	@staticmethod
	def clean_up():
		"""Cleans up the game system after it is finished working."""
		# Exit pygame.
		pygame.quit()
Ejemplo n.º 33
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:
Ejemplo n.º 34
0
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
Ejemplo n.º 35
0
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 = """