Пример #1
0
        def render(self, surface: Any, wieldables: list[tuple[str,
                                                              dict]]) -> None:
            rendering.render(surface, "Wield which weapon?", self.x, self.y,
                             (0, 255, 0))
            rendering.render(surface, "- unarmed", self.x, self.y + 1,
                             (255, 255, 255))

            self.print_items(wieldables, surface)
Пример #2
0
        def render(self, surface: Any) -> None:
            # Makes little barrier
            for i in range(self.width):
                rendering.render(surface, chr(9472), self.x + i, self.y,
                                 (0, 255, 0))

            for msg in enumerate(self.messages):
                rendering.render(surface, f"> {msg[1]['Text']}", self.x + 1,
                                 self.y + 1 + msg[0], msg[1]['Color'])
Пример #3
0
    def handle_rendering(self, surface: Any) -> None:
        """Handles rendering for the SelectTarget state."""

        super().handle_rendering(surface)

        # Draws a line along the bullet path.
        for point in self.engine.player.bullet_path:
            # Later remove hard-coded color and character.
            rendering.render(surface, '*', point[0], point[1],
                             self.engine.game_data.colors["RED"])
Пример #4
0
def initalizeGame(pygame):
    # Set window properties
    globalVariables.screen = pygame.display.set_mode(globalVariables.size)
    pygame.display.set_caption('Snake')

    # Initialize logic
    logic.resetGame()

    # Render the initial frame
    rendering.render()
Пример #5
0
    def render_projectile(self, points: list[tuple[int, int]], char: str,
                          color: tuple[int, int, int], delay: float) -> None:
        """'Animates' a projectile as it flies through the air by sleeping briefly between renders."""

        self.game_entities.render_all(self.game_entities.surface)
        for point in points:
            rendering.render(self.game_entities.surface, char, point[0],
                             point[1], color)
        self.game_entities.window.present(self.game_entities.surface)
        time.sleep(delay)
Пример #6
0
        def render(self, surface: Any,
                   actor_: game_entities.actor.Actor) -> None:
            rendering.render(
                surface,
                f"Inventory: {len(actor_.inventory)} / {actor_.MAX_INVENTORY_SIZE} slots",
                self.x, self.y, (0, 255, 0))

            items: list[tuple[str, dict]] = [
                item_ for item_ in actor_.inventory.items()
            ]
            self.print_items(items, surface)
Пример #7
0
        def print_items(self, items: list[tuple[str, dict]], surface: Any):
            items.sort()
            for item in enumerate(items):
                # For smoother grammar
                amount: Union[int, str] = item[1][1]["Amount"]
                if amount == 1:
                    amount = 'a'

                rendering.render(
                    surface,
                    f"{item[1][0]} - {amount} {item[1][1]['Item'].name}",
                    self.x, self.y + 2 + item[0], (0, 255, 255))
Пример #8
0
 def get_cache(self):
     if self.shape_params == 'fusion_shape_branch' and self.color_params == 'color_branch':
         with torch.no_grad():
             self.train_kwargs[
                 'network_fine'].get_cached = 'shape' if self.edit_type in (
                     'addition', 'removal') else 'color'
             self.train_kwargs.update({'near': self.near, 'far': self.far})
             H, W, f = self.hwfs[0]
             features, weights = [], []
             for i in range(len(self.dataset)):
                 batch_rays, _, style, _, _, _, _ = self.dataset.get_data_batch(
                     all_rays=True, imgnum=i)
                 rgb, disp, acc, extras = render(H,
                                                 W,
                                                 f,
                                                 style=style,
                                                 rays=batch_rays,
                                                 **self.train_kwargs)
                 features.append(extras['features'])
                 weights.append(extras['weights0'])
             if self.edit_type in ('addition', 'removal'):
                 self.dataset.shape_features = features
             else:
                 self.dataset.color_features = features
             self.dataset.weights = weights
             self.train_kwargs['network_fine'].get_cached = None
Пример #9
0
    def do_GET(self):
        if self.path == '/':
            with open('index.html', 'r') as f:
                source = f.read()

            self.send_response(200)
            self.send_header('Content-type', 'text/html;charset=utf-8')
            self.end_headers()
            self.wfile.write(source.encode('utf-8'))
            return

        elif self.path in LITERALS:
            with open(self.path[1:], 'r') as f:
                source = f.read()

            self.send_response(200)

            if self.path.endswith('.js'):
                self.send_header('Content-type',
                                 'text/javascript;charset=utf-8')
            else:
                self.send_header('Content-type', 'text/html;charset=utf-8')

            self.end_headers()
            self.wfile.write(source.encode('utf-8'))
            return

        file_path = os.path.join(
            EXAMPLES_DIRECTORY,
            self.path[1:] if self.path.startswith('/') else self.path,
        )

        try:
            with open(file_path, 'r') as f:
                source = f.read()

        except FileNotFoundError:
            self.send_response(404)
            self.send_header('Content-type', 'text/plain;charset=utf-8')
            self.end_headers()
            self.wfile.write(
                'File "{}" not found'.format(file_path).encode('utf-8'))
            return

        try:
            source_json = json.loads(source)

        except json.decoder.JSONDecodeError:
            self.send_response(500)
            self.send_header('Content-type', 'text/plain;charset=utf-8')
            self.end_headers()
            self.wfile.write(
                'Invalid file "{}"'.format(file_path).encode('utf-8'))
            return

        self.send_response(200)
        self.send_header('Content-type', 'text/html;charset=utf-8')
        self.end_headers()
        self.wfile.write(
            rendering.as_page(rendering.render(source_json)).encode('utf-8'))
