Skip to main content

Installation

pip install tankwar-env

or

git clone https://github.com/khoda81/tankwar.git
cd tankwar
pip install -e

or

pip install git+https://github.com/khoda81/tankwar.git

Keyboard

  • Environment:
    • Esc : set env.done to True (end episode on next step)
    • F : toggle limited frame rate

  • HumanAgent:
    • W A S D : movement
    • Q E : rotate turret
    • Space : toggle shooting
    • Left Mouse Button : start shooting when pressed and stop shooting when released

  • Script:
    • G : toggle window update (disabling window update will blur window and increase performance)

Basic Usage

import pygame

from tankwar.agents import HumanAgent, RandomAgent
from tankwar.envs import TankWarEnv


def main():
    random_agents = 2

    # create environment
    env = TankWarEnv(random_agents + 1, shape=(200, 200))

    # create agents
    agents = [HumanAgent(env)] + [RandomAgent(env) for _ in range(random_agents)]

    # initialize a window with the height of 200
    # width is calculated based on env.shape
    # limit frame rate to 60 if a human is playing
    env.init_window(600, True)
    done = False

    # reset environment
    observations = env.reset()
    display_to_human = True

    while True:
        if display_to_human:
            env.render("human")  # render to screen
        else:
            # if render is not called window events are not processed either
            # so, manually processing window events
            env.process_window_events()

        actions = [
            agent.act((None, None), 0, done)
            for agent in agents
        ]

        observations, rewards, done, info = env.step(actions, print_fps=True)

        # if g is pressed screen is toggled
        # disabling screen will make rendering faster
        # because copying frame to window takes time
        for event in env.events:
            if event.type == pygame.KEYDOWN and event.key == pygame.K_g:
                display_to_human = not display_to_human

                if not display_to_human:
                    env.blur_window()

        if done:
            break


if __name__ == "__main__":
    main()

Main Usage

import time

import pygame
import torch
from torch.nn.functional import interpolate
from tqdm import tqdm

from tankwar.agents import HumanAgent, RandomAgent
from tankwar.envs import TankWarEnv

MAX_EPISODE_STEPS = 5000


def main():
    random_agents = 2
    human_agent = False  # whether or not a human is currently playing
    display_to_human = human_agent

    # create environment
    env = TankWarEnv(random_agents + human_agent, shape=(200, 200))
    w, h = env.shape

    # create agents
    agents = (
            [HumanAgent(env)] * human_agent +
            [RandomAgent(env) for _ in range(random_agents)])

    # initialize a window with the height of 200
    # width is calculated based on env.shape
    # limit frame rate to 60 if a human is playing
    env.init_window(h, human_agent)
    padded_frame = torch.zeros(3, w + 200, h + 200)

    observations = env.reset()
    done = False

    rewards = [0] * env.n

    s = time.time()
    for _ in tqdm(range(MAX_EPISODE_STEPS), unit="step"):
        # render to screen
        if display_to_human:
            env.render("human")

        # convert frame to pytorch tensor with shape (3, height, width)
        # frames are cached and will be rendered once per step
        frame = env.render("rgb_array")
        frame_torch = (torch.from_numpy(frame) / 255).permute(2, 0, 1)

        # each frame will be down sampled to (w, h)
        if env.window_scale != 1:
            frame_torch = interpolate(frame_torch.reshape(1, *frame_torch.shape), (h, w))[0]
        # with 100 pixels padding on each side:
        padded_frame[:, 100:-100, 100:-100] = frame_torch

        # image that each agent can see
        images = []
        for i, tank in enumerate(env.tanks):
            x, y = tank.body.position.int_tuple
            images.append(padded_frame[:, y:y + 200, x:x + 200])

        actions = [
            agent.act((observation, image), reward, done)
            for agent, observation, image, reward
            in zip(agents, observations, images, rewards)
        ]

        observations, rewards, done, info = env.step(actions)

        # if g is pressed screen is toggled
        # disabling screen will make rendering faster
        # because copying frame to window takes time
        for event in env.events:
            if event.type == pygame.KEYDOWN and event.key == pygame.K_g:
                display_to_human = not display_to_human

                if not display_to_human:
                    env.blur_window()

        if done:
            break

    print(f"Episode took {time.time() - s:.2f} seconds.")


if __name__ == "__main__":
    main()

Metadata

Release files for tankwar-env 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tankwar-env 1.0.1
File Size Uploaded Provenance
tankwar-env-1.0.1.tar.gz 9.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for tankwar-env 1.0.1
File Interpreter ABI Platform
tankwar_env-1.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 19.4 kB

Release files / tankwar-env-1.0.1.tar.gz

Download URL tankwar-env-1.0.1.tar.gz
Size 9.9 kB
Tags Source
SHA-256 checksum
How to use checksums
dd59c0debb551e122e2d54ed2080480ad2fedc257df78732af9ea5e5bf4f8bd8
BLAKE2b-256 checksum
How to use checksums
f7dde23933573a4b3c6bca3c316981b282d7b62c57e0ee9074a23b279bb5364e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7

Release files / tankwar_env-1.0.1-py3-none-any.whl

Download URL tankwar_env-1.0.1-py3-none-any.whl
Size 9.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4a4a3f8799de4a652428fc19ad99a065db7af540206647688afb183c421c9166
BLAKE2b-256 checksum
How to use checksums
ea85c4ba6f45182b0891cd5decd4e950f9236d950f6cd683b7928e972e85454c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.9.7

Security for tankwar-env 1.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

1.0.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page