Exemple #1
0
class Enemy(Collider):
    """The big bad evil guy"""
    pattern_list = [
        BlarghAttackPattern, BounceAttackPattern, BombAttackPattern
    ]

    sprite_image = image_load('enemy.png')

    bomb_image_120px = image_load('enemy_bomb_120px.png')
    bullet_image_120px = image_load('enemy_bullet_120px.png')
    bullet_image_60px = image_load('enemy_bullet_60px.png')
    bullet_image_30px = image_load('enemy_bullet_30px.png')

    def __init__(self, play_screen, start):
        """Creates the enemy"""
        super().__init__(containers=play_screen.get_containers(
            'ENEMY', 'ENTITY'),
                         image=self.sprite_image,
                         start=start,
                         health=Health(400),
                         damage=10)
        self.play_screen = play_screen
        HealthBar(containers=play_screen.everything,
                  health=self.health,
                  size=np.array((580, 30)),
                  start=np.array((320, 45)),
                  border_size=3,
                  color=(255, 0, 0))
        self.attack_pattern = None
        self.current_pattern = -1
        self.new_attack_pattern()

    def new_attack_pattern(self):
        """Switches to a new attack pattern"""
        new_index = self.current_pattern
        if len(self.pattern_list) > 1:
            while new_index == self.current_pattern:
                new_index = random.randrange(len(self.pattern_list))
        self.current_pattern = new_index
        self.attack_pattern = self.pattern_list[new_index](self)

    def update(self):
        """Updates the enemy"""
        # check if game started yet
        if not self.play_screen.game_started:
            return

        # update attack pattern
        if self.attack_pattern.done:
            self.new_attack_pattern()
        self.attack_pattern.update()

        # check for keypress to cheat and win
        pressed = pygame.key.get_pressed()
        if pressed[ord('y')]:
            self.health.die()
Exemple #2
0
def process_img(name, label, crop_shape, scale, random_draws, 
                to_augment=True, no_rotation=True, logging=True):
    imgs = []
    if logging:
        print "%s [%d] Processing file %s" % (get_time(), os.getpid(), name)
    pad_value = 127
    img = image_load(name)
    simg = scale_radius(img, round(scale / .9))
    uimg = unsharp_img(simg, round(scale / .9))
    suimg = subsample_inner_circle_img(uimg, round(scale / .9), pad_value)
    cimg = center_crop(suimg, crop_shape)
    pimg = pad_img(cimg, (2 * scale, 2 * scale, 3), value=127)
    pimg[:10, :, :] = pad_value
    pimg[-10:, :, :] = pad_value
    imgs.append(pimg)

    # Check if augmentation is needed
    if (to_augment and np.random.uniform(0, 1) > pb[label]) or (not to_augment):
        return imgs

    for i in range(random_draws):
        dist_img = get_distorted_img(simg, 127, no_rotation)
        uimg = unsharp_img(dist_img, round(scale / .9))
        suimg = subsample_inner_circle_img(uimg, round(scale / .9), pad_value)
        cimg = center_crop(suimg, (256, 256))
        dimg = pad_img(cimg, (2 * scale, 2 * scale, 3), value=127)
        dimg[:10, :, :] = pad_value
        dimg[-10:, :, :] = pad_value
        imgs.append(dimg)

    return imgs
Exemple #3
0
    def __init__(self, pos=None):
        super().__init__()
        self._sheet = image_load(BASEDIR / "assets" / "images" /
                                 "characters.png").convert_alpha()
        self.animation = {}
        self._position = pos or [0, 0]
        self.velocity = [0, 0]
        self.anim_dir = "down"
        self.frame = 0.0
        self.frame_speed = 3.0
        self.speed = 20

        for i, anim in enumerate(["down", "left", "right", "up"]):
            r = pygame.Rect((3 * 16, 16 * i), (16, 16))
            self.animation.setdefault(anim,
                                      []).append(self._sheet.subsurface(r))
            r.left += 16
            self.animation.setdefault(anim,
                                      []).append(self._sheet.subsurface(r))
            r.left += 16
            self.animation.setdefault(anim,
                                      []).append(self._sheet.subsurface(r))

        self.image = self.animation[self.anim_dir][int(self.frame)]
        self.rect = self.image.get_rect()
        self.feet = pygame.Rect(0, 0, self.rect.width + 4, 4)
        self._old_position = self.position
Exemple #4
0
def main():

    start_epoch = 0
    epochs = 30
    cuda = '0'
    res_train= []
    res_test = []

    # Use CUDA
    os.environ['CUDA_VISIBLE_DEVICES'] = '0'
    use_cuda = torch.cuda.is_available()

    #Data
    trainLoader, testLoader = image_load(args.train_batch, args.test_batch)

    #Load Network
    if(args.arch == 'teacher'):
        teacher_net = resnet.resnet50(pretrained=True)

        #fine_tuning

        teacher_net.avgpool = nn.AvgPool2d(1, stride=1)
        teacher_net.fc = nn.Linear(2048, 1000)
        model = teacher_net

    elif(args.arch == 'student'):
        student_net = vgg.vgg11(pretrained=False)
        model = student_net

    model = model.cuda()

    #nn.CrossEntropyLoss에 softmax가 포함되어 있다.

    criterion = nn.CrossEntropyLoss().cuda()
    optimizer = optim.SGD(model.parameters(), args.lr, momentum=args.momentum, weight_decay=args.weight_decay)

    for epoch in range(start_epoch, epochs):

        trainTop1Val = train(trainLoader, model, criterion, optimizer, epoch , print_freq=100)
        testTop1Val = test(testLoader, model,criterion, epoch, print_freq=100)
        a = model.state_dict()
        b = optimizer.state_dict()
        state = {'epoch': epoch+1,
                 'arch': 'teacherNet',
                 'state_dict': model.state_dict(),
                 'optimizer': optimizer.state_dict()
                 }
        filename =  'teacherNet_'+'checkpoint.pth'
        torch.save(state, filename)

        res_train.append(trainTop1Val)
        res_test.append(testTop1Val)

    print(res_test, res_train)
    top1AccPlot(res_train, res_test, epoch)