Пример #10
0
    def copy(self, ev):
        self.copy_mask = self.copy_canvas.mask
        tgt_style = self.copy_canvas.instance_style
        index = self.copy_canvas.index
        area = renormalize.from_url(self.copy_mask,
                                    target='pt',
                                    size=(256, 256))[0]
        t, l, b, r = positive_bounding_box(area)
        H, W, focal = self.hwfs[0]
        H, W = H.item(), W.item()

        with torch.no_grad():
            rays_o, rays_d = get_rays(int(H), int(W), focal, self.poses[index])
            rays_o, rays_d = rays_o[t:b, l:r], rays_d[t:b, l:r]
            rays_o, rays_d = rays_o.contiguous().view(
                -1, rays_o.shape[-1]), rays_d.contiguous().view(
                    -1, rays_d.shape[-1])
            batch_rays = torch.stack([rays_o, rays_d], 0)
            # render the rays under the editing canvas color style
            style = torch.cat([tgt_style[:, :32], self.instance_style[:, 32:]],
                              dim=1)
            style = style.repeat((batch_rays.shape[1], 1))
            rgb, disp, acc, extras = render(H,
                                            W,
                                            focal.item(),
                                            style=style,
                                            rays=batch_rays,
                                            **self.test_kwargs)

        self.copy_canvas.rgb = rgb.view(b - t, r - l, -1).cpu() * 2 - 1
        self.copy_canvas.mask = ''
Пример #11
0
    def optimize(self):
        niter = N_ITERS[self.edit_type]
        H, W, f = self.hwfs[0]
        if self.optimizer is not None:
            for param_group in self.optimizer.param_groups:
                param_group['lr'] = LR
        for i in range(niter):
            batch_rays, target_s, style, mask_rays, shape_features, color_features, weights = self.dataset.get_data_batch(
            )
            if shape_features is not None:
                features = shape_features
            elif color_features is not None:
                features = color_features
            else:
                features = None
            self.train_kwargs.update({'near': self.near, 'far': self.far})
            if self.optimizer is not None:
                self.optimizer.zero_grad()
            rgb, disp, acc, extras = render(H,
                                            W,
                                            f,
                                            style=style,
                                            rays=batch_rays,
                                            feature=features,
                                            weights=weights,
                                            **self.train_kwargs)

            loss = img2mse(rgb, target_s)
            if self.edit_type == 'addition':
                loss += img2mse(extras['rgb0'], target_s)

            weight_change_loss = torch.tensor(0.)
            for k, v in self.train_kwargs['network_fine'].named_parameters():
                if 'weight' in k:
                    weight_change_loss += (self.old_fine_network[k] -
                                           v).pow(2).mean()
            weight_change_loss = 10 * weight_change_loss
            loss += weight_change_loss

            if self.edit_type == 'removal':
                sigma_loss = 0.01 * (
                    mask_rays *
                    (-extras['weights'] *
                     (extras['weights'] + 1e-7).log()).sum(dim=1)).mean()
                loss += sigma_loss
            else:
                sigma_loss = torch.tensor(0.)

            loss.backward()
            if self.optimizer is not None:
                self.optimizer.step()

            if VERBOSE:
                self.msg_out.print(
                    f'Iter {i+1}/{niter}, Loss: {loss.item():.4f}',
                    replace=True)
            else:
                self.msg_out.print(f'Iter {i+1}/{niter}', replace=True)
Пример #12
0
def show_player_stats():
    player_stats=libtcod.console_new(20,20)
    libtcod.console_set_default_background(player_stats,libtcod.darkest_grey)
    libtcod.console_set_default_foreground(player_stats, libtcod.white)
    #  libtcod.console_clear(player_stats)
    libtcod.console_print_frame(player_stats,
        0, 0,
        libtcod.console_get_width(player_stats),
        libtcod.console_get_height(player_stats),
        clear=True)
    height=0
    libtcod.console_print_rect(player_stats, 1, 1,
        libtcod.console_get_width(player_stats)-2,
        libtcod.console_get_height(player_stats)-2,
        "Name: %s \nHealth: %s/%s\nView distance: %s\nStrength: %s\nTo hit: %s\nExp: %s"#
        %(P.player.name,P.player.health,P.player.max_health, P.player.view_distance,
          P.player.strength,P.player.to_hit,P.player.exp))
    libtcod.console_print_ex(player_stats,
        libtcod.console_get_width(player_stats)//2,
        0,
        libtcod.BKGND_DEFAULT,
        libtcod.CENTER,
        "Player Stats")
    libtcod.console_print_ex(player_stats,
        libtcod.console_get_width(player_stats)//2,
        libtcod.console_get_height(player_stats)-1,
        libtcod.BKGND_DEFAULT,
        libtcod.CENTER,
        "[spacebar]")
    libtcod.console_blit(player_stats,0,0,
        libtcod.console_get_width(player_stats),
        libtcod.console_get_height(player_stats),
        0,5,5,
        1.0,0.1)
    key = libtcod.console_check_for_keypress(libtcod.KEY_PRESSED)
    while not (libtcod.KEY_SPACE==key.vk):
        key = libtcod.console_check_for_keypress(libtcod.KEY_PRESSED)
        libtcod.console_blit(player_stats,0,0,
          libtcod.console_get_width(player_stats),
          libtcod.console_get_height(player_stats),
          0,5,5,
          1.0,0.1)
        libtcod.console_flush()
        R.render()
