Ejemplo n.º 1
0
 def on_init(self):
     pygame.init()
     self.res = pygame.display.list_modes()[5]
     self._display_surf = pygame.display.set_mode(
         self.res, pygame.HWSURFACE | pygame.DOUBLEBUF)
     self._running = True
     self._loader = Loader(self.res, "resources/level0.json")
     self._level, self._player = self._loader.load()
Ejemplo n.º 2
0
def test_build_path():
    loader = Loader(settings)
    current_path = path.dirname(__file__)
    path_string = path.split(current_path)

    loader.build_path()

    assert loader.data_folder == path_string[0] + "/src/data"
    assert loader.img_folder == path_string[0] + "/src/data/img"
Ejemplo n.º 3
0
def test_from_aspired_model(aspired_models):
    asp_1, asp_2 = aspired_models
    asp_1.load_type = LoadType.local
    l = Loader.from_aspired_model(asp_1,
                                  '{}/data/model_load_dir'.format(dir_path))
    asp_2.load_type = 'TEST'
    with pytest.raises(NotImplementedError):
        l = Loader.from_aspired_model(
            asp_2, '{}/data/model_load_dir'.format(dir_path))
Ejemplo n.º 4
0
class App:
    def __init__(self):
        self._running = True
        self._display_surf = None

    def on_init(self):
        pygame.init()
        self.res = pygame.display.list_modes()[5]
        self._display_surf = pygame.display.set_mode(
            self.res, pygame.HWSURFACE | pygame.DOUBLEBUF)
        self._running = True
        self._loader = Loader(self.res, "resources/level0.json")
        self._level, self._player = self._loader.load()

    def on_event(self, event):
        self._player.on_event(event)
        self._level.on_event(event)
        if event.type == pygame.USEREVENT + 2:
            self._level, self._player = self._loader.load()
        if event.type == pygame.QUIT:
            self._running = False
        if event.type == pygame.KEYDOWN:
            keys = pygame.key.get_pressed()
            if keys[pygame.K_ESCAPE]:
                self._running = False
            # elif keys[pygame.K_s]:
            # 	pygame.mixer.init()
            # 	pygame.mixer.music.load("/Users/Cutie/Movies/backgroundmusic.mp3")

    def on_render(self):
        self._display_surf.fill(consts.BLACK)
        self._level.on_render(self._display_surf)
        self._player.on_render(self._display_surf)
        pygame.display.flip()

    # def on_loop(self):
    #     self._player.on_loop()
    #     self._level.on_loop()

    def on_cleanup(self):
        pygame.quit()

    def on_execute(self):
        if self.on_init() == False:
            self._running = False
        while (self._running):
            for event in pygame.event.get():
                self.on_event(event)
            self.on_render()
        self.on_cleanup()
Ejemplo n.º 5
0
 def __init__(self):
     pg.init()
     pg.mixer.init()
     self.character = self.dt = None
     self.clock = pg.time.Clock()
     with open("settings.yaml") as f:
         self.settings = yaml.load(f)
         f.close()
     self.init_game_window()
     pg.display.set_caption(self.settings["gen"]["title"])
     pg.key.set_repeat(100, 100)
     self.data = Loader(self.settings)
     self.data.build_path()
     self.data.load_data()
     self.hp = self.max_hp = self.settings["player"]["hp"]
     pg.mouse.set_visible(False)
     pg.display.set_icon(self.data.undervoid_icon)
Ejemplo n.º 6
0
    def __init__(self, aspired_model: AspiredModel, model_dir: str = 'data/models'):
        logging.debug('Initialize servable {}'.format(aspired_model.model_name))
        self.model_dir = model_dir
        self.aspired_model = aspired_model
        self.loader = Loader.from_aspired_model(aspired_model=aspired_model, model_dir=model_dir)

        self.meta_data: ServableMetaData = None
        self.model: ModelWrapper = None
        self.status = ServableStatus.NOT_LOADED

        self.update()