Exemple #5
0
class GameStartCircle(VectorSprite):
    """A circle used at the start of a game. Hover cursor inside to begin game."""
    circle_image = image_load('game_start_circle.png')

    def __init__(self, play_screen, start):
        """Create the circle"""
        super().__init__(play_screen.everything, self.circle_image, start)
        self.play_screen = play_screen

    def update(self):
        """If cursor is inside, start the game and die"""
        radius = self.rect.size[0] / 2
        cursor_loc = np.array(pygame.mouse.get_pos())
        if np.linalg.norm(self.vec - cursor_loc) < radius:
            self.play_screen.start_game()
            self.kill()
def main():
    config = fix_seeds(config_process(parser.parse_args()))
    examples, labels, class_map = utils.image_load(config['class_file'],
                                                   config['image_label'])
    # train, test, label, train_attr, test_attr
    datasets = utils.split_byclass(config, examples, labels,
                                   np.loadtxt(config['attributes_file']),
                                   class_map)
    print('load the train: {} the test: {}'.format(len(datasets[0][0]),
                                                   len(datasets[0][1])))
    best_cfg = config
    best_cfg = fix_seeds(best_cfg)
    best_cfg['epochs'] = config['final_epoch']
    best_cfg['n_classes'] = datasets[0][3].size(0)
    best_cfg['n_train_lbl'] = datasets[0][3].size(0)
    best_cfg['n_test_lbl'] = datasets[0][4].size(0)

    # data grab
    train_set = grab_data(best_cfg, datasets[0][0], datasets[0][2], True)
    test_set = grab_data(best_cfg, datasets[0][1], datasets[0][2], False)

    # create model
    model = models.__dict__['resnet101'](pretrained=True)
    model = aren.AREN(best_cfg, model, Parameter(F.normalize(datasets[0][3])),
                      Parameter(F.normalize(datasets[0][4])))
    model = nn.DataParallel(model).cuda()

    # define loss function (criterion) and optimizer
    criterion = nn.CrossEntropyLoss().cuda()
    optimizer = torch.optim.SGD(model.parameters(),
                                lr=best_cfg['lr'],
                                momentum=best_cfg['momentum'],
                                weight_decay=best_cfg['weight_decay'])
    # load the fine-tuned checkpoint
    if best_cfg['pretrain'] == 1:
        load_model(best_cfg, model, optimizer, best_cfg['pre_model'])

    # best_meas, best_epoch, best_pred_prob = train_test(best_cfg, model, optimizer, criterion, train_set, test_set)
    best_meas, best_epoch, best_pred_prob = test(best_cfg, model, criterion,
                                                 test_set)
    print('Reproducing CUB:PS ACA = {:.3f}%'.format(best_meas))
Exemple #7
0
class Player(Collider):
    """The player entity for the game"""
    MOVE_SPEED = 20
    SHOOT_DELAY = 3
    BULLET_VELOCITY = np.array((0, -20))
    BULLET_DAMAGE = 1
    BULLET_SPAWN_OFFSET = np.array((0, -12))

    sprite_image = image_load('player.png')
    hitbox_image = image_load('player_hitbox.png')
    bullet_image = image_load('player_bullet.png')

    @staticmethod
    def health_from_difficulty(diff):
        """Creates the player's health, given the difficulty"""
        if diff == Difficulty.TRIVIAL:
            return InfiniteHealth()
        if diff == Difficulty.NORMAL:
            return Health(100, .1)
        if diff == Difficulty.HARD:
            return OneHealth()
        return None

    def __init__(self, play_screen, start, diff=Difficulty.NORMAL):
        """Creates the Player"""
        super().__init__(containers=play_screen.get_containers(
            'PLAYER', 'ENTITY'),
                         image=self.sprite_image,
                         start=start,
                         health=self.health_from_difficulty(diff),
                         damage=.1,
                         hitbox=self.hitbox_image)
        self.difficulty = diff
        self.play_screen = play_screen
        HealthBar(containers=play_screen.everything,
                  health=self.health,
                  size=np.array((160, 20)),
                  start=np.array((100, 610)),
                  border_size=2,
                  color=(0, 255, 0))
        self.next_shot = 0
        self.bullet_containers = play_screen.get_containers('PLAYER', 'BULLET')

    def update(self):
        """Does various things to update the player"""
        # check if game started yet
        if not self.play_screen.game_started:
            return

        # make movement towards cursor
        vec_move = np.array(pygame.mouse.get_pos()) - self.vec
        dist = np.linalg.norm(vec_move)
        if dist > self.MOVE_SPEED:
            vec_move = vec_move * self.MOVE_SPEED / dist
        self.move_by(vec_move)

        # update health
        self.health.update()

        # shoot bullet if available
        if self.next_shot == 0:
            LinearBullet(containers=self.bullet_containers,
                         image=self.bullet_image,
                         start=self.vec + self.BULLET_SPAWN_OFFSET,
                         damage=self.BULLET_DAMAGE,
                         velocity=self.BULLET_VELOCITY)
            self.next_shot = self.SHOOT_DELAY
        self.next_shot -= 1

        # check for keypresses (X to die, Z to lose some health)
        pressed = pygame.key.get_pressed()
        if pressed[ord('x')]:
            self.health.die()
        if pressed[ord('z')]:
            self.health.take_damage(10)