Пример #13
0
 def fire(self, x, y, dx, dy):
     # The distance this bullet has traveled.
     steps = 0
     shot_accuracy=self.accuracy
     libtcod.map_compute_fov (P.player.fov, x, y, int(P.player.view_distance*1.5),
                               True,libtcod.FOV_SHADOW)
     R.render()
     libtcod.line_init(x, y, dx, dy)
     lx,ly=libtcod.line_step()
     while (not lx is None):
         steps = steps + 1
         if not M.gameworld[lx][ly].characters:
             libtcod.console_set_char_background(
                     cons.game_console,
                     lx,
                     ly,
                     libtcod.white,
                     libtcod.BKGND_OVERLAY)
             libtcod.console_blit(cons.game_console,0,0,M.MAP_WIDTH,M.MAP_HEIGHT,0,0,0,1)
             libtcod.console_flush()
             lx,ly=libtcod.line_step()
         else:
             if random.random() <= shot_accuracy:
                 S.add_status("You hit!")
                 libtcod.console_set_char_background(
                         cons.game_console,
                         lx,
                         ly,
                         libtcod.red,
                         libtcod.BKGND_OVERLAY)
                 libtcod.console_blit(cons.game_console,0,0,M.MAP_WIDTH,M.MAP_HEIGHT,0,0,0,1)
                 libtcod.console_flush()
                 M.gameworld[lx][ly].characters[-1].take_damage(
                         int(self.damage*random.uniform(self.accuracy, 1.0)))
             else:
                 S.add_status("You fire and miss!")
             break
     self.ammo = self.ammo-1
     self.owner.name = self.owner.name.rsplit('(')[0] + '(' + str(self.ammo) + ')'
     P.player.compute_fov()
Пример #14
0
    def __init__(self, md=True):
        self.R = render()
        self.M = map()
        self.xycar = car()

        self.end = False
        self.steering_AOC = 200

        self.set_frame(self.framepersec)
        self.curr_path = os.getcwd()
        self.pygame_exit = False
        if md:
            self.make_dir()
Пример #15
0
 def render_template(*args, **kwargs):
     res = fn(*args, **kwargs)
     if isinstance(res, tuple):
         if len(res) == 2:
             (new_context, partials) = res
         elif len(res) == 1:
             (new_context, partials) = (res[0], {})
     elif isinstance(res, dict):
         (new_context, partials) = (res, {})
     else:
         (new_context, partials) = ({}, {})
     context = copy(template_globals)
     context.update(new_context)
     return render(template, context, partials, state)
Пример #16
0
 def fn():
     optimizer.zero_grad()
     self.style_optimizer.zero_grad()
     batch_rays, target_s, style, H, W, focal, near, far, _ = self.get_data_batch(
         optimize_style=False)
     train_fn.update({'near': near, 'far': far})
     rgb, disp, acc, extras = render(H,
                                     W,
                                     focal,
                                     style=style,
                                     rays=batch_rays,
                                     **train_fn)
     loss = img2mse(rgb, target_s) + img2mse(extras['rgb0'], target_s)
     return loss
Пример #17
0
 def render_template(*args, **kwargs):
     res = fn(*args, **kwargs)
     if isinstance(res, tuple):
         if len(res) == 2:
             (new_context, partials) = res
         elif len(res) == 1:
             (new_context, partials) = (res[0], {})
     elif isinstance(res, dict):
         (new_context, partials) = (res, {})
     else:
         (new_context, partials) = ({}, {})
     context = copy(template_globals)
     context.update(new_context)
     return render(template, context, partials, state)
Пример #18
0
def step(action):

    # Take the selected action
    globalVariables.pending_snake_direction = action

    # Take step and receive reward
    reward, isTerminalState = logic.update()

    # Add reward to score
    globalVariables.score = globalVariables.score + reward

    # Render the next frame
    screen = rendering.render()

    # Update the number of steps counter
    globalVariables.numberOfSteps = globalVariables.numberOfSteps + 1

    return reward, screen, isTerminalState
