ml-agents icon indicating copy to clipboard operation
ml-agents copied to clipboard

Training to beat "asteroids like" game

Open MDReptile opened this issue 8 years ago • 7 comments

Hey guys, I'm not sure where else to post this, where I might get help, so figured I'd start here.

I'm working on creating an AI to play an old android game I made called Asteroid Buster. It is essentially a slightly more advanced version of the classic asteroids gameplay, with powerups.

See the game here: https://play.google.com/store/apps/details?id=com.NinjeticStudios.AsteroidBusterReboot

In this game I've given the agent discrete controls to use the joystick to go up, down, left, or right, as well as fire and thrust the ship.

I give the agent only the positions of the ship, and the asteroids. I tried also giving him velocities, but I felt that might have been too much info, and confused him?

I reward for blowing up asteroids, and beating "waves". I punish for being hit by an asteroid and dying.

I'm hoping I've made some mistakes you guys can spot, because under these conditions I've ran him for almost 2.5 million steps, but so far he only has managed to train well enough to sometimes make it into the fifth wave, while I hope to have him train well enough to make it sometimes into much higher waves, hopefully surpassing the best human players who have ever played. But training him seems to be slowing down, even kind of hitting a ceiling of peak performance I suppose.

Now I have to train him in real time, and only a single agent at a time, because the old game depends a lot of stuff happening in Update, and might get de-synched variables and stuff if I turn up the timescale, and only one at a time because the game uses the edges of the screen as the border of the world, wrapping asteroids or the ship to the other side if they pass it (just like old school asteroids).

Here is how I've set up my agent:


