Esempio n. 1
0
class Effects(pygame.sprite.Sprite):
    BLOOD_F1 = load_image('blood_f1.png')
    BLOOD_F2 = load_image('blood_f2.png')

    def __init__(self, x, y):
        super(Effects, self).__init__()

        self.images = ([self.BLOOD_F1] * (FPS / 15)) + ([self.BLOOD_F2] *
                                                        (FPS / 15))
        self.rect = self.images[0].get_rect(centerx=x, centery=y)
        self.frame_count = 0
        self.simply_gravity = 0

    def update(self):
        self.simply_gravity += 1
        self.image = self.images[self.frame_count % len(self.images)]
        self.frame_count += 1
        self.rect.move_ip(0, self.simply_gravity)

    def alive(self):  # ;))
        if self.frame_count > len(self.images):
            return False
        return True

    def draw(self, surface):
        surface.blit(self.image, self.rect)
Esempio n. 2
0
class Spider(CommonSpider):
    IMG_1 = load_image('spider_f1.png')
    IMG_2 = load_image('spider_f2.png')
    IMG_DEAD = load_image('spider_dead.png')

    def __init__(self):
        super(Spider, self).__init__(self.IMG_1, self.IMG_2, self.IMG_DEAD)
Esempio n. 3
0
class Fish(pygame.sprite.Sprite):
    image = load_image('good_fish.png')
    bomb_image = load_image('bomb_fish.png')

    def __init__(self, group, is_bomb):
        self.timer = 0

        super().__init__(group)
        self.is_bomb = is_bomb
        if is_bomb:
            self.image = Fish.bomb_image
        else:
            self.image = Fish.image
        self.rect = self.image.get_rect()
        self.rect.x = width
        self.rect.y = height

    def show(self):
        self.rect.x = width // 2 - 50
        self.rect.y = height // 2 - 50

    def hide(self):
        self.rect.x = width
        self.rect.y = height

    def update(self):
        pass
Esempio n. 4
0
def train():

    Dt1_train_dir = "/media/wutong/New Volume/reseach/Dataset/OU-ISIR_by_Setoguchi/Gallery/signed/128_3ch/CV01_(Gallery&Probe)_2nd"

    train1 = load_image(path_dir=Dt1_train_dir, mode=True)

    Dt2_train_dir = "/media/wutong/New Volume/reseach/Dataset/OU-ISIR_by_Setoguchi/Gallery/signed/128_3ch/CV01_Dt2_(Gallery&Probe)"
    train2 = load_image(path_dir=Dt2_train_dir, mode=True)

    model = Multi_modal_GEINet()

    model.to_gpu()

    Dt1_train_iter = iterators.SerialIterator(train1,
                                              batch_size=239,
                                              shuffle=False)
    Dt2_train_iter = iterators.SerialIterator(train2,
                                              batch_size=239,
                                              shuffle=False)

    optimizer = chainer.optimizers.MomentumSGD(lr=0.02, momentum=0.9)
    optimizer.setup(model)
    optimizer.add_hook(chainer.optimizer.WeightDecay(0.01))

    # updater = training.ParallelUpdater(train_iter, optimizer, devices={'main': 0, 'second': 1})
    updater = Multi_modal_Updater(model,
                                  Dt1_train_iter,
                                  Dt2_train_iter,
                                  optimizer,
                                  device=0)
    epoch = 6250

    trainer = training.Trainer(
        updater, (epoch, 'epoch'),
        out='/home/wutong/Setoguchi/chainer_files/result')

    # trainer.extend(extensions.Evaluator(test_iter, model, device=0))
    trainer.extend(extensions.ExponentialShift(attr='lr', rate=0.56234),
                   trigger=(1250, 'epoch'))
    trainer.extend(
        extensions.LogReport(log_name='SFDEI_log', trigger=(50, "epoch")))
    trainer.extend(extensions.snapshot(), trigger=(1250, 'epoch'))
    trainer.extend(extensions.snapshot_object(
        target=model, filename='model_snapshot_{.updater.epoch}'),
                   trigger=(1250, 'epoch'))
    trainer.extend(extensions.PrintReport(['epoch', 'accuracy', 'loss']))
    # 'validation/main/accuracy']),
    # trigger=(1, "epoch"))
    trainer.extend(
        extensions.dump_graph(root_name="loss", out_name="multi_modal.dot"))
    trainer.extend(extensions.PlotReport(["loss"]), trigger=(20, 'epoch'))
    trainer.extend(extensions.ProgressBar())

    # Run the trainer
    trainer.run()
Esempio n. 5
0
def build_model():

    if os.path.exists(UUID_PRFIX):
        shutil.rmtree(UUID_PRFIX)
    os.makedirs(UUID_PRFIX)
    if os.path.exists(CHECKPOINT_DIR):
        shutil.rmtree(CHECKPOINT_DIR)
    os.makedirs(CHECKPOINT_DIR)
    if os.path.exists(OUTPUT_DIR):
        shutil.rmtree(OUTPUT_DIR)
    os.makedirs(OUTPUT_DIR)
    if os.path.isfile(LOG_PATH):
        os.remove(LOG_PATH)
    with open(LOG_PATH, 'w') as f:
        pass

    # Check directory path
    if not os.path.isdir(CHECKPOINT_DIR):
        raise ValueError(CHECKPOINT_DIR + " doesn't exist.")
    if not os.path.isdir(OUTPUT_DIR):
        raise ValueError(OUTPUT_DIR + " doesn't exist.")
    if not os.path.isdir(DATA_PATH):
        raise ValueError(DATA_PATH + " doesn't exist.")

    # Check file path
    if not os.path.exists(VGG_PATH):
        raise ValueError(VGG_PATH + " doesn't exist.")
    if not os.path.exists(VGG_PATH):
        raise ValueError(STYLE_PATH + " doesn't exist.")
    if not os.path.exists(TEST_PATH):
        raise ValueError(TEST_PATH + " doesn't exist.")

    style_image = load_image(STYLE_PATH)
    test_image = load_image(TEST_PATH, (256, 256))

    # https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory
    files = []
    for (dirpath, dirnames, filenames) in os.walk(DATA_PATH):
        files.extend(filenames)
        break
    files = [os.path.join(DATA_PATH, x) for x in files]

    new_style = Style(content_images=files,
                      style_image=style_image,
                      content_weight=7.5,
                      style_weight=100,
                      denoise_weight=100,
                      vgg_path=VGG_PATH,
                      ck_dir=CHECKPOINT_DIR,
                      test_image=test_image,
                      test_out_dir=OUTPUT_DIR,
                      log_path=LOG_PATH,
                      batch_size=32,
                      alpha=1e-3)
    new_style.train()
Esempio n. 6
0
class Tarantula(CommonSpider):
    IMG_1 = load_image('tarantula_f1.png')
    IMG_2 = load_image('tarantula_f2.png')
    IMG_DEAD = load_image('tarantula_dead.png')

    def __init__(self):
        super(Tarantula, self).__init__(self.IMG_1,
                                        self.IMG_2,
                                        self.IMG_DEAD,
                                        health=5)

    def update(self, level):
        self.image = self.images[self.frame_count % FPS]
        self.frame_count += 1
        self.rect.move_ip(0, random.randint(-int(math.log(level, 4)) - 1, 0))
Esempio n. 7
0
class WailingWidow(CommonSpider):
    IMG_1 = load_image('wailing_widow_f1.png')
    IMG_2 = load_image('wailing_widow_f2.png')
    IMG_DEAD = load_image('wailing_widow_dead.png')

    def __init__(self):
        super(WailingWidow, self).__init__(self.IMG_1,
                                           self.IMG_2,
                                           self.IMG_DEAD,
                                           health=35)

    def update(self, level):
        self.image = self.images[self.frame_count % FPS]
        self.frame_count += 1
        self.rect.move_ip(0, random.randint(-int(math.log(level, 5)) - 1, 0))
Esempio n. 8
0
class PoisonSpider(CommonSpider):
    IMG_1 = load_image('poison_spider_f1.png')
    IMG_2 = load_image('poison_spider_f2.png')
    IMG_DEAD = load_image('poison_spider_dead.png')

    def __init__(self):
        super(PoisonSpider, self).__init__(self.IMG_1,
                                           self.IMG_2,
                                           self.IMG_DEAD,
                                           health=2)

    def update(self, level):
        self.image = self.images[self.frame_count % FPS]
        self.frame_count += 1
        self.rect.move_ip(0, random.randint(-int(math.log(level, 5)) - 1, 0))
Esempio n. 9
0
 def __init__(self, gb, sprpos, cell):
     #static data for game mechanics
     self.__GAMEBOARD = gb # pointer to the game board to ask for services such as "find me a creep to attack" 
     self.__MAXHP = config_get_tower_hp()
     self.__ATK = config_get_tower_atk()
     self.__ATK_RANGE = config_get_tower_atk_range() #range at which tower can attack creep
     self.__MVT_RANGE =  config_get_tower_mvt_range() #range at which tower can move (2 means it can potentially jump over a creep) 
     self.__MVT_COOLDOWN = config_get_tower_mvt_cooldown() #cooldown before tower can move again, in frames
     #dynamic data (status)
     self.__hp = self.__MAXHP
     self.__atk_cooldown_tick = config_get_tower_atk_cooldown() #at the beginning it can not attack
     self.__atk_anim_tick = config_get_tower_atk_anim_duration() #initialized at animduration and decreased each tick. when == 0, tower actually attacks
     # towers actually inflicts dmg every (atkcooldown + atkanimation) frames
     self.__mvt_cooldown_tick = self.__MVT_COOLDOWN #when towers are created, player has to wait before towers can be moved
     self.__current_cell = cell
     self.__target = None
     #__SPRITE
     self.__SPRITE = pygame.sprite.Sprite()   
     self.__SPRITE.image, self.__SPRITE.rect = load_image(config_get_tower_sprite(), 
                                                          (int(self.__GAMEBOARD.get_cell_width()*config_get_tower_sprite_scale()),
                                                          int(self.__GAMEBOARD.get_cell_height()*config_get_tower_sprite_scale()))
                                                          )
     self.__padding = (1 - config_get_tower_sprite_scale()) / 2
     self.__SPRITE.rect.topleft = int(sprpos[0] + self.__GAMEBOARD.get_cell_width()*self.__padding), int(sprpos[1] + self.__GAMEBOARD.get_cell_height()*self.__padding) 
     #if spritescale = 0.8, then padding should be (1-0.8)/2 = 0.1 on top and bottom, and 0.1 on left and right 
     #so that the spr is centered in the middle of the cell
     return 
Esempio n. 10
0
 def __init__(self, type, pos=(0, 0)):
     super().__init__()
     self.image = load_image(type)
     self.rect = self.image.get_rect()
     self.square = True
     if self.rect.height != self.rect.width:
         self.square = False
Esempio n. 11
0
def transfer(reserve=False):
    if not os.path.isfile(CONTENT_PATH):
        raise ValueError(CONTENT_PATH + " doesn't exist.")

    content_image = load_image(CONTENT_PATH)
    neural_transfer.transfer(content_image=content_image,
                             output_path=GENRD_PATH,
                             model_path=MODEL_PATH,
                             reserve_color=reserve)
Esempio n. 12
0
    def train(self):
        target_grams = _target_grams(self.vgg_path, self.st_image)

        batch_test_image = [self.test_image] * self.batch_size
        batch_test_image = np.array(batch_test_image)

        with tf.Graph().as_default(), tf.Session() as sess:
            content_loss, genrAndvgg_net, _genr_net, x_content = self.create_content_loss(
            )
            style_loss = self.create_style_loss(genrAndvgg_net, target_grams)
            denoise_loss = self.create_denoise_loss(_genr_net)

            total_loss = content_loss + style_loss + denoise_loss
            print("total_loss type=", type(total_loss))
            my_optimizer = tf.train.AdamOptimizer(
                self.alpha).minimize(total_loss)
            sess.run(tf.global_variables_initializer())

            numOfExamples = len(self.ct_images)
            cur_iter = 0
            st_idx, ed_idx = 0, self.batch_size
            while ed_idx < numOfExamples:
                batch_data = self.ct_images[st_idx:ed_idx]
                x_batch = list(
                    map(lambda x: load_image(x, (256, 256)).astype(np.float32),
                        batch_data))
                x_batch = np.array(x_batch)
                my_optimizer.run(feed_dict={x_content: x_batch})

                st_idx += self.batch_size
                ed_idx += self.batch_size

                if not cur_iter % SAVE_PERIOD:
                    file_name = "model_{}.ckpt".format(cur_iter)
                    tf.train.Saver().save(sess,
                                          os.path.join(self.ck_dir, file_name))

                    # use test image to do pre-propagation
                    pre_prop = [
                        content_loss, style_loss, denoise_loss, total_loss,
                        _genr_net
                    ]
                    ret = sess.run(pre_prop,
                                   feed_dict={x_content: batch_test_image})

                    save_image(
                        os.path.join(self.test_out_dir,
                                     "{}.png".format(cur_iter)), ret[4][0])
                    with open(self.log_path, 'a') as f:
                        print(
                            "{}   content_loss:{:.3f} style_loss:{:.3f}  denoise_loss:{:.3f} total_loss:{:.3f}"
                            .format(cur_iter, ret[0], ret[1], ret[2], ret[3]))
                        f.write(
                            "{}   content_loss:{:.3f} style_loss:{:.3f}  denoise_loss:{:.3f} total_loss:{:.3f}\n"
                            .format(cur_iter, ret[0], ret[1], ret[2], ret[3]))

                cur_iter += 1
Esempio n. 13
0
def tool_init():
    global back
    back = sprite.Sprite(tool_group)
    back.image = pygame.Surface((width, 60), pygame.SRCALPHA)
    back.image.fill((255, 255, 255))
    back.rect = back.image.get_rect()

    Button(tool_group, load_image(fr'tools\save.jpg'), save, (5, 5))
    Button(tool_group, load_image(fr'tools\open.png'), open_im, (60, 5))

    Button(tool_group, load_image(fr'tools\palette.png'), new_color, (width - 80, 0))
    for i in range(5, 36, 30):
        for j in range(width - 370, width - 100, 30):
            Palette(tool_group, (j, i), update_color, col_mark, pygame.Color('red'), 20)
    tool_group.update(event=pygame.event.Event(pygame.MOUSEBUTTONDOWN, button=1, pos=(width - 369, 6)))
    tool_setting(Rect, 'rect', (width - 500, 5), True)
    tool_setting(Circle, 'circle', (width - 440, 5))
    tool_setting(Line, 'line', (width - 560, 5))
Esempio n. 14
0
def tool_setting(c, im, pos, t=False):
    def func(*args):
        global figure
        figure = c
        if drawing:
            figure_arr.pop()
            figure_arr.append(c(draw_group))
    b = Button(tool_group, load_image(fr'tools\{im}.bmp', pygame.Color((255, 255, 255))), func, pos, type=mode)
    if t:
        mode.move(b.rect)
Esempio n. 15
0
class Pow(pygame.sprite.Sprite):
    l_image = load_image('Pow1.png')
    r_image = load_image('Pow2.png')
    l_x, l_y = 0, 0
    x_pressed, y_pressed = width // 2 - 100, height // 2 - 100
    r_x, r_y = width - 200, height - 200

    def __init__(self, group, left):
        super().__init__(group)
        self.left = left
        self.pressed = False
        self.timer = 0
        if left:
            self.image = Pow.l_image
            self.rect = self.image.get_rect()
        else:
            self.image = Pow.r_image
            self.rect = self.image.get_rect()
            self.rect.x = Pow.r_x
            self.rect.y = Pow.r_y

    def press(self):
        self.pressed = True
        self.timer = 0
        self.rect.x = Pow.x_pressed
        self.rect.y = Pow.y_pressed

    def unpress(self):
        self.pressed = False
        self.timer = 0
        if self.left:
            self.rect.x = Pow.l_x
            self.rect.y = Pow.l_y
        else:
            self.rect.x = Pow.r_x
            self.rect.y = Pow.r_y

    def update(self):
        if self.pressed:
            self.timer += 1
            if self.timer > 4:
                self.unpress()