Пример #19
0
def main():
    board = Board(3, 3)
    cursor_pos = [0, 0]
    player1_is_x = True
    is_player1_turn = True

    key_reader = _Getch()

    print('Would you like to play as x? (y/n)')
    if key_reader().lower() == 'y':
        player1_is_x = True
        is_player1_turn = True
    else:
        player1_is_x = False
        is_player1_turn = False
    clear_terminal()

    # Game loop
    while True:
        render(board.state, board.height, board.width, cursor_pos)
        check_if_win(board.state, player1_is_x)

        key = key_reader()

        if key == 'q':
            exit()
        elif key == 'w' and cursor_pos[1] - 1 >= 0:
            cursor_pos[1] -= 1
        elif key == 'a' and cursor_pos[0] - 1 >= 0:
            cursor_pos[0] -= 1
        elif key == 's' and cursor_pos[1] + 1 <= board.height - 1:
            cursor_pos[1] += 1
        elif key == 'd' and cursor_pos[0] + 1 <= board.width - 1:
            cursor_pos[0] += 1
        elif key == ' ' and board.state[cursor_pos[1]][cursor_pos[0]] == 0:
            if player1_is_x:
                board.state[cursor_pos[1]][cursor_pos[0]] = 1
                render(board.state, board.height, board.width, cursor_pos)
                check_if_win(board.state, player1_is_x)
                ai_move(board, player1_is_x)
            else:
                board.state[cursor_pos[1]][cursor_pos[0]] = 2
                render(board.state, board.height, board.width, cursor_pos)
                check_if_win(board.state, player1_is_x)
                ai_move(board, player1_is_x)
    def main_function(self, path_to_save):
        vapp = 0.0
        count_for_render = 0
        jp_list, jn_list = [], []
        vapp_list = []

        carrier = ContinuityEquation(self.boundary, self.dict_a, self.dict_b, self.a0, self.b0, self.row, self.col)

        while (self.sigma_a/P.N**2)/self.num < 1:
            print("(sigma_a/N**2)/num =", (self.sigma_a/P.N**2)/self.num)

            if vapp < 0.2:
                vapp += 0.01
            else:
                vapp = 0.2

            V = self.psi0 + vapp / C.VT  # normalized applied voltage
            print("vapp =", vapp, "V=", V, "psi0=", self.psi0)

            _, self.psi = self.electrode(self.boundary, self.psi, V, self.psi0)  # 印可電圧更新
            ion = Ion(P.h, self.boundary, self.dict_a, self.dict_b, self.a0, self.row, self.col)

            # self-consistent loop
            while True:
                # solve Poisson equation & continuity equations
                self.psi, residue = poisson(P.ETA, self.p, self.n, self.c, self.psi, self.boundary)
                self.p = carrier.continuity(self.psi, self.p0)
                self.n = carrier.continuity(-self.psi, self.n0)
                # converge?
                print("         psi residue:", residue)
                if residue < P.TOLERANCE:
                    break

            self.Nd, self.courant_cond = ion.execute(self.Nd, self.psi, P.Nd0_)
            self.sigma_a += self.courant_cond
            self.c = np.add(self.Nd, -self.Na)



            # evaluate current
            self.jp = current(self.psi, self.p, self.jp)
            self.jp *= -P.UJP
            self.jn = current(-self.psi, self.n, self.jn)
            self.jn *=  P.UJN

            self.j = np.add(self.jp, self.jn)


            jp_list.append(self.jp[int(P.N/2), int(P.N/2)])
            jn_list.append(self.jn[int(P.N/2), int(P.N/2)])
            vapp_list.append(vapp)


            

            if count_for_render % 10 == 0:
                if not os.path.exists(path_to_save):
                    os.makedirs(path_to_save)
                os.chdir(path_to_save)

                np.savetxt('IV.txt',
                np.column_stack([vapp_list, jp_list, jn_list, np.add(jp_list, jn_list)]), fmt='%15.8e')

                render(path_to_save, self.psi, self.Nd, self.j, self.p, 
                    self.n, self.boundary, count_for_render, vapp)
                

            count_for_render += 1
Пример #21
0
    def shoot(self):
        gun = -1
        for i in range(len(self.equipped)):
            if self.equipped[i].gun and self.equipped[i].gun.ammo > 0:
                gun = i
        if not gun==-1:
            class Target:
                def __init__(self, x, y):
                    self.x = x
                    self.y = y
            target = Target(self.x, self.y)
            libtcod.console_blit(cons.game_console,0,0,M.MAP_WIDTH,M.MAP_HEIGHT,0,0,0,1)
            libtcod.console_flush()
            key = libtcod.console_wait_for_keypress(True)
            while not key.vk == libtcod.KEY_SPACE:
                R.render()
                if key.pressed:
                    if ord('k') == key.c:
                        target.y=target.y-1
                    elif ord('j') == key.c:
                        target.y=target.y+1
                    elif ord('h') == key.c:
                        target.x=target.x-1
                    elif ord('l') == key.c:
                        target.x=target.x+1
                    elif ord('y') == key.c:
                        target.x=target.x-1
                        target.y=target.y-1
                    elif ord('u') == key.c:
                        target.x=target.x+1
                        target.y=target.y-1
                    elif ord('i') == key.c:
                        target.x=target.x-1
                        target.y=target.y+1
                    elif ord('o') == key.c:
                        target.x=target.x+1
                        target.y=target.y+1
                libtcod.line_init(self.x, self.y, target.x, target.y)
                x,y=libtcod.line_step()

                # Clear the console that shows our target line.
                libtcod.console_clear(cons.gun_console)
                # Draw the target line on the gun console.
                while (not x is None):
                    if (M.gameworld[x][y].is_floor() and
                        libtcod.map_is_in_fov (player.fov, x, y)
                       ):
                        libtcod.console_set_char_background(cons.gun_console, x, y,
                            libtcod.white, libtcod.BKGND_OVERLAY)
                        target.x=x
                        target.y=y
                        x,y=libtcod.line_step()
                    else:
                        break
                # Draw the gun console to the root console.
                libtcod.console_blit(cons.gun_console,0,0,M.MAP_WIDTH,M.MAP_HEIGHT,0,0,0,0,0.5)
                libtcod.console_flush()
                key = libtcod.console_wait_for_keypress(True)
            self.equipped[gun].gun.fire(self.x, self.y, target.x, target.y)
        else:
            S.add_status("No gun in hand!")