` using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;

public class AstroAgent : Agent { public static AstroAgent Instance;

public Vector2 JoyDir = Vector2.zero;

[SerializeField]
private Vector2 shipVelocity, shipPosition;
[SerializeField]
private List<Vector2> asteroidPositions;//, asteroidVelocities;
[SerializeField]
private Text text;

int score;
int solved, died;

//float survivalTime = 0;

bool actionLeft = false, actionRight = false, actionUp = false, actionDown = false, actionFire = false, actionThrust = false;

GameLogicScript gls;

public override void InitializeAgent()
{
    Instance = this;
    gls = GameLogicScript.Instance;

    asteroidPositions = new List<Vector2>();
    //asteroidVelocities = new List<Vector2>();
}

public override List<float> CollectState()
{
    // 4 + (4 * 30) = 124 = total number of states

    List<float> state = new List<float>();
    //state.Add(shipVelocity.x);
    //state.Add(shipVelocity.y);
    state.Add(shipPosition.x);
    state.Add(shipPosition.y);
    for(int i = 0; i < 30; i++)
    {
        if (asteroidPositions.Count > i)
        {
            state.Add(asteroidPositions[i].x);
            state.Add(asteroidPositions[i].y);
        }
        else
        {
            state.Add(0); // give blank info because there aren't 30 asteroids right now active
            state.Add(0);
        }
    }
    return state;
}

int lastLevel = 2; // the last level we reached (starts at 2 because 

public override void AgentStep(float[] action)
{
    switch ((int)action[0])
    {
        case 0:
            //currentNumber -= 0.01f;
            actionLeft = true;
            actionRight = false;
            actionUp = false;
            actionDown = false;
            actionFire = false;
            actionThrust = false;
            break;
        case 1:
            //currentNumber += 0.01f;
            actionLeft = false;
            actionRight = true;
            actionUp = false;
            actionDown = false;
            actionFire = false;
            actionThrust = false;
            break;
        case 2:
            actionLeft = true;
            actionRight = false;
            actionUp = false;
            actionDown = false;
            actionFire = false;
            actionThrust = true;
            break;
        case 3:
            actionLeft = false;
            actionRight = true;
            actionUp = false;
            actionDown = false;
            actionFire = false;
            actionThrust = true;
            break;
        case 4:
            actionLeft = true;
            actionRight = false;
            actionUp = false;
            actionDown = false;
            actionFire = true;
            actionThrust = true;
            break;
        case 5:
            actionLeft = false;
            actionRight = true;
            actionUp = false;
            actionDown = false;
            actionFire = true;
            actionThrust = true;
            break;
        case 6:
            actionLeft = true;
            actionRight = false;
            actionUp = false;
            actionDown = false;
            actionFire = true;
            actionThrust = false;
            break;
        case 7:
            actionLeft = false;
            actionRight = true;
            actionUp = false;
            actionDown = false;
            actionFire = true;
            actionThrust = false;
            break;
        case 8:
            actionLeft = false;
            actionRight = false;
            actionUp = true;
            actionDown = false;
            actionFire = false;
            actionThrust = false;
            break;
        case 9:
            actionLeft = false;
            actionRight = false;
            actionUp = false;
            actionDown = true;
            actionFire = false;
            actionThrust = false;
            break;
        case 10:
            actionLeft = false;
            actionRight = false;
            actionUp = true;
            actionDown = false;
            actionFire = false;
            actionThrust = true;
            break;
        case 11:
            actionLeft = false;
            actionRight = false;
            actionUp = false;
            actionDown = true;
            actionFire = false;
            actionThrust = true;
            break;
        case 12:
            actionLeft = false;
            actionRight = false;
            actionUp = true;
            actionDown = false;
            actionFire = true;
            actionThrust = true;
            break;
        case 13:
            actionLeft = false;
            actionRight = false;
            actionUp = false;
            actionDown = true;
            actionFire = true;
            actionThrust = true;
            break;
        case 14:
            actionLeft = false;
            actionRight = false;
            actionUp = true;
            actionDown = false;
            actionFire = true;
            actionThrust = false;
            break;
        case 15:
            actionLeft = false;
            actionRight = false;
            actionUp = false;
            actionDown = true;
            actionFire = true;
            actionThrust = false;
            break;
        case 16:
            actionLeft = false;
            actionRight = false;
            actionUp = false;
            actionDown = false;
            actionFire = false;
            actionThrust = false;
            break;
        default:
            return;
    }

    //cube.position = new Vector3(currentNumber * 5f, 0, 0);
    // take input and apply it
    if (actionLeft)
    {
        // turn ship left
        JoyDir.x = -1;
    }
    else if (actionRight)
    {
        // turn ship right
        JoyDir.x = 1;
    }
    else if (actionUp)
    {
        // turn to go up
        JoyDir.y = 1;
    }
    else if (actionDown)
    {
        // turn to go down
        JoyDir.y = -1;
    }
    else // no dir input
        JoyDir = Vector2.zero;

    if (actionThrust)
    {
        // thrust ship
        gls.GetShipScript().ThrustHit = true;
    }
    else
        gls.GetShipScript().ThrustHit = false;

    if (actionFire)
    {
        // fire ship
        gls.GetShipScript().FireButtonHit();
    }
    else if (gls.GetShipScript().fireDown)
        gls.GetShipScript().FireButtonReleased();

    //if (currentNumber < -1.2f || currentNumber > 1.2f)
    if(!gls.GetShipScript().Alive && gls.PlayerReady)
    {
        Debug.Log("Fail");
        died++;
        gls.PlayerReady = false;
        reward -= 0.5f; // failure
        rewardLast = reward;
        done = true; // reset will be called
        return;
    }

    if (gls.currentLevel > lastLevel)
    {
        Debug.Log("Success, level up");
        solved++;
        reward += 1; // success
        lastLevel = gls.currentLevel;
        rewardLast = reward;
        // don't quit, keep playing?
        //done = true;
        //return;
    }

    // get important info to the ai
    asteroidPositions.Clear();
    //asteroidVelocities.Clear();
    for (int i = 0; i < gls.Asteroids.Count; i++)
    {
        if (gls.Asteroids[i] != null)
        {
            asteroidPositions.Add(gls.Asteroids[i].transform.position);
            //asteroidVelocities.Add(gls.Asteroids[i].GetComponent<Rigidbody>().velocity);
        }
    }
    shipPosition = gls.PlayerShip.transform.position;
    shipVelocity = gls.PlayerShip.GetComponent<Rigidbody>().velocity;
    if (died != 0 || solved != 0)
        successPercent = ((float)solved / ((float)died + solved)) * 100.0f;

    if(GameLogicScript.wave > highestWave)
        highestWave = GameLogicScript.wave;

    if (GameLogicScript.score > highestScore)
        highestScore = GameLogicScript.score;

    // a gui for info about progress
    text.text = string.Format("Total Waves: {0} | Total Deaths: {1} {2}Success %: {3} | Last Reward: {4} {5}Highest Wave: {6} | Highest Score: {7}", solved, died, 
        System.Environment.NewLine, successPercent, rewardLast, System.Environment.NewLine, highestWave, highestScore);
}

float successPercent = 0, rewardLast;
int highestWave = 0, highestScore;

public void GotPoints(int points)
{
    float r = 0.01f * (points / 100);
    Debug.Log("success - reward: " + r);
    reward += r;
    rewardLast = reward;
}

public override void AgentReset()
{
    if (gls == null)
        gls = GameLogicScript.Instance;
    gls.AgentResetGame(); // restart the game from wave 1 if the agent dies
    asteroidPositions.Clear();
    lastLevel = 2;
    Debug.Log("Reset Agent");
}

} `


