O'Reilly logo

Game Programming using Qt 5 Beginner's Guide - Second Edition by Lorenz Haas, Witold Wysota, Pavel Strakhov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Time for action – Writing a strategy script

Our first script will simply select a random move:

{
    "step": function(current) {
        function getRandomInt(min, max) {
          return Math.floor(Math.random() * (max - min)) + min;
        }
        return {
            x: current.pos().x + getRandomInt(-1, 2),
            y: current.pos().y + getRandomInt(-1, 2),
        }
    }
}

Of course, a more intelligent strategy can beat this script. You can find a more advanced script in the code bundle. First, when it sees an enemy entity nearby, it always goes for the kill. If there is no such enemy, it tries to move away from the closest ally, attempting to fill the whole board. This script will easily wipe out the randomly moving enemy:

Of course, there is always room for improvement. Try to think of a better strategy ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required