Пример #22
0
def train():
    parser = config_parser()
    args = parser.parse_args()

    # Create log dir and copy the config file
    basedir = args.basedir
    expname = args.savedir if args.savedir else args.expname
    print('Experiment dir:', expname)

    # Load data
    images, poses, style, i_test, i_train, bds_dict, dataset, hwfs, near_fars, style_inds = load_data(
        args)
    _, poses_test, style_test, hwfs_test, nf_test = images[i_test], poses[
        i_test], style[i_test], hwfs[i_test], near_fars[i_test]
    _, poses_train, style_train, hwfs_train, nf_train = images[i_train], poses[
        i_train], style[i_train], hwfs[i_train], near_fars[i_train]

    os.makedirs(os.path.join(basedir, expname), exist_ok=True)

    np.save(os.path.join(basedir, expname, 'poses.npy'), poses_train.cpu())
    np.save(os.path.join(basedir, expname, 'hwfs.npy'), hwfs_train.cpu())
    f = os.path.join(basedir, expname, 'args.txt')
    with open(f, 'w') as file:
        for arg in sorted(vars(args)):
            attr = getattr(args, arg)
            file.write('{} = {}\n'.format(arg, attr))
    if args.config is not None:
        f = os.path.join(basedir, expname, 'config.txt')
        with open(f, 'w') as file:
            file.write(open(args.config, 'r').read())

    # Create nerf model
    render_kwargs_train, render_kwargs_test, start, grad_vars, optimizer = create_nerf(
        args)

    print(render_kwargs_train['network_fine'])
    old_coarse_network = copy.deepcopy(
        render_kwargs_train['network_fn']).state_dict()
    old_fine_network = copy.deepcopy(
        render_kwargs_train['network_fine']).state_dict()

    global_step = start
    real_image_application = (args.real_image_dir is not None)
    optimize_mlp = not real_image_application
    render_kwargs_train.update(bds_dict)
    render_kwargs_test.update(bds_dict)
    loss = None

    if start == 0:
        # if we're starting from scratch, delete all the logs in that directory.
        if os.path.exists(os.path.join(basedir, expname, 'log.txt')):
            os.remove(os.path.join(basedir, expname, 'log.txt'))
    start = start + 1

    for i in range(start, args.n_iters + 1):
        # Sample random ray batch
        batch_rays, target_s, style, H, W, focal, near, far, viewdirs_reg = dataset.get_data_batch(
            train_fn=render_kwargs_train, optimizer=optimizer, loss=loss)
        render_kwargs_train.update({'near': near, 'far': far})

        #####  Core optimization loop  #####
        rgb, disp, acc, extras = render(H,
                                        W,
                                        focal,
                                        style=style,
                                        chunk=args.chunk,
                                        rays=batch_rays,
                                        viewdirs_reg=viewdirs_reg,
                                        **render_kwargs_train)
        optimizer.zero_grad()

        img_loss = img2mse(rgb, target_s)
        loss = img_loss
        psnr = mse2psnr(img_loss)

        if args.var_param > 0:
            var = extras['var']
            var0 = extras['var0']
            var_loss = var.mean(dim=0)
            var_loss_coarse = var0.mean(dim=0)

            loss += args.var_param * var_loss
            loss += args.var_param * var_loss_coarse
            var_loss = var_loss.item()
            var_loss_coarse = var_loss_coarse.item()
        else:
            var_loss = 0
            var_loss_coarse = 0

        if 'rgb0' in extras:
            img_loss0 = img2mse(extras['rgb0'], target_s)
            loss = loss + img_loss0
            psnr0 = mse2psnr(img_loss0).item()
        else:
            psnr0 = -1

        if args.weight_change_param >= 0:
            weight_change_loss_coarse = 0.
            for k, v in render_kwargs_train['network_fn'].named_parameters():
                if 'weight' in k:
                    diff = (old_coarse_network[k] - v).pow(2).mean()
                    weight_change_loss_coarse += diff
            weight_change_loss_fine = 0.
            for k, v in render_kwargs_train['network_fine'].named_parameters():
                if 'weight' in k:
                    diff = (old_fine_network[k] - v).pow(2).mean()
                    weight_change_loss_fine += diff
            weight_change_loss = weight_change_loss_coarse + weight_change_loss_fine
            loss = loss + args.weight_change_param * weight_change_loss
        else:
            weight_change_loss = torch.tensor(0.)

        loss.backward()
        if optimize_mlp:
            optimizer.step()

        # NOTE: IMPORTANT!
        decay_rate = 0.1
        decay_steps = args.lrate_decay * 1000
        new_lrate = args.lrate * (decay_rate**(global_step / decay_steps))

        for param_group in optimizer.param_groups:
            param_group['lr'] = new_lrate
        ################################
        #####           end            #####

        if i % args.i_weights == 0:
            path = os.path.join(basedir, expname, '{:06d}.tar'.format(i))
            state_dict = {
                'global_step':
                global_step,
                'network_fn_state_dict':
                render_kwargs_train['network_fn'].state_dict(),
                'optimizer_state_dict':
                optimizer.state_dict(),
                'styles':
                dataset.style,
                'style_optimizer':
                dataset.style_optimizer.state_dict()
            }
            if args.N_importance > 0:
                state_dict['network_fine_state_dict'] = render_kwargs_train[
                    'network_fine'].state_dict()
            torch.save(state_dict, path)
            print('Saved checkpoints at', path)

        if i % args.i_testset == 0 and i > 0:
            if real_image_application:
                style_test = dataset.get_features().repeat(
                    (poses_test.shape[0], 1))
            testsavedir = os.path.join(basedir, expname,
                                       'testset_{:06d}'.format(i))
            os.makedirs(testsavedir, exist_ok=True)
            with torch.no_grad():
                render_path(poses_test.to(device),
                            style_test,
                            hwfs_test,
                            args.chunk,
                            render_kwargs_test,
                            nfs=nf_test,
                            savedir=testsavedir,
                            maximum=100)
            print('Saved test set')

        if i % args.i_trainset == 0 and i > 0:
            if real_image_application:
                style_train = dataset.get_features().repeat(
                    (poses_train.shape[0], 1))
            trainsavedir = os.path.join(basedir, expname,
                                        'trainset_{:06d}'.format(i))
            os.makedirs(trainsavedir, exist_ok=True)
            with torch.no_grad():
                render_path(poses_train.to(device),
                            style_train,
                            hwfs_train,
                            args.chunk,
                            render_kwargs_test,
                            nfs=nf_train,
                            savedir=trainsavedir,
                            maximum=100)
            print('Saved train set')

        if i % args.i_print == 0 or i == 1:
            log_str = f"[TRAIN] Iter: {i} Loss: {loss.item()} PSNR: {psnr.item()} PSNR0: {psnr0} Var loss: {var_loss} Var loss coarse: {var_loss_coarse} Weight change loss: {weight_change_loss}"
            with open(os.path.join(basedir, expname, 'log.txt'), 'a+') as f:
                f.write(log_str + '\n')
            print(log_str)

        global_step += 1

        if real_image_application and global_step - start == args.n_iters_real:
            return

        if real_image_application and global_step - start == args.n_iters_code_only:
            optimize_mlp = True
            dataset.optimizer_name = 'adam'
            dataset.style_optimizer = torch.optim.Adam(dataset.params,
                                                       lr=dataset.lr)
            print('Starting to jointly optimize weights with code')
