How to use getLocation method in Cucumber-gherkin

Best JavaScript code snippet using cucumber-gherkin

Run Cucumber-gherkin automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

overrideBaseIntersectionMethod.js

Source: overrideBaseIntersectionMethod.js Github

copy
1//// [overrideBaseIntersectionMethod.ts]
2// Repro from #14615
3
4type Constructor<T> = new (...args: any[]) => T;
5
6const WithLocation = <T extends Constructor<Point>>(Base: T) => class extends Base {
7  getLocation(): [number, number] {
8    const [x,y] = super.getLocation();
9    return [this.x | x, this.y | y];
10  }
11}
12
13class Point {
14  constructor(public x: number, public y: number) { }
15  getLocation(): [number, number] {
16    return [0,0];
17  }
18}
19
20class Foo extends WithLocation(Point) {
21  calculate() {
22    return this.x + this.y;
23  }
24  getLocation() {
25    return super.getLocation()
26  }
27  whereAmI() {
28    return this.getLocation();
29  }
30}
31
32
33//// [overrideBaseIntersectionMethod.js]
34"use strict";
35// Repro from #14615
36var __extends = (this && this.__extends) || (function () {
37    var extendStatics = function (d, b) {
38        extendStatics = Object.setPrototypeOf ||
39            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
40            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
41        return extendStatics(d, b);
42    };
43    return function (d, b) {
44        extendStatics(d, b);
45        function __() { this.constructor = d; }
46        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
47    };
48})();
49var WithLocation = function (Base) { return /** @class */ (function (_super) {
50    __extends(class_1, _super);
51    function class_1() {
52        return _super !== null && _super.apply(this, arguments) || this;
53    }
54    class_1.prototype.getLocation = function () {
55        var _a = _super.prototype.getLocation.call(this), x = _a[0], y = _a[1];
56        return [this.x | x, this.y | y];
57    };
58    return class_1;
59}(Base)); };
60var Point = /** @class */ (function () {
61    function Point(x, y) {
62        this.x = x;
63        this.y = y;
64    }
65    Point.prototype.getLocation = function () {
66        return [0, 0];
67    };
68    return Point;
69}());
70var Foo = /** @class */ (function (_super) {
71    __extends(Foo, _super);
72    function Foo() {
73        return _super !== null && _super.apply(this, arguments) || this;
74    }
75    Foo.prototype.calculate = function () {
76        return this.x + this.y;
77    };
78    Foo.prototype.getLocation = function () {
79        return _super.prototype.getLocation.call(this);
80    };
81    Foo.prototype.whereAmI = function () {
82        return this.getLocation();
83    };
84    return Foo;
85}(WithLocation(Point)));
86
Full Screen

align-test.js

Source: align-test.js Github

copy
1const { checkExist, setReload } = require('../../../util/utils');
2const { mouseAction } = require('../../../util/actions');
3
4test('Check Top align', async function() {
5    const { app } = require('../../../test');
6    await setReload();
7    await checkExist('#svgcanvas',15000);
8
9    const rect = await app.client.$('#left-Rectangle');
10    await rect.click();
11    await mouseAction([
12        { type: 'pointerMove', x: 250, y: 250, duration: 100, },
13        { type: 'pointerDown', button: 0, },
14        { type: 'pointerMove', x: 300, y: 300, duration: 1000, },
15        { type: 'pointerUp', button: 0, },
16    ]);
17    await checkExist('#svg_1');
18    
19    const rect2 = await app.client.$('#left-Rectangle');
20    await rect2.click();
21    await mouseAction([
22        { type: 'pointerMove', x: 350, y: 350, duration: 100, },
23        { type: 'pointerDown', button: 0, },
24        { type: 'pointerMove', x: 400, y: 400, duration: 1000, },
25        { type: 'pointerUp', button: 0, },
26    ]);
27    await checkExist('#svg_2');
28    
29    const rect3 = await app.client.$('#left-Rectangle');
30    await rect3.click();
31    await mouseAction([
32        { type: 'pointerMove', x: 450, y: 450, duration: 100, },
33        { type: 'pointerDown', button: 0, },
34        { type: 'pointerMove', x: 500, y: 500, duration: 1000, },
35        { type: 'pointerUp', button: 0, },
36
37        { type: 'pointerMove', x: 510, y: 510, duration: 100, },
38        { type: 'pointerDown', button: 0, },
39        { type: 'pointerUp', button: 0, },
40    ]);
41    await checkExist('#svg_3');
42
43    await mouseAction([
44        { type: 'pointerMove', x: 100, y: 100, duration: 100, },
45        { type: 'pointerDown', button: 0, },
46        { type: 'pointerMove', x: 600, y: 600, duration: 1000, },
47        { type: 'pointerUp', button: 0, },
48    ]);
49
50    const topalign = await app.client.$('#qa-top_align');
51    await topalign.click();
52    
53    const rectlocation = await app.client.$('#svg_1');
54    const rect2location = await app.client.$('#svg_2');
55    const rect3location = await app.client.$('#svg_3');
56    expect(await rectlocation.getLocation('y')).toEqual(await rect2location.getLocation('y'));
57    expect(await rectlocation.getLocation('y')).toEqual(await rect3location.getLocation('y'));
58    // console.log(await rectlocation.getLocation('y'));
59    await app.client.execute(() =>{
60        svgCanvas.undoMgr.undo();
61    });
62});
63
64test('Check Middle align', async function() {
65    const { app } = require('../../../test');
66
67    await mouseAction([
68        { type: 'pointerMove', x: 100, y: 100, duration: 100, },
69        { type: 'pointerDown', button: 0, },
70        { type: 'pointerMove', x: 600, y: 600, duration: 1000, },
71        { type: 'pointerUp', button: 0, },
72    ]);
73
74    const middlealign = await app.client.$('#qa-middle_align');
75    await middlealign.click();
76    
77    const rectlocation = await app.client.$('#svg_1');
78    const rect2location = await app.client.$('#svg_2');
79    const rect3location = await app.client.$('#svg_3');
80    // console.log(await rectlocation.getLocation('y'));
81    expect(await rectlocation.getLocation('y')).toEqual(await rect2location.getLocation('y'));
82    expect(await rectlocation.getLocation('y')).toEqual(await rect3location.getLocation('y'));
83 
84    await app.client.execute(() =>{
85        svgCanvas.undoMgr.undo();
86    });
87});
88
89test('Check bottom align', async function() {
90    const { app } = require('../../../test');
91
92    await mouseAction([
93        { type: 'pointerMove', x: 100, y: 100, duration: 100, },
94        { type: 'pointerDown', button: 0, },
95        { type: 'pointerMove', x: 600, y: 600, duration: 1000, },
96        { type: 'pointerUp', button: 0, },
97    ]);
98
99    const bottomalign = await app.client.$('#qa-bottom_align');
100    await bottomalign.click();
101
102    const rectlocation = await app.client.$('#svg_1');
103    const rect2location = await app.client.$('#svg_2');
104    const rect3location = await app.client.$('#svg_3');
105    // console.log(await rectlocation.getLocation('y'));
106    expect(await rectlocation.getLocation('y')).toEqual(await rect2location.getLocation('y'));
107    expect(await rectlocation.getLocation('y')).toEqual(await rect3location.getLocation('y'));
108 
109    await app.client.execute(() =>{
110        svgCanvas.undoMgr.undo();
111    });
112});
113
114test('Check Left align', async function() {
115    const { app } = require('../../../test');
116
117    await mouseAction([
118        { type: 'pointerMove', x: 100, y: 100, duration: 100, },
119        { type: 'pointerDown', button: 0, },
120        { type: 'pointerMove', x: 600, y: 600, duration: 1000, },
121        { type: 'pointerUp', button: 0, },
122    ]);
123
124    const leftalign = await app.client.$('#qa-left_align');
125    await leftalign.click();
126
127    const rectlocation = await app.client.$('#svg_1');
128    const rect2location = await app.client.$('#svg_2');
129    const rect3location = await app.client.$('#svg_3');
130    expect(await rectlocation.getLocation('x')).toEqual(await rect2location.getLocation('x'));
131    expect(await rectlocation.getLocation('x')).toEqual(await rect3location.getLocation('x'));
132    // console.log(await rectlocation.getLocation('x'));
133    await app.client.execute(() =>{
134        svgCanvas.undoMgr.undo();
135    });
136});
137
138test('check Center align', async function() {
139    const { app } = require('../../../test');
140
141    await mouseAction([
142        { type: 'pointerMove', x: 100, y: 100, duration: 100, },
143        { type: 'pointerDown', button: 0, },
144        { type: 'pointerMove', x: 600, y: 600, duration: 1000, },
145        { type: 'pointerUp', button: 0, },
146    ]);
147
148    const centeralign = await app.client.$('#qa-center_align');
149    await centeralign.click();
150    
151    const rectlocation = await app.client.$('#svg_1');
152    const rect2location = await app.client.$('#svg_2');
153    const rect3location = await app.client.$('#svg_3');
154    expect(await rectlocation.getLocation('x')).toEqual(await rect2location.getLocation('x'));
155    expect(await rectlocation.getLocation('x')).toEqual(await rect3location.getLocation('x'));
156    // console.log(await rectlocation.getLocation('x'));
157    await app.client.execute(() =>{
158        svgCanvas.undoMgr.undo();
159    });
160});
161
162test('check Right align', async function() {
163    const { app } = require('../../../test');
164    
165    await mouseAction([
166        { type: 'pointerMove', x: 100, y: 100, duration: 100, },
167        { type: 'pointerDown', button: 0, },
168        { type: 'pointerMove', x: 600, y: 600, duration: 1000, },
169        { type: 'pointerUp', button: 0, },
170    ]);
171    
172    const rightalign = await app.client.$('#qa-right_align');
173    await rightalign.click();
174    
175    const rectlocation = await app.client.$('#svg_1');
176    const rect2location = await app.client.$('#svg_2');
177    const rect3location = await app.client.$('#svg_3');
178    expect(await rectlocation.getLocation('x')).toEqual(await rect2location.getLocation('x'));
179    expect(await rectlocation.getLocation('x')).toEqual(await rect3location.getLocation('x'));
180    // console.log(await rectlocation.getLocation('x'));
181    await app.client.execute(() =>{
182    svgCanvas.undoMgr.undo();
183    });
184});
185
Full Screen