Ejemplo n.º 7
0
def test_abstract_methods(aspired_models, file_names):
    asp_1, asp_2 = aspired_models
    l = Loader(asp_1, '{}/data/model_load_dir'.format(dir_path))
    with pytest.raises(NotImplementedError):
        l.load_available_models()
    with pytest.raises(NotImplementedError):
        l.load(file_names[0])
Ejemplo n.º 8
0
    def run(self):
        # TODO: Unncomment for uncompress and move events json file compressed
        # self._uncompress_events()

        # TODO: Unncomment for deleting events json file compressed
        # Delete events json file
        # os.remove(src_gz_file)

        extractor = Extractor(self.src_db_config)
        df_plans = extractor.export_table_to_df(self.table_plans)

        transformer = Transformer()
        df_events = transformer.create_events_info_df_from_file(
            self.src_events)
        df_purchase = transformer.create_purchase_detail_df_from_df(
            df_events, df_plans)

        loader = Loader(db_name='test_fever')

        events_json = df_events.to_dict(orient="records")
        # loader.delete_many(collection_name=self.mongo_db_events, json_query={}) # Test

        try:
            loader.insert_many(collection_name=self.mongo_db_events,
                               json_list=events_json)
        except pymongo.errors.BulkWriteError:
            loader.upsert_many_one_by_one(collection_name=self.mongo_db_events,
                                          json_list=events_json)

        purchase_json = df_purchase.to_dict(orient="records")

        # loader.delete_many(collection_name=self.mongo_db_purchase, json_query={}) # Test
        try:
            loader.insert_many(collection_name=self.mongo_db_purchase,
                               json_list=purchase_json)
        except pymongo.errors.BulkWriteError:
            loader.upsert_many_one_by_one(
                collection_name=self.mongo_db_purchase,
                json_list=purchase_json)
Ejemplo n.º 9
0
 def setUp(self):
     self.loader = Loader(db_uri='mongodb://localhost:27017/',
                          db_name="test_fever_unittest")
     self.coll_purchase = "purchase_detail"
     self.coll_events = "events_info"
Ejemplo n.º 10
0
class TestLoader(unittest.TestCase):
    def setUp(self):
        self.loader = Loader(db_uri='mongodb://localhost:27017/',
                             db_name="test_fever_unittest")
        self.coll_purchase = "purchase_detail"
        self.coll_events = "events_info"

    def tearDown(self):
        self.loader.delete_many(self.coll_purchase, {})
        self.loader.delete_many(self.coll_events, {})

    def test_insert_many_events(self):
        with open('/opt/repos/plan-test/test/out/events.json') as f:
            data = json.load(f)

        self.loader.insert_many(self.coll_events, data)

    def test_insert_many_purchase(self):
        with open('/opt/repos/plan-test/test/out/purchase.json') as f:
            data = json.load(f)

        self.loader.insert_many(self.coll_events, data)

    def test_insert_one(self):
        num_before = self.loader.count_elems(self.coll_events)

        self.loader.insert_one(
            self.coll_events, {
                "city": "MAD",
                "event": "end_app_session",
                "os": "ios",
                "plan_id": "6846",
                "time": 1530057600000,
                "user_id": 611248618,
                "_id": "611248618|nan|2018-06-27 00:00:00|end_app_session|ios"
            })

        num_after = self.loader.count_elems(self.coll_events)

        self.assertEqual(num_after, num_before + 1)
Ejemplo n.º 11
0
def main():
    l = Loader()
    plot_data(l.data, estimate=True)
Ejemplo n.º 12
0
# coding: utf-8
import sys
sys.path.append("../")
from src.program_controller import ProgramController
from src.loader import Loader

controller = ProgramController()
l = Loader()
l.read_mem_values()
controller.pipeline.mem = l.get_mem_x()
controller.pipeline.mem.extend(l.get_mem_y())