Пример #23
0
def handle_keys (key):
    global turncount

    # Has a turn been accomplished?
    turn=False

    # Exit the game on escape.
    if libtcod.KEY_ESCAPE == key.vk:
        return True
    if P.player.health > 0:
        if ord('h') == key.c:
            P.player.move (-1, 0)
            turn = True
        elif ord('j') == key.c :
            P.player.move (0, 1)
            turn = True
        elif ord('k') == key.c :
            P.player.move (0, -1)
            turn = True
        elif ord('l') == key.c :
            P.player.move (1, 0)
            turn = True
        elif ord('y') == key.c :
            P.player.move (-1, -1)
            turn = True
        elif ord('u') == key.c :
            P.player.move (1, -1)
            turn = True
        elif ord('i') == key.c :
            P.player.move (-1, 1)
            turn = True
        elif ord('o') == key.c :
            P.player.move (1, 1)
            turn = True
        elif ord('c') == key.c :
            show_player_stats()
        elif ord(',') == key.c :
            P.player.pick_up()
        elif ord('.') == key.c :
            P.player.show_inventory()
        elif ord('d') == key.c :
            P.player.drop()
        elif ord('z') == key.c :
            P.player.shoot()
            turn = True
        if turn:
            # Move all enemies toward the player.
            characters = []
            for y in range (M.MAP_HEIGHT):
                for x in range (M.MAP_WIDTH):
                    for character in M.gameworld[x][y].characters:
                        characters.append(character)

            for character in characters:
                if character.npc and P.player.health > 0 and random.random() <= M.ZOMBIE_MOVE_CHANCE:
                    path = libtcod.path_new_using_map(P.player.fov)
                    # Compute the path between the hostile object and the player.
                    libtcod.path_compute(path, character.x, character.y,
                      P.player.x, P.player.y)
                    if libtcod.path_size(path) < 100:
                        libtcod.path_walk(path, True)
                        character.move_to_coordinates(libtcod.path_get_origin(path)[0],
                                libtcod.path_get_origin(path)[1])
            #spawn a new zombie
            if random.random() <= M.ENEMY_SPAWN_CHANCE:
                x,y=find_blind_open_tile()
                C.Character('Zombie',
                          random.randint(5,20),
                          x, y,
                          "Z",
                          libtcod.black,
                          npc=True)
                if random.random() <= 0.20:
                    Item ('cheap revolver', x, y, 'r', libtcod.red, gun=Gun(5, 0.6))
                    M.gameworld[x][y].characters[0].pick_up()
                if random.random() <= 0.02:
                    Item ('silver revolver', x, y, 'r', libtcod.cyan, gun=Gun(15, 0.9))
                    M.gameworld[x][y].characters[0].pick_up()
                if random.random() <= 0.10:
                    Item ('medkit', x, y, 'H', libtcod.red, health=Health(100))
                    M.gameworld[x][y].characters[0].pick_up()
            turncount = turncount + 1
            if P.player.health < P.player.max_health:
                P.player.health = P.player.health + 1
    ## Add items in the current tile to the status.
    # for item in M.gameworld[player.x][player.y].items:
    #       add_status("A %s."% (item.name))
    ## Add items in the current tile to the items indicator.
    add_items()
    # Render events.
    R.render()
    # Clear the status string.
    if turn:
        S.clear_status()
    # If there are items on the player's current tile, draw them to the screen.
    if items_here():
        draw_items()
    # Clear the list of current tile items.
    clear_items()
    # Return False if the game should still play.
    return False