getLocation.js

Source: getLocation.js Github

copy
1/******************************************************************************/
2/* getLocation.js                                                             */
3/* Author: Seung Jae Lee                                                      */
4/*                                                                            */
5/* This is a mocha test file that tests getLocation() function in scraper.js. */
6/******************************************************************************/
7
8var assert = require("assert");
9var scraper = require('../scraper.js');
10
11describe('getLocation()', function() {
12    describe('no match', function() {
13        it('getLocation(\"\") should equal \"\"', function() {
14            assert.equal(scraper.getLocation(""), "");
15        })
16        it('getLocation(\"qqq\") should equal \"\"', function() {
17            assert.equal(scraper.getLocation("xyz"), "");
18        })
19    })
20    describe('one match', function() {
21        it('getLocation(\"clapp\") should equal \"1927 - Clapp Hall\"', function() {
22            assert.equal(scraper.getLocation("clapp"), "1927 - Clapp Hall");
23        })
24        it('getLocation(\"come to dod hall!\") should equal \"Dod Hall\"', function() {
25            assert.equal(scraper.getLocation("come to dod hall!"), "Dod Hall");
26        })
27    })
28    describe('case-insensitive match', function() {
29        it('getLocation(\"EQuad has food\") should equal \"Enginerring QUAD\"', function() {
30            assert.equal(scraper.getLocation("EQuad has food"), "Enginerring QUAD");
31        })
32        it('getLocation(\"FRIST HAS FOOD\") should equal \"Frist Campus Center\"', function() {
33            assert.equal(scraper.getLocation("FRIST HAS FOOD"), "Frist Campus Center");
34        })
35        it('getLocation(\"Pizza at CoLoNiAl ClUb\") should equal \"Colonial Club\"', function() {
36            assert.equal(scraper.getLocation("Pizza at CoLoNiAl ClUb"), "Colonial Club");
37        })
38    })
39    describe('punctuation deletion', function() {
40        it('getLocation(\"Come to F,r,i,s,t\") should equal \"Frist Campus Center\"', function() {
41            assert.equal(scraper.getLocation("Come to F,r,i,s,t"), "Frist Campus Center");
42        })
43        it('getLocation(\"Edward\'s Hall\") should equal \"Edwards Hall\"', function() {
44            assert.equal(scraper.getLocation("Edward\'s Hall"), "Edwards Hall");
45        })
46    })
47    describe('regex match', function() {
48        it('getLocation(\"Friend 112\") should equal \"Friend Center\"', function() {
49            assert.equal(scraper.getLocation("Friend 112"), "Friend Center");
50        })
51        it('getLocation(\"Lewis 123\") should equal \"Lewis Library\"', function() {
52            assert.equal(scraper.getLocation("Lewis 123"), "Lewis Library");
53        })
54    })
55
56    describe('biggest substring', function(){
57        it('getLocation(\"Ticket holders to Friend Center\") should equal \"Friend Center\"', function() {
58            assert.equal(scraper.getLocation("Ticket holders to Friend Center"), "Friend Center");
59        })
60        it('getLocation(\"Lewis 123, Bring your spoon!\") should equal \"Lewis Library\"', function() {
61            assert.equal(scraper.getLocation("Lewis 123, Bring your spoon!"), "Lewis Library");
62        })
63    });
64});
Full Screen

Assignment1.py

Source: Assignment1.py Github