controller.pipeline.PC = ["00100000000000100000000000000010",
                          "00100000000001010000001111101000",
                          "00100000000001100001001110001000",
                          "00100000000000010000000000000000",
                          "00100000000001110000000000000100",
                          "10001100101011110000000000000000",
                          "00000001111000100111100000011000",
                          "10001100110100000000000000000000",
                          "00000001111100001000000000100000",
                          "10101100110100000000000000000000",
                          "00100000001000010000000000000001",
                          "00100000101001010000000000000100",
                          "00100000110001100000000000000100",
                          "00011100001001110000000000010100"]
                          

controller.run_clocks_continuously()

Ejemplo n.º 13
0
class Client:
    """
    Client Class
    """
    def __init__(self):
        pg.init()
        pg.mixer.init()
        self.character = self.dt = None
        self.clock = pg.time.Clock()
        with open("settings.yaml") as f:
            self.settings = yaml.load(f)
            f.close()
        self.init_game_window()
        pg.display.set_caption(self.settings["gen"]["title"])
        pg.key.set_repeat(100, 100)
        self.data = Loader(self.settings)
        self.data.build_path()
        self.data.load_data()
        self.hp = self.max_hp = self.settings["player"]["hp"]
        pg.mouse.set_visible(False)
        pg.display.set_icon(self.data.undervoid_icon)

    def init_game_window(self):
        """
        Initializes a centered game window either with windowed resolution or fullscreen.
        """
        environ["SDL_VIDEO_CENTERED"] = "1"
        if self.settings["gen"]["fullscreen"] == "on":
            self.settings["gen"]["width"], self.settings["gen"]["height"] = (
                pg.display.Info().current_w,
                pg.display.Info().current_h,
            )
            self.screen = pg.display.set_mode((0, 0), pg.FULLSCREEN)
        else:
            self.settings["gen"]["width"] = self.settings["gen"]["winres"][
                "width"]
            self.settings["gen"]["height"] = self.settings["gen"]["winres"][
                "height"]
            self.screen = pg.display.set_mode((self.settings["gen"]["width"],
                                               self.settings["gen"]["height"]))

    def draw(self, game):
        """
        Draws the map and all sprites.
        Draws Player health and gold coins.
        """
        pg.display.set_caption("Undervoid")
        self.screen.fill(game.bg_color)
        self.screen.blit(game.map_img, game.camera.apply_rect(game.map_rect))
        # self.draw_grid()
        for sprite in game.sprite_grouping.all_sprites:
            if isinstance(sprite, Mob) and sprite.hp < sprite.max_hp:
                draw_hp(
                    self,
                    sprite.image,
                    0,
                    0,
                    sprite.hp / sprite.max_hp,
                    self.settings["gen"]["tilesize"],
                    int(self.settings["gen"]["tilesize"] / 10),
                    False,
                )
            self.screen.blit(sprite.image, game.camera.apply(sprite))
        draw_hp(
            self,
            self.screen,
            10,
            self.settings["gen"]["height"] - 30,
            game.player.hp / game.player.max_hp,
            200,
            15,
            True,
        )
        draw_score(self, game.player.coins)
        if self.settings["gen"]["displayfps"] == "on":
            draw_fps(self)
        pg.display.flip()

    def events(self):
        """
        Checks for key/mouse presses.
        Checks if the user is quitting the game.
        """
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.quit()
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    self.quit()
                if self.menu.inmenu:
                    self.menu.menu_event(event)

    # Text Renderer https://www.sourcecodester.com/tutorials/python/11784/python-pygame-simple-main-menu-selection.html
    def text_format(self,
                    message: str,
                    textFont: str,
                    textSize: int,
                    textColor=[0, 0, 0]) -> pg.font.Font:
        """
        Returns a pygame text ready to be drawn to screen.
        """
        newFont = pg.font.SysFont(textFont, textSize)
        newText = newFont.render(message, 0, textColor)

        return newText

    def show_start_screen(self):
        """
        Initializes the menus, music, and starts menu loop.
        """
        self.font = "franklingothic"
        pg.mixer.music.load(
            path.join(self.data.music_folder,
                      self.settings["music"]["voidwalk"]))
        if self.settings["gen"]["music"] == "on":
            pg.mixer.music.play(-1, 0.0)
        self.menu = Menu(self.clock, self.screen, self.settings, self.data,
                         self.font, self.character)
        self.character = self.menu.run(self.menu.menu_main)

    def show_go_screen(self):
        """
        This method is used upon player death to restart at the main menu.
        """
        self.show_start_screen()
        g = Game(c.data, c.character)
        self.run(g)

    def run(self, game: Game):
        """
        Game loop; ticks the clock, checks for events, updates game state, draws game state
        """
        if self.settings["gen"]["music"] == "on":
            pg.mixer.music.load(
                path.join(self.data.music_folder,
                          self.settings["music"]["leavinghome"]))
            pg.mixer.music.play(-1, 0.0)

        self.playing = True
        while self.playing:
            # tick_busy_loop() uses more cpu but is more accurate
            self.dt = self.clock.tick_busy_loop(
                self.settings["gen"]["fps"]) / 1000
            self.events()
            game.update(self.dt)
            if game.player.hp <= 0:
                self.playing = False
            self.draw(game)

    def quit(self):
        """
        Quits pygame and exits the program
        """
        pg.quit()
        sys.exit()