Пример #24
0
    def render(self, surface: Any) -> None:
        """Renders the entity."""

        if self.visible:
            rendering.render(surface, self.graphic, self.x, self.y, self.color,
                             self.bgcolor)
Пример #25
0
        def render(self, surface: Any, drugs: list[tuple[str, dict]]) -> None:
            rendering.render(surface, "Use which drug?", self.x, self.y,
                             (0, 255, 0))

            self.print_items(drugs, surface)
Пример #26
0
    def main_function(self, path_to_save):
        j_list_rec1 = []
        j_list_rec2 = []
        j_list_all = []
        j_list_line = []
        j_list_surr = []
        vapp_list = []

        v_read = 0.05
        V = self.psi0 + v_read / C.VT  # normalized applied voltage

        print("  vapp =", v_read, "V=", V, "psi0=", self.psi0)

        carrier = ContinuityEquation(self.boundary, self.dict_a, self.dict_b,
                                     self.a0, self.b0, self.row, self.col)
        os.chdir("C:/Users/sakailab/Desktop/nagata/0225/two_elec/cycle1")
        filenames = glob.glob("Nd_*.txt")
        print("{} files were found.".format(len(filenames)))
        for name in filenames:
            print("loading Nd from {}.".format(name))

            filename = {"Nd": name}
            self.load("C:/Users/sakailab/Desktop/nagata/0225/two_elec/cycle1/",
                      filename,
                      eraseT24=False)

            if name[3:8].isdigit():
                count = int(name[3:8])
            else:
                print("count not understood.")
            print("file number: {}".format(count))

            _, self.psi = self.electrode(self.boundary, self.psi, V,
                                         self.psi0)  # 印可電圧更新

            # self-consistent loop
            while True:
                # solve Poisson equation & continuity equations
                self.psi, residue = poisson(P.ETA, self.p, self.n, self.c,
                                            self.psi, self.boundary)
                self.p = carrier.continuity(self.psi, self.p0)
                self.n = carrier.continuity(-self.psi, self.n0)
                # converge?
                print("         psi residue:", residue)
                if residue < P.TOLERANCE:
                    break

            # evaluate current
            self.jp = current(self.psi, self.p, self.jp)
            self.jp *= -P.UJP
            self.jn = current(-self.psi, self.n, self.jn)
            self.jn *= P.UJN

            self.j = np.add(self.jp, self.jn)

            vapp_list.append(float(name[11:-4]))

            j_list_rec1.append(np.sum(self.j[72:98, 72:98].flatten()))
            R_list_rec1 = [V / j_ for j_ in j_list_rec1]

            j_list_rec2.append(np.sum(self.j[62:108, 62:108].flatten()))
            R_list_rec2 = [V / j_ for j_ in j_list_rec2]

            j_list_all.append(np.sum(self.j.flatten()))
            R_list_all = [V / j_ for j_ in j_list_all]

            _row = range(72, 98)
            _col = range(72, 98)
            region = np.stack((_row, _col), axis=1)
            sum_j = 0
            for r in region:
                ii, jj = int(r[0]), int(r[1])
                sum_j += self.j[ii, jj]
            j_list_line.append(sum_j)
            R_list_line = [V / j_ for j_ in j_list_line]

            sum_j = 0
            left_r = range(97, 158)
            for ii in left_r:
                sum_j += self.j[ii, 97]
            right_r = range(98, 159)
            for ii in right_r:
                sum_j += self.j[ii, 158]
            up_c = range(98, 159)
            for jj in up_c:
                sum_j += self.j[97, jj]
            down_c = range(97, 158)
            for jj in up_c:
                sum_j += self.j[158, jj]
            j_list_surr.append(sum_j)
            R_list_surr = [V / j_ for j_ in j_list_surr]

            if not os.path.exists(path_to_save):
                os.makedirs(path_to_save)
            os.chdir(path_to_save)

            render(path_to_save, self.psi, self.Nd, self.j, self.p, self.n,
                   self.boundary, count, v_read)

        np.savetxt('IV_rec1.txt',
                   np.column_stack([vapp_list, j_list_rec1, R_list_rec1]),
                   fmt='%15.8e')

        np.savetxt('IV_rec2.txt',
                   np.column_stack([vapp_list, j_list_rec2, R_list_rec2]),
                   fmt='%15.8e')

        np.savetxt('IV_all.txt',
                   np.column_stack([vapp_list, j_list_all, R_list_all]),
                   fmt='%15.8e')

        np.savetxt('IV_line.txt',
                   np.column_stack([vapp_list, j_list_line, R_list_line]),
                   fmt='%15.8e')

        np.savetxt('IV_surr.txt',
                   np.column_stack([vapp_list, j_list_surr, R_list_surr]),
                   fmt='%15.8e')

        np.savetxt('Vapp.txt', vapp_list, fmt='%15.8e')