copy
1from Plot import *
2from Robot import *
3import sys
4import math
5
6filename=sys.argv[1]
7algorithmChoice=int(sys.argv[2])
8runs=1
9totalRuns=1
10try:            #Handles having just 2 arguments
11    totalRuns=int(sys.argv[3])
12except IndexError:
13    print "Number of runs was not specified. Setting totalRuns to default.(1)"
14
15averageCrops=0
16#will run totalRuns times
17while runs<=totalRuns:
18    p = Plot()      #create plot
19    robot = Robot()         #create robot
20    walls = []
21    walls.append([])
22    walls = p.RetrievePlot(filename, walls)
23    runs+=1
24    if algorithmChoice == 1 or algorithmChoice == 5:            #These algorithms are similar. They run the same code but altered slightly.
25        highestPercentLocation=(0,0)
26        highestPercent=0
27        bestCrop=(0,0)
28        if algorithmChoice == 5:            #Algorithm 5 finds the best coordinate for crops that have highest probability of growing the most
29            bestCrop = (0, 0)
30            bestTime = 999
31            for crop in p.cropCoordinates:              #algorithm for calculating the location
32                percent = p.plotDictionary[crop][0]
33                avg = math.ceil(1 / percent)
34                refresh = (percent ** 2) * 100
35                total = avg + refresh
36                if total < bestTime:
37                    bestTime = total
38                    bestCrop = crop
39        elif algorithmChoice == 1:      #If algorithm 1, find the highest percentage crop location
40            highestPercent=0
41            highestPercentLocation=(0,0)
42            for j in p.cropCoordinates:
43                if highestPercent < p.plotDictionary[j][0]:
44                    highestPercentLocation=j
45                    highestPercent=p.plotDictionary[j][0]
46        count = 0
47        time = (p.xLimit * p.yLimit) * .25          #time unit for this algorithm. If needed, comment this and uncomment the next to test different times
48        #time=500
49        visitedCoordinates = []         #Holds the coordinates we have already been to so we dont go over them more than once.
50        wallCoordinates = []            #Holds the coordinates of the walls. Not counting the outer walls.
51        traverse = []                   #traverse holds the coordinates to help manuever around walls
52        wallFound = False               #Holds whether or not we have run into a wall.
53        found = False                   #If the location is found, we will make this true.
54        while count <= time:
55            if found != True:
56                wallFound = False
57                visitedCoordinates = [robot.GetLocation()]
58                if algorithmChoice == 5:
59                    currentEndpoint = bestCrop
60                elif algorithmChoice == 1:
61                    currentEndpoint = highestPercentLocation
62                prevCoord = (0, 0)         #Holds previous coordinate in order to check for
63                while robot.GetLocation() != currentEndpoint and count<=time:       #move the robot until you hit the location or time runs out
64                    if prevCoord == robot.GetLocation():
65                        visitedCoordinates = [robot.GetLocation()]
66                    prevCoord = robot.GetLocation()
67                    p.UpdatePlot()      #Update the plot
68
69                    #The following if statements check for walls in each direction and determines if it has been visited or not.
70                    #This will determine which direction the robot will move until it hits a wall.
71
72                    if robot.GetLocation()[0] < currentEndpoint[0] and robot.GetLocation()[1] < currentEndpoint[1] and \
73                                    p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1)][
74                                        0] != "#" and (
75                                robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1) not in visitedCoordinates:
76                        robot.MoveNorthEast()
77                    elif robot.GetLocation()[0] < currentEndpoint[0] and robot.GetLocation()[1] > currentEndpoint[1] and \
78                                    p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1)][
79                                        0] != "#" and (
80                                robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1) not in visitedCoordinates:
81                        robot.MoveSouthEast()
82                    elif robot.GetLocation()[0] > currentEndpoint[0] and robot.GetLocation()[1] > currentEndpoint[1] and \
83                                    p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1)][
84                                        0] != "#" and (
85                                robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1) not in visitedCoordinates:
86                        robot.MoveSouthWest()
87                    elif robot.GetLocation()[0] > currentEndpoint[0] and robot.GetLocation()[1] < currentEndpoint[1] and \
88                                    p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1)][
89                                        0] != "#" and (
90                                robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1) not in visitedCoordinates:
91                        robot.MoveNorthWest()
92                    elif robot.GetLocation()[0] < currentEndpoint[0] and \
93                                    p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1])][
94                                        0] != "#" and (
95                                robot.GetLocation()[0] + 1, robot.GetLocation()[1]) not in visitedCoordinates:
96                        robot.MoveEast()
97                    elif robot.GetLocation()[0] > currentEndpoint[0] and \
98                                    p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1])][
99                                        0] != "#" and (
100                                robot.GetLocation()[0] - 1, robot.GetLocation()[1]) not in visitedCoordinates:
101                        robot.MoveWest()
102                    elif robot.GetLocation()[1] < currentEndpoint[1] and \
103                                    p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] + 1)][
104                                        0] != "#" and (
105                            robot.GetLocation()[0], robot.GetLocation()[1] + 1) not in visitedCoordinates:
106                        robot.MoveNorth()
107                    elif robot.GetLocation()[1] > currentEndpoint[1] and \
108                                    p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] - 1)][
109                                        0] != "#" and (
110                            robot.GetLocation()[0], robot.GetLocation()[1] - 1) not in visitedCoordinates:
111                        robot.MoveSouth()
112                    else:                       #If it reaches here, a wall has been reached
113                        if wallFound == False:
114                            wallFound = True
115                            x = robot.GetLocation()[0]
116                            y = robot.GetLocation()[1]
117                            coord = (0, 0)
118                            if p.plotDictionary[(x + 1, y)][0] == "#":
119                                coord = (x + 1, y)
120                            elif p.plotDictionary[(x - 1, y)][0] == "#":
121                                coord = (x - 1, y)
122                            elif p.plotDictionary[(x, y + 1)][0] == "#":
123                                coord = (x, y + 1)
124                            elif p.plotDictionary[(x, y - 1)][0] == "#":
125                                coord = (x, y - 1)
126                            for w in walls:     #find the coordinate of the wall and find the list of coordinates of the wall in the wall list
127                                if coord in w:
128                                    wallCoordinates = w
129
130                            #We populate the traverse list in order to move the robot around the wall
131
132                            for c in wallCoordinates:
133                                if p.plotDictionary[(c[0] + 1, c[1])][0] != "#" and (
134                                    c[0] + 1, c[1]) not in traverse and (
135                                            c[0] + 1, c[1]) not in wallCoordinates:
136                                    traverse.append((c[0] + 1, c[1]))
137                                if p.plotDictionary[(c[0] - 1, c[1])][0] != "#" and (
138                                    c[0] - 1, c[1]) not in traverse and (
139                                            c[0] - 1, c[1]) not in wallCoordinates:
140                                    traverse.append((c[0] - 1, c[1]))
141                                if p.plotDictionary[(c[0], c[1] + 1)][0] != "#" and (
142                                c[0], c[1] + 1) not in traverse and (
143                                        c[0], c[1] + 1) not in wallCoordinates:
144                                    traverse.append((c[0], c[1] + 1))
145                                if p.plotDictionary[(c[0], c[1] - 1)][0] != "#" and (
146                                c[0], c[1] - 1) not in traverse and (
147                                        c[0], c[1] - 1) not in wallCoordinates:
148                                    traverse.append((c[0], c[1] - 1))
149                                if p.plotDictionary[(c[0] + 1, c[1] + 1)][0] != "#" and (
150                                            c[0] + 1, c[1] + 1) not in traverse and (
151                                            c[0] + 1, c[1] + 1) not in wallCoordinates:
152                                    traverse.append((c[0] + 1, c[1] + 1))
153                                if p.plotDictionary[(c[0] - 1, c[1] + 1)][0] != "#" and (
154                                            c[0] - 1, c[1] + 1) not in traverse and (
155                                            c[0] - 1, c[1] + 1) not in wallCoordinates:
156                                    traverse.append((c[0] - 1, c[1] + 1))
157                                if p.plotDictionary[(c[0] + 1, c[1] - 1)][0] != "#" and (
158                                            c[0] + 1, c[1] - 1) not in traverse and (
159                                            c[0] + 1, c[1] - 1) not in wallCoordinates:
160                                    traverse.append((c[0] + 1, c[1] - 1))
161                                if p.plotDictionary[(c[0] - 1, c[1] - 1)][0] != "#" and (
162                                            c[0] - 1, c[1] - 1) not in traverse and (
163                                            c[0] - 1, c[1] - 1) not in wallCoordinates:
164                                    traverse.append((c[0] - 1, c[1] - 1))
165
166                        #Use same traversal code but this time check to also see if its in the traverse list. We dont move in relation to the endpoint.
167
168                        if p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1)][0] != "#" and (
169                                    robot.GetLocation()[0] + 1,
170                                    robot.GetLocation()[1] + 1) not in visitedCoordinates and (
171                                    robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1) in traverse:
172                            robot.MoveNorthEast()
173                        elif p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1)][0] != "#" and (
174                                    robot.GetLocation()[0] + 1,
175                                    robot.GetLocation()[1] - 1) not in visitedCoordinates and (
176                                    robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1) in traverse:
177                            robot.MoveSouthEast()
178                        elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1)][0] != "#" and (
179                                    robot.GetLocation()[0] - 1,
180                                    robot.GetLocation()[1] - 1) not in visitedCoordinates and (
181                                    robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1) in traverse:
182                            robot.MoveSouthWest()
183                        elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1)][0] != "#" and (
184                                    robot.GetLocation()[0] - 1,
185                                    robot.GetLocation()[1] + 1) not in visitedCoordinates and (
186                                    robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1) in traverse:
187                            robot.MoveNorthWest()
188                        elif p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1])][0] != "#" and (
189                                    robot.GetLocation()[0] + 1, robot.GetLocation()[1]) not in visitedCoordinates and (
190                                    robot.GetLocation()[0] + 1, robot.GetLocation()[1]) in traverse:
191                            robot.MoveEast()
192                        elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1])][0] != "#" and (
193                                    robot.GetLocation()[0] - 1, robot.GetLocation()[1]) not in visitedCoordinates and (
194                                    robot.GetLocation()[0] - 1, robot.GetLocation()[1]) in traverse:
195                            robot.MoveWest()
196                        elif p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] + 1)][0] != "#" and (
197                                robot.GetLocation()[0], robot.GetLocation()[1] + 1) not in visitedCoordinates and (
198                                robot.GetLocation()[0], robot.GetLocation()[1] + 1) in traverse:
199                            robot.MoveNorth()
200                        elif p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] - 1)][0] != "#" and (
201                                robot.GetLocation()[0], robot.GetLocation()[1] - 1) not in visitedCoordinates and (
202                                robot.GetLocation()[0], robot.GetLocation()[1] - 1) in traverse:
203                            robot.MoveSouth()
204                    count += 1
205                    visitedCoordinates.append(robot.GetLocation())
206                    if robot.CheckForCrop(p.plotDictionary):        #check for a crop
207                        p.RemoveCrop(robot.x, robot.y)
208                found = True
209            else:
210                if algorithmChoice == 1:        #if algorithm 1 just sit there and collect. If 5, follow the collection algorithm below.
211                    while count <= time:
212                        p.UpdatePlot()
213                        if robot.CheckForCrop(p.plotDictionary):
214                            p.RemoveCrop(robot.x,robot.y)
215                        count+=1
216                elif algorithmChoice == 5:      #Ran out of time to fix. Only works if current location has all 8 surrounding tiles as plots and not walls
217                    iter = 0
218                    while count <= time:
219                        p.UpdatePlot()
220                        if iter == 0:
221                            robot.MoveNorth()
222                            if robot.CheckForCrop(p.plotDictionary):
223                                p.RemoveCrop(robot.x, robot.y)
224                            iter += 1
225                            count += 1
226                        elif iter == 1:
227                            robot.MoveEast()
228                            if robot.CheckForCrop(p.plotDictionary):
229                                p.RemoveCrop(robot.x, robot.y)
230                            iter += 1
231                            count += 1
232                        elif iter == 2:
233                            robot.MoveSouth()
234                            if robot.CheckForCrop(p.plotDictionary):
235                                p.RemoveCrop(robot.x, robot.y)
236                            iter += 1
237                            count += 1
238                        elif iter == 3:
239                            robot.MoveSouth()
240                            if robot.CheckForCrop(p.plotDictionary):
241                                p.RemoveCrop(robot.x, robot.y)
242                            iter += 1
243                            count += 1
244                        elif iter == 4:
245                            robot.MoveWest()
246                            if robot.CheckForCrop(p.plotDictionary):
247                                p.RemoveCrop(robot.x, robot.y)
248                            iter += 1
249                            count += 1
250                        elif iter == 5:
251                            robot.MoveWest()
252                            if robot.CheckForCrop(p.plotDictionary):
253                                p.RemoveCrop(robot.x, robot.y)
254                            iter += 1
255                            count += 1
256                        elif iter == 6:
257                            robot.MoveNorth()
258                            if robot.CheckForCrop(p.plotDictionary):
259                                p.RemoveCrop(robot.x, robot.y)
260                            iter += 1
261                            count += 1
262                        elif iter == 7:
263                            robot.MoveNorth()
264                            if robot.CheckForCrop(p.plotDictionary):
265                                p.RemoveCrop(robot.x, robot.y)
266                            iter += 1
267                            count += 1
268                        elif iter == 8:
269                            robot.MoveSouthEast()
270                            if robot.CheckForCrop(p.plotDictionary):
271                                p.RemoveCrop(robot.x, robot.y)
272                            iter = 0
273                            count += 1
274        #print "Number of crops found = " + str(robot.numberOfCrops)            #Uncomment this to see total per run
275        averageCrops+=robot.numberOfCrops   #add so we can average the values at the end.
276    elif algorithmChoice == 2:                  #Algorithm 2 begins running here
277        time = (p.xLimit * p.yLimit) * .25
278        #time=500
279        count = 0
280        while count != time:
281            rand = random.random()          #Get a random number to determine direction
282            rand *= 100
283            if rand < 12.5:                 #rand will determine direction.
284                while count != time:        #Go until time runs out or hit a wall
285                    p.UpdatePlot()
286                    current = [robot.GetLocation()[0], robot.GetLocation()[1]]
287                    current[1] += 1
288                    check = (current[0], current[1])
289                    if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
290                        robot.MoveNorth()
291                        if robot.CheckForCrop(p.plotDictionary):
292                            p.RemoveCrop(robot.x, robot.y)
293                        count += 1
294                    else:
295                        break
296            elif rand >= 12.5 and rand < 25:        #Same as above comment, just different direction
297                while count != time:
298                    p.UpdatePlot()
299                    current = [robot.GetLocation()[0], robot.GetLocation()[1]]
300                    current[1] += 1
301                    current[0] += 1
302                    check = (current[0], current[1])
303                    if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
304                        robot.MoveNorthEast()
305                        if robot.CheckForCrop(p.plotDictionary):
306                            p.RemoveCrop(robot.x, robot.y)
307                        count += 1
308                    else:
309                        break
310            elif rand >= 25 and rand < 37.5:
311                while count != time:
312                    p.UpdatePlot()
313                    current = [robot.GetLocation()[0], robot.GetLocation()[1]]
314                    current[0] += 1
315                    check = (current[0], current[1])
316                    if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
317                        robot.MoveEast()
318                        if robot.CheckForCrop(p.plotDictionary):
319                            p.RemoveCrop(robot.x, robot.y)
320                        count += 1
321                    else:
322                        break
323            elif rand >= 37.5 and rand < 50:
324                while count != time:
325                    p.UpdatePlot()
326                    current = [robot.GetLocation()[0], robot.GetLocation()[1]]
327                    current[1] -= 1
328                    current[0] += 1
329                    check = (current[0], current[1])
330                    if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
331                        robot.MoveSouthEast()
332                        if robot.CheckForCrop(p.plotDictionary):
333                            p.RemoveCrop(robot.x, robot.y)
334                        count += 1
335                    else:
336                        break
337            elif rand >= 50 and rand < 62.5:
338                while count != time:
339                    p.UpdatePlot()
340                    current = [robot.GetLocation()[0], robot.GetLocation()[1]]
341                    current[1] -= 1
342                    check = (current[0], current[1])
343                    if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
344                        robot.MoveSouth()
345                        if robot.CheckForCrop(p.plotDictionary):
346                            p.RemoveCrop(robot.x, robot.y)
347                        count += 1
348                    else:
349                        break
350            elif rand >= 62.5 and rand < 75:
351                while count != time:
352                    p.UpdatePlot()
353                    current = [robot.GetLocation()[0], robot.GetLocation()[1]]
354                    current[1] -= 1
355                    current[0] -= 1
356                    check = (current[0], current[1])
357                    if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
358                        robot.MoveSouthWest()
359                        if robot.CheckForCrop(p.plotDictionary):
360                            p.RemoveCrop(robot.x, robot.y)
361                        count += 1
362                    else:
363                        break
364            elif rand >= 75 and rand < 87.5:
365                while count != time:
366                    p.UpdatePlot()
367                    current = [robot.GetLocation()[0], robot.GetLocation()[1]]
368                    current[0] -= 1
369                    check = (current[0], current[1])
370                    if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
371                        robot.MoveWest()
372                        if robot.CheckForCrop(p.plotDictionary):
373                            p.RemoveCrop(robot.x, robot.y)
374                        count += 1
375                    else:
376                        break
377            elif rand >= 87.5:
378                while count != time:
379                    p.UpdatePlot()
380                    current = [robot.GetLocation()[0], robot.GetLocation()[1]]
381                    current[1] += 1
382                    current[0] -= 1
383                    check = (current[0], current[1])
384                    if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
385                        robot.MoveNorthWest()
386                        if robot.CheckForCrop(p.plotDictionary):
387                            p.RemoveCrop(robot.x, robot.y)
388                        count += 1
389                    else:
390                        break
391        #print "Number of crops found = " + str(robot.numberOfCrops)
392        averageCrops+=robot.numberOfCrops
393    elif algorithmChoice == 3:                  #Choose random direction every unit of time
394        time = (p.xLimit * p.yLimit) * .25
395        #time=500
396        count = 0
397        while count != time:            #Similar to above but instead of while inside of if statements, its outside.
398            p.UpdatePlot()              #Update plot and randomize direction every turn
399            rand = random.random()
400            rand *= 100
401            if rand < 12.5:
402                current = [robot.GetLocation()[0], robot.GetLocation()[1]]
403                current[1] += 1
404                check = (current[0], current[1])
405                if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
406                    robot.MoveNorth()
407                    if robot.CheckForCrop(p.plotDictionary):
408                        p.RemoveCrop(robot.x, robot.y)
409            elif rand >= 12.5 and rand < 25:
410                current = [robot.GetLocation()[0], robot.GetLocation()[1]]
411                current[1] += 1
412                current[0] += 1
413                check = (current[0], current[1])
414                if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
415                    robot.MoveNorthEast()
416                    if robot.CheckForCrop(p.plotDictionary):
417                        p.RemoveCrop(robot.x, robot.y)
418            elif rand >= 25 and rand < 37.5:
419                current = [robot.GetLocation()[0], robot.GetLocation()[1]]
420                current[0] += 1
421                check = (current[0], current[1])
422                if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
423                    robot.MoveEast()
424                    if robot.CheckForCrop(p.plotDictionary):
425                        p.RemoveCrop(robot.x, robot.y)
426            elif rand >= 37.5 and rand < 50:
427                current = [robot.GetLocation()[0], robot.GetLocation()[1]]
428                current[1] -= 1
429                current[0] += 1
430                check = (current[0], current[1])
431                if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
432                    robot.MoveSouthEast()
433                    if robot.CheckForCrop(p.plotDictionary):
434                        p.RemoveCrop(robot.x, robot.y)
435            elif rand >= 50 and rand < 62.5:
436                current = [robot.GetLocation()[0], robot.GetLocation()[1]]
437                current[1] -= 1
438                check = (current[0], current[1])
439                if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
440                    robot.MoveSouth()
441                    if robot.CheckForCrop(p.plotDictionary):
442                        p.RemoveCrop(robot.x, robot.y)
443            elif rand >= 62.5 and rand < 75:
444                current = [robot.GetLocation()[0], robot.GetLocation()[1]]
445                current[1] -= 1
446                current[0] -= 1
447                check = (current[0], current[1])
448                if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
449                    robot.MoveSouthWest()
450                    if robot.CheckForCrop(p.plotDictionary):
451                        p.RemoveCrop(robot.x, robot.y)
452            elif rand >= 75 and rand < 87.5:
453                current = [robot.GetLocation()[0], robot.GetLocation()[1]]
454                current[0] -= 1
455                check = (current[0], current[1])
456                if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
457                    robot.MoveWest()
458                    if robot.CheckForCrop(p.plotDictionary):
459                        p.RemoveCrop(robot.x, robot.y)
460            else:
461                current = [robot.GetLocation()[0], robot.GetLocation()[1]]
462                current[1] += 1
463                current[0] -= 1
464                check = (current[0], current[1])
465                if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
466                    robot.MoveNorthWest()
467                    if robot.CheckForCrop(p.plotDictionary):
468                        p.RemoveCrop(robot.x, robot.y)
469            count += 1
470        #print "Number of crops found = " + str(robot.numberOfCrops)
471        averageCrops+=robot.numberOfCrops
472    elif algorithmChoice == 4:              #This algorithm finds a location and goes to said location. Uses same traverse technique as 1 and 5
473        count = 0
474        time = (p.xLimit * p.yLimit) * .25
475        #time = 500
476        visitedCoordinates = []         #similar variables as algorithm 1,5
477        wallCoordinates = []
478        traverse = []
479        wallFound = False
480        while count != time:
481            wallFound = False
482            visitedCoordinates = [robot.GetLocation()]
483            arrayLength = len(p.cropCoordinates)
484            rand = random.random()
485            rand *= 100
486            rand = int(rand % arrayLength)
487            currentEndpoint = p.cropCoordinates[rand]           #Get a random coordinate containing a crop
488            prevCoord = (0, 0)
489
490            # Same as algorithm 1,5. Determine which direction to go until hit a wall
491            # However, after reaching the random location, we choose another coordinate to go to, which is why we use the while loop
492
493            while robot.GetLocation() != currentEndpoint and count != time:
494                if prevCoord == robot.GetLocation():
495                    visitedCoordinates = [robot.GetLocation()]
496                prevCoord = robot.GetLocation()
497                p.UpdatePlot()
498                if robot.GetLocation()[0] < currentEndpoint[0] and robot.GetLocation()[1] < currentEndpoint[1] and \
499                                p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1)][
500                                    0] != "#" and (
501                    robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1) not in visitedCoordinates:
502                    robot.MoveNorthEast()
503                elif robot.GetLocation()[0] < currentEndpoint[0] and robot.GetLocation()[1] > currentEndpoint[1] and \
504                                p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1)][
505                                    0] != "#" and (
506                    robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1) not in visitedCoordinates:
507                    robot.MoveSouthEast()
508                elif robot.GetLocation()[0] > currentEndpoint[0] and robot.GetLocation()[1] > currentEndpoint[1] and \
509                                p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1)][
510                                    0] != "#" and (
511                    robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1) not in visitedCoordinates:
512                    robot.MoveSouthWest()
513                elif robot.GetLocation()[0] > currentEndpoint[0] and robot.GetLocation()[1] < currentEndpoint[1] and \
514                                p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1)][
515                                    0] != "#" and (
516                    robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1) not in visitedCoordinates:
517                    robot.MoveNorthWest()
518                elif robot.GetLocation()[0] < currentEndpoint[0] and \
519                                p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1])][0] != "#" and (
520                    robot.GetLocation()[0] + 1, robot.GetLocation()[1]) not in visitedCoordinates:
521                    robot.MoveEast()
522                elif robot.GetLocation()[0] > currentEndpoint[0] and \
523                                p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1])][0] != "#" and (
524                    robot.GetLocation()[0] - 1, robot.GetLocation()[1]) not in visitedCoordinates:
525                    robot.MoveWest()
526                elif robot.GetLocation()[1] < currentEndpoint[1] and \
527                                p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] + 1)][0] != "#" and (
528                robot.GetLocation()[0], robot.GetLocation()[1] + 1) not in visitedCoordinates:
529                    robot.MoveNorth()
530                elif robot.GetLocation()[1] > currentEndpoint[1] and \
531                                p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] - 1)][0] != "#" and (
532                robot.GetLocation()[0], robot.GetLocation()[1] - 1) not in visitedCoordinates:
533                    robot.MoveSouth()
534                else:                           #if running into the wall, make traverse wall and continue
535                    if wallFound == False:
536                        wallFound = True
537                        x = robot.GetLocation()[0]
538                        y = robot.GetLocation()[1]
539                        coord = (0, 0)
540                        if p.plotDictionary[(x + 1, y)][0] == "#":
541                            coord = (x + 1, y)
542                        elif p.plotDictionary[(x - 1, y)][0] == "#":
543                            coord = (x - 1, y)
544                        elif p.plotDictionary[(x, y + 1)][0] == "#":
545                            coord = (x, y + 1)
546                        elif p.plotDictionary[(x, y - 1)][0] == "#":
547                            coord = (x, y - 1)
548                        for w in walls:
549                            if coord in w:
550                                wallCoordinates = w
551                        for c in wallCoordinates:
552                            if p.plotDictionary[(c[0] + 1, c[1])][0] != "#" and (c[0] + 1, c[1]) not in traverse and (
553                                c[0] + 1, c[1]) not in wallCoordinates:
554                                traverse.append((c[0] + 1, c[1]))
555                            if p.plotDictionary[(c[0] - 1, c[1])][0] != "#" and (c[0] - 1, c[1]) not in traverse and (
556                                c[0] - 1, c[1]) not in wallCoordinates:
557                                traverse.append((c[0] - 1, c[1]))
558                            if p.plotDictionary[(c[0], c[1] + 1)][0] != "#" and (c[0], c[1] + 1) not in traverse and (
559                            c[0], c[1] + 1) not in wallCoordinates:
560                                traverse.append((c[0], c[1] + 1))
561                            if p.plotDictionary[(c[0], c[1] - 1)][0] != "#" and (c[0], c[1] - 1) not in traverse and (
562                            c[0], c[1] - 1) not in wallCoordinates:
563                                traverse.append((c[0], c[1] - 1))
564                            if p.plotDictionary[(c[0] + 1, c[1] + 1)][0] != "#" and (
565                                c[0] + 1, c[1] + 1) not in traverse and (c[0] + 1, c[1] + 1) not in wallCoordinates:
566                                traverse.append((c[0] + 1, c[1] + 1))
567                            if p.plotDictionary[(c[0] - 1, c[1] + 1)][0] != "#" and (
568                                c[0] - 1, c[1] + 1) not in traverse and (c[0] - 1, c[1] + 1) not in wallCoordinates:
569                                traverse.append((c[0] - 1, c[1] + 1))
570                            if p.plotDictionary[(c[0] + 1, c[1] - 1)][0] != "#" and (
571                                c[0] + 1, c[1] - 1) not in traverse and (c[0] + 1, c[1] - 1) not in wallCoordinates:
572                                traverse.append((c[0] + 1, c[1] - 1))
573                            if p.plotDictionary[(c[0] - 1, c[1] - 1)][0] != "#" and (
574                                c[0] - 1, c[1] - 1) not in traverse and (c[0] - 1, c[1] - 1) not in wallCoordinates:
575                                traverse.append((c[0] - 1, c[1] - 1))
576                    if p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1)][0] != "#" and (
577                        robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1) not in visitedCoordinates and (
578                        robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1) in traverse:
579                        robot.MoveNorthEast()
580                    elif p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1)][0] != "#" and (
581                        robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1) not in visitedCoordinates and (
582                        robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1) in traverse:
583                        robot.MoveSouthEast()
584                    elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1)][0] != "#" and (
585                        robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1) not in visitedCoordinates and (
586                        robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1) in traverse:
587                        robot.MoveSouthWest()
588                    elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1)][0] != "#" and (
589                        robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1) not in visitedCoordinates and (
590                        robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1) in traverse:
591                        robot.MoveNorthWest()
592                    elif p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1])][0] != "#" and (
593                        robot.GetLocation()[0] + 1, robot.GetLocation()[1]) not in visitedCoordinates and (
594                        robot.GetLocation()[0] + 1, robot.GetLocation()[1]) in traverse:
595                        robot.MoveEast()
596                    elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1])][0] != "#" and (
597                        robot.GetLocation()[0] - 1, robot.GetLocation()[1]) not in visitedCoordinates and (
598                        robot.GetLocation()[0] - 1, robot.GetLocation()[1]) in traverse:
599                        robot.MoveWest()
600                    elif p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] + 1)][0] != "#" and (
601                    robot.GetLocation()[0], robot.GetLocation()[1] + 1) not in visitedCoordinates and (
602                    robot.GetLocation()[0], robot.GetLocation()[1] + 1) in traverse:
603                        robot.MoveNorth()
604                    elif p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] - 1)][0] != "#" and (
605                    robot.GetLocation()[0], robot.GetLocation()[1] - 1) not in visitedCoordinates and (
606                    robot.GetLocation()[0], robot.GetLocation()[1] - 1) in traverse:
607                        robot.MoveSouth()
608                count += 1
609                visitedCoordinates.append(robot.GetLocation())
610                if robot.CheckForCrop(p.plotDictionary):
611                    p.RemoveCrop(robot.x, robot.y)
612        #print "Number of crops found = " + str(robot.numberOfCrops)
613        averageCrops+=robot.numberOfCrops
614    else:
615        print "Algorithm not found."
616averageCrops=float(float(averageCrops)/float(totalRuns))
617print "Average number of crops found per run = " + str(averageCrops)
Full Screen