Ejemplo n.º 14
0
def main():
    ''' Main function '''
    # Verify API usage settings
    if not USE_API:
        loader = Loader('data/')
    else:
        if len(sys.argv) > 1 and len(sys.argv[1]) > 0:
            loader = Parser(sys.argv[1])
        else:
            loader = Parser(MAL_USERNAME)

    # Load data
    loader.create_document()
    user = loader.get_user_object(include_current=True,
                                  include_onhold=True,
                                  include_dropped=True,
                                  include_planned=True)

    # Retrieve improper tagged entries
    improper_tagged_anime = ', '.join(
        get_improper_tagged(user, list_type='anime'))
    improper_tagged_manga = ', '.join(
        get_improper_tagged(user, list_type='manga'))

    # User data displaying
    print()
    print('- User Data -')
    print('  Username: {}'.format(user.info.user_name))
    print('  User ID: {}'.format(user.info.user_id))
    print()

    # Anime statistics displaying
    if DISPLAY_ANIME_STATS:
        print('- Anime Data -')
        print('  List Data', end='\n  ')
        print('Total: {}'.format(user.anime_list.count('all')), end=' | ')
        print('Watching: {}'.format(user.anime_list.count('watching')),
              end=' | ')
        print('Completed: {}'.format(user.anime_list.count('completed')),
              end=' | ')
        print('On-Hold: {}'.format(user.anime_list.count('on-hold')),
              end=' | ')
        print('Dropped: {}'.format(user.anime_list.count('dropped')),
              end=' | ')
        print('Planned: {}'.format(user.anime_list.count('plan to watch')))
        print()

        if sum(user.anime_list.get_scores()) != 0:
            print('  Scoring Data', end='\n  ')
            print('Total: {}'.format(len(user.anime_list.get_scores())),
                  end=' | ')
            print('Range: {}~{}'.format(user.anime_list.get_min(),
                                        user.anime_list.get_max()),
                  end=' | ')
            print('Average: {:.2f}'.format(user.anime_list.get_average()),
                  end=' | ')
            print('Median: {:g}'.format(user.anime_list.get_median()),
                  end=' | ')
            print('SD: {:.2f}'.format(user.anime_list.get_sd()))
            print()
            print('  Improper Tagged')
            print('  {}'.format(improper_tagged_anime
                                ) if len(improper_tagged_anime) > 0 else
                  '  None, all anime are being tagged properly.')
            print()

    # Manga statistics displaying
    if DISPLAY_MANGA_STATS:
        print('- Manga Data -')
        print('  List Data', end='\n  ')
        print('Total: {}'.format(user.manga_list.count('all')), end=' | ')
        print('Reading: {}'.format(user.manga_list.count('reading')),
              end=' | ')
        print('Completed: {}'.format(user.manga_list.count('completed')),
              end=' | ')
        print('On-Hold: {}'.format(user.manga_list.count('on-hold')),
              end=' | ')
        print('Dropped: {}'.format(user.manga_list.count('dropped')),
              end=' | ')
        print('Planned: {}'.format(user.manga_list.count('plan to read')))
        print()

        if sum(user.manga_list.get_scores()) != 0:
            print('  Scoring Data', end='\n  ')
            print('Total: {}'.format(len(user.manga_list.get_scores())),
                  end=' | ')
            print('Range: {}~{}'.format(user.manga_list.get_min(),
                                        user.manga_list.get_max()),
                  end=' | ')
            print('Average: {:.2f}'.format(user.manga_list.get_average()),
                  end=' | ')
            print('Median: {:g}'.format(user.manga_list.get_median()),
                  end=' | ')
            print('SD: {:.2f}'.format(user.manga_list.get_sd()))
            print()
            print('  Improper Tagged')
            print('  {}'.format(improper_tagged_manga
                                ) if len(improper_tagged_manga) > 0 else
                  '  None, all manga are being tagged properly.')
            print()

    # Render machine initiation
    render_machine = RenderMachine('charts/', style=CHART_STYLE)

    # Render anime charts
    if sum(user.anime_list.get_scores()) != 0:
        # Render anime pie chart
        render_machine.render_pie_chart(
            user.anime_list.get_grouped_list(
                group_by='series_type',
                manual_sort=MANUAL_SORT_ANIME,
                disassemble_key=['my_score', 'series_title']),
            title='{}\'{} Anime Series Types'.format(
                user.info.user_name, 's' * (user.info.user_name[-1] != 's')),
            file_name='anime_series_types')

        # Render anime bar charts
        render_machine.render_bar_chart(
            user.anime_list.get_summed_scores(),
            title='{}\'{} Scored Anime Titles'.format(
                user.info.user_name, 's' * (user.info.user_name[-1] != 's')),
            file_name='anime_scored')
        render_machine.render_bar_chart(
            user.anime_list.get_summed_grouped_scores(
                group_by='series_type', manual_sort=MANUAL_SORT_ANIME),
            title='{}\'{} Scored Anime Titles (By Series Type)'.format(
                user.info.user_name, 's' * (user.info.user_name[-1] != 's')),
            file_name='anime_scored_by_series_type')

        # Render anime treemap chart
        render_machine.render_treemap(
            user.anime_list.get_grouped_list(
                group_by='series_type',
                manual_sort=MANUAL_SORT_ANIME,
                disassemble_key=['my_score', 'series_title']),
            title='{}\'{} Scored Anime Treemap'.format(
                user.info.user_name, 's' * (user.info.user_name[-1] != 's')),
            file_name='anime_treemap')

    # Render manga chart
    if sum(user.manga_list.get_scores()) != 0:
        # Render manga bar chart
        render_machine.render_bar_chart(
            user.manga_list.get_summed_scores(),
            title='{}\'{} Scored Manga Titles'.format(
                user.info.user_name, 's' * (user.info.user_name[-1] != 's')),
            file_name='manga_scored')

    # Auto-open charts
    if ENABLE_AUTO_CHART_OPEN:
        try:
            if platform.system() == 'Windows':
                notice(
                    'Opening chart files automatically is unsupported on Windows.'
                )
            else:
                os.system('open charts/*')
                notice('Opening chart files.')
        except (FileNotFoundError, OSError, PermissionError):
            error('Something unexpected happened, please try again.')

    # Windows' cmd line fix
    if platform.system() != 'Windows':
        print()
Ejemplo n.º 15
0
def test_loader_dir_not_found(aspired_models):
    for aspired_model in aspired_models:
        with pytest.raises(NotADirectoryError):
            l = Loader(aspired_model, 'not/existing/dir')