//// [overrideBaseIntersectionMethod.ts]
// Repro from #14615
type Constructor<T> = new (...args: any[]) => T;
const WithLocation = <T extends Constructor<Point>>(Base: T) => class extends Base {
getLocation(): [number, number] {
const [x,y] = super.getLocation();
return [this.x | x, this.y | y];
}
}
class Point {
constructor(public x: number, public y: number) { }
getLocation(): [number, number] {
return [0,0];
}
}
class Foo extends WithLocation(Point) {
calculate() {
return this.x + this.y;
}
getLocation() {
return super.getLocation()
}
whereAmI() {
return this.getLocation();
}
}
//// [overrideBaseIntersectionMethod.js]
"use strict";
// Repro from #14615
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var WithLocation = function (Base) { return /** @class */ (function (_super) {
__extends(class_1, _super);
function class_1() {
return _super !== null && _super.apply(this, arguments) || this;
}
class_1.prototype.getLocation = function () {
var _a = _super.prototype.getLocation.call(this), x = _a[0], y = _a[1];
return [this.x | x, this.y | y];
};
return class_1;
}(Base)); };
var Point = /** @class */ (function () {
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.getLocation = function () {
return [0, 0];
};
return Point;
}());
var Foo = /** @class */ (function (_super) {
__extends(Foo, _super);
function Foo() {
return _super !== null && _super.apply(this, arguments) || this;
}
Foo.prototype.calculate = function () {
return this.x + this.y;
};
Foo.prototype.getLocation = function () {
return _super.prototype.getLocation.call(this);
};
Foo.prototype.whereAmI = function () {
return this.getLocation();
};
return Foo;
}(WithLocation(Point)));
const { checkExist, setReload } = require('../../../util/utils');
const { mouseAction } = require('../../../util/actions');
test('Check Top align', async function() {
const { app } = require('../../../test');
await setReload();
await checkExist('#svgcanvas',15000);
const rect = await app.client.$('#left-Rectangle');
await rect.click();
await mouseAction([
{ type: 'pointerMove', x: 250, y: 250, duration: 100, },
{ type: 'pointerDown', button: 0, },
{ type: 'pointerMove', x: 300, y: 300, duration: 1000, },
{ type: 'pointerUp', button: 0, },
]);
await checkExist('#svg_1');
const rect2 = await app.client.$('#left-Rectangle');
await rect2.click();
await mouseAction([
{ type: 'pointerMove', x: 350, y: 350, duration: 100, },
{ type: 'pointerDown', button: 0, },
{ type: 'pointerMove', x: 400, y: 400, duration: 1000, },
{ type: 'pointerUp', button: 0, },
]);
await checkExist('#svg_2');
const rect3 = await app.client.$('#left-Rectangle');
await rect3.click();
await mouseAction([
{ type: 'pointerMove', x: 450, y: 450, duration: 100, },
{ type: 'pointerDown', button: 0, },
{ type: 'pointerMove', x: 500, y: 500, duration: 1000, },
{ type: 'pointerUp', button: 0, },
{ type: 'pointerMove', x: 510, y: 510, duration: 100, },
{ type: 'pointerDown', button: 0, },
{ type: 'pointerUp', button: 0, },
]);
await checkExist('#svg_3');
await mouseAction([
{ type: 'pointerMove', x: 100, y: 100, duration: 100, },
{ type: 'pointerDown', button: 0, },
{ type: 'pointerMove', x: 600, y: 600, duration: 1000, },
{ type: 'pointerUp', button: 0, },
]);
const topalign = await app.client.$('#qa-top_align');
await topalign.click();
const rectlocation = await app.client.$('#svg_1');
const rect2location = await app.client.$('#svg_2');
const rect3location = await app.client.$('#svg_3');
expect(await rectlocation.getLocation('y')).toEqual(await rect2location.getLocation('y'));
expect(await rectlocation.getLocation('y')).toEqual(await rect3location.getLocation('y'));
// console.log(await rectlocation.getLocation('y'));
await app.client.execute(() =>{
svgCanvas.undoMgr.undo();
});
});
test('Check Middle align', async function() {
const { app } = require('../../../test');
await mouseAction([
{ type: 'pointerMove', x: 100, y: 100, duration: 100, },
{ type: 'pointerDown', button: 0, },
{ type: 'pointerMove', x: 600, y: 600, duration: 1000, },
{ type: 'pointerUp', button: 0, },
]);
const middlealign = await app.client.$('#qa-middle_align');
await middlealign.click();
const rectlocation = await app.client.$('#svg_1');
const rect2location = await app.client.$('#svg_2');
const rect3location = await app.client.$('#svg_3');
// console.log(await rectlocation.getLocation('y'));
expect(await rectlocation.getLocation('y')).toEqual(await rect2location.getLocation('y'));
expect(await rectlocation.getLocation('y')).toEqual(await rect3location.getLocation('y'));
await app.client.execute(() =>{
svgCanvas.undoMgr.undo();
});
});
test('Check bottom align', async function() {
const { app } = require('../../../test');
await mouseAction([
{ type: 'pointerMove', x: 100, y: 100, duration: 100, },
{ type: 'pointerDown', button: 0, },
{ type: 'pointerMove', x: 600, y: 600, duration: 1000, },
{ type: 'pointerUp', button: 0, },
]);
const bottomalign = await app.client.$('#qa-bottom_align');
await bottomalign.click();
const rectlocation = await app.client.$('#svg_1');
const rect2location = await app.client.$('#svg_2');
const rect3location = await app.client.$('#svg_3');
// console.log(await rectlocation.getLocation('y'));
expect(await rectlocation.getLocation('y')).toEqual(await rect2location.getLocation('y'));
expect(await rectlocation.getLocation('y')).toEqual(await rect3location.getLocation('y'));
await app.client.execute(() =>{
svgCanvas.undoMgr.undo();
});
});
test('Check Left align', async function() {
const { app } = require('../../../test');
await mouseAction([
{ type: 'pointerMove', x: 100, y: 100, duration: 100, },
{ type: 'pointerDown', button: 0, },
{ type: 'pointerMove', x: 600, y: 600, duration: 1000, },
{ type: 'pointerUp', button: 0, },
]);
const leftalign = await app.client.$('#qa-left_align');
await leftalign.click();
const rectlocation = await app.client.$('#svg_1');
const rect2location = await app.client.$('#svg_2');
const rect3location = await app.client.$('#svg_3');
expect(await rectlocation.getLocation('x')).toEqual(await rect2location.getLocation('x'));
expect(await rectlocation.getLocation('x')).toEqual(await rect3location.getLocation('x'));
// console.log(await rectlocation.getLocation('x'));
await app.client.execute(() =>{
svgCanvas.undoMgr.undo();
});
});
test('check Center align', async function() {
const { app } = require('../../../test');
await mouseAction([
{ type: 'pointerMove', x: 100, y: 100, duration: 100, },
{ type: 'pointerDown', button: 0, },
{ type: 'pointerMove', x: 600, y: 600, duration: 1000, },
{ type: 'pointerUp', button: 0, },
]);
const centeralign = await app.client.$('#qa-center_align');
await centeralign.click();
const rectlocation = await app.client.$('#svg_1');
const rect2location = await app.client.$('#svg_2');
const rect3location = await app.client.$('#svg_3');
expect(await rectlocation.getLocation('x')).toEqual(await rect2location.getLocation('x'));
expect(await rectlocation.getLocation('x')).toEqual(await rect3location.getLocation('x'));
// console.log(await rectlocation.getLocation('x'));
await app.client.execute(() =>{
svgCanvas.undoMgr.undo();
});
});
test('check Right align', async function() {
const { app } = require('../../../test');
await mouseAction([
{ type: 'pointerMove', x: 100, y: 100, duration: 100, },
{ type: 'pointerDown', button: 0, },
{ type: 'pointerMove', x: 600, y: 600, duration: 1000, },
{ type: 'pointerUp', button: 0, },
]);
const rightalign = await app.client.$('#qa-right_align');
await rightalign.click();
const rectlocation = await app.client.$('#svg_1');
const rect2location = await app.client.$('#svg_2');
const rect3location = await app.client.$('#svg_3');
expect(await rectlocation.getLocation('x')).toEqual(await rect2location.getLocation('x'));
expect(await rectlocation.getLocation('x')).toEqual(await rect3location.getLocation('x'));
// console.log(await rectlocation.getLocation('x'));
await app.client.execute(() =>{
svgCanvas.undoMgr.undo();
});
});
/******************************************************************************/
/* getLocation.js */
/* Author: Seung Jae Lee */
/* */
/* This is a mocha test file that tests getLocation() function in scraper.js. */
/******************************************************************************/
var assert = require("assert");
var scraper = require('../scraper.js');
describe('getLocation()', function() {
describe('no match', function() {
it('getLocation(\"\") should equal \"\"', function() {
assert.equal(scraper.getLocation(""), "");
})
it('getLocation(\"qqq\") should equal \"\"', function() {
assert.equal(scraper.getLocation("xyz"), "");
})
})
describe('one match', function() {
it('getLocation(\"clapp\") should equal \"1927 - Clapp Hall\"', function() {
assert.equal(scraper.getLocation("clapp"), "1927 - Clapp Hall");
})
it('getLocation(\"come to dod hall!\") should equal \"Dod Hall\"', function() {
assert.equal(scraper.getLocation("come to dod hall!"), "Dod Hall");
})
})
describe('case-insensitive match', function() {
it('getLocation(\"EQuad has food\") should equal \"Enginerring QUAD\"', function() {
assert.equal(scraper.getLocation("EQuad has food"), "Enginerring QUAD");
})
it('getLocation(\"FRIST HAS FOOD\") should equal \"Frist Campus Center\"', function() {
assert.equal(scraper.getLocation("FRIST HAS FOOD"), "Frist Campus Center");
})
it('getLocation(\"Pizza at CoLoNiAl ClUb\") should equal \"Colonial Club\"', function() {
assert.equal(scraper.getLocation("Pizza at CoLoNiAl ClUb"), "Colonial Club");
})
})
describe('punctuation deletion', function() {
it('getLocation(\"Come to F,r,i,s,t\") should equal \"Frist Campus Center\"', function() {
assert.equal(scraper.getLocation("Come to F,r,i,s,t"), "Frist Campus Center");
})
it('getLocation(\"Edward\'s Hall\") should equal \"Edwards Hall\"', function() {
assert.equal(scraper.getLocation("Edward\'s Hall"), "Edwards Hall");
})
})
describe('regex match', function() {
it('getLocation(\"Friend 112\") should equal \"Friend Center\"', function() {
assert.equal(scraper.getLocation("Friend 112"), "Friend Center");
})
it('getLocation(\"Lewis 123\") should equal \"Lewis Library\"', function() {
assert.equal(scraper.getLocation("Lewis 123"), "Lewis Library");
})
})
describe('biggest substring', function(){
it('getLocation(\"Ticket holders to Friend Center\") should equal \"Friend Center\"', function() {
assert.equal(scraper.getLocation("Ticket holders to Friend Center"), "Friend Center");
})
it('getLocation(\"Lewis 123, Bring your spoon!\") should equal \"Lewis Library\"', function() {
assert.equal(scraper.getLocation("Lewis 123, Bring your spoon!"), "Lewis Library");
})
});
});
from Plot import *
from Robot import *
import sys
import math
filename=sys.argv[1]
algorithmChoice=int(sys.argv[2])
runs=1
totalRuns=1
try: #Handles having just 2 arguments
totalRuns=int(sys.argv[3])
except IndexError:
print "Number of runs was not specified. Setting totalRuns to default.(1)"
averageCrops=0
#will run totalRuns times
while runs<=totalRuns:
p = Plot() #create plot
robot = Robot() #create robot
walls = []
walls.append([])
walls = p.RetrievePlot(filename, walls)
runs+=1
if algorithmChoice == 1 or algorithmChoice == 5: #These algorithms are similar. They run the same code but altered slightly.
highestPercentLocation=(0,0)
highestPercent=0
bestCrop=(0,0)
if algorithmChoice == 5: #Algorithm 5 finds the best coordinate for crops that have highest probability of growing the most
bestCrop = (0, 0)
bestTime = 999
for crop in p.cropCoordinates: #algorithm for calculating the location
percent = p.plotDictionary[crop][0]
avg = math.ceil(1 / percent)
refresh = (percent ** 2) * 100
total = avg + refresh
if total < bestTime:
bestTime = total
bestCrop = crop
elif algorithmChoice == 1: #If algorithm 1, find the highest percentage crop location
highestPercent=0
highestPercentLocation=(0,0)
for j in p.cropCoordinates:
if highestPercent < p.plotDictionary[j][0]:
highestPercentLocation=j
highestPercent=p.plotDictionary[j][0]
count = 0
time = (p.xLimit * p.yLimit) * .25 #time unit for this algorithm. If needed, comment this and uncomment the next to test different times
#time=500
visitedCoordinates = [] #Holds the coordinates we have already been to so we dont go over them more than once.
wallCoordinates = [] #Holds the coordinates of the walls. Not counting the outer walls.
traverse = [] #traverse holds the coordinates to help manuever around walls
wallFound = False #Holds whether or not we have run into a wall.
found = False #If the location is found, we will make this true.
while count <= time:
if found != True:
wallFound = False
visitedCoordinates = [robot.GetLocation()]
if algorithmChoice == 5:
currentEndpoint = bestCrop
elif algorithmChoice == 1:
currentEndpoint = highestPercentLocation
prevCoord = (0, 0) #Holds previous coordinate in order to check for
while robot.GetLocation() != currentEndpoint and count<=time: #move the robot until you hit the location or time runs out
if prevCoord == robot.GetLocation():
visitedCoordinates = [robot.GetLocation()]
prevCoord = robot.GetLocation()
p.UpdatePlot() #Update the plot
#The following if statements check for walls in each direction and determines if it has been visited or not.
#This will determine which direction the robot will move until it hits a wall.
if robot.GetLocation()[0] < currentEndpoint[0] and robot.GetLocation()[1] < currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1)][
0] != "#" and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1) not in visitedCoordinates:
robot.MoveNorthEast()
elif robot.GetLocation()[0] < currentEndpoint[0] and robot.GetLocation()[1] > currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1)][
0] != "#" and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1) not in visitedCoordinates:
robot.MoveSouthEast()
elif robot.GetLocation()[0] > currentEndpoint[0] and robot.GetLocation()[1] > currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1)][
0] != "#" and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1) not in visitedCoordinates:
robot.MoveSouthWest()
elif robot.GetLocation()[0] > currentEndpoint[0] and robot.GetLocation()[1] < currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1)][
0] != "#" and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1) not in visitedCoordinates:
robot.MoveNorthWest()
elif robot.GetLocation()[0] < currentEndpoint[0] and \
p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1])][
0] != "#" and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1]) not in visitedCoordinates:
robot.MoveEast()
elif robot.GetLocation()[0] > currentEndpoint[0] and \
p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1])][
0] != "#" and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1]) not in visitedCoordinates:
robot.MoveWest()
elif robot.GetLocation()[1] < currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] + 1)][
0] != "#" and (
robot.GetLocation()[0], robot.GetLocation()[1] + 1) not in visitedCoordinates:
robot.MoveNorth()
elif robot.GetLocation()[1] > currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] - 1)][
0] != "#" and (
robot.GetLocation()[0], robot.GetLocation()[1] - 1) not in visitedCoordinates:
robot.MoveSouth()
else: #If it reaches here, a wall has been reached
if wallFound == False:
wallFound = True
x = robot.GetLocation()[0]
y = robot.GetLocation()[1]
coord = (0, 0)
if p.plotDictionary[(x + 1, y)][0] == "#":
coord = (x + 1, y)
elif p.plotDictionary[(x - 1, y)][0] == "#":
coord = (x - 1, y)
elif p.plotDictionary[(x, y + 1)][0] == "#":
coord = (x, y + 1)
elif p.plotDictionary[(x, y - 1)][0] == "#":
coord = (x, y - 1)
for w in walls: #find the coordinate of the wall and find the list of coordinates of the wall in the wall list
if coord in w:
wallCoordinates = w
#We populate the traverse list in order to move the robot around the wall
for c in wallCoordinates:
if p.plotDictionary[(c[0] + 1, c[1])][0] != "#" and (
c[0] + 1, c[1]) not in traverse and (
c[0] + 1, c[1]) not in wallCoordinates:
traverse.append((c[0] + 1, c[1]))
if p.plotDictionary[(c[0] - 1, c[1])][0] != "#" and (
c[0] - 1, c[1]) not in traverse and (
c[0] - 1, c[1]) not in wallCoordinates:
traverse.append((c[0] - 1, c[1]))
if p.plotDictionary[(c[0], c[1] + 1)][0] != "#" and (
c[0], c[1] + 1) not in traverse and (
c[0], c[1] + 1) not in wallCoordinates:
traverse.append((c[0], c[1] + 1))
if p.plotDictionary[(c[0], c[1] - 1)][0] != "#" and (
c[0], c[1] - 1) not in traverse and (
c[0], c[1] - 1) not in wallCoordinates:
traverse.append((c[0], c[1] - 1))
if p.plotDictionary[(c[0] + 1, c[1] + 1)][0] != "#" and (
c[0] + 1, c[1] + 1) not in traverse and (
c[0] + 1, c[1] + 1) not in wallCoordinates:
traverse.append((c[0] + 1, c[1] + 1))
if p.plotDictionary[(c[0] - 1, c[1] + 1)][0] != "#" and (
c[0] - 1, c[1] + 1) not in traverse and (
c[0] - 1, c[1] + 1) not in wallCoordinates:
traverse.append((c[0] - 1, c[1] + 1))
if p.plotDictionary[(c[0] + 1, c[1] - 1)][0] != "#" and (
c[0] + 1, c[1] - 1) not in traverse and (
c[0] + 1, c[1] - 1) not in wallCoordinates:
traverse.append((c[0] + 1, c[1] - 1))
if p.plotDictionary[(c[0] - 1, c[1] - 1)][0] != "#" and (
c[0] - 1, c[1] - 1) not in traverse and (
c[0] - 1, c[1] - 1) not in wallCoordinates:
traverse.append((c[0] - 1, c[1] - 1))
#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.
if p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1)][0] != "#" and (
robot.GetLocation()[0] + 1,
robot.GetLocation()[1] + 1) not in visitedCoordinates and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1) in traverse:
robot.MoveNorthEast()
elif p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1)][0] != "#" and (
robot.GetLocation()[0] + 1,
robot.GetLocation()[1] - 1) not in visitedCoordinates and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1) in traverse:
robot.MoveSouthEast()
elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1)][0] != "#" and (
robot.GetLocation()[0] - 1,
robot.GetLocation()[1] - 1) not in visitedCoordinates and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1) in traverse:
robot.MoveSouthWest()
elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1)][0] != "#" and (
robot.GetLocation()[0] - 1,
robot.GetLocation()[1] + 1) not in visitedCoordinates and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1) in traverse:
robot.MoveNorthWest()
elif p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1])][0] != "#" and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1]) not in visitedCoordinates and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1]) in traverse:
robot.MoveEast()
elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1])][0] != "#" and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1]) not in visitedCoordinates and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1]) in traverse:
robot.MoveWest()
elif p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] + 1)][0] != "#" and (
robot.GetLocation()[0], robot.GetLocation()[1] + 1) not in visitedCoordinates and (
robot.GetLocation()[0], robot.GetLocation()[1] + 1) in traverse:
robot.MoveNorth()
elif p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] - 1)][0] != "#" and (
robot.GetLocation()[0], robot.GetLocation()[1] - 1) not in visitedCoordinates and (
robot.GetLocation()[0], robot.GetLocation()[1] - 1) in traverse:
robot.MoveSouth()
count += 1
visitedCoordinates.append(robot.GetLocation())
if robot.CheckForCrop(p.plotDictionary): #check for a crop
p.RemoveCrop(robot.x, robot.y)
found = True
else:
if algorithmChoice == 1: #if algorithm 1 just sit there and collect. If 5, follow the collection algorithm below.
while count <= time:
p.UpdatePlot()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x,robot.y)
count+=1
elif algorithmChoice == 5: #Ran out of time to fix. Only works if current location has all 8 surrounding tiles as plots and not walls
iter = 0
while count <= time:
p.UpdatePlot()
if iter == 0:
robot.MoveNorth()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
iter += 1
count += 1
elif iter == 1:
robot.MoveEast()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
iter += 1
count += 1
elif iter == 2:
robot.MoveSouth()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
iter += 1
count += 1
elif iter == 3:
robot.MoveSouth()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
iter += 1
count += 1
elif iter == 4:
robot.MoveWest()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
iter += 1
count += 1
elif iter == 5:
robot.MoveWest()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
iter += 1
count += 1
elif iter == 6:
robot.MoveNorth()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
iter += 1
count += 1
elif iter == 7:
robot.MoveNorth()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
iter += 1
count += 1
elif iter == 8:
robot.MoveSouthEast()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
iter = 0
count += 1
#print "Number of crops found = " + str(robot.numberOfCrops) #Uncomment this to see total per run
averageCrops+=robot.numberOfCrops #add so we can average the values at the end.
elif algorithmChoice == 2: #Algorithm 2 begins running here
time = (p.xLimit * p.yLimit) * .25
#time=500
count = 0
while count != time:
rand = random.random() #Get a random number to determine direction
rand *= 100
if rand < 12.5: #rand will determine direction.
while count != time: #Go until time runs out or hit a wall
p.UpdatePlot()
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] += 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveNorth()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
count += 1
else:
break
elif rand >= 12.5 and rand < 25: #Same as above comment, just different direction
while count != time:
p.UpdatePlot()
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] += 1
current[0] += 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveNorthEast()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
count += 1
else:
break
elif rand >= 25 and rand < 37.5:
while count != time:
p.UpdatePlot()
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[0] += 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveEast()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
count += 1
else:
break
elif rand >= 37.5 and rand < 50:
while count != time:
p.UpdatePlot()
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] -= 1
current[0] += 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveSouthEast()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
count += 1
else:
break
elif rand >= 50 and rand < 62.5:
while count != time:
p.UpdatePlot()
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] -= 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveSouth()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
count += 1
else:
break
elif rand >= 62.5 and rand < 75:
while count != time:
p.UpdatePlot()
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] -= 1
current[0] -= 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveSouthWest()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
count += 1
else:
break
elif rand >= 75 and rand < 87.5:
while count != time:
p.UpdatePlot()
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[0] -= 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveWest()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
count += 1
else:
break
elif rand >= 87.5:
while count != time:
p.UpdatePlot()
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] += 1
current[0] -= 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveNorthWest()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
count += 1
else:
break
#print "Number of crops found = " + str(robot.numberOfCrops)
averageCrops+=robot.numberOfCrops
elif algorithmChoice == 3: #Choose random direction every unit of time
time = (p.xLimit * p.yLimit) * .25
#time=500
count = 0
while count != time: #Similar to above but instead of while inside of if statements, its outside.
p.UpdatePlot() #Update plot and randomize direction every turn
rand = random.random()
rand *= 100
if rand < 12.5:
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] += 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveNorth()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
elif rand >= 12.5 and rand < 25:
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] += 1
current[0] += 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveNorthEast()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
elif rand >= 25 and rand < 37.5:
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[0] += 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveEast()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
elif rand >= 37.5 and rand < 50:
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] -= 1
current[0] += 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveSouthEast()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
elif rand >= 50 and rand < 62.5:
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] -= 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveSouth()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
elif rand >= 62.5 and rand < 75:
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] -= 1
current[0] -= 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveSouthWest()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
elif rand >= 75 and rand < 87.5:
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[0] -= 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveWest()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
else:
current = [robot.GetLocation()[0], robot.GetLocation()[1]]
current[1] += 1
current[0] -= 1
check = (current[0], current[1])
if p.plotDictionary[check][0] != "#" and check[0] != 0 and check[1] != 0:
robot.MoveNorthWest()
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
count += 1
#print "Number of crops found = " + str(robot.numberOfCrops)
averageCrops+=robot.numberOfCrops
elif algorithmChoice == 4: #This algorithm finds a location and goes to said location. Uses same traverse technique as 1 and 5
count = 0
time = (p.xLimit * p.yLimit) * .25
#time = 500
visitedCoordinates = [] #similar variables as algorithm 1,5
wallCoordinates = []
traverse = []
wallFound = False
while count != time:
wallFound = False
visitedCoordinates = [robot.GetLocation()]
arrayLength = len(p.cropCoordinates)
rand = random.random()
rand *= 100
rand = int(rand % arrayLength)
currentEndpoint = p.cropCoordinates[rand] #Get a random coordinate containing a crop
prevCoord = (0, 0)
# Same as algorithm 1,5. Determine which direction to go until hit a wall
# However, after reaching the random location, we choose another coordinate to go to, which is why we use the while loop
while robot.GetLocation() != currentEndpoint and count != time:
if prevCoord == robot.GetLocation():
visitedCoordinates = [robot.GetLocation()]
prevCoord = robot.GetLocation()
p.UpdatePlot()
if robot.GetLocation()[0] < currentEndpoint[0] and robot.GetLocation()[1] < currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1)][
0] != "#" and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1) not in visitedCoordinates:
robot.MoveNorthEast()
elif robot.GetLocation()[0] < currentEndpoint[0] and robot.GetLocation()[1] > currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1)][
0] != "#" and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1) not in visitedCoordinates:
robot.MoveSouthEast()
elif robot.GetLocation()[0] > currentEndpoint[0] and robot.GetLocation()[1] > currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1)][
0] != "#" and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1) not in visitedCoordinates:
robot.MoveSouthWest()
elif robot.GetLocation()[0] > currentEndpoint[0] and robot.GetLocation()[1] < currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1)][
0] != "#" and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1) not in visitedCoordinates:
robot.MoveNorthWest()
elif robot.GetLocation()[0] < currentEndpoint[0] and \
p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1])][0] != "#" and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1]) not in visitedCoordinates:
robot.MoveEast()
elif robot.GetLocation()[0] > currentEndpoint[0] and \
p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1])][0] != "#" and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1]) not in visitedCoordinates:
robot.MoveWest()
elif robot.GetLocation()[1] < currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] + 1)][0] != "#" and (
robot.GetLocation()[0], robot.GetLocation()[1] + 1) not in visitedCoordinates:
robot.MoveNorth()
elif robot.GetLocation()[1] > currentEndpoint[1] and \
p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] - 1)][0] != "#" and (
robot.GetLocation()[0], robot.GetLocation()[1] - 1) not in visitedCoordinates:
robot.MoveSouth()
else: #if running into the wall, make traverse wall and continue
if wallFound == False:
wallFound = True
x = robot.GetLocation()[0]
y = robot.GetLocation()[1]
coord = (0, 0)
if p.plotDictionary[(x + 1, y)][0] == "#":
coord = (x + 1, y)
elif p.plotDictionary[(x - 1, y)][0] == "#":
coord = (x - 1, y)
elif p.plotDictionary[(x, y + 1)][0] == "#":
coord = (x, y + 1)
elif p.plotDictionary[(x, y - 1)][0] == "#":
coord = (x, y - 1)
for w in walls:
if coord in w:
wallCoordinates = w
for c in wallCoordinates:
if p.plotDictionary[(c[0] + 1, c[1])][0] != "#" and (c[0] + 1, c[1]) not in traverse and (
c[0] + 1, c[1]) not in wallCoordinates:
traverse.append((c[0] + 1, c[1]))
if p.plotDictionary[(c[0] - 1, c[1])][0] != "#" and (c[0] - 1, c[1]) not in traverse and (
c[0] - 1, c[1]) not in wallCoordinates:
traverse.append((c[0] - 1, c[1]))
if p.plotDictionary[(c[0], c[1] + 1)][0] != "#" and (c[0], c[1] + 1) not in traverse and (
c[0], c[1] + 1) not in wallCoordinates:
traverse.append((c[0], c[1] + 1))
if p.plotDictionary[(c[0], c[1] - 1)][0] != "#" and (c[0], c[1] - 1) not in traverse and (
c[0], c[1] - 1) not in wallCoordinates:
traverse.append((c[0], c[1] - 1))
if p.plotDictionary[(c[0] + 1, c[1] + 1)][0] != "#" and (
c[0] + 1, c[1] + 1) not in traverse and (c[0] + 1, c[1] + 1) not in wallCoordinates:
traverse.append((c[0] + 1, c[1] + 1))
if p.plotDictionary[(c[0] - 1, c[1] + 1)][0] != "#" and (
c[0] - 1, c[1] + 1) not in traverse and (c[0] - 1, c[1] + 1) not in wallCoordinates:
traverse.append((c[0] - 1, c[1] + 1))
if p.plotDictionary[(c[0] + 1, c[1] - 1)][0] != "#" and (
c[0] + 1, c[1] - 1) not in traverse and (c[0] + 1, c[1] - 1) not in wallCoordinates:
traverse.append((c[0] + 1, c[1] - 1))
if p.plotDictionary[(c[0] - 1, c[1] - 1)][0] != "#" and (
c[0] - 1, c[1] - 1) not in traverse and (c[0] - 1, c[1] - 1) not in wallCoordinates:
traverse.append((c[0] - 1, c[1] - 1))
if p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1)][0] != "#" and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1) not in visitedCoordinates and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1] + 1) in traverse:
robot.MoveNorthEast()
elif p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1)][0] != "#" and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1) not in visitedCoordinates and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1] - 1) in traverse:
robot.MoveSouthEast()
elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1)][0] != "#" and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1) not in visitedCoordinates and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1] - 1) in traverse:
robot.MoveSouthWest()
elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1)][0] != "#" and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1) not in visitedCoordinates and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1] + 1) in traverse:
robot.MoveNorthWest()
elif p.plotDictionary[(robot.GetLocation()[0] + 1, robot.GetLocation()[1])][0] != "#" and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1]) not in visitedCoordinates and (
robot.GetLocation()[0] + 1, robot.GetLocation()[1]) in traverse:
robot.MoveEast()
elif p.plotDictionary[(robot.GetLocation()[0] - 1, robot.GetLocation()[1])][0] != "#" and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1]) not in visitedCoordinates and (
robot.GetLocation()[0] - 1, robot.GetLocation()[1]) in traverse:
robot.MoveWest()
elif p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] + 1)][0] != "#" and (
robot.GetLocation()[0], robot.GetLocation()[1] + 1) not in visitedCoordinates and (
robot.GetLocation()[0], robot.GetLocation()[1] + 1) in traverse:
robot.MoveNorth()
elif p.plotDictionary[(robot.GetLocation()[0], robot.GetLocation()[1] - 1)][0] != "#" and (
robot.GetLocation()[0], robot.GetLocation()[1] - 1) not in visitedCoordinates and (
robot.GetLocation()[0], robot.GetLocation()[1] - 1) in traverse:
robot.MoveSouth()
count += 1
visitedCoordinates.append(robot.GetLocation())
if robot.CheckForCrop(p.plotDictionary):
p.RemoveCrop(robot.x, robot.y)
#print "Number of crops found = " + str(robot.numberOfCrops)
averageCrops+=robot.numberOfCrops
else:
print "Algorithm not found."
averageCrops=float(float(averageCrops)/float(totalRuns))
print "Average number of crops found per run = " + str(averageCrops)
'''
* Copyright (c) 2014, 2015 Entertainment Intelligence Lab, Georgia Institute of Technology.
* Originally developed by Mark Riedl.
* Last edited by Mark Riedl 05/2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
'''
import sys, pygame, math, numpy, random, time, copy
from pygame.locals import *
from constants import *
from utils import *
from core import *
from moba import *
class MyMinion(Minion):
def __init__(self, position, orientation, world, image = NPC, speed = SPEED, viewangle = 360, hitpoints = HITPOINTS, firerate = FIRERATE, bulletclass = SmallBullet):
Minion.__init__(self, position, orientation, world, image, speed, viewangle, hitpoints, firerate, bulletclass)
self.states = [Idle]
### Add your states to self.states (but don't remove Idle)
### YOUR CODE GOES BELOW HERE ###
self.states.append(Move)
self.states.append(Attack)
self.states.append(MovingAttack)
### YOUR CODE GOES ABOVE HERE ###
def start(self):
Minion.start(self)
self.changeState(Idle)
############################
### Idle
###
### 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.
class Idle(State):
def enter(self, oldstate):
State.enter(self, oldstate)
# stop moving
self.agent.stopMoving()
def execute(self, delta = 0):
State.execute(self, delta)
### YOUR CODE GOES BELOW HERE ###
self.agent.changeState(Move)
### YOUR CODE GOES ABOVE HERE ###
return None
##############################
### Taunt
###
### This is a state given as an example of how to pass arbitrary parameters into a State.
### To taunt someome, Agent.changeState(Taunt, enemyagent)
class Taunt(State):
def parseArgs(self, args):
self.victim = args[0]
def execute(self, delta = 0):
if self.victim is not None:
print "Hey " + str(self.victim) + ", I don't like you!"
self.agent.changeState(Idle)
##############################
### YOUR STATES GO HERE:
def closestTarget(agent, targets):
agentLocation = agent.getLocation()
returnTarget = None
targetDist = INFINITY
for target in targets:
if distance(agentLocation, target.getLocation()) < targetDist:
returnTarget = target
targetDist = distance(agentLocation, target.getLocation())
return returnTarget
def shootTarget(agent, target):
agent.turnToFace(target.getLocation())
agent.shoot()
class Move(State):
def enter(self, oldstate):
State.enter(self, oldstate)
towers = self.agent.world.getEnemyTowers(self.agent.getTeam())
bases = self.agent.world.getEnemyBases(self.agent.getTeam())
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
if len(towers) > 0:
self.agent.navigateTo(closestTarget(self.agent, towers).getLocation())
elif len(bases) > 0:
self.agent.navigateTo(closestTarget(self.agent, bases).getLocation())
elif len(enemies) > 0:
self.agent.navigateTo(closestTarget(self.agent, enemies).getLocation())
def execute(self, delta = 0):
towers = self.agent.world.getEnemyTowers(self.agent.getTeam())
bases = self.agent.world.getEnemyBases(self.agent.getTeam())
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
if not self.agent.isMoving():
self.agent.changeState(Move)
if len(towers) > 0:
destinationTower = closestTarget(self.agent, towers)
#self.agent.navigateTo(destinationTower.getLocation())
elif len(bases) > 0:
destinationBase = closestTarget(self.agent, bases)
#self.agent.navigateTo(destinationBase.getLocation())
elif len(enemies) > 0:
destinationEnemy = closestTarget(self.agent, enemies)
#self.agent.navigateTo(destinationEnemy.getLocation())
if len(towers) > 0 and distance(self.agent.getLocation(),
destinationTower.getLocation()) < 150 and rayTraceWorld(
self.agent.getLocation(), destinationTower.getLocation(),
self.agent.world.getLinesWithoutBorders()) is None:
self.agent.changeState(Attack, destinationTower)
if len(bases) > 0 and len(towers) == 0 and distance(self.agent.getLocation(),
destinationBase.getLocation()) < 150 and rayTraceWorld(
self.agent.getLocation(), destinationBase.getLocation(),
self.agent.world.getLinesWithoutBorders()) is None:
self.agent.changeState(Attack, destinationBase)
if len(enemies) > 0 and len(bases) == 0 and len(towers) == 0 and distance(self.agent.getLocation(),
destinationEnemy.getLocation()) < 150 and rayTraceWorld(
self.agent.getLocation(), destinationEnemy.getLocation(),
self.agent.world.getLinesWithoutBorders()) is None:
if destinationEnemy.isMoving():
self.agent.changeState(MovingAttack, destinationEnemy)
else:
self.agent.changeState(Attack, destinationEnemy)
class Attack(State):
def parseArgs(self, args):
self.target = args[0]
def enter(self, oldstate):
State.enter(self, oldstate)
if isinstance(self.target, MOBAAgent):
if self.target.isMoving():
self.agent.changeState(MovingAttack, self.target)
self.agent.stopMoving()
towers = self.agent.world.getEnemyTowers(self.agent.getTeam())
bases = self.agent.world.getEnemyBases(self.agent.getTeam())
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
allPossiblePoints = self.agent.getPossibleDestinations()
self.targetPoints = []
for point in allPossiblePoints:
if distance(point, self.target.getLocation()) < 150 and distance(point, self.target.getLocation()) > 50:
self.targetPoints.append(point)
if self.target in set(towers) or self.target in set(bases) or self.target in set(enemies):
shootTarget(self.agent, self.target)
else: self.agent.changeState(Move)
def execute(self, delta = 0):
if isinstance(self.target, MOBAAgent):
if self.target.isMoving():
self.agent.changeState(MovingAttack, self.target)
towers = self.agent.world.getEnemyTowers(self.agent.getTeam())
bases = self.agent.world.getEnemyBases(self.agent.getTeam())
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
if not self.agent.isMoving():
self.agent.navigateTo(random.choice(self.targetPoints))
if self.target in set(towers) or self.target in set(bases) or self.target in set(enemies):
shootTarget(self.agent, self.target)
else:
self.agent.changeState(Move)
class MovingAttack(State):
def parseArgs(self, args):
self.target = args[0]
def enter(self, oldstate):
State.enter(self, oldstate)
if not self.target.isMoving():
self.agent.changeState(Attack, self.target)
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
if self.target in set(enemies):
self.agent.navigateTo(self.target.getLocation())
shootTarget(self.agent, self.target)
else: self.agent.changeState(Move)
def execute(self, delta = 0):
if not self.target.isMoving():
self.agent.changeState(Attack, self.target)
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
if self.target in set(enemies):
self.agent.navigateTo(self.target.getLocation())
shootTarget(self.agent, self.target)
else: self.agent.changeState(Move)
'''
* Copyright (c) 2014, 2015 Entertainment Intelligence Lab, Georgia Institute of Technology.
* Originally developed by Mark Riedl.
* Last edited by Mark Riedl 05/2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
'''
import sys, pygame, math, numpy, random, time, copy
from pygame.locals import *
from constants import *
from utils import *
from core import *
from moba2 import *
from btnode import *
###########################
### SET UP BEHAVIOR TREE
def treeSpec(agent):
myid = str(agent.getTeam())
spec = None
### YOUR CODE GOES BELOW HERE ###
spec = [(Selector, "root"),
[(Selector, "retreat or fight"),
[(CloseMinion, 0.5, "minion nearby"),
(StrafeKillMinion, "kill minion retreat")],
(Retreat, 0.5, "retreat")],
[(HitpointDaemon, 0.25, "good to fight"),
[(Selector, "chase or kill"),
[(NoCloseEnemies, "no close enemies"),
[(Selector, "chase hero or minion"),
[(BuffDaemon, -1, "hero strong"),
(ChaseHero, "chase hero")
],
(ChaseMinion, "chase minion"),
(ChaseHero, "chase hero if no minion")
]
],
[(Selector, "kill hero or minion"),
(StrafeKillHero, "kill hero"),
(StrafeKillMinion, "kill minion")
]
]
]
]
### YOUR CODE GOES ABOVE HERE ###
return spec
def myBuildTree(agent):
myid = str(agent.getTeam())
root = None
### YOUR CODE GOES BELOW HERE ###
### YOUR CODE GOES ABOVE HERE ###
return root
### Helper function for making BTNodes (and sub-classes of BTNodes).
### type: class type (BTNode or a sub-class)
### agent: reference to the agent to be controlled
### This function takes any number of additional arguments that will be passed to the BTNode and parsed using BTNode.parseArgs()
def makeNode(type, agent, *args):
node = type(agent, args)
return node
###############################
### BEHAVIOR CLASSES:
##################
### Taunt
###
### Print disparaging comment, addressed to a given NPC
### Parameters:
### 0: reference to an NPC
### 1: node ID string (optional)
class Taunt(BTNode):
### target: the enemy agent to taunt
def parseArgs(self, args):
BTNode.parseArgs(self, args)
self.target = None
# First argument is the target
if len(args) > 0:
self.target = args[0]
# Second argument is the node ID
if len(args) > 1:
self.id = args[1]
def execute(self, delta = 0):
ret = BTNode.execute(self, delta)
if self.target is not None:
print "Hey", self.target, "I don't like you!"
return ret
##################
### MoveToTarget
###
### Move the agent to a given (x, y)
### Parameters:
### 0: a point (x, y)
### 1: node ID string (optional)
class MoveToTarget(BTNode):
### target: a point (x, y)
def parseArgs(self, args):
BTNode.parseArgs(self, args)
self.target = None
# First argument is the target
if len(args) > 0:
self.target = args[0]
# Second argument is the node ID
if len(args) > 1:
self.id = args[1]
def enter(self):
BTNode.enter(self)
self.agent.navigateTo(self.target)
def execute(self, delta = 0):
ret = BTNode.execute(self, delta)
if self.target == None:
# failed executability conditions
print "exec", self.id, "false"
return False
elif distance(self.agent.getLocation(), self.target) < self.agent.getRadius():
# Execution succeeds
print "exec", self.id, "true"
return True
else:
# executing
return None
return ret
##################
### Retreat
###
### Move the agent back to the base to be healed
### Parameters:
### 0: percentage of hitpoints that must have been lost to retreat
### 1: node ID string (optional)
class Retreat(BTNode):
### percentage: Percentage of hitpoints that must have been lost
def parseArgs(self, args):
BTNode.parseArgs(self, args)
self.percentage = 0.5
# First argument is the factor
if len(args) > 0:
self.percentage = args[0]
# Second argument is the node ID
if len(args) > 1:
self.id = args[1]
def enter(self):
BTNode.enter(self)
self.agent.navigateTo(self.agent.world.getBaseForTeam(self.agent.getTeam()).getLocation())
def execute(self, delta = 0):
ret = BTNode.execute(self, delta)
bases = self.agent.world.getEnemyBases(self.agent.getTeam())
if self.agent.getHitpoints() > self.agent.getMaxHitpoints() * self.percentage:
# fail executability conditions
print "exec", self.id, "false"
return False
elif self.agent.getHitpoints() == self.agent.getMaxHitpoints():
# Exection succeeds
print "exec", self.id, "true"
return True
else:
# executing
if distance(bases[0].getLocation(), self.agent.getLocation()) < 250:
return None
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
for e in enemies:
if e in set(self.agent.getVisible()) and distance(self.agent.getLocation(),
e.getLocation()) < 250 and isinstance(e, Minion):
return False
break
return None
return ret
##################
### ChaseMinion
###
### Find the closest minion and move to intercept it.
### Parameters:
### 0: node ID string (optional)
class ChaseMinion(BTNode):
### target: the minion to chase
### timer: how often to replan
def parseArgs(self, args):
BTNode.parseArgs(self, args)
self.target = None
self.timer = 50
# First argument is the node ID
if len(args) > 0:
self.id = args[0]
def enter(self):
BTNode.enter(self)
self.timer = 50
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
if len(enemies) > 0:
best = None
dist = 0
for e in enemies:
if isinstance(e, Minion):
d = distance(self.agent.getLocation(), e.getLocation())
if best == None or d < dist:
best = e
dist = d
self.target = best
if self.target is not None:
navTarget = self.chooseNavigationTarget()
if navTarget is not None:
self.agent.navigateTo(navTarget)
def execute(self, delta = 0):
ret = BTNode.execute(self, delta)
if self.target == None or self.target.isAlive() == False:
# failed execution conditions
print "exec", self.id, "false"
return False
elif self.target is not None and distance(self.agent.getLocation(), self.target.getLocation()) < BIGBULLETRANGE:
# succeeded
print "exec", self.id, "true"
return True
else:
# executing
self.timer = self.timer - 1
if self.timer <= 0:
self.timer = 50
navTarget = self.chooseNavigationTarget()
if navTarget is not None:
self.agent.navigateTo(navTarget)
return None
return ret
def chooseNavigationTarget(self):
if self.target is not None:
return self.target.getLocation()
else:
return None
##################
### KillMinion
###
### Kill the closest minion. Assumes it is already in range.
### Parameters:
### 0: node ID string (optional)
class KillMinion(BTNode):
### target: the minion to shoot
def parseArgs(self, args):
BTNode.parseArgs(self, args)
self.target = None
# First argument is the node ID
if len(args) > 0:
self.id = args[0]
def enter(self):
BTNode.enter(self)
self.agent.stopMoving()
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
if len(enemies) > 0:
best = None
dist = 0
for e in enemies:
if isinstance(e, Minion):
d = distance(self.agent.getLocation(), e.getLocation())
if best == None or d < dist:
best = e
dist = d
self.target = best
def execute(self, delta = 0):
ret = BTNode.execute(self, delta)
if self.target == None or distance(self.agent.getLocation(), self.target.getLocation()) > BIGBULLETRANGE:
# failed executability conditions
print "exec", self.id, "false"
return False
elif self.target.isAlive() == False:
# succeeded
print "exec", self.id, "true"
return True
else:
# executing
self.shootAtTarget()
return None
return ret
def shootAtTarget(self):
if self.agent is not None and self.target is not None:
self.agent.turnToFace(self.target.getLocation())
self.agent.shoot()
##################
### ChaseHero
###
### Move to intercept the enemy Hero.
### Parameters:
### 0: node ID string (optional)
class ChaseHero(BTNode):
### target: the hero to chase
### timer: how often to replan
def ParseArgs(self, args):
BTNode.parseArgs(self, args)
self.target = None
self.timer = 50
# First argument is the node ID
if len(args) > 0:
self.id = args[0]
def enter(self):
BTNode.enter(self)
self.timer = 50
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
for e in enemies:
if isinstance(e, Hero):
self.target = e
navTarget = self.chooseNavigationTarget()
if navTarget is not None:
self.agent.navigateTo(navTarget)
return None
def execute(self, delta = 0):
ret = BTNode.execute(self, delta)
if self.target == None or self.target.isAlive() == False:
# fails executability conditions
print "exec", self.id, "false"
return False
elif distance(self.agent.getLocation(), self.target.getLocation()) < BIGBULLETRANGE:
# succeeded
print "exec", self.id, "true"
return True
else:
# executing
self.timer = self.timer - 1
if self.timer <= 0:
navTarget = self.chooseNavigationTarget()
if navTarget is not None:
self.agent.navigateTo(navTarget)
return None
return ret
def chooseNavigationTarget(self):
if self.target is not None:
return self.target.getLocation()
else:
return None
##################
### KillHero
###
### Kill the enemy hero. Assumes it is already in range.
### Parameters:
### 0: node ID string (optional)
class KillHero(BTNode):
### target: the minion to shoot
def ParseArgs(self, args):
BTNode.parseArgs(self, args)
self.target = None
# First argument is the node ID
if len(args) > 0:
self.id = args[0]
def enter(self):
BTNode.enter(self)
self.agent.stopMoving()
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
for e in enemies:
if isinstance(e, Hero):
self.target = e
return None
def execute(self, delta = 0):
ret = BTNode.execute(self, delta)
if self.target == None or distance(self.agent.getLocation(), self.target.getLocation()) > BIGBULLETRANGE:
# failed executability conditions
if self.target == None:
print "foo none"
else:
print "foo dist", distance(self.agent.getLocation(), self.target.getLocation())
print "exec", self.id, "false"
return False
elif self.target.isAlive() == False:
# succeeded
print "exec", self.id, "true"
return True
else:
#executing
self.shootAtTarget()
return None
return ret
def shootAtTarget(self):
if self.agent is not None and self.target is not None:
self.agent.turnToFace(self.target.getLocation())
self.agent.shoot()
##################
### HitpointDaemon
###
### Only execute children if hitpoints are above a certain threshold.
### Parameters:
### 0: percentage of hitpoints that must have been lost to fail the daemon check
### 1: node ID string (optional)
class HitpointDaemon(BTNode):
### percentage: percentage of hitpoints that must have been lost to fail the daemon check
def parseArgs(self, args):
BTNode.parseArgs(self, args)
self.percentage = 0.5
# First argument is the factor
if len(args) > 0:
self.percentage = args[0]
# Second argument is the node ID
if len(args) > 1:
self.id = args[1]
def execute(self, delta = 0):
ret = BTNode.execute(self, delta)
if self.agent.getHitpoints() < self.agent.getMaxHitpoints() * self.percentage:
# Check failed
print "exec", self.id, "fail"
return False
else:
# Check didn't fail, return child's status
return self.getChild(0).execute(delta)
return ret
##################
### BuffDaemon
###
### Only execute children if agent's level is significantly above enemy hero's level.
### Parameters:
### 0: Number of levels above enemy level necessary to not fail the check
### 1: node ID string (optional)
class BuffDaemon(BTNode):
### advantage: Number of levels above enemy level necessary to not fail the check
def parseArgs(self, args):
BTNode.parseArgs(self, args)
self.advantage = 0
# First argument is the advantage
if len(args) > 0:
self.advantage = args[0]
# Second argument is the node ID
if len(args) > 1:
self.id = args[1]
def execute(self, delta = 0):
ret = BTNode.execute(self, delta)
hero = None
# Get a reference to the enemy hero
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
for e in enemies:
if isinstance(e, Hero):
hero = e
break
if hero == None or self.agent.level <= hero.level + self.advantage:
# fail check
print "exec", self.id, "fail"
return False
else:
# Check didn't fail, return child's status
return self.getChild(0).execute(delta)
return ret
#################################
### MY CUSTOM BEHAVIOR CLASSES
class NoCloseEnemies(BTNode):
def parseArgs(self, args):
BTNode.parseArgs(self, args)
if len(args) > 0:
self.id = args[0]
def execute(self, delta=0):
ret = BTNode.execute(self, delta)
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
for e in enemies:
if e in set(self.agent.getVisible()) and distance(self.agent.getLocation(), e.getLocation()) < 250:
return False
break
return self.getChild(0).execute(delta)
return ret
class CloseMinion(BTNode):
def parseArgs(self, args):
BTNode.parseArgs(self, args)
self.percentage = 0.5
# First argument is the factor
if len(args) > 0:
self.percentage = args[0]
# Second argument is the node ID
if len(args) > 1:
self.id = args[1]
def execute(self, delta=0):
ret = BTNode.execute(self, delta)
if self.agent.getHitpoints() > self.agent.getMaxHitpoints() * self.percentage:
# fail executability conditions
print "exec", self.id, "false"
return False
bases = self.agent.world.getEnemyBases(self.agent.getTeam())
for base in bases:
if distance(base.getLocation(), self.agent.getLocation()) < 250 :
return False
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
for e in enemies:
if e in set(self.agent.getVisible()) and distance(self.agent.getLocation(), e.getLocation()) < 250 and isinstance(e, Minion):
return self.getChild(0).execute(delta)
break
return False
return ret
class StrafeKillHero(BTNode):
### target: the minion to shoot
def parseArgs(self, args):
BTNode.parseArgs(self, args)
self.target = None
# First argument is the node ID
if len(args) > 0:
self.id = args[0]
def enter(self):
BTNode.enter(self)
self.agent.stopMoving()
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
for e in enemies:
if isinstance(e, Hero) and e in self.agent.getVisible():
self.target = e
return None
def execute(self, delta=0):
ret = BTNode.execute(self, delta)
if self.target == None or self.target not in self.agent.getVisible() or distance(self.agent.getLocation(),
self.target.getLocation()) > BIGBULLETRANGE:
# failed executability conditions
if self.target == None:
print "foo none"
else:
print "foo dist", distance(self.agent.getLocation(), self.target.getLocation())
print "exec", self.id, "false"
return False
elif self.target.isAlive() == False:
# succeeded
print "exec", self.id, "true"
return True
else:
# executing
if self.agent.canAreaEffect() and distance(self.agent.getLocation(), self.target.getLocation()) <= (self.agent.getRadius() * 2):
self.agent.areaEffect()
return None
if self.agent.getMoveTarget() == None:
strafe(self.agent, self.target)
shootTarget(self.agent, self.target)
return None
return ret
class StrafeKillMinion(BTNode):
### target: the minion to shoot
def parseArgs(self, args):
BTNode.parseArgs(self, args)
self.target = None
# First argument is the node ID
if len(args) > 0:
self.id = args[0]
def enter(self):
BTNode.enter(self)
self.agent.stopMoving()
enemies = self.agent.world.getEnemyNPCs(self.agent.getTeam())
if len(enemies) > 0:
best = None
dist = 0
for e in enemies:
if isinstance(e, Minion) and e in self.agent.getVisible():
d = distance(self.agent.getLocation(), e.getLocation())
if best == None or d < dist:
best = e
dist = d
self.target = best
def execute(self, delta=0):
ret = BTNode.execute(self, delta)
if self.target == None or self.target not in self.agent.getVisible() or distance(self.agent.getLocation(),
self.target.getLocation()) > BIGBULLETRANGE:
# failed executability conditions
print "exec", self.id, "false"
return False
elif self.target.isAlive() == False:
# succeeded
print "exec", self.id, "true"
return True
else:
# executing
if self.agent.canAreaEffect() and distance(self.agent.getLocation(), self.target.getLocation()) <= (self.agent.getRadius() * 2):
self.agent.areaEffect()
return None
if self.agent.getMoveTarget() == None:
strafe(self.agent, self.target)
shootTarget(self.agent, self.target)
return None
return ret
def strafe(agent, target):
enemyLocation = target.getLocation()
pos = agent.getLocation()
allPossiblePoints = agent.getPossibleDestinations()
targetPoints = []
for point in allPossiblePoints:
if distance(point, target.getLocation()) < 250 and distance(point, target.getLocation()) > 50:
targetPoints.append(point)
finalDest = random.choice(targetPoints)
ang = math.degrees(angle((enemyLocation[0] - pos[0], enemyLocation[1] - pos[1]), (finalDest[0] - pos[0], finalDest[1] - pos[1])))
while not clearShot(pos, finalDest, agent.world.getLinesWithoutBorders(), None, agent) or ang < 45 or ang > 135:
finalDest = random.choice(targetPoints)
ang = math.degrees(
angle((enemyLocation[0] - pos[0], enemyLocation[1] - pos[1]), (finalDest[0] - pos[0], finalDest[1] - pos[1])))
agent.navigateTo(finalDest)
def shootTarget(agent, target):
if agent is not None and target is not None:
targetPos = target.getLocation()
if not target.isMoving():
agent.turnToFace(targetPos)
agent.shoot()
else:
angle = target.orientation
rad = math.radians(angle)
if angle < 0:
angle += 2*math.pi
nextPos = (target.speed[0]*math.cos(rad), -1 * target.speed[1]*math.sin(rad))
aimLocation = (targetPos[0] + nextPos[0] * 10, targetPos[1] + nextPos[1] * 10)
agent.turnToFace(aimLocation)
agent.shoot()