MyMinion.py

Source: MyMinion.py Github

copy
1'''
2 * Copyright (c) 2014, 2015 Entertainment Intelligence Lab, Georgia Institute of Technology.
3 * Originally developed by Mark Riedl.
4 * Last edited by Mark Riedl 05/2015
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 *     http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17'''
18
19import sys, pygame, math, numpy, random, time, copy
20from pygame.locals import * 
21
22from constants import *
23from utils import *
24from core import *
25from moba import *
26
27class MyMinion(Minion):
28	
29	def __init__(self, position, orientation, world, image = NPC, speed = SPEED, viewangle = 360, hitpoints = HITPOINTS, firerate = FIRERATE, bulletclass = SmallBullet):
30		Minion.__init__(self, position, orientation, world, image, speed, viewangle, hitpoints, firerate, bulletclass)
31		self.states = [Idle]
32		### Add your states to self.states (but don't remove Idle)
33		### YOUR CODE GOES BELOW HERE ###
34		self.states.append(Move)
35		self.states.append(Attack)
36		self.states.append(MovingAttack)
37		### YOUR CODE GOES ABOVE HERE ###
38
39	def start(self):
40		Minion.start(self)
41		self.changeState(Idle)
42
43############################
44### Idle
45###
46### This is the default state of MyMinion. The main purpose of the Idle state is to figure out what state to change to and do that immediately.
47
48class Idle(State):
49	
50	def enter(self, oldstate):
51		State.enter(self, oldstate)
52		# stop moving
53		self.agent.stopMoving()
54	
55	def execute(self, delta = 0):
56		State.execute(self, delta)
57		### YOUR CODE GOES BELOW HERE ###
58		self.agent.changeState(Move)
59		### YOUR CODE GOES ABOVE HERE ###
60		return None
61
62##############################
63### Taunt
64###
65### This is a state given as an example of how to pass arbitrary parameters into a State.
66### To taunt someome, Agent.changeState(Taunt, enemyagent)
67
68class Taunt(State):
69
70	def parseArgs(self, args):
71		self.victim = args[0]
72
73	def execute(self, delta = 0):
74		if self.victim is not None:
75			print "Hey " + str(self.victim) + ", I don't like you!"
76		self.agent.changeState(Idle)
77
78##############################
79### YOUR STATES GO HERE:
80
81def closestTarget(agent, targets):
82	agentLocation = agent.getLocation()
83	returnTarget = None
84	targetDist = INFINITY
85	for target in targets:
86		if distance(agentLocation, target.getLocation()) < targetDist:
87			returnTarget = target
88			targetDist = distance(agentLocation, target.getLocation())
89	return returnTarget
90
91def shootTarget(agent, target):
92	agent.turnToFace(target.getLocation())
93	agent.shoot()
94
95class Move(State):
96
97	def enter(self, oldstate):
98		State.enter(self, oldstate)
99		towers = self.agent.world.getEnemyTowers(self.agent.getTeam())
100		bases = self.agent.world.getEnemyBases(self.agent.getTeam())
101		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
102		if len(towers) > 0:
103			self.agent.navigateTo(closestTarget(self.agent, towers).getLocation())
104		elif len(bases) > 0:
105			self.agent.navigateTo(closestTarget(self.agent, bases).getLocation())
106		elif len(enemies) > 0:
107			self.agent.navigateTo(closestTarget(self.agent, enemies).getLocation())
108
109	def execute(self, delta = 0):
110		towers = self.agent.world.getEnemyTowers(self.agent.getTeam())
111		bases = self.agent.world.getEnemyBases(self.agent.getTeam())
112		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
113		if not self.agent.isMoving():
114			self.agent.changeState(Move)
115		if len(towers) > 0:
116			destinationTower = closestTarget(self.agent, towers)
117			#self.agent.navigateTo(destinationTower.getLocation())
118		elif len(bases) > 0:
119			destinationBase = closestTarget(self.agent, bases)
120			#self.agent.navigateTo(destinationBase.getLocation())
121		elif len(enemies) > 0:
122			destinationEnemy = closestTarget(self.agent, enemies)
123			#self.agent.navigateTo(destinationEnemy.getLocation())
124		if len(towers) > 0 and distance(self.agent.getLocation(),
125			destinationTower.getLocation()) < 150 and rayTraceWorld(
126			self.agent.getLocation(), destinationTower.getLocation(),
127			self.agent.world.getLinesWithoutBorders()) is None:
128			self.agent.changeState(Attack, destinationTower)
129		if len(bases) > 0 and len(towers) == 0 and distance(self.agent.getLocation(),
130			destinationBase.getLocation()) < 150 and rayTraceWorld(
131			self.agent.getLocation(), destinationBase.getLocation(),
132			self.agent.world.getLinesWithoutBorders()) is None:
133			self.agent.changeState(Attack, destinationBase)
134		if len(enemies) > 0 and len(bases) == 0 and len(towers) == 0 and distance(self.agent.getLocation(),
135			destinationEnemy.getLocation()) < 150 and rayTraceWorld(
136			self.agent.getLocation(), destinationEnemy.getLocation(),
137			self.agent.world.getLinesWithoutBorders()) is None:
138				if destinationEnemy.isMoving():
139					self.agent.changeState(MovingAttack, destinationEnemy)
140				else:
141					self.agent.changeState(Attack, destinationEnemy)
142
143class Attack(State):
144
145	def parseArgs(self, args):
146		self.target = args[0]
147
148	def enter(self, oldstate):
149		State.enter(self, oldstate)
150		if isinstance(self.target, MOBAAgent):
151			if self.target.isMoving():
152				self.agent.changeState(MovingAttack, self.target)
153		self.agent.stopMoving()
154		towers = self.agent.world.getEnemyTowers(self.agent.getTeam())
155		bases = self.agent.world.getEnemyBases(self.agent.getTeam())
156		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
157		allPossiblePoints = self.agent.getPossibleDestinations()
158		self.targetPoints = []
159		for point in allPossiblePoints:
160			if distance(point, self.target.getLocation()) < 150 and distance(point, self.target.getLocation()) > 50:
161				self.targetPoints.append(point)
162		if self.target in set(towers) or self.target in set(bases) or self.target in set(enemies):
163			shootTarget(self.agent, self.target)
164		else: self.agent.changeState(Move)
165
166	def execute(self, delta = 0):
167		if isinstance(self.target, MOBAAgent):
168			if self.target.isMoving():
169				self.agent.changeState(MovingAttack, self.target)
170		towers = self.agent.world.getEnemyTowers(self.agent.getTeam())
171		bases = self.agent.world.getEnemyBases(self.agent.getTeam())
172		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
173		if not self.agent.isMoving():
174			self.agent.navigateTo(random.choice(self.targetPoints))
175		if self.target in set(towers) or self.target in set(bases) or self.target in set(enemies):
176			shootTarget(self.agent, self.target)
177		else:
178			self.agent.changeState(Move)
179
180class MovingAttack(State):
181
182	def parseArgs(self, args):
183		self.target = args[0]
184
185	def enter(self, oldstate):
186		State.enter(self, oldstate)
187		if not self.target.isMoving():
188			self.agent.changeState(Attack, self.target)
189		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
190		if self.target in set(enemies):
191			self.agent.navigateTo(self.target.getLocation())
192			shootTarget(self.agent, self.target)
193		else: self.agent.changeState(Move)
194
195	def execute(self, delta = 0):
196		if not self.target.isMoving():
197			self.agent.changeState(Attack, self.target)
198		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
199		if self.target in set(enemies):
200			self.agent.navigateTo(self.target.getLocation())
201			shootTarget(self.agent, self.target)
202		else: self.agent.changeState(Move)
Full Screen