And here is how I've set up my PPO:


`

General parameters

max_steps = 3000000 # Set maximum number of steps to run environment. run_path = "ppo" # The sub-directory name for model and summary statistics load_model = True # Whether to load a saved model. train_model = True # Whether to train the model. summary_freq = 10000 # Frequency at which to save training statistics. save_freq = 50000 # Frequency at which to save model. env_name = "TestBuild" # Name of the training environment file. curriculum_file = None

Algorithm-specific parameters for tuning

gamma = 0.99 # Reward discount rate. lambd = 0.95 # Lambda parameter for GAE. time_horizon = 2048 # How many steps to collect per agent before adding to buffer. beta = 1e-3 # Strength of entropy regularization num_epoch = 5 # Number of gradient descent steps per batch of experiences. num_layers = 4 # Number of hidden layers between state/observation encoding and value/policy layers. epsilon = 0.2 # Acceptable threshold around ratio of old and new policy probabilities. buffer_size = 2048 # How large the experience buffer should be before gradient descent. learning_rate = 3e-4 # Model learning rate. hidden_units = 256 # Number of units in hidden layer. batch_size = 256 # How many experiences per gradient descent update step. normalize = False

Logging dictionary for hyperparameters

hyperparameter_dict = {'max_steps':max_steps, 'run_path':run_path, 'env_name':env_name, 'curriculum_file':curriculum_file, 'gamma':gamma, 'lambd':lambd, 'time_horizon':time_horizon, 'beta':beta, 'num_epoch':num_epoch, 'epsilon':epsilon, 'buffe_size':buffer_size, 'leaning_rate':learning_rate, 'hidden_units':hidden_units, 'batch_size':batch_size} `


Any idea why things aren't working very well? Any idea how I could improve his learning? Should I use controls that allow him to rotate left and right, rather than point towards cardinal directions? Should I change from discrete to continuous action space? Is it just too complex of a scenario that I'm trying to solve with too simple of a control scheme? Maybe I shouldn't send blank data to him like that when there are only a few asteroids, but if I didn't, the game gets an error that the size of data didn't match up, so I figured just send it zeroes?

Maybe I should make it dumber, with just "rotate left" and "rotate right" and "thrust" actions, while always shooting? He seems to always be shooting anyway (or as fast as the game allows the ship to fire)

Should I not refer to a ML agent as "him"?

Any advice is appreciated! :)

EDIT: I've tried to format the code, but it isn't working - sorry about that

MDReptile avatar Dec 29 '17 20:12 MDReptile

Hi

I skimmed over your issue. One problem is that your inputs are not normalized. Inputs shall be in the range from 0 to +1 or -1 to +1. So dividing the coordinates by the highest value possible in your scenario is one approach for that. If there are negative values as well go with this: normalization

Stick with discrete action space as continuous control is much more complex.

Concerning your input space, I suggest to collect only an excerpt of the environment like the 20 closest asteroids. I'd also include their velocity. For faster training results, simplify your environment and once it works out, scale the complexity up.

If there are less asteroids than inputs, then just set them to -1 or 0.

