def main():

    config = Config()
    storage = Storage()
    graphic = Graphic(config.get("courses"))
    graphic_cfg = config.get("graphic")
    all_params = get_graphic_params(graphic_cfg)
    courses = list()
    seen_courses = list()

    for params in all_params:
        if params[1] == 1:
            weeks = graphic.weeks(params[0], params[1], params[2])

            for week in weeks:
                new_courses = graphic.courses(week)
                for new_course in new_courses:
                    check_new_course = new_course['start_date'].strftime("%d%m%Y%H") + '-' + new_course['end_date'].strftime("%d%m%Y%H") + '-' +  new_course['course_name']
                    if check_new_course not in seen_courses:
                        seen_courses.append(check_new_course)
                        courses.append(new_course)
        else:
            distance_learning_weeks = graphic.distance_learning_weeks(params[0], params[1], params[2])

            for week in distance_learning_weeks:
                new_courses = graphic.distance_learning_courses(week)
                for new_course in new_courses['courses']:
                    check_new_course = new_course['start_date'].strftime("%d%m%Y%H") + '-' + new_course['end_date'].strftime("%d%m%Y%H") + '-' +  new_course['course_name']
                    if check_new_course not in seen_courses:
                        seen_courses.append(check_new_course)
                        courses.append(new_course)

    storage.save(courses)
    print_actions(storage.get_actions())
    print('Calendar sync finished.')
Beispiel #2
0
 def new_state(self, state):
     self.state.set_state(state)
     if state == State.STATE_GAME_BATTLE:
         self.player.velocity = [0, 0]
         self.player.graphic.graphics = [self.graphics.player_idle]
         self.player.graphic.times = [1]
         self.player.position = (
             ((self.screen_width / self.sprite_width) / 2) *
             self.sprite_width, self.screen_height - self.sprite_height)
         self.player.floor += 1
         self.turn_counter.enemies = [
             Enemy(self, ((self.screen_width / 2) -
                          (self.sprite_width / 2), self.sprite_height),
                   (32, 32), 100, 50,
                   Graphic([self.graphics.enemy_bug_1], [0]))
         ]
         for e in self.turn_counter.enemies:
             self.game_objects[State.STATE_GAME_BATTLE].append(e)
     if state == State.STATE_GAME_CLIMB:
         if self.player.floor > 1:
             self.background.graphic.graphics[
                 0] = self.graphics.background_blank
         else:
             self.background.graphic.graphics[0] = self.graphics.background
         self.ladder.__init__(self,
                              int(self.screen_width / self.sprite_width),
                              int(self.screen_height / self.sprite_height),
                              (0, 0))
         self.player.set_health(100)
         self.player.previous_rung = (0, 0)
         self.player.velocity = (0, 0)
         self.player.position = (
             ((self.screen_width / self.sprite_width) / 2) *
             self.sprite_width, self.screen_height - self.sprite_height)
Beispiel #3
0
 def set_graphic(self,svg):
     """Sets the SVG graphic that is used in the plot. Returns None."""
     self.graphic = Graphic(svg,plot=self)
     if self.graphic.get_height() > self.get_available_height():
         self.graphic = None
         raise SizeError("The height (%s) of this graphic is too large to fit on the material (%s)." %(self.graphic.get_height(),self.get_available_height()))
     elif self.graphic.get_width() > self.get_available_width():
         self.graphic = None
         raise SizeError("The width (%s) of this graphic is too large to fit on the material (%s)." %(self.graphic.get_width(),self.get_available_width()))
     self.update()
Beispiel #4
0
def main():
    setting = Setting()
    npuzzle = NPuzzle(setting)
    if setting.graphic and setting.size < 9:
        Graphic(npuzzle)
    elif setting.graphic and setting.size >= 9:
        print("The puzzle size is too big for graphic mode, "
              "switching to normal mode")
        npuzzle.report()
    else:
        npuzzle.report()
Beispiel #5
0
    def start(self):
        """Iterate over generations and print them."""

        if self.console_display:
            while self.generation_counter <= self.max_gen:
                self._console_display()
                self.next_generation()

        else:
            graphic = Graphic(self)
            graphic.main_loop()