mybehaviors.py

Source: mybehaviors.py Github

copy
1'''
2 * Copyright (c) 2014, 2015 Entertainment Intelligence Lab, Georgia Institute of Technology.
3 * Originally developed by Mark Riedl.
4 * Last edited by Mark Riedl 05/2015
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 *     http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17'''
18
19import sys, pygame, math, numpy, random, time, copy
20from pygame.locals import *
21
22from constants import *
23from utils import *
24from core import *
25from moba2 import *
26from btnode import *
27
28###########################
29### SET UP BEHAVIOR TREE
30
31
32def treeSpec(agent):
33	myid = str(agent.getTeam())
34	spec = None
35	### YOUR CODE GOES BELOW HERE ###
36	spec =	[(Selector, "root"),
37		 [(Selector, "retreat or fight"),
38		  [(CloseMinion, 0.5, "minion nearby"),
39		  	(StrafeKillMinion, "kill minion retreat")],
40		   		(Retreat, 0.5, "retreat")],
41		 [(HitpointDaemon, 0.25, "good to fight"),
42		  [(Selector, "chase or kill"),
43		   [(NoCloseEnemies, "no close enemies"),
44			[(Selector, "chase hero or minion"),
45			 [(BuffDaemon, -1, "hero strong"),
46			  (ChaseHero, "chase hero")
47			  ],
48			 (ChaseMinion, "chase minion"),
49			 (ChaseHero, "chase hero if no minion")
50			 ]
51			],
52		   [(Selector, "kill hero or minion"),
53			(StrafeKillHero, "kill hero"),
54			(StrafeKillMinion, "kill minion")
55			]
56		   ]
57		  ]
58		 ]
59	### YOUR CODE GOES ABOVE HERE ###
60	return spec
61
62def myBuildTree(agent):
63	myid = str(agent.getTeam())
64	root = None
65	### YOUR CODE GOES BELOW HERE ###
66
67	### YOUR CODE GOES ABOVE HERE ###
68	return root
69
70### Helper function for making BTNodes (and sub-classes of BTNodes).
71### type: class type (BTNode or a sub-class)
72### agent: reference to the agent to be controlled
73### This function takes any number of additional arguments that will be passed to the BTNode and parsed using BTNode.parseArgs()
74def makeNode(type, agent, *args):
75	node = type(agent, args)
76	return node
77
78###############################
79### BEHAVIOR CLASSES:
80
81
82##################
83### Taunt
84###
85### Print disparaging comment, addressed to a given NPC
86### Parameters:
87###   0: reference to an NPC
88###   1: node ID string (optional)
89
90class Taunt(BTNode):
91
92	### target: the enemy agent to taunt
93
94	def parseArgs(self, args):
95		BTNode.parseArgs(self, args)
96		self.target = None
97		# First argument is the target
98		if len(args) > 0:
99			self.target = args[0]
100		# Second argument is the node ID
101		if len(args) > 1:
102			self.id = args[1]
103
104	def execute(self, delta = 0):
105		ret = BTNode.execute(self, delta)
106		if self.target is not None:
107			print "Hey", self.target, "I don't like you!"
108		return ret
109
110##################
111### MoveToTarget
112###
113### Move the agent to a given (x, y)
114### Parameters:
115###   0: a point (x, y)
116###   1: node ID string (optional)
117
118class MoveToTarget(BTNode):
119	
120	### target: a point (x, y)
121	
122	def parseArgs(self, args):
123		BTNode.parseArgs(self, args)
124		self.target = None
125		# First argument is the target
126		if len(args) > 0:
127			self.target = args[0]
128		# Second argument is the node ID
129		if len(args) > 1:
130			self.id = args[1]
131
132	def enter(self):
133		BTNode.enter(self)
134		self.agent.navigateTo(self.target)
135
136	def execute(self, delta = 0):
137		ret = BTNode.execute(self, delta)
138		if self.target == None:
139			# failed executability conditions
140			print "exec", self.id, "false"
141			return False
142		elif distance(self.agent.getLocation(), self.target) < self.agent.getRadius():
143			# Execution succeeds
144			print "exec", self.id, "true"
145			return True
146		else:
147			# executing
148			return None
149		return ret
150
151##################
152### Retreat
153###
154### Move the agent back to the base to be healed
155### Parameters:
156###   0: percentage of hitpoints that must have been lost to retreat
157###   1: node ID string (optional)
158
159
160class Retreat(BTNode):
161	
162	### percentage: Percentage of hitpoints that must have been lost
163	
164	def parseArgs(self, args):
165		BTNode.parseArgs(self, args)
166		self.percentage = 0.5
167		# First argument is the factor
168		if len(args) > 0:
169			self.percentage = args[0]
170		# Second argument is the node ID
171		if len(args) > 1:
172			self.id = args[1]
173
174	def enter(self):
175		BTNode.enter(self)
176		self.agent.navigateTo(self.agent.world.getBaseForTeam(self.agent.getTeam()).getLocation())
177	
178	def execute(self, delta = 0):
179		ret = BTNode.execute(self, delta)
180		bases = self.agent.world.getEnemyBases(self.agent.getTeam())
181		if self.agent.getHitpoints() > self.agent.getMaxHitpoints() * self.percentage:
182			# fail executability conditions
183			print "exec", self.id, "false"
184			return False
185		elif self.agent.getHitpoints() == self.agent.getMaxHitpoints():
186			# Exection succeeds
187			print "exec", self.id, "true"
188			return True
189		else:
190			# executing
191			if distance(bases[0].getLocation(), self.agent.getLocation()) < 250:
192				return None
193			enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
194			for e in enemies:
195				if e in set(self.agent.getVisible()) and distance(self.agent.getLocation(),
196															 e.getLocation()) < 250 and isinstance(e, Minion):
197					return False
198					break
199			return None
200		return ret
201
202##################
203### ChaseMinion
204###
205### Find the closest minion and move to intercept it.
206### Parameters:
207###   0: node ID string (optional)
208
209
210class ChaseMinion(BTNode):
211
212	### target: the minion to chase
213	### timer: how often to replan
214
215	def parseArgs(self, args):
216		BTNode.parseArgs(self, args)
217		self.target = None
218		self.timer = 50
219		# First argument is the node ID
220		if len(args) > 0:
221			self.id = args[0]
222
223	def enter(self):
224		BTNode.enter(self)
225		self.timer = 50
226		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
227		if len(enemies) > 0:
228			best = None
229			dist = 0
230			for e in enemies:
231				if isinstance(e, Minion):
232					d = distance(self.agent.getLocation(), e.getLocation())
233					if best == None or d < dist:
234						best = e
235						dist = d
236			self.target = best
237		if self.target is not None:
238			navTarget = self.chooseNavigationTarget()
239			if navTarget is not None:
240				self.agent.navigateTo(navTarget)
241
242
243	def execute(self, delta = 0):
244		ret = BTNode.execute(self, delta)
245		if self.target == None or self.target.isAlive() == False:
246			# failed execution conditions
247			print "exec", self.id, "false"
248			return False
249		elif self.target is not None and distance(self.agent.getLocation(), self.target.getLocation()) < BIGBULLETRANGE:
250			# succeeded
251			print "exec", self.id, "true"
252			return True
253		else:
254			# executing
255			self.timer = self.timer - 1
256			if self.timer <= 0:
257				self.timer = 50
258				navTarget = self.chooseNavigationTarget()
259				if navTarget is not None:
260					self.agent.navigateTo(navTarget)
261			return None
262		return ret
263
264	def chooseNavigationTarget(self):
265		if self.target is not None:
266			return self.target.getLocation()
267		else:
268			return None
269
270##################
271### KillMinion
272###
273### Kill the closest minion. Assumes it is already in range.
274### Parameters:
275###   0: node ID string (optional)
276
277
278class KillMinion(BTNode):
279
280	### target: the minion to shoot
281
282	def parseArgs(self, args):
283		BTNode.parseArgs(self, args)
284		self.target = None
285		# First argument is the node ID
286		if len(args) > 0:
287			self.id = args[0]
288
289	def enter(self):
290		BTNode.enter(self)
291		self.agent.stopMoving()
292		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
293		if len(enemies) > 0:
294			best = None
295			dist = 0
296			for e in enemies:
297				if isinstance(e, Minion):
298					d = distance(self.agent.getLocation(), e.getLocation())
299					if best == None or d < dist:
300						best = e
301						dist = d
302			self.target = best
303
304
305	def execute(self, delta = 0):
306		ret = BTNode.execute(self, delta)
307		if self.target == None or distance(self.agent.getLocation(), self.target.getLocation()) > BIGBULLETRANGE:
308			# failed executability conditions
309			print "exec", self.id, "false"
310			return False
311		elif self.target.isAlive() == False:
312			# succeeded
313			print "exec", self.id, "true"
314			return True
315		else:
316			# executing
317			self.shootAtTarget()
318			return None
319		return ret
320
321	def shootAtTarget(self):
322		if self.agent is not None and self.target is not None:
323			self.agent.turnToFace(self.target.getLocation())
324			self.agent.shoot()
325
326
327##################
328### ChaseHero
329###
330### Move to intercept the enemy Hero.
331### Parameters:
332###   0: node ID string (optional)
333
334class ChaseHero(BTNode):
335
336	### target: the hero to chase
337	### timer: how often to replan
338
339	def ParseArgs(self, args):
340		BTNode.parseArgs(self, args)
341		self.target = None
342		self.timer = 50
343		# First argument is the node ID
344		if len(args) > 0:
345			self.id = args[0]
346
347	def enter(self):
348		BTNode.enter(self)
349		self.timer = 50
350		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
351		for e in enemies:
352			if isinstance(e, Hero):
353				self.target = e
354				navTarget = self.chooseNavigationTarget()
355				if navTarget is not None:
356					self.agent.navigateTo(navTarget)
357				return None
358
359
360	def execute(self, delta = 0):
361		ret = BTNode.execute(self, delta)
362		if self.target == None or self.target.isAlive() == False:
363			# fails executability conditions
364			print "exec", self.id, "false"
365			return False
366		elif distance(self.agent.getLocation(), self.target.getLocation()) < BIGBULLETRANGE:
367			# succeeded
368			print "exec", self.id, "true"
369			return True
370		else:
371			# executing
372			self.timer = self.timer - 1
373			if self.timer <= 0:
374				navTarget = self.chooseNavigationTarget()
375				if navTarget is not None:
376					self.agent.navigateTo(navTarget)
377			return None
378		return ret
379
380	def chooseNavigationTarget(self):
381		if self.target is not None:
382			return self.target.getLocation()
383		else:
384			return None
385
386##################
387### KillHero
388###
389### Kill the enemy hero. Assumes it is already in range.
390### Parameters:
391###   0: node ID string (optional)
392
393
394class KillHero(BTNode):
395
396	### target: the minion to shoot
397
398	def ParseArgs(self, args):
399		BTNode.parseArgs(self, args)
400		self.target = None
401		# First argument is the node ID
402		if len(args) > 0:
403			self.id = args[0]
404
405	def enter(self):
406		BTNode.enter(self)
407		self.agent.stopMoving()
408		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
409		for e in enemies:
410			if isinstance(e, Hero):
411				self.target = e
412				return None
413
414	def execute(self, delta = 0):
415		ret = BTNode.execute(self, delta)
416		if self.target == None or distance(self.agent.getLocation(), self.target.getLocation()) > BIGBULLETRANGE:
417			# failed executability conditions
418			if self.target == None:
419				print "foo none"
420			else:
421				print "foo dist", distance(self.agent.getLocation(), self.target.getLocation())
422			print "exec", self.id, "false"
423			return False
424		elif self.target.isAlive() == False:
425			# succeeded
426			print "exec", self.id, "true"
427			return True
428		else:
429			#executing
430			self.shootAtTarget()
431			return None
432		return ret
433
434	def shootAtTarget(self):
435		if self.agent is not None and self.target is not None:
436			self.agent.turnToFace(self.target.getLocation())
437			self.agent.shoot()
438
439
440##################
441### HitpointDaemon
442###
443### Only execute children if hitpoints are above a certain threshold.
444### Parameters:
445###   0: percentage of hitpoints that must have been lost to fail the daemon check
446###   1: node ID string (optional)
447
448
449class HitpointDaemon(BTNode):
450	
451	### percentage: percentage of hitpoints that must have been lost to fail the daemon check
452	
453	def parseArgs(self, args):
454		BTNode.parseArgs(self, args)
455		self.percentage = 0.5
456		# First argument is the factor
457		if len(args) > 0:
458			self.percentage = args[0]
459		# Second argument is the node ID
460		if len(args) > 1:
461			self.id = args[1]
462
463	def execute(self, delta = 0):
464		ret = BTNode.execute(self, delta)
465		if self.agent.getHitpoints() < self.agent.getMaxHitpoints() * self.percentage:
466			# Check failed
467			print "exec", self.id, "fail"
468			return False
469		else:
470			# Check didn't fail, return child's status
471			return self.getChild(0).execute(delta)
472		return ret
473
474##################
475### BuffDaemon
476###
477### Only execute children if agent's level is significantly above enemy hero's level.
478### Parameters:
479###   0: Number of levels above enemy level necessary to not fail the check
480###   1: node ID string (optional)
481
482class BuffDaemon(BTNode):
483
484	### advantage: Number of levels above enemy level necessary to not fail the check
485
486	def parseArgs(self, args):
487		BTNode.parseArgs(self, args)
488		self.advantage = 0
489		# First argument is the advantage
490		if len(args) > 0:
491			self.advantage = args[0]
492		# Second argument is the node ID
493		if len(args) > 1:
494			self.id = args[1]
495
496	def execute(self, delta = 0):
497		ret = BTNode.execute(self, delta)
498		hero = None
499		# Get a reference to the enemy hero
500		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
501		for e in enemies:
502			if isinstance(e, Hero):
503				hero = e
504				break
505		if hero == None or self.agent.level <= hero.level + self.advantage:
506			# fail check
507			print "exec", self.id, "fail"
508			return False
509		else:
510			# Check didn't fail, return child's status
511			return self.getChild(0).execute(delta)
512		return ret
513
514#################################
515### MY CUSTOM BEHAVIOR CLASSES
516
517class NoCloseEnemies(BTNode):
518
519	def parseArgs(self, args):
520		BTNode.parseArgs(self, args)
521		if len(args) > 0:
522			self.id = args[0]
523
524	def execute(self, delta=0):
525		ret = BTNode.execute(self, delta)
526		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
527		for e in enemies:
528			if e in set(self.agent.getVisible()) and distance(self.agent.getLocation(), e.getLocation()) < 250:
529				return False
530				break
531
532		return self.getChild(0).execute(delta)
533
534		return ret
535
536class CloseMinion(BTNode):
537
538	def parseArgs(self, args):
539		BTNode.parseArgs(self, args)
540		self.percentage = 0.5
541		# First argument is the factor
542		if len(args) > 0:
543			self.percentage = args[0]
544		# Second argument is the node ID
545		if len(args) > 1:
546			self.id = args[1]
547
548	def execute(self, delta=0):
549		ret = BTNode.execute(self, delta)
550		if self.agent.getHitpoints() > self.agent.getMaxHitpoints() * self.percentage:
551			# fail executability conditions
552			print "exec", self.id, "false"
553			return False
554		bases = self.agent.world.getEnemyBases(self.agent.getTeam())
555		for base in bases:
556			if distance(base.getLocation(), self.agent.getLocation()) < 250 :
557				return False
558		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
559		for e in enemies:
560			if e in set(self.agent.getVisible()) and distance(self.agent.getLocation(), e.getLocation()) < 250 and isinstance(e, Minion):
561				return self.getChild(0).execute(delta)
562				break
563
564		return False
565
566		return ret
567
568class StrafeKillHero(BTNode):
569	### target: the minion to shoot
570
571	def parseArgs(self, args):
572		BTNode.parseArgs(self, args)
573		self.target = None
574		# First argument is the node ID
575		if len(args) > 0:
576			self.id = args[0]
577
578	def enter(self):
579		BTNode.enter(self)
580		self.agent.stopMoving()
581		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
582		for e in enemies:
583			if isinstance(e, Hero) and e in self.agent.getVisible():
584				self.target = e
585				return None
586
587	def execute(self, delta=0):
588		ret = BTNode.execute(self, delta)
589		if self.target == None or self.target not in self.agent.getVisible() or distance(self.agent.getLocation(),
590																						 self.target.getLocation()) > BIGBULLETRANGE:
591			# failed executability conditions
592			if self.target == None:
593				print "foo none"
594			else:
595				print "foo dist", distance(self.agent.getLocation(), self.target.getLocation())
596			print "exec", self.id, "false"
597			return False
598		elif self.target.isAlive() == False:
599			# succeeded
600			print "exec", self.id, "true"
601			return True
602		else:
603			# executing
604			if self.agent.canAreaEffect() and distance(self.agent.getLocation(), self.target.getLocation()) <= (self.agent.getRadius() * 2):
605				self.agent.areaEffect()
606				return None
607			if self.agent.getMoveTarget() == None:
608				strafe(self.agent, self.target)
609			shootTarget(self.agent, self.target)
610			return None
611		return ret
612
613class StrafeKillMinion(BTNode):
614	### target: the minion to shoot
615
616	def parseArgs(self, args):
617		BTNode.parseArgs(self, args)
618		self.target = None
619		# First argument is the node ID
620		if len(args) > 0:
621			self.id = args[0]
622
623	def enter(self):
624		BTNode.enter(self)
625		self.agent.stopMoving()
626		enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
627		if len(enemies) > 0:
628			best = None
629			dist = 0
630			for e in enemies:
631				if isinstance(e, Minion) and e in self.agent.getVisible():
632					d = distance(self.agent.getLocation(), e.getLocation())
633					if best == None or d < dist:
634						best = e
635						dist = d
636			self.target = best
637
638	def execute(self, delta=0):
639		ret = BTNode.execute(self, delta)
640		if self.target == None or self.target not in self.agent.getVisible() or distance(self.agent.getLocation(),
641																						 self.target.getLocation()) > BIGBULLETRANGE:
642			# failed executability conditions
643			print "exec", self.id, "false"
644			return False
645		elif self.target.isAlive() == False:
646			# succeeded
647			print "exec", self.id, "true"
648			return True
649		else:
650			# executing
651			if self.agent.canAreaEffect() and distance(self.agent.getLocation(), self.target.getLocation()) <= (self.agent.getRadius() * 2):
652				self.agent.areaEffect()
653				return None
654			if self.agent.getMoveTarget() == None:
655				strafe(self.agent, self.target)
656			shootTarget(self.agent, self.target)
657			return None
658		return ret
659
660
661
662def strafe(agent, target):
663	enemyLocation = target.getLocation()
664	pos = agent.getLocation()
665	allPossiblePoints = agent.getPossibleDestinations()
666	targetPoints = []
667	for point in allPossiblePoints:
668		if distance(point, target.getLocation()) < 250 and distance(point, target.getLocation()) > 50:
669			targetPoints.append(point)
670	finalDest = random.choice(targetPoints)
671	ang = math.degrees(angle((enemyLocation[0] - pos[0], enemyLocation[1] - pos[1]), (finalDest[0] - pos[0], finalDest[1] - pos[1])))
672	while not clearShot(pos, finalDest, agent.world.getLinesWithoutBorders(), None, agent) or ang < 45 or ang > 135:
673		finalDest = random.choice(targetPoints)
674		ang = math.degrees(
675			angle((enemyLocation[0] - pos[0], enemyLocation[1] - pos[1]), (finalDest[0] - pos[0], finalDest[1] - pos[1])))
676	agent.navigateTo(finalDest)
677
678
679def shootTarget(agent, target):
680	if agent is not None and target is not None:
681		targetPos = target.getLocation()
682		if not target.isMoving():
683			agent.turnToFace(targetPos)
684			agent.shoot()
685		else:
686			angle = target.orientation
687			rad = math.radians(angle)
688			if angle < 0:
689				angle += 2*math.pi
690			nextPos = (target.speed[0]*math.cos(rad), -1 * target.speed[1]*math.sin(rad))
691			aimLocation = (targetPos[0] + nextPos[0] * 10, targetPos[1] + nextPos[1] * 10)
692			agent.turnToFace(aimLocation)
693			agent.shoot()
694
Full Screen