Пример #27
0
        def render(self, surface: Any,
                   power_sources: list[tuple[str, dict]]) -> None:
            rendering.render(surface, "Charge with which power-source?",
                             self.x, self.y, (0, 255, 0))

            self.print_items(power_sources, surface)
Пример #28
0
        def render(self, surface: Any) -> None:
            # Makes little barrier
            for i in range(self.height):
                rendering.render(surface, chr(9474), self.x, self.y + i,
                                 (0, 255, 0))

            # Shows who you are
            rendering.render(
                surface,
                f"{self.player.name}\nThe {self.player.race} {self.player.class_name}",
                self.x + 2, self.y + 1, (0, 255, 255))

            # Show stats
            rendering.render(surface, (
                f"HP: {self.player.health}        MP: {self.player.mp}\n"
                f"Charge: {self.player.charge_percent}%    AC: {self.player.ac}"
            ), self.x + 2, self.y + 5, (128, 0, 128))

            # Show attributes
            rendering.render(surface, (
                f"Muscle: {self.player.muscle}     Smarts: {self.player.smarts}\n"
                f"Reflexes: {self.player.reflexes}   Charm: {self.player.charm}\n"
                f"Grit: {self.player.grit}       Wits: {self.player.wits}"),
                             self.x + 2, self.y + 10, (255, 192, 203))

            # Show worn
            wielding_: str
            if self.player.wielding is None:
                wielding_ = "Unarmed"
            else:
                wielding_ = self.player.wielding.name

                if self.player.wielding.distance == "RANGED":
                    rendering.render(
                        surface,
                        f"[{self.player.wielding.rounds_in_mag}/{self.player.wielding.mag_capacity}]",
                        self.x + 17, self.y + 16, (255, 255, 255))

            rendering.render(
                surface,
                f"Wielding: {wielding_}\nWearing: {self.player.wearing}",
                self.x + 2, self.y + 16, (255, 255, 255))

            # Show currency
            rendering.render(surface, f"Smokes: {self.player.smokes}",
                             self.x + 2, self.y + 18, (255, 215, 0))

            # Show game stats
            rendering.render(surface,
                             f"Floor: {self.floor}       Time: {self.time}",
                             self.x + 2, self.y + 22, (255, 63, 0))
Пример #29
0
 def render(self, surface: Any, thing: Any) -> None:
     rendering.render(surface, thing.name, self.x, self.y, (0, 255, 0))
     rendering.render(surface, thing.desc, self.x, self.y + 2,
                      (255, 255, 255))
Пример #30
0
## Changes the keyboard repeat delay.
# libtcod.console_set_keyboard_repeat(0, 0)
###############
## Game loop ##
###############

while not libtcod.console_is_window_closed ():
    if not firstRun:
        key = libtcod.console_check_for_keypress(libtcod.KEY_PRESSED)
        #key = libtcod.console_wait_for_keypress(True)
    else:
        # If this is the first run of the game, then build a game world and place
        # the player on it.
        key = libtcod.console_check_for_keypress()
#    M.gameworld = [[Tile(floor=False) for y in range (M.MAP_HEIGHT)]
#        for x in range (M.MAP_WIDTH)]
        bsp = bspgen.Bsp(M.MAP_WIDTH,M.MAP_HEIGHT, M.gameworld)
        bsp.render_bsp()
        place_player()
        add_items()
        S.display_status()
        R.render()
        draw_items()
        clear_items()

    if handle_keys (key):
        break
    firstRun = False
    libtcod.console_flush ()
Пример #31
0
        def render(self, surface: Any, throwables: list[tuple[str,
                                                              dict]]) -> None:
            rendering.render(surface, "Throw which item?", self.x, self.y,
                             (0, 255, 0))

            self.print_items(throwables, surface)