file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
MathLeolaLibrary.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/MathLeolaLibrary.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoNamespace;
/**
* @author Tony
*
*/
public class MathLeolaLibrary implements LeolaLibrary {
private Leola runtime;
/* (non-Javadoc)
* @see leola.vm.lib.LeolaLibrary#init(leola.vm.Leola, leola.vm.types.LeoNamespace)
*/
@Override
@LeolaIgnore
public void init(Leola leola, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = leola;
this.runtime.putIntoNamespace(this, namespace);
//
// LeoNamespace math = this.runtime.getOrCreateNamespace("math");
// math.store(this);
//
// namespace.put("math", math);
}
public Vector2f newVec2(Double x, Double y) {
if(x != null && y != null)
return new Vector2f(x.floatValue(), y.floatValue());
if(x != null)
return new Vector2f(x.floatValue(), 0.0f);
return new Vector2f();
}
public Rectangle newRect(Integer x, Integer y, Integer w, Integer h) {
if (x != null && y != null && w != null && h != null) {
return new Rectangle(x, y, w, h);
}
if (x != null && y != null) {
return new Rectangle(0, 0, x, y);
}
return new Rectangle();
}
}
| 1,469 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FloatUtil.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/FloatUtil.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
/**
* Floating point utilities to account for float precision errors.
*
* @author Tony
*
*/
public /*strictfp*/ class FloatUtil {
private FloatUtil() {
}
/**
* Epsilon
*/
public static float epsilon = 0.001f;
/**
* Determine if two floats are equal by a given Epsilon.
*
* @param f1
* @param f2
* @return
*/
public static boolean eq(float f1, float f2) {
return Math.abs(f1 - f2) < epsilon;
}
/**
* Determine if two floats are equal by a given Epsilon.
*
* @param f1
* @param f2
* @param epsilon
* @return true if equal
*/
public static boolean eq(float f1, float f2, float epsilon) {
return Math.abs(f1 - f2) < epsilon;
}
/**
* Determine if one float is greater than another
*
* @param f1
* @param f2
* @return
*/
public static boolean gt(float f1, float f2) {
return !eq(f1, f2) && (f1 > f2);
}
/**
* Determine if one float is less than another
*
* @param f1
* @param f2
* @return
*/
public static boolean lt(float f1, float f2) {
return !eq(f1, f2) && (f1 < f2);
}
/**
* Determine if one float is greater than another or equal
*
* @param f1
* @param f2
* @return
*/
public static boolean gte(float f1, float f2) {
return gt(f1, f2) || eq(f1, f2);
}
/**
* Determine if one float is less than another or equal
*
* @param f1
* @param f2
* @return
*/
public static boolean lte(float f1, float f2) {
return lt(f1, f2) || eq(f1, f2);
}
/*
===================================================================================
Float Vector based Implementation
===================================================================================
*/
/**
* Float index for the X component
*/
public static final int X = 0;
/**
* Float index for the Y component
*/
public static final int Y = 1;
public static void Vector2fAdd(float[] a, float[] b, float[] dest) {
dest[X] = a[X] + b[X];
dest[Y] = a[Y] + b[Y];
}
public static void Vector2fSubtract(float[] a, float[] b, float[] dest) {
dest[X] = a[X] - b[X];
dest[Y] = a[Y] - b[Y];
}
public static void Vector2fMult(float[] a, float[] b, float[] dest) {
dest[X] = a[X] * b[X];
dest[Y] = a[Y] * b[Y];
}
public static void Vector2fMult(float[] a, float scalar, float[] dest) {
dest[X] = a[X] * scalar;
dest[Y] = a[Y] * scalar;
}
public static void Vector2fDiv(float[] a, float[] b, float[] dest) {
dest[X] = a[X] / b[X];
dest[Y] = a[Y] / b[Y];
}
public static float Vector2fCross(float[] a, float[] b) {
return a[X] * b[Y] - a[Y] * b[X];
}
public static boolean Vector2fEquals(float[] a, float[] b) {
return a[X] == b[X] && a[Y] == b[Y];
}
/**
* Accounts for float inaccuracy.
*
* @param a
* @param b
* @return
*/
public static boolean Vector2fApproxEquals(float[] a, float[] b) {
return FloatUtil.eq(a[X], b[X]) && FloatUtil.eq(a[Y], b[Y]);
}
public static void Vector2fRotate(float[] a, float radians, float[]dest) {
dest[X] = (float)(a[X] * cos(radians) - a[Y] * sin(radians));
dest[Y] = (float)(a[X] * sin(radians) + a[Y] * cos(radians));
}
public static float Vector2fLength(float[] a) {
return (float)Math.sqrt( (a[X] * a[X] + a[Y] * a[Y]) );
}
public static float Vector2fLengthSq(float[] a) {
return (a[X] * a[X] + a[Y] * a[Y]);
}
public static void Vector2fNormalize(float[] a, float[] dest) {
float fLen = (float)Math.sqrt( (a[X] * a[X] + a[Y] * a[Y]) );
if ( fLen == 0 ) return;
fLen = 1.0f / fLen;
dest[X] = a[X] * fLen;
dest[Y] = a[Y] * fLen;
}
public static void Vector2fCopy(float[] a, float[] dest) {
dest[X] = a[X];
dest[Y] = a[Y];
}
public static void Vector2fZeroOut(float[] a) {
a[X] = a[Y] = 0;
}
public static boolean Vector2fIsZero(float[] a) {
return a[X] == 0 && a[Y] == 0;
}
public static Vector2f Vector2fToVector2f(float[] a) {
return new Vector2f(a);
}
public static float[] Vector2fNew() {
return new float[]{0,0};
}
/**
* Calculates the length squared for each vector and determines if
* a is greater or equal in length.
*
* @param a
* @param b
* @return
*/
public static boolean Vector2fGreaterOrEq(float[] a, float[] b) {
float aLength = (a[X] * a[X] + a[Y] * a[Y]);
float bLength = (b[X] * b[X] + b[Y] * b[Y]);
return FloatUtil.gte(aLength, bLength);
}
public static void Vector2fRound(float[] a, float[] dest) {
dest[X] = Math.round(a[X]);
dest[Y] = Math.round(a[Y]);
}
public static void Vector2fSet(float[] a, float x, float y) {
a[X] = x;
a[Y] = y;
}
public static void Vector2fNegate(float[] a, float[] dest) {
dest[X] = -a[X];
dest[Y] = -a[Y];
}
}
| 5,608 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Vector3f.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/math/Vector3f.java | /*
* leola-live
* see license.txt
*/
package seventh.math;
/**
* @author Tony
*
*/
public class Vector3f {
/**
* X Component
*/
public float x;
/**
* Y Component
*/
public float y;
/**
* Z Component
*/
public float z;
/**
* @param x
* @param y
* @param z
*/
public Vector3f(float x, float y, float z) {
super();
this.x = x;
this.y = y;
this.z = z;
}
/**
* @param v
*/
public Vector3f(Vector3f v) {
this(v.x, v.y, v.z);
}
/**
*/
public Vector3f() {
this(0, 0, 0);
}
/**
* Sets all components.
*
* @param x
* @param y
* @param z
*/
public void set(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Sets all components.
*
* @param v
*/
public void set(Vector3f v) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
}
/**
* @return the x
*/
public float getX() {
return this.x;
}
/**
* @param x the x to set
*/
public void setX(float x) {
this.x = x;
}
/**
* @return the y
*/
public float getY() {
return this.y;
}
/**
* @param y the y to set
*/
public void setY(float y) {
this.y = y;
}
/**
* @return the z
*/
public float getZ() {
return this.z;
}
/**
* @param z the z to set
*/
public void setZ(float z) {
this.z = z;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(x);
result = prime * result + Float.floatToIntBits(y);
result = prime * result + Float.floatToIntBits(z);
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vector3f other = (Vector3f) obj;
if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x))
return false;
if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y))
return false;
if (Float.floatToIntBits(z) != Float.floatToIntBits(other.z))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "{ x: " + x + ", y: " + y + ", z: " + z + "}";
}
/**
* Vector add.
*
* @param a
* @param b
* @param dest
*/
public static void Vector3fAdd(Vector3f a, Vector3f b, Vector3f dest) {
dest.x = a.x + b.x;
dest.y = a.y + b.y;
dest.z = a.z + b.z;
}
/**
* Vector subtract.
*
* @param a
* @param b
* @param dest
*/
public static void Vector3fSubtract(Vector3f a, Vector3f b, Vector3f dest) {
dest.x = a.x - b.x;
dest.y = a.y - b.y;
dest.z = a.z - b.z;
}
/**
* Multiplication.
*
* @param a
* @param b
* @param dest
*/
public static /*strictfp*/ void Vector3fMult(Vector3f a, Vector3f b, Vector3f dest) {
dest.x = a.x * b.x;
dest.y = a.y * b.y;
dest.z = a.z * b.z;
}
/**
* Multiplication.
*
* @param a
* @param scalar
* @param dest
*/
public static /*strictfp*/ void Vector3fMult(Vector3f a, float scalar, Vector3f dest) {
dest.x = a.x * scalar;
dest.y = a.y * scalar;
dest.z = a.z * scalar;
}
/**
* Lerp between the two vectors
*
* @param a
* @param b
* @param alpha
* @param dest
*/
public static /*strictfp*/ void Vector3fLerp(Vector3f a, Vector3f b, float alpha, Vector3f dest) {
final float invAlpha = 1.0f - alpha;
dest.x = (a.x * invAlpha) + (b.x * alpha);
dest.y = (a.y * invAlpha) + (b.y * alpha);
dest.y = (a.z * invAlpha) + (b.z * alpha);
}
}
| 4,458 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ServerStartState.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/ServerStartState.java | /*
* see license.txt
*/
package seventh.server;
import seventh.shared.State;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class ServerStartState implements State {
public ServerStartState() {
}
/* (non-Javadoc)
* @see palisma.shared.State#enter()
*/
@Override
public void enter() {
}
/* (non-Javadoc)
* @see palisma.shared.State#update(leola.live.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
}
/* (non-Javadoc)
* @see palisma.shared.State#exit()
*/
@Override
public void exit() {
}
}
| 619 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MapCycle.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/MapCycle.java | /*
* see license.txt
*/
package seventh.server;
import java.util.List;
import seventh.shared.Command;
import seventh.shared.Console;
import seventh.shared.MapList.MapEntry;
/**
* The play list for maps.
*
* @author Tony
*
*/
public class MapCycle {
private List<MapEntry> maps;
private int currentMap;
/**
* @param maps
*/
public MapCycle(List<MapEntry> maps) {
this.maps = maps;
this.currentMap = 0;
if(this.maps.isEmpty()) {
throw new IllegalArgumentException("There are no maps defined the the map list.");
}
}
/**
* @return the Command that lists out the map cycle list
*/
public Command getMapListCommand() {
return new Command("map_list") {
@Override
public void execute(Console console, String... args) {
MapEntry currentMap = getCurrentMap();
console.println("\n");
console.println("Current map: " + currentMap);
for(MapEntry map : maps) {
if(currentMap.equals(map)) {
console.println(map + "*");
}
else {
console.println(map);
}
}
console.println("\n");
}
};
}
/**
* @return the {@link Command} that adds to the map list
*/
public Command getMapAddCommand() {
return new Command("map_add") {
@Override
public void execute(Console console, String... args) {
addMap(this.mergeArgsDelim(" ", args));
}
};
}
/**
* @return the {@link Command} that removes from the map list
*/
public Command getMapRemoveCommand() {
return new Command("map_remove") {
@Override
public void execute(Console console, String... args) {
removeMap(this.mergeArgsDelim(" ", args));
}
};
}
/**
* Adds a map to the rotation
* @param map
*/
public void addMap(String map) {
this.maps.add(new MapEntry(map));
}
public void addMap(MapEntry map) {
this.maps.add((map));
}
/**
* Removes a map from the rotation
*
* @param map
*/
public void removeMap(String map) {
int index = 0;
for(MapEntry entry : this.maps) {
if(entry.getFileName().equals(map)) {
this.maps.remove(index);
break;
}
index++;
}
}
/**
* If the supplied map file exists in this cycle
* @param map
* @return true if it exists
*/
public boolean hasMap(String map) {
for(MapEntry entry : this.maps) {
if(entry.getFileName().equals(map)) {
return true;
}
}
return false;
}
public boolean hasMap(MapEntry map) {
return hasMap(map.getFileName());
}
/**
* Sets the current map
* @param map
*/
public void setCurrentMap(MapEntry map) {
if(!hasMap(map)) {
addMap(map);
}
for(int i = 0; i < maps.size(); i++) {
if(maps.get(i).equals(map)) {
this.currentMap = i;
break;
}
}
}
/**
* @return the next map
*/
public MapEntry getNextMap() {
this.currentMap = (this.currentMap + 1) % maps.size();
return this.maps.get(currentMap);
}
/**
* @return the current map
*/
public MapEntry getCurrentMap() {
return this.maps.get(currentMap);
}
}
| 3,836 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
RemoteClient.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/RemoteClient.java | /*
* see license.txt
*/
package seventh.server;
import harenet.api.Connection;
import seventh.game.Player;
/**
* Represents a Remote Client
*
* @author Tony
*
*/
public class RemoteClient {
private Connection conn;
private Player player;
private boolean isReady;
private long rconToken;
private boolean isRconAuthenticated;
/**
* @param network
*/
public RemoteClient(Connection conn) {
this.conn = conn;
this.player = new Player(conn.getId());
this.isReady = false;
this.rconToken = ServerContext.INVALID_RCON_TOKEN;
this.isRconAuthenticated = false;
}
/**
* @param rconToken the rconToken to set
*/
public void setRconToken(long rconToken) {
this.rconToken = rconToken;
}
/**
* @return the rconToken
*/
public long getRconToken() {
return rconToken;
}
/**
* @return true if this remote client has a valid rcon token
*/
public boolean hasRconToken() {
return this.rconToken != ServerContext.INVALID_RCON_TOKEN;
}
/**
* @return the isRconAuthenticated
*/
public boolean isRconAuthenticated() {
return isRconAuthenticated;
}
/**
* @param isRconAuthenticated the isRconAuthenticated to set
*/
public void setRconAuthenticated(boolean isRconAuthenticated) {
this.isRconAuthenticated = isRconAuthenticated;
}
/**
* @return the isReady
*/
public boolean isReady() {
return isReady;
}
/**
* @param isReady the isReady to set
*/
public void setReady(boolean isReady) {
this.isReady = isReady;
}
public Connection getConnection() {
return this.conn;
}
public int getId() {
return player.getId();
}
/**
* @return the player
*/
public Player getPlayer() {
return player;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.player.setName(name);
}
/**
* @return the name
*/
public String getName() {
return this.player.getName();
}
}
| 2,402 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ServerContext.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/ServerContext.java | /*
* see license.txt
*/
package seventh.server;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicReference;
import harenet.NetConfig;
import harenet.api.Server;
import harenet.api.impl.HareNetServer;
import leola.vm.Leola;
import seventh.shared.Console;
import seventh.shared.Debugable.DebugableListener;
import seventh.shared.MapList.MapEntry;
import seventh.shared.RconHash;
import seventh.shared.Scripting;
import seventh.shared.State;
import seventh.shared.StateMachine;
/**
* Context information for a {@link GameServer}
*
* @author Tony
*
*/
public class ServerContext {
/**
* Invalid rcon token
*/
public static final long INVALID_RCON_TOKEN = -1;
private Server server;
private GameServer gameServer;
private RemoteClients clients;
private ServerNetworkProtocol protocol;
private Leola runtime;
private Console console;
private String rconPassword;
private MapCycle mapCycle;
private ServerSeventhConfig config;
private Random random;
private StateMachine<State> stateMachine;
private AtomicReference<GameSession> gameSession;
private List<GameSessionListener> gameSessionListeners;
private GameSessionListener sessionListener = new GameSessionListener() {
@Override
public void onGameSessionDestroyed(GameSession session) {
gameSession.set(null);
for(GameSessionListener l : gameSessionListeners) {
l.onGameSessionDestroyed(session);
}
}
@Override
public void onGameSessionCreated(GameSession session) {
gameSession.set(session);
for(GameSessionListener l : gameSessionListeners) {
l.onGameSessionCreated(session);
}
}
};
/**
* @param gameServer
* @param config
* @param runtime
*/
public ServerContext(GameServer gameServer, ServerSeventhConfig config, Leola runtime, Console console) {
this.gameServer = gameServer;
this.config = config;
this.runtime = runtime;
this.console = console;
this.rconPassword = config.getRconPassword();
this.random = new Random();
this.clients = new RemoteClients(config.getMaxPlayers());
this.stateMachine = new StateMachine<State>();
NetConfig netConfig = config.getNetConfig();
netConfig.setMaxConnections(config.getMaxPlayers());
this.server = new HareNetServer(netConfig);
this.protocol = new ServerNetworkProtocol(this);
this.server.addConnectionListener(this.protocol);
this.gameSessionListeners = new Vector<>();
addGameSessionListener(this.protocol);
this.gameSession = new AtomicReference<>();
this.mapCycle = new MapCycle(config.getMapListings());
}
/**
* @return true if there is a debug listener
*/
public boolean hasDebugListener() {
return this.gameServer.getDebugListener() != null;
}
/**
* @return the {@link DebugableListener}
*/
public DebugableListener getDebugableListener() {
return this.gameServer.getDebugListener();
}
/**
* Spawns a new GameSession
*
* @param map - the map to load
*/
public void spawnGameSession(MapEntry map) {
this.mapCycle.setCurrentMap(map);
this.stateMachine.changeState(new LoadingState(this, this.sessionListener, map));
}
/**
* Spawns a new Game Session
*/
public void spawnGameSession() {
spawnGameSession(mapCycle.getNextMap());
}
/**
* @return true if there is a {@link GameSession} loaded
*/
public boolean hasGameSession() {
return gameSession.get() != null;
}
/**
* @return the gameSession
*/
public GameSession getGameSession() {
return gameSession.get();
}
/**
* Adds a {@link GameSessionListener}
*
* @param l
*/
public void addGameSessionListener(GameSessionListener l) {
this.gameSessionListeners.add(l);
}
/**
* Removes a {@link GameSessionListener}
*
* @param l
*/
public void removeGameSessionListener(GameSessionListener l) {
this.gameSessionListeners.remove(l);
}
/**
* Creates a security token for RCON sessions
*
* @return a security token
*/
public long createToken() {
long token = INVALID_RCON_TOKEN;
while(token == INVALID_RCON_TOKEN) {
token = this.random.nextLong();
}
return token;
}
/**
* @return the port in which this server is listening on
*/
public int getPort() {
return this.gameServer.getPort();
}
/**
* @param token
* @return the hashed rcon password
*/
public String getRconPassword(long token) {
RconHash hash = new RconHash(token);
return hash.hash(this.rconPassword);
}
/**
* @return the mapCycle
*/
public MapCycle getMapCycle() {
return mapCycle;
}
/**
* @return the random
*/
public Random getRandom() {
return random;
}
/**
* @return the server
*/
public Server getServer() {
return server;
}
/**
* @return the serverProtocolListener
*/
public ServerNetworkProtocol getServerProtocol() {
return protocol;
}
/**
* @return the stateMachine
*/
public StateMachine<State> getStateMachine() {
return stateMachine;
}
/**
* @return the gameServer
*/
public GameServer getGameServer() {
return gameServer;
}
/**
* @return the console
*/
public Console getConsole() {
return console;
}
/**
* @return the clients
*/
public RemoteClients getClients() {
return clients;
}
/**
* @return the runtime
*/
public Leola getRuntime() {
return runtime;
}
/**
* @return a new instance of the {@link Leola} runtime
*/
public Leola newRuntime() {
Leola runtime = Scripting.newRuntime();
return runtime;
}
/**
* @return the config
*/
public ServerSeventhConfig getConfig() {
return config;
}
}
| 6,684 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SeventhScriptingCommonLibrary.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/SeventhScriptingCommonLibrary.java | /*
* see license.txt
*/
package seventh.server;
import leola.vm.types.LeoObject;
import seventh.game.Game;
import seventh.game.Trigger;
import seventh.game.entities.Door;
import seventh.game.entities.Entity;
import seventh.game.game_types.obj.BombTargetObjective;
import seventh.game.weapons.Bullet;
import seventh.game.weapons.Explosion;
import seventh.map.Tile;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
import seventh.shared.Cons;
/**
* Some common functions exposed to the scripting runtime
*
* @author Tony
*
*/
public class SeventhScriptingCommonLibrary {
/**
* Initializes a new {@link Vector2f}
*
* @param x optional x component
* @param y optional y component
* @return the {@link Vector2f}
*/
public static Vector2f newVec2(Double x, Double y) {
if(x != null && y != null)
return new Vector2f(x.floatValue(), y.floatValue());
if(x != null)
return new Vector2f(x.floatValue(), 0.0f);
return new Vector2f();
}
/**
* Initializes a new {@link Rectangle}
*
* @param x optional x component
* @param y optional y component
* @param w optional w component
* @param h optional h component
* @return the {@link Rectangle}
*/
public static Rectangle newRect(Integer x, Integer y, Integer w, Integer h) {
if (x != null && y != null && w != null && h != null) {
return new Rectangle(x, y, w, h);
}
if (x != null && y != null) {
return new Rectangle(0, 0, x, y);
}
return new Rectangle();
}
public static BombTargetObjective newBombTarget(float x, float y, String name, Boolean rotated) {
return new BombTargetObjective(new Vector2f(x, y), name, rotated);
}
/**
* Places a door in the world at the specified tileX/tileY coordinates
*
* @param tileX
* @param tileY
* @param hinge
*/
public static Door newDoor(Game game, int tileX, int tileY, String hinge, String pos) {
if(game.getMap().checkTileBounds(tileX, tileY)) {
return null;
}
Tile tile = game.getMap().getTile(0, tileX, tileY);
int offset = 0;
if(pos != null) {
switch(pos.toLowerCase()) {
case "left":
offset = Door.DOOR_WIDTH / 2;
break;
case "top":
offset = Door.DOOR_WIDTH / 2;
break;
case "middle":
offset += tile.getHeight() / 2;
break;
case "bottom":
offset = tile.getHeight() - Door.DOOR_WIDTH / 2;
break;
case "right":
offset = tile.getHeight() - Door.DOOR_WIDTH / 2;
break;
}
}
float posX = 0;
float posY = 0;
float facingX = 0;
float facingY = 0;
switch(hinge.toLowerCase()) {
case "n":
case "north":
posX = tile.getX() + offset;
posY = tile.getY();
facingX = 0;
facingY = 1;
break;
case "e":
case "east":
posX = tile.getX() + tile.getWidth();
posY = tile.getY() + offset;
facingX = 1;
facingY = 0;
break;
case "s":
case "south":
posX = tile.getX() + offset;
posY = tile.getY() + tile.getHeight();
facingX = 0;
facingY = -1;
break;
case "w":
case "west":
posX = tile.getX();
posY = tile.getY() + offset;
facingX = -1;
facingY = 0;
break;
}
return game.newDoor(posX, posY, facingX, facingY);
}
/**
* Binds an explosion to a tile. If a bullet or an explosion intersects the tile
* at the specified location.
*
* @param game
* @param tileX
* @param tileY
*/
public static void newExplosiveCrate(Game game, final int tileX, final int tileY, final LeoObject function) {
if(game.getMap().checkTileBounds(tileX, tileY)) {
Cons.println("Invalid tile position: " + tileX + ", " + tileY);
return;
}
final Tile tile = game.getMap().getTile(0, tileX, tileY);
game.addTrigger(new Trigger() {
Entity triggeredEntity = null;
@Override
public boolean checkCondition(Game game) {
Entity[] entities = game.getEntities();
for(int i = 0; i < entities.length; i++) {
Entity ent = entities[i];
if(ent != null) {
if(ent instanceof Bullet ||
ent instanceof Explosion) {
if(tile.getBounds().intersects(ent.getBounds())) {
triggeredEntity = ent;
return true;
}
}
}
}
return false;
}
@Override
public void execute(Game game) {
if(triggeredEntity != null) {
game.newBigExplosion(new Vector2f(tile.getX(),tile.getY()), triggeredEntity, 15, 25, 1);
}
if(function != null) {
LeoObject result = function.call(triggeredEntity.asScriptObject());
if(result.isError()) {
Cons.println("*** Error calling trigger function for exploting crate: \n" + result);
}
}
}
});
}
}
| 6,219 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
RconLogger.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/RconLogger.java | /*
* see license.txt
*/
package seventh.server;
import seventh.network.messages.RconMessage;
import seventh.shared.Logger;
/**
* @author Tony
*
*/
public class RconLogger implements Logger {
private ServerNetworkProtocol protocol;
private int clientId;
/**
* @param clientId
* @param protocol
*/
public RconLogger(int clientId, ServerNetworkProtocol protocol) {
this.clientId = clientId;
this.protocol = protocol;
}
@Override
public void print(Object msg) {
this.protocol.sendRconMessage(clientId, new RconMessage(msg.toString()));
}
@Override
public void println(Object msg) {
print(msg.toString() + "\n");
}
@Override
public void printf(Object msg, Object... args) {
print(String.format(msg.toString(), args));
}
}
| 846 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
RemoteClients.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/RemoteClients.java | /*
* see license.txt
*/
package seventh.server;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Tony
*
*/
public class RemoteClients {
/**
* Iterator for remote clients
*
* @author Tony
*
*/
public static interface RemoteClientIterator {
public void onRemoteClient(RemoteClient client);
}
private Map<Integer, RemoteClient> clients;
private int maxClients;
/**
* @param maxClients the max number of clients allowed
*/
public RemoteClients(int maxClients) {
this.maxClients = maxClients;
this.clients = new ConcurrentHashMap<>();
}
/**
* @return the maxClients
*/
public int getMaxClients() {
return maxClients;
}
/**
* Iterates through each registered client
*
* @param it
*/
public void foreach(RemoteClientIterator it) {
for(RemoteClient client : this.clients.values()) {
it.onRemoteClient(client);
}
}
/**
* Adds a {@link RemoteClient}
*
* @param clientId
* @param client
*/
public void addRemoteClient(int clientId, RemoteClient client) {
if(this.clients.size() > this.maxClients) {
throw new IllegalArgumentException("Max clients has been reached: " + this.clients.size());
}
this.clients.put(clientId, client);
}
/**
* Get the client by ID
*
* @param clientId
* @return the client, or null if not found
*/
public RemoteClient getClient(int clientId) {
return this.clients.get(clientId);
}
/**
* Removes the {@link RemoteClient} bound by the client ID.
*
* @param clientId
*/
public void removeClient(int clientId) {
this.clients.remove(clientId);
}
}
| 1,899 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ServerNetworkProtocol.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/ServerNetworkProtocol.java | /*
* see license.txt
*/
package seventh.server;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import harenet.api.Connection;
import harenet.api.Endpoint;
import harenet.api.Server;
import harenet.messages.NetMessage;
import seventh.game.Game;
import seventh.game.Player;
import seventh.game.PlayerInfo;
import seventh.game.Team;
import seventh.game.entities.PlayerEntity;
import seventh.game.net.NetTeam;
import seventh.network.messages.AICommandMessage;
import seventh.network.messages.BombDisarmedMessage;
import seventh.network.messages.BombExplodedMessage;
import seventh.network.messages.BombPlantedMessage;
import seventh.network.messages.ClientDisconnectMessage;
import seventh.network.messages.ClientReadyMessage;
import seventh.network.messages.ConnectAcceptedMessage;
import seventh.network.messages.ConnectRequestMessage;
import seventh.network.messages.FlagCapturedMessage;
import seventh.network.messages.FlagReturnedMessage;
import seventh.network.messages.FlagStolenMessage;
import seventh.network.messages.GameEndedMessage;
import seventh.network.messages.GamePartialStatsMessage;
import seventh.network.messages.GameReadyMessage;
import seventh.network.messages.GameStatsMessage;
import seventh.network.messages.GameUpdateMessage;
import seventh.network.messages.PlayerAwardMessage;
import seventh.network.messages.PlayerCommanderMessage;
import seventh.network.messages.PlayerConnectedMessage;
import seventh.network.messages.PlayerDisconnectedMessage;
import seventh.network.messages.PlayerInputMessage;
import seventh.network.messages.PlayerKilledMessage;
import seventh.network.messages.PlayerNameChangeMessage;
import seventh.network.messages.PlayerSpawnedMessage;
import seventh.network.messages.PlayerSpeechMessage;
import seventh.network.messages.PlayerSwitchPlayerClassMessage;
import seventh.network.messages.PlayerSwitchTeamMessage;
import seventh.network.messages.PlayerSwitchTileMessage;
import seventh.network.messages.PlayerSwitchWeaponClassMessage;
import seventh.network.messages.RconMessage;
import seventh.network.messages.RconTokenMessage;
import seventh.network.messages.RoundEndedMessage;
import seventh.network.messages.RoundStartedMessage;
import seventh.network.messages.GameEventMessage;
import seventh.network.messages.TeamTextMessage;
import seventh.network.messages.TextMessage;
import seventh.network.messages.TileAddedMessage;
import seventh.network.messages.TileRemovedMessage;
import seventh.network.messages.TilesAddedMessage;
import seventh.network.messages.TilesRemovedMessage;
import seventh.shared.Cons;
import seventh.shared.Console;
import seventh.shared.Logger;
import seventh.shared.NetworkProtocol;
/**
* Handles the server side of the {@link NetworkProtocol} of The Seventh.
*
* @author Tony
*
*/
public class ServerNetworkProtocol extends NetworkProtocol implements GameSessionListener, ServerProtocol {
/**
* Queued up message for clients
*
* @author Tony
*
*/
private static class OutboundMessage {
NetMessage msg;
MessageType type;
int flags;
int id;
public OutboundMessage(NetMessage msg, MessageType type, int id, int flags) {
this.msg = msg;
this.type = type;
this.id = id;
this.flags = flags;
}
}
private Game game;
private Console console;
private Server server;
private RemoteClients clients;
private ServerContext serverContext;
private Queue<OutboundMessage> outboundQ;
private Map<Integer, Logger> rconLoggers;
/**
* @param serverContext
*/
public ServerNetworkProtocol(ServerContext serverContext) {
super(serverContext.getServer());
this.serverContext = serverContext;
this.server = serverContext.getServer();
this.console = serverContext.getConsole();
this.clients = serverContext.getClients();
this.outboundQ = new ConcurrentLinkedQueue<ServerNetworkProtocol.OutboundMessage>();
this.rconLoggers = new HashMap<>();
}
/* (non-Javadoc)
* @see seventh.server.GameSessionListener#onGameSessionCreated(seventh.server.GameSession)
*/
@Override
public void onGameSessionCreated(GameSession session) {
this.game = session.getGame();
}
/* (non-Javadoc)
* @see seventh.server.GameSessionListener#onGameSessionDestroyed(seventh.server.GameSession)
*/
@Override
public void onGameSessionDestroyed(GameSession session) {
}
/*
* (non-Javadoc)
* @see seventh.shared.NetworkProtocol#postQueuedMessages()
*/
@Override
public void postQueuedMessages() {
while(!this.outboundQ.isEmpty()) {
try {
OutboundMessage oMsg = this.outboundQ.poll();
switch(oMsg.type) {
case ALL_CLIENTS:
this.server.sendToAll(oMsg.flags, oMsg.msg);
break;
case ALL_EXCEPT:
this.server.sendToAllExcept(oMsg.flags, oMsg.msg, oMsg.id);
break;
case ONE:
this.server.sendTo(oMsg.flags, oMsg.msg, oMsg.id);
break;
default:
break;
}
}
catch(Exception e) {
Cons.println("Error sending packet: " + e);
}
}
}
private void queueSendToAll(int protocolFlags, NetMessage message) {
this.outboundQ.add(new OutboundMessage(message, MessageType.ALL_CLIENTS, 0, protocolFlags));
}
private void sendTo(int protocolFlags, int clientId, NetMessage msg) {
try {
this.server.sendTo(protocolFlags, msg, clientId);
}
catch(IOException e) {
Cons.println("*** ERROR: Failed to send message to: " + clientId + " - " + e);
}
}
private void queueSendToAllExcept(int protocolFlags, NetMessage message, int id) {
this.outboundQ.add(new OutboundMessage(message, MessageType.ALL_EXCEPT, id, protocolFlags));
}
// private void queueSendToClient(int protocolFlags, NetMessage message, int id) {
// this.outboundQ.add(new OutboundMessage(message, MessageType.ONE, id, protocolFlags));
// }
@Override
public void onConnected(Connection conn) {
this.clients.addRemoteClient(conn.getId(), new RemoteClient(conn));
this.console.println("Negotiating connection with remote client: " + conn.getRemoteAddress());
}
@Override
public void onDisconnected(Connection conn) {
this.queueInboundMessage(conn, new ClientDisconnectMessage());
}
@Override
public void onServerFull(Connection conn) {
Cons.println("Connected attempted but the server is full.");
}
/*
* (non-Javadoc)
* @see palisma.shared.NetworkProtocol#processMessage(com.esotericsoftware.kryonet.Connection, palisma.network.messages.Message)
*/
@Override
protected void processMessage(Connection conn, NetMessage message) throws IOException {
if(message instanceof PlayerInputMessage) {
receivePlayerInputMessage(conn, (PlayerInputMessage)message);
}
else if(message instanceof ConnectRequestMessage) {
receiveConnectRequestMessage(conn, (ConnectRequestMessage)message);
}
else if(message instanceof ClientReadyMessage) {
receiveClientReadyMessage(conn, (ClientReadyMessage)message);
}
else if(message instanceof PlayerSwitchWeaponClassMessage) {
receivePlayerSwitchWeaponClassMessage(conn, (PlayerSwitchWeaponClassMessage)message );
}
else if(message instanceof AICommandMessage) {
receiveAICommand(conn, (AICommandMessage)message);
}
else if(message instanceof PlayerSwitchTeamMessage) {
receivePlayerSwitchedTeamMessage(conn, (PlayerSwitchTeamMessage)message);
}
else if(message instanceof PlayerSwitchTileMessage) {
receivePlayerSwitchTileMessage(conn, (PlayerSwitchTileMessage)message);
}
else if(message instanceof PlayerSpeechMessage) {
receivePlayerSpeechMessage(conn, (PlayerSpeechMessage)message);
}
else if(message instanceof PlayerCommanderMessage) {
receivePlayerCommanderMessage(conn, (PlayerCommanderMessage)message);
}
else if(message instanceof ClientDisconnectMessage) {
receiveClientDisconnectMessage(conn, (ClientDisconnectMessage)message);
}
else if(message instanceof TextMessage) {
receiveTextMessage(conn, (TextMessage)message);
}
else if(message instanceof TeamTextMessage) {
receiveTeamTextMessage(conn, (TeamTextMessage)message);
}
else if(message instanceof PlayerNameChangeMessage) {
receivePlayerNameChangedMessage(conn, (PlayerNameChangeMessage)message);
}
else if(message instanceof RconMessage) {
receiveRconMessage(conn, (RconMessage)message);
}
else {
Cons.println("Unknown message: " + message);
}
}
/*
* (non-Javadoc)
* @see seventh.server.ServerProtocol#receivePlayerSwitchWeaponClassMessage(harenet.api.Connection, seventh.network.messages.PlayerSwitchWeaponClassMessage)
*/
@Override
public void receivePlayerSwitchWeaponClassMessage(Connection conn, PlayerSwitchWeaponClassMessage message) throws IOException {
game.playerSwitchWeaponClass(conn.getId(), message.weaponType);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#receivePlayerSwitchClassMessage(harenet.api.Connection, seventh.network.messages.PlayerSwitchPlayerClassMessage)
*/
@Override
public void receivePlayerSwitchClassMessage(Connection conn, PlayerSwitchPlayerClassMessage message) throws IOException {
game.playerSwitchPlayerClass(conn.getId(), message.playerClass);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#receivePlayerSwitchTileMessage(harenet.api.Connection, seventh.network.messages.PlayerSwitchTileMessage)
*/
@Override
public void receivePlayerSwitchTileMessage(Connection conn, PlayerSwitchTileMessage message) throws IOException {
game.playerSwitchTile(conn.getId(), message.newTileId);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#connectRequest(harenet.api.Connection, seventh.network.messages.ConnectRequestMessage)
*/
@Override
public void receiveConnectRequestMessage(Connection conn, ConnectRequestMessage msg) throws IOException {
this.console.println(msg.name + " is attempting to connect");
RemoteClient client = this.clients.getClient(conn.getId());
client.setName(msg.name);
this.game.playerJoined(client.getPlayer());
/* notify all players (accept the one connecting) that a new player
is coming in
*/
PlayerConnectedMessage connectBroadcast = new PlayerConnectedMessage();
connectBroadcast.name = msg.name;
connectBroadcast.playerId = client.getId();
sendPlayerConnectedMessage(connectBroadcast, conn.getId());
// Give the new player the full game state
ConnectAcceptedMessage acceptedMessage = new ConnectAcceptedMessage();
acceptedMessage.playerId = conn.getId();
acceptedMessage.gameState = this.game.getNetGameState();
sendConnectAcceptedMessage(conn.getId(), acceptedMessage);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#clientReady(harenet.api.Connection, seventh.network.messages.ClientReadyMessage)
*/
@Override
public void receiveClientReadyMessage(Connection conn, ClientReadyMessage msg) {
RemoteClient client = this.clients.getClient(conn.getId());
if(client != null) {
if(!client.isReady()) {
client.setReady(true);
client.getPlayer().setPing(conn.getReturnTripTime());
this.console.println(client.getName() + " has connected.");
}
}
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#userInput(harenet.api.Connection, seventh.network.messages.UserInputMessage)
*/
@Override
public void receivePlayerInputMessage(Connection conn, PlayerInputMessage msg) {
this.game.applyPlayerInput(conn.getId(), msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#clientDisconnect(harenet.api.Connection, seventh.network.messages.ClientDisconnectMessage)
*/
@Override
public void receiveClientDisconnectMessage(Connection conn, ClientDisconnectMessage msg) throws IOException {
this.game.playerLeft(conn.getId());
PlayerDisconnectedMessage disconnectBroadcast = new PlayerDisconnectedMessage();
disconnectBroadcast.playerId = conn.getId();
sendPlayerDisconnectedMessage(disconnectBroadcast, conn.getId());
this.clients.removeClient(conn.getId());
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#playerSwitchedTeam(harenet.api.Connection, seventh.network.messages.PlayerSwitchTeamMessage)
*/
@Override
public void receivePlayerSwitchedTeamMessage(Connection conn, PlayerSwitchTeamMessage msg) throws IOException {
if ( game.playerSwitchedTeam( (int)msg.playerId, msg.teamId) ) {
sendPlayerSwitchTeamMessage(msg);
}
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#playerSpeech(harenet.api.Connection, seventh.network.messages.PlayerSpeechMessage)
*/
@Override
public void receivePlayerSpeechMessage(Connection conn, PlayerSpeechMessage msg) throws IOException {
if(conn.getId() == msg.playerId) {
PlayerInfo player = game.getPlayerById(msg.playerId);
if(player != null) {
if(player.isAlive()) {
PlayerEntity entity = player.getEntity();
// server is authorative of the actual player position
msg.posX = (short)entity.getCenterPos().x;
msg.posY = (short)entity.getCenterPos().y;
sendPlayerSpeechMessage(msg, conn.getId());
}
}
}
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#textMessage(harenet.api.Connection, seventh.network.messages.TextMessage)
*/
@Override
public void receiveTextMessage(Connection conn, TextMessage msg) throws IOException {
msg.playerId = conn.getId();
sendTextMessage(msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#teamTextMessage(harenet.api.Connection, seventh.network.messages.TeamTextMessage)
*/
@Override
public void receiveTeamTextMessage(Connection conn, TeamTextMessage msg) throws IOException {
RemoteClient client = this.clients.getClient(conn.getId());
msg.playerId = conn.getId();
Player player = client.getPlayer();
Team team = this.game.getGameType().getTeam(player);
NetTeam netTeam = team.getNetTeam();
for(int i = 0; i < netTeam.playerIds.length; i++) {
sendTeamTextMessage(netTeam.playerIds[i], msg);
}
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#playerNameChangedMessage(harenet.api.Connection, seventh.network.messages.PlayerNameChangeMessage)
*/
@Override
public void receivePlayerNameChangedMessage(Connection conn, PlayerNameChangeMessage msg ) throws IOException {
RemoteClient client = this.clients.getClient(conn.getId());
Player player = client.getPlayer();
player.setName(msg.name);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#receivePlayerCommanderMessage(harenet.api.Connection, seventh.network.messages.PlayerCommanderMessage)
*/
@Override
public void receivePlayerCommanderMessage(Connection conn, PlayerCommanderMessage msg) {
RemoteClient client = this.clients.getClient(conn.getId());
Player player = client.getPlayer();
if(game.playerCommander(player, msg.isCommander)) {
sendPlayerCommanderMessage(msg);
}
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#aiCommand(harenet.api.Connection, seventh.network.messages.AICommandMessage)
*/
@Override
public void receiveAICommand(Connection conn, AICommandMessage msg) throws IOException {
game.receiveAICommand(conn.getId(), msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#rconMessage(harenet.api.Connection, seventh.network.messages.RconMessage)
*/
@Override
public void receiveRconMessage(Connection conn, RconMessage msg) throws IOException {
RemoteClient client = this.clients.getClient(conn.getId());
if(client != null) {
String cmd = msg.getCommand();
if(cmd != null) {
/*
* Authentication process:
* 1) Client requests to login
* 2) Server sends session token
* 3) Client sends password (hashed with token)
* 4) Server sends pass/fail
* 5) If pass, client can send remote console commands
*/
if(cmd.startsWith("login")) {
long token = this.serverContext.createToken();
RconTokenMessage tokenMessage = new RconTokenMessage(token);
client.setRconToken(token);
sendRconTokenMessage(client.getId(), tokenMessage);
}
else if (cmd.startsWith("logoff")) {
client.setRconAuthenticated(false);
client.setRconToken(ServerContext.INVALID_RCON_TOKEN);
console.removeLogger(this.rconLoggers.get(client.getId()));
}
else if(cmd.startsWith("password")) {
if(!client.hasRconToken()) {
RconMessage rconMsg = new RconMessage("You must first initiate a login: rcon login");
sendRconMessage(client.getId(), rconMsg);
}
else {
String password = cmd.replace("password ", "");
// if the password hashes match, they are authenticated
String serverPassword = this.serverContext.getRconPassword(client.getRconToken());
if( serverPassword.equals(password) ) {
client.setRconAuthenticated(true);
Logger logger = this.rconLoggers.put(client.getId(), new RconLogger(client.getId(), this));
console.removeLogger(logger);
if(!serverContext.getGameServer().isLocal()) {
console.addLogger(this.rconLoggers.get(client.getId()));
}
}
else {
client.setRconAuthenticated(false);
RconMessage rconMsg = new RconMessage("Invalid password.");
sendRconMessage(client.getId(), rconMsg);
}
}
}
else if(client.isRconAuthenticated()) {
console.execute(msg.getCommand());
}
else {
RconMessage rconMsg = new RconMessage("You must first authenticate by executing these commands:\n rcon login\n rcon password [password]");
sendRconMessage(client.getId(), rconMsg);
}
}
}
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendGamePartialStatsMessage(seventh.network.messages.GamePartialStatsMessage)
*/
@Override
public void sendGamePartialStatsMessage(GamePartialStatsMessage msg) throws IOException {
this.server.sendToAll(Endpoint.FLAG_UNRELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendGameStatsMessage(seventh.network.messages.GameStatsMessage)
*/
@Override
public void sendGameStatsMessage(GameStatsMessage msg) throws IOException {
this.server.sendToAll(Endpoint.FLAG_UNRELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendGameUpdateMessage(seventh.network.messages.GameUpdateMessage, int)
*/
@Override
public void sendGameUpdateMessage(GameUpdateMessage msg, int clientId) throws IOException {
this.server.sendTo(Endpoint.FLAG_UNRELIABLE, msg, clientId);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendGameReadyMessage(seventh.network.messages.GameReadyMessage)
*/
@Override
public void sendGameReadyMessage(GameReadyMessage msg, int clientId) throws IOException {
this.server.sendTo(Endpoint.FLAG_RELIABLE, msg, clientId);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendGameEndedMessage(seventh.network.messages.GameEndedMessage)
*/
@Override
public void sendGameEndedMessage(GameEndedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendRoundStartedMessage(seventh.network.messages.RoundStartedMessage)
*/
@Override
public void sendRoundStartedMessage(RoundStartedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendRoundEndedMessage(seventh.network.messages.RoundEndedMessage)
*/
@Override
public void sendRoundEndedMessage(RoundEndedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendPlayerKilledMessage(seventh.network.messages.PlayerKilledMessage)
*/
@Override
public void sendPlayerKilledMessage(PlayerKilledMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendPlayerSpawnedMessage(seventh.network.messages.PlayerSpawnedMessage)
*/
@Override
public void sendPlayerSpawnedMessage(PlayerSpawnedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendBombPlantedMessage(seventh.network.messages.BombPlantedMessage)
*/
@Override
public void sendBombPlantedMessage(BombPlantedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendBombDisarmedMessage(seventh.network.messages.BombDisarmedMessage)
*/
@Override
public void sendBombDisarmedMessage(BombDisarmedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendBombExplodedMessage(seventh.network.messages.BombExplodedMessage)
*/
@Override
public void sendBombExplodedMessage(BombExplodedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendTileRemovedMessage(seventh.network.messages.TileRemovedMessage)
*/
@Override
public void sendTileRemovedMessage(TileRemovedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendTilesRemovedMessage(seventh.network.messages.TilesRemovedMessage)
*/
@Override
public void sendTilesRemovedMessage(TilesRemovedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
@Override
public void sendTileAddedMessage(TileAddedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendTilesRemovedMessage(seventh.network.messages.TilesRemovedMessage)
*/
@Override
public void sendTilesAddedMessage(TilesAddedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendRconTokenMessage(int, seventh.network.messages.RconTokenMessage)
*/
@Override
public void sendRconTokenMessage(int clientId, RconTokenMessage msg) {
sendTo(Endpoint.FLAG_RELIABLE, clientId, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendRconMessage(int, seventh.network.messages.RconMessage)
*/
@Override
public void sendRconMessage(int clientId, RconMessage msg) {
sendTo(Endpoint.FLAG_RELIABLE, clientId, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendTextMessage(int, seventh.network.messages.TextMessage)
*/
@Override
public void sendTextMessage(TextMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendTeamTextMessage(int, seventh.network.messages.TeamTextMessage)
*/
@Override
public void sendTeamTextMessage(int clientId, TeamTextMessage msg) {
sendTo(Endpoint.FLAG_RELIABLE, clientId, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendConnectAcceptedMessage(int, seventh.network.messages.ConnectAcceptedMessage)
*/
@Override
public void sendConnectAcceptedMessage(int clientId, ConnectAcceptedMessage msg) {
sendTo(Endpoint.FLAG_RELIABLE, clientId, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendPlayerConnectedMessage(seventh.network.messages.PlayerConnectedMessage, int)
*/
@Override
public void sendPlayerConnectedMessage(PlayerConnectedMessage msg, int exceptClientId) {
queueSendToAllExcept(Endpoint.FLAG_RELIABLE, msg, exceptClientId);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendPlayerDisconnectedMessage(seventh.network.messages.PlayerDisconnectedMessage, int)
*/
@Override
public void sendPlayerDisconnectedMessage(PlayerDisconnectedMessage msg, int exceptClientId) {
queueSendToAllExcept(Endpoint.FLAG_RELIABLE, msg, exceptClientId);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendPlayerSwitchTeamMessage(seventh.network.messages.PlayerSwitchTeamMessage)
*/
@Override
public void sendPlayerSwitchTeamMessage(PlayerSwitchTeamMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendPlayerSpeechMessage(seventh.network.messages.PlayerSpeechMessage, int)
*/
@Override
public void sendPlayerSpeechMessage(PlayerSpeechMessage msg, int exceptClientId) {
queueSendToAllExcept(Endpoint.FLAG_RELIABLE, msg, exceptClientId);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendPlayerSwitchClassMessage(seventh.network.messages.PlayerSwitchPlayerClassMessage)
*/
@Override
public void sendPlayerSwitchClassMessage(PlayerSwitchPlayerClassMessage message) throws IOException {
queueSendToAll(Endpoint.FLAG_RELIABLE, message);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendFlagCapturedMessage(seventh.network.messages.FlagCapturedMessage)
*/
@Override
public void sendFlagCapturedMessage(FlagCapturedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendFlagReturnedMessage(seventh.network.messages.FlagReturnedMessage)
*/
@Override
public void sendFlagReturnedMessage(FlagReturnedMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendFlagStolenMessage(seventh.network.messages.FlagStolenMessage)
*/
@Override
public void sendFlagStolenMessage(FlagStolenMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendPlayerCommanderMessage(seventh.network.messages.PlayerCommanderMessage)
*/
@Override
public void sendPlayerCommanderMessage(PlayerCommanderMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendPlayerAwardMessage(seventh.network.messages.PlayerAwardMessage)
*/
@Override
public void sendPlayerAwardMessage(PlayerAwardMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
/* (non-Javadoc)
* @see seventh.server.ServerProtocol#sendSurvivoEventrMessage(seventh.network.messages.GameEventMessage)
*/
@Override
public void sendGameEventMessage(GameEventMessage msg) {
queueSendToAll(Endpoint.FLAG_RELIABLE, msg);
}
}
| 30,146 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ServerSeventhConfig.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/ServerSeventhConfig.java | /*
* see license.txt
*/
package seventh.server;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoString;
import seventh.game.game_types.GameType;
import seventh.shared.Config;
import seventh.shared.Cons;
import seventh.shared.MapList;
import seventh.shared.MapList.MapEntry;
import seventh.shared.SeventhConfig;
import seventh.shared.SeventhConstants;
/**
* The server configuration file
*
* @author Tony
*
*/
public class ServerSeventhConfig extends SeventhConfig {
/**
* @param configurationPath
* @param configurationRootNode
* @throws Exception
*/
public ServerSeventhConfig(String configurationPath, String configurationRootNode) throws Exception {
super(configurationPath, configurationRootNode);
}
/**
* @param config
*/
public ServerSeventhConfig(Config config) {
super(config);
}
/**
* @return true if the debugger is enabled
*/
public boolean isDebuggerEnabled() {
return this.config.getBool("debugger", "enabled");
}
/**
* @return the class path
*/
public String getDebuggerClasspath() {
return this.config.getString("debugger", "classpath");
}
/**
* @return the debugger class name
*/
public String getDebuggerClassName() {
return this.config.getStr("", "debugger", "class_name");
}
/**
* @return the listening port
*/
public int getPort() {
return this.config.getInt(SeventhConstants.DEFAULT_PORT, "net", "port");
}
/**
* @return the local host name
*/
public String getAddress() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
Cons.println("*** ERROR: Unable to obtain local host address: " + e);
return "0.0.0.0";
}
}
/**
* @return the map listings
*/
public List<MapEntry> getMapListings() {
/* Allow for a subset of the maps to be
* cycled through
*/
if(this.config.has("map_list")) {
LeoArray mapList = this.config.get("map_list").as();
List<MapEntry> maps = new ArrayList<MapEntry>(mapList.size());
for(LeoObject m : mapList) {
String mapFile = m.toString();
MapEntry entry = new MapEntry(MapList.stripFileExtension(mapFile), mapFile);
maps.add(entry);
}
return maps;
}
/* this just allows ALL maps that are in the maps
* directory
*/
return MapList.getMapListing(getGameType());
}
/**
* Sets the map listings
*
* @param maps
*/
public void setMapListings(List<String> maps) {
LeoArray mapList = new LeoArray(maps.size());
for(String map : maps) {
mapList.add(LeoString.valueOf(map));
}
this.config.set(mapList, "map_list");
}
/**
* @return the weapons
*/
public LeoObject getWeapons() {
return this.config.get("weapons");
}
/**
* @param weapons
*/
public void setWeapons(LeoObject weapons) {
this.config.set(weapons, "weapons");
}
/**
* @return the rcon password
*/
public String getRconPassword() {
return this.config.getStr("brett_favre", "rcon_password");
}
/**
* @param rconPassword
*/
public void setRconPassword(String rconPassword) {
this.config.set(rconPassword, "rcon_password");
}
/**
* @return the server name
*/
public String getServerName() {
return this.config.getStr("The Seventh Server", "name");
}
/**
* @param serverName
*/
public void setServerName(String serverName) {
this.config.set(serverName, "name");
}
/**
* @return the match time -- the max amount of time a match should last
*/
public long getMatchTime() {
return this.config.getInt(20, "sv_matchtime");
}
public void setMatchTime(long matchTime) {
this.config.set(matchTime, "sv_matchtime");
}
/**
* @return the max score needed to win
*/
public int getMaxScore() {
return this.config.getInt(50, "sv_maxscore");
}
public void setMaxScore(int maxscore) {
this.config.set(maxscore, "sv_maxscore");
}
/**
* @return the max number of players allowed on this server
*/
public int getMaxPlayers() {
return this.config.getInt(SeventhConstants.MAX_PLAYERS, "sv_maxplayers");
}
/**
* Sets the max number of players
*
* @param maxPlayers
*/
public void setMaxPlayers(int maxPlayers) {
this.config.set(maxPlayers, "sv_maxplayers");
}
/**
* @return the game type
*/
public GameType.Type getGameType() {
return GameType.Type.toType(this.config.getStr("tdm", "sv_gametype"));
}
public void setGameType(GameType.Type gameType) {
this.config.set(gameType.name(), "sv_gametype");
}
public int getServerFrameRate() {
return this.config.getInt(20, "sv_framerate");
}
public void setServerFrameRate(int fps) {
this.config.set(fps, "sv_framerate");
}
public int getServerNetUpdateRate() {
return this.config.getInt(20, "sv_netupdaterate");
}
public int getServerNetFullStatDelay() {
return this.config.getInt(20_000, "sv_netfullstatdelay");
}
public int getServerNetPartialStatDelay() {
return this.config.getInt(5_000, "sv_netpartialstatdelay");
}
public String getStartupScript() {
return this.config.getStr(null, "sv_startupscript");
}
public boolean isPrivate() {
return this.config.getBool(false, "sv_private");
}
public void setPrivate(boolean isPrivate) {
this.config.set(LeoObject.valueOf(isPrivate), "sv_private");
}
public String getPrivatePassword() {
return this.config.getStr(null, "sv_privatePassword");
}
public void setPrivatePassword(String password) {
this.config.set(LeoObject.valueOf(password), "sv_privatePassword");
}
}
| 6,588 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
LoadingState.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/LoadingState.java | /*
* see license.txt
*/
package seventh.server;
import leola.vm.Leola;
import seventh.game.GameMap;
import seventh.game.Players;
import seventh.game.game_types.AbstractGameTypeScript;
import seventh.game.game_types.GameType;
import seventh.game.game_types.cmd.CommanderScript;
import seventh.game.game_types.ctf.CaptureTheFlagScript;
import seventh.game.game_types.obj.ObjectiveScript;
import seventh.game.game_types.svr.SurvivorScript;
import seventh.game.game_types.tdm.TeamDeathMatchScript;
import seventh.map.Map;
import seventh.map.MapLoaderUtil;
import seventh.shared.Cons;
import seventh.shared.MapList.MapEntry;
import seventh.shared.State;
import seventh.shared.TimeStep;
/**
* Responsible for loading maps
*
* @author Tony
*
*/
public class LoadingState implements State {
private ServerContext serverContext;
private Leola runtime;
private GameSession gameSession;
private Players players;
private MapEntry mapFile;
private GameSessionListener gameSessionListener;
/**
* @param serverContext
* @param gameSessionListener
* @param mapFile
*/
public LoadingState(ServerContext serverContext, GameSessionListener gameSessionListener, MapEntry mapFile) {
this.serverContext = serverContext;
this.gameSessionListener = gameSessionListener;
this.mapFile = mapFile;
this.runtime = serverContext.newRuntime();
/* indicates we haven't successfully loaded the map */
this.gameSession = null;
}
/**
* Loads a new {@link Map}
*
* @param file
* @throws Exception
*/
private GameMap loadMap(MapEntry file) throws Exception {
Cons.println("Loading " + file.getFileName() + " map...");
Map map = MapLoaderUtil.loadMap(this.runtime, file.getFileName(), false);
GameMap gameMap = new GameMap(file.getFileName(), "Unknown", map);
Cons.println("Successfully loaded!");
return gameMap;
}
/**
* Loads a game type
*
* @param mapFile
* @param script
* @return the {@link GameType}
* @throws Exception
*/
private GameType loadGameType(MapEntry mapFile, AbstractGameTypeScript script) throws Exception {
ServerSeventhConfig config = this.serverContext.getConfig();
int maxKills = config.getMaxScore();
long matchTime = config.getMatchTime() * 60L * 1000L;
return script.loadGameType(mapFile.getFileName(), maxKills, matchTime);
}
private GameType loadTDMGameType(MapEntry mapFile) throws Exception {
return loadGameType(mapFile, new TeamDeathMatchScript(runtime));
}
private GameType loadObjGameType(MapEntry mapFile) throws Exception {
return loadGameType(mapFile, new ObjectiveScript(runtime));
}
private GameType loadCTFGameType(MapEntry mapFile) throws Exception {
return loadGameType(mapFile, new CaptureTheFlagScript(runtime));
}
private GameType loadCMDGameType(MapEntry mapFile) throws Exception {
return loadGameType(mapFile, new CommanderScript(runtime));
}
private GameType loadSVRGameType(MapEntry mapFile) throws Exception {
return loadGameType(mapFile, new SurvivorScript(runtime));
}
/**
* Ends the game
*/
private void endGame() {
if(this.serverContext.hasGameSession()) {
GameSession session = this.serverContext.getGameSession();
this.gameSessionListener.onGameSessionDestroyed(session);
/* remember which players are still playing */
this.players = session.getPlayers();
session.destroy();
}
else {
this.players = new Players();
}
}
/* (non-Javadoc)
* @see palisma.shared.State#enter()
*/
@Override
public void enter() {
try {
endGame();
GameMap gameMap = loadMap(mapFile);
GameType gameType = null;
switch(this.serverContext.getConfig().getGameType()) {
case OBJ: {
gameType = loadObjGameType(mapFile);
break;
}
case TDM: {
gameType = loadTDMGameType(mapFile);
break;
}
case CTF: {
gameType = loadCTFGameType(mapFile);
break;
}
case CMD: {
gameType = loadCMDGameType(mapFile);
break;
}
case SVR: {
gameType = loadSVRGameType(mapFile);
break;
}
default: {
throw new IllegalArgumentException
("Unknown game type: " + this.serverContext.getConfig().getGameType());
}
}
this.gameSession = new GameSession(serverContext.getConfig(), gameMap, gameType, players);
}
catch(Exception e) {
Cons.println("*** Unable to load map: " + this.mapFile + " -> " + e);
}
}
/* (non-Javadoc)
* @see palisma.shared.State#update(leola.live.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
if(this.gameSession != null) {
Cons.println("Server loading the InGameState...");
this.gameSessionListener.onGameSessionCreated(gameSession);
this.serverContext.getStateMachine().changeState(new InGameState(serverContext, gameSession));
}
else {
this.serverContext.getStateMachine().changeState(new ServerStartState());
}
}
/* (non-Javadoc)
* @see palisma.shared.State#exit()
*/
@Override
public void exit() {
}
}
| 6,153 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GameServerLeolaLibrary.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/GameServerLeolaLibrary.java | /*
* see license.txt
*/
package seventh.server;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoNamespace;
import seventh.ai.AICommand;
import seventh.ai.basic.DefaultAISystem;
import seventh.ai.basic.actions.Action;
import seventh.game.Game;
import seventh.game.PlayerInfo;
import seventh.game.Team;
import seventh.math.Vector2f;
import seventh.shared.Cons;
/**
* The server-side (game side) script API.
*
* @author Tony
*
*/
public class GameServerLeolaLibrary implements LeolaLibrary {
private Game game;
/**
* @param game
*/
public GameServerLeolaLibrary(Game game) {
this.game = game;
}
/* (non-Javadoc)
* @see leola.vm.lib.LeolaLibrary#init(leola.vm.Leola, leola.vm.types.LeoNamespace)
*/
@Override
public void init(Leola runtime, LeoNamespace namespace) throws LeolaRuntimeException {
runtime.putIntoNamespace(this, namespace);
}
/**
* Adds a bot
*
* @param id
* @param name
* @param team
*/
public void addBot(int id, String name, String team) {
game.addBot(id, name);
if(team != null) {
game.playerSwitchedTeam(id, team.toLowerCase().startsWith("axis") ? Team.AXIS_TEAM_ID : Team.ALLIED_TEAM_ID);
}
}
public PlayerInfo getBot(int id) {
PlayerInfo info = game.getPlayerById(id);
if(info == null) {
Cons.println("*** ERROR: No player with the id: " + id);
}
else {
if(!info.isBot()) {
Cons.println("*** ERROR: Player with the id: " + id + " is not a bot.");
info = null;
}
}
return info;
}
public void botPlace(int id, float x, float y) {
PlayerInfo info = getBot(id);
if(info != null && info.isAlive()) {
info.getEntity().moveTo(new Vector2f(x, y));
}
}
public void botCommand(int id, String command) {
DefaultAISystem system = (DefaultAISystem)game.getAISystem();
PlayerInfo info = getBot(id);
if(info != null) {
system.receiveAICommand(info, new AICommand(command));
}
}
public void botAction(int id, Action action) {
DefaultAISystem system = (DefaultAISystem)game.getAISystem();
PlayerInfo info = getBot(id);
if(info != null) {
system.getBrain(id).getCommunicator().makeTopPriority(action);
}
}
}
| 2,580 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
InGameState.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/InGameState.java | /*
* see license.txt
*/
package seventh.server;
import java.io.IOException;
import harenet.api.Connection;
import seventh.game.Game;
import seventh.game.Player;
import seventh.game.PlayerAwardSystem.Award;
import seventh.game.Players;
import seventh.game.Players.PlayerIterator;
import seventh.game.Team;
import seventh.game.entities.Entity;
import seventh.game.events.BombDisarmedEvent;
import seventh.game.events.BombDisarmedListener;
import seventh.game.events.BombExplodedEvent;
import seventh.game.events.BombExplodedListener;
import seventh.game.events.BombPlantedEvent;
import seventh.game.events.BombPlantedListener;
import seventh.game.events.FlagCapturedEvent;
import seventh.game.events.FlagCapturedListener;
import seventh.game.events.FlagReturnedEvent;
import seventh.game.events.FlagReturnedListener;
import seventh.game.events.FlagStolenEvent;
import seventh.game.events.FlagStolenListener;
import seventh.game.events.GameEndEvent;
import seventh.game.events.GameEndListener;
import seventh.game.events.KillRollEvent;
import seventh.game.events.KillRollListener;
import seventh.game.events.KillStreakEvent;
import seventh.game.events.KillStreakListener;
import seventh.game.events.PlayerAwardEvent;
import seventh.game.events.PlayerAwardListener;
import seventh.game.events.PlayerKilledEvent;
import seventh.game.events.PlayerKilledListener;
import seventh.game.events.PlayerSpawnedEvent;
import seventh.game.events.PlayerSpawnedListener;
import seventh.game.events.RoundEndedEvent;
import seventh.game.events.RoundEndedListener;
import seventh.game.events.RoundStartedEvent;
import seventh.game.events.RoundStartedListener;
import seventh.game.events.GameEvent;
import seventh.game.events.GameEventListener;
import seventh.game.events.TileAddedEvent;
import seventh.game.events.TileAddedListener;
import seventh.game.events.TileRemovedEvent;
import seventh.game.events.TileRemovedListener;
import seventh.game.net.NetGameUpdate;
import seventh.game.net.NetMapAddition;
import seventh.network.messages.BombDisarmedMessage;
import seventh.network.messages.BombExplodedMessage;
import seventh.network.messages.BombPlantedMessage;
import seventh.network.messages.FlagCapturedMessage;
import seventh.network.messages.FlagReturnedMessage;
import seventh.network.messages.FlagStolenMessage;
import seventh.network.messages.GameEndedMessage;
import seventh.network.messages.GamePartialStatsMessage;
import seventh.network.messages.GameReadyMessage;
import seventh.network.messages.GameStatsMessage;
import seventh.network.messages.GameUpdateMessage;
import seventh.network.messages.PlayerAwardMessage;
import seventh.network.messages.PlayerKilledMessage;
import seventh.network.messages.PlayerSpawnedMessage;
import seventh.network.messages.RoundEndedMessage;
import seventh.network.messages.RoundStartedMessage;
import seventh.network.messages.GameEventMessage;
import seventh.network.messages.TileAddedMessage;
import seventh.network.messages.TileRemovedMessage;
import seventh.server.RemoteClients.RemoteClientIterator;
import seventh.shared.Command;
import seventh.shared.Cons;
import seventh.shared.Console;
import seventh.shared.EventDispatcher;
import seventh.shared.EventMethod;
import seventh.shared.State;
import seventh.shared.TimeStep;
/**
* Represents the state in which the game is active.
*
* @author Tony
*
*/
public class InGameState implements State {
/**
* When a game ends, lets have a time delay to let the
* score display and players to calm down from the carnage
*/
private static final long GAME_END_DELAY = 20_000;
private Game game;
private GameSession gameSession;
private ServerContext serverContext;
private EventDispatcher dispatcher;
private final long netFullStatDelay;
private final long netPartialStatDelay;
private final long netUpdateRate;
private long nextGameStatUpdate;
private long nextGamePartialStatUpdate;
private long nextGameUpdate;
private long gameEndTime;
private boolean gameEnded;
private boolean calculatePing;
private GameStatsMessage statsMessage;
private GamePartialStatsMessage partialStatsMessage;
private Players players;
private RemoteClients clients;
private RemoteClientIterator clientIterator;
private ServerNetworkProtocol protocol;
/**
* @param serverContext
* @param gameSession
*/
public InGameState(final ServerContext serverContext,
final GameSession gameSession) {
this.serverContext = serverContext;
this.gameSession = gameSession;
this.players = gameSession.getPlayers();
this.clients = serverContext.getClients();
this.protocol = serverContext.getServerProtocol();
this.dispatcher = gameSession.getEventDispatcher();
this.game = gameSession.getGame();
ServerSeventhConfig config = serverContext.getConfig();
this.netFullStatDelay = config.getServerNetFullStatDelay();
this.netPartialStatDelay = config.getServerNetPartialStatDelay();
final long netRate = Math.abs(config.getServerNetUpdateRate());
this.netUpdateRate = 1000 / netRate == 0 ? 20 : netRate;
this.nextGameStatUpdate = 2_000; // first big update, wait only 2 seconds
this.nextGamePartialStatUpdate = this.netPartialStatDelay;
this.nextGameUpdate = this.netUpdateRate;
this.statsMessage = new GameStatsMessage();
this.partialStatsMessage = new GamePartialStatsMessage();
this.clientIterator = new RemoteClientIterator() {
@Override
public void onRemoteClient(RemoteClient client) {
if(client.isReady()) {
sendGameUpdateMessage(client.getId());
}
if(calculatePing) {
int ping = client.getConnection().getReturnTripTime();
client.getPlayer().setPing(ping);
}
}
};
this.dispatcher.addEventListener(PlayerKilledEvent.class, new PlayerKilledListener() {
@Override
@EventMethod
public void onPlayerKilled(PlayerKilledEvent event) {
PlayerKilledMessage msg = new PlayerKilledMessage();
msg.deathType = event.getMeansOfDeath();
msg.killedById = event.getKillerId();
msg.playerId = event.getPlayer().getId();
msg.posX = (short)event.getPos().x;
msg.posY = (short)event.getPos().y;
protocol.sendPlayerKilledMessage(msg);
}
});
this.dispatcher.addEventListener(PlayerSpawnedEvent.class, new PlayerSpawnedListener() {
@Override
@EventMethod
public void onPlayerSpawned(PlayerSpawnedEvent event) {
PlayerSpawnedMessage msg = new PlayerSpawnedMessage();
Player player = event.getPlayer();
msg.playerId = player.getId();
msg.posX = (short)event.getSpawnLocation().x;
msg.posY = (short)event.getSpawnLocation().y;
protocol.sendPlayerSpawnedMessage(msg);
}
});
this.dispatcher.addEventListener(GameEndEvent.class, new GameEndListener() {
@Override
@EventMethod
public void onGameEnd(GameEndEvent event) {
if(!gameEnded) {
GameEndedMessage msg = new GameEndedMessage();
msg.stats = game.getNetGameStats();
protocol.sendGameEndedMessage(msg);
gameEnded = true;
}
}
});
this.dispatcher.addEventListener(RoundEndedEvent.class, new RoundEndedListener() {
@Override
@EventMethod
public void onRoundEnded(RoundEndedEvent event) {
RoundEndedMessage msg = new RoundEndedMessage();
msg.stats = game.getNetGameStats();//event.getStats();
Team winner = event.getWinner();
if(winner != null) {
msg.winnerTeamId = winner.getId();
}
protocol.sendRoundEndedMessage(msg);
}
});
this.dispatcher.addEventListener(RoundStartedEvent.class, new RoundStartedListener() {
@Override
@EventMethod
public void onRoundStarted(RoundStartedEvent event) {
RoundStartedMessage msg = new RoundStartedMessage();
msg.gameState = game.getNetGameState();
protocol.sendRoundStartedMessage(msg);
}
});
this.dispatcher.addEventListener(BombPlantedEvent.class, new BombPlantedListener() {
@Override
@EventMethod
public void onBombPlanted(BombPlantedEvent event) {
int bombTargetId = event.getBombTarget() != null ? event.getBombTarget().getId() : Entity.INVALID_ENTITY_ID;
protocol.sendBombPlantedMessage(new BombPlantedMessage(bombTargetId));
}
});
this.dispatcher.addEventListener(BombDisarmedEvent.class, new BombDisarmedListener() {
@EventMethod
@Override
public void onBombDisarmedEvent(BombDisarmedEvent event) {
int bombTargetId = event.getBombTarget() != null ? event.getBombTarget().getId() : Entity.INVALID_ENTITY_ID;
protocol.sendBombDisarmedMessage(new BombDisarmedMessage(bombTargetId));
}
});
this.dispatcher.addEventListener(BombExplodedMessage.class, new BombExplodedListener() {
@EventMethod
@Override
public void onBombExplodedEvent(BombExplodedEvent event) {
protocol.sendBombExplodedMessage(new BombExplodedMessage());
}
});
this.dispatcher.addEventListener(TileRemovedEvent.class, new TileRemovedListener() {
@Override
public void onTileRemoved(TileRemovedEvent event) {
TileRemovedMessage msg = new TileRemovedMessage();
msg.x = event.getTileX();
msg.y = event.getTileY();
protocol.sendTileRemovedMessage(msg);
}
});
this.dispatcher.addEventListener(TileAddedEvent.class, new TileAddedListener() {
@Override
public void onTileAdded(TileAddedEvent event) {
TileAddedMessage msg = new TileAddedMessage();
msg.tile = new NetMapAddition(event.getTileX(), event.getTileY(), event.getType());
protocol.sendTileAddedMessage(msg);
}
});
this.dispatcher.addEventListener(FlagCapturedEvent.class, new FlagCapturedListener() {
@Override
public void onFlagCapturedEvent(FlagCapturedEvent event) {
FlagCapturedMessage msg = new FlagCapturedMessage();
msg.flagId = event.getFlag().getId();
msg.capturedBy = event.getPlayerId();
protocol.sendFlagCapturedMessage(msg);
}
});
this.dispatcher.addEventListener(FlagReturnedEvent.class, new FlagReturnedListener() {
@Override
public void onFlagReturnedEvent(FlagReturnedEvent event) {
FlagReturnedMessage msg = new FlagReturnedMessage();
msg.flagId = event.getFlag().getId();
msg.returnedBy = event.getPlayerId();
protocol.sendFlagReturnedMessage(msg);
}
});
this.dispatcher.addEventListener(FlagStolenEvent.class, new FlagStolenListener() {
@Override
public void onFlagStolenEvent(FlagStolenEvent event) {
FlagStolenMessage msg = new FlagStolenMessage();
msg.flagId = event.getFlag().getId();
msg.stolenBy = event.getPlayerId();
protocol.sendFlagStolenMessage(msg);
}
});
this.dispatcher.addEventListener(KillStreakEvent.class, new KillStreakListener() {
@Override
public void onKillStreak(KillStreakEvent event) {
PlayerAwardMessage msg = new PlayerAwardMessage();
msg.playerId = event.getPlayer().getId();
msg.award = Award.KillStreak;
msg.killStreak = (byte) event.getStreak();
protocol.sendPlayerAwardMessage(msg);
}
});
this.dispatcher.addEventListener(KillRollEvent.class, new KillRollListener() {
@Override
public void onKillRoll(KillRollEvent event) {
PlayerAwardMessage msg = new PlayerAwardMessage();
msg.playerId = event.getPlayer().getId();
msg.award = Award.KillRoll;
msg.killStreak = (byte) event.getStreak();
protocol.sendPlayerAwardMessage(msg);
}
});
this.dispatcher.addEventListener(PlayerAwardEvent.class, new PlayerAwardListener() {
@Override
public void onPlayerAward(PlayerAwardEvent event) {
PlayerAwardMessage msg = new PlayerAwardMessage();
msg.playerId = event.getPlayer().getId();
msg.award = event.getAward();
protocol.sendPlayerAwardMessage(msg);
}
});
this.dispatcher.addEventListener(GameEvent.class, new GameEventListener() {
@Override
public void onGameEvent(GameEvent event) {
GameEventMessage msg = new GameEventMessage();
msg.eventType = event.getEventType();
msg.path = event.getPath();
msg.pos = event.getPos();
msg.pos2 = event.getPos2();
msg.rotation = event.getRotation();
msg.playerId1 = event.getPlayerId1();
msg.playerId2 = event.getPlayerId2();
msg.light = event.getLight();
protocol.sendGameEventMessage(msg);
}
});
}
/* (non-Javadoc)
* @see palisma.shared.State#enter()
*/
@Override
public void enter() {
this.serverContext.getConsole().addCommand(new Command("sv_fow") {
@Override
public void execute(Console console, String... args) {
if(args.length > 0) {
int enabled = Integer.parseInt(args[0]);
game.enableFOW(enabled != 0);
}
console.println("sv_fow: " + (game.isEnableFOW() ? 1 : 0));
}
});
this.gameEnded = false;
this.gameEndTime = 0;
this.players.forEachPlayer(new PlayerIterator() {
@Override
public void onPlayer(Player player) {
game.playerJoined(player);
}
});
this.game.startGame();
sendReadyMessage();
Cons.println("Server InGameState initialiazed and ready for players");
}
/* (non-Javadoc)
* @see palisma.shared.State#exit()
*/
@Override
public void exit() {
this.gameSession.destroy();
this.serverContext.getConsole().removeCommand("sv_fow");
}
/* (non-Javadoc)
* @see palisma.shared.State#update(leola.live.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
this.protocol.updateNetwork(timeStep);
this.game.update(timeStep);
this.dispatcher.processQueue();
this.protocol.postQueuedMessages();
/* only send a partial update if we did NOT send
* a full update
*/
if ( ! sendGameStatMessage(timeStep) ) {
sendGamePartialStatMessage(timeStep);
}
sendClientGameUpdates(timeStep);
this.game.postUpdate();
// check for game end
if(gameEnded) {
if(gameEndTime > GAME_END_DELAY) {
/* load up the next level */
serverContext.spawnGameSession();
}
gameEndTime += timeStep.getDeltaTime();
}
if(this.serverContext.hasDebugListener()) {
this.serverContext.getDebugableListener().onDebugable(this.game);
}
}
private void sendClientGameUpdates(TimeStep timeStep) {
this.nextGameUpdate -= timeStep.getDeltaTime();
if(this.nextGameUpdate <= 0) {
this.clients.foreach(this.clientIterator);
this.nextGameUpdate = this.netUpdateRate;
}
}
/**
* Send out a message to all clients indicating that
* the game is now ready for play
*
*/
private void sendReadyMessage() {
GameReadyMessage msg = new GameReadyMessage();
msg.gameState = this.game.getNetGameState();
for(Connection conn : serverContext.getServer().getConnections()) {
try {
if(conn != null) {
RemoteClient client = clients.getClient(conn.getId());
if(client != null && client.isReady()) {
protocol.sendGameReadyMessage(msg, client.getId());
}
}
}
catch (IOException e) {
Cons.println("Failed to send game ready state message - " + e );
}
}
}
/**
* Sends a game update to the client
*
* @param clientId
*/
private void sendGameUpdateMessage(int clientId) {
NetGameUpdate netUpdate = this.game.getNetGameUpdateFor(clientId);
if(netUpdate != null) {
GameUpdateMessage updateMessage = new GameUpdateMessage();
updateMessage.netUpdate = netUpdate;
try {
protocol.sendGameUpdateMessage(updateMessage, clientId);
}
catch(Exception e) {
Cons.println("*** Error sending game update to client: " + e);
}
}
}
/**
* Sends a partial stat update
* @param timeStep
*/
private void sendGamePartialStatMessage(TimeStep timeStep) {
nextGamePartialStatUpdate -= timeStep.getDeltaTime();
if(nextGamePartialStatUpdate <= 0) {
partialStatsMessage.stats = this.game.getNetGamePartialStats();
this.nextGamePartialStatUpdate = this.netPartialStatDelay;
try {
protocol.sendGamePartialStatsMessage(partialStatsMessage);
}
catch(Exception e) {
Cons.println("*** Error sending game stats to client: " + e);
}
}
}
/**
* Sends a full game stat update.
*
* @param timeStep
* @return true if an update was sent
*/
private boolean sendGameStatMessage(TimeStep timeStep) {
this.nextGameStatUpdate -= timeStep.getDeltaTime();
if(this.nextGameStatUpdate <= 0) {
this.statsMessage.stats = this.game.getNetGameStats();
this.nextGameStatUpdate = this.netFullStatDelay;
this.nextGamePartialStatUpdate = this.netPartialStatDelay;
try {
this.protocol.sendGameStatsMessage(this.statsMessage);
this.calculatePing = true;
}
catch(Exception e) {
Cons.println("*** Error sending game stats to client: " + e);
}
}
else {
this.calculatePing = false;
}
return this.calculatePing;
}
}
| 21,046 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ServerProtocol.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/ServerProtocol.java | /*
* see license.txt
*/
package seventh.server;
import java.io.IOException;
import harenet.api.Connection;
import seventh.network.messages.AICommandMessage;
import seventh.network.messages.BombDisarmedMessage;
import seventh.network.messages.BombExplodedMessage;
import seventh.network.messages.BombPlantedMessage;
import seventh.network.messages.ClientDisconnectMessage;
import seventh.network.messages.ClientReadyMessage;
import seventh.network.messages.ConnectAcceptedMessage;
import seventh.network.messages.ConnectRequestMessage;
import seventh.network.messages.FlagCapturedMessage;
import seventh.network.messages.FlagReturnedMessage;
import seventh.network.messages.FlagStolenMessage;
import seventh.network.messages.GameEndedMessage;
import seventh.network.messages.GamePartialStatsMessage;
import seventh.network.messages.GameReadyMessage;
import seventh.network.messages.GameStatsMessage;
import seventh.network.messages.GameUpdateMessage;
import seventh.network.messages.PlayerAwardMessage;
import seventh.network.messages.PlayerCommanderMessage;
import seventh.network.messages.PlayerConnectedMessage;
import seventh.network.messages.PlayerDisconnectedMessage;
import seventh.network.messages.PlayerInputMessage;
import seventh.network.messages.PlayerKilledMessage;
import seventh.network.messages.PlayerNameChangeMessage;
import seventh.network.messages.PlayerSpawnedMessage;
import seventh.network.messages.PlayerSpeechMessage;
import seventh.network.messages.PlayerSwitchPlayerClassMessage;
import seventh.network.messages.PlayerSwitchTeamMessage;
import seventh.network.messages.PlayerSwitchTileMessage;
import seventh.network.messages.PlayerSwitchWeaponClassMessage;
import seventh.network.messages.RconMessage;
import seventh.network.messages.RconTokenMessage;
import seventh.network.messages.RoundEndedMessage;
import seventh.network.messages.RoundStartedMessage;
import seventh.network.messages.GameEventMessage;
import seventh.network.messages.TeamTextMessage;
import seventh.network.messages.TextMessage;
import seventh.network.messages.TileAddedMessage;
import seventh.network.messages.TileRemovedMessage;
import seventh.network.messages.TilesAddedMessage;
import seventh.network.messages.TilesRemovedMessage;
/**
* The messages the server receives from the clients
*
* @author Tony
*
*/
public interface ServerProtocol {
/**
* Connection request from a client
*
* @param conn
* @param msg
* @throws IOException
*/
public void receiveConnectRequestMessage(Connection conn, ConnectRequestMessage msg) throws IOException;
/**
* The client is ready for game state messages, all network negotiations are completed.
*
* @param conn
* @param msg
*/
public void receiveClientReadyMessage(Connection conn, ClientReadyMessage msg) throws IOException;
/**
* The client has disconnected from the server.
*
* @param conn
* @param msg
* @throws IOException
*/
public void receiveClientDisconnectMessage(Connection conn, ClientDisconnectMessage msg) throws IOException;
/**
* The Players input controls to their character.
*
* @param conn
* @param msg
* @throws IOException
*/
public void receivePlayerInputMessage(Connection conn, PlayerInputMessage msg) throws IOException;
/**
* The Player has requested to switch teams
*
* @param conn
* @param msg
* @throws IOException
*/
public void receivePlayerSwitchedTeamMessage(Connection conn, PlayerSwitchTeamMessage msg) throws IOException;
/**
* The Player has requested to switch weapon class
*
* @param conn
* @param message
* @throws IOException
*/
public void receivePlayerSwitchWeaponClassMessage(Connection conn, PlayerSwitchWeaponClassMessage message) throws IOException;
/**
* The Player has requested to switch player classes
*
* @param conn
* @param message
* @throws IOException
*/
public void receivePlayerSwitchClassMessage(Connection conn, PlayerSwitchPlayerClassMessage message) throws IOException;
/**
* The Player has requested to switch their active tile
*
* @param conn
* @param message
* @throws IOException
*/
public void receivePlayerSwitchTileMessage(Connection conn, PlayerSwitchTileMessage message) throws IOException;
/**
* The Player has issued a voice command
*
* @param conn
* @param msg
* @throws IOException
*/
public void receivePlayerSpeechMessage(Connection conn, PlayerSpeechMessage msg) throws IOException;
/**
* The Player has changed their name
*
* @param conn
* @param msg
* @throws IOException
*/
public void receivePlayerNameChangedMessage(Connection conn, PlayerNameChangeMessage msg) throws IOException;
/**
* A player has gone to or from Commander
*
* @param conn
* @param msg
*/
public void receivePlayerCommanderMessage(Connection conn, PlayerCommanderMessage msg);
/**
* The client has issued a global text message
*
* @param conn
* @param msg
* @throws IOException
*/
public void receiveTextMessage(Connection conn, TextMessage msg) throws IOException;
/**
* The client has issued a team text message
*
* @param conn
* @param msg
* @throws IOException
*/
public void receiveTeamTextMessage(Connection conn, TeamTextMessage msg) throws IOException;
/**
* Issue an AI command for a Bot
*
* @param conn
* @param msg
* @throws IOException
*/
public void receiveAICommand(Connection conn, AICommandMessage msg) throws IOException;
/**
* A client has issued a remote command request
*
* @param conn
* @param msg
* @throws IOException
*/
public void receiveRconMessage(Connection conn, RconMessage msg) throws IOException;
/**
* Sends a {@link GamePartialStatsMessage} to all clients
*
* @param msg
* @throws IOException
*/
public void sendGamePartialStatsMessage(GamePartialStatsMessage msg) throws IOException;
/**
* Sends a {@link GameStatsMessage} to all clients
*
* @param msg
* @throws IOException
*/
public void sendGameStatsMessage(GameStatsMessage msg) throws IOException;
/**
* Sends a {@link GameUpdateMessage} to the supplied client id
*
* @param msg
* @param clientId
* @throws IOException
*/
public void sendGameUpdateMessage(GameUpdateMessage msg, int clientId) throws IOException;
/**
* Sends a {@link GameReadyMessage} to the supplied client id
*
* @param msg
* @param clientId
* @throws IOException
*/
public void sendGameReadyMessage(GameReadyMessage msg, int clientId) throws IOException;
/**
* Sends a {@link GameEndedMessage} to all clients
*
* @param msg
*/
public void sendGameEndedMessage(GameEndedMessage msg);
/**
* Sends a {@link RoundStartedMessage} to all clients
*
* @param msg
*/
public void sendRoundStartedMessage(RoundStartedMessage msg);
/**
* Sends a {@link RoundEndedMessage} to all clients
* @param msg
*/
public void sendRoundEndedMessage(RoundEndedMessage msg);
/**
* Sends a {@link PlayerKilledMessage} to all clients
*
* @param msg
*/
public void sendPlayerKilledMessage(PlayerKilledMessage msg);
/**
* Sends a {@link PlayerSpawnedMessage} to all clients
* @param msg
*/
public void sendPlayerSpawnedMessage(PlayerSpawnedMessage msg);
/**
* Sends a {@link BombPlantedMessage} to all clients
*
* @param msg
*/
public void sendBombPlantedMessage(BombPlantedMessage msg);
/**
* Sends a {@link BombDisarmedMessage} to all clients
*
* @param msg
*/
public void sendBombDisarmedMessage(BombDisarmedMessage msg);
/**
* Sends a {@link BombExplodedMessage} to all clients
*
* @param msg
*/
public void sendBombExplodedMessage(BombExplodedMessage msg);
/**
* Sends a {@link TileRemovedMessage} to all clients
*
* @param msg
*/
public void sendTileRemovedMessage(TileRemovedMessage msg);
/**
* Sends a {@link TilesRemovedMessage} to all clients
*
* @param msg
*/
public void sendTilesRemovedMessage(TilesRemovedMessage msg);
/**
* Sends a {@link TileAddedMessage} to all clients
*
* @param msg
*/
public void sendTileAddedMessage(TileAddedMessage msg);
/**
* Sends a {@link TilesAddedMessage} to all clients
*
* @param msg
*/
public void sendTilesAddedMessage(TilesAddedMessage msg);
/**
* Sends an {@link RconTokenMessage} to a particular client
*
* @param clientId
* @param msg
*/
public void sendRconTokenMessage(int clientId, RconTokenMessage msg);
/**
* Sends an {@link RconMessage} to a particular client
*
* @param clientId
* @param msg
*/
public void sendRconMessage(int clientId, RconMessage msg);
/**
* Sends a {@link TeamTextMessage} to a particular client
*
* @param clientId
* @param msg
*/
public void sendTeamTextMessage(int clientId, TeamTextMessage msg);
/**
* Sends a {@link TextMessage} to all clients
* @param msg
*/
public void sendTextMessage(TextMessage msg);
/**
* Sends a {@link PlayerConnectedMessage} to all clients except the supplied client id.
*
* @param msg
* @param exceptClientId
*/
public void sendPlayerConnectedMessage(PlayerConnectedMessage msg, int exceptClientId);
/**
* Sends a {@link PlayerDisconnectedMessage} to all clients except the supplied client id.
*
* @param msg
* @param exceptClientId
*/
public void sendPlayerDisconnectedMessage(PlayerDisconnectedMessage msg, int exceptClientId);
/**
* Sends a {@link TeamTextMessage} to all clients
*
* @param msg
*/
public void sendPlayerSwitchTeamMessage(PlayerSwitchTeamMessage msg);
/**
* Sends a {@link PlayerSpeechMessage} to all clients except the supplied client id.
*
* @param msg
* @param exceptClientId
*/
public void sendPlayerSpeechMessage(PlayerSpeechMessage msg, int exceptClientId);
/**
* Sends a {@link PlayerSwitchPlayerClassMessage} to all clients
*
* @param conn
* @param message
* @throws IOException
*/
public void sendPlayerSwitchClassMessage(PlayerSwitchPlayerClassMessage message) throws IOException;
/**
* Sends a {@link ConnectAcceptedMessage} to a particular client
*
* @param clientId
* @param msg
*/
public void sendConnectAcceptedMessage(int clientId, ConnectAcceptedMessage msg);
/**
* Sends a {@link FlagCapturedMessage} message to all clients
*
* @param msg
*/
public void sendFlagCapturedMessage(FlagCapturedMessage msg);
/**
* Sends a {@link FlagReturnedMessage} message to all clients
* @param msg
*/
public void sendFlagReturnedMessage(FlagReturnedMessage msg);
/**
* Sends a {@link FlagStolenMessage} message to all clients
*
* @param msg
*/
public void sendFlagStolenMessage(FlagStolenMessage msg);
/**
* Sends a {@link PlayerCommanderMessage}
*
* @param msg
*/
public void sendPlayerCommanderMessage(PlayerCommanderMessage msg);
/**
* Sends a {@link PlayerAwardMessage}
*
* @param msg
*/
public void sendPlayerAwardMessage(PlayerAwardMessage msg);
/**
* Sends a {@link GameEventMessage}
*
* @param msg
*/
public void sendGameEventMessage(GameEventMessage msg);
} | 12,255 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GameServer.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/GameServer.java | /*
* see license.txt
*/
package seventh.server;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import harenet.api.Server;
import leola.vm.Leola;
import leola.vm.util.Classpath;
import seventh.game.Game;
import seventh.game.GameInfo;
import seventh.game.PlayerInfo;
import seventh.game.PlayerInfos;
import seventh.game.PlayerInfos.PlayerInfoIterator;
import seventh.game.game_types.GameType;
import seventh.game.Players;
import seventh.game.Team;
import seventh.game.net.NetGameStats;
import seventh.shared.Command;
import seventh.shared.CommonCommands;
import seventh.shared.Config;
import seventh.shared.Cons;
import seventh.shared.Console;
import seventh.shared.Debugable.DebugableListener;
import seventh.shared.LANServerRegistration;
import seventh.shared.MapList.MapEntry;
import seventh.shared.Scripting;
import seventh.shared.State;
import seventh.shared.StateMachine;
import seventh.shared.StateMachine.StateMachineListener;
import seventh.shared.TimeStep;
/**
* The {@link GameServer} handles running the game and listening for clients.
*
* @author Tony
*
*/
public class GameServer {
public static final String VERSION = "0.1.0.1-Beta";
/**
* Is the server running?
*/
private boolean isRunning;
private int port;
private Console console;
private final boolean isLocal;
private ServerContext serverContext;
private MasterServerRegistration registration;
private LANServerRegistration lanRegistration;
private OnServerReadyListener serverListener;
private DebugableListener debugListener;
/**
* A callback for when the server is loaded and is about to start
* the game.
*
* @author Tony
*
*/
public static interface OnServerReadyListener {
/**
* The server is ready for remote clients to connect.
*
* @param server
*/
public void onServerReady(GameServer server);
}
/**
* Server Game Settings
*
* @author Tony
*
*/
public static class GameServerSettings {
public String serverConfigPath = "./assets/server_config.leola";
public String serverName;
public MapEntry currentMap;
public String startupScript;
public String password;
public int maxScore;
public int maxPlayers;
public long matchTime;
public GameType.Type gameType;
public List<String> alliedTeam;
public List<String> axisTeam;
public boolean isDedicatedServer;
public boolean isLAN;
public boolean isPrivate;
public int port;
}
/**
* @param config
* @param console
* @param runtime
* @param isLocal
* @param settings
*
* @throws Exception
*/
public GameServer(ServerSeventhConfig config,
Console console,
Leola runtime,
boolean isLocal,
GameServerSettings settings) throws Exception {
this.console = console;
this.isLocal = isLocal;
/* if no settings are supplied, use
* the default configured settings
*/
if(settings == null) {
settings = new GameServerSettings();
settings.startupScript = config.getStartupScript();
settings.serverName = config.getServerName();
settings.gameType = config.getGameType();
settings.matchTime = config.getMatchTime();
settings.maxScore = config.getMaxScore();
settings.maxPlayers = config.getMaxPlayers();
settings.port = config.getPort();
settings.isDedicatedServer = true;
settings.isLAN = false;
}
init(config, runtime, settings);
}
/**
* @param console
* @param runtime
* @param isLocal
* @param settings
* @throws Exception
*/
public GameServer(Console console,
Leola runtime,
boolean isLocal,
GameServerSettings settings) throws Exception {
this(new ServerSeventhConfig(new Config(settings.serverConfigPath, "server_config", runtime)),
console,
runtime,
isLocal,
settings);
}
/**
* Defaults to a dedicated server in which uses the configured
* default settings
*
* @param config
* @param console
* @param runtime
* @throws Exception
*/
public GameServer(ServerSeventhConfig config, Console console, Leola runtime) throws Exception {
this(config, console, runtime, false, null);
}
/**
* Initializes the {@link GameServer}
*
* @param settings
* @throws Exception
*/
private void init(final ServerSeventhConfig config,
final Leola runtime,
final GameServerSettings settings) throws Exception {
this.serverContext = new ServerContext(this, config, runtime, this.console);
/* load some helper functions for objective scripts */
runtime.loadStatics(SeventhScriptingCommonLibrary.class);
runtime.put("console", this.console);
/* if this is a dedicated server, we'll contact the
* master server so that users know about this server
*/
this.console.print("Initializing MasterServerRegistration...");
this.registration = new MasterServerRegistration(this.serverContext);
if(settings.isDedicatedServer) {
this.registration.start();
this.console.println("done!");
}
else this.console.println("");
this.console.print("Initializing LANServerRegistration...");
this.lanRegistration = new LANServerRegistration(this.serverContext);
if(settings.isLAN) {
this.lanRegistration.start();
this.console.println("done!");
}
else this.console.println("");
/* attempt to attach a debugger */
if(config.isDebuggerEnabled()) {
this.console.println("Initializing debugger: " + config.getDebuggerClassName());
DebugableListener debugableListener = createDebugListener(config);
if(debugableListener != null) {
setDebugListener(debugableListener);
}
}
/*
* Load up the bots
*/
this.serverContext.getStateMachine().setListener(new StateMachineListener<State>() {
@Override
public void onEnterState(State state) {
/* only listen for the first in game state
* transition because we only need to 'wait'
* for the server to be up the first time in.
*
* This addresses the Single Player bug of the
* Bots not spawning
*/
if( (state instanceof InGameState) ) {
console.println("Entering game state");
if(settings.startupScript != null) {
console.println("Running startup script: '" + settings.startupScript + "'");
console.execute("run", settings.startupScript);
}
if(settings.alliedTeam != null) {
for(String name : settings.alliedTeam) {
console.execute("add_bot " + name + " allies");
}
}
if(settings.axisTeam != null) {
for(String name : settings.axisTeam) {
console.execute("add_bot " + name + " axis");
}
}
if(serverListener != null) {
serverListener.onServerReady(GameServer.this);
}
/* clear out this listener because we only want
* to do this once for a game load!
*/
serverContext.getStateMachine().setListener(null);
}
}
@Override
public void onExitState(State state) {
}
});
setupServerCommands(console);
config.setServerName(settings.serverName);
config.setGameType(settings.gameType);
config.setMatchTime(settings.matchTime);
config.setMaxScore(settings.maxScore);
MapCycle mapCycle = serverContext.getMapCycle();
if(settings.currentMap == null) {
settings.currentMap = mapCycle.getCurrentMap();
}
mapCycle.setCurrentMap(settings.currentMap);
/* load up the map */
serverContext.spawnGameSession(settings.currentMap);
console.println("Done initialzing the game server, ready to launch network...");
}
/**
* Attempt to create a {@link DebugableListener} from the supplied configuration
*
* @param config
* @return the {@link DebugableListener} if one is available, or null
*/
private DebugableListener createDebugListener(ServerSeventhConfig config) {
try {
String className = config.getDebuggerClassName();
if(className != null && !"".equals(className)) {
/* add jars to the class path if needed */
String classpath = config.getDebuggerClasspath();
if(classpath != null && !"".equals(classpath)) {
Classpath.loadJars(classpath);
}
Class<?> aClass = Class.forName(className);
DebugableListener listener = (DebugableListener)aClass.newInstance();
if(listener != null) {
listener.init(config);
}
return listener;
}
}
catch(Throwable t) {
Cons.println("Unable to load the debugger: " + t);
}
return null;
}
/**
* Setups server side console commands
*
* @param console
*/
private void setupServerCommands(Console console) {
CommonCommands.addCommonCommands(console);
final ServerSeventhConfig config = serverContext.getConfig();
final MapCycle mapCycle = serverContext.getMapCycle();
console.addCommand(mapCycle.getMapListCommand());
console.addCommand(mapCycle.getMapAddCommand());
console.addCommand(mapCycle.getMapRemoveCommand());
console.addCommand(new Command("map") {
@Override
public void execute(Console console, String... args) {
serverContext.spawnGameSession(new MapEntry(mergeArgsDelim(" ", args)));
}
});
console.addCommand(new Command("map_next") {
@Override
public void execute(Console console, String... args) {
serverContext.spawnGameSession(mapCycle.getNextMap());
}
});
console.addCommand(new Command("map_restart") {
@Override
public void execute(Console console, String... args) {
serverContext.spawnGameSession(serverContext.getMapCycle().getCurrentMap());
}
});
console.addCommand(new Command("run") {
@Override
public void execute(Console console, String... args) {
Scripting.loadScript(serverContext.getRuntime(), mergeArgs(args));
}
});
console.addCommand(new Command("sv_privatePassword") {
@Override
public void execute(Console console, String... args) {
ServerSeventhConfig config = serverContext.getConfig();
if(args == null || args.length < 1) {
console.println("sv_privatePassword: " + config.getPrivatePassword());
}
else {
config.setPrivatePassword(args[0]);
}
}
});
console.addCommand(new Command("add_bot") {
@Override
public void execute(Console console, String... args) {
Game game = serverContext.getGameSession().getGame();
if(game != null) {
if(args.length < 1) {
console.println("<usage> add_bot [bot name] [optional team]");
}
else {
int id = serverContext.getServer().reserveId();
if(id >= 0) {
String botName = mergeArgsDelim(" ", args);
String teamName = args[args.length-1].trim();
if(teamName.toLowerCase().equals(Team.ALLIED_TEAM_NAME.toLowerCase()) ||
teamName.toLowerCase().equals(Team.AXIS_TEAM_NAME.toLowerCase())) {
botName = botName.replace(teamName, "");
}
game.addBot(id, botName);
if(teamName.startsWith(Team.ALLIED_TEAM_NAME.toLowerCase())) {
game.playerSwitchedTeam(id, Team.ALLIED_TEAM_ID);
}
else if(teamName.startsWith(Team.AXIS_TEAM_NAME.toLowerCase())) {
game.playerSwitchedTeam(id, Team.AXIS_TEAM_ID);
}
console.println("Added Bot...ID: " + id);
}
else {
console.println("Server if full, could not add bot");
}
}
}
else {
console.println("The game has not properly been setup yet!");
}
}
});
console.addCommand(new Command("add_dummy_bot") {
@Override
public void execute(Console console, String... args) {
Game game = serverContext.getGameSession().getGame();
if(game != null) {
int id = serverContext.getServer().reserveId();
if(id >= 0) {
game.addDummyBot(id);
}
console.println("Added Dummy Bot...ID: " + id);
}
}
});
console.addCommand(new Command("kick") {
@Override
public void execute(Console console, String... args) {
Game game = serverContext.getGameSession().getGame();
if(game != null) {
switch(args.length) {
case 0 : console.println("*** You must supply a playerId");
break;
default: {
int id = Integer.parseInt(args[0]);
console.println("Kicking playerId: " + id);
game.kickPlayer(id);
}
}
}
}
});
console.addCommand(new Command("kill") {
@Override
public void execute(Console console, String... args) {
GameInfo game = serverContext.getGameSession().getGame();
if(game != null) {
switch(args.length) {
case 0 : console.println("*** You must supply a playerId");
break;
default: {
int id = Integer.parseInt(args[0]);
PlayerInfo player = game.getPlayerById(id);
if(player != null && !player.isDead()) {
player.getEntity().kill(player.getEntity());
}
}
}
}
}
});
console.addCommand(new Command("players") {
@Override
public void execute(final Console console, String... args) {
GameInfo game = serverContext.getGameSession().getGame();
if(game != null) {
PlayerInfos players = game.getPlayerInfos();
console.println("Name ID Ping");
console.println("============================================");
players.forEachPlayerInfo(new PlayerInfoIterator() {
@Override
public void onPlayerInfo(PlayerInfo p) {
console.printf("%-25s %-16d %-4d\n", p.getName(), p.getId(), p.getPing());
}
});
console.println("\n");
}
}
});
console.addCommand(new Command("stats") {
@Override
public void execute(final Console console, String... args) {
Game game = serverContext.getGameSession().getGame();
if(game != null) {
final DateFormat format = new SimpleDateFormat("HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
console.println("\n");
Players players = game.getPlayers();
console.println("Name Kills Deaths Joined Team");
console.println("======================================================================");
players.forEachPlayerInfo(new PlayerInfoIterator() {
@Override
public void onPlayerInfo(PlayerInfo p) {
console.printf("%-25s %6d %11d %12s %12s\n", p.getName(), p.getKills(), p.getDeaths()
, format.format(new Date(p.getJoinTime())), p.getTeam().getName());
}
});
console.println("\n");
console.println("\tTeam ID Score");
console.println("\t=============================");
NetGameStats stats = game.getNetGameStats();
console.printf("\t%-15s %2d %10d\n", Team.getName(stats.alliedTeamStats.id)
, stats.alliedTeamStats.id
, stats.alliedTeamStats.score );
console.printf("\t%-15s %2d %10d\n", Team.getName(stats.axisTeamStats.id)
, stats.axisTeamStats.id
, stats.axisTeamStats.score );
console.println("\n");
}
}
});
console.addCommand(new Command("sv_exit") {
@Override
public void execute(Console console, String... args) {
console.println("Shutting down the system...");
shutdown();
console.println("Shutdown complete!");
System.exit(0);
}
});
if(console.getCommand("exit") == null) {
console.addCommand("exit", console.getCommand("sv_exit"));
console.addCommand("quit", console.getCommand("sv_exit"));
}
console.addCommand(new Command("get") {
@Override
public void execute(Console console, String... args) {
switch(args.length) {
case 0: console.println("<Usage> get [variable name]");
break;
default:
console.println(args[0] + " = " + config.getConfig().get(args[0]));
break;
}
}
});
console.addCommand(new Command("set") {
@Override
public void execute(Console console, String... args) {
switch(args.length) {
case 0: console.println("<Usage> set [variable name] [value]");
break;
case 1: console.println(args[0] + " = " + config.getConfig().get(args[0]));
break;
default: {
config.getConfig().set( mergeArgsDelimAt(" ", 1, args), args[0]);
}
}
}
});
console.addCommand(new Command("seti") {
@Override
public void execute(Console console, String... args) {
switch(args.length) {
case 0: console.println("<Usage> seti [variable name] [value]");
break;
case 1: console.println(args[0] + " = " + config.getConfig().get(args[0]));
break;
default: {
try {
config.getConfig().set(Integer.parseInt(args[1]), args[0]);
}
catch(Exception e) {
console.println("Illegal input, must be an integer value");
}
}
}
}
});
console.addCommand(new Command("new_tank") {
@Override
public void execute(Console console, String... args) {
if(getServerContext().hasGameSession()) {
GameSession session = getServerContext().getGameSession();
Game game = session.getGame();
if (game != null) {
switch(args.length) {
case 2:
try {
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
game.newShermanTank(x, y, 60_000L);
}
catch(Exception e) {
console.println("Unable to create tank: " + e);
}
break;
default: {
console.println("<usage> new_tank [x coordinate] [y coordinate]");
}
}
}
}
}
});
console.addCommand(new Command("gametype") {
@Override
public void execute(Console console, String... args) {
if(getServerContext().hasGameSession()) {
GameSession session = getServerContext().getGameSession();
Game game = session.getGame();
if (game != null) {
switch(args.length) {
case 0:
console.println("<usage> gametype [obj|tdm] [max score] [time]");
break;
case 1:
console.execute("set sv_gametype " + args[0]);
break;
case 2:
console.execute("set sv_gametype " + args[0]);
console.execute("set sv_maxscore " + args[1]);
break;
case 3:
console.execute("set sv_gametype " + args[0]);
console.execute("seti sv_maxscore " + args[1]);
console.execute("seti sv_matchtime " + args[2]);
break;
default: {
console.println("<usage> new_tank [x coordinate] [y coordinate]");
}
}
}
}
}
});
}
/**
* @return the serverContext
*/
public ServerContext getServerContext() {
return serverContext;
}
/**
* @return the serverListener
*/
public OnServerReadyListener getServerListener() {
return serverListener;
}
/**
* @param serverListener the serverListener to set
*/
public void setServerListener(OnServerReadyListener serverListener) {
this.serverListener = serverListener;
}
/**
* @param debugListener the debugListener to set
*/
public void setDebugListener(DebugableListener debugListener) {
this.debugListener = debugListener;
}
/**
* @return the debugListener
*/
public DebugableListener getDebugListener() {
return debugListener;
}
/**
* @return the isRunning
*/
public boolean isRunning() {
return isRunning;
}
/**
* @return the isLocal
*/
public boolean isLocal() {
return isLocal;
}
/**
* @return the port
*/
public int getPort() {
return port;
}
/**
* Starts the server listening on the supplied port
*
* @param port
* @throws Exception
*/
public void start(int port) throws Exception {
if(this.isRunning) {
throw new IllegalStateException("The server is already running");
}
this.port = port;
this.isRunning = true;
Cons.println("*** Launching GameServer v" + VERSION + " ***");
Server server = this.serverContext.getServer();
StateMachine<State> sm = this.serverContext.getStateMachine();
/* start listening on the supplied port */
server.bind(port);
server.start();
Cons.println("*** Listening on port: " + port + " ***");
try {
long currentTime = System.currentTimeMillis();
long accumalator = 0;
long gameClock = 0;
final int maxIterations = 5;
final long maxDelta = 250;
final long frameRate = Math.abs(serverContext.getConfig().getServerFrameRate());
final long dt = 1000 / frameRate == 0 ? 20 : frameRate;
final TimeStep timeStep = new TimeStep();
timeStep.setDeltaTime(dt);
timeStep.setGameClock(gameClock);
// flush pending console commands
updateConsole(timeStep);
while(this.isRunning) {
long newTime = System.currentTimeMillis();
long deltaTime = newTime - currentTime;
if(deltaTime > maxDelta) {
deltaTime = maxDelta;
}
if ( deltaTime >= dt ) {
currentTime = newTime;
accumalator += deltaTime;
int iteration = 0;
while( accumalator >= dt && iteration < maxIterations) {
timeStep.setDeltaTime(dt);
timeStep.setGameClock(gameClock);
serverFrame(sm, timeStep);
gameClock += dt;
accumalator -= dt;
iteration++;
}
}
}
}
catch(Exception e) {
Cons.println("*** An error occured in the main server game loop: " + e);
Cons.println("*** Stack trace: " + Arrays.toString(e.getStackTrace()));
}
finally {
Cons.println("Shutting down the server...");
sm.changeState(null); // makes sure the current state is exited
server.stop();
server.close();
this.registration.shutdown();
this.lanRegistration.shutdown();
if(this.debugListener != null) {
this.debugListener.shutdown();
}
Cons.println("Server shutdown completed!");
}
}
private void updateConsole(TimeStep timeStep) {
if(!this.isLocal) {
this.console.update(timeStep);
}
}
/**
* Executes a server frame
*
* @param timeStep
*/
private void serverFrame(StateMachine<State> sm, TimeStep timeStep) {
updateConsole(timeStep);
sm.update(timeStep);
}
/**
* Shutdown the server
*/
public void shutdown() {
this.isRunning = false;
}
}
| 30,786 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MasterServerRegistration.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/MasterServerRegistration.java | /*
* see license.txt
*/
package seventh.server;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import seventh.shared.Cons;
import seventh.shared.MasterServerClient;
import seventh.shared.MasterServerConfig;
/**
* Registers with the Master Server
*
* @author Tony
*
*/
public class MasterServerRegistration implements Runnable {
private ServerContext serverContext;
private MasterServerClient serverClient;
private int pingRate;
private ScheduledExecutorService service;
/**
* @param serverContext
*/
public MasterServerRegistration(ServerContext serverContext) {
this.serverContext = serverContext;
MasterServerConfig config = serverContext.getConfig().getMasterServerConfig();
this.serverClient = new MasterServerClient(config);
this.pingRate = config.getPingRateMinutes();
}
/**
* Start the background process in which pings the master server at a fixed rate
* for as long as this game server is operational.
*
*/
public void start() {
if(this.service == null) {
this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "master-server-ping");
thread.setDaemon(true);
return thread;
}
});
this.service.scheduleWithFixedDelay(this, pingRate, pingRate, TimeUnit.MINUTES);
}
}
/**
* Shuts down the heartbeat
*/
public void shutdown() {
if(this.service != null) {
this.service.shutdownNow();
this.service = null;
}
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
try {
sendHeartbeat();
}
catch(Exception e) {
Cons.println("*** Error, unable to send heartbeat to master server: " + e);
}
}
/**
* Sends a heart beat to the master server
* @throws Exception
*/
public void sendHeartbeat() throws Exception {
this.serverClient.sendHeartbeat(this.serverContext);
}
}
| 2,496 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GameSessionListener.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/GameSessionListener.java | /*
* see license.txt
*/
package seventh.server;
/**
* Listens for {@link GameSession} creation/destruction.
*
* @author Tony
*
*/
public interface GameSessionListener {
/**
* A new {@link GameSession} has started
*
* @param session
*/
public void onGameSessionCreated(GameSession session);
/**
* The current {@link GameSession} has been terminated
*
* @param session
*/
public void onGameSessionDestroyed(GameSession session);
}
| 508 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GameSession.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/server/GameSession.java | /*
* see license.txt
*/
package seventh.server;
import seventh.game.Game;
import seventh.game.GameMap;
import seventh.game.Players;
import seventh.game.game_types.GameType;
import seventh.shared.EventDispatcher;
import seventh.shared.SeventhConfig;
/**
* A game is in session, represents a structure holding session data.
*
* @author Tony
*
*/
public class GameSession {
private Game game;
private GameMap map;
private GameType gameType;
private Players players;
private EventDispatcher eventDispatcher;
/**
* @param config
* @param map
* @param gameType
* @param players
*/
public GameSession(SeventhConfig config, GameMap map, GameType gameType, Players players) {
this.map = map;
this.gameType = gameType;
this.players = players;
this.eventDispatcher = new EventDispatcher();
this.game = new Game(config, players, gameType, map, this.eventDispatcher);
}
/**
* @param game
* @param map
* @param gameType
* @param players
* @param eventDispatcher
*/
public GameSession(Game game, GameMap map, GameType gameType, Players players, EventDispatcher eventDispatcher) {
this.game = game;
this.map = map;
this.gameType = gameType;
this.players = players;
this.eventDispatcher = eventDispatcher;
}
/**
* Destroys the {@link GameSession}, clearing out all
* state associated with the session.
*
*/
public void destroy() {
this.game.destroy();
this.eventDispatcher.removeAllEventListeners();
this.eventDispatcher.clearQueue();
}
/**
* @return the game
*/
public Game getGame() {
return game;
}
/**
* @return the map
*/
public GameMap getMap() {
return map;
}
/**
* @return the gameType
*/
public GameType getGameType() {
return gameType;
}
/**
* @return the players
*/
public Players getPlayers() {
return players;
}
/**
* @return the eventDispatcher
*/
public EventDispatcher getEventDispatcher() {
return eventDispatcher;
}
}
| 2,263 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AICommand.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/AICommand.java | /*
* see license.txt
*/
package seventh.ai;
import seventh.network.messages.BufferIO;
import harenet.IOBuffer;
import harenet.messages.NetMessage;
/**
* Directs a bot to do something
*
* @author Tony
*
*/
public class AICommand implements NetMessage {
private String message;
/**
*/
public AICommand() {
this("");
}
/**
* @param message
*/
public AICommand(String message) {
this.message = message;
}
/* (non-Javadoc)
* @see harenet.messages.NetMessage#read(harenet.IOBuffer)
*/
@Override
public void read(IOBuffer buffer) {
this.message = BufferIO.readString(buffer);
}
/* (non-Javadoc)
* @see harenet.messages.NetMessage#write(harenet.IOBuffer)
*/
@Override
public void write(IOBuffer buffer) {
BufferIO.writeString(buffer, message);
}
/**
* @return the message
*/
public String getMessage() {
return message;
}
}
| 1,002 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AISystem.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/AISystem.java | /*
* see license.txt
*/
package seventh.ai;
import seventh.ai.basic.AIConfig;
import seventh.game.GameInfo;
import seventh.game.PlayerInfo;
import seventh.shared.Debugable;
import seventh.shared.Randomizer;
import seventh.shared.Updatable;
/**
* The AI Subsystem
*
* @author Tony
*
*/
public interface AISystem extends Updatable, Debugable {
/**
* Initialize the AI system
* @param game
*/
public void init(GameInfo game);
public AIConfig getConfig();
public Randomizer getRandomizer();
/**
* Cleans up any allocated resources
*/
public void destroy();
/**
* A player has joined
* @param player
*/
public void playerJoined(PlayerInfo player);
/**
* A player has left the game
* @param player
*/
public void playerLeft(PlayerInfo player);
/**
* A player has just spawned
* @param player
*/
public void playerSpawned(PlayerInfo player);
/**
* A player has been killed
* @param player
*/
public void playerKilled(PlayerInfo player);
/**
* The start of a match
* @param game
*/
public void startOfRound(GameInfo game);
/**
* The end of a match
* @param game
*/
public void endOfRound(GameInfo game);
/**
* Receives an {@link AICommand}
* @param forBot
* @param command
*/
public void receiveAICommand(PlayerInfo forBot, AICommand command);
}
| 1,514 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Memory.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/Memory.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.ai.basic.memory.FeelMemory;
import seventh.ai.basic.memory.SightMemory;
import seventh.ai.basic.memory.SoundMemory;
import seventh.shared.TimeStep;
import seventh.shared.Updatable;
/**
* The {@link Brain}s memory, store and retrieve information.
*
* @author Tony
*
*/
public class Memory implements Updatable {
private SightMemory sightMemory;
private SoundMemory soundMemory;
private FeelMemory feelMemory;
public Memory(Brain brain) {
AIConfig config = brain.getConfig();
this.sightMemory = new SightMemory(config.getSightExpireTime());
this.soundMemory = new SoundMemory(config.getSoundExpireTime());
this.feelMemory = new FeelMemory(config.getFeelExpireTime());
}
/* (non-Javadoc)
* @see seventh.shared.Updatable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
this.sightMemory.update(timeStep);
this.soundMemory.update(timeStep);
this.feelMemory.update(timeStep);
}
/**
* @return the soundMemory
*/
public SoundMemory getSoundMemory() {
return soundMemory;
}
/**
* @return the sightMemory
*/
public SightMemory getSightMemory() {
return sightMemory;
}
/**
* @return the feelMemory
*/
public FeelMemory getFeelMemory() {
return feelMemory;
}
/**
* Clear the memory
*/
public void clear() {
this.sightMemory.clear();
this.soundMemory.clear();
this.feelMemory.clear();
}
}
| 1,680 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Cover.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/Cover.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.math.Vector2f;
/**
* Cover from an attack direction
*
* @author Tony
*
*/
public class Cover {
private Vector2f coverPos;
private Vector2f attackDir;
/**
* @param coverPos
* @param attackDir
*/
public Cover(Vector2f coverPos, Vector2f attackDir) {
this.coverPos = coverPos;
this.attackDir = attackDir;
}
/**
* @param attackDir the attackDir to set
*/
public void setAttackDir(Vector2f attackDir) {
this.attackDir.set(attackDir);
}
/**
* @param coverPos the coverPos to set
*/
public void setCoverPos(Vector2f coverPos) {
this.coverPos.set(coverPos);
}
/**
* @return the attackDir
*/
public Vector2f getAttackDir() {
return attackDir;
}
/**
* @return the coverPos
*/
public Vector2f getCoverPos() {
return coverPos;
}
}
| 987 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ThoughtProcess.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/ThoughtProcess.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.shared.Debugable;
import seventh.shared.TimeStep;
/**
* The entities thought process
*
* @author Tony
*
*/
public interface ThoughtProcess extends Debugable {
/**
* This brain has freshly spawned
* @param brain
*/
public void onSpawn(Brain brain);
/**
* The player has been killed
* @param brain
*/
public void onKilled(Brain brain);
/**
* A pluggable thinking/strategy
* @param timeStep
* @param brain
*/
public void think(TimeStep timeStep, Brain brain);
}
| 624 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Sensor.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/Sensor.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.shared.TimeStep;
/**
* A Sensor is a sense, such as Sight, Sound, etc.
*
* @author Tony
*
*/
public interface Sensor {
/**
* Reset to a starting state
* @param brain
*/
public void reset(Brain brain);
/**
* Updates the Sensor
*
* @param timeStep
*/
public void update(TimeStep timeStep);
}
| 452 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FeelSensor.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/FeelSensor.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.ai.basic.memory.FeelMemory;
import seventh.ai.basic.memory.FeelMemory.FeelMemoryRecord;
import seventh.game.entities.Entity;
import seventh.game.entities.PlayerEntity;
import seventh.game.entities.Entity.OnDamageListener;
import seventh.shared.TimeStep;
/**
* Anything touching us
*
* @author Tony
*
*/
public class FeelSensor implements Sensor, OnDamageListener {
private FeelMemory memory;
private TimeStep timeStep;
private Brain brain;
/**
* @param brain
*/
public FeelSensor(Brain brain) {
this.brain = brain;
this.memory = brain.getMemory().getFeelMemory();
PlayerEntity ent = brain.getEntityOwner();
if(ent != null) {
ent.onDamage = this;
}
}
/**
* Retrieves the most recent attacker
*
* @return Retrieves the most recent attacker
*/
public Entity getMostRecentAttacker() {
FeelMemoryRecord[] records = memory.getFeelRecords();
Entity recentAttacker = null;
long mostRecentTime = Long.MAX_VALUE;
for(int i = 0; i < records.length; i++) {
if(records[i].isValid()) {
if (recentAttacker == null ||
mostRecentTime > records[i].getTimeFeltAgo()) {
mostRecentTime = records[i].getTimeFeltAgo();
recentAttacker = records[i].getDamager();
}
}
}
return recentAttacker;
}
/* (non-Javadoc)
* @see seventh.ai.Sensor#reset(seventh.ai.Brain)
*/
@Override
public void reset(Brain brain) {
this.memory.clear();
PlayerEntity ent = brain.getEntityOwner();
if(ent!=null) {
ent.onDamage = this;
}
}
/* (non-Javadoc)
* @see palisma.ai.Sensor#update(leola.live.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
this.timeStep = timeStep;
}
/**
* Registered callback
* @param damager
* @param amount
*/
@Override
public void onDamage(Entity damager, int amount) {
if( damager != null && !this.brain.getPlayer().isTeammateWith(damager.getId())) {
this.memory.feel(this.timeStep, damager);
}
}
}
| 2,426 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Sensors.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/Sensors.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.shared.TimeStep;
/**
* Just a container for all of our sensory inputs
*
* @author Tony
*
*/
public class Sensors {
private SightSensor sightSensor;
private SoundSensor soundSensor;
private FeelSensor feelSensor;
public Sensors(Brain brain) {
this.sightSensor = new SightSensor(brain);
this.soundSensor = new SoundSensor(brain);
this.feelSensor = new FeelSensor(brain);
}
/**
* Resets each {@link Sensor}
*
* @param brain
*/
public void reset(Brain brain) {
this.sightSensor.reset(brain);
this.soundSensor.reset(brain);
this.feelSensor.reset(brain);
}
/**
* @return the feelSensor
*/
public FeelSensor getFeelSensor() {
return feelSensor;
}
/**
* @return the sightSensor
*/
public SightSensor getSightSensor() {
return sightSensor;
}
/**
* @return the soundSensor
*/
public SoundSensor getSoundSensor() {
return soundSensor;
}
/**
* Poll each sensor
* @param timeStep
*/
public void update(TimeStep timeStep) {
this.sightSensor.update(timeStep);
this.soundSensor.update(timeStep);
this.feelSensor.update(timeStep);
}
}
| 1,399 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Brain.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/Brain.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.ai.basic.actions.Action;
import seventh.ai.basic.teamstrategy.TeamStrategy;
import seventh.game.PlayerInfo;
import seventh.game.entities.PlayerEntity;
import seventh.graph.GraphNode;
import seventh.map.Tile;
import seventh.math.Vector2f;
import seventh.shared.DebugDraw;
import seventh.shared.Debugable;
import seventh.shared.TimeStep;
/**
* An AI Brain, handles all of the sensory inputs, locomotion, memory and
* thought processes.
*
* @author Tony
*
*/
public class Brain implements Debugable {
private Locomotion motion;
private Memory memory;
private Sensors sensors;
private ThoughtProcess thoughtProcess;
private Communicator communicator;
private World world;
private PlayerInfo player;
private PlayerEntity entityOwner;
private TargetingSystem targetingSystem;
private PersonalityTraits personality;
/**
* @param runtime
* @param world
*/
public Brain(PersonalityTraits personality, TeamStrategy strategy, World world, PlayerInfo player) {
this.personality = personality;
this.world = world;
this.player = player;
this.entityOwner = player.getEntity();
this.memory = new Memory(this);
this.motion = new Locomotion(this);
this.sensors = new Sensors(this);
this.thoughtProcess = new WeightedThoughtProcess(strategy, this);
this.communicator = new Communicator(world);
this.targetingSystem = new TargetingSystem(this);
}
/**
* Called after the player is all set, and this entity
* is ready to roll
*/
public void spawned(TeamStrategy strategy) {
this.entityOwner = player.getEntity();
this.targetingSystem.reset(this);
this.communicator.reset(this);
this.sensors.reset(this);
this.motion.reset(this);
/* if this is a Dummy bot, make it just sit there */
if(player.isDummyBot()) {
this.thoughtProcess = DummyThoughtProcess.getInstance();
}
else {
this.thoughtProcess = new WeightedThoughtProcess(strategy, this);
}
this.thoughtProcess.onSpawn(this);
}
/**
* Called when the agent dies
*/
public void killed() {
this.thoughtProcess.onKilled(this);
}
/**
* @return the config
*/
public AIConfig getConfig() {
return this.world.getConfig();
}
/**
* @return the player
*/
public PlayerInfo getPlayer() {
return player;
}
public double getRandomRange(double min, double max) {
return this.world.getRandom().getRandomRange(min, max);
}
public double getRandomRangeMin(double min) {
return getRandomRange(min, 1.0);
}
public double getRandomRangeMax(double max) {
return getRandomRange(0.0, max);
}
/**
* @return the personality
*/
public PersonalityTraits getPersonality() {
return personality;
}
/**
* Broadcasts a command
*
* @param cmd
*/
public void broadcastCommand(Action cmd) {
this.communicator.broadcastAction(this, cmd);
}
/**
* Have this bot do the supplied {@link Action}, make
* it top priority
*
* @param action
*/
public void doAction(Action action) {
this.communicator.makeTopPriority(action);
}
/**
* Lets the brain think for a game tick
*
* @param timeStep
*/
public void update(TimeStep timeStep) {
/* We can't rely on the player's isAlive method because
* we might have respawned with a new entity, in which
* case the Brain.spawned method will be invoked, but
* for now we must rely on the entity that is currently
* bound to this Brain
*/
if(entityOwner!=null&&entityOwner.isAlive()) {
this.memory.update(timeStep);
this.sensors.update(timeStep);
this.motion.update(timeStep);
this.thoughtProcess.think(timeStep, this);
this.targetingSystem.update(timeStep);
//debugDraw();
//debugDrawPathPlanner();
}
}
@SuppressWarnings("unused")
private void debugDraw() {
Cover cover = world.getCover(entityOwner, entityOwner.getPos());
//DebugDraw.fillRectRelative( (int)cover.getCoverPos().x, (int)cover.getCoverPos().y, 5, 5, 0xff00ff00);
/*List<AttackDirection> attackDirections = world.getAttackDirections(entityOwner);
for(AttackDirection dir : attackDirections) {
DebugDraw.drawLineRelative(entityOwner.getPos(), dir.getDirection(), 0xff00ff00);
}*/
//DebugDraw.drawString(this.thoughtProcess.toString(), new Vector2f(-120, 700), 0xff00ffff);
//Vector2f p = new Vector2f(entityOwner.getPos().x-250, entityOwner.getPos().y + 40);
//DebugDraw.drawStringRelative(motion.getDebugInformation().toString(), p, 0xff00ffff);
//DebugDraw.drawString(this.thoughtProcess.toString(), p, 0xff00ffff);
Vector2f p = new Vector2f(entityOwner.getPos().x-50, entityOwner.getPos().y + 40);
String str = this.thoughtProcess.toString();
String[] sections = str.split("\\{");
for(String section : sections) {
String[] attributes = section.split(":");
for(String att : attributes) {
DebugDraw.drawStringRelative(att, p, 0xff00ffff);
p.y += 12;
}
p.x += 10;
}
/*for(BombTarget target : world.getBombTargetsWithActiveBombs()) {
if( target.getBomb() != null ) {
Bomb bomb = target.getBomb();
Rectangle b = bomb.getBlastRadius();
DebugDraw.fillRectRelative(b.x, b.y, b.width, b.height, 0xaf00ffff);
}
}*/
}
@SuppressWarnings("unused")
private void debugDrawPathPlanner() {
int x = (int) entityOwner.getCenterPos().x;
int y = (int) entityOwner.getCenterPos().y;
GraphNode<Tile, ?> snode = world.getGraph().getNodeByWorld(x,y);
if(snode != null) {
DebugDraw.fillRectRelative(snode.getValue().getX(), snode.getValue().getY(), snode.getValue().getWidth(), snode.getValue().getHeight(), 0x3b00ff00);
}
Tile t = world.getMap().getWorldTile(0, x, y);
if(t!=null) {
DebugDraw.fillRectRelative(t.getX(), t.getY(), t.getWidth(), t.getHeight(), 0x1b0000ff);
}
// MapGraph<?> tt = world.getGraph();
// for(int yy = 0; yy < tt.graph.length; yy++) {
// for(int xx = 0; xx < tt.graph[0].length; xx++) {
// snode = (GraphNode<Tile, ?>) tt.graph[yy][xx];
// if(snode != null) {
// DebugDraw.fillRectRelative(snode.getValue().getX(), snode.getValue().getY(), snode.getValue().getWidth(), snode.getValue().getHeight(), 0x1fffff00);
// DebugDraw.drawRectRelative(snode.getValue().getX(), snode.getValue().getY(), snode.getValue().getWidth(), snode.getValue().getHeight(), 0xffffffff);
// }
// }
// }
PathPlanner<?> pathPlanner = motion.getPathPlanner();
if(pathPlanner != null) {
for(GraphNode<Tile, ?> node : pathPlanner.getPath()) {
Tile tile = node.getValue();
if(tile != null) {
DebugDraw.fillRectRelative(tile.getX(), tile.getY(), tile.getWidth(), tile.getHeight(), 0x0600ff00);
}
}
}
}
/**
* @return the targetingSystem
*/
public TargetingSystem getTargetingSystem() {
return targetingSystem;
}
/**
* @return the motion
*/
public Locomotion getMotion() {
return motion;
}
/**
* @return the memory
*/
public Memory getMemory() {
return memory;
}
/**
* @return the sensors
*/
public Sensors getSensors() {
return sensors;
}
/**
* @return the thoughtProcess
*/
public ThoughtProcess getThoughtProcess() {
return thoughtProcess;
}
/**
* @return the communicator
*/
public Communicator getCommunicator() {
return communicator;
}
/**
* @return the world
*/
public World getWorld() {
return world;
}
/**
* @return the entityOwner
*/
public PlayerEntity getEntityOwner() {
return entityOwner;
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
me.add("entity_id", (this.entityOwner!=null) ? getEntityOwner().getId() : null)
.add("locomotion", this.motion)
.add("thoughts", getThoughtProcess());
return me;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 9,571 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DefaultAISystem.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/DefaultAISystem.java | /*
* see license.txt
*/
package seventh.ai.basic;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import leola.vm.Leola;
import leola.vm.types.LeoMap;
import leola.vm.types.LeoObject;
import leola.vm.types.LeoUserFunction;
import seventh.ai.AICommand;
import seventh.ai.AISystem;
import seventh.ai.basic.actions.Action;
import seventh.ai.basic.actions.Actions;
import seventh.ai.basic.commands.AICommands;
import seventh.ai.basic.teamstrategy.CaptureTheFlagTeamStrategy;
import seventh.ai.basic.teamstrategy.CommanderTeamStrategy;
import seventh.ai.basic.teamstrategy.ObjectiveTeamStrategy;
import seventh.ai.basic.teamstrategy.TDMTeamStrategy;
import seventh.ai.basic.teamstrategy.TeamStrategy;
import seventh.game.GameInfo;
import seventh.game.PlayerInfo;
import seventh.game.PlayerInfos;
import seventh.game.PlayerInfos.PlayerInfoIterator;
import seventh.game.game_types.GameType;
import seventh.game.game_types.cmd.CommanderGameType;
import seventh.game.Team;
import seventh.math.Rectangle;
import seventh.shared.AssetLoader;
import seventh.shared.AssetWatcher;
import seventh.shared.Cons;
import seventh.shared.DebugDraw;
import seventh.shared.FileSystemAssetWatcher;
import seventh.shared.Randomizer;
import seventh.shared.Scripting;
import seventh.shared.SeventhConstants;
import seventh.shared.TimeStep;
/**
* The Default AI System implementation. This implementation is based
* off of making Reactive Decisions based off of Sensory inputs. If no
* immediate decision can be made, a general goal (objective) is worked
* towards.
*
* @author Tony
*
*/
public class DefaultAISystem implements AISystem {
private GameInfo game;
private TeamStrategy alliedAIStrategy;
private TeamStrategy axisAIStrategy;
private Brain[] brains;
private Zones zones;
private Stats stats;
private Randomizer random;
private Leola runtime;
private Actions goals;
private AICommands aiCommands;
private AssetWatcher watcher;
private AIConfig config;
private World world;
private final Map<String, PersonalityTraits> personalities;
private static final PersonalityTraits defaultPersonality = new PersonalityTraits();
static {
defaultPersonality.accuracy = 0.6;
defaultPersonality.aggressiveness = 0.7;
defaultPersonality.curiosity = 0.65;
defaultPersonality.obedience = 1.0;
}
/**
*
*/
public DefaultAISystem() {
this.brains = new Brain[SeventhConstants.MAX_PLAYERS];
this.personalities = new HashMap<>();
try {
this.runtime = Scripting.newRuntime();
this.watcher = new FileSystemAssetWatcher(new File("./assets/ai"));
this.watcher.loadAsset("goals.leola", new AssetLoader<File>() {
@Override
public File loadAsset(String filename) throws IOException {
try {
Cons.println("Evaluating: " + filename);
runtime.eval(new File(filename));
Cons.println("Successfully evaluated: " + filename);
}
catch (Exception e) {
Cons.println("*** Error evaluating: " + filename);
Cons.println("*** " + e);
}
return null;
}
});
this.watcher.loadAsset("personalities.leola", new AssetLoader<File>() {
@Override
public File loadAsset(String filename) throws IOException {
try {
Cons.println("Evaluating: " + filename);
runtime.eval(new File(filename));
LeoObject config = runtime.get("personalities");
if(LeoObject.isTrue(config) && config.isMap()) {
LeoMap a = config.as();
a.foreach(new LeoUserFunction() {
public LeoObject call(LeoObject key, LeoObject value) {
PersonalityTraits traits = new PersonalityTraits();
traits.accuracy = value.getObject("accuracy").asDouble();
traits.aggressiveness = value.getObject("aggressiveness").asDouble();
traits.curiosity = value.getObject("curiosity").asDouble();
traits.obedience = value.getObject("obedience").asDouble();
personalities.put(key.toString(), traits);
return LeoObject.NULL;
}
});
}
Cons.println("Successfully evaluated: " + filename);
}
catch (Exception e) {
Cons.println("*** Error evaluating: " + filename);
Cons.println("*** " + e);
}
return null;
}
});
}
catch(Exception e) {
Cons.println("Unable to load the Leola runtime : " + e);
}
}
/* (non-Javadoc)
* @see seventh.ai.AISystem#init(seventh.game.Game)
*/
@Override
public void init(final GameInfo game) {
this.game = game;
this.random = new Randomizer(game.getRandom());
this.config = new AIConfig(game.getConfig().getConfig());
this.zones = new Zones(game);
this.stats = new Stats(game, this.zones);
initScriptingEngine();
this.aiCommands = new AICommands(this);
this.world = new World(config, game, zones, goals, random);
GameType gameType = game.getGameType();
switch(gameType.getType()) {
case CTF:
this.alliedAIStrategy = new CaptureTheFlagTeamStrategy(this, gameType.getAlliedTeam());
this.axisAIStrategy = new CaptureTheFlagTeamStrategy(this, gameType.getAxisTeam());
break;
case OBJ:
this.alliedAIStrategy = new ObjectiveTeamStrategy(this, gameType.getAlliedTeam());
this.axisAIStrategy = new ObjectiveTeamStrategy(this, gameType.getAxisTeam());
break;
case CMD:
this.alliedAIStrategy = new CommanderTeamStrategy((CommanderGameType)gameType, this, gameType.getAlliedTeam());
this.axisAIStrategy = new CommanderTeamStrategy((CommanderGameType)gameType, this, gameType.getAxisTeam());
break;
case TDM:
default:
this.alliedAIStrategy = new TDMTeamStrategy(this, gameType.getAlliedTeam());
this.axisAIStrategy = new TDMTeamStrategy(this, gameType.getAxisTeam());
break;
}
PlayerInfos players = game.getPlayerInfos();
players.forEachPlayerInfo(new PlayerInfoIterator() {
@Override
public void onPlayerInfo(PlayerInfo player) {
if(player.isBot()) {
brains[player.getId()] = new Brain(getPersonalityTraitsFor(player), getStrategyFor(player), world, player);
}
}
});
this.watcher.startWatching();
}
/**
* Initialize the scripting engine
*/
private void initScriptingEngine() {
try {
AILeolaLibrary aiLib = new AILeolaLibrary(this);
this.runtime.loadLibrary(aiLib, "ai");
this.runtime.eval(new File("./assets/ai/goals.leola"));
this.goals = aiLib.getActionFactory();
}
catch(Exception e) {
Cons.println("Unable to load the Leola runtime : " + e);
}
}
/**
* @param player
* @return the team strategy for a given player
*/
private TeamStrategy getStrategyFor(PlayerInfo player) {
if(Team.ALLIED_TEAM_ID == player.getTeamId()) {
return this.alliedAIStrategy;
}
else if(Team.AXIS_TEAM_ID == player.getTeamId()) {
return this.axisAIStrategy;
}
return this.alliedAIStrategy;
}
private PersonalityTraits getPersonalityTraitsFor(PlayerInfo player) {
PersonalityTraits traits = null;
if(player!=null) {
traits = this.personalities.get(player.getName().toLowerCase());
if(traits==null) {
traits = this.personalities.get("default");
}
}
return traits==null ? defaultPersonality : traits;
}
/**
* @return the config
*/
@Override
public AIConfig getConfig() {
return config;
}
/**
* @return the runtime
*/
public Leola getRuntime() {
return runtime;
}
/**
* @return the random
*/
@Override
public Randomizer getRandomizer() {
return random;
}
/**
* @return the zones
*/
public Zones getZones() {
return zones;
}
/**
* @return the stats
*/
public Stats getStats() {
return stats;
}
/**
* @return the game
*/
public GameInfo getGame() {
return game;
}
/**
* @return the goals
*/
public Actions getGoals() {
return goals;
}
/**
* @return the world
*/
public World getWorld() {
return world;
}
/* (non-Javadoc)
* @see seventh.ai.AISystem#destroy()
*/
@Override
public void destroy() {
this.watcher.stopWatching();
for(int i = 0; i < this.brains.length; i++) {
this.brains[i] = null;
}
}
/* (non-Javadoc)
* @see seventh.ai.AISystem#playerJoined(seventh.game.Player)
*/
@Override
public void playerJoined(PlayerInfo player) {
if(player.isBot()) {
this.brains[player.getId()] = new Brain(getPersonalityTraitsFor(player), getStrategyFor(player), world, player);
}
}
/* (non-Javadoc)
* @see seventh.ai.AISystem#playerLeft(seventh.game.Player)
*/
@Override
public void playerLeft(PlayerInfo player) {
this.brains[player.getId()] = null;
}
/* (non-Javadoc)
* @see seventh.ai.AISystem#playerSpawned(seventh.game.Player)
*/
@Override
public void playerSpawned(PlayerInfo player) {
TeamStrategy teamStrategy = getStrategyFor(player);
Brain brain = getBrain(player);
if(brain != null) {
brain.spawned(teamStrategy);
}
if(teamStrategy != null) {
teamStrategy.playerSpawned(player);
}
}
/* (non-Javadoc)
* @see seventh.ai.AISystem#playerKilled(seventh.game.Player)
*/
@Override
public void playerKilled(PlayerInfo player) {
Brain brain = getBrain(player);
if(brain != null) {
brain.killed();
}
TeamStrategy teamStrategy = getStrategyFor(player);
if(teamStrategy != null) {
teamStrategy.playerKilled(player);
}
}
/* (non-Javadoc)
* @see seventh.shared.Updatable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
this.stats.update(timeStep);
for(int i = 0; i < brains.length; i++) {
Brain brain = brains[i];
if(brain != null) {
brain.update(timeStep);
}
}
this.alliedAIStrategy.update(timeStep, game);
this.axisAIStrategy.update(timeStep, game);
//debugDraw();
//debugDrawZones();
}
/**
* Draws the {@link Zones}
*/
@SuppressWarnings("unused")
private void debugDrawZones() {
Zone[] zones = this.stats.getTop5DeadliesZones();
for(int i = 0; i < zones.length; i++) {
Zone z = zones[i];
if(z!=null) {
Rectangle bounds = z.getBounds();
DebugDraw.drawStringRelative(z.getId()+"", bounds.x, bounds.y, 0xff00ffff);
DebugDraw.fillRectRelative(bounds.x, bounds.y, bounds.width, bounds.height, 0x1fff00ff);
DebugDraw.drawString(i + ":" + z.getId()+"", 10, 40 + (i*20), 0xff00ffff);
}
}
/*
Zone[][] zs = zones.getZones();
for(int y = 0; y < zs.length; y++) {
for(int x = 0; x < zs[y].length; x++) {
Zone z = zs[y][x];
Rectangle bounds = z.getBounds();
DebugDraw.drawStringRelative(z.getId()+"", bounds.x, bounds.y, 0xff00ffff);
DebugDraw.drawRectRelative(bounds.x, bounds.y, bounds.width, bounds.height, 0xffff00ff);
}
}
for(int i = 0; i < brains.length; i++) {
Brain brain = brains[i];
if(brain != null) {
if(brain.getPlayer().isAlive()) {
World world = brain.getWorld();
Zone currentZone = zones.getZone(brain.getEntityOwner().getCenterPos());
final int range = 88;
Zone[] adjacent = world.findAdjacentZones(currentZone, range);
int cx = currentZone.getBounds().x + currentZone.getBounds().width / 2;
int cy = currentZone.getBounds().y + currentZone.getBounds().height / 2;
DebugDraw.drawLineRelative(new Vector2f(cx, cy), new Vector2f(cx , cy+range), 0x5ffff0ff);
DebugDraw.drawLineRelative(new Vector2f(cx, cy), new Vector2f(cx , cy-range), 0x5ffff0ff);
DebugDraw.drawLineRelative(new Vector2f(cx, cy), new Vector2f(cx+range, cy ), 0x5ffff0ff);
DebugDraw.drawLineRelative(new Vector2f(cx, cy), new Vector2f(cx-range, cy ), 0x5ffff0ff);
//Zone[] adjacent = zones.getAdjacentZones(zones.getZone(brain.getEntityOwner().getCenterPos()));
for(Zone zone : adjacent) {
if(zone != null) {
Rectangle bounds = zone.getBounds();
DebugDraw.fillRectRelative(bounds.x, bounds.y, bounds.width, bounds.height, 0x5ffff0ff);
}
}
}
}
}*/
}
/**
* Helpful debug for AI
*/
@SuppressWarnings("unused")
private void debugDraw() {
int y = 100;
int x = 20;
final int yOffset = 20;
int color = 0xff00ff00;
final String message = "%-16s %-3s %-10s";
DebugDraw.drawString(String.format(message, "Name", "ID", "State"), x, y, color);
DebugDraw.drawString("====================================", x, y += yOffset, color);
for(int i = 0; i < brains.length; i++) {
Brain brain = brains[i];
if(brain != null) {
String state = "DEAD";
if(brain.getPlayer().isAlive()) {
state = brain.getEntityOwner().getCurrentState().name();
}
String text = String.format(message, brain.getPlayer().getName(), brain.getPlayer().getId(), state);
DebugDraw.drawString(text, x, y += yOffset, color);
}
}
}
/* (non-Javadoc)
* @see seventh.ai.AISystem#startOfRound(seventh.game.Game)
*/
@Override
public void startOfRound(GameInfo game) {
zones.calculateBombTargets();
alliedAIStrategy.startOfRound(game);
axisAIStrategy.startOfRound(game);
}
/* (non-Javadoc)
* @see seventh.ai.AISystem#endOfRound(seventh.game.Game)
*/
@Override
public void endOfRound(GameInfo game) {
alliedAIStrategy.endOfRound(game);
axisAIStrategy.endOfRound(game);
}
/**
* @param playerId
* @return the {@link Brain} from the supplied player Id.
*/
public Brain getBrain(int playerId) {
if(playerId >= 0 && playerId < brains.length) {
return brains[playerId];
}
return null;
}
/**
* @param player
* @return the {@link Brain} from the supplied player
*/
public Brain getBrain(PlayerInfo player) {
if(player != null && player.isBot()) {
return getBrain(player.getId());
}
return null;
}
/* (non-Javadoc)
* @see seventh.ai.AISystem#receiveAICommand(seventh.game.PlayerInfo, seventh.ai.basic.commands.AICommand)
*/
@Override
public void receiveAICommand(PlayerInfo forBot, AICommand command) {
if(forBot.isBot() && forBot.isAlive()) {
Brain brain = getBrain(forBot);
if(brain != null) {
Action action = this.aiCommands.compile(brain, command);
if(action != null) {
brain.getCommunicator().makeTopPriority(action);
}
}
}
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
me.add("brains", this.brains)
.add("stats", this.stats)
.add("allied_strategy", this.alliedAIStrategy)
.add("axis_strategy", this.axisAIStrategy);
return me;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 18,626 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Zones.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/Zones.java | /*
* see license.txt
*/
package seventh.ai.basic;
import static seventh.shared.SeventhConstants.PLAYER_HEIGHT;
import static seventh.shared.SeventhConstants.PLAYER_WIDTH;
import java.util.ArrayList;
import java.util.List;
import seventh.game.GameInfo;
import seventh.game.entities.BombTarget;
import seventh.map.Map;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
/**
* A container for all the {@link Zone}s in a map
*
* @author Tony
*
*/
public class Zones {
private Zone[][] zones;
private final int zoneWidth, zoneHeight;
private final int mapWidth, mapHeight;
private final int numberOfCols, numberOfRows;
private final int numberOfZones;
private List<Zone> bombTargetZones;
private GameInfo game;
/**
* @param game
*/
public Zones(GameInfo game) {
this.game = game;
bombTargetZones = new ArrayList<>();
final int ZONE_SIZE_IN_TILES = 12;
Map map = game.getMap();
mapWidth = map.getMapWidth();
mapHeight = map.getMapHeight();
zoneWidth = mapWidth / ZONE_SIZE_IN_TILES;
zoneHeight = mapHeight / ZONE_SIZE_IN_TILES;
numberOfCols = mapWidth / zoneWidth;
numberOfRows = mapHeight / zoneHeight;
numberOfZones = numberOfCols * numberOfRows;
zones = new Zone[numberOfRows][numberOfCols];
Rectangle entityBounds = new Rectangle(PLAYER_WIDTH, PLAYER_HEIGHT);
int id = 0;
for(int y = 0; y < numberOfRows; y++) {
for(int x = 0; x < numberOfCols; x++) {
Rectangle bounds = new Rectangle(x * zoneWidth, y * zoneHeight, zoneWidth, zoneHeight);
boolean isHabitable = hasHabitableLocation(entityBounds, bounds, map);
zones[y][x] = new Zone(id++, bounds, isHabitable);
}
}
}
/**
* Determines if a player could fit somewhere inside this zone
*
* @param entityBounds
* @param zoneBounds
* @param map
* @return true if a player could fit in this zone
*/
private boolean hasHabitableLocation(Rectangle entityBounds, Rectangle zoneBounds, Map map) {
int x = zoneBounds.x;
int y = zoneBounds.y;
entityBounds.setLocation(x, y);
int maxX = zoneBounds.x+zoneBounds.width;
int maxY = zoneBounds.y+zoneBounds.height;
boolean hitMaxX = false;
boolean hitMaxY = false;
while (map.rectCollides(entityBounds)) {
if(x+entityBounds.width <= maxX) {
x += entityBounds.width;
}
else {
hitMaxX = true;
}
if(y+entityBounds.height <= maxY) {
y += entityBounds.height;
}
else {
hitMaxY = true;
}
entityBounds.setLocation(x, y);
if(hitMaxX && hitMaxY) {
return false;
}
}
return true;
}
/**
* Determines which Zone's the {@link BombTarget}s
* fall into
*/
public void calculateBombTargets() {
for(int y = 0; y < numberOfRows; y++) {
for(int x = 0; x < numberOfCols; x++) {
zones[y][x].clearTargets();
}
}
List<BombTarget> targets = game.getBombTargets();
for(BombTarget target : targets) {
Zone zone = getZone(target.getCenterPos());
if(zone != null && zone.isHabitable()) {
zone.addTarget(target);
bombTargetZones.add(zone);
}
}
}
/**
* @return the zones
*/
public Zone[][] getZones() {
return zones;
}
/**
* @return the number of zones
*/
public int getNumberOfZones() {
return this.numberOfZones;
}
/**
* @return the bombTargetZones
*/
public List<Zone> getBombTargetZones() {
return bombTargetZones;
}
/**
* @param pos
* @return a {@link Zone} at a specified location
*/
public Zone getZone(Vector2f pos) {
return getZone( (int)pos.x, (int)pos.y);
}
/**
* @param x
* @param y
* @return a {@link Zone} at a specified location
*/
public Zone getZone(int x, int y) {
if(x<0 || y<0 || x>mapWidth || y>mapHeight) {
return null;
}
int offsetX = 0;//(x % zoneWidth);
int offsetY = 0;//(y % zoneHeight);
int xIndex = (x + offsetX) / zoneWidth;
int yIndex = (y + offsetY) / zoneHeight;
if (xIndex > zones[0].length-1 || yIndex > zones.length-1) {
return null;
}
return zones[yIndex][xIndex];
}
/**
* Finds the adjacent zones
*
* @param zone
* @return the adjacent zones
*/
public Zone[] getAdjacentZones(Zone zone) {
return getAdjacentZones(zone.getBounds().x, zone.getBounds().y);
}
/**
* Finds the adjacent nodes
*
* @param x
* @param y
* @return the adjacent nodes
*/
public Zone[] getAdjacentZones(int x, int y) {
if(x<0 || y<0 || x>mapWidth || y>mapHeight) {
return null;
}
int xIndex = x / zoneWidth;
int yIndex = y / zoneHeight;
if (xIndex > zones[0].length-1 || yIndex > zones.length-1) {
return null;
}
Zone[] adjacentZones = new Zone[8];
adjacentZones[0] = getZoneByIndex(xIndex, yIndex+1);
adjacentZones[1] = getZoneByIndex(xIndex+1, yIndex+1);
adjacentZones[2] = getZoneByIndex(xIndex+1, yIndex);
adjacentZones[3] = getZoneByIndex(xIndex+1, yIndex-1);
adjacentZones[4] = getZoneByIndex(xIndex, yIndex-1);
adjacentZones[5] = getZoneByIndex(xIndex-1, yIndex-1);
adjacentZones[6] = getZoneByIndex(xIndex-1, yIndex);
adjacentZones[7] = getZoneByIndex(xIndex-1, yIndex+1);
return adjacentZones;
}
private Zone getZoneByIndex(int x, int y) {
if(y >= zones.length || x >= zones[0].length) {
return null;
}
if(x < 0 || y < 0) {
return null;
}
return zones[y][x];
}
/**
* @param id
* @return the {@link Zone}
*/
// public Zone getZoneById(int id) {
// // TODO
//// int y = (id / this.numberOfRows) - 1;
//// int x = (id-y) % this.numberOfCols;
//// return this.zones[y][x];
// return null;
// }
}
| 7,010 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Communicator.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/Communicator.java | /*
* see license.txt
*/
package seventh.ai.basic;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import seventh.ai.basic.actions.Action;
import seventh.ai.basic.teamstrategy.TeamStrategy;
import seventh.game.Player;
import seventh.game.entities.PlayerEntity;
import seventh.math.Rectangle;
/**
* Allows for giving an Agent to be given orders/Goals from another
* source (either a {@link TeamStrategy}, remote command, another agent, etc)
*
* @author Tony
*
*/
public class Communicator {
private Queue<Action> commands;
private World world;
private Rectangle broadcastBounds;
/**
* @param world
*/
public Communicator(World world) {
this.world = world;
this.commands = new ConcurrentLinkedQueue<Action>();
this.broadcastBounds = new Rectangle(1000, 1000);
}
/**
* Resets this {@link Communicator}
*
* @param brain
*/
public void reset(Brain brain) {
this.commands.clear();
}
/**
* @return true if there are pending {@link Action}s to be processed
*/
public boolean hasPendingCommands() {
return !this.commands.isEmpty();
}
/**
* @return peeks at the next action
*/
public Action peek() {
Action cmd = commands.peek();
return cmd;
}
/**
* Receives any pending {@link Action}s.
*
*/
public Action poll() {
Action cmd = commands.poll();
return cmd;
}
/**
* Post a command to this bot
* @param cmd
*/
public void post(Action cmd) {
this.commands.add(cmd);
}
/**
* Removes all previous posted {@link Action}s and makes the supplied
* Action the only {@link Action}
* @param cmd
*/
public void makeTopPriority(Action cmd) {
this.commands.clear();
this.commands.add(cmd);
}
/**
* Broadcasts an action for another entity to pick up
*
* @param cmd
*/
public void broadcastAction(Brain brain, Action cmd) {
if(brain.getPlayer().isAlive()) {
broadcastBounds.centerAround(brain.getEntityOwner().getCenterPos());
List<Player> teammates = world.getTeammates(brain);
for(int i = 0; i < teammates.size(); i++) {
Player player = teammates.get(i);
if(player.isBot() && player.isAlive()) {
PlayerEntity ent = player.getEntity();
if(broadcastBounds.intersects(ent.getBounds())) {
Brain other = world.getBrain(player.getId());
other.getCommunicator().post(cmd);
}
}
}
}
}
}
| 2,860 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AILeolaLibrary.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/AILeolaLibrary.java | /*
* see license.txt
*/
package seventh.ai.basic;
import leola.vm.Leola;
import leola.vm.exceptions.LeolaRuntimeException;
import leola.vm.lib.LeolaIgnore;
import leola.vm.lib.LeolaLibrary;
import leola.vm.types.LeoNamespace;
import seventh.ai.AISystem;
import seventh.ai.basic.actions.Actions;
/**
* AI Library, which includes useful AI functions for scripting.
*
* @see Actions
* @author Tony
*
*/
public class AILeolaLibrary implements LeolaLibrary {
private Leola runtime;
private Actions actions;
private AISystem aiSystem;
/**
* @param aiSystem
*/
public AILeolaLibrary(AISystem aiSystem) {
this.aiSystem = aiSystem;
}
/* (non-Javadoc)
* @see leola.vm.lib.LeolaLibrary#init(leola.vm.Leola, leola.vm.types.LeoNamespace)
*/
@LeolaIgnore
@Override
public void init(Leola leola, LeoNamespace namespace) throws LeolaRuntimeException {
this.runtime = leola;
this.runtime.putIntoNamespace(this, namespace);
this.actions = new Actions(this.aiSystem, this.runtime);
this.runtime.putIntoNamespace(this.actions, namespace);
}
/**
* @return the {@link Actions} factory
*/
@LeolaIgnore
public Actions getActionFactory() {
return actions;
}
}
| 1,327 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ZoneStats.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/ZoneStats.java | /*
* see license.txt
*/
package seventh.ai.basic;
/**
* Some useful statistics about a zone. This helps the AI
* make some decisions on strategy.
*
* @author Tony
*
*/
public class ZoneStats {
private int numberOfAxisDeaths;
private int numberOfAxisKills;
private int numberOfAlliedDeaths;
private int numberOfAlliedKills;
private Zone zone;
/**
*/
public ZoneStats(Zone zone) {
this.zone = zone;
}
/**
* @return the {@link Zone}
*/
public Zone getZone() {
return zone;
}
/**
* @return the total number of deaths in this Zone
*/
public int getTotalKilled() {
return this.numberOfAlliedDeaths + this.numberOfAxisDeaths;
}
public void addAxisDeath() {
numberOfAxisDeaths++;
}
public void addAxisKill() {
numberOfAxisKills++;
}
/**
* @return the numberOfDeaths
*/
public int getNumberOfAxisDeaths() {
return numberOfAxisDeaths;
}
/**
* @return the numberOfKills
*/
public int getNumberOfAxisKills() {
return numberOfAxisKills;
}
public void addAlliedDeath() {
numberOfAlliedDeaths++;
}
public void addAlliedKill() {
numberOfAlliedKills++;
}
/**
* @return the numberOfDeaths
*/
public int getNumberOfAlliedDeaths() {
return numberOfAlliedDeaths;
}
/**
* @return the numberOfKills
*/
public int getNumberOfAlliedKills() {
return numberOfAlliedKills;
}
}
| 1,626 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
TargetingSystem.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/TargetingSystem.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.ai.basic.memory.SightMemory.SightMemoryRecord;
import seventh.game.entities.Entity;
import seventh.game.entities.PlayerEntity;
import seventh.game.entities.Entity.Type;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
import seventh.shared.Timer;
import seventh.shared.Updatable;
/**
* Responsible for fixating on the most appropriate target (enemy).
*
* @author Tony
*
*/
public class TargetingSystem implements Updatable {
private Brain brain;
private PlayerEntity currentTarget;
private Timer checkTimer;
private Timer reactionTimeTimer;
/**
*
*/
public TargetingSystem(Brain brain) {
this.brain = brain;
AIConfig config = brain.getConfig();
this.checkTimer = new Timer(true, config.getTriggeringSystemPollTime());
this.checkTimer.start();
this.reactionTimeTimer = new Timer(false, config.getReactionTime());
}
public void reset(Brain brain) {
this.clearTarget();
}
/* (non-Javadoc)
* @see seventh.shared.Updatable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
checkTimer.update(timeStep);
reactionTimeTimer.update(timeStep);
if(checkTimer.isTime()) {
Sensors sensors = brain.getSensors();
Entity recentAttacker = sensors.getFeelSensor().getMostRecentAttacker();
PlayerEntity closestEnemyInSight = sensors.getSightSensor().getClosestEnemy();
// SoundEmittedEvent closestSound = sensors.getSoundSensor().getClosestSound();
PlayerEntity newTarget = this.currentTarget;
this.currentTarget = null;
/* if we are being attacked, this is fairly high priority */
if(recentAttacker != null && recentAttacker.getType().equals(Type.PLAYER)) {
if(closestEnemyInSight != null) {
/* if the closest in sight and attacker are the same, then
* the choice is obvious
*/
if(closestEnemyInSight == recentAttacker) {
this.currentTarget = closestEnemyInSight;
}
else {
Vector2f botPos = this.brain.getEntityOwner().getCenterPos();
float attackerDis = Vector2f.Vector2fDistanceSq(botPos, recentAttacker.getCenterPos());
float sightDis = Vector2f.Vector2fDistanceSq(botPos, closestEnemyInSight.getCenterPos());
if(sightDis < attackerDis) {
this.currentTarget = closestEnemyInSight;
}
else {
this.currentTarget = (PlayerEntity)recentAttacker;
}
}
}
else {
this.currentTarget = (PlayerEntity)recentAttacker;
}
}
else {
if(closestEnemyInSight != null) {
this.currentTarget = closestEnemyInSight;
}
}
if(newTarget != this.currentTarget) {
this.reactionTimeTimer.reset();
}
}
/*
* If we have a target, look at them
*/
stareAtTarget();
}
/**
* Stare at the current target, if there is one
*/
public void stareAtTarget() {
if(hasTarget()) {
brain.getMotion().stareAtEntity(getCurrentTarget());
}
else {
brain.getMotion().scanArea();
}
}
/**
* If there is a target
* @return
*/
public boolean hasTarget() {
return this.currentTarget != null && this.currentTarget.isAlive() && this.reactionTimeTimer.isTime();
}
/**
* Clears the target
*/
public void clearTarget() {
this.currentTarget = null;
}
/**
* @return the currentTarget
*/
public PlayerEntity getCurrentTarget() {
return currentTarget;
}
/**
* The last remembered position
*
* @return
*/
public Vector2f getLastRemeberedPosition() {
if(hasTarget()) {
SightMemoryRecord record = this.brain.getSensors().getSightSensor().getMemoryRecordFor(currentTarget);
if(record.isValid()) {
return record.getLastSeenAt();
}
}
return null;
}
/**
* @param target
* @return true if the current target position is in the line of fire
*/
public boolean targetInLineOfFire(Vector2f target) {
PlayerEntity bot = brain.getEntityOwner();
float distanceSq = bot.distanceFromSq(target);
if(distanceSq <= bot.getCurrentWeaponDistanceSq()) {
return brain.getWorld().inLineOfFire(bot, target);
}
return false;
}
/**
* @return true if the current target is in the line of fire
*/
public boolean currentTargetInLineOfFire() {
if(hasTarget()) {
PlayerEntity bot = brain.getEntityOwner();
float distanceSq = bot.distanceFromSq(currentTarget);
if(distanceSq <= bot.getCurrentWeaponDistanceSq()) {
return brain.getWorld().inLineOfFire(bot, currentTarget);
}
}
return false;
}
}
| 5,809 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SoundSensor.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/SoundSensor.java | /*
* see license.txt
*/
package seventh.ai.basic;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import seventh.ai.basic.memory.SoundMemory;
import seventh.ai.basic.memory.SoundMemory.SoundMemoryRecord;
import seventh.game.SoundEventPool;
import seventh.game.Team;
import seventh.game.entities.PlayerEntity;
import seventh.game.events.SoundEmittedEvent;
import seventh.math.Vector2f;
import seventh.shared.SoundType;
import seventh.shared.TimeStep;
import seventh.shared.Timer;
/**
* Listens for sounds
*
* @author Tony
*
*/
public class SoundSensor implements Sensor {
/**
* Less important sounds
*/
private static final EnumSet<SoundType> lessImportant
= EnumSet.of(SoundType.IMPACT_DEFAULT
, SoundType.IMPACT_FOLIAGE
, SoundType.IMPACT_METAL
, SoundType.IMPACT_WOOD);
private SoundMemory memory;
private PlayerEntity entity;
private World world;
private Timer updateEar;
private List<SoundEmittedEvent> sounds;
/**
* @param brain
*/
public SoundSensor(Brain brain) {
this.memory = brain.getMemory().getSoundMemory();
this.entity = brain.getEntityOwner();
this.world = brain.getWorld();
this.updateEar = new Timer(true, brain.getConfig().getSoundPollTime());
this.updateEar.start();
this.sounds = new ArrayList<SoundEmittedEvent>();
}
/**
* Gets the closest most interesting sound
* @return
*/
public SoundEmittedEvent getClosestSound() {
Team myTeam = entity.getTeam();
SoundMemoryRecord[] sounds = memory.getSoundRecords();
SoundEmittedEvent closestSound = null;
for(int i = 0; i < sounds.length; i++) {
if(sounds[i].isValid()) {
SoundEmittedEvent sound = sounds[i].getSound();
long id = sound.getId();
/* ignore your own sounds */
if(entity.getId() == id) {
continue;
}
/* ignore your friendly sounds (this is a cheat, but what'evs) */
PlayerEntity personMakingSound = world.getPlayerById(id);
if(personMakingSound != null && personMakingSound.getTeam().equals(myTeam)) {
continue;
}
Vector2f soundPos = sound.getPos();
/* make the first sound the closest */
if(closestSound == null) {
closestSound = sound;
}
else {
/* now lets check and see if there is a higher priority sound (such as foot steps, gun fire, etc.) */
if(lessImportant.contains(closestSound.getSoundType()) && !lessImportant.contains(sound.getSoundType())) {
closestSound = sound;
}
else {
/* short of there being a higher priority sound, check the distance */
if(closestSound.getPos().lengthSquared() > soundPos.lengthSquared()) {
closestSound = sound;
}
}
}
}
}
return closestSound;
}
/* (non-Javadoc)
* @see seventh.ai.Sensor#reset(seventh.ai.Brain)
*/
@Override
public void reset(Brain brain) {
this.sounds.clear();
this.entity = brain.getEntityOwner();
}
/* (non-Javadoc)
* @see palisma.ai.Sensor#update(leola.live.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
this.updateEar.update(timeStep);
if(this.updateEar.isTime()) {
listen(timeStep);
}
}
/**
* Listen for sounds
*/
private void listen(TimeStep timeStep) {
this.sounds.clear();
SoundEventPool emittedSounds = world.getSoundEvents();
if(emittedSounds.hasSounds()) {
this.entity.getHeardSounds(emittedSounds, this.sounds);
this.memory.hear(timeStep, sounds);
}
}
}
| 4,481 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Stats.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/Stats.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.game.GameInfo;
import seventh.game.Player;
import seventh.game.PlayerInfo;
import seventh.game.PlayerInfos;
import seventh.game.Team;
import seventh.game.events.BombExplodedEvent;
import seventh.game.events.BombExplodedListener;
import seventh.game.events.PlayerKilledEvent;
import seventh.game.events.PlayerKilledListener;
import seventh.game.events.PlayerSpawnedEvent;
import seventh.game.events.PlayerSpawnedListener;
import seventh.shared.Debugable;
import seventh.shared.TimeStep;
import seventh.shared.Updatable;
/**
* Keeps interesting statistics about the game
*
* @author Tony
*
*/
public class Stats implements PlayerKilledListener, PlayerSpawnedListener, BombExplodedListener, Updatable, Debugable {
private Zones zones;
private PlayerInfos players;
private int numberOfAlliesAlive;
private int numberOfAxisAlive;
private int numberOfBombsExploded;
private int totalNumberOfBombTargets;
private Zone[] topFiveDeadliest;
/**
* @param game
* @param zones
*/
public Stats(GameInfo game, Zones zones) {
this.players = game.getPlayerInfos();
this.zones = zones;
this.totalNumberOfBombTargets = game.getBombTargets().size();
this.topFiveDeadliest = new Zone[5];
game.getDispatcher().addEventListener(PlayerKilledEvent.class, this);
game.getDispatcher().addEventListener(PlayerSpawnedEvent.class, this);
}
/* (non-Javadoc)
* @see seventh.shared.Updatable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
calculateTop5DeadliesZones();
}
/**
* @return the Zone which contains the most amount of deaths
*/
public Zone getDeadliesZone() {
// Zone deadliest = null;
// int killCount = 0;
//
// Zone[][] zs = this.zones.getZones();
// for(int y = 0; y < zs.length; y++) {
// for(int x = 0; x < zs[y].length; x++) {
// Zone zone = zs[y][x];
// if(zone.isHabitable()) {
// ZoneStats s = zone.getStats();
//
// int totalKilled = s.getTotalKilled();
// if(deadliest == null || killCount < totalKilled) {
// deadliest = s.getZone();
// killCount = totalKilled;
// }
// }
// }
// }
//
// return deadliest;
if(this.topFiveDeadliest[0]==null) {
return this.zones.getZone(0, 0);
}
return this.topFiveDeadliest[0];
}
private boolean isAlreadyInTop5(Zone zone) {
for(int j = 0; j < this.topFiveDeadliest.length; j++) {
if(this.topFiveDeadliest[j]!=null&&this.topFiveDeadliest[j].getId()==zone.getId()) {
return true;
}
}
return false;
}
public Zone[] getTop5DeadliesZones() {
return this.topFiveDeadliest;
}
private void calculateTop5DeadliesZones() {
Zone[][] zs = this.zones.getZones();
for(int y = 0; y < zs.length; y++) {
for(int x = 0; x < zs[y].length; x++) {
Zone zone = zs[y][x];
if(zone.isHabitable() && !isAlreadyInTop5(zone)) {
ZoneStats s = zone.getStats();
int totalKilled = s.getTotalKilled();
int positionToSet = -1;
//for(int i = 0; i < this.topFiveDeadliest.length; i++) {
for(int i = this.topFiveDeadliest.length-1; i >= 0; i--) {
if(this.topFiveDeadliest[i]==null) {
positionToSet = i;
continue;
}
if(this.topFiveDeadliest[i].getStats().getTotalKilled() < totalKilled) {
positionToSet = i;
}
else {
break;
}
}
if(positionToSet>-1) {
if(positionToSet<4) {
for(int i = this.topFiveDeadliest.length-1; i > positionToSet; i--) {
Zone tmp = this.topFiveDeadliest[i-1];
this.topFiveDeadliest[i] = tmp;
}
}
this.topFiveDeadliest[positionToSet] = zone;
}
}
}
}
}
/*
* (non-Javadoc)
* @see seventh.game.events.BombExplodedListener#onBombExplodedEvent(seventh.game.events.BombExplodedEvent)
*/
@Override
public void onBombExplodedEvent(BombExplodedEvent event) {
this.numberOfBombsExploded++;
}
/**
* @return the totalNumberOfBombTargets
*/
public int getTotalNumberOfBombTargets() {
return totalNumberOfBombTargets;
}
/**
* @return the numberOfBombsExploded
*/
public int getNumberOfBombsExploded() {
return numberOfBombsExploded;
}
/**
* @return the number of Allied players that are alive
*/
public int getNumberOfAlliesAlive() {
return numberOfAlliesAlive;
}
/**
* @return the number of Axis players that are alive
*/
public int getNumberOfAxisAlive() {
return numberOfAxisAlive;
}
/*
* (non-Javadoc)
* @see seventh.game.events.PlayerSpawnedListener#onPlayerSpawned(seventh.game.events.PlayerSpawnedEvent)
*/
@Override
public void onPlayerSpawned(PlayerSpawnedEvent event) {
switch(event.getPlayer().getTeamId()) {
case Team.ALLIED_TEAM_ID:
numberOfAlliesAlive++;
break;
case Team.AXIS_TEAM_ID:
numberOfAxisAlive++;
break;
}
}
/* (non-Javadoc)
* @see seventh.game.events.PlayerKilledListener#onPlayerKilled(seventh.game.events.PlayerKilledEvent)
*/
@Override
public void onPlayerKilled(PlayerKilledEvent event) {
Zone zone = zones.getZone(event.getPos());
if(zone != null) {
ZoneStats stats = zone.getStats();
Player killed = event.getPlayer();
if(killed.getTeamId()==Team.ALLIED_TEAM_ID) {
stats.addAlliedDeath();
}
else {
stats.addAxisDeath();
}
PlayerInfo killer = players.getPlayerInfo(event.getKillerId());
if (killer != null) {
if(killer.getTeamId()==Team.ALLIED_TEAM_ID) {
stats.addAlliedKill();
}
else {
stats.addAxisKill();
}
}
}
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
// TODO
return me;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 7,998 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PersonalityTraits.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/PersonalityTraits.java | /*
* see license.txt
*/
package seventh.ai.basic;
/**
* Personality traits of a bot player
*
* @author Tony
*
*/
public class PersonalityTraits {
/**
* Max value to offset aiming
*/
private static final double MAX_SLOP = (Math.PI/8);
public double aggressiveness;
public double obedience;
public double accuracy;
public double curiosity;
public float calculateAccuracy(Brain brain) {
double slop = (1.0-brain.getRandomRangeMax(accuracy)) * (MAX_SLOP);
slop *= brain.getWorld().getRandom().nextBoolean() ? -1 : 1;
return (float)slop;
}
}
| 625 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AttackDirection.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/AttackDirection.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.math.Vector2f;
/**
* A direction that an enemy can attack from
*
* @author Tony
*
*/
public class AttackDirection {
private Vector2f direction;
/**
*
*/
public AttackDirection(Vector2f direction) {
this.direction = direction;
}
/**
* @return the direction
*/
public Vector2f getDirection() {
return direction;
}
}
| 467 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SightSensor.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/SightSensor.java | /*
* see license.txt
*/
package seventh.ai.basic;
import java.util.ArrayList;
import java.util.List;
import seventh.ai.basic.memory.SightMemory;
import seventh.ai.basic.memory.SightMemory.SightMemoryRecord;
import seventh.game.Team;
import seventh.game.entities.Entity;
import seventh.game.entities.PlayerEntity;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
import seventh.shared.Timer;
/**
* The bots vision
*
* @author Tony
*
*/
public class SightSensor implements Sensor {
private SightMemory memory;
private PlayerEntity entity;
private World world;
private Timer updateSight;
private List<PlayerEntity> entitiesInView;
/**
* @param width
* @param height
*/
public SightSensor(Brain brain) {
this.memory = brain.getMemory().getSightMemory();
this.entity = brain.getEntityOwner();
this.world = brain.getWorld();
this.updateSight = new Timer(true, brain.getConfig().getSightPollTime());
this.updateSight.start();
this.entitiesInView = new ArrayList<PlayerEntity>();
}
/**
* The sight records
*
* @return
*/
public SightMemoryRecord[] getSightMemoryRecords() {
return this.memory.getEntityRecords();
}
/**
* Get the closest entity to this bot
* @return the closest entity to this bot
*/
public PlayerEntity getClosestEntity() {
PlayerEntity result = null;
float closestDistance = Float.MAX_VALUE;
Vector2f botPos = this.entity.getCenterPos();
SightMemoryRecord[] records = getSightMemoryRecords();
for(int i = 0; i < records.length; i++) {
if( records[i].isValid()) {
if(result==null) {
result = records[i].getEntity();
}
else {
Vector2f pos = records[i].getEntity().getCenterPos();
float distance = Vector2f.Vector2fDistanceSq(pos, botPos);
if(distance < closestDistance) {
result = records[i].getEntity();
closestDistance = distance;
}
}
}
}
return result;
}
/**
* Get the closest enemy to this bot
* @return the closest enemy to this bot
*/
public PlayerEntity getClosestEnemy() {
PlayerEntity result = null;
float closestDistance = Float.MAX_VALUE;
Vector2f botPos = this.entity.getCenterPos();
Team myTeam = this.entity.getTeam();
SightMemoryRecord[] records = getSightMemoryRecords();
for(int i = 0; i < records.length; i++) {
if( records[i].isValid() ) {
PlayerEntity other = records[i].getEntity();
if(other.getTeam().getId() == myTeam.getId()) {
continue;
}
if(result==null) {
result = other;
}
else {
Vector2f pos = other.getCenterPos();
float distance = Vector2f.Vector2fDistanceSq(pos, botPos);
if(distance < closestDistance) {
result = other;
closestDistance = distance;
}
}
}
}
return result;
}
/**
* Get the list of enemies in view
* @param results the resulting list of enemies in the view
* @return the same results object, just convenience
*/
public List<PlayerEntity> getEnemies(List<PlayerEntity> results) {
Team myTeam = entity.getTeam();
SightMemoryRecord[] records = getSightMemoryRecords();
for(int i = 0; i < records.length; i++) {
if( records[i].isValid()) {
PlayerEntity otherPlayer = records[i].getEntity();
Team otherTeam = otherPlayer.getTeam();
if(otherTeam==null || myTeam==null || otherTeam.getId() != myTeam.getId()) {
results.add(otherPlayer);
break;
}
}
}
return results;
}
/**
* The memory record for the entity
*
* @param ent
* @return
*/
public SightMemoryRecord getMemoryRecordFor(Entity ent) {
if(ent != null) {
return getSightMemoryRecords()[ent.getId()];
}
return null;
}
/**
* If the supplied entity was in view (or recently in view)
*
* @param entity
* @return If the supplied entity was in view (or recently in view)
*/
public boolean inView(Entity entity) {
SightMemoryRecord[] records = getSightMemoryRecords();
if(entity != null) {
return records[entity.getId()].isValid();
}
return false;
}
/**
* Last time this {@link Entity} was seen by the bot
*
* @param entity
* @return Last time this {@link Entity} was seen by the bot
*/
public long lastSeen(Entity entity) {
SightMemoryRecord[] records = getSightMemoryRecords();
if(entity != null) {
return records[entity.getId()].getTimeSeen();
}
return -1;
}
/**
* The amount of msec's this {@link Entity} was last seen.
*
* @param entity
* @return The amount of msec's this {@link Entity} was last seen.
*/
public long timeSeenAgo(Entity entity) {
SightMemoryRecord[] records = getSightMemoryRecords();
if(entity != null) {
return records[entity.getId()].getTimeSeenAgo();
}
return -1;
}
/* (non-Javadoc)
* @see seventh.ai.Sensor#reset()
*/
@Override
public void reset(Brain brain) {
this.entitiesInView.clear();
this.entity = brain.getEntityOwner();
this.updateSight.reset();
this.memory.clear();
}
/* (non-Javadoc)
* @see palisma.ai.Sensor#update(leola.live.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
this.updateSight.update(timeStep);
if(this.updateSight.isTime()) {
see(timeStep);
}
}
/**
* Looks for anything interesting in the
* current view port
*/
private void see(TimeStep timeStep) {
/*
* If we should pool the world for visuals, go
* ahead and do so now
*/
if(this.entity != null && this.entity.isAlive()) {
this.entitiesInView.clear();
this.world.getPlayersInLineOfSight(this.entitiesInView, this.entity);
this.memory.see(timeStep, entitiesInView);
}
}
}
| 7,142 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
World.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/World.java | /*
* see license.txt
*/
package seventh.ai.basic;
import java.util.ArrayList;
import java.util.List;
import seventh.ai.basic.actions.Actions;
import seventh.game.GameInfo;
import seventh.game.Player;
import seventh.game.SoundEventPool;
import seventh.game.Team;
import seventh.game.entities.BombTarget;
import seventh.game.entities.Door;
import seventh.game.entities.Entity;
import seventh.game.entities.PlayerEntity;
import seventh.game.entities.vehicles.Vehicle;
import seventh.game.game_types.GameType;
import seventh.game.game_types.obj.ObjectiveGameType;
import seventh.map.Map;
import seventh.map.MapGraph;
import seventh.map.Tile;
import seventh.math.OBB;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
import seventh.shared.Randomizer;
import seventh.shared.SeventhConstants;
/**
* Just a collection of data so that the {@link Brain}s
* can make sense of the world.
*
* @author Tony
*
*/
public class World {
private Entity[] entities;
private PlayerEntity[] players;
private Map map;
private MapGraph<?> graph;
private Randomizer random;
private List<Tile> tiles;
private Rectangle tileBounds;
private GameInfo game;
private SoundEventPool lastFramesSounds;
private List<AttackDirection> attackDirections;
private List<BombTarget> activeBombs;
private Zones zones;
private Actions goals;
private AIConfig config;
/**
* @param entities
* @param map
* @param graph
*/
public World(AIConfig config, GameInfo game, Zones zones, Actions goals, Randomizer randomizer) {
super();
this.config = config;
this.game = game;
this.zones = zones;
this.goals = goals;
this.random = randomizer;
this.entities = game.getEntities();
this.players = game.getPlayerEntities();
this.map = game.getMap();
this.graph = game.getGraph();
this.tiles = new ArrayList<Tile>();
this.tileBounds = new Rectangle();
this.tileBounds.setWidth(map.getTileWidth());
this.tileBounds.setHeight(map.getTileHeight());
this.lastFramesSounds = new SoundEventPool(SeventhConstants.MAX_SOUNDS);
this.attackDirections = new ArrayList<AttackDirection>();
this.activeBombs = new ArrayList<BombTarget>();
}
/**
* @return the config
*/
public AIConfig getConfig() {
return config;
}
/**
* @return the goals
*/
public Actions getGoals() {
return goals;
}
/**
* @return the zones
*/
public Zones getZones() {
return zones;
}
/**
* @return the soundEvents
*/
public SoundEventPool getSoundEvents() {
this.lastFramesSounds.clear();
this.lastFramesSounds.set(this.game.getLastFramesSoundEvents());
this.lastFramesSounds.set(this.game.getSoundEvents());
return this.lastFramesSounds;
}
/**
* @return the entities
*/
public Entity[] getEntities() {
return entities;
}
/**
* Gets a player by id
* @param id
* @return the player
*/
public PlayerEntity getPlayerById(long id) {
int size = this.players.length;
for(int i = 0; i < size; i++) {
PlayerEntity ent = this.players[i];
if(ent!=null) {
if(ent.getId() == id) {
return ent;
}
}
}
return null;
}
/**
* @param playerId
* @return the brain of the player
*/
public Brain getBrain(int playerId) {
DefaultAISystem aiSystem = (DefaultAISystem) game.getAISystem();
return aiSystem.getBrain(playerId);
}
/**
* @return the map
*/
public Map getMap() {
return map;
}
/**
* @return the graph
*/
public MapGraph<?> getGraph() {
return graph;
}
/**
* @return the vehicles
*/
public List<Vehicle> getVehicles() {
return game.getVehicles();
}
/**
* @return the bomb targets
*/
public List<BombTarget> getBombTargets() {
return this.game.getBombTargets();
}
/**
* @return the doors
*/
public List<Door> getDoors() {
return this.game.getDoors();
}
/**
* @return true if there are bomb targets
*/
public boolean hasBombTargets() {
return !this.game.getBombTargets().isEmpty();
}
/**
* @return {@link BombTarget}'s that have an active bomb on it
*/
public List<BombTarget> getBombTargetsWithActiveBombs() {
this.activeBombs.clear();
List<BombTarget> targets = getBombTargets();
for(int i = 0; i < targets.size(); i++) {
BombTarget target = targets.get(i);
if(target.isAlive() && target.bombActive()) {
activeBombs.add(target);
}
}
return this.activeBombs;
}
/**
* @param team
* @return true if the supplied team is on offense
*/
public boolean isOnOffense(Team team) {
GameType gt = game.getGameType();
if(gt instanceof ObjectiveGameType) {
ObjectiveGameType objectiveGameType = (ObjectiveGameType)gt;
Team attacker = objectiveGameType.getAttacker();
if(team != null && attacker != null) {
return attacker.getId() == team.getId();
}
}
return false;
}
/**
* @param brain
* @return the teammates of the supplied bot
*/
public List<Player> getTeammates(Brain brain) {
return brain.getPlayer().getTeam().getPlayers();
}
/**
* Determines if the supplied potentialEnemy is an enemy of the supplied {@link Brain}
*
* @param brain
* @param potentialEnemy
* @return true if potential enemy is an enemy
*/
public boolean isEnemyOf(Brain brain, PlayerEntity potentialEnemy) {
return !brain.getPlayer().getTeam().onTeam(potentialEnemy.getId());
}
/**
* @param entity
* @param target
* @return determines if the enemy is in line of fire
*/
public boolean inLineOfFire(PlayerEntity entity, PlayerEntity target) {
// TODO: account for vehicles
return !map.lineCollides(entity.getCenterPos(), target.getCenterPos(), entity.getHeightMask());
}
/**
* @param entity
* @param target
* @return determines if the enemy is in line of fire
*/
public boolean inLineOfFire(PlayerEntity entity, Vector2f target) {
return !map.lineCollides(entity.getCenterPos(), target, entity.getHeightMask());
}
/**
*
* @param players
* @param entity
* @return
*/
public List<PlayerEntity> getPlayersInLineOfSight(List<PlayerEntity> players, PlayerEntity entity) {
tiles = entity.calculateLineOfSight(tiles);
int size = tiles.size();
for(int i = 0; i < size;i++) {
Tile tile = tiles.get(i);
if(tile!=null && tile.getMask() > 0) {
this.tileBounds.setLocation(tile.getX(), tile.getY());
playersIn(players, tileBounds);
}
}
map.setMask(tiles, 0);
if(!players.isEmpty()) {
players.remove(entity);
}
return players;
}
/**
* @param bounds
* @return the players found in the supplied bounds
*/
public List<PlayerEntity> playersIn(List<PlayerEntity> result, Rectangle bounds) {
/*
* Currently uses brute force
*/
for(int i = 0; i < this.players.length; i++) {
PlayerEntity entity = this.players[i];
if(entity!=null) {
if(bounds.contains(entity.getCenterPos())) {
result.add(entity);
}
}
}
return result;
}
/**
* @param entity
* @return a random position anywhere in the game world
*/
public Vector2f getRandomSpot(Entity entity) {
return game.findFreeRandomSpot(entity);
}
/**
* @param entity
* @param bounds
* @return a random position anywhere in the supplied bounds
*/
public Vector2f getRandomSpot(Entity entity, Rectangle bounds) {
return game.findFreeRandomSpot(entity, bounds);
}
/**
*
* @param entity
* @param x
* @param y
* @param width
* @param height
* @return a random position anywhere in the supplied bounds
*/
public Vector2f getRandomSpot(Entity entity, int x, int y, int width, int height) {
return game.findFreeRandomSpot(entity, x, y, width, height);
}
/**
*
* @param entity
* @param x
* @param y
* @param width
* @param height
* @param notIn
* @return a random position anywhere in the supplied bounds and not in the supplied {@link Rectangle}
*/
public Vector2f getRandomSpotNotIn(Entity entity, int x, int y, int width, int height, Rectangle notIn) {
return game.findFreeRandomSpotNotIn(entity, x, y, width, height, notIn);
}
/**
* @return the random
*/
public Randomizer getRandom() {
return random;
}
/**
* @param pos
* @return the Zone at the supplied position
*/
public Zone getZone(Vector2f pos) {
return this.zones.getZone(pos);
}
public Zone getZone(int x, int y) {
return this.zones.getZone(x, y);
}
public Zone[] findAdjacentZones(Zone zone, int minDistance) {
Rectangle bounds = zone.getBounds();
int fuzzy = 5;
Zone[] adjacentZones = new Zone[8];
adjacentZones[0] = getNorthZone(bounds, fuzzy, minDistance);
adjacentZones[1] = getNorthEastZone(bounds, fuzzy, minDistance);
adjacentZones[2] = getEastZone(bounds, fuzzy, minDistance);
adjacentZones[3] = getSouthEastZone(bounds, fuzzy, minDistance);
adjacentZones[4] = getSouthZone(bounds, fuzzy, minDistance);
adjacentZones[5] = getSouthWestZone(bounds, fuzzy, minDistance);
adjacentZones[6] = getWestZone(bounds, fuzzy, minDistance);
adjacentZones[7] = getNorthWestZone(bounds, fuzzy, minDistance);
return adjacentZones;
}
/**
* Attempts to find an adjacent {@link Zone} given the minimum distance
* @param zone
* @param minDistance
* @return an adjacent zone or null if none are found
*/
public Zone findAdjacentZone(Zone zone, int minDistance) {
Rectangle bounds = zone.getBounds();
int fuzzy = 5;
Zone adjacentZone = null;
final int numberOfDirections = 8;
int adjacentIndex = random.nextInt(numberOfDirections);
for(int i = 0; i < numberOfDirections && adjacentZone==null; i++) {
switch(adjacentIndex) {
case 0:
adjacentZone = getNorthZone(bounds, fuzzy, minDistance);
break;
case 1:
adjacentZone = getNorthEastZone(bounds, fuzzy, minDistance);
break;
case 2:
adjacentZone = getEastZone(bounds, fuzzy, minDistance);
break;
case 3:
adjacentZone = getSouthEastZone(bounds, fuzzy, minDistance);
break;
case 4:
adjacentZone = getSouthZone(bounds, fuzzy, minDistance);
break;
case 5:
adjacentZone = getSouthWestZone(bounds, fuzzy, minDistance);
break;
case 6:
adjacentZone = getWestZone(bounds, fuzzy, minDistance);
break;
case 7:
adjacentZone = getNorthWestZone(bounds, fuzzy, minDistance);
break;
default:
return null;
}
adjacentIndex = (adjacentIndex+1) % numberOfDirections;
}
return adjacentZone;
}
private Zone getNorthZone(Rectangle bounds, int fuzzy, int minDistance) {
int adjacentZoneX = bounds.x;
int adjacentZoneY = bounds.y - (bounds.height/2 + fuzzy + minDistance);
Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY);
return adjacentZone;
}
private Zone getNorthWestZone(Rectangle bounds, int fuzzy, int minDistance) {
int adjacentZoneX = bounds.x - (bounds.width/2 + fuzzy + minDistance);
int adjacentZoneY = bounds.y - (bounds.height/2 + fuzzy + minDistance);
Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY);
return adjacentZone;
}
private Zone getNorthEastZone(Rectangle bounds, int fuzzy, int minDistance) {
int adjacentZoneX = bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance);
int adjacentZoneY = bounds.y - (bounds.height/2 + fuzzy + minDistance);
Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY);
return adjacentZone;
}
private Zone getEastZone(Rectangle bounds, int fuzzy, int minDistance) {
int adjacentZoneX = bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance);
int adjacentZoneY = bounds.y;
Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY);
return adjacentZone;
}
private Zone getSouthZone(Rectangle bounds, int fuzzy, int minDistance) {
int adjacentZoneX = bounds.x;
int adjacentZoneY = bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance);
Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY);
return adjacentZone;
}
private Zone getSouthWestZone(Rectangle bounds, int fuzzy, int minDistance) {
int adjacentZoneX = bounds.x - (bounds.width/2 + fuzzy + minDistance);
int adjacentZoneY = bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance);
Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY);
return adjacentZone;
}
private Zone getSouthEastZone(Rectangle bounds, int fuzzy, int minDistance) {
int adjacentZoneX = bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance);
int adjacentZoneY = bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance);
Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY);
return adjacentZone;
}
private Zone getWestZone(Rectangle bounds, int fuzzy, int minDistance) {
int adjacentZoneX = bounds.x - (bounds.width/2 + fuzzy + minDistance);
int adjacentZoneY = bounds.y;
Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY);
return adjacentZone;
}
/**
* The hiding position
*
* @param obstaclePos
* @param obstacleRadius
* @param targetPos
* @param result the result
* @return
*/
public Vector2f getHidingPosition(Vector2f obstaclePos, float obstacleRadius, Vector2f targetPos, Vector2f result) {
final float distanceFromBoundary = 5f;
float distAway = obstacleRadius + distanceFromBoundary;
Vector2f.Vector2fSubtract(obstaclePos, targetPos, result);
Vector2f.Vector2fNormalize(result, result);
Vector2f.Vector2fMA(obstaclePos, result, distAway, result);
return result;
}
/**
* Locates the best hiding position
*
* @param obstacles list of obstacles to hide by
* @param myPos the Agents current position
* @param targetPos the position which you want to hide from
* @return the best hiding position or the ZERO vector if non could be found
*/
public Vector2f findBestHidingPosition(List<Tile> obstacles, Vector2f myPos, Vector2f targetPos) {
// int bestCost = -1;
float distToClosest = 0f;
Vector2f bestHidingSpot = new Vector2f();
Vector2f nextHidingSpot = new Vector2f();
Vector2f tilePos = new Vector2f();
for(int i = 0; i < obstacles.size(); i++) {
Tile tile = obstacles.get(i);
tilePos.set(tile.getX()+tile.getWidth()/2, tile.getY()+tile.getHeight()/2);
nextHidingSpot = getHidingPosition(tilePos, tile.getWidth(), targetPos, nextHidingSpot);
/* skip if this is an invalid spot */
// if(map.pointCollides((int)nextHidingSpot.x, (int)nextHidingSpot.y)) {
// continue;
// }
Tile collidableTile = map.getWorldCollidableTile((int)nextHidingSpot.x, (int)nextHidingSpot.y);
if(collidableTile != null) {
continue;
}
Tile wTile = map.getWorldTile(0, (int)nextHidingSpot.x, (int)nextHidingSpot.y);
if(wTile == null) {
continue;
}
nextHidingSpot.x = wTile.getX() + wTile.getWidth()/2;
nextHidingSpot.y = wTile.getY() + wTile.getHeight()/2;
// int cost = this.graph.pathCost(myPos, nextHidingSpot);
// if(cost > bestCost) {
// bestCost = cost;
// bestHidingSpot.set(nextHidingSpot);
// }
/* if this hiding spot is closer to the agent, use it */
float dist = Vector2f.Vector2fDistanceSq(nextHidingSpot, myPos);
if(dist < distToClosest || bestHidingSpot.isZero()) {
bestHidingSpot.set(nextHidingSpot);
distToClosest = dist;
}
}
return bestHidingSpot;
}
/**
* Attempts to find {@link Cover} between the agent and an attack direction
*
* @param entity
* @param attackDir
* @return a place to take {@link Cover}
*/
public Cover getCover(Entity entity, Vector2f attackDir) {
Vector2f bestHidingSpot = getClosestCoverPosition(entity, attackDir);
// DebugDraw.fillRectRelative( (int)bestHidingSpot.x, (int)bestHidingSpot.y, 10, 10, 0xff00ff00);
//
// for(Tile tile : collidableTiles) {
// DebugDraw.fillRectRelative(tile.getX(), tile.getY(), tile.getWidth(), tile.getHeight(), 0x3fff0000);
// }
return new Cover(bestHidingSpot, attackDir);
}
/**
* Attempts to find the closest position which will serve as 'cover' between the agent and an attack direction
*
* @param entity
* @param attackDir
* @return the position to take cover
*/
public Vector2f getClosestCoverPosition(Entity entity, Vector2f attackDir) {
Vector2f pos = entity.getCenterPos();
map.getTilesInCircle( (int)pos.x, (int)pos.y, 250, tiles);
List<Tile> collidableTiles = map.getCollisionTilesAt(tiles, new ArrayList<Tile>());
Vector2f bestHidingSpot = findBestHidingPosition(collidableTiles, pos, attackDir);
return bestHidingSpot;
}
/**
* Calculates the possible {@link AttackDirection}'s from the supplied {@link Entity}s position.
*
* @param entity
* @return the list of possible {@link AttackDirection}s
*/
public List<AttackDirection> getAttackDirections(Entity entity) {
return getAttackDirections(entity.getCenterPos(), 300f, 10);
}
/**
* Calculates the possible {@link AttackDirection}'s from the supplied position.
*
* @param pos
* @return the list of possible {@link AttackDirection}s
*/
public List<AttackDirection> getAttackDirections(Vector2f pos, float distanceToCheck, int numberOfDirectionsToCheck) {
this.attackDirections.clear();
Vector2f attackDir = new Vector2f();
/* check each direction and see if a wall is providing us some
* cover
*/
float currentAngle = 0;
for(int i = 0; i < numberOfDirectionsToCheck; i++) {
attackDir.set(1,0);
Vector2f.Vector2fRotate(attackDir, Math.toRadians(currentAngle), attackDir);
Vector2f.Vector2fMA(pos, attackDir, distanceToCheck, attackDir);
if(!map.lineCollides(pos, attackDir)) {
this.attackDirections.add(new AttackDirection(attackDir.createClone()));
}
currentAngle += 360f/(float)numberOfDirectionsToCheck;
}
return this.attackDirections;
}
public void tilesTouchingEntity(Entity entOnTile, List<Tile> tilesToAvoid) {
tilesToAvoid.clear();
getMap().getTilesInRect(entOnTile.getBounds(), tilesToAvoid);
if(entOnTile.getType().isVehicle()) {
Vehicle vehicle = (Vehicle) entOnTile;
OBB oob = vehicle.getOBB();
for(int i = 0; i < tilesToAvoid.size(); ) {
Tile t = tilesToAvoid.get(i);
if(!oob.intersects(t.getBounds())) {
tilesToAvoid.remove(i);
}
else {
i++;
}
}
}
}
}
| 21,767 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AIConfig.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/AIConfig.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.shared.Config;
/**
* @author Tony
*
*/
public class AIConfig {
private Config config;
/**
*
*/
public AIConfig(Config config) {
this.config = config;
}
public long getSightExpireTime() {
return this.config.getInt(8_000, "ai", "sightExpireTime");
}
public long getSightPollTime() {
return this.config.getInt(300, "ai", "sightPollTime");
}
public long getSoundPollTime() {
return this.config.getInt(200, "ai", "soundPollTime");
}
public long getSoundExpireTime() {
return this.config.getInt(1_000, "ai", "soundExpireTime");
}
public long getFeelPollTime() {
return this.config.getInt(200, "ai", "soundPollTime");
}
public long getFeelExpireTime() {
return this.config.getInt(1_000, "ai", "feelExpireTime");
}
public long getTriggeringSystemPollTime() {
return this.config.getInt(200, "ai", "triggeringSystemPollTime");
}
public long getEvaluationPollTime() {
return this.config.getInt(300, "ai", "evaluationPollTime");
}
public long getReactionTime() {
return this.config.getInt(500, "ai", "reactionTime");
}
}
| 1,298 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Locomotion.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/Locomotion.java | /*
* see license.txt
*/
package seventh.ai.basic;
import java.util.List;
import seventh.ai.basic.actions.Action;
import seventh.ai.basic.actions.DecoratorAction;
import seventh.ai.basic.actions.atom.BombAction;
import seventh.ai.basic.actions.atom.DropWeaponAction;
import seventh.ai.basic.actions.atom.StareAtEntityAction;
import seventh.ai.basic.actions.atom.body.CrouchAction;
import seventh.ai.basic.actions.atom.body.HeadScanAction;
import seventh.ai.basic.actions.atom.body.LookAtAction;
import seventh.ai.basic.actions.atom.body.MeleeAction;
import seventh.ai.basic.actions.atom.body.MoveAction;
import seventh.ai.basic.actions.atom.body.ReloadAction;
import seventh.ai.basic.actions.atom.body.ShootAction;
import seventh.ai.basic.actions.atom.body.SprintAction;
import seventh.ai.basic.actions.atom.body.SwitchWeaponAction;
import seventh.ai.basic.actions.atom.body.ThrowGrenadeAction;
import seventh.ai.basic.actions.atom.body.WalkAction;
import seventh.game.PlayerClass;
import seventh.game.PlayerClass.WeaponEntry;
import seventh.game.Team;
import seventh.game.entities.BombTarget;
import seventh.game.entities.Entity;
import seventh.game.entities.Entity.Type;
import seventh.game.entities.PlayerEntity;
import seventh.game.weapons.GrenadeBelt;
import seventh.game.weapons.Weapon;
import seventh.graph.GraphNode;
import seventh.map.MapGraph;
import seventh.map.Tile;
import seventh.math.Vector2f;
import seventh.shared.DebugDraw;
import seventh.shared.Debugable;
import seventh.shared.Randomizer;
import seventh.shared.TimeStep;
/**
* Used for handling Agent motion
*
* @author Tony
*
*/
public class Locomotion implements Debugable {
private Brain brain;
private DecoratorAction destinationGoal;
private DecoratorAction facingGoal;
private DecoratorAction handsGoal;
private DecoratorAction legsGoal;
private PlayerEntity me;
private final PathPlanner<?> pathPlanner;
private Vector2f moveDelta;
private Randomizer random;
/*
* cached common actions
*/
private LookAtAction lookAt;
private HeadScanAction headScan;
private StareAtEntityAction stareAt;
private MoveAction moveAction;
private CrouchAction crouchAction;
private WalkAction walkAction;
private SprintAction sprintAction;
private ReloadAction reloadAction;
private MeleeAction meleeAction;
private DropWeaponAction dropWeaponAction;
private ShootAction shootAction;
/**
*
*/
public Locomotion(Brain brain) {
this.brain = brain;
this.pathPlanner = new PathPlanner<>(brain, brain.getWorld().getGraph());
this.random = brain.getWorld().getRandom();
this.destinationGoal = new DecoratorAction(brain);
this.legsGoal = new DecoratorAction(brain);
this.facingGoal = new DecoratorAction(brain);
this.handsGoal = new DecoratorAction(brain);
this.moveDelta = new Vector2f();
this.headScan = new HeadScanAction();
this.moveAction = new MoveAction();
this.lookAt = new LookAtAction(0);
this.stareAt = new StareAtEntityAction(null);
this.crouchAction = new CrouchAction();
this.walkAction = new WalkAction();
this.sprintAction = new SprintAction();
this.reloadAction = new ReloadAction();
this.meleeAction = new MeleeAction();
this.dropWeaponAction = new DropWeaponAction();
this.shootAction = new ShootAction();
reset(brain);
}
/**
* Resets, generally this was caused by a death
*/
public void reset(Brain brain) {
this.destinationGoal.end(brain);
this.facingGoal.end(brain);
this.handsGoal.end(brain);
this.legsGoal.end(brain);
this.me = brain.getEntityOwner();
}
/**
* Remove the {@link PathPlanner}
*/
public void emptyPath() {
this.pathPlanner.clearPath();
}
/**
* @return the pathFeeder
*/
public PathPlanner<?> getPathPlanner() {
return pathPlanner;
}
@SuppressWarnings("unused")
private void debugDraw() {
// int y = 100;
// int x = 20;
// final int yOffset = 20;
// int color = 0xff00ff00;
//
// final String message = "%-8s %-19s %-5s";
// DebugDraw.drawString(String.format(message, "Motion", "State", "IsFinished"), x, y, color);
// DebugDraw.drawString("====================================", x, y += yOffset, color);
//
// String text = String.format(message, "Walking", destinationGoal.getAction() != null ? destinationGoal.getAction().getClass().getSimpleName():"[none]", destinationGoal.isFinished(brain));
// DebugDraw.drawString(text, x, y += yOffset, color);
//
// text = String.format(message, "Facing", facingGoal.getAction() != null ? facingGoal.getAction().getClass().getSimpleName():"[none]", facingGoal.isFinished(brain));
// DebugDraw.drawString(text, x, y += yOffset, color);
//
// text = String.format(message, "Hands", handsGoal.getAction() != null ? handsGoal.getAction().getClass().getSimpleName():"[none]", handsGoal.isFinished(brain));
// DebugDraw.drawString(text, x, y += yOffset, color);
MapGraph<?> graph = brain.getWorld().getGraph();
for(int y = 0; y < graph.graph.length; y++) {
for(int x = 0; x < graph.graph[0].length; x++) {
GraphNode<Tile, ?> node = graph.getNodeByIndex(x, y);
if(node != null) {
Tile t = node.getValue();
//DebugDraw.fillRectRelative(t.getX(), t.getY(), t.getWidth(), t.getHeight(), 0x1f00ff00);
//DebugDraw.drawRectRelative(t.getX(), t.getY(), t.getWidth(), t.getHeight(), 0x8f00ffff);
}
}
}
Entity ent = brain.getEntityOwner();
if(ent != null) {
DebugDraw.fillRectRelative(ent.getBounds().x, ent.getBounds().y, ent.getBounds().width, ent.getBounds().height, 0xffff0000);
}
}
/**
* @param timeStep
*/
public void update(TimeStep timeStep) {
// debugDraw();
if(!destinationGoal.isFinished(brain)) {
destinationGoal.update(brain, timeStep);
}
if(!legsGoal.isFinished(brain)) {
legsGoal.update(brain, timeStep);
}
if(!facingGoal.isFinished(brain)) {
facingGoal.update(brain, timeStep);
}
else {
if(!destinationGoal.isFinished(brain)) {
scanArea();
}
}
if(!handsGoal.isFinished(brain)) {
handsGoal.update(brain, timeStep);
}
moveEntity();
}
/**
* Do the actual movement
*/
private void moveEntity() {
moveDelta.zeroOut();
if(pathPlanner.hasPath()) {
if (!pathPlanner.atDestination()) {
Vector2f waypoint = pathPlanner.nextWaypoint(me);
moveDelta.set(waypoint);
}
else {
Vector2f nextDest = pathPlanner.getDestination();
Vector2f.Vector2fSubtract(nextDest, me.getPos(), moveDelta);
if(moveDelta.lengthSquared() < 26) {
moveDelta.zeroOut();
}
}
}
directMove(moveDelta);
}
/**
* Scans the area
*/
public void scanArea() {
if(!this.facingGoal.is(HeadScanAction.class)) {
this.headScan.reset();
this.facingGoal.setAction(this.headScan);
}
}
/**
* Switches to another weapon in the bots arsenal
* @param weapon
*/
public void changeWeapon(Type weapon) {
Weapon currentWeapon = me.getInventory().currentItem();
if(currentWeapon != null) {
if(!currentWeapon.getType().equals(weapon)) {
Action action = new SwitchWeaponAction(weapon);
handsGoal.setAction(action);
}
}
}
/**
* Plants a bomb
*/
public void plantBomb(BombTarget bomb) {
handsGoal.setAction(new BombAction(bomb, true));
}
/**
* Defuses a bomb
*/
public void defuseBomb(BombTarget bomb) {
handsGoal.setAction(new BombAction(bomb, false));
}
/**
* Moves to the destination, the bot will do a optimized path
* to the destination
*
* @param dest
* @return an {@link Action} to invoke
*/
public void moveTo(Vector2f dest) {
this.moveAction.setDestination(dest);
this.moveAction.clearAvoids();
this.destinationGoal.setAction(this.moveAction);
}
/**
* Moves to the destination, avoiding the supplied {@link Zone}s.
*
* @param dest
* @param avoid
*/
public void avoidMoveTo(Vector2f dest, List<Zone> avoid) {
this.moveAction.setDestination(dest);
this.moveAction.setZonesToAvoid(avoid);
this.destinationGoal.setAction(this.moveAction);
}
public void stopMoving() {
this.destinationGoal.end(brain);
}
public void stopUsingHands() {
this.handsGoal.end(brain);
}
/**
* @return the destination this entity is moving towards, or null if no
* destination
*/
public Vector2f getDestination() {
if(this.pathPlanner != null) {
return pathPlanner.getDestination();
}
return null;
}
public boolean isMoving() {
return this.destinationGoal.hasAction() && !this.destinationGoal.isFinished(brain);
}
public boolean isPlanting() {
return this.handsGoal.hasAction() && this.handsGoal.is(BombAction.class);
}
public boolean isDefusing() {
return this.handsGoal.hasAction() && this.handsGoal.is(BombAction.class);
}
/**
* Crouch down
*/
public void crouch() {
this.destinationGoal.end(this.brain);
this.legsGoal.end(this.brain);
this.legsGoal.setAction(this.crouchAction);
}
/**
* Stop crouching
*/
public void standup() {
if(isCrouching()) {
this.legsGoal.end(this.brain);
}
}
/**
* @return true if crouching
*/
public boolean isCrouching() {
return this.legsGoal.is(CrouchAction.class);
}
/**
* @return true if sprinting
*/
public boolean isSprinting() {
return this.legsGoal.is(SprintAction.class);
}
/**
* @return true if walking
*/
public boolean isWalking() {
return this.legsGoal.is(WalkAction.class);
}
public void walk() {
this.legsGoal.setAction(this.walkAction);
}
public void stopWalking() {
if(this.legsGoal.is(WalkAction.class)) {
this.legsGoal.end(brain);
}
}
public void sprint() {
this.legsGoal.setAction(this.sprintAction);
}
public void stopSprinting() {
if(this.legsGoal.is(SprintAction.class)) {
this.legsGoal.end(brain);
}
}
public void reload() {
this.handsGoal.setAction(this.reloadAction);
}
public void meleeAttack() {
this.handsGoal.setAction(this.meleeAction);
}
public void dropWeapon() {
this.handsGoal.setAction(this.dropWeaponAction);
}
public void lookAt(Vector2f pos) {
this.lookAt.reset(me, pos);
this.facingGoal.setAction(this.lookAt);
}
public void stareAtEntity(Entity entity) {
this.stareAt.reset(entity);
this.facingGoal.setAction(this.stareAt);
}
public boolean isStaringAtEntity() {
return this.facingGoal.is(StareAtEntityAction.class);
}
public void shoot() {
this.handsGoal.setAction(this.shootAction);
}
public void stopShooting() {
if(this.handsGoal.is(ShootAction.class)) {
this.handsGoal.end(this.brain);
}
}
public boolean handsInUse() {
return this.handsGoal.hasAction();
}
public boolean isTooClose(Entity ent) {
return (Vector2f.Vector2fDistanceSq(this.me.getPos(), ent.getPos()) < 2500);
}
public boolean throwGrenade(Vector2f pos) {
GrenadeBelt belt=this.me.getInventory().getGrenades();
if( belt.getNumberOfGrenades() > 0 /*&& !handsInUse()*/ ) {
this.handsGoal.setAction(new ThrowGrenadeAction(me, pos));
return true;
}
return false;
}
/**
* Directly moves the entity, based on the delta inputs
* @param delta
*/
public void directMove(Vector2f delta) {
directMove(delta.x, delta.y);
}
/**
* Directly moves the entity, based on the delta inputs
* @param x the X direction to move
* @param y the Y direction to move
*/
public void directMove(float x, float y) {
final float threshold = 0f; // was 0
if(me.isOperatingVehicle()) {
// Vehicle vehicle = me.getVehicle();
// Tank tank = (Tank)vehicle; // TODO - handle this generically
// TODO make movement of tank work!!
// float fx = x - tank.getFacing().x;
// float fy = y - tank.getFacing().y;
// double angle = Vector2f.Vector2fAngle(new Vector2f(x, y), tank.getFacing());
// System.out.println(angle + " vs " + tank.getOrientation());
// double deltaAngle = angle - tank.getOrientation();
// if(deltaAngle < -threshold) {
// tank.maneuverLeft();
// }
// else if(deltaAngle > threshold) {
// tank.maneuverRight();
//
// }
// else {
// tank.stopManeuvering();
// }
//
// if(fy < -threshold) {
// //tank.forwardThrottle();
// }
// else if(fy > threshold) {
// //tank.backwardThrottle();
// }
// //tank.backwardThrottle();
// //tank.forwardThrottle();
// //tank.stopManeuvering();
// tank.stopThrottle();
}
else {
if (x < -threshold ) {
me.moveLeft();
}
else if (x > threshold ) {
me.moveRight();
}
else {
me.noMoveX();
}
if(y < -threshold ) {
me.moveUp();
}
else if(y > threshold) {
me.moveDown();
}
else {
me.noMoveY();
}
}
}
/**
* Picks a weapon class to use
* @return the type of weapon
*/
public Type pickWeapon() {
PlayerEntity bot = brain.getEntityOwner();
Type type = getRandomWeapon(bot.getTeam());
bot.setPlayerClass(brain.getPlayer().getPlayerClass(), type);
changeWeapon(type);
return type;
}
/**
* Picks a semi-random weapon. It may attempt to pick
* a weapon based on the world (this is chosen randomly).
*
* @param team
* @return the weapon type
*/
private Type getRandomWeapon(Team team) {
int index = -1;
if(team != null) {
PlayerClass playerClass = this.brain.getPlayer().getPlayerClass();
List<WeaponEntry> availableWeapons = playerClass.getAvailableWeapons();
int max = availableWeapons.size();
// lean more towards standard guns vs flamethrower/RL
if(max > 3) {
if(random.nextInt(4) != 1) {
max -= 1;
}
}
boolean pickSmart = random.nextBoolean();
if(pickSmart) {
index = pickThoughtfulWeapon(team, availableWeapons);
}
else {
index = random.nextInt(max);
}
return availableWeapons.get(index).type.getTeamWeapon(team);
}
return Type.UNKNOWN;
}
/**
* Picks a weapon based on some world conditions.
*
* @param team
* @return the index to the weapon
*/
private int pickThoughtfulWeapon(Team team, List<WeaponEntry> availableWeapons) {
if(team != null) {
// TODO: Make a thoughtful selection
return random.nextInt(availableWeapons.size());
}
return -1;
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation info = new DebugInformation();
info.add("hands", this.handsGoal)
.add("destination", this.destinationGoal)
.add("facing", this.facingGoal)
.add("legs", this.legsGoal)
;
return info;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 17,699 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Zone.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/Zone.java | /*
* see license.txt
*/
package seventh.ai.basic;
import java.util.ArrayList;
import java.util.List;
import seventh.game.entities.BombTarget;
import seventh.game.entities.Entity;
import seventh.math.Rectangle;
import seventh.shared.Debugable;
/**
* A {@link Zone} represents a section of the game world. We break the game world
* into {@link Zone}s so that we can gather statistics about "hot" areas and makes
* it easier to defend or attack areas of the map.
*
* @author Tony
*
*/
public class Zone implements Debugable {
private Rectangle bounds;
private int id;
private List<BombTarget> targets;
private ZoneStats stats;
private boolean isHabitable;
/**
* @param id
* @param bounds
* @param isHabitable
*/
public Zone(int id, Rectangle bounds, boolean isHabitable) {
this.id = id;
this.bounds = bounds;
this.targets = new ArrayList<BombTarget>();
this.stats = new ZoneStats(this);
this.isHabitable = isHabitable;
}
/**
* @return the isHabitable
*/
public boolean isHabitable() {
return isHabitable;
}
/**
* @return the stats
*/
public ZoneStats getStats() {
return stats;
}
/**
* @return the bounds
*/
public Rectangle getBounds() {
return bounds;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @return true if this Zone has {@link BombTarget}s
*/
public boolean hasTargets() {
return !this.targets.isEmpty();
}
/**
* @return the targets
*/
public List<BombTarget> getTargets() {
return targets;
}
/**
* Clears any registered targets
*/
public void clearTargets() {
this.targets.clear();
}
/**
* Adds a bomb target to this {@link Zone}
* @param target
*/
public void addTarget(BombTarget target) {
this.targets.add(target);
}
/**
* @return true if this zone still contains undestroyed {@link BombTarget}s
*/
public boolean isTargetsStillActive() {
boolean stillActive = false;
for(int i = 0; i < targets.size(); i++) {
BombTarget target = targets.get(i);
if(target.isAlive()) {
stillActive = true;
break;
}
}
return stillActive;
}
/**
* @return true if there is an active bomb
*/
public boolean hasActiveBomb() {
for(int i = 0; i < targets.size(); i++) {
BombTarget target = targets.get(i);
if(target.isAlive()) {
if(target.bombActive() || target.bombPlanting()) {
return true;
}
}
}
return false;
}
/**
* @param entity
* @return true if the supplied Entity is in this {@link Zone}
*/
public boolean contains(Entity entity) {
return this.bounds.intersects(entity.getBounds());
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
me.add("id", this.id)
.add("bounds", this.bounds);
return me;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 3,631 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PathPlanner.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/PathPlanner.java | /*
* leola-live
* see license.txt
*/
package seventh.ai.basic;
import java.util.ArrayList;
import java.util.List;
import seventh.game.Player;
import seventh.game.PlayerInfo;
import seventh.game.entities.Door;
import seventh.game.entities.Entity;
import seventh.game.entities.PlayerEntity;
import seventh.game.entities.vehicles.Vehicle;
import seventh.graph.AStarGraphSearch;
import seventh.graph.GraphNode;
import seventh.map.MapGraph;
import seventh.map.Tile;
import seventh.math.Vector2f;
/**
* Feeds the next graph node. This is the path planner for an agent. This allows an agent to
* know which tile to move to next
*
* @author Tony
*
*/
public class PathPlanner<E> {
private MapGraph<E> graph;
private List<GraphNode<Tile, E>> path;
private int currentNode;
private int currentNodeCount;
private Vector2f nextWaypoint;
private Vector2f finalDestination;
private World world;
private Brain brain;
private List<Tile> tilesToAvoid;
private Entity isEntityOnTile(Tile tile) {
Entity ent = isVehicleOnTile(tile);
if(ent==null) {
ent = isTeammateOnTile(tile);
}
return ent;
}
private Entity isTeammateOnTile(Tile tile) {
List<Player> teammates = world.getTeammates(brain);
PlayerInfo bot = brain.getPlayer();
int size = teammates.size();
for(int i = 0; i < size; i++) {
if(bot.getId() != i) {
Player p = teammates.get(i);
PlayerEntity ent = p.getEntity();
if(p.isAlive()) {
if(tile.getBounds().contains(ent.getCenterPos())) {
return ent;
}
}
}
}
return null;
}
private Entity isVehicleOnTile(Tile tile) {
List<Vehicle> vehicles = world.getVehicles();
int size = vehicles.size();
for(int i = 0; i < size; i++) {
Vehicle v = vehicles.get(i);
if(tile.getBounds().intersects(v.getBounds())) {
if(v.getOBB().intersects(tile.getBounds())) {
return v;
}
}
}
return null;
}
public static class SearchPath<E> extends AStarGraphSearch<Tile, E> {
public List<Tile> tilesToAvoid = new ArrayList<>();
@Override
protected int heuristicEstimateDistance(
GraphNode<Tile, E> startNode,
GraphNode<Tile, E> currentNode,
GraphNode<Tile, E> goal) {
Tile startTile = startNode.getValue();
Tile currentTile = currentNode.getValue();
Tile goalTile = goal.getValue();
int dx = Math.abs(currentTile.getX() - goalTile.getX());
int dy = Math.abs(currentTile.getY() - goalTile.getY());
int sdx = Math.abs(startTile.getX() - goalTile.getX());
int sdy = Math.abs(startTile.getY() - goalTile.getY());
final int D = 1;
//final int D2 = 2;
//distance = D * (dx+dy) + (D2 - 2 * D) * Math.min(dx, dy);
int distance = D * (dx+dy);
int cross = Math.abs(dx*sdy - sdx*dy);
return distance + (cross);//
}
@Override
protected boolean shouldIgnore(GraphNode<Tile, E> node) {
boolean ignore = this.tilesToAvoid.contains(node.getValue());
if(ignore) {
//System.out.println("Ignoring: " + node.getValue().getXIndex() + "," + node.getValue().getYIndex());
return true;
}
return false;
}
}
public static class AvoidSearchPath<E> extends AStarGraphSearch<Tile,E> {
public List<Tile> tilesToAvoid = new ArrayList<>();
public List<Zone> zonesToAvoid;
@Override
protected int heuristicEstimateDistance(
GraphNode<Tile, E> startNode,
GraphNode<Tile, E> currentNode,
GraphNode<Tile, E> goal) {
Tile currentTile = currentNode.getValue();
Tile goalTile = goal.getValue();
int dx = Math.abs(currentTile.getX() - goalTile.getX());
int dy = Math.abs(currentTile.getY() - goalTile.getY());
final int D = 1;
//final int D2 = 2;
//distance = D * (dx+dy) + (D2 - 2 * D) * Math.min(dx, dy);
int distance = D * (dx+dy);
if(shouldBeAvoided(currentTile)||shouldBeAvoided(goalTile)) {
distance = Integer.MAX_VALUE;
}
return distance;
}
private boolean shouldBeAvoided(Tile tile) {
for(int i = 0; i < zonesToAvoid.size(); i++) {
Zone zone = zonesToAvoid.get(i);
if(zone.getBounds().intersects(tile.getBounds())) {
return true;
}
}
return false;
}
@Override
protected boolean shouldIgnore(GraphNode<Tile, E> node) {
/*Tile tile = node.getValue();
for(int i = 0; i < zonesToAvoid.size(); i++) {
Zone zone = zonesToAvoid.get(i);
if(zone.getBounds().intersects(tile.getBounds())) {
return true;
}
}*/
return this.tilesToAvoid.contains(node.getValue());
}
}
private SearchPath<E> fuzzySearchPath;
private AvoidSearchPath<E> avoidSearchPath;
/**
* @param path
*/
public PathPlanner(Brain brain, MapGraph<E> graph) {
this.brain = brain;
this.world = brain.getWorld();
this.graph = graph;
this.finalDestination = new Vector2f();
this.nextWaypoint = new Vector2f();
this.path = new ArrayList<GraphNode<Tile, E>>();
this.tilesToAvoid = new ArrayList<Tile>();
this.currentNode = 0;
this.fuzzySearchPath = new SearchPath<E>();
this.avoidSearchPath = new AvoidSearchPath<E>();
}
private void setPath(List<GraphNode<Tile, E>> newPath) {
clearPath();
if(newPath != null) {
for(int i = 0; i < newPath.size(); i++) {
this.path.add(newPath.get(i));
}
}
}
/**
* Clears out the path
*/
public void clearPath() {
this.currentNode = 0;
this.finalDestination.zeroOut();
this.path.clear();
this.tilesToAvoid.clear();
}
/**
* Calculate the estimated cost of the path from the start to destination
*
* @param start
* @param destination
* @return the estimated cost of moving from start to destination
*/
public int pathCost(Vector2f start, Vector2f destination) {
List<GraphNode<Tile, E>> newPath = this.graph.findPath(this.fuzzySearchPath, start, destination);
int cost = newPath.size() * 32;
return cost;
}
/**
* Finds the optimal path between the start and end point
*
* @param start
* @param destination
*/
public void findPath(Vector2f start, Vector2f destination) {
List<GraphNode<Tile, E>> newPath = this.graph.findPath(this.fuzzySearchPath, start, destination);
setPath(newPath);
this.finalDestination.set(destination);
}
public void findPath(Vector2f start, Vector2f destination, List<Tile> tilesToAvoid) {
this.fuzzySearchPath.tilesToAvoid.clear();
this.fuzzySearchPath.tilesToAvoid.addAll(tilesToAvoid);
List<GraphNode<Tile, E>> newPath = this.graph.findPath(this.fuzzySearchPath, start, destination);
setPath(newPath);
this.finalDestination.set(destination);
}
/**
* Finds a path, avoiding the supplied {@link Zone}s
*
*
* @param start
* @param destination
* @param zonesToAvoid
*/
public void findAvoidancePath(Vector2f start, Vector2f destination, List<Zone> zonesToAvoid) {
this.avoidSearchPath.zonesToAvoid = zonesToAvoid;
List<GraphNode<Tile, E>> newPath = this.graph.findPathAvoidZones(this.avoidSearchPath, start, destination, zonesToAvoid);
setPath(newPath);
this.finalDestination.set(destination);
}
/**
* @return if there is currently a path
*/
public boolean hasPath() {
return !this.path.isEmpty();
}
/**
* @return the final destination
*/
public Vector2f getDestination() {
return this.finalDestination;
}
/**
* @return the path
*/
public List<GraphNode<Tile, E>> getPath() {
return path;
}
/**
* @return the current node that the entity is trying to reach
*/
public GraphNode<Tile, E> getCurrentNode() {
if (!path.isEmpty() && currentNode < path.size()) {
return path.get(currentNode);
}
return null;
}
/**
* @return true if this path is on the first node (just started)
*/
public boolean onFirstNode() {
return currentNode == 0 && !path.isEmpty();
}
/**
* Retrieves the next way-point on the path.
*
* @param ent
* @return the next way-point on the path
*/
public Vector2f nextWaypoint(PlayerEntity ent) {
Vector2f cPos = ent.getCenterPos();
int x = (int)cPos.x;
int y = (int)cPos.y;
//for(Tile t : dbg) {
//DebugDraw.fillRectRelative(t.getX(), t.getY(), t.getWidth(), t.getHeight(), 0xff00ffff);
//DebugDraw.drawRectRelative(t.getX(), t.getY(), t.getWidth(), t.getHeight(), 0xffff00ff);
//DebugDraw.drawStringRelative("" + t.getXIndex() + "," + t.getYIndex(),t.getX()+16, t.getY()+16, 0xffff00ff);
//}
nextWaypoint.zeroOut();
if(! path.isEmpty() && currentNode < path.size() ) {
GraphNode<Tile, E> node = path.get(currentNode);
Tile tile = node.getValue();
int centerX = tile.getX() + tile.getWidth()/2;
int centerY = tile.getY() + tile.getHeight()/2;
if( Math.abs(centerX - x) < 6
&& Math.abs(centerY - y) < 6
//tile.getBounds().contains(currentPosition)
) {
currentNode++;
currentNodeCount = 0;
// if(ent.isSprinting()) {
// if(currentNode < path.size()) {
// tile = path.get(currentNode).getValue();
// }
// }
if(currentNode < path.size()) {
tile = path.get(currentNode).getValue();
Entity entOnTile = isEntityOnTile(tile);
if(entOnTile != null) {
world.tilesTouchingEntity(entOnTile, tilesToAvoid);
findPath(cPos, this.finalDestination, tilesToAvoid);
return nextWaypoint(ent);
}
}
}
else {
currentNodeCount++;
}
// if we get stuck, try to avoid this
// area to get to the destination
if(currentNodeCount > 50) {
currentNodeCount = 0;
tilesToAvoid.add(path.get(currentNode).getValue());
int size = world.getDoors().size();
for(int i = 0; i < size; i++ ) {
Door door = world.getDoors().get(i);
// we are probably stuck on this door
if(door.canBeHandledBy(ent)) {
Tile hinge = world.getMap().getWorldTile(0, (int)door.getPos().x, (int)door.getPos().y);
Tile handle = world.getMap().getWorldTile(0, (int)door.getHandle().x, (int)door.getHandle().y);
if(hinge!=null) tilesToAvoid.add(hinge);
if(handle!=null) tilesToAvoid.add(handle);
}
}
findPath(cPos, this.finalDestination, tilesToAvoid);
return nextWaypoint(ent);
}
// if(tile.getBounds().intersects(bounds)) {
// currentNode++;
//
// if(ent.isSprinting()) {
// if(currentNode < path.size()) {
// tile = path.get(currentNode).getValue();
// }
// }
// }
nextWaypoint.x = (centerX - x);
nextWaypoint.y = (centerY - y);
}
return nextWaypoint;
}
/**
* @return true if the current position is about the end of the path
*/
public boolean atDestination() {
return (currentNode >= path.size());
}
}
| 13,529 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DummyThoughtProcess.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/DummyThoughtProcess.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.shared.TimeStep;
/**
* A {@link ThoughtProcess} that does nothing, this is to allow for
* having Agents that do nothing for debugging purposes.
*
* @author Tony
*
*/
public class DummyThoughtProcess implements ThoughtProcess {
/**
* The single instance
*/
private static final ThoughtProcess DUMMY_THOUGHT_PROCESS = new DummyThoughtProcess();
/**
* @return the singleton instance
*/
public static ThoughtProcess getInstance() {
return DUMMY_THOUGHT_PROCESS;
}
/**
*/
protected DummyThoughtProcess() {
}
/* (non-Javadoc)
* @see seventh.ai.basic.Strategy#onSpawn(seventh.ai.basic.Brain)
*/
@Override
public void onSpawn(Brain brain) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.Strategy#onKilled(seventh.ai.basic.Brain)
*/
@Override
public void onKilled(Brain brain) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.Strategy#think(seventh.shared.TimeStep, seventh.ai.basic.Brain)
*/
@Override
public void think(TimeStep timeStep, Brain brain) {
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
me.add("type", getClass().getSimpleName());
return me;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 1,637 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
WeightedThoughtProcess.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/WeightedThoughtProcess.java | /*
* see license.txt
*/
package seventh.ai.basic;
import seventh.ai.basic.actions.ConcurrentAction;
import seventh.ai.basic.actions.Actions;
import seventh.ai.basic.actions.WeightedAction;
import seventh.ai.basic.actions.evaluators.AttackActionEvaluator;
import seventh.ai.basic.actions.evaluators.AvoidGrenadeActionEvaluator;
import seventh.ai.basic.actions.evaluators.CommandActionEvaluator;
import seventh.ai.basic.actions.evaluators.DefendSelfActionEvaluator;
import seventh.ai.basic.actions.evaluators.DegroupActionEvaluator;
import seventh.ai.basic.actions.evaluators.DoNothingEvaluator;
import seventh.ai.basic.actions.evaluators.ExploreActionEvaluator;
import seventh.ai.basic.actions.evaluators.HandleDoorActionEvaluator;
import seventh.ai.basic.actions.evaluators.InvestigateActionEvaluator;
import seventh.ai.basic.actions.evaluators.ReloadWeaponEvaluator;
import seventh.ai.basic.actions.evaluators.StrategyEvaluator;
import seventh.ai.basic.actions.evaluators.SwitchWeaponEvaluator;
import seventh.ai.basic.teamstrategy.TeamStrategy;
import seventh.shared.Randomizer;
import seventh.shared.TimeStep;
/**
* Weighted thought process means it attempts to make fuzzy decisions based on the surrounding environment and
* circumstances.
*
* @author Tony
*
*/
public class WeightedThoughtProcess implements ThoughtProcess {
private ConcurrentAction currentGoal;
/**
* @param teamStrategy
* @param brain
*/
public WeightedThoughtProcess(TeamStrategy teamStrategy, Brain brain) {
World world = brain.getWorld();
Actions goals = world.getGoals();
Randomizer rand = world.getRandom();
this.currentGoal = new ConcurrentAction(
// high level goals
new WeightedAction(brain.getConfig(), "highLevelGoal",
new AvoidGrenadeActionEvaluator(goals, rand.getRandomRange(0.8, 0.9), 0.9),
new AttackActionEvaluator(goals, rand.getRandomRangeMin(0.85), 0.82),
new DefendSelfActionEvaluator(goals, rand.getRandomRangeMin(0.85), 0.81),
new CommandActionEvaluator(goals, rand.getRandomRange(0.7, 0.8), 0.8),
new InvestigateActionEvaluator(goals, rand.getRandomRange(0.5, 0.9), 0.6),
// new RideVehicleEvaluator(goals, 1.0f,1f),//brain.getRandomRange(0.5, 0.7), 0.51),
new StrategyEvaluator(teamStrategy, goals, rand.getRandomRange(0.2, 0.6), 0),
new DegroupActionEvaluator(goals, 1, 0.99),
new ExploreActionEvaluator(goals, rand.getRandomRange(0.1, 0.5), 0.5)
),
// Auxiliary goals, ones that do not impact the high level goals
new WeightedAction(brain.getConfig(), "auxiliaryGoal",
new ReloadWeaponEvaluator(goals, rand.getRandomRange(0.3, 0.8), 0),
new SwitchWeaponEvaluator(goals, rand.getRandomRange(0.3, 0.8), 0),
new HandleDoorActionEvaluator(goals, 0, 1),
new DoNothingEvaluator(goals, rand.getRandomRange(0.4, 0.9), 0)
)
);
}
/* (non-Javadoc)
* @see seventh.ai.basic.ThoughtProcess#onSpawn(seventh.ai.basic.Brain)
*/
@Override
public void onSpawn(Brain brain) {
brain.getMotion().pickWeapon();
this.currentGoal.cancel();
this.currentGoal.start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.ThoughtProcess#onKilled(seventh.ai.basic.Brain)
*/
@Override
public void onKilled(Brain brain) {
this.currentGoal.cancel();
}
/* (non-Javadoc)
* @see seventh.ai.basic.ThoughtProcess#think(seventh.shared.TimeStep, seventh.ai.basic.Brain)
*/
@Override
public void think(TimeStep timeStep, Brain brain) {
this.currentGoal.update(brain, timeStep);
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation info = new DebugInformation();
//info.add("goal", this.currentGoal);
info.add("goal", this.currentGoal.getAction(0));
return info;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 4,812 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SightMemory.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/memory/SightMemory.java | /*
* see license.txt
*/
package seventh.ai.basic.memory;
import java.util.List;
import seventh.game.entities.PlayerEntity;
import seventh.game.weapons.Weapon;
import seventh.math.Vector2f;
import seventh.shared.SeventhConstants;
import seventh.shared.TimeStep;
import seventh.shared.Updatable;
/**
* Visual sight memory -- what this bot has seen, we store in a small cache so that he doesn't immediately forget the
* world around him
*
*
* @author Tony
*
*/
public class SightMemory implements Updatable {
/**
* Visual record of a sighting of a {@link PlayerEntity}
*
* @author Tony
*
*/
public static class SightMemoryRecord {
private final long expireTime;
private PlayerEntity entity;
private Weapon lastSeenWithWeapon;
private Vector2f lastSeenAt;
private long timeSeen;
private long seenDelta;
private boolean isValid;
/**
* @param expireTime
*/
public SightMemoryRecord(long expireTime) {
this.expireTime = expireTime;
this.lastSeenAt = new Vector2f();
this.isValid = false;
}
/**
* See a {@link PlayerEntity}
*
* @param timeStep
* @param entity
*/
public void seeEntity(TimeStep timeStep, PlayerEntity ent) {
if(ent.isAlive()) {
this.entity = ent;
this.timeSeen = timeStep.getGameClock();
this.lastSeenAt = ent.getCenterPos();
this.lastSeenWithWeapon = ent.getInventory().currentItem();
this.isValid = true;
}
}
/**
* @return the isValid
*/
public boolean isValid() {
return isValid;
}
/**
* Checks if this memory record has expired
*
* @param timeStep
*/
public void checkExpired(TimeStep timeStep) {
this.seenDelta = timeStep.getGameClock() - this.timeSeen;
if(isExpired(timeStep)) {
expire();
}
}
/**
* Expire this record
*/
public void expire() {
this.entity = null;
this.lastSeenWithWeapon = null;
this.lastSeenAt.zeroOut();
this.isValid = false;
}
/**
* If this entity is expired
*
* @param timeStep
* @return
*/
public boolean isExpired(TimeStep timeStep) {
return this.entity == null ||
!this.entity.isAlive() ||
(timeStep.getGameClock() - this.timeSeen > this.expireTime);
}
/**
* @return the entity
*/
public PlayerEntity getEntity() {
return entity;
}
/**
* @return the lastSeenAt
*/
public Vector2f getLastSeenAt() {
return lastSeenAt;
}
/**
* @return the lastSeenWithWeapon
*/
public Weapon getLastSeenWithWeapon() {
return lastSeenWithWeapon;
}
/**
* @return the timeSeen
*/
public long getTimeSeen() {
return timeSeen;
}
/**
* @return the amount of msec's ago this entity was seen
*/
public long getTimeSeenAgo() {
return seenDelta;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return isValid + "";
}
}
private SightMemoryRecord[] entityRecords;
/**
*
*/
public SightMemory(long expireTime) {
this.entityRecords = new SightMemoryRecord[SeventhConstants.MAX_PLAYERS];
for(int i = 0; i < this.entityRecords.length; i++) {
this.entityRecords[i] = new SightMemoryRecord(expireTime);
}
}
/* (non-Javadoc)
* @see seventh.shared.Updatable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
updateSightMemory(timeStep);
}
/**
* Expire this memory
*/
public void clear() {
for(int i = 0; i < this.entityRecords.length; i++) {
this.entityRecords[i].expire();
}
}
private void updateSightMemory(TimeStep timeStep) {
for(int i = 0; i < this.entityRecords.length; i++) {
this.entityRecords[i].checkExpired(timeStep);
}
}
/**
* @return the entityRecords
*/
public SightMemoryRecord[] getEntityRecords() {
return entityRecords;
}
/**
* See a set of {@link PlayerEntity}
*
* @param timeStep
* @param entitiesInView
*/
public void see(TimeStep timeStep,List<PlayerEntity> entitiesInView) {
for(int i = 0; i < entitiesInView.size(); i++) {
PlayerEntity ent = entitiesInView.get(i);
see(timeStep, ent);
}
}
/**
* See a {@link PlayerEntity}
*
* @param timeStep
* @param ent
*/
public void see(TimeStep timeStep, PlayerEntity ent) {
if(ent != null) {
int id = ent.getId();
if(id>-1 && id < this.entityRecords.length) {
this.entityRecords[id].seeEntity(timeStep, ent);
}
}
}
}
| 5,767 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FeelMemory.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/memory/FeelMemory.java | /*
* see license.txt
*/
package seventh.ai.basic.memory;
import seventh.game.entities.Entity;
import seventh.shared.SeventhConstants;
import seventh.shared.TimeStep;
import seventh.shared.Updatable;
/**
* @author Tony
*
*/
public class FeelMemory implements Updatable {
/**
* Feeling memory record
*
* @author Tony
*
*/
public static class FeelMemoryRecord {
private final long expireTime;
private Entity damager;
private long timeFelt;
private long timeFeltAgo;
private boolean isValid;
/**
* @param expireTime
*/
public FeelMemoryRecord(long expireTime) {
this.expireTime = expireTime;
this.isValid = false;
}
/**
* Feel the pain
*
* @param timeStep
* @param damager
*/
public void feelDamage(TimeStep timeStep, Entity damager) {
this.damager = damager;
this.timeFelt = timeStep.getGameClock();
this.isValid = true;
}
/**
* @return the isValid
*/
public boolean isValid() {
return isValid;
}
/**
* Checks if this memory record has expired
*
* @param timeStep
*/
public void checkExpired(TimeStep timeStep) {
this.timeFeltAgo = timeStep.getGameClock() - this.timeFelt;
if(isExpired(timeStep)) {
expire();
}
}
/**
* Expire this record
*/
public void expire() {
this.damager = null;
this.isValid = false;
}
/**
* If this entity is expired
*
* @param timeStep
* @return
*/
public boolean isExpired(TimeStep timeStep) {
return this.damager == null ||
(timeStep.getGameClock() - this.timeFelt > this.expireTime);
}
/**
* @return the damager
*/
public Entity getDamager() {
return damager;
}
/**
* @return the timeFelt
*/
public long getTimeFelt() {
return timeFelt;
}
/**
* @return the timeFeltAgo
*/
public long getTimeFeltAgo() {
return timeFeltAgo;
}
}
private FeelMemoryRecord[] feelingRecords;
/**
*
*/
public FeelMemory(long expireTime) {
this.feelingRecords = new FeelMemoryRecord[SeventhConstants.MAX_PLAYERS];
for(int i = 0; i < this.feelingRecords.length; i++) {
this.feelingRecords[i] = new FeelMemoryRecord(expireTime);
}
}
/* (non-Javadoc)
* @see seventh.shared.Updatable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
updateFeelingMemory(timeStep);
}
/**
* Expire this memory
*/
public void clear() {
for(int i = 0; i < this.feelingRecords.length; i++) {
this.feelingRecords[i].expire();
}
}
private void updateFeelingMemory(TimeStep timeStep) {
for(int i = 0; i < this.feelingRecords.length; i++) {
this.feelingRecords[i].checkExpired(timeStep);
}
}
/**
* @return the feel records
*/
public FeelMemoryRecord[] getFeelRecords() {
return feelingRecords;
}
/**
* Feel damage
*
* @param timeStep
* @param event
*/
public void feel(TimeStep timeStep, Entity damager) {
long oldest = 0;
int oldestIndex = 0;
for(int i = 0; i < this.feelingRecords.length; i++) {
if(!this.feelingRecords[i].isValid()) {
oldestIndex = i;
break;
}
else {
/* replace with oldest sound */
if( oldest < this.feelingRecords[i].getTimeFeltAgo()) {
oldest = this.feelingRecords[i].getTimeFeltAgo();
oldestIndex = i;
}
}
}
this.feelingRecords[oldestIndex].feelDamage(timeStep, damager);
}
}
| 4,619 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SoundMemory.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/memory/SoundMemory.java | /*
* see license.txt
*/
package seventh.ai.basic.memory;
import java.util.List;
import seventh.game.SoundEventPool;
import seventh.game.entities.PlayerEntity;
import seventh.game.events.SoundEmittedEvent;
import seventh.math.Vector2f;
import seventh.shared.SeventhConstants;
import seventh.shared.SoundType;
import seventh.shared.TimeStep;
import seventh.shared.Updatable;
/**
* Sound memory -- what this bot has heard, we store in a small cache so that he doesn't immediately forget the
* world around him
*
*
* @author Tony
*
*/
public class SoundMemory implements Updatable {
/**
* Record of a sound
*
* @author Tony
*
*/
public static class SoundMemoryRecord {
private final long expireTime;
private long timeHeard;
private long timeHeardAgo;
private SoundEmittedEvent sound;
private boolean isValid;
/**
* @param expireTime
*/
public SoundMemoryRecord(long expireTime) {
this.expireTime = expireTime;
this.isValid = false;
this.sound = new SoundEmittedEvent(this, 0, SoundType.MUTE, new Vector2f());
}
/**
* See a {@link PlayerEntity}
*
* @param timeStep
* @param entity
*/
public void hearSound(TimeStep timeStep, SoundEmittedEvent sound) {
this.timeHeard = timeStep.getGameClock();
this.sound.setId(sound.getId());
this.sound.setPos(sound.getPos());
this.sound.setSoundType(sound.getSoundType());
this.sound.setSource(sound.getSource());
this.isValid = true;
}
/**
* @return the isValid
*/
public boolean isValid() {
return isValid;
}
/**
* Checks if this memory record has expired
*
* @param timeStep
*/
public void checkExpired(TimeStep timeStep) {
this.timeHeardAgo = timeStep.getGameClock() - this.timeHeard;
if(isExpired(timeStep)) {
expire();
}
}
/**
* Expire this record
*/
public void expire() {
this.sound.setId(-1);
this.sound.setSoundType(SoundType.MUTE);
this.isValid = false;
}
/**
* If this sound is expired
*
* @param timeStep
* @return
*/
public boolean isExpired(TimeStep timeStep) {
return (timeStep.getGameClock() - this.timeHeard > this.expireTime);
}
/**
* @return the sound
*/
public SoundEmittedEvent getSound() {
return sound;
}
/**
* @return the timeHeard
*/
public long getTimeHeard() {
return timeHeard;
}
/**
* @return the timeHeardAgo
*/
public long getTimeHeardAgo() {
return timeHeardAgo;
}
}
private SoundMemoryRecord[] soundRecords;
/**
*
*/
public SoundMemory(long expireTime) {
this.soundRecords = new SoundMemoryRecord[SeventhConstants.MAX_SOUNDS*3];
for(int i = 0; i < this.soundRecords.length; i++) {
this.soundRecords[i] = new SoundMemoryRecord(expireTime);
}
}
/* (non-Javadoc)
* @see seventh.shared.Updatable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
updateSoundMemory(timeStep);
}
/**
* Expire this memory
*/
public void clear() {
for(int i = 0; i < this.soundRecords.length; i++) {
this.soundRecords[i].expire();
}
}
/**
* @return the soundRecords
*/
public SoundMemoryRecord[] getSoundRecords() {
return soundRecords;
}
/**
* Expire the sounds
*
* @param timeStep
*/
private void updateSoundMemory(TimeStep timeStep) {
for(int i = 0; i < this.soundRecords.length; i++) {
this.soundRecords[i].checkExpired(timeStep);
}
}
/**
* Hear sounds
*
* @param timeStep
* @param sounds
*/
public void hear(TimeStep timeStep, List<SoundEmittedEvent> sounds) {
for(int i = 0; i < sounds.size(); i++) {
SoundEmittedEvent sound = sounds.get(i);
hear(timeStep, sound);
}
}
/**
* Hear sounds
*
* @param timeStep
* @param sounds
*/
public void hear(TimeStep timeStep, SoundEventPool pool) {
for(int i = 0; i < pool.numberOfSounds(); i++) {
SoundEmittedEvent sound = pool.getSound(i);
hear(timeStep, sound);
}
}
/**
* Hear a sound
*
* @param timeStep
* @param event
*/
public void hear(TimeStep timeStep, SoundEmittedEvent event) {
long oldest = 0;
int oldestIndex = 0;
for(int i = 0; i < this.soundRecords.length; i++) {
if(!this.soundRecords[i].isValid()) {
oldestIndex = i;
break;
}
else {
/* replace with oldest sound */
if( oldest < this.soundRecords[i].getTimeHeardAgo()) {
oldest = this.soundRecords[i].getTimeHeardAgo();
oldestIndex = i;
}
}
}
this.soundRecords[oldestIndex].hearSound(timeStep, event);
}
}
| 5,844 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AIGroupAction2.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/group/AIGroupAction2.java | /*
* see license.txt
*/
package seventh.ai.basic.group;
import seventh.ai.basic.actions.Action;
import seventh.shared.Updatable;
/**
* Assigns {@link Action} to each member in the {@link AIGroup}
*
* @author Tony
*
*/
public abstract class AIGroupAction2 implements Updatable {
public abstract void start(AIGroup aIGroup);
public abstract void end(AIGroup aIGroup);
public abstract void cancel(AIGroup aIGroup);
public abstract boolean isFinished(AIGroup aIGroup);
}
| 498 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AIGroup.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/group/AIGroup.java | /*
* see license.txt
*/
package seventh.ai.basic.group;
import seventh.ai.basic.Brain;
import seventh.ai.basic.DefaultAISystem;
import seventh.ai.basic.World;
import seventh.ai.basic.teamstrategy.Roles;
import seventh.game.PlayerInfo;
import seventh.shared.SeventhConstants;
import seventh.shared.TimeStep;
import seventh.shared.Updatable;
/**
* Represents a small AI Group of bots that can take on team work type activities
*
* @author Tony
*
*/
public class AIGroup implements Updatable {
private DefaultAISystem aiSystem;
private Brain[] members;
private Roles roles;
private AIGroupAction aIGroupAction;
private int size;
/**
*
*/
public AIGroup(DefaultAISystem aiSystem) {
this.aiSystem = aiSystem;
this.members = new Brain[SeventhConstants.MAX_PLAYERS];
this.roles = new Roles();
}
/**
* @return the roles
*/
public Roles getRoles() {
return roles;
}
public void addMember(Brain bot) {
if(bot.getPlayer().isAlive()) {
if(this.members[bot.getPlayer().getId()] == null) {
this.size++;
}
this.members[bot.getPlayer().getId()] = bot;
}
}
public boolean inGroup(Brain bot) {
for(int i = 0; i < this.members.length; i++) {
Brain member = this.members[i];
if(member.getPlayer().getId() == bot.getPlayer().getId()) {
return true;
}
}
return false;
}
public int groupSize() {
return size;
}
public World getWorld() {
return this.aiSystem.getWorld();
}
/**
* @return the aiSystem
*/
public DefaultAISystem getAISystem() {
return aiSystem;
}
/**
* @return the members
*/
public Brain[] getMembers() {
return members;
}
public void doAction(AIGroupAction action) {
if(this.aIGroupAction!=null) {
this.aIGroupAction.cancel(this);
}
this.aIGroupAction = action;
this.aIGroupAction.start(this);
}
/* (non-Javadoc)
* @see seventh.shared.Updatable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
if(this.aIGroupAction != null) {
this.aIGroupAction.update(timeStep);
if(this.aIGroupAction.isFinished(this)) {
this.aIGroupAction.end(this);
this.aIGroupAction = null;
}
}
}
public void onPlayerKilled(PlayerInfo player) {
this.members[player.getId()] = null;
if(this.size>0) {
this.size--;
}
this.roles.removeDeadPlayer(player);
}
}
| 2,816 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AIGroupDefendAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/group/AIGroupDefendAction.java | /*
* see license.txt
*/
package seventh.ai.basic.group;
import java.util.ArrayList;
import java.util.List;
import seventh.ai.basic.AttackDirection;
import seventh.ai.basic.Brain;
import seventh.ai.basic.World;
import seventh.ai.basic.actions.Action;
import seventh.ai.basic.actions.WaitAction;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class AIGroupDefendAction extends AIGroupAction {
private Vector2f defendPosition;
private List<AttackDirection> directionsToDefend;
/**
* @param position
*/
public AIGroupDefendAction(Vector2f position) {
this.defendPosition = position;
this.directionsToDefend = new ArrayList<>();
}
@Override
public void start(AIGroup aIGroup) {
World world = aIGroup.getWorld();
float radius = (float)world.getRandom().getRandomRange(100f, 150f);
directionsToDefend.addAll(world.getAttackDirections(this.defendPosition, radius, 12));
}
/* (non-Javadoc)
* @see seventh.ai.basic.group.AIGroupAction#getAction(seventh.ai.basic.group.AIGroup)
*/
@Override
public Action getAction(AIGroup aIGroup) {
if(aIGroup.groupSize() > 0 ) {
World world = aIGroup.getWorld();
Brain[] members = aIGroup.getMembers();
// Roles roles = aIGroup.getRoles();
int squadSize = aIGroup.groupSize();
if(!directionsToDefend.isEmpty() && squadSize>0) {
int increment = 1;
if(directionsToDefend.size()> squadSize) {
increment = directionsToDefend.size() / squadSize;
}
int i = 0;
for(int j = 0; j < members.length; j++) {
Brain member = members[j];
if(member!=null) {
//if(roles.getAssignedRole(member.getPlayer()) != Role.None)
{
AttackDirection dir = directionsToDefend.get( (i += increment) % directionsToDefend.size());
Vector2f position = new Vector2f(dir.getDirection());
//Vector2f.Vector2fMA(defendPosition, dir.getDirection(), 10f + world.getRandom().nextInt(100), position);
return (world.getGoals().guard(position));
}
}
}
}
}
return new WaitAction(500);
}
/* (non-Javadoc)
* @see seventh.ai.basic.group.AIGroupAction#end(seventh.ai.basic.group.AIGroup)
*/
@Override
public void end(AIGroup aIGroup) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.group.AIGroupAction#cancel(seventh.ai.basic.group.AIGroup)
*/
@Override
public void cancel(AIGroup aIGroup) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.group.AIGroupAction#isFinished(seventh.ai.basic.group.AIGroup)
*/
@Override
public boolean isFinished(AIGroup aIGroup) {
return false;
}
/* (non-Javadoc)
* @see seventh.shared.Updatable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
}
}
| 3,353 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AIGroupMember.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/group/AIGroupMember.java | /*
* see license.txt
*/
package seventh.ai.basic.group;
import seventh.ai.basic.Brain;
/**
* @author Tony
*
*/
public class AIGroupMember {
public static enum Role {
LEADER,
LEFT_FLANK,
RIGHT_FLANK,
REAR_FLANK,
}
private Role type;
private Brain bot;
/**
*
*/
public AIGroupMember(Brain brain, Role type) {
this.bot = brain;
this.type = type;
}
/**
* @return the bot
*/
public Brain getBot() {
return bot;
}
public Role getRole() {
return this.type;
}
}
| 612 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AIGroupAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/group/AIGroupAction.java | /*
* see license.txt
*/
package seventh.ai.basic.group;
import seventh.ai.basic.actions.Action;
import seventh.shared.Updatable;
/**
* @author Tony
*
*/
public abstract class AIGroupAction implements Updatable {
public abstract void start(AIGroup aIGroup);
public abstract void end(AIGroup aIGroup);
public abstract void cancel(AIGroup aIGroup);
public abstract boolean isFinished(AIGroup aIGroup);
public abstract Action getAction(AIGroup aIGroup);
}
| 481 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AIGroupAttackAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/group/AIGroupAttackAction.java | /*
* see license.txt
*/
package seventh.ai.basic.group;
import java.util.ArrayList;
import java.util.List;
import seventh.ai.basic.AttackDirection;
import seventh.ai.basic.Brain;
import seventh.ai.basic.World;
import seventh.ai.basic.actions.Action;
import seventh.ai.basic.actions.SequencedAction;
import seventh.ai.basic.actions.WaitAction;
import seventh.ai.basic.teamstrategy.Roles;
import seventh.ai.basic.teamstrategy.Roles.Role;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class AIGroupAttackAction extends AIGroupAction {
private Vector2f attackPosition;
private List<AttackDirection> attackDirections;
/**
* @param position
*/
public AIGroupAttackAction(Vector2f position) {
this.attackPosition = position;
this.attackDirections = new ArrayList<>();
}
@Override
public void start(AIGroup aIGroup) {
World world = aIGroup.getWorld();
this.attackDirections.addAll(world.getAttackDirections(attackPosition, 150f, aIGroup.groupSize()));
if(attackDirections.isEmpty()) {
attackDirections.add(new AttackDirection(attackPosition));
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.group.AIGroupAction#getAction(seventh.ai.basic.group.AIGroup)
*/
@Override
public Action getAction(AIGroup aIGroup) {
if(aIGroup.groupSize()>0) {
World world = aIGroup.getWorld();
Brain[] members = aIGroup.getMembers();
Roles roles = aIGroup.getRoles();
int j = 0;
for(int i = 0; i < members.length; i++) {
Brain member = members[i];
if(member!=null) {
if(roles.getAssignedRole(member.getPlayer()) != Role.None) {
AttackDirection dir = attackDirections.get( (j+=1) % attackDirections.size());
return new SequencedAction("squadAttack")
.addNext(world.getGoals().moveToAction(dir.getDirection()));
}
}
}
}
return new WaitAction(500);
}
/* (non-Javadoc)
* @see seventh.ai.basic.group.AIGroupAction#end(seventh.ai.basic.group.AIGroup)
*/
@Override
public void end(AIGroup aIGroup) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.group.AIGroupAction#cancel(seventh.ai.basic.group.AIGroup)
*/
@Override
public void cancel(AIGroup aIGroup) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.group.AIGroupAction#isFinished(seventh.ai.basic.group.AIGroup)
*/
@Override
public boolean isFinished(AIGroup aIGroup) {
return false;
}
/* (non-Javadoc)
* @see seventh.shared.Updatable#update(seventh.shared.TimeStep)
*/
@Override
public void update(TimeStep timeStep) {
}
}
| 2,986 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SequencedAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/SequencedAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import seventh.ai.basic.Brain;
/**
* @author Tony
*
*/
public class SequencedAction extends CompositeAction {
private boolean started;
/**
* @param name
*/
public SequencedAction(String name) {
super(name);
this.started = false;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.CompositeAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
super.start(brain);
this.started = true;
}
public SequencedAction addNext(Action action) {
this.addLastAction(action);
return this;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Goal#isFinished(seventh.ai.basic.Brain)
*/
@Override
public boolean isFinished(Brain brain) {
if(!this.started) {
return false;
}
Action action = this.currentAction();
if(action!=null && action.isFinished(brain)) {
if(action.getActionResult().isFailure()) {
getActionResult().setFailure();
cancel();
return true;
}
}
return super.isFinished(brain);
}
}
| 1,269 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AdapterAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/AdapterAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import seventh.ai.basic.Brain;
import seventh.shared.TimeStep;
/**
* An empty implementation for ease of inheritance use.
*
* @author Tony
*
*/
public class AdapterAction implements Action {
private ActionResult result;
/**
*/
public AdapterAction() {
this.result = new ActionResult();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Action#cancel()
*/
@Override
public void cancel() {
}
/* (non-Javadoc)
* @see seventh.ai.basic.Action#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.Action#end(seventh.ai.basic.Brain)
*/
@Override
public void end(Brain brain) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.Action#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return true;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Action#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Action#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Action#getActionResult()
*/
@Override
public ActionResult getActionResult() {
return this.result;
}
/* (non-Javadoc)
* @see seventh.ai.basic.Action#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
me.add("type", getClass().getSimpleName());
return me;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 2,190 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Actions.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/Actions.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import java.util.ArrayList;
import java.util.List;
import leola.vm.Leola;
import leola.vm.lib.LeolaMethod;
import leola.vm.types.LeoArray;
import leola.vm.types.LeoObject;
import seventh.ai.AISystem;
import seventh.ai.basic.AIConfig;
import seventh.ai.basic.AttackDirection;
import seventh.ai.basic.Brain;
import seventh.ai.basic.Cover;
import seventh.ai.basic.DefaultAISystem;
import seventh.ai.basic.Zone;
import seventh.ai.basic.actions.atom.AvoidMoveToAction;
import seventh.ai.basic.actions.atom.DefendAttackDirectionsAction;
import seventh.ai.basic.actions.atom.DefendZoneAction;
import seventh.ai.basic.actions.atom.DefuseBombAction;
import seventh.ai.basic.actions.atom.EnterVehicleAction;
import seventh.ai.basic.actions.atom.EvaluateAttackDirectionsAction;
import seventh.ai.basic.actions.atom.FindClosestBombTarget;
import seventh.ai.basic.actions.atom.FindSafeDistanceFromActiveBombAction;
import seventh.ai.basic.actions.atom.FollowEntityAction;
import seventh.ai.basic.actions.atom.GuardAction;
import seventh.ai.basic.actions.atom.GuardUntilAction;
import seventh.ai.basic.actions.atom.HandleDoorAction;
import seventh.ai.basic.actions.atom.MoveToAction;
import seventh.ai.basic.actions.atom.MoveToBombAction;
import seventh.ai.basic.actions.atom.MoveToBombTargetToPlantAction;
import seventh.ai.basic.actions.atom.MoveToFlagAction;
import seventh.ai.basic.actions.atom.MoveToVehicleAction;
import seventh.ai.basic.actions.atom.PlantBombAction;
import seventh.ai.basic.actions.atom.SecureZoneAction;
import seventh.ai.basic.actions.atom.SupressFireUntilAction;
import seventh.ai.basic.actions.atom.body.LookAtAction;
import seventh.ai.basic.actions.atom.body.MoveAction;
import seventh.ai.basic.actions.atom.body.ShootAction;
import seventh.ai.basic.actions.evaluators.DoNothingEvaluator;
import seventh.ai.basic.actions.evaluators.GrenadeEvaluator;
import seventh.ai.basic.actions.evaluators.MeleeEvaluator;
import seventh.ai.basic.actions.evaluators.MoveTowardEnemyEvaluator;
import seventh.ai.basic.actions.evaluators.ShootWeaponEvaluator;
import seventh.ai.basic.actions.evaluators.StayStillEvaluator;
import seventh.ai.basic.actions.evaluators.TakeCoverEvaluator;
import seventh.game.PlayerInfo;
import seventh.game.entities.BombTarget;
import seventh.game.entities.Door;
import seventh.game.entities.Flag;
import seventh.game.entities.PlayerEntity;
import seventh.game.entities.vehicles.Vehicle;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
import seventh.shared.Randomizer;
/**
* A factory for creating compound Actions
*
* @author Tony
*
*/
public class Actions {
private Leola runtime;
private Randomizer random;
private AIConfig config;
private DefaultAISystem aiSystem;
/**
* @param aiSystem
* @param runtime
*/
public Actions(AISystem aiSystem, Leola runtime) {
this.aiSystem = (DefaultAISystem)aiSystem;
this.runtime = runtime;
this.random = aiSystem.getRandomizer();
this.config = aiSystem.getConfig();
}
/*--------------------------------------------------------------------------
* Factory of Atom Actions
--------------------------------------------------------------------------*/
public Action shootAtAction(Vector2f destination) {
return new SequencedAction("shootAt")
.addNext(new LookAtAction(destination))
.addNext(new ShootAction());
}
public MoveToAction moveToAction(Vector2f destination) {
return new MoveToAction(destination);
}
public AvoidMoveToAction avoidMoveToAction(Vector2f destination, LeoArray zonesToAvoid) {
List<Zone> zones = new ArrayList<>(zonesToAvoid.size());
for(LeoObject obj : zonesToAvoid) {
zones.add( (Zone)obj.getValue());
}
return new AvoidMoveToAction(destination, zones);
}
public MoveToFlagAction moveToFlagAction(Flag flag) {
return new MoveToFlagAction(flag);
}
public SecureZoneAction secureZoneAction(Zone zone) {
return new SecureZoneAction(zone);
}
public DefendZoneAction defendZoneAction(Zone zone) {
return new DefendZoneAction(zone);
}
public MoveToBombAction moveToBombAction(BombTarget bomb) {
return new MoveToBombAction(bomb);
}
public MoveToBombTargetToPlantAction moveToBombTargetToPlantAction(BombTarget bomb) {
return new MoveToBombTargetToPlantAction(bomb);
}
public HandleDoorAction handleDoorAction(Door door) {
return new HandleDoorAction(door);
}
public PlantBombAction plantBombAction(BombTarget bomb) {
return new PlantBombAction(bomb);
}
public DefuseBombAction defuseBombAction(BombTarget bomb) {
return new DefuseBombAction(bomb);
}
public FindClosestBombTarget findClosestBombTargetToPlant() {
return new FindClosestBombTarget(false);
}
public FindClosestBombTarget findClosestBombTargetToDefuse() {
return new FindClosestBombTarget(true);
}
public FindSafeDistanceFromActiveBombAction findSafeDistanceFromActiveBombAction(BombTarget target) {
return new FindSafeDistanceFromActiveBombAction(target);
}
public EvaluateAttackDirectionsAction evaluateAttackDirectionsAction() {
return new EvaluateAttackDirectionsAction();
}
public DefendAttackDirectionsAction defendAttackDirectionsAction(List<AttackDirection> attackDirs, long timeToDefend) {
return new DefendAttackDirectionsAction(attackDirs, timeToDefend);
}
public WaitAction waitAction(long timeToWaitMSec) {
return new WaitAction(timeToWaitMSec);
}
public GuardAction guardAction() {
return new GuardAction();
}
public GuardUntilAction guardUntilAction(LeoObject isFinished) {
return new GuardUntilAction(isFinished);
}
public SupressFireUntilAction supressFireUntilAction(Vector2f target, LeoObject isFinished) {
return new SupressFireUntilAction(isFinished, target);
}
/**
* Get an {@link Action} defined in a {@link Leola} script
*
* @param action
* @return the {@link Action} if found, otherwise this will return a {@link WaitAction}
*/
@LeolaMethod(alias="action")
public Action getScriptedAction(String action) {
LeoObject actionFunction = runtime.get(action);
if(LeoObject.isTrue(actionFunction)) {
LeoObject gen = actionFunction.call();
ScriptedAction goal = new ScriptedAction(action, gen );
return goal;
}
return new WaitAction(1_000);
}
public Action defuseBomb() {
return getScriptedAction("defuseBomb");
}
public Action plantBomb() {
return getScriptedAction("plantBomb");
}
public Action infiltrate(Zone zone) {
Action action = getScriptedAction("infiltrate");
action.getActionResult().setValue(zone);
return action;
}
public Action defend(Zone zone) {
Action action = getScriptedAction("defend");
action.getActionResult().setValue(zone);
return action;
}
public Action defendLeader(PlayerInfo leader) {
//Action action = getScriptedAction("defendLeader");
//action.getActionResult().setValue(leader.getEntityOwner());
if(leader.isAlive()) {
Zone zone = this.aiSystem.getZones().getZone(leader.getEntity().getCenterPos());
return defend(zone);
}
return waitAction(1000);
}
public Action defendPlantedBomb(BombTarget target) {
Action action = getScriptedAction("defendPlantedBomb");
action.getActionResult().setValue(target);
return action;
}
public Action moveToRandomSpot(Brain brain) {
return new MoveAction(brain.getWorld().getRandomSpot(brain.getEntityOwner()));
}
public Action takeCover(Vector2f attackDir) {
Action action = getScriptedAction("takeCover");
action.getActionResult().setValue(attackDir);
return new ConcurrentAction(action, new WeightedAction(this.config, "moveToCover",
new ShootWeaponEvaluator(this, random.getRandomRangeMin(0.8), 0.8),
new MeleeEvaluator(this, random.getRandomRange(0.2, 0.4), 0),
new DoNothingEvaluator(this, random.getRandomRangeMin(0.3), 0),
new GrenadeEvaluator(this, random.getRandomRangeMin(0.5), 0)
));
}
public Action moveToCover(Cover cover) {
Action action = getScriptedAction("moveToCover");
action.getActionResult().setValue(cover);
return new ConcurrentAction(action, new WeightedAction(config, "moveToCover",
new ShootWeaponEvaluator(this, random.getRandomRangeMin(0.93), 0.8),
new MeleeEvaluator(this, 1, 0),
new DoNothingEvaluator(this, random.getRandomRange(0.1, 0.25), 0),
new GrenadeEvaluator(this, random.getRandomRangeMin(0.5), 0)
));
}
public Action operateVehicle(Vehicle vehicle) {
CompositeAction goal = new SequencedAction("operateVehicle");
goal.addLastAction(new MoveToVehicleAction(vehicle));
goal.addLastAction(new EnterVehicleAction(vehicle));
return goal;
}
public Action wander() {
Action action = getScriptedAction("wander");
return action;
}
public Action attackEnemy(PlayerEntity enemy) {
return decideAttackMethod();
}
public Action chargeEnemy(PlayerEntity enemy) {
return new ConcurrentAction(decideAttackMethod(), new FollowEntityAction(enemy)
/*, new WeightedGoal(brain, new DodgeEvaluator(goals, brain.getRandomRange(0.4, 0.8)),
new DoNothingEvaluator(goals, brain.getRandomRange(0, 0)) )
*/
);
}
/**
* Goal which decides which attack method to use
*
* @param goals
* @param brain
* @return the goal
*/
public CompositeAction decideAttackMethod() {
return new WeightedAction(config, "decideAttackMethod",
//new DoNothingEvaluator(goals, 1, 1)
new ShootWeaponEvaluator(this, random.getRandomRangeMin(0.8), 0.8),
new MeleeEvaluator(this, random.getRandomRangeMin(0.95), 0),
new GrenadeEvaluator(this, random.getRandomRangeMin(0.2), 0.2)
);
}
public CompositeAction enemyEncountered() {
return new WeightedAction(config, "enemyEncountered",
new StayStillEvaluator(this, random.getRandomRangeMin(0.31), 0.3),
new MoveTowardEnemyEvaluator(this, random.getRandomRangeMin(0.68), 0.8),
new TakeCoverEvaluator(this, random.getRandomRangeMin(0.21), 0.7)
);
}
public Action surpressFire(Vector2f position) {
// return new WeightedGoal(brain, "surpressFire",
//// new MoveTowardEnemyEvaluator(goals, brain.getRandomRangeMin(0.4), 0.8),
// new SurpressFireEvaluator(goals, brain.getRandomRangeMin(0.3), 0.9, position)
// );
Action action = getScriptedAction("surpressFire");
action.getActionResult().setValue(position);
return action;
}
public Action guard(Vector2f position) {
SequencedAction goal = new SequencedAction("guard: " + position);
return goal.addNext(new MoveToAction(position)).addNext(new GuardAction());
}
public Action returnFlag(Flag flag) {
SequencedAction goal = new SequencedAction("returnFlag: " + flag.getType());
// TODO
return goal.addNext(new MoveToFlagAction(flag));
}
public Action captureFlag(Flag flag, Vector2f homebase) {
SequencedAction goal = new SequencedAction("captureFlag: " + flag.getType());
Zone flagZone = aiSystem.getWorld().getZone(flag.getSpawnLocation());
Zone homeBaseZone = aiSystem.getWorld().getZone(homebase);
List<Zone> zonesToAvoid = new ArrayList<>();
Zone[] zones = aiSystem.getStats().getTop5DeadliesZones();
for(int i = 0; i < zones.length;i++) {
Zone zone = zones[i];
if(zone!=null&&flagZone!=zone&&homeBaseZone!=zone) {
zonesToAvoid.add(zone);
}
}
//AvoidMoveToAction
return goal.addNext(new MoveToFlagAction(flag, zonesToAvoid))
.addNext(new AvoidMoveToAction(homebase, zonesToAvoid));
}
public Action defendFlag(Flag flag, Rectangle homebase) {
SequencedAction goal = new SequencedAction("defendFlag: " + flag.getType());
return goal.addNext(new MoveToFlagAction(flag)); // TODO .addNext(defend(zone));
}
}
| 13,353 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DecoratorAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/DecoratorAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import seventh.ai.basic.Brain;
import seventh.shared.TimeStep;
/**
* Allows for wrapping an action
*
* @author Tony
*
*/
public class DecoratorAction extends AdapterAction {
private Action action;
private Brain brain;
public DecoratorAction(Brain brain) {
this(brain, null);
}
/**
* @param the decorated action
*/
public DecoratorAction(Brain brain, Action action) {
super();
this.brain = brain;
setAction(action);
}
/**
* @param action the action to set
*/
public void setAction(Action action) {
// if(hasAction()) {
// this.action.end(brain);
// }
this.action = action;
if(this.action != null) {
this.action.start(brain);
}
}
/**
* @return the action
*/
public Action getAction() {
return action;
}
/**
* Determines if this is of another type of Action
* @param action
* @return true if the current action is of the supplied type
*/
public boolean is(Class<? extends Action> action) {
if(hasAction()) {
return this.action.getClass().equals(action);
}
return false;
}
/**
* @return true if there is an action bound
*/
public boolean hasAction() {
return this.action != null && !this.action.isFinished(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.Action#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
if(this.action != null) {
this.action.start(brain);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.Action#end(seventh.ai.basic.Brain)
*/
@Override
public void end(Brain brain) {
if(this.action != null) {
this.action.end(brain);
}
this.action = null;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
if(this.action != null) {
this.action.interrupt(brain);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
if(this.action != null) {
this.action.resume(brain);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#getActionResult()
*/
@Override
public ActionResult getActionResult() {
if(this.action != null) {
return this.action.getActionResult();
}
return super.getActionResult();
}
/* (non-Javadoc)
* @see seventh.ai.basic.Action#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return this.action != null ? this.action.isFinished(brain) : true;
}
/* (non-Javadoc)
* @see seventh.ai.basic.Action#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
if(this.action != null) {
this.action.update(brain, timeStep);
}
}
@Override
public DebugInformation getDebugInformation() {
return action != null ? action.getDebugInformation() : super.getDebugInformation();
}
}
| 3,557 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
TimedAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/TimedAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import seventh.ai.basic.Brain;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class TimedAction extends WaitAction {
/**
*
*/
public TimedAction(long timeToWait) {
super(timeToWait);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
super.update(brain, timeStep);
doAction(brain, timeStep);
}
/**
* Do the action
*
* @param brain
* @param timeStep
*/
protected void doAction(Brain brain, TimeStep timeStep) {
}
}
| 764 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
WaitAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/WaitAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import seventh.ai.basic.Brain;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class WaitAction extends AdapterAction {
private final long timeToWait;
private long currentWaitTime;
/**
*
*/
public WaitAction(long timeToWait) {
this.timeToWait = timeToWait;
this.currentWaitTime = 0;
}
public void reset() {
this.currentWaitTime = 0;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
this.currentWaitTime += timeStep.getDeltaTime();
if(isFinished(brain)) {
this.getActionResult().setSuccess();
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return this.currentWaitTime > this.timeToWait;
}
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation()
.add("timeToWait", this.timeToWait)
.add("currentWaitTime", this.currentWaitTime);
}
}
| 1,323 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ConcurrentAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/ConcurrentAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import java.util.ArrayList;
import java.util.List;
import seventh.ai.basic.Brain;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class ConcurrentAction implements Action {
private List<Action> concurrentActions;
private ActionResult result;
/**
*
*/
public ConcurrentAction(Action ... concurrentActions) {
this.concurrentActions = new ArrayList<Action>();
for(Action a : concurrentActions) {
this.concurrentActions.add(a);
}
this.result = new ActionResult();
}
/**
* @param index
* @return the Action
*/
public Action getAction(int index) {
if(index > -1 && index <this.concurrentActions.size())
return this.concurrentActions.get(index);
return null;
}
/**
* Adds a concurrent action
* @param action
*/
public void addConcurrentAction(Action action) {
this.concurrentActions.add(action);
}
/**
* Removes all concurrent actions
*/
public void cancel() {
int size = this.concurrentActions.size();
for(int i = 0; i < size; i++) {
this.concurrentActions.get(i).cancel();
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Goal#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
int size = this.concurrentActions.size();
for(int i = 0; i < size; i++) {
this.concurrentActions.get(i).start(brain);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Action#end(seventh.ai.basic.Brain)
*/
@Override
public void end(Brain brain) {
int size = this.concurrentActions.size();
for(int i = 0; i < size; i++) {
this.concurrentActions.get(i).end(brain);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Action#isFinished(seventh.ai.basic.Brain)
*/
@Override
public boolean isFinished(Brain brain) {
int size = this.concurrentActions.size();
boolean isDone = true;
for(int i = 0; i < size; i++) {
isDone = this.concurrentActions.get(i).isFinished(brain) && isDone;
}
return isDone;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Action#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
int size = this.concurrentActions.size();
for(int i = 0; i < size; i++) {
this.concurrentActions.get(i).interrupt(brain);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Action#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
int size = this.concurrentActions.size();
for(int i = 0; i < size; i++) {
this.concurrentActions.get(i).resume(brain);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Action#getActionResult()
*/
@Override
public ActionResult getActionResult() {
return this.result;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Action#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
int size = this.concurrentActions.size();
for(int i = 0; i < size; i++) {
this.concurrentActions.get(i).update(brain, timeStep);
}
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation info = new DebugInformation();
info.add("goals", this.concurrentActions);
return info;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 4,024 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ActionResult.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/ActionResult.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
/**
* The result of completing an {@link Action}
*
* @author Tony
*
*/
public class ActionResult {
public enum Result {
SUCCESS,
FAILURE,
NONE,
}
private Result result;
/* Any stored value */
private Object value;
/**
* @param result
* @param value
*/
public ActionResult(Result result, Object value) {
this.result = result;
this.value = value;
}
/**
* @param value
*/
public ActionResult(Object value) {
this(Result.SUCCESS, value);
}
/**
*/
public ActionResult() {
this(Result.NONE, null);
}
/**
* Sets this state from the supplied one
* @param r
*/
public void set(ActionResult r) {
this.result = r.result;
this.value = r.value;
}
/**
* @return true if successful
*/
public boolean isSuccessful() {
return result==Result.SUCCESS;
}
/**
* @return true if a failure
*/
public boolean isFailure() {
return result ==Result.FAILURE;
}
public void setSuccess() {
result=Result.SUCCESS;
}
public void setFailure() {
result=Result.FAILURE;
}
public void setSuccess(Object value) {
this.result=Result.SUCCESS;
this.value = value;
}
public void setFailure(Object value) {
this.result=Result.FAILURE;
this.value = value;
}
/**
* @param result the result to set
*/
public void setResult(Result result) {
this.result = result;
}
/**
* @param value the value to set
*/
public void setValue(Object value) {
this.value = value;
}
/**
* @return the result
*/
public Result getResult() {
return result;
}
/**
* @return the value
*/
public Object getValue() {
return value;
}
}
| 2,175 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
WeightedAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/WeightedAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import java.util.ArrayList;
import java.util.List;
import seventh.ai.basic.AIConfig;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.evaluators.ActionEvaluator;
import seventh.ai.basic.actions.evaluators.Evaluators;
import seventh.shared.TimeStep;
import seventh.shared.Timer;
/**
* Determines the best course of action to take based on {@link ActionEvaluator}s
*
*
* @author Tony
*
*/
public class WeightedAction extends CompositeAction {
private List<ActionEvaluator> evaluators;
private Timer updateEval;
private ActionEvaluator currentActiveEvaluator;
private Action currentAction;
/**
*
*/
public WeightedAction(AIConfig config, String name, ActionEvaluator ... evaluators) {
super(name);
this.evaluators = new ArrayList<ActionEvaluator>();
for(ActionEvaluator e : evaluators) {
this.evaluators.add(e);
}
this.updateEval = new Timer(true, config.getEvaluationPollTime());
this.updateEval.start();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Goal#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
this.currentActiveEvaluator = Evaluators.evaluate(brain, evaluators);
replace(this.currentActiveEvaluator.getAction(brain));
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Goal#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
this.updateEval.update(timeStep);
if(this.updateEval.isTime()) {
ActionEvaluator newEvaluator = Evaluators.evaluate(brain, evaluators);
boolean isFinished = isFinished(brain);
if( this.currentActiveEvaluator == null ||
isFinished ||
newEvaluator.isRepeatable() ||
((newEvaluator.getKeepBias() > this.currentActiveEvaluator.getKeepBias() ) &&
(newEvaluator != this.currentActiveEvaluator)) ) {
Action action = newEvaluator.getAction(brain);
if(action!=null && (isFinished||this.currentAction!=action) ) {
this.currentActiveEvaluator = newEvaluator;
if(this.currentActiveEvaluator.isContinuable()) {
interrupt(brain);
addFirstAction(action);
}
else {
this.replace(action);
}
if(newEvaluator.isRepeatable()) {
action.start(brain);
}
this.currentAction = action;
}
}
}
super.update(brain, timeStep);
}
}
| 3,072 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
CompositeAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/CompositeAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;
import seventh.ai.basic.Brain;
import seventh.shared.Debugable;
import seventh.shared.TimeStep;
/**
* Represents a collection of {@link Action}s to be executed.
*
* @author Tony
*
*/
public class CompositeAction extends AdapterAction implements Debugable {
private Deque<Action> actions;
private boolean isFirstAction;
private String name;
/**
*
*/
public CompositeAction(String name) {
this.actions = new ConcurrentLinkedDeque<>();
this.isFirstAction = true;
this.name = name;
}
/**
* Cancels all the actions
*/
@Override
public void cancel() {
this.actions.clear();
}
/**
* Replaces the current actions, with the supplied action
* @param action
*/
public void replace(Action action) {
cancel();
addFirstAction(action);
}
/* (non-Javadoc)
* @see seventh.ai.basic.Action#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
Action action = currentAction();
if(action != null) {
action.interrupt(brain);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
Action action = currentAction();
if(action != null) {
action.resume(brain);
}
}
/**
* Updates the status of the {@link CompositeAction}
*
* @param timeStep
*/
public void update(Brain brain, TimeStep timeStep) {
if(!this.actions.isEmpty()) {
Action action = this.actions.peek();
if(isFirstAction) {
action.start(brain);
isFirstAction = false;
}
if(action.isFinished(brain)) {
action.end(brain);
/* remove this action because the action may have pushed another action on the queue */
this.actions.remove(action);
Action nextAction = this.actions.peek();
if(nextAction != null) {
nextAction.start(brain);
getActionResult().set(nextAction.getActionResult());
}
else {
isFirstAction = true;
getActionResult().set(action.getActionResult());
}
}
else {
action.update(brain, timeStep);
getActionResult().set(action.getActionResult());
}
}
else {
isFirstAction = true;
}
}
/**
* @return the current Action or null if none
*/
public Action currentAction() {
return this.actions.peek();
}
/**
* Adds an {@link Action} to this {@link CompositeAction}
*
* @param action
* @return this Goal for function chaining
*/
public CompositeAction addLastAction(Action action) {
if(action != null) {
this.actions.add(action);
}
return this;
}
/**
* Adds an {@link Action} to the front of this {@link CompositeAction}
*
* @param action
* @return this Goal for function chaining
*/
public CompositeAction addFirstAction(Action action) {
if(action != null) {
this.actions.addFirst(action);
}
return this;
}
/**
* @return the number of actions left to be processed.
*/
public int numberOfActions() {
return this.actions.size();
}
/**
* Clears any pending and current {@link Action}s
*/
public void end(Brain brain) {
if(!this.actions.isEmpty()) {
this.actions.peek().end(brain);
}
this.actions.clear();
}
/* (non-Javadoc)
* @see seventh.ai.basic.Action#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return this.actions.isEmpty();
}
/* (non-Javadoc)
* @see seventh.shared.Debugable#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
me.add("name", this.name);
me.add("actions", this.actions.peek());
return me;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return getDebugInformation().toString();
}
}
| 5,014 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ScriptedAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/ScriptedAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import leola.vm.Leola;
import leola.vm.types.LeoObject;
import seventh.ai.basic.Brain;
import seventh.shared.Cons;
import seventh.shared.TimeStep;
/**
* Allows for scripting actions
*
* @author Tony
*
*/
public class ScriptedAction extends AdapterAction {
private CompositeAction goal;
private LeoObject goalFunction;
private boolean isFunctionDone;
private String name;
/**
* @param name
* @param goalFunction
*/
public ScriptedAction(String name, LeoObject goalFunction) {
this.goalFunction = goalFunction;
this.name = name;
this.goal = new CompositeAction(name);
this.isFunctionDone = false;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
goal.interrupt(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
goal.resume(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
goal.update(brain, timeStep);
if(goal.isFinished(brain)) {
try {
LeoObject result = goalFunction.xcall(Leola.toLeoObject(brain), Leola.toLeoObject(goal), Leola.toLeoObject(goal.getActionResult()));
if(!LeoObject.isTrue(result)) {
this.isFunctionDone = true;
}
else {
Object obj = result.getValue();
if(obj instanceof Action) {
Action newAction = (Action)obj;
goal.addFirstAction(newAction);
}
}
}
catch(Throwable e) {
Cons.println("Unable to execute scripted goal: " + e);
}
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished(seventh.ai.basic.Brain)
*/
@Override
public boolean isFinished(Brain brain) {
return goal.isFinished(brain) && this.isFunctionDone;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#getActionResult()
*/
@Override
public ActionResult getActionResult() {
return goal.getActionResult();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
DebugInformation me = new DebugInformation();
me.add("type", this.name);
me.add("goal", this.goal);
return me;
}
}
| 2,951 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
QuickWeightedAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/QuickWeightedAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.evaluators.ActionEvaluator;
import seventh.ai.basic.actions.evaluators.Evaluators;
/**
* Determines the best course of action to take based on {@link ActionEvaluator}s. It will
* make a decision once and that is it.
*
*
* @author Tony
*
*/
public class QuickWeightedAction extends CompositeAction {
private ActionEvaluator[] evaluators;
private ActionEvaluator currentActiveEvaluator;
/**
* @param brain
* @param name
* @param evaluators
*/
public QuickWeightedAction(Brain brain, String name, ActionEvaluator ... evaluators) {
super(name);
this.evaluators = evaluators;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.Goal#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
this.currentActiveEvaluator = Evaluators.evaluate(brain, evaluators);
replace(this.currentActiveEvaluator.getAction(brain));
}
}
| 1,089 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Action.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/Action.java | /*
* see license.txt
*/
package seventh.ai.basic.actions;
import seventh.ai.basic.Brain;
import seventh.shared.Debugable;
import seventh.shared.TimeStep;
/**
* An action a bot can take, such as Follow someone, attack, etc.
*
* @author Tony
*
*/
public interface Action extends Debugable {
/**
* Cancels this action
*/
public void cancel();
/**
* Starts the action, only invoked once upon starting the
* action.
*
* @param brain
*/
public void start(Brain brain);
/**
* Ends the action, only invoked when isFinished returns true.
*
* @param brain
*/
public void end(Brain brain);
/**
* @return true if the action is completed
*/
public boolean isFinished(Brain brain);
/**
* Interrupts this {@link Action}, allows it to halt
* any pending activity.
*
* @param brain
*/
public void interrupt(Brain brain);
/**
* Resumes the execution of this {@link Action}.
*
* @param brain
*/
public void resume(Brain brain);
/**
* This becomes valid if {@link #isFinished(Brain)} returns true.
* @return the {@link ActionResult}
*/
public ActionResult getActionResult();
/**
* Updates the action
*
* @param brain
* @param timeStep
*/
public void update(Brain brain, TimeStep timeStep);
}
| 1,452 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
HandleDoorAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/HandleDoorAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.Door;
import seventh.game.entities.PlayerEntity;
import seventh.shared.TimeStep;
import seventh.shared.Timer;
/**
* Opens or closes a {@link Door}
*
* @author Tony
*
*/
public class HandleDoorAction extends AdapterAction {
private Door door;
private boolean operated;
private Timer blockCheck;
public HandleDoorAction(Door door) {
this.door = door;
this.operated = false;
this.blockCheck = new Timer(true, 800);
this.blockCheck.start();
getActionResult().setFailure();
}
/**
* @return true if the Door has been operated on
*/
protected boolean isFinished() {
boolean isFinished = this.operated && (this.door.isClosed() || this.door.isOpened());
return isFinished;
}
@Override
public boolean isFinished(Brain brain) {
return isFinished();
}
@Override
public void update(Brain brain, TimeStep timeStep) {
this.blockCheck.update(timeStep);
PlayerEntity player = brain.getEntityOwner();
if(!this.operated) {
player.useSingle();
}
this.operated = true;
if(this.door.isBlocked() && this.blockCheck.isOnFirstTime()) {
this.operated = false;
}
if(isFinished()) {
getActionResult().setSuccess();
}
}
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation()
.add("door", this.door.getId())
;
}
}
| 1,779 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DefuseBombAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/DefuseBombAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.Locomotion;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.BombTarget;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* Defuses a bomb
*
* @author Tony
*
*/
public class DefuseBombAction extends AdapterAction {
private BombTarget bomb;
/**
*
*/
public DefuseBombAction(BombTarget bomb) {
this.bomb = bomb;
this.getActionResult().setFailure();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
brain.getMotion().stopUsingHands();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#end(seventh.ai.basic.Brain)
*/
@Override
public void end(Brain brain) {
brain.getMotion().stopUsingHands();
}
/**
* @return true if the bomb is defused
*/
protected boolean isDefused() {
/* check and see if we saved the day! */
if(!bomb.bombActive() && !bomb.bombPlanting() && !bomb.isBombAttached()) {
return true;
}
/* still working on being the hero */
return false;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
if(isDefused()) {
this.getActionResult().setSuccess();
}
else {
Locomotion motion = brain.getMotion();
if(!bomb.isTouching(brain.getEntityOwner())) {
Vector2f dest = motion.getDestination();
if(dest == null || !dest.equals(bomb.getCenterPos())) {
motion.moveTo(bomb.getCenterPos());
}
}
else if(!bomb.bombDisarming() || !motion.isDefusing()) {
motion.defuseBomb(bomb);
}
getActionResult().setFailure();
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
/* error cases, we must finish then */
if(!bomb.isAlive()) {
return true;
}
return isDefused();
}
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation().add("target", this.bomb.getId());
}
}
| 2,674 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DefendZoneAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/DefendZoneAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.Locomotion;
import seventh.ai.basic.Zone;
import seventh.ai.basic.actions.AdapterAction;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class DefendZoneAction extends AdapterAction {
private Zone zone;
private long timeToDefend;
private long timeSpentDefending;
/**
*/
public DefendZoneAction() {
this(null);
}
/**
*
*/
public DefendZoneAction(Zone zone) {
this.zone = zone;
timeToDefend = 5_000; /* time spent before we ask what to do next */
timeSpentDefending = 0;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
timeToDefend = 5_000; /* time spent before we ask what to do next */
timeSpentDefending = 0;
if(zone==null) {
zone = brain.getWorld().getZone(brain.getEntityOwner().getCenterPos());
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
if(zone==null) {
zone = brain.getWorld().getZone(brain.getEntityOwner().getCenterPos());
}
Vector2f pos = brain.getWorld().getRandomSpot(brain.getEntityOwner(), zone.getBounds());
Locomotion motion = brain.getMotion();
if(pos != null) {
motion.moveTo(pos);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
Locomotion motion = brain.getMotion();
if(!motion.isMoving()) {
if(zone==null) {
zone = brain.getWorld().getZone(brain.getEntityOwner().getCenterPos());
}
Vector2f pos = brain.getWorld().getRandomSpot(brain.getEntityOwner(), zone.getBounds());
if(pos != null) {
motion.moveTo(pos);
}
}
timeSpentDefending += timeStep.getDeltaTime();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return timeSpentDefending >= timeToDefend;
}
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation().add("zone", zone);
}
}
| 2,739 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
AvoidMoveToAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/AvoidMoveToAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import java.util.List;
import seventh.ai.basic.Brain;
import seventh.ai.basic.Zone;
import seventh.math.Vector2f;
/**
* @author Tony
*
*/
public class AvoidMoveToAction extends MoveToAction {
private List<Zone> zonesToAvoid;
/**
*
*/
public AvoidMoveToAction(Vector2f dest, List<Zone> zonesToAvoid) {
super(dest);
this.zonesToAvoid = zonesToAvoid;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
brain.getMotion().avoidMoveTo(getDestination(), zonesToAvoid);
}
}
| 739 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MoveToAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/MoveToAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.Locomotion;
import seventh.ai.basic.PathPlanner;
import seventh.ai.basic.actions.AdapterAction;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class MoveToAction extends AdapterAction {
private Vector2f destination;
/**
*
*/
public MoveToAction( Vector2f dest) {
this.destination = dest;
}
/**
* @param destination the destination to set
*/
public void reset(Brain brain, Vector2f destination) {
brain.getMotion().stopMoving();
this.destination.set(destination);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
brain.getMotion().moveTo(destination);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
brain.getMotion().stopMoving();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#end(seventh.ai.basic.Brain)
*/
@Override
public void end(Brain brain) {
brain.getMotion().stopMoving();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
Locomotion motion = brain.getMotion();
if(!motion.isMoving()) {
resume(brain);
}
if( isFinished(brain) ) {
getActionResult().setSuccess();
}
else {
getActionResult().setFailure();
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
PathPlanner<?> path = brain.getMotion().getPathPlanner();
boolean isFinished = path.atDestination();
if(isFinished) {
getActionResult().setSuccess();
}
return isFinished;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#getDebugInformation()
*/
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation().add("destination", this.destination);
}
/**
* @return the destination
*/
public Vector2f getDestination() {
return destination;
}
}
| 2,871 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
StrafeAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/StrafeAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.Locomotion;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.PlayerEntity;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
import seventh.shared.Timer;
/**
* @author Tony
*
*/
public class StrafeAction extends AdapterAction {
private Timer strafeTimer;
private Vector2f dest;
private int direction;
/**
*
*/
public StrafeAction() {
this.strafeTimer = new Timer(true, 1000);
this.dest = new Vector2f();
this.direction = 1;
}
/**
* @param destination the destination to set
*/
public void reset(Brain brain) {
this.strafeTimer.stop();
this.strafeTimer.start();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
this.strafeTimer.start();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
this.strafeTimer.stop();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
Locomotion motion = brain.getMotion();
if(motion.isMoving()) {
getActionResult().setSuccess();
}
PlayerEntity bot = brain.getEntityOwner();
Vector2f vel = bot.getFacing();
Vector2f.Vector2fPerpendicular(vel, dest);
Vector2f.Vector2fMult(dest, direction, dest);
bot.getVel().set(dest);
System.out.println(dest);
this.strafeTimer.update(timeStep);
if(this.strafeTimer.isTime()) {
this.strafeTimer.setEndTime(brain.getWorld().getRandom().nextInt(1000) + 500);
this.strafeTimer.start();
this.direction *= -1;
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return !brain.getMotion().isMoving();
}
}
| 2,573 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MoveToBombTargetToPlantAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/MoveToBombTargetToPlantAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.game.entities.Bomb;
import seventh.game.entities.BombTarget;
/**
* Moves to a bomb target with the intention of planting a {@link Bomb}. This is slightly different
* from {@link MoveToBombAction} in that it will fail/stop if the target is already being planted.
*
* @author Tony
*
*/
public class MoveToBombTargetToPlantAction extends MoveToAction {
private BombTarget target;
/**
* @param target
*/
public MoveToBombTargetToPlantAction(BombTarget target) {
super(target.getCenterPos());
this.target = target;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.MoveToAction#isFinished(seventh.ai.basic.Brain)
*/
@Override
public boolean isFinished(Brain brain) {
if(this.target.bombPlanting() || this.target.bombActive()) {
getActionResult().setFailure();
return true;
}
return super.isFinished(brain);
}
}
| 1,083 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DefendAttackDirectionsAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/DefendAttackDirectionsAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import java.util.List;
import seventh.ai.basic.AttackDirection;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.Entity;
import seventh.game.entities.PlayerEntity;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class DefendAttackDirectionsAction extends AdapterAction {
private List<AttackDirection> attackDirs;
private long lookTime;
private long timeToDefend, originalTimeToDefend;
private int currentDirection;
private Vector2f dir;
private boolean interrupted;
/**
*
*/
public DefendAttackDirectionsAction(List<AttackDirection> attackDirs, long timeToDefend) {
this.attackDirs = attackDirs;
this.timeToDefend = timeToDefend;
this.originalTimeToDefend = timeToDefend;
this.dir = new Vector2f();
if(this.attackDirs.isEmpty()) {
this.interrupted = true;
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
this.timeToDefend = this.originalTimeToDefend;
if(!this.interrupted && this.attackDirs.size() > 0) {
this.currentDirection = (currentDirection+1) % this.attackDirs.size();
this.dir.set(this.attackDirs.get(currentDirection).getDirection());
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
if(this.attackDirs.isEmpty()) {
this.interrupted = true;
}
else {
this.interrupted = false;
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
this.interrupted = true;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
lookTime += timeStep.getDeltaTime();
timeToDefend -= timeStep.getDeltaTime();
PlayerEntity ent = brain.getEntityOwner();
if(lookTime > 2_000 && !this.interrupted && this.attackDirs.size() > 0) {
this.currentDirection = (currentDirection+1) % this.attackDirs.size();
this.dir.set(this.attackDirs.get(currentDirection).getDirection());
lookTime = 0;
}
float destinationOrientation = (float)Entity.getAngleBetween(dir, ent.getCenterPos());
ent.setOrientation(destinationOrientation);
// float destinationDegree = (float)Math.toDegrees(destinationOrientation);
//
// float currentDegree = (float)Math.toDegrees(ent.getOrientation());
// float deltaDegree = destinationDegree - currentDegree;
//
// /* find the normalized delta */
// if(deltaDegree>0) {
// deltaDegree=1;
// }
// else if(deltaDegree < 0) {
// deltaDegree=-1;
// }
// else {
// deltaDegree=0;
// }
//
// float rotationSpeed = 150.0f;
// currentDegree += deltaDegree * rotationSpeed * timeStep.asFraction();
// ent.setOrientation( (float)Math.toRadians(currentDegree));
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished(seventh.ai.basic.Brain)
*/
@Override
public boolean isFinished(Brain brain) {
return interrupted || timeToDefend <= 0;
}
}
| 3,853 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ExitVehicleAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/ExitVehicleAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.PlayerEntity;
import seventh.shared.TimeStep;
/**
* Exits a vehicle
*
* @author Tony
*
*/
public class ExitVehicleAction extends AdapterAction {
/**
*
*/
public ExitVehicleAction() {
this.getActionResult().setFailure();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
brain.getMotion().stopUsingHands();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#end(seventh.ai.basic.Brain)
*/
@Override
public void end(Brain brain) {
brain.getMotion().stopUsingHands();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
PlayerEntity bot = brain.getEntityOwner();
if(bot.isExitingVehicle()) {
this.getActionResult().setSuccess();
}
else {
bot.use();
getActionResult().setFailure();
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
getActionResult().setFailure();
PlayerEntity bot = brain.getEntityOwner();
if(bot.isExitingVehicle() || !bot.isOperatingVehicle()) {
getActionResult().setSuccess();
return true;
}
return false;
}
}
| 1,807 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FindClosestBombTarget.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/FindClosestBombTarget.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import java.util.List;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.BombTarget;
import seventh.math.Vector2f;
/**
* @author Tony
*
*/
public class FindClosestBombTarget extends AdapterAction {
private boolean toDefuse;
/**
*
*/
public FindClosestBombTarget(boolean toDefuse) {
this.toDefuse = toDefuse;
}
private boolean isValidBombTarget(Brain brain, BombTarget bomb) {
return bomb.isAlive() && ( toDefuse ? bomb.bombActive() : (!bomb.isBombAttached() && !bomb.bombActive() && !bomb.bombPlanting()) );
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
List<BombTarget> targets = brain.getWorld().getBombTargets();
Vector2f botPos = brain.getEntityOwner().getPos();
if(!targets.isEmpty()) {
BombTarget closestBomb = null;
float distance = -1;
/* lets find the closest bomb target */
for(int i = 0; i < targets.size(); i++) {
BombTarget bomb = targets.get(i);
/* make sure this bomb is eligable for planting */
if(isValidBombTarget(brain, bomb)) {
float distanceToBomb = Vector2f.Vector2fDistanceSq(bomb.getPos(), botPos);
/* if we haven't assigned a closest or we have a closer bomb
* assign it.
*/
if(closestBomb == null || distanceToBomb < distance) {
closestBomb = bomb;
distance = distanceToBomb;
}
}
}
if(closestBomb != null) {
this.getActionResult().setSuccess(closestBomb);
return;
}
}
getActionResult().setFailure();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return true;
}
}
| 2,567 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SupressFireUntilAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/SupressFireUntilAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import leola.vm.Leola;
import leola.vm.types.LeoObject;
import seventh.ai.basic.Brain;
import seventh.ai.basic.Locomotion;
import seventh.ai.basic.actions.AdapterAction;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class SupressFireUntilAction extends AdapterAction {
private LeoObject isFinished;
private LeoObject result;
private Vector2f target;
/**
*
*/
public SupressFireUntilAction(LeoObject isFinished, Vector2f target) {
this.isFinished = isFinished;
this.target = target;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
Locomotion motion = brain.getMotion();
motion.lookAt(target);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
result = this.isFinished.xcall(Leola.toLeoObject(timeStep));
Locomotion motion = brain.getMotion();
if (brain.getEntityOwner().isFacing(target)) {
motion.shoot();
//motion.stopShooting();
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
if(brain.getTargetingSystem().hasTarget()) {
return true;
}
return LeoObject.isTrue(result);
}
}
| 1,907 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FollowEntityAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/FollowEntityAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.PathPlanner;
import seventh.ai.basic.SightSensor;
import seventh.ai.basic.actions.AdapterAction;
import seventh.ai.basic.memory.SightMemory.SightMemoryRecord;
import seventh.game.entities.Entity;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* Follows the supplied {@link Entity}.
*
* @author Tony
*
*/
public class FollowEntityAction extends AdapterAction {
private Entity followMe;
private long timeSinceLastSeenExpireMSec;
private Vector2f previousDestination;
/**
* @param feeder
*/
public FollowEntityAction(Entity followMe) {
this.followMe = followMe;
if(followMe == null) {
throw new NullPointerException("The followMe entity is NULL!");
}
this.previousDestination = new Vector2f();
this.timeSinceLastSeenExpireMSec = 2_000;
//System.out.println("new follow");
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
this.timeSinceLastSeenExpireMSec = 12_000;
this.timeSinceLastSeenExpireMSec += brain.getWorld().getRandom().nextInt(3) * 1000;
}
/* (non-Javadoc)
* @see palisma.ai.Action#end(palisma.ai.Brain)
*/
@Override
public void end(Brain brain) {
brain.getMotion().emptyPath();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
brain.getMotion().emptyPath();
}
/* (non-Javadoc)
* @see palisma.ai.Action#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
SightSensor sight = brain.getSensors().getSightSensor();
SightMemoryRecord mem = sight.getMemoryRecordFor(followMe);
boolean isFinished = true;
if(mem != null && mem.isValid()) {
isFinished = mem.getTimeSeenAgo() > timeSinceLastSeenExpireMSec;
}
/* if the entity is out of our sensory memory or is Dead,
* expire this action
*/
return !this.followMe.isAlive() || isFinished;
}
/* (non-Javadoc)
* @see palisma.ai.Action#update(palisma.ai.Brain, leola.live.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
PathPlanner<?> feeder = brain.getMotion().getPathPlanner();
SightSensor sight = brain.getSensors().getSightSensor();
if(!feeder.hasPath() || !feeder.onFirstNode()) {
SightMemoryRecord mem = sight.getMemoryRecordFor(followMe);
if(mem != null && mem.isValid()) {
Vector2f newPosition = mem.getLastSeenAt();
Vector2f start = brain.getEntityOwner().getPos();
if(Vector2f.Vector2fDistanceSq(previousDestination, newPosition) > 15_000) {
// if the entity we are following is a certain distance away,
// recalculate the path to it
if(Vector2f.Vector2fDistanceSq(start, newPosition) > 15_000) {
feeder.findPath(start, newPosition);
//System.out.println("new: " + previousDestination + " vs " + newPosition);
previousDestination.set(newPosition);
}
else {
if(feeder.hasPath()) {
feeder.clearPath();
}
}
}
}
}
}
}
| 3,940 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SecureZoneAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/SecureZoneAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import java.util.ArrayList;
import java.util.List;
import seventh.ai.basic.Brain;
import seventh.ai.basic.Zone;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.PlayerEntity;
import seventh.math.Vector2f;
/**
* @author Tony
*
*/
public class SecureZoneAction extends AdapterAction {
private Zone zone;
private List<PlayerEntity> playersInZone;
/**
*
*/
public SecureZoneAction(Zone zone) {
this.zone = zone;
this.playersInZone = new ArrayList<>();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
Vector2f pos = brain.getWorld().getRandomSpot(brain.getEntityOwner(), zone.getBounds());
if(pos != null) {
brain.getMotion().moveTo(pos);
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
getActionResult().setFailure();
/* ensure the player is within the Zone */
// if (!zone.getBounds().contains(brain.getEntityOwner().getCenterPos())) {
// return true;
// }
this.playersInZone.clear();
brain.getWorld().playersIn(this.playersInZone, zone.getBounds());
boolean isClear = true;
for(int i = 0; i < playersInZone.size(); i++) {
PlayerEntity ent = playersInZone.get(i);
if(ent.isAlive()) {
if(!brain.getEntityOwner().isOnTeamWith(ent)) {
isClear = false;
break;
}
}
}
if(isClear) {
getActionResult().setSuccess();
}
return isClear;
}
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation().add("zone", this.zone);
}
}
| 2,304 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GuardAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/GuardAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class GuardAction extends AdapterAction {
/**
*
*/
public GuardAction() {
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
brain.getMotion().scanArea();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return brain.getTargetingSystem().hasTarget();
}
}
| 1,189 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
ShootAtAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/ShootAtAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.PlayerEntity;
import seventh.game.weapons.Weapon;
import seventh.shared.TimeStep;
import seventh.shared.Timer;
/**
* @author Tony
*
*/
public class ShootAtAction extends AdapterAction {
private Timer shouldCheckLOF;
private boolean inLOF;
/**
*/
public ShootAtAction() {
this.shouldCheckLOF = new Timer(true, 100);
this.shouldCheckLOF.start();
this.inLOF = false;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#cancel()
*/
@Override
public void cancel() {
this.inLOF = false;
}
/* (non-Javadoc)
* @see palisma.ai.Action#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
Weapon weapon = brain.getEntityOwner().getInventory().currentItem();
return !this.inLOF || (weapon==null || weapon.getBulletsInClip()==0);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
this.inLOF = brain.getTargetingSystem().currentTargetInLineOfFire();
}
/* (non-Javadoc)
* @see palisma.ai.Action#update(palisma.ai.Brain, leola.live.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
PlayerEntity player = brain.getEntityOwner();
this.shouldCheckLOF.update(timeStep);
if(this.shouldCheckLOF.isTime()) {
this.inLOF = brain.getTargetingSystem().currentTargetInLineOfFire();
}
if(this.inLOF) {
if(player.canFire()) {
player.beginFire();
player.endFire();
}
}
}
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation();
}
}
| 2,043 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
EnterVehicleAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/EnterVehicleAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.Locomotion;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.PlayerEntity;
import seventh.game.entities.vehicles.Vehicle;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* Enters a vehicle
*
* @author Tony
*
*/
public class EnterVehicleAction extends AdapterAction {
private Vehicle vehicle;
/**
*
*/
public EnterVehicleAction(Vehicle vehicle) {
this.vehicle = vehicle;
this.getActionResult().setFailure();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
brain.getMotion().stopUsingHands();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#end(seventh.ai.basic.Brain)
*/
@Override
public void end(Brain brain) {
brain.getMotion().stopUsingHands();
}
/**
* @return true if the bot is in the vehicle
*/
protected boolean isInVehicle(PlayerEntity bot) {
if(this.vehicle.hasOperator() && bot.isOperatingVehicle()) {
return this.vehicle == bot.getVehicle();
}
return false;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
PlayerEntity bot = brain.getEntityOwner();
if(isInVehicle(bot)) {
this.getActionResult().setSuccess();
}
else {
Locomotion motion = brain.getMotion();
if(!vehicle.canOperate(brain.getEntityOwner())) {
Vector2f dest = motion.getDestination();
if(dest == null || !dest.equals(vehicle.getCenterPos())) {
motion.moveTo(vehicle.getCenterPos());
}
}
else if( !bot.isEnteringVehicle() ) {
bot.use();
}
getActionResult().setFailure();
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
getActionResult().setFailure();
/* error cases, we must finish then */
if(!vehicle.isAlive()) {
return true;
}
if(vehicle.hasOperator()) {
return true;
}
PlayerEntity bot = brain.getEntityOwner();
if(isInVehicle(bot)) {
getActionResult().setSuccess();
return true;
}
return false;
}
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation().add("vehicle", this.vehicle.getId());
}
}
| 3,010 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PickAttackDirectionAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/PickAttackDirectionAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import java.util.List;
import seventh.ai.basic.AttackDirection;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.math.Vector2f;
/**
* @author Tony
*
*/
public class PickAttackDirectionAction extends AdapterAction {
private List<AttackDirection> attackDirs;
/**
*
*/
public PickAttackDirectionAction(List<AttackDirection> attackDirs) {
this.attackDirs = attackDirs;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
if(!attackDirs.isEmpty()) {
Vector2f targetPos = attackDirs.get(brain.getWorld().getRandom().nextInt(attackDirs.size())).getDirection();
this.getActionResult().setSuccess(targetPos);
}
else {
this.getActionResult().setFailure();
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished(seventh.ai.basic.Brain)
*/
@Override
public boolean isFinished(Brain brain) {
return true;
}
}
| 1,404 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
PlantBombAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/PlantBombAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.Locomotion;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.BombTarget;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class PlantBombAction extends AdapterAction {
private BombTarget target;
/**
*/
public PlantBombAction() {
this(null);
}
/**
* @param target
*/
public PlantBombAction(BombTarget target) {
this.target = target;
}
/**
* Resets the action
* @param target
*/
public void reset(BombTarget target) {
this.target = target;
getActionResult().setFailure();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
if(target != null && target.bombActive()) {
getActionResult().setSuccess();
}
else {
getActionResult().setFailure();
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#end(seventh.ai.basic.Brain)
*/
@Override
public void end(Brain brain) {
brain.getMotion().stopUsingHands();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
brain.getMotion().stopUsingHands();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
if(target != null) {
if(target.bombActive()) {
getActionResult().setSuccess();
}
else {
Locomotion motion = brain.getMotion();
if(!target.bombPlanting() || !motion.isPlanting()) {
motion.plantBomb(target);
}
getActionResult().setFailure();
}
}
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
/* error cases, we must finish then */
if(target == null || !target.isAlive()) {
return true;
}
/* check and see if we planted the bomb */
if(target.bombActive()) {
return true;
}
if(!brain.getEntityOwner().isTouching(target)) {
return true;
}
/* still working on being the hero */
return false;
}
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation().add("target", this.target.getId());
}
}
| 3,163 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MoveToVehicleAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/MoveToVehicleAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.game.entities.vehicles.Vehicle;
/**
* @author Tony
*
*/
public class MoveToVehicleAction extends MoveToAction {
private Vehicle vehicle;
/**
* @param target
*/
public MoveToVehicleAction(Vehicle vehicle) {
super(vehicle.getCenterPos());
this.vehicle = vehicle;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.MoveToAction#isFinished(seventh.ai.basic.Brain)
*/
@Override
public boolean isFinished(Brain brain) {
getActionResult().setFailure();
if(!this.vehicle.isAlive()) {
return true;
}
if(this.vehicle.hasOperator()) {
return true;
}
if(this.vehicle.canOperate(vehicle)) {
getActionResult().setSuccess();
return true;
}
return super.isFinished(brain);
}
}
| 1,000 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MoveToFlagAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/MoveToFlagAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import java.util.Collections;
import java.util.List;
import seventh.ai.basic.Zone;
import seventh.game.entities.Flag;
/**
* @author Tony
*
*/
public class MoveToFlagAction extends AvoidMoveToAction {
private static final List<Zone> emptyZonesToAvoid = Collections.emptyList();
/**
* @param target
*/
public MoveToFlagAction(Flag target, List<Zone> zonesToAvoid) {
super(target.getCenterPos(), zonesToAvoid);
}
public MoveToFlagAction(Flag target) {
super(target.getCenterPos(), emptyZonesToAvoid);
}
}
| 660 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
StareAtEntityAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/StareAtEntityAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.PersonalityTraits;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.SmoothOrientation;
import seventh.game.entities.Entity;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class StareAtEntityAction extends AdapterAction {
private Entity stareAtMe;
private final long timeSinceLastSeenExpireMSec;
private SmoothOrientation smoother;
public StareAtEntityAction(Entity stareAtMe) {
reset(stareAtMe);
timeSinceLastSeenExpireMSec = 1000_300;
this.smoother = new SmoothOrientation(Math.toRadians(5.0f));
}
/**
* @param stareAtMe the stareAtMe to set
*/
public void reset(Entity stareAtMe) {
this.stareAtMe = stareAtMe;
}
/* (non-Javadoc)
* @see palisma.ai.Action#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return !this.stareAtMe.isAlive() || brain.getSensors().getSightSensor().timeSeenAgo(stareAtMe) > timeSinceLastSeenExpireMSec;
}
/* (non-Javadoc)
* @see palisma.ai.Action#update(palisma.ai.Brain, leola.live.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
Entity me = brain.getEntityOwner();
Vector2f entityPos = stareAtMe.getCenterPos();
// if( brain.getSensors().getSightSensor().inView(this.stareAtMe) || brain.getTargetingSystem().targetInLineOfFire(entityPos))
{
/* add some slop value so that the Agent isn't too accurate */
PersonalityTraits personality = brain.getPersonality();
float slop = personality.calculateAccuracy(brain);
float desiredOrientation = Entity.getAngleBetween(entityPos, me.getCenterPos()) + slop;
smoother.setDesiredOrientation(desiredOrientation);
smoother.setOrientation(me.getOrientation());
smoother.update(timeStep);
me.setOrientation(smoother.getOrientation());
//me.setOrientation(desiredOrientation);
}
}
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation().add("stareAt", this.stareAtMe);
}
}
| 2,441 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
CoverEntityAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/CoverEntityAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.PathPlanner;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.Entity;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* Cover a friend
*
* @author Tony
*
*/
public class CoverEntityAction extends AdapterAction {
private Entity followMe;
private long lastVisibleTime;
private final long timeSinceLastSeenExpireMSec;
/**
* @param feeder
*/
public CoverEntityAction(Entity followMe) {
this.followMe = followMe;
this.timeSinceLastSeenExpireMSec = 7_000;
}
/* (non-Javadoc)
* @see palisma.ai.Action#end(palisma.ai.Brain)
*/
@Override
public void end(Brain brain) {
brain.getMotion().emptyPath();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
brain.getMotion().emptyPath();
}
/* (non-Javadoc)
* @see palisma.ai.Action#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
boolean isfinished = !this.followMe.isAlive() || this.lastVisibleTime > timeSinceLastSeenExpireMSec;
return isfinished;
}
/* (non-Javadoc)
* @see palisma.ai.Action#update(palisma.ai.Brain, leola.live.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
if(! brain.getSensors().getSightSensor().inView(this.followMe) ) {
this.lastVisibleTime += timeStep.getDeltaTime();
}
else {
this.lastVisibleTime = 0;
}
PathPlanner<?> feeder = brain.getMotion().getPathPlanner();
if(!feeder.hasPath() || !feeder.onFirstNode()) {
Vector2f newPosition = this.followMe.getPos();
Vector2f start = brain.getEntityOwner().getPos();
float distance = Vector2f.Vector2fDistanceSq(start, newPosition);
if(distance > 15_000) {
feeder.findPath(start, newPosition);
}
else {
/* stop the agent */
if(feeder != null) {
feeder.clearPath();
brain.getMotion().scanArea();
}
}
}
}
}
| 2,532 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
GuardUntilAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/GuardUntilAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import leola.vm.Leola;
import leola.vm.types.LeoObject;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class GuardUntilAction extends AdapterAction {
private LeoObject isFinished;
private LeoObject result;
/**
* @param isFinished
*/
public GuardUntilAction(LeoObject isFinished) {
this.isFinished = isFinished;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
brain.getMotion().scanArea();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
result = isFinished.xcall(Leola.toLeoObject(timeStep));
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
if(brain.getTargetingSystem().hasTarget()) {
return true;
}
return LeoObject.isTrue(result);
}
}
| 1,526 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
BombAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/BombAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.BombTarget;
import seventh.game.entities.PlayerEntity;
import seventh.shared.TimeStep;
/**
* Plants or defuses a bomb
*
* @author Tony
*
*/
public class BombAction extends AdapterAction {
private boolean plant;
private BombTarget bombTarget;
/**
*
*/
public BombAction(BombTarget bombTarget, boolean plant) {
this.bombTarget = bombTarget;
this.plant = plant;
getActionResult().setFailure();
}
/* (non-Javadoc)
* @see palisma.ai.Action#end(palisma.ai.Brain)
*/
@Override
public void end(Brain brain) {
brain.getEntityOwner().unuse();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#interrupt(seventh.ai.basic.Brain)
*/
@Override
public void interrupt(Brain brain) {
brain.getEntityOwner().unuse();
if(isFinished()) {
getActionResult().setSuccess();
}
}
/**
* @return true if the bomb is planted/defused
*/
protected boolean isFinished() {
boolean isFinished = plant ? bombTarget.bombActive()||!bombTarget.isAlive() : !bombTarget.isBombAttached();
return isFinished;
}
/* (non-Javadoc)
* @see palisma.ai.Action#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return isFinished();
}
/* (non-Javadoc)
* @see palisma.ai.Action#update(palisma.ai.Brain, leola.live.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
PlayerEntity player = brain.getEntityOwner();
player.use();
if(isFinished()) {
getActionResult().setSuccess();
}
}
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation()
.add("target", this.bombTarget.getId())
.add("plant", plant);
}
}
| 2,127 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
EvaluateAttackDirectionsAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/EvaluateAttackDirectionsAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import java.util.ArrayList;
import java.util.List;
import seventh.ai.basic.AttackDirection;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
/**
* @author Tony
*
*/
public class EvaluateAttackDirectionsAction extends AdapterAction {
/**
*
*/
public EvaluateAttackDirectionsAction() {
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
List<AttackDirection> attackDirs = new ArrayList<>(brain.getWorld().getAttackDirections(brain.getEntityOwner()));
this.getActionResult().setSuccess(attackDirs);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return true;
}
}
| 1,146 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
DropWeaponAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/DropWeaponAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.PlayerEntity;
import seventh.shared.TimeStep;
/**
* Reload a weapon action
*
* @author Tony
*
*/
public class DropWeaponAction extends AdapterAction {
/**
*/
public DropWeaponAction() {
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished(seventh.ai.basic.Brain)
*/
@Override
public boolean isFinished(Brain brain) {
return true;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
PlayerEntity entity = brain.getEntityOwner();
entity.dropItem(true);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
}
}
| 1,078 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
FindSafeDistanceFromActiveBombAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/FindSafeDistanceFromActiveBombAction.java | /**
*
*/
package seventh.ai.basic.actions.atom;
import seventh.ai.basic.Brain;
import seventh.ai.basic.World;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.Bomb;
import seventh.game.entities.BombTarget;
import seventh.game.entities.PlayerEntity;
import seventh.math.Rectangle;
import seventh.math.Vector2f;
/**
* @author Tony
*
*/
public class FindSafeDistanceFromActiveBombAction extends AdapterAction {
private BombTarget target;
/**
*
*/
public FindSafeDistanceFromActiveBombAction(BombTarget target) {
this.target = target;
}
/*
* (non-Javadoc)
*
* @see seventh.ai.basic.actions.AdapterAction#start(seventh.ai.basic.Brain)
*/
@Override
public void start(Brain brain) {
Bomb bomb = target.getBomb();
if(bomb==null) {
this.getActionResult().setFailure();
return;
}
World world = brain.getWorld();
PlayerEntity bot = brain.getEntityOwner();
Rectangle coverBounds = new Rectangle(300, 300);
coverBounds.centerAround(target.getCenterPos());
Vector2f moveTo = world.getRandomSpotNotIn(bot, coverBounds.x, coverBounds.y, coverBounds.width, coverBounds.height, bomb.getBlastRadius());
getActionResult().setSuccess(moveTo);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#resume(seventh.ai.basic.Brain)
*/
@Override
public void resume(Brain brain) {
start(brain);
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished(seventh.ai.basic.Brain)
*/
@Override
public boolean isFinished(Brain brain) {
return true;
}
}
| 1,763 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
MoveToBombAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/MoveToBombAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom;
import seventh.game.entities.BombTarget;
/**
* @author Tony
*
*/
public class MoveToBombAction extends MoveToAction {
/**
* @param target
*/
public MoveToBombAction(BombTarget target) {
super(target.getCenterPos());
}
}
| 339 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
CrouchAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/body/CrouchAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom.body;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class CrouchAction extends AdapterAction {
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#isFinished(seventh.ai.basic.Brain)
*/
@Override
public boolean isFinished(Brain brain) {
return false;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
brain.getEntityOwner().crouch();
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#end(seventh.ai.basic.Brain)
*/
@Override
public void end(Brain brain) {
brain.getEntityOwner().standup();
}
}
| 938 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
LookAtAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/body/LookAtAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom.body;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.entities.Entity;
import seventh.game.entities.PlayerEntity;
import seventh.math.FastMath;
import seventh.math.Vector2f;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class LookAtAction extends AdapterAction {
private float destinationOrientation;
private Vector2f position;
public LookAtAction(float orientation) {
this.destinationOrientation = orientation;
}
public LookAtAction(Entity entity, Vector2f position) {
reset(entity, position);
}
/**
*
*/
public LookAtAction(Vector2f position) {
this.position = position;
}
/**
* Sets the orientation to move in order for the Entity to look at the
* dest vector.
*
* @param me
* @param dest
*/
public void reset(Entity me, Vector2f dest) {
this.destinationOrientation = Entity.getAngleBetween(dest, me.getPos());
final float fullCircle = FastMath.fullCircle;
if(this.destinationOrientation < 0) {
this.destinationOrientation += fullCircle;
}
}
/* (non-Javadoc)
* @see palisma.ai.Action#start(palisma.ai.Brain)
*/
@Override
public void start(Brain brain) {
if(this.position != null) {
reset(brain.getEntityOwner(), this.position);
}
}
/* (non-Javadoc)
* @see palisma.ai.Action#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
PlayerEntity ent = brain.getEntityOwner();
float currentOrientation = ent.getOrientation();
double currentDegree = Math.toDegrees(currentOrientation);
double destDegree = Math.toDegrees(destinationOrientation);
// TODO: Work out Looking at something (being shot while takingCover)
return Math.abs(currentDegree - destDegree) < 5;
}
/* (non-Javadoc)
* @see seventh.ai.basic.actions.AdapterAction#update(seventh.ai.basic.Brain, seventh.shared.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
PlayerEntity ent = brain.getEntityOwner();
float currentOrientation = ent.getOrientation();
final float fullCircle = FastMath.fullCircle;
// Thank you: http://dev.bennage.com/blog/2013/03/05/game-dev-03/
float deltaOrientation = (destinationOrientation - currentOrientation);
float deltaOrientationAbs = Math.abs(deltaOrientation);
if(deltaOrientationAbs > Math.PI) {
deltaOrientation *= -1;
}
final double movementSpeed = Math.toRadians(15.0f);
if(deltaOrientationAbs != 0) {
float direction = deltaOrientation / deltaOrientationAbs;
currentOrientation += (direction * Math.min(movementSpeed, deltaOrientationAbs));
if(currentOrientation < 0) {
currentOrientation = fullCircle + currentOrientation;
}
currentOrientation %= fullCircle;
}
ent.setOrientation( currentOrientation );
}
@Override
public DebugInformation getDebugInformation() {
return super.getDebugInformation().add("orientation", Math.toDegrees(destinationOrientation));
}
}
| 3,538 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
SwitchWeaponAction.java | /FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/ai/basic/actions/atom/body/SwitchWeaponAction.java | /*
* see license.txt
*/
package seventh.ai.basic.actions.atom.body;
import seventh.ai.basic.Brain;
import seventh.ai.basic.actions.AdapterAction;
import seventh.game.Inventory;
import seventh.game.entities.PlayerEntity;
import seventh.game.entities.Entity.Type;
import seventh.game.weapons.Weapon;
import seventh.shared.TimeStep;
/**
* @author Tony
*
*/
public class SwitchWeaponAction extends AdapterAction {
private Type weapon;
private boolean isDone;
/**
*
*/
public SwitchWeaponAction(Type weapon) {
this.weapon = weapon;
this.isDone = false;
}
public void reset(Type weapon) {
this.weapon = weapon;
this.isDone = false;
}
/* (non-Javadoc)
* @see palisma.ai.Action#isFinished()
*/
@Override
public boolean isFinished(Brain brain) {
return isDone;
}
/* (non-Javadoc)
* @see palisma.ai.Action#update(palisma.ai.Brain, leola.live.TimeStep)
*/
@Override
public void update(Brain brain, TimeStep timeStep) {
PlayerEntity player = brain.getEntityOwner();
Inventory inventory = player.getInventory();
Weapon currentItem = inventory.currentItem();
if(currentItem != null) {
if(currentItem.getType().equals(weapon)) {
isDone = true;
}
else {
if(currentItem.isReady()) {
player.nextWeapon();
}
}
}
else {
isDone = true; /* we don't have any items */
}
if(isDone) {
getActionResult().setSuccess();
}
else {
getActionResult().setFailure();
}
}
}
| 1,770 | Java | .java | tonysparks/seventh | 49 | 30 | 7 | 2014-05-05T22:57:09Z | 2019-11-27T01:44:13Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.