Beispiel #6
0
def main():
    g = Graphic()
    game = Game(g)
    game.display_instruct()
    enemy = game.ask_who_is_enemy()
    player1 = game.get_human_player()
    player2 = None
    if enemy == Players.human:
        player2 = game.get_human_player()
    elif enemy == Players.comp:
        player2 = game.get_computer_player()
    player1.setup_ships()
    player2.setup_ships()
    game.begin(player1, player2)
Beispiel #7
0
 def __init__(self,
              game,
              position,
              size,
              armour=100,
              health=100,
              graphic=False):
     super().__init__(game, position, size, graphic)
     self.armour = armour
     self.health = health
     self.weapon = 5
     self.alive = True
     self.choices = [self.attack, self.defend]
     self.weights = [0.9, 0.1]
     self.defending = False
     self.armour_image = Graphic([self.game.graphics.enemy_armour], [0])
Beispiel #8
0
    def run(self):
        """ Converts an SVG into HPGL. """

        # Set initial HPGL commands
        hpgl = ['IN', 'SP1']
        hpgl.extend(self.commands['send_before'])

        if self.device['cutting_force'][1]:
            hpgl.append('FS%d' % self.device['cutting_force'][0])

        if self.device['cutting_speed'][1]:
            hpgl.append('VS%d' % self.device['cutting_speed'][0])

        # Read the input SVG into a Graphic to provide easy manipulation.
        g = Graphic(self.input)
        g.set_rotation(self.device['axis_rotation'])
        g.set_scale(self.device['axis_scale'][0] * HPGL_SCALE,
                    self.device['axis_scale'][1] * HPGL_SCALE)
        g.set_position(self.device['axis_translate'][0],
                       self.device['axis_translate'][1])

        # Create the HPGL data
        paths = g.get_polyline()

        # Apply device specific settings
        if self.device['cutting_overlap'][1]:
            Plugin.apply_cutting_overlap(paths,
                                         self.device['cutting_overlap'][0])
        if self.device['cutting_blade_offset'][1]:
            Plugin.apply_cutting_blade_offset(
                paths, self.device['cutting_blade_offset'][0])

        data = []
        for path in paths:
            x, y = path.pop(0)[1]
            data.append('PU%i,%i' % (round(x), round(y)))
            cmd = "PD"
            for line in path:
                x, y = line[1]
                cmd += '%i,%i,' % (round(x), round(y))
            data.append(cmd[:-1])

        hpgl.extend(data)
        hpgl.extend(self.commands['send_after'])

        # Not friendly for large files!
        self.output = ";\n".join(hpgl) + ";"
Beispiel #9
0
 def set_graphic(self, svg):
     """Sets the SVG graphic that is used in the plot. Returns False."""
     self.graphic = Graphic(svg, plot=self)
     if self.graphic.get_height() > self.get_available_height():
         h1, h2 = self.graphic.get_height(), self.get_available_height()
         self.graphic = None
         raise Exception(
             "The height (%s) of this graphic is too large to fit on the material (%s). \n Please resize the graphic or choose a new material."
             % (h1, h2))
     elif self.graphic.get_width() > self.get_available_width():
         w1, w2 = self.graphic.get_width(), self.get_available_width()
         self.graphic = None
         raise Exception(
             "The width (%s) of this graphic is too large to fit on the material (%s). \n Please resize the graphic or choose a new material."
             % (w1, w2))
     self.update()
     return False
Beispiel #10
0
    def play_game(self, snake, food, button_direction, score, screen, clock):
        """Launch the snake game.

        Parameters
        ----------
        snake : tuple[int]
            The snake coordinates.
        food : tuple[int]
            The food coordinates.
        button_direction : int
            The direction the snake will follow.
        score : int
            The score value.
        screen : type
            The scene.
        clock : int
            The speed of the snake.

        Returns
        -------
        snake: tuple[int]
            The snake's coordinates.
        food: tuple[int]
            The food's coordinates.
        score: int
            The updated score value.

        """

        gr = Graphic(scene_width=self.width, scene_height=self.height,
                     info_zone=self.info_zone, block=self.block,
                     bg_color=self.bg, food_color=self.pink,
                     wall_color=self.black, snake_color=self.blue)
        alive = True
        while alive:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    alive = False
            scene = gr.draw_scene(scene=screen, score=score)
            gr.draw_food(scene=scene, food=food)
            snake, food, score = self.move(
                snake, food, button_direction, score)
            scene = gr.draw_snake(scene=scene, snake=snake)
            pygame.display.update()
            pygame.time.Clock().tick(clock)
            return snake, food, score