MarcoMeter avatar Dec 29 '17 21:12 MarcoMeter

I discovered that I wasn't giving it the right position of the player ship (that variable I used was actually the prefab, doh) - woops!

I also changed from so many state options to just "turn left", "turn right", "thrust", a combination of thrust/turning, and had the ship always firing, since the previous attempts the ship always fired all the time anyway.

And lastly I gave it the rotation of the player ship, hoping this helps it learn that where the ship points is where it fires.

With this new setup, it seems to be working a tiny bit better, hopefully.

MDReptile avatar Dec 29 '17 21:12 MDReptile

@MarcoMeter you say I need to use normalized data for the data out? So for asteroid/ship positions, they need to be 0-1? and velocities, what about them? Instead of negatives use 0 - 1 as well? And the rotation of the ship is 0 - 360, so I suppose I need to scale all of these into normalized values then?

I didn't know that!

So if I set them to -1 when there are less asteroids than 30, wouldn't that be out of the 0 to 1 range as well?

I'm confused about this.

MDReptile avatar Dec 29 '17 22:12 MDReptile

Normalization is due to the nature of neural networks. If the value ranges of the inputs are not similar to each other, inputs ranging from 0 - 1000 have a much higher impact compared to a range from 0 - 1. As the weights in a neural network get summed, much smaller input ranges loose their impact.

MarcoMeter avatar Dec 29 '17 22:12 MarcoMeter

Ok, thanks a lot for the help!

I'll try using things like: shipPosition.x = (shipPosition.x - minXWorld) / (maxXWorld - minXWorld);

MDReptile avatar Dec 29 '17 22:12 MDReptile

Ok so after setting him up differently, I tried moving the logic in Update functions to FixedUpdate, and that way I could run it at a higher speed. Now I trained him much faster to 13 million steps.

He still only seems to get a max of wave 7 (that means most of the time he doesn't do very good).

What I've changed: -Normalized all the stuff the ai reads except velocites (which don't usually go much over 1 or below -1) -Reduced the actions to any combination of turn left, turn right, thrust, or do nothing, with the ship always firing. -Tried optimizing the PPO settings some more. They look like this now:


Algorithm-specific parameters for tuning

gamma = 0.99 # Reward discount rate. lambd = 0.95 # Lambda parameter for GAE. time_horizon = 2048 # How many steps to collect per agent before adding to buffer. beta = 1e-3 # Strength of entropy regularization num_epoch = 5 # Number of gradient descent steps per batch of experiences. num_layers = 3 # Number of hidden layers between state/observation encoding and value/policy layers. epsilon = 0.2 # Acceptable threshold around ratio of old and new policy probabilities. buffer_size = 2048 # How large the experience buffer should be before gradient descent. learning_rate = 3e-4 # Model learning rate. hidden_units = 64 # Number of units in hidden layer. batch_size = 64 # How many experiences per gradient descent update step. normalize = False


Ideas for what might cause it to still suck: -I don't ever set "done" to true when the agent succeeds, he keeps playing into higher waves until he dies. Does that matter? -The variables I give it are ship pos, asteroid pos's, their velocites, and the ships rotation. Maybe this is too many floats, with too many wildly different possible situations?

Ideas I might try but I'm not sure will help: -Having it start at a difficult wave, and just have it repeatedly defeat that wave (calling "done" in the agent when it wins or dies) and not rewarding getting points but only survival. -Giving it only a handful of nearby asteroids (like suggested above)

I'm open to suggestions still about how I'm doing this wrong :)

I see so many people have their tensorflow bot just handed pixels of the screen (understandably they aren't using source code and usually just regular games) and I thought maybe it'd be better if I tried doing that, but that defeats the "accuracy" of me having the source to the project the AI is using... so I don't know about doing that.

So far, his most impressive run hit wave 7, and his strategy seems to be "spin around fast and pray n spray" like you can see in this GIF: https://i.gyazo.com/2387dcc3669aa4bfbacdcc6b9d6b0d8b.gif

MDReptile avatar Dec 31 '17 16:12 MDReptile

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

lock[bot] avatar Jan 04 '20 20:01 lock[bot]