Esempio n. 16
0
def feature_based(args, valid=False):
    img_l = tools.load_image(args.left_image, 0)
    img_r = tools.load_image(args.right_image, 0)
    if valid:
        img_l, img_r = img_r, img_l
    feat_l = tools.get_features(img_l)
    feat_r = tools.get_features(img_r)
    disparity = np.zeros(img_l.shape).astype(np.int)
    disparity = functions.GetDisparity_feature(img_l,
                                               img_r,
                                               args.kernel_size,
                                               feat_l,
                                               feat_r,
                                               args.measure,
                                               disparity,
                                               valid=valid)
    disparity = cv2.filter2D(disparity.astype(np.float32), -1,
                             tools.mean_kernel2D)
    print
    return disparity.astype(np.int)
Esempio n. 17
0
 def create_all(self, name, alpha=True):
     """generate surface and alternative maps
     and reference them"""
     surface = tools.load_image(name, self.theme, self.scene, alpha)
     self.surfaces.update({name: surface})
     hit = tools.make_white(surface)
     shadow = tools.make_shadow(surface, parameters.SHADOWSCALE)
     array = tools.make_array(surface)
     self.hit.update({name: hit})
     self.shadow.update({name: shadow})
     self.array.update({name: array})
Esempio n. 18
0
 def __init__(self, default_pos, pos):
     super().__init__()
     self.image = load_image('bullet1.png')
     self.rect = self.image.get_rect() 
     self.rect.topleft = default_pos[0], default_pos[1]
     self.speed = 10
     self.x = default_pos[0]
     self.y = default_pos[1]
     dx = pos[0] - self.rect.center[0]
     dy = -(pos[1] - self.rect.center[1])
     dz = sqrt(dx ** 2 + dy ** 2)
     self.speedx = dx/dz * self.speed
     self.speedy = dy/dz * self.speed
Esempio n. 19
0
def region_based(args, valid=False):
    img_l = tools.load_image(args.left_image, 0)
    img_r = tools.load_image(args.right_image, 0)
    if valid:
        img_l, img_r = img_r, img_l
    pyramid_l = functions.GaussianPyramid(img_l, args.level)
    pyramid_r = functions.GaussianPyramid(img_r, args.level)
    disparity = np.zeros(pyramid_l[-1].shape)
    for i in range(args.level - 1, -1, -1):
        print "### Lv.%d" % (i + 1)
        disparity = disparity.astype(np.int)
        disparity = functions.GetDisparity_region(pyramid_l[i],
                                                  pyramid_r[i],
                                                  args.kernel_size,
                                                  args.window_length,
                                                  args.measure,
                                                  disparity,
                                                  valid=valid)
        disparity = cv2.filter2D(disparity.astype(np.float32), -1,
                                 tools.mean_kernel2D)
        if i > 0:
            disparity = functions.Expand(disparity) * 2
    print
    return disparity.astype(np.int)
Esempio n. 20
0
def recognition(model_name):
    # 識別用のデータをダウンロード
    train1, train_labels1 = load_image(
        "/media/wutong/New Volume/reseach/Dataset/OU-ISIR_by_Setoguchi/Gallery/signed/128_3ch/CV02(Gallery)_2nd",
        mode=False)
    train2, train_labels2 = load_image(
        "/media/wutong/New Volume/reseach/Dataset/OU-ISIR_by_Setoguchi/Gallery/signed/128_3ch/CV02_Dt2(Gallery)",
        mode=False)
    test1, test_labels1 = load_image(
        "/media/wutong/New Volume/reseach/Dataset/OU-ISIR_by_Setoguchi/Probe/signed/128_3ch/CV02(Probe)_2nd",
        mode=False)
    test2, test_labels2 = load_image(
        "/media/wutong/New Volume/reseach/Dataset/OU-ISIR_by_Setoguchi/Probe/signed/128_3ch/CV02_Dt2(Probe)",
        mode=False)

    # extract features
    model = Multi_modal_GEINet()
    serializers.load_npz(model_name, obj=model)

    train_features = extract_features(model, train1, train2)
    test_features = extract_features(model, test1, test2)

    neigh = KNeighborsClassifier(n_neighbors=1)
    neigh.fit(train_features, train_labels1)

    correct = 0.0
    for i, item in enumerate(test_features):
        predit = neigh.predict([item])[0]
        print "label:%d, predict:%d" % (test_labels1[i], predit)
        if predit == test_labels1[i]:
            correct = correct + 1
    # else:
    #         f.write("label:%d, predict:%d" %(true_label[i],predit)+"\n")

    acc = correct / len(test_features)
    print acc
Esempio n. 21
0
def start_cat():
    end_flag = False
    screen = pygame.display.set_mode(size)

    all_sprites = pygame.sprite.Group()

    # создадим спрайт
    sprite = pygame.sprite.Sprite()
    # определим его вид
    sprite.image = load_image("cat_bg.png")
    # и размеры
    sprite.rect = sprite.image.get_rect()
    # добавим спрайт в группу
    all_sprites.add(sprite)

    fishs = FishGroup(Fish(all_sprites, False), Fish(all_sprites, True))

    l_pow = Pow(all_sprites, True)
    r_pow = Pow(all_sprites, False)

    running = True
    fps = 30  # пикселей в секунду
    clock = pygame.time.Clock()
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:  # rshift — 303,     lshift — 304
                if event.key in (303, 1073742053):
                    r_pow.press()
                    fishs.press(False)
                elif event.key in (304, 1073742049):
                    l_pow.press()
                    fishs.press(True)
        screen.fill((255, 255, 255))
        fishs.update()
        all_sprites.update()
        all_sprites.draw(screen)
        if p1 > 4 or p2 > 4:
            return p1 if p1 >= 0 else 0, p2 if p2 >= 0 else 0
        show_points(screen)
        pygame.display.flip()
        clock.tick(fps)

    pygame.quit()
    return p1, p2
Esempio n. 22
0
    def __init__(self):
        self.clock = pygame.time.Clock()
        pygame.mouse.set_visible(0)

        self.surface = main_surface
        self.deadline = 120  # for monster :))

        self.font = pygame.font.Font(None, 30)
        self.background = load_image('background.png')
        pygame.mixer.music.load(load_sound('background.ogg'))

        self.brushing()

        self.level_formula = lambda x: (x + random.randint(5, x + 5))

        self.MAIN_LOOP = self.MENU_LOOP = self.OPTIONS_LOOP = False

        pygame.mixer.music.play(-1, 0.0)
        self.show_menu()
        self.start()
Esempio n. 23
0
    def __init__(self, image, dimensions, colorkey=-1):

        # load the image
        if type(image) is str:
            image = load_image(image)

        if colorkey == -1:
            colorkey = image.get_at((0,0))
            
        if colorkey:
            image.set_colorkey(colorkey)

        cols, rows = dimensions
        w = self.width = 1.0 * image.get_width() / cols
        h = self.height = 1.0 * image.get_height() / rows

        # build the images
        self._images = []
        for y in range(rows):
            row = []
            for x in range(cols):
                row.append(image.subsurface((x*w, y*h, w, h)))
            self._images.append(row)
Esempio n. 24
0
 def __init__(self, gb, sprpos, cell):
     #static data for game mechanics
     self.__GAMEBOARD = gb  # pointer to the game board to ask for services such as "get me a tower to attack"
     self.__MAXHP = config_get_creep_hp()
     self.__ATK = config_get_creep_atk()
     self.__ATK_RANGE = config_get_creep_atk_range(
     )  #range at which creep can attack tower
     self.__MVT_RANGE = config_get_creep_mvt_range(
     )  #range at which creep can move (2 means it can potentially jump over a tower)
     self.__MVT_COOLDOWN = config_get_creep_mvt_cooldown(
     )  #cooldown before creep can move again, in frames
     #dynamic data (status)
     self.__hp = self.__MAXHP
     self.__atk_cooldown_tick = config_get_creep_atk_cooldown(
     )  #at the beginning creeps can not attack
     self.__atk_anim_tick = config_get_creep_atk_anim_duration(
     )  #initialized at animduration and decreased each tick. when == 0, creep actually attacks
     # creep actually inflicts dmg every (atkcooldown + atkanimation) frames
     self.__mvt_cooldown_tick = self.__MVT_COOLDOWN  #at beginning, creeps have to wait before moving
     self.__current_cell = cell
     self.__target = None
     #__SPRITE
     self.__SPRITE = pygame.sprite.Sprite()
     self.__SPRITE.image, self.__SPRITE.rect = load_image(
         config_get_creep_sprite(),
         (int(self.__GAMEBOARD.get_cell_width() *
              config_get_creep_sprite_scale()),
          int(self.__GAMEBOARD.get_cell_height() *
              config_get_creep_sprite_scale())))
     self.__SPRITE.area = pygame.display.get_surface().get_rect()
     self.__padding = (1 - config_get_creep_sprite_scale()) / 2
     self.__SPRITE.rect.topleft = int(
         sprpos[0] + self.__GAMEBOARD.get_cell_width() * self.__padding
     ), int(sprpos[1] + self.__GAMEBOARD.get_cell_height() * self.__padding)
     #if spritescale = 0.8, then padding should be (1-0.8)/2 = 0.1 on top and bottom, and 0.1 on left and right
     #so that the spr is centered in the middle of the cell
     return
Esempio n. 25
0
class BlackSkull(Weapon):
    IMG = load_image('black_skull.png')
    hit = 5

    def __init__(self, centerx, top, direction):
        super(BlackSkull, self).__init__(centerx, top, self.IMG, direction)
Esempio n. 26
0
def run_ping():
    pygame.init()
    width = 850
    height = 450
    my_win = pygame.display.set_mode((width, height))
    radius = 15
    bumper_w = 50
    bumper_h = 110
    xspeed1 = 0
    xspeed2 = 0
    yspeed1 = 0
    yspeed2 = 0
    frame_count = 0
    p1_score = 0
    p2_score = 0
    bg = load_image('ping_bg.png')
    bumper1_img = load_image('bar1.png')
    bumper2_img = load_image('bar2.png')
    myFont = pygame.font.Font(None, 60)
    x = width / 2
    y = height / 2
    b1_x = 10
    b1_y = 190
    b2_x = 790
    b2_y = 190
    num = random.randint(1, 4)
    if num == 1:
        x_v = 4
        y_v = -4
    if num == 2:
        x_v = 4
        y_v = 4
    if num == 3:
        x_v = -4
        y_v = 4
    if num == 4:
        x_v = -4
        y_v = -4

    flag = True
    while flag:
        pygame.time.delay(15)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                flag = False
            elif event.type == pygame.KEYDOWN:
                if pygame.key.name(event.key) == "w":
                    yspeed1 = -5
                if pygame.key.name(event.key) == "d":
                    xspeed1 = 5
                if pygame.key.name(event.key) == "s":
                    yspeed1 = 5
                if pygame.key.name(event.key) == "a":
                    xspeed1 = -5
                if pygame.key.name(event.key) == "up":
                    yspeed2 = -5
                if pygame.key.name(event.key) == "right":
                    xspeed2 = 5
                if pygame.key.name(event.key) == "down":
                    yspeed2 = 5
                if pygame.key.name(event.key) == "left":
                    xspeed2 = -5
            elif event.type == pygame.KEYUP:
                if pygame.key.name(event.key) == "w":
                    yspeed1 = 0
                if pygame.key.name(event.key) == "d":
                    xspeed1 = 0
                if pygame.key.name(event.key) == "s":
                    yspeed1 = 0
                if pygame.key.name(event.key) == "a":
                    xspeed1 = 0
                if pygame.key.name(event.key) == "up":
                    yspeed2 = 0
                if pygame.key.name(event.key) == "right":
                    xspeed2 = 0
                if pygame.key.name(event.key) == "down":
                    yspeed2 = 0
                if pygame.key.name(event.key) == "left":
                    xspeed2 = 0

        x += x_v
        y += y_v

        frame_count += 1
        increment = 1

        if frame_count >= 500:
            frame_count = 0
            if x_v > 0:
                x_v += increment
            if x_v < 0:
                x_v += -increment
            if y_v > 0:
                y_v += increment
            if y_v < 0:
                y_v += -increment
        b1_x += xspeed1
        b1_y += yspeed1
        b2_x += xspeed2
        b2_y += yspeed2
        if b1_x < 0:
            b1_x = 0
        if b1_x > 399:
            b1_x = 399
        if b1_y < 0:
            b1_y = 0
        if b1_y > 370:
            b1_y = 370
        if b2_x < 426:
            b2_x = 426
        if b2_x > 825:
            b2_x = 825
        if b2_y < 0:
            b2_y = 0
        if b2_y > 370:
            b2_y = 370
        if x < -radius:
            p2_score += 1
            (x, y) = (width / 2, height / 2)
            frame_count = 0
            num = random.randint(1, 4)
            if num == 1:
                x_v = 4
                y_v = -4
            if num == 2:
                x_v = 4
                y_v = 4
            if num == 3:
                x_v = -4
                y_v = 4
            if num == 4:
                x_v = -4
                y_v = -4
        if x > (width + radius):
            p1_score += 1
            (x, y) = (width / 2, height / 2)
            frame_count = 0
            num = random.randint(1, 4)
            if num == 1:
                x_v = 4
                y_v = -4
            if num == 2:
                x_v = 4
                y_v = 4
            if num == 3:
                x_v = -4
                y_v = 4
            if num == 4:
                x_v = -4
                y_v = -4
        if y <= radius:
            y_v = -1 * y_v
        if y >= (height - radius):
            y_v = -1 * y_v
        if (x_v < 0) and (xspeed1 >= 0):
            if ((x - b1_x) <= (radius + bumper_w)) and (
                    (x - b1_x) > ((radius + bumper_w) - bumper_w)):
                if ((y - b1_y) > -radius) and ((y - b1_y) <= (bumper_h / 2)):
                    x_v = -1 * x_v
                    y_v = -1 * abs(y_v)
                if ((y - b1_y) > (bumper_h / 2)) and ((y - b1_y) < (bumper_h + radius)):
                    x_v = -1 * x_v
                    y_v = abs(y_v)

        if (x_v > 0) and (xspeed2 <= 0):
            if ((b2_x - x) <= radius) and ((b2_x - x) > (radius - bumper_w)):
                if ((y - b2_y) > -radius) and ((y - b2_y) <= (bumper_h / 2)):
                    x_v = -1 * x_v
                    y_v = -1 * abs(y_v)
                if ((y - b2_y) > (bumper_h / 2)) and ((y - b2_y) < (bumper_h + radius)):
                    x_v = -1 * x_v
                    y_v = abs(y_v)

        my_win.fill(pygame.color.Color("#281042"))
        my_win.blit(bg, (0, 0))

        score_label_1 = myFont.render(str(p1_score), True, pygame.color.Color("white"))
        my_win.blit(score_label_1, (304, 400))

        score_label_2 = myFont.render(str(p2_score), True, pygame.color.Color("white"))
        my_win.blit(score_label_2, (520, 20))

        pygame.draw.circle(my_win, pygame.color.Color("red"), (int(x), int(y)), int(radius))
        my_win.blit(bumper1_img, (b1_x, b1_y))
        my_win.blit(bumper2_img, (b2_x, b2_y))

        if p1_score > 4 or p2_score > 4:
            return p1_score, p2_score

        pygame.display.update()

    pygame.quit()
    return p1_score, p2_score
Esempio n. 27
0
def BlendImage(image_1, image_2, pixel_1=-1, pixel_2=-1):
    '''
    blend image base on n level Laplacian pyramid of both image and n level Gaussian pyramid of bit masks. And finally use reconstruction function to reconstruct the final image

    param image_1, image_2: input images to be blended
    param pixel_1, pixel_2: x value of points corresponse

    return: blended image
    '''
    img_1 = tools.load_image(image_1)
    img_2 = tools.load_image(image_2)

    img_height = img_1.shape[0]
    img_width_1 = img_1.shape[1]
    img_width_2 = img_2.shape[1]
    print img_width_1, img_width_2

    # pick width by clicking
    if pixel_1 < 0 or pixel_2 < 0:
        plt.imshow(cv2.cvtColor(img_1.astype('uint8'), cv2.COLOR_BGR2RGB))
        x, _ = plt.ginput(1)[0]
        plt.close('all')
        pixel_1 = x
        plt.imshow(cv2.cvtColor(img_2.astype('uint8'), cv2.COLOR_BGR2RGB))
        x, _ = plt.ginput(1)[0]
        plt.close('all')
        pixel_2 = x
    pixel_1 = int(img_width_1 - pixel_1)
    pixel_2 = int(pixel_2)

    blend_width = max([
        img_width_1 + img_width_2 - pixel_1 - pixel_2, img_width_1, img_width_2
    ])

    left_width = img_width_1 - pixel_1
    right_width = blend_width - img_width_2 + pixel_2

    img_1 = np.hstack(
        (img_1, np.zeros((img_height, blend_width - img_width_1, 3))))
    img_2 = np.hstack((np.zeros(
        (img_height, blend_width - img_width_2, 3)), img_2))

    # bit-mask
    bit_mask_1 = np.hstack((np.ones((img_height, left_width, 3)),
                            np.zeros(
                                (img_height, blend_width - left_width, 3))))
    bit_mask_2 = np.hstack((np.zeros((img_height, right_width, 3)),
                            np.ones((img_height, img_width_2 - pixel_2, 3))))

    # pyramid
    laplacian_img_1 = LaplacianPyramid(img_1, 5)
    laplacian_img_2 = LaplacianPyramid(img_2, 5)
    print ">>> Generating bit-masks for image 1"
    gaussian_mask_1 = GaussianPyramid(bit_mask_1, 5)
    print ">>> Generating bit-masks for image 2"
    gaussian_mask_2 = GaussianPyramid(bit_mask_2, 5)

    # blend
    blend_pyramid_1 = [
        img * mask for img, mask in zip(laplacian_img_1, gaussian_mask_1)
    ]
    blend_pyramid_2 = [
        img * mask for img, mask in zip(laplacian_img_2, gaussian_mask_2)
    ]

    blend_pyramid = [
        blend_1 + blend_2
        for blend_1, blend_2 in zip(blend_pyramid_1, blend_pyramid_2)
    ]

    blended_img = Reconstruct(blend_pyramid, 5)
    return blended_img
Esempio n. 28
0
class WhiteSkull(Weapon):
    IMG = load_image('skull.png')
    hit = 1

    def __init__(self, centerx, top, direction):
        super(WhiteSkull, self).__init__(centerx, top, self.IMG, direction)
Esempio n. 29
0
 def create_surf(self, name, alpha=True):
     """generate only pygame surface """
     surface = tools.load_image(name, self.theme, self.scene, alpha)
     self.surfaces.update({name: surface})
Esempio n. 30
0
from neupy import storage

storage.load(net, WEIGHTS_FILE)

import numpy as np
import matplotlib.pyplot as plt

images = []
image_paths = []
target = []

for path, directories, image_names in os.walk(IMAGE_DIR):
    for image_name in image_names:
        image_path = os.path.join(path, image_name)
        image = load_image(image_path,
                           image_size=(224, 224),
                           crop_size=(224, 224))

        images.append(image)
        image_paths.append(image_path)

        label = image_path.split(os.path.sep)[-2]
        if label == "Benign":
            label = 3
        if label == "malignant":
            label = 2
        if label == "benignwhite":
            label = 1
        if label == "malignantwhite":
            label = 0
Esempio n. 31
0
import sys

import pygame
from tools import load_image, win
from cat import start_cat
from play2 import run_ping
from play1 import run_car

FPS = 50
size = WIDTH, HEIGHT = 900, 600

screen = pygame.display.set_mode(size)

start_bg = load_image('start_bg.png')
start_bg_car = load_image('start_bg_car.png')
start_bg_kub = load_image('start_bg_kub.png')
start_bg_ping = load_image('start_bg_ping.png')
start_bg_pow = load_image('start_bg_pow.png')

pygame.mixer.music.load('FortyThr33 - Bay Breeze FREE DOWNLOAD.mp3')
pygame.mixer.music.set_volume(0.5)


def terminate():
    pygame.quit()
    sys.exit()


def hover(pos, click=True):
    pygame.mixer.music.play(-1)
    x, y = pos[0], pos[1]
Esempio n. 32
0
class Player(pygame.sprite.Sprite):
    IMG_HEALTH = load_image('life.png')

    CHAR_LEFT_F1 = load_image('character_left_f1.png')
    CHAR_LEFT_F2 = load_image('character_left_f2.png')
    CHAR_LEFT_F3 = load_image('character_left_f3.png')

    CHAR_RIGHT_F1 = load_image('character_right_f1.png')
    CHAR_RIGHT_F2 = load_image('character_right_f2.png')
    CHAR_RIGHT_F3 = load_image('character_right_f3.png')

    def __init__(self, health=10):
        super(Player, self).__init__()

        self.health = [self.IMG_HEALTH] * health
        self.images_left = []
        self.images_right = []

        for i, name in enumerate((
                self.CHAR_LEFT_F1,
                self.CHAR_LEFT_F2,
                self.CHAR_LEFT_F3,
                self.CHAR_RIGHT_F1,
                self.CHAR_RIGHT_F2,
                self.CHAR_RIGHT_F3,
        )):
            if i < 3:
                self.images_left.extend([name] * (FPS / 6))
            else:
                self.images_right.extend([name] * (FPS / 6))

        self.image = self.images_left[0]

        self.rect = self.image.get_rect()
        self.rect.top = 66
        self.rect.centerx = SCREEN_WIDTH / 2
        self.max = SCREEN_WIDTH
        self.frame_count = 1

        self.black_skulls = 0

        # for left
        self.direction = -5

    def update(self, keys):
        if keys[K_LEFT]:
            self.direction = -5
            self.frame_count += 1
            self.image = self.images_left[self.frame_count % (FPS / 2)]
            self.rect.move_ip(-10, 0)
            if self.rect.centerx < 0:
                self.rect.centerx = 0
        elif keys[K_RIGHT]:
            self.direction = 5
            self.frame_count += 1
            self.image = self.images_right[self.frame_count % (FPS / 2)]
            self.rect.move_ip(10, 0)
            if self.rect.centerx > self.max:
                self.rect.centerx = self.max

    def draw(self, surface):
        surface.blit(self.image, self.rect)

    def hit(self):
        if self.health:
            del self.health[-1]

    def alive(self):
        if not self.health:
            return False
        return True
Esempio n. 33
0
    def update(self):
        node_type = self.circuit_grid_model.get_node_gate_part(
            self.wire_num, self.column_num
        )

        if node_type == node_types.H:
            self.image, self.rect = load_image("gate_images/h_gate.png", -1)
        elif node_type == node_types.X:
            node = self.circuit_grid_model.get_node(self.wire_num, self.column_num)
            if node.ctrl_a >= 0 or node.ctrl_b >= 0:
                # This is a control-X gate or Toffoli gate
                # TODO: Handle Toffoli gates more completely
                if self.wire_num > max(node.ctrl_a, node.ctrl_b):
                    self.image, self.rect = load_image(
                        "gate_images/not_gate_below_ctrl.png", -1
                    )
                else:
                    self.image, self.rect = load_image(
                        "gate_images/not_gate_above_ctrl.png", -1
                    )
            elif node.radians != 0:
                self.image, self.rect = load_image("gate_images/rx_gate.png", -1)
                self.rect = self.image.get_rect()
                pygame.draw.arc(
                    self.image,
                    COLORS["MAGENTA"],
                    self.rect,
                    0,
                    node.radians % (2 * np.pi),
                    6,
                )
                pygame.draw.arc(
                    self.image,
                    COLORS["MAGENTA"],
                    self.rect,
                    node.radians % (2 * np.pi),
                    2 * np.pi,
                    1,
                )
            else:
                self.image, self.rect = load_image("gate_images/x_gate.png", -1)
        elif node_type == node_types.Y:
            node = self.circuit_grid_model.get_node(self.wire_num, self.column_num)
            if node.radians != 0:
                self.image, self.rect = load_image("gate_images/ry_gate.png", -1)
                self.rect = self.image.get_rect()
                pygame.draw.arc(
                    self.image,
                    COLORS["MAGENTA"],
                    self.rect,
                    0,
                    node.radians % (2 * np.pi),
                    6,
                )
                pygame.draw.arc(
                    self.image,
                    COLORS["MAGENTA"],
                    self.rect,
                    node.radians % (2 * np.pi),
                    2 * np.pi,
                    1,
                )
            else:
                self.image, self.rect = load_image("gate_images/y_gate.png", -1)
        elif node_type == node_types.Z:
            node = self.circuit_grid_model.get_node(self.wire_num, self.column_num)
            if node.radians != 0:
                self.image, self.rect = load_image("gate_images/rz_gate.png", -1)
                self.rect = self.image.get_rect()
                pygame.draw.arc(
                    self.image,
                    COLORS["MAGENTA"],
                    self.rect,
                    0,
                    node.radians % (2 * np.pi),
                    6,
                )
                pygame.draw.arc(
                    self.image,
                    COLORS["MAGENTA"],
                    self.rect,
                    node.radians % (2 * np.pi),
                    2 * np.pi,
                    1,
                )
            else:
                self.image, self.rect = load_image("gate_images/z_gate.png", -1)
        elif node_type == node_types.S:
            self.image, self.rect = load_image("gate_images/s_gate.png", -1)
        elif node_type == node_types.SDG:
            self.image, self.rect = load_image("gate_images/sdg_gate.png", -1)
        elif node_type == node_types.T:
            self.image, self.rect = load_image("gate_images/t_gate.png", -1)
        elif node_type == node_types.TDG:
            self.image, self.rect = load_image("gate_images/tdg_gate.png", -1)
        elif node_type == node_types.IDEN:
            # a completely transparent PNG is used to place at the end of the circuit to prevent crash
            # the game crashes if the circuit is empty
            self.image, self.rect = load_image("gate_images/transparent.png", -1)
        elif node_type == node_types.CTRL:
            # TODO: Handle Toffoli gates correctly
            if self.wire_num > self.circuit_grid_model.get_gate_wire_for_control_node(
                self.wire_num, self.column_num
            ):
                self.image, self.rect = load_image(
                    "gate_images/ctrl_gate_bottom_wire.png", -1
                )
            else:
                self.image, self.rect = load_image(
                    "gate_images/ctrl_gate_top_wire.png", -1
                )
        elif node_type == node_types.TRACE:
            self.image, self.rect = load_image("gate_images/trace_gate.png", -1)
        elif node_type == node_types.SWAP:
            self.image, self.rect = load_image("gate_images/swap_gate.png", -1)
        else:
            self.image = pygame.Surface([GATE_TILE_WIDTH, GATE_TILE_HEIGHT])
            self.image.set_alpha(0)
            self.rect = self.image.get_rect()

        self.image.convert()
Esempio n. 34
0
 def __init__(self):
     pygame.sprite.Sprite.__init__(self)
     self.image, self.rect = load_image(
         "cursor_images/circuit-grid-cursor-medium.png", -1
     )
     self.image.convert_alpha()
Esempio n. 35
0
 def _load_image(self, path):
     grayscale = self.channels == 1
     return tools.load_image(path,
                             (self.target_imsize[1], self.target_imsize[0]),
                             grayscale)