Beispiel #11
0
def main(type='console', path='results/all_print.txt'):
    if type != 'console':
        orig_stdout = sys.stdout
        f = open(path, 'w')
        sys.stdout = f

    stat = Statistic()
    stat.load_data("data.txt")
    # print(stat.get_data())

    gr = Graphic()
    gr.build_hist_and_emp(stat.get_data())
    print(
        "Гистограмма и график эмпирической функции распределения построены.\n")

    print("Среднее значение выборки: %.3f" %
          (stat.find_average_sample_value()))
    print("Выборочная дисперсия: %.3f" % (stat.find_selective_dispersion()))
    print("Стандартная ошибка: %.3f" % (stat.find_standard_error()))
    print("Мода: ", stat.find_mode())
    print("Медиана: ", stat.find_median())
    print("Квартили: ", (stat.find_quartiles()))
    q1, q2, q3 = stat.find_quartiles()
    gr.build_box_plot(stat.get_data(), q1, q2, q3, stat.find_min(),
                      stat.find_max())
    print("Ящик с усами построен. ")
    print("Стандартное отклонени: %.3f" % (stat.find_standard_deviation()))
    print("Эксцесс: %.3f" % (stat.find_kurtosis()))
    print("Асимметричность: %.3f (%s)" % (stat.find_skewness()))
    print("Минимум: ", (stat.find_min()))
    print("Максимум: ", (stat.find_max()))

    print("\nПроверка гипотезы H_0:")
    stat.pearson_criterion()

    print("\nДоверительный интервал матожидания: (%.3f; %.3f)" %
          (stat.expected_value_interval()))
    print("\nДоверительный интервал среднеквадратичного "
          "отклонения: (%.3f; %.3f)" % (stat.standard_deviation_interval()))

    if type != 'console':
        sys.stdout = orig_stdout
        f.close()
Beispiel #12
0
    def __init__(self, root):
        self.root = root
        self.g = Graphic(self.root)

        # 落下判定用のメンバ変数を初期化
        self.fall_count = 0
        self.speed = self.DEFAULT_FALL_SPEED
        self.speed_backup = self.DEFAULT_FALL_SPEED
        self.speed_up_count = 0

        # ぷよ動作のキーイベントを設定
        self.key_events = (
            # (key, event)
            ('Left', self.left_move),
            ('Right', self.right_move),
            ('6', self.rolling_right),
            ('4', self.rolling_left),
        )
        self.start_key = 'Return'  # Enterキーでゲームスタート
        self.restart_key = 'r'  # Rキーでりスタート
Beispiel #13
0
 def __init__(self, game, position, graphic=False):
     g = graphic
     if not g:
         g = Graphic([game.graphics.rung], [0])
     super().__init__(game, position, graphic=g)
Beispiel #14
0
 def __init__(self, game, position):
     super().__init__(game, position,
                      Graphic([game.graphics.rung_upgrade_station], [0]))
Beispiel #15
0
 def collect(self):
     self.collected = True
     self.graphic = Graphic([self.game.graphics.rung], [0])
Beispiel #16
0
 def __init__(self, game, position):
     super().__init__(game, position,
                      Graphic([game.graphics.rung_packet], [0]))
     self.collected = False
Beispiel #17
0
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode(
            (self.screen_width * self.screen_scale,
             self.screen_height * self.screen_scale))
        pygame.display.set_caption("InfoWest Tower Security")
        self.clock = pygame.time.Clock()
        self.graphics = Graphics()
        self.canvas = Canvas(self)

        self.timer = Timer()

        self.turn_counter = TurnCounter()
        self.game_objects[State.STATE_GAME_BATTLE].append(self.turn_counter)

        # === Game Objects ===
        self.title_screen = Object(self, (0, 0), self.screen_size,
                                   Graphic([self.graphics.title_screen], [0]))
        self.background = Object(self, (0, 0), self.screen_size,
                                 Graphic([self.graphics.background], [0]))
        self.player = Player(
            self,
            (((self.screen_width / self.sprite_width) / 2) * self.sprite_width,
             self.screen_height - self.sprite_height), (32, 32),
            Graphic([
                self.graphics.player_walk_0, self.graphics.player_walk_1,
                self.graphics.player_walk_2
            ], [10, 10, 10]))
        self.heart = Object(self, (self.screen_width - 18, 2), (16, 16),
                            Graphic([self.graphics.heart_full], [0]))
        self.heart_bar = Object(self, (self.screen_width - 14, 22), (8, 38),
                                color=(250, 15, 15))
        self.armour = Object(self, (self.screen_width - 18, 64), (16, 16),
                             Graphic([self.graphics.armour], [0]))
        self.armour_bar = Object(self, (self.screen_width - 14, 84), (8, 38),
                                 color=(100, 100, 100))
        self.ladder = Ladder(self, int(self.screen_width / self.sprite_width),
                             int(self.screen_height / self.sprite_height),
                             (0, 0))
        self.game_over = Object(self, (0, 0), self.screen_size,
                                Graphic([self.graphics.game_over], [0]))
        self.game_objects[State.STATE_GAME_MENU].append(self.title_screen)
        self.game_objects[State.STATE_GAME_CLIMB].append(self.background)
        for i in range(7):
            cloudtype = randint(0, 2)
            types = [
                self.graphics.cloud_1, self.graphics.cloud_2,
                self.graphics.cloud_3
            ]
            cloud = Object(self, (randint(
                0, self.screen_width), randint(0, self.screen_height - 75)),
                           (24, 24), Graphic([types[cloudtype]], [0]))
            cloud.set_velocity(random.uniform(1, 1.5), 0)
            self.clouds.append(cloud)
            self.game_objects[State.STATE_GAME_CLIMB].append(cloud)

        self.game_objects[State.STATE_GAME_CLIMB].append(self.player)
        self.game_objects[State.STATE_GAME_CLIMB].append(self.heart)
        self.game_objects[State.STATE_GAME_CLIMB].append(self.heart_bar)
        self.game_objects[State.STATE_GAME_CLIMB].append(self.armour)
        self.game_objects[State.STATE_GAME_CLIMB].append(self.armour_bar)
        self.game_objects[State.STATE_GAME_BATTLE].append(self.background)
        self.game_objects[State.STATE_GAME_BATTLE].append(self.player)
        self.game_objects[State.STATE_GAME_BATTLE].append(self.heart_bar)
        self.game_objects[State.STATE_GAME_BATTLE].append(self.heart)
        self.game_objects[State.STATE_GAME_BATTLE].append(self.armour)
        self.game_objects[State.STATE_GAME_BATTLE].append(self.armour_bar)
        self.game_objects[State.STATE_GAME_OVER].append(self.game_over)
        self.game_objects[State.STATE_GAME_CLIMB].append(self.ladder)

        timer_lengths = []
        for i in range(self.timer.max):
            timer_lengths.append(self.timer.max / 8)
        self.action_timer = ActionTimer(
            self, (0, 0), self.sprite_size,
            Graphic([self.graphics.timer_face], [0]),
            Graphic([
                self.graphics.timer_needle_n, self.graphics.timer_needle_ne,
                self.graphics.timer_needle_e, self.graphics.timer_needle_se,
                self.graphics.timer_needle_s, self.graphics.timer_needle_sw,
                self.graphics.timer_needle_w, self.graphics.timer_needle_nw
            ], timer_lengths))
        self.game_objects[State.STATE_GAME_CLIMB].append(self.action_timer)

        self.menu_battle = Menu(self, (0, self.screen_height),
                                ["Attack", "Defend", "Item"],
                                pointer=Graphic([self.graphics.menu_arrow],
                                                [0]))
        self.game_objects[State.STATE_GAME_BATTLE].append(self.menu_battle)

        self.game_objects[State.STATE_GAME_CLIMB].append(self.player)
        self.game_objects[State.STATE_GAME_BATTLE].append(self.player)

        self.floor_text = Text(self, (4, self.screen_height - 28),
                               str(self.player.floor), 24, (255, 255, 255))
        self.game_objects[State.STATE_GAME_CLIMB].append(self.floor_text)
Beispiel #18
0
    block = 20
    pink = (171, 54, 81)
    blue = (106, 133, 164)
    screen = pygame.display.set_mode((width, height))
    # Create snake
    sn = Snake(width=width, height=height, block=block)
    x_snake, y_snake = sn.get_random_location()
    snake = [(x_snake, y_snake)]
    direction = 'right'
    eaten = True
    while True:
        # Draw scene
        gr = Graphic(scene_width=width,
                     scene_height=height,
                     block=block,
                     bg_color=bg,
                     food_color=pink,
                     wall_color=black,
                     snake_color=blue)

        scene = gr.draw_scene(scene=screen)
        if eaten:
            x_food = random.randint(3 * block, width - 2 * block)
            y_food = random.randint(3 * block, height - 2 * block)
            x_food = block * round(x_food / block)
            y_food = block * round(y_food / block)
            food = (x_food, y_food)
            eaten = False
        gr.draw_food(scene=scene, food=food)
        # time.sleep(3)
        keys_pressed = pygame.event.get()
Beispiel #19
0
 def __init__(self, width, height):
     self._g = Graphic(width, height)
     self._components = list()
Beispiel #20
0
 def __init__(self, url, chart_id):
     self.url = url
     self.chart_id = chart_id
     self.axes = Axes()
     self.graphics = Graphic()
     self.layout = Layout()
Beispiel #21
0
 def game_restart(self, event):
     self.root.unbind_all('<Key-' + self.restart_key + '>')
     self.root.bind_all('<Key-' + self.start_key + '>', self.game_start)
     self.g = Graphic(self.root)
Beispiel #22
0
                counter += 1
                (a, s) = r
                print('[' + str(counter) + '] ' + '{0:.2f}'.format(a) + ' ' +
                      s)

            save(Result(args['layoutName'], cars), args['save'])
        else:
            mapLayout = args['layout']
            gene = Gene(mapLayout.getTrafficLights())
            geneInfo = GeneInfo(gene)
            carmap = CarMap(mapLayout, geneInfo)
            cars = randomStartEndPoint(args['number'])
            carmap = CarMap(mapLayout, geneInfo)
            simulation = Simulation(cars, carmap)

            app = Graphic(mapLayout.mapInfo, carmap.cars, carmap.trafficlights,
                          args['size'])
            start_new_thread(run, ())
            app.run()

    else:
        r = load(args['load'])
        mapLayout = getLayout(r.layout)
        geneStr = raw_input('Input Gene String: ')
        gene = Gene(mapLayout.getTrafficLights(), False, geneStr)
        geneInfo = GeneInfo(gene)
        carmap = CarMap(mapLayout, geneInfo)
        cars = r.cars
        simulation = Simulation(cars, carmap)

        if args['display'] is True:
            app = Graphic(mapLayout.mapInfo, carmap.cars, carmap.trafficlights,
Beispiel #23
0
# __author__ = Liu bn
# 2018/8/20

import make_tree as mt
from graphic import Graphic

ltt = mt.get_tree("call.txt")
graph = {0: Graphic(ltt[1]).join_funcs()}

depth = sorted(ltt.keys())[-1]
i = 1

width = len(graph[0][2])
logic_path = {
    0: lambda x, y: x[0],
    1: Graphic.join_block,
}
sep = "   "
while i <= depth:
    gr_list = []
    for n in ltt[i]:
        if n.son_list:
            gr_list.append(Graphic(n.son_list).join_funcs())
    if gr_list:
        w = logic_path[0 if len(gr_list) == 0 else 1](gr_list, sep)
        graph[i] = w
        if width < len(w[0]):
            width = len(w[0])
    print(width)
    i += 1
Beispiel #24
0
 def __init__(self, game, position):
     super().__init__(game, position,
                      Graphic([game.graphics.rung_frozen], [0]))
Beispiel #25
0
    def update(self):
        """
        Builds the plot from the graphic. Uses all the current properties.
        Raises exceptions if it cannot create the plot given the current
        values. This needs done whenever a property of self.graphic is changed.
        """
        # Check that there is enough room to fit all the copies.
        copies_left = self.get_copies()
        fit_x, fit_y = [self.get_stack_size_x(), self.get_stack_size_y()]
        rotate = False
        if fit_x * fit_y < copies_left:
            if self.get_auto_rotate():
                fit_x, fit_y = [
                    self.get_stack_size_x(rotate=True),
                    self.get_stack_size_y(rotate=True)
                ]
            if fit_x * fit_y < copies_left:
                raise Exception(
                    "%s graphics are to be made but only %s will fit on the current material. Please adjust settings and try again."
                    % (copies_left, fit_x * fit_y))
            else:
                rotate = True  # This should only be set if the only way for it to fit is to rotate!

        # ==================== Generate the list of graphic positions, note that these are absolute.================================
        # positions, not relative to the plot padding like plot.set_position().
        x, y = self.get_position(absolute=True)

        if self.get_weedline_status(
        ):  # If plot weedlines are enabled, we have to shift the graphics so the weedline fits.
            x += self.get_weedline_padding()
            y += self.get_weedline_padding()

        if rotate: self.graphic.set_rotation(90)  # 90 should be a variable!
        dx, dy = self.graphic.get_width() + self.get_spacing(
        )[0], self.graphic.get_height() + self.get_spacing()[1]
        positions = []
        if self.get_rotation() == 90:  # Stack in positive x direction.
            while copies_left >= fit_y:
                for i in range(0, fit_y):  # Fill a vertical stack.
                    positions.append([x, i * dy + y])
                # Add a new stack.
                x += dx
                copies_left -= fit_y

            # Fill leftover copies.
            for i in range(0, copies_left):
                positions.append([x, i * dy + y])

        else:  # Stack in positive y direction.
            while copies_left >= fit_x:
                for i in range(0, fit_x):  # Fill a horizontal stack.
                    positions.append([i * dx + x, y])
                # Add a new stack.
                y += dy
                copies_left -= fit_x

            # Fill leftover copies.
            for i in range(0, copies_left):
                positions.append([i * dx + x, y])

        # ==================== Create the plot from the given graphic positions ================================
        len_data = len(self._data) - (self.get_weedline_status() and 1 or 0)
        if self.graphic.get_changed_flag() or len(
                self._data) == 0 or len_data != len(
                    positions):  # Only make new copies if the graphic changed
            self._data = []
            # Bugfix
            self.graphic._plot = None
            for pos in positions:
                x, y = pos
                g = deepcopy(self.graphic)
                g.set_position(x, y)
                self._data.append(g)
            self.graphic._plot = self

        else:  # Just reposition the current data.  This should skip the weedline if it's enabled.
            for pos, g in zip(positions, self._data):
                x, y = pos
                g.set_position(x, y)
        if len(
                self._data
        ) == self.get_copies() + 1:  # weedlines were previously enabled!
            self._data.pop()

        if self.get_weedline_status():  # add it to the data
            minx, maxx, miny, maxy = self.get_bounding_box()
            p = self.get_weedline_padding()
            d = "M%f,%f V%f H%f V%f Z" % (minx - p, miny - p, maxy + p,
                                          maxx + p, miny - p)
            svg = etree.fromstring(SVG)
            path = etree.Element('path')
            path.set('d', d)
            svg.append(path)
            g = Graphic(etree.tostring(svg))
            self._data.append(g)
Beispiel #26
0
from graphic import Graphic
import start

if __name__ == '__main__':
    a = float(input("Введите тепловой коэффициент: "))
    start_u = start.get()
    print(start_u)
    Graphic(a, start_u).get()