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
PlayerInfo.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/PlayerInfo.java
/* * see license.txt */ package seventh.game; import seventh.game.entities.Entity; import seventh.game.entities.PlayerEntity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; /** * Gather information about a Players state * * @author Tony * */ public interface PlayerInfo { /** * @return the killedAt the position this player was last killed at */ public abstract Vector2f getKilledAt(); /** * @return the weaponClass */ public abstract Type getWeaponClass(); public abstract PlayerClass getPlayerClass(); /** * @return true if we are ready to spawn */ public abstract boolean readyToSpawn(); /** * @return determines if enough time has passed if the * player can stop viewing their death */ public abstract boolean readyToLookAwayFromDeath(); /** * @return the number of times this player has died. */ public abstract int getDeaths(); /** * @return the number of kills this player has accrued. */ public abstract int getKills(); /** * @return the name */ public abstract String getName(); /** * @return Get the players current active tile (for builder player class only) */ public int getActiveTile(); /** * @return true if this player is a bot */ public abstract boolean isBot(); /** * @return true if this player is a bot and has a 'dummy' brain */ public abstract boolean isDummyBot(); /** * @return the time this player joined the game. In Epoch time. */ public abstract long getJoinTime(); /** * @return the ping of the Player. If this represents a remote player, * this is be the round trip time from their client to the server in milliseconds. */ public abstract int getPing(); /** * @return the Players Id */ public abstract int getId(); /** * @return true if this player is controlling a game world {@link Entity} */ public abstract boolean hasEntity(); /** * @return true if this player is eligible to spawn */ public boolean canSpawn(); /** * @return true if this Player is not controlling an {@link Entity} or the * controlled {@link Entity} is dead. */ public abstract boolean isDead(); /** * @return true if this Player is controlling an {@link Entity} and said {@link Entity} * is alive. * @see PlayerInfo#isDead() */ public abstract boolean isAlive(); /** * @return true if this player is spectating */ public abstract boolean isSpectating(); /** * @return the player is not in the game, but is a purely spectating */ public abstract boolean isPureSpectator(); /** * @return if the player is currently commanding their team */ public boolean isCommander(); /** * @return the {@link Entity} which this player is spectating */ public abstract PlayerEntity getSpectatingEntity(); /** * @return the {@link Entity}'s id which this player is spectating. */ public abstract int getSpectatingPlayerId(); /** * @return the {@link Player} which this player is spectating */ public abstract Player getSpectating(); /** * @return the {@link Entity} this player is controlling in the game world. */ public abstract PlayerEntity getEntity(); /** * @return the team which this player belongs to */ public abstract Team getTeam(); /** * @return the teamId (if the stats are reset, this will keep the teamId) */ public abstract byte getTeamId(); /** * If this player is a teammate with the supplied id * @param playerId * @return true if they are teammates */ public abstract boolean isTeammateWith(int playerId); }
3,941
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
SoundEmitter.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/SoundEmitter.java
/* * see license.txt */ package seventh.game; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.Timer; import seventh.shared.Updatable; /** * Limits the frequency of a sound. Use this if you want to play a sound only within an * alloted amount of time (i.e., it won't play if the alloted amount of time hasn't elapsed). * * @author Tony * */ public class SoundEmitter implements Updatable { private Timer timer; private boolean hasStarted;; public SoundEmitter(long start) { this(start, false); } public SoundEmitter(long start, boolean loop) { this.timer = new Timer(loop, start); this.hasStarted = false; } public void reset() { this.timer.reset(); this.hasStarted = false; } public void stop() { this.timer.stop(); this.hasStarted = false; } public void play(Game game, int id, SoundType sound, Vector2f pos) { if(this.timer.isTime()|| !this.hasStarted) { game.emitSound(id, sound, pos); this.hasStarted = true; } } @Override public void update(TimeStep timeStep) { this.timer.update(timeStep); } }
1,279
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
GameInfo.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/GameInfo.java
/* * see license.txt */ package seventh.game; import java.util.List; import java.util.Random; import seventh.ai.AISystem; import seventh.game.entities.BombTarget; import seventh.game.entities.Door; import seventh.game.entities.Entity; import seventh.game.entities.Flag; import seventh.game.entities.PlayerEntity; import seventh.game.entities.vehicles.Vehicle; import seventh.game.game_types.GameType; import seventh.map.Map; import seventh.map.MapGraph; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.EventDispatcher; import seventh.shared.SeventhConfig; /** * Used for acquiring information about the current game state * * @author Tony * */ public interface GameInfo { /** * @param entity * @return a random position anywhere in the game world */ public Vector2f findFreeRandomSpot(Entity entity); /** * @param entity * @param bounds * @return a random position anywhere in the supplied bounds */ public Vector2f findFreeRandomSpot(Entity entity, Rectangle bounds); /** * * @param entity * @param x * @param y * @param width * @param height * @return a random position anywhere in the supplied bounds */ public Vector2f findFreeRandomSpot(Entity entity, int x, int y, int width, int 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 findFreeRandomSpotNotIn(Entity entity, int x, int y, int width, int height, Rectangle notIn); /** * @return the aiSystem */ public abstract AISystem getAISystem(); /** * @return the config */ public abstract SeventhConfig getConfig(); /** * @return the random */ public abstract Random getRandom(); /** * @return the dispatcher */ public abstract EventDispatcher getDispatcher(); /** * @return the game {@link Timers} */ public abstract Timers getGameTimers(); /** * @return the lastFramesSoundEvents */ public abstract SoundEventPool getLastFramesSoundEvents(); /** * @return the soundEvents */ public abstract SoundEventPool getSoundEvents(); /** * @param playerId * @return the player, or null if not found */ public abstract PlayerInfo getPlayerById(int playerId); /** * @return the players */ public abstract PlayerInfos getPlayerInfos(); /** * @return the gameType */ public abstract GameType getGameType(); /** * @return the map */ public abstract Map getMap(); /** * @return the entities */ public abstract Entity[] getEntities(); /** * @return the playerEntities */ public abstract PlayerEntity[] getPlayerEntities(); /** * @return the graph */ public abstract MapGraph<Void> getGraph(); /** * @return the bomb targets */ public abstract List<BombTarget> getBombTargets(); /** * @return the vehicles */ public abstract List<Vehicle> getVehicles(); /** * @return the doors */ public abstract List<Door> getDoors(); /** * @return the flags */ public abstract List<Flag> getFlags(); /** * Gets a {@link BombTarget} if its in arms length from the {@link PlayerEntity} * @param entity * @return the {@link BombTarget} that is touching the {@link PlayerEntity}, null otherwise */ public abstract BombTarget getArmsReachBombTarget(PlayerEntity entity); /** * Determines if the supplied Entity is close enough to a {@link Vehicle} * to operate it (and that the {@link Vehicle} can be driven). * @param operator * @return the {@link Vehicle} to be operated on */ public abstract Vehicle getArmsReachOperableVehicle(Entity operator); /** * Determines if the supplied entity touches another * entity. If the {@link Entity#onTouch} listener * is implemented, it will invoke it. * * @param ent * @return true if it does. */ public abstract boolean doesTouchOthers(Entity ent); public abstract boolean doesTouchOthers(Entity ent, boolean invokeTouch); public boolean doesTouchEntity(Rectangle bounds); /** * Determines if the supplied entity touches another * entity. If the {@link Entity#onTouch} listener * is implemented, it will invoke it. * * @param ent * @return true if it does. */ public abstract boolean doesTouchPlayers(Entity ent); /** * Determines if the supplied entity touches a * {@link Vehicle}. If the {@link Entity#onTouch} listener * is implemented, it will invoke it. * * @param ent * @return true if it does. */ public abstract boolean doesTouchVehicles(Entity ent); /** * Determines if the supplied entity touches a * {@link Door}. If the {@link Entity#onTouch} listener * is implemented, it will invoke it. * * @param ent * @return true if it does. */ public boolean doesTouchDoors(Entity ent); /** * Determines if the supplied entity touches another * entity. If the {@link Entity#onTouch} listener * is implemented, it will invoke it. * * @param ent * @return true if it does. */ public abstract boolean doesTouchPlayers(Entity ent, Vector2f origin, Vector2f dir); /** * @param vehicle * @return true if the supplied {@link Vehicle} touches a {@link PlayerEntity} */ public abstract boolean doesVehicleTouchPlayers(Vehicle vehicle); /** * Determines if the supplied entity is reachable given the origin and direction. * * @param other * @param origin * @param dir * @return true if reachable (i.e., in sight or projectile can pierce) */ public abstract boolean isEntityReachable(Entity other, Vector2f origin, Vector2f dir); }
6,249
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Timers.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/Timers.java
/* * see license.txt */ package seventh.game; import seventh.shared.TimeStep; import seventh.shared.Timer; import seventh.shared.Updatable; /** * @author Tony * */ public class Timers implements Updatable { private Timer[] timers; /** * */ public Timers(int maxTimers) { this.timers = new Timer[maxTimers]; } /* (non-Javadoc) * @see seventh.shared.Updatable#update(seventh.shared.TimeStep) */ @Override public void update(TimeStep timeStep) { for(int i = 0; i < timers.length; i++) { if(timers[i]!=null) { Timer timer = timers[i]; timer.update(timeStep); if(timer.isExpired()) { timers[i] = null; } } } } /** * Attempts to add a timer * @param timer * @return true if the timer was added; false if there is no more room */ public boolean addTimer(Timer timer) { for(int i = 0; i < timers.length; i++) { if(timers[i]==null) { timers[i] = timer; return true; } } return false; } /** * Removes all of the timers */ public void removeTimers() { for(int i = 0; i < timers.length; i++) { timers[i] = null; } } }
1,373
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
PlayerInfos.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/PlayerInfos.java
/* * see license.txt */ package seventh.game; /** * Simple structure that holds references to all the Players in the game * * @author Tony * */ public interface PlayerInfos { /** * Simple call back mechanism used for iterating through the * available players. * * @author Tony * */ public static interface PlayerInfoIterator { public void onPlayerInfo(PlayerInfo player); } /** * @param id the {@link PlayerInfo} id * @return the {@link PlayerInfo} if found, null if no entity exists with * the supplied id */ public abstract PlayerInfo getPlayerInfo(int id); /** * @return the total number of players in the game */ public abstract int getNumberOfPlayers(); /** * Iterates through all the available players, invoking the * {@link PlayerInfoIterator} for each player. * @param it */ public abstract void forEachPlayerInfo(PlayerInfoIterator it); /** * @return the underlying list of players. For performance reasons * this array may contain empty slots, it is up to the client * to filter these. */ public abstract PlayerInfo[] getPlayerInfos(); /** * @return attempts to find a Player that is alive. Null if none are found */ public abstract Player getRandomAlivePlayer(); public abstract Player getPrevAlivePlayerFrom(Player oldPlayer); public abstract Player getNextAlivePlayerFrom(Player oldPlayer); }
1,574
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetTeam.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetTeam.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetTeam implements NetMessage { public static final int HAS_PLAYERS = 1; public static final int IS_ATTACKER = 2; public static final int IS_DEFENDER = 4; public byte id; public int[] playerIds; private boolean hasPlayers; public boolean isAttacker; public boolean isDefender; /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { id = BufferIO.readTeamId(buffer); hasPlayers = buffer.getBooleanBit(); isAttacker = buffer.getBooleanBit(); isDefender = !isAttacker; if(hasPlayers) { byte len = buffer.getByteBits(BufferIO.numPlayerIdBits()); playerIds = new int[len]; for(byte i = 0; i < len; i++) { playerIds[i] = buffer.getUnsignedByte(); } } } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { hasPlayers = playerIds != null && playerIds.length > 0; BufferIO.writeTeamId(buffer, id); buffer.putBooleanBit(hasPlayers); buffer.putBooleanBit(isAttacker); if(hasPlayers) { buffer.putByteBits( (byte)playerIds.length, BufferIO.numPlayerIdBits()); for(int i = 0; i < playerIds.length; i++) { buffer.putUnsignedByte(playerIds[i]); } } } }
1,786
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetWeapon.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetWeapon.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.game.entities.Entity.Type; import seventh.game.weapons.Weapon.WeaponState; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetWeapon implements NetMessage { public Type type; public short ammoInClip; public short totalAmmo; public WeaponState weaponState; /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { type = BufferIO.readType(buffer); ammoInClip = (short)buffer.getUnsignedByte(); totalAmmo = buffer.getShort(); weaponState = BufferIO.readWeaponState(buffer); } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { BufferIO.writeType(buffer, type); buffer.putUnsignedByte(ammoInClip); buffer.putShort(totalAmmo); BufferIO.writeWeaponState(buffer, weaponState); } }
1,154
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetSound.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetSound.java
/* * see license.txt */ package seventh.game.net; import java.util.List; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.game.SoundEventPool; import seventh.game.events.SoundEmittedEvent; import seventh.math.Vector2f; import seventh.shared.Bits; import seventh.shared.SeventhConstants; import seventh.shared.SoundType; /** * Break sounds up into categories: * * 1) ones that are just spawned at a location * 2) others that are associated with an Entity (can be attached, so * that the sound moves with the entity) * 3) global, ones that are heard always * * @author Tony * */ public class NetSound implements NetMessage { public byte type; public int posX, posY; private boolean hasPositionalInformation; private static final short TILE_WIDTH = 32; private static final short TILE_HEIGHT = 32; public NetSound() { } /** * @param pos */ public NetSound(Vector2f pos) { this.setPos(pos); this.enablePosition(); } public void setPos(Vector2f pos) { this.posX = (int)pos.x; this.posY = (int)pos.y; } public void setSoundType(SoundType soundType) { if(this.hasPositionalInformation) { this.type = Bits.setSignBit(soundType.netValue()); } else { this.type = soundType.netValue(); } } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { /* type = buffer.get(); * * This is actually done by the readNetSound factory * method * */ if(hasPositionalInformation()) { posX = (buffer.getByte() & 0xFF); posX *= TILE_WIDTH; posY = (buffer.getByte() & 0xFF); posY *= TILE_WIDTH; } } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { if(this.hasPositionalInformation) { this.type = Bits.setSignBit(this.type); } buffer.putByte(type); if(this.hasPositionalInformation) { buffer.putByte( (byte)(posX/TILE_WIDTH) ); buffer.putByte( (byte)(posY/TILE_HEIGHT) ); } } /** * @return the {@link SoundType} */ public SoundType getSoundType() { return SoundType.fromNet(Bits.getWithoutSignBit(type)); } /** * Determines if this {@link NetSound} has positional (x,y) * information * * @return the hasPositionalInformation */ public boolean hasPositionalInformation() { return Bits.isSignBitSet(this.type); } /** * Enable the positional information of this NetSound */ public void enablePosition() { this.hasPositionalInformation = true; } /** * Converts the {@link SoundEmittedEvent} into a {@link NetSound} * @param event */ public static NetSound toNetSound(SoundEmittedEvent event) { NetSound sound = null; switch(event.getSoundType().getSourceType()) { case POSITIONAL: { sound = new NetSound(event.getPos()); break; } case REFERENCED: case REFERENCED_ATTACHED: { sound = new NetSoundByEntity(event.getPos(), event.getEntityId()); break; } default: sound = new NetSound(); } sound.setSoundType(event.getSoundType()); return sound; } public static NetSound readNetSound(IOBuffer buffer) { NetSound snd = null; byte type = buffer.getByte(); switch(SoundType.fromNet(Bits.getWithoutSignBit(type)).getSourceType()) { case REFERENCED: case REFERENCED_ATTACHED: snd = new NetSoundByEntity(); snd.type = type; snd.read(buffer); break; case POSITIONAL: snd = new NetSound(); snd.type = type; snd.read(buffer); break; case GLOBAL: snd = new NetSound(); snd.type = type; snd.read(buffer); break; default: throw new IllegalArgumentException("Invalid NetSound type: " + type); } return snd; } /** * Consolidates the {@link List} of {@link SoundEmittedEvent}'s, which means it will * remove any duplicates * * @param sounds * @return the list of {@link NetSound}s */ public static NetSound[] consolidateToNetSounds(List<SoundEmittedEvent> sounds) { int sum = 0; int size = sounds.size(); SoundEmittedEvent[] buffer = new SoundEmittedEvent[SeventhConstants.MAX_SOUNDS]; for(int i = 0; i < size; i++) { SoundEmittedEvent sndEvent = sounds.get(i); if(buffer[sndEvent.getBufferIndex()] == null) { buffer[sndEvent.getBufferIndex()] = sndEvent; sum++; } } NetSound[] snds = new NetSound[sum]; int index = 0; for(int i = 0; i < buffer.length; i++) { SoundEmittedEvent sndEvent = buffer[i]; if(sndEvent != null) { snds[index++] = NetSound.toNetSound(sndEvent); } } return snds; } /** * @param sounds * @return converts the List of {@link SoundEmittedEvent} to the respective {@link NetSound} array */ public static NetSound[] toNetSounds(List<SoundEmittedEvent> sounds) { int size = sounds.size(); NetSound[] snds = new NetSound[size]; for(int i = 0; i < size; i++) { snds[i] = NetSound.toNetSound(sounds.get(i)); } return snds; } /** * @param sounds * @return converts the List of {@link SoundEmittedEvent} to the respective {@link NetSound} array */ public static NetSound[] toNetSounds(SoundEventPool sounds) { int size = sounds.numberOfSounds(); NetSound[] snds = new NetSound[size]; for(int i = 0; i < size; i++) { snds[i] = NetSound.toNetSound(sounds.getSound(i)); } return snds; } }
6,670
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetVehicle.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetVehicle.java
/* * see license.txt */ package seventh.game.net; /** * * @author Tony * */ public class NetVehicle extends NetEntity { }
130
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetBullet.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetBullet.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetBullet extends NetEntity { public byte damage; public int ownerId; /** * */ public NetBullet() { this.type = Type.BULLET; } /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); ownerId = BufferIO.readPlayerId(buffer); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); BufferIO.writePlayerId(buffer, ownerId); } }
874
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetGameState.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetGameState.java
/* * see license.txt */ package seventh.game.net; import harenet.BitArray; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.game.game_types.GameType.Type; import seventh.network.messages.BufferIO; import seventh.shared.SeventhConstants; /** * Full game state * * @author Tony * */ public class NetGameState implements NetMessage { private static final int FL_GAMETYPE = (1<<0); private static final int FL_ENTITIES = (1<<1); private static final int FL_GAMEMAP = (1<<2); private static final int FL_GAMESTATS= (1<<3); private static final int FL_DESTRUCTABLES = (1<<4); private static final int FL_ADDITIONS = (1<<5); public NetGameTypeInfo gameType; public NetEntity[] entities; public NetMap map; public NetGameStats stats; public NetMapDestructables mapDestructables; public NetMapAdditions mapAdditions; protected byte bits; private BitArray bitArray; private int numberOfBytes; public NetGameState() { bitArray = new BitArray(SeventhConstants.MAX_ENTITIES); entities = new NetEntity[SeventhConstants.MAX_ENTITIES]; numberOfBytes = bitArray.numberOfBytes(); } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { bits = buffer.getByte(); if( (bits & FL_GAMETYPE) != 0) { gameType = NetGameTypeInfo.newNetGameTypeInfo(Type.fromNet(buffer.getByteBits(Type.numOfBits()))); gameType.read(buffer); } if( (bits & FL_ENTITIES) != 0) { for(int i = 0; i < numberOfBytes; i++) { bitArray.setDataElement(i, buffer.getByte()); } for(int i = 0; i < entities.length; i++) { if(bitArray.getBit(i)) { entities[i] = BufferIO.readEntity(buffer); entities[i].id = i; } } } if ( (bits & FL_GAMEMAP) != 0) { map = new NetMap(); map.read(buffer); } if( (bits & FL_GAMESTATS) != 0) { stats = new NetGameStats(); stats.read(buffer); } if( (bits & FL_DESTRUCTABLES) != 0) { mapDestructables = new NetMapDestructables(); mapDestructables.read(buffer); } if( (bits & FL_ADDITIONS) != 0) { mapAdditions = new NetMapAdditions(); mapAdditions.read(buffer); } } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { bits = 0; if(gameType != null) { bits |= FL_GAMETYPE; } if(entities != null && entities.length > 0) { bits |= FL_ENTITIES; } if(map != null) { bits |= FL_GAMEMAP; } if(stats != null) { bits |= FL_GAMESTATS; } if(mapDestructables != null && mapDestructables.length > 0) { bits |= FL_DESTRUCTABLES; } if(mapAdditions != null && mapAdditions.tiles.length > 0) { bits |= FL_ADDITIONS; } buffer.putByte(bits); if(gameType != null) { buffer.putByteBits(gameType.type, Type.numOfBits()); gameType.write(buffer); } if(entities != null && entities.length > 0) { bitArray.clear(); for(int i = 0; i < entities.length; i++) { if(entities[i]!=null) { bitArray.setBit(i); } } byte[] data = bitArray.getData(); for(int i = 0; i < data.length; i++) { buffer.putByte(data[i]); } for(int i = 0; i < entities.length; i++) { if(entities[i]!=null) { entities[i].write(buffer); } } } if(map != null) { map.write(buffer); } if(stats != null) { stats.write(buffer); } if( (bits & FL_DESTRUCTABLES) != 0) { mapDestructables.write(buffer); } if( (bits & FL_ADDITIONS) != 0) { mapAdditions.write(buffer); } } }
4,544
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetSoundByEntity.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetSoundByEntity.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.math.Vector2f; /** * A sound in which is sourced/attached to an entity * * @author Tony * */ public class NetSoundByEntity extends NetSound { public int entityId; public NetSoundByEntity() { } /** * @param pos * @param entityId */ public NetSoundByEntity(Vector2f pos, int entityId) { /* NOTE: this does not set the enabled position flag */ setPos(pos); this.entityId = entityId; } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); this.entityId = buffer.getUnsignedByte(); } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); buffer.putUnsignedByte(this.entityId); } }
1,074
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetSmoke.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetSmoke.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; /** * @author Tony * */ public class NetSmoke extends NetEntity { /** * */ public NetSmoke() { this.type = Type.SMOKE; } /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); } }
674
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetFire.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetFire.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetFire extends NetEntity { public int ownerId; /** * */ public NetFire() { this.type = Type.FIRE; } /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); ownerId = BufferIO.readPlayerId(buffer); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); BufferIO.writePlayerId(buffer, ownerId); } }
835
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetPlayer.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetPlayer.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.State; import seventh.game.entities.Entity.Type; import seventh.network.messages.BufferIO; /** * The full player state. This is message is for the local player. * * @author Tony * */ public class NetPlayer extends NetEntity { public static final int HAS_WEAPON = 2; public static final int IS_OPERATING_VEHICLE = 4; public static final int IS_SMOKE_GRENADES = 8; public NetPlayer() { this.type = Type.PLAYER; } public State state; public byte grenades; public byte health; public boolean isOperatingVehicle; public boolean isSmokeGrenades; public int vehicleId; protected byte bits; public NetWeapon weapon; /* (non-Javadoc) * @see seventh.game.net.NetEntity#checkBits() */ protected void checkBits() { if(weapon!=null) { bits |= HAS_WEAPON; } if(isOperatingVehicle) { bits = 0; /* clear the weapon isRotated */ bits |= IS_OPERATING_VEHICLE; } if(isSmokeGrenades) { bits |= IS_SMOKE_GRENADES; } } /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); bits = buffer.getByte(); orientation = BufferIO.readAngle(buffer); state = BufferIO.readState(buffer); grenades = buffer.getByteBits(4); health = buffer.getByteBits(7); if((bits & HAS_WEAPON) != 0) { weapon = new NetWeapon(); weapon.read(buffer); } if((bits & IS_OPERATING_VEHICLE) != 0) { isOperatingVehicle = true; vehicleId = buffer.getUnsignedByte(); } if((bits & IS_SMOKE_GRENADES) != 0) { isSmokeGrenades = true; } } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); bits = 0; checkBits(); buffer.putByte(bits); BufferIO.writeAngle(buffer, orientation); BufferIO.writeState(buffer, state); buffer.putByteBits(grenades, 4); buffer.putByteBits(health, 7); if(weapon != null && !isOperatingVehicle) { weapon.write(buffer); } if(isOperatingVehicle) { buffer.putUnsignedByte(vehicleId); } } }
2,765
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetMapAddition.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetMapAddition.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.network.messages.BufferIO; /** * A tile addition, specifies the location of the * tile and type of tile * * @author Tony * */ public class NetMapAddition implements NetMessage { public int tileX, tileY; public int type; public NetMapAddition() { } public NetMapAddition(int tileX, int tileY, int type) { this.tileX = tileX; this.tileY = tileY; this.type = type; } @Override public void read(IOBuffer buffer) { this.tileX = buffer.getUnsignedByte(); this.tileY = buffer.getUnsignedByte(); this.type = BufferIO.readTileType(buffer); } @Override public void write(IOBuffer buffer) { buffer.putUnsignedByte(this.tileX); buffer.putUnsignedByte(this.tileY); BufferIO.writeTileType(buffer, this.type); } }
974
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetExplosion.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetExplosion.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetExplosion extends NetEntity { public int ownerId; /** * */ public NetExplosion() { this.type = Type.EXPLOSION; } /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); ownerId = BufferIO.readPlayerId(buffer); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); BufferIO.writePlayerId(buffer, ownerId); } }
850
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetLight.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetLight.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; /** * @author Tony * */ public class NetLight extends NetEntity { public short r, g, b; public short luminacity; public short size; /** */ public NetLight() { this.type = Type.LIGHT_BULB; } /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); r = (short)(buffer.getUnsignedByte()); g = (short)(buffer.getUnsignedByte()); b = (short)(buffer.getUnsignedByte()); luminacity = (short)(buffer.getUnsignedByte()); size = buffer.getShort(); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); buffer.putUnsignedByte(r); buffer.putUnsignedByte(g); buffer.putUnsignedByte(b); buffer.putUnsignedByte(luminacity); buffer.putShort(size); } }
1,197
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetRocket.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetRocket.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetRocket extends NetBullet { public NetRocket() { this.type = Type.ROCKET; } /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); this.orientation = BufferIO.readAngle(buffer); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); BufferIO.writeAngle(buffer, orientation); } }
792
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetPlayerStat.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetPlayerStat.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.network.messages.BufferIO; import seventh.shared.Bits; /** * @author Tony * */ public class NetPlayerStat implements NetMessage { public int playerId; public String name; public short kills; public short deaths; public short assists; public byte hitPercentage; public short ping; public int joinTime; public byte teamId; public boolean isBot; public boolean isCommander; /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { playerId = BufferIO.readPlayerId(buffer); name = BufferIO.readString(buffer); kills = Bits.getSignedShort(buffer.getShortBits(10), 10); deaths = buffer.getShortBits(10); assists = buffer.getShortBits(10); hitPercentage = buffer.getByteBits(7); ping = buffer.getShortBits(9); joinTime = buffer.getInt(); teamId = BufferIO.readTeamId(buffer); isBot = buffer.getBooleanBit(); isCommander = buffer.getBooleanBit(); } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { BufferIO.writePlayerId(buffer, playerId); BufferIO.writeString(buffer, name != null ? name : ""); buffer.putShortBits(Bits.setSignedShort(kills, 10), 10); buffer.putShortBits(deaths, 10); buffer.putShortBits(assists, 10); buffer.putByteBits(hitPercentage, 7); buffer.putShortBits(ping, 9); buffer.putInt(joinTime); BufferIO.writeTeamId(buffer, teamId); buffer.putBooleanBit(isBot); buffer.putBooleanBit(isCommander); } }
1,929
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetEntity.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetEntity.java
/* * see license.txt */ package seventh.game.net; import java.util.List; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetEntity implements NetMessage { public Type type; public int id; // public byte dir; public short orientation; public int posX; public int posY; // public byte width; // public byte height; // public byte events; /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { type = BufferIO.readType(buffer); // NOTE: Must match BufferIO.readEntity //type = buffer.get(); // id = buffer.getInt(); // orientation = buffer.getShort(); // posX = buffer.getShort(); // posY = buffer.getShort(); posX = buffer.getIntBits(13); // max X & Y of 256x256 tiles (32x32 tiles) ~8191 posY = buffer.getIntBits(13); // width = buffer.get(); // height = buffer.get(); // events = buffer.get(); } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { BufferIO.writeType(buffer, type); //buffer.put(type); // buffer.putInt(id); // buffer.putShort(orientation); // buffer.putShort(posX); // buffer.putShort(posY); buffer.putIntBits(posX, 13); buffer.putIntBits(posY, 13); // buffer.put(width); // buffer.put(height); // buffer.put(events); } /** * Copies the Entity array into the NetEntity array * @param entities * @param results * @return the passed in NetEntity array */ public static NetEntity[] toNetEntities(Entity[] entities, NetEntity[] results) { for(int i = 0; i < entities.length; i++) { if(entities[i]!=null) { results[i] = entities[i].getNetEntity(); } } return results; } /** * @param entities * @return converts the List of {@link Entity} to the respective {@link NetEntity} array */ public static NetEntity[] toNetEntities(List<Entity> entities, NetEntity[] results) { int size = entities.size(); for(int i = 0; i < size; i++) { Entity ent = entities.get(i); if(ent != null) { results[ent.getId()] = ent.getNetEntity(); } } return results; } }
2,970
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetMap.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetMap.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetMap implements NetMessage { public int id; public String path; public String name; /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { id = buffer.getInt(); path = BufferIO.readString(buffer); name = BufferIO.readString(buffer); } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { buffer.putInt(id); BufferIO.writeString(buffer, path); BufferIO.writeString(buffer, name); } }
869
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetPlayerPartialStat.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetPlayerPartialStat.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.network.messages.BufferIO; import seventh.shared.Bits; /** * A partial player statistics (updated at a higher frequency than full network stats) * * @author Tony * */ public class NetPlayerPartialStat implements NetMessage { public int playerId; public short kills; public short deaths; public short assists; /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { playerId = BufferIO.readPlayerId(buffer); kills = Bits.getSignedShort(buffer.getShortBits(10), 10); deaths = buffer.getShortBits(10); assists = buffer.getShortBits(10); } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { BufferIO.writePlayerId(buffer, playerId); buffer.putShortBits(Bits.setSignedShort(kills, 10), 10); buffer.putShortBits(deaths, 10); buffer.putShortBits(assists, 10); } }
1,230
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetSquad.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetSquad.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.game.PlayerClass; import seventh.game.game_types.cmd.CommanderGameType; import seventh.game.game_types.cmd.Squad; import seventh.network.messages.BufferIO; import seventh.shared.SeventhConstants; /** * The {@link CommanderGameType} contains {@link Squad}s which have a number * of {@link PlayerClass}s. This defines which players are which class. * * @author Tony * */ public class NetSquad implements NetMessage { // The array index relates the player players ID public PlayerClass[] playerClasses = new PlayerClass[SeventhConstants.MAX_PLAYERS]; @Override public void read(IOBuffer buffer) { int playerIndexBits = buffer.getIntBits(SeventhConstants.MAX_PLAYERS); for(int i = 0; i < SeventhConstants.MAX_PLAYERS; i++) { if(((playerIndexBits >> i) & 1) == 1) { playerClasses[i] = BufferIO.readPlayerClassType(buffer); } } } @Override public void write(IOBuffer buffer) { if(playerClasses != null) { int playerIndexBits = 0; for(int i = 0; i < playerClasses.length; i++) { if(playerClasses[i] != null) { playerIndexBits = (playerIndexBits << i) | 1; } } buffer.putIntBits(playerIndexBits, SeventhConstants.MAX_PLAYERS); for(int i = 0; i < playerClasses.length; i++) { if(playerClasses[i] != null) { BufferIO.writePlayerClassType(buffer, playerClasses[i]); } } } else { buffer.putIntBits(0, SeventhConstants.MAX_PLAYERS); } } }
1,876
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetFlag.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetFlag.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetFlag extends NetEntity { public int carriedBy; /** */ public NetFlag() { } /** * The type of flag this is * @param type */ public NetFlag(Type type) { this.type = type; } /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(harenet.IOBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); this.carriedBy = BufferIO.readPlayerId(buffer); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(harenet.IOBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); BufferIO.writePlayerId(buffer, carriedBy); } }
925
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetCtfGameTypeInfo.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetCtfGameTypeInfo.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetCtfGameTypeInfo extends NetGameTypeInfo { public Rectangle axisHomeBase; public Rectangle alliedHomeBase; public Vector2f axisFlagSpawn; public Vector2f alliedFlagSpawn; public NetCtfGameTypeInfo() { } @Override public void read(IOBuffer buffer) { super.read(buffer); this.axisHomeBase = BufferIO.readRect(buffer); this.alliedHomeBase = BufferIO.readRect(buffer); this.axisFlagSpawn = BufferIO.readVector2f(buffer); this.alliedFlagSpawn = BufferIO.readVector2f(buffer); } @Override public void write(IOBuffer buffer) { super.write(buffer); BufferIO.writeRect(buffer, this.axisHomeBase); BufferIO.writeRect(buffer, this.alliedHomeBase); BufferIO.writeVector2f(buffer, this.axisFlagSpawn); BufferIO.writeVector2f(buffer, this.alliedFlagSpawn); } }
1,166
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetGameUpdate.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetGameUpdate.java
/* * see license.txt */ package seventh.game.net; import harenet.BitArray; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.network.messages.BufferIO; import seventh.shared.SeventhConstants; /** * @author Tony * */ public class NetGameUpdate implements NetMessage { public static final int ENTITIES_MASK = (1<<0); public static final int SOUND_MASK = (1<<1); public static final int DEAD_ENTS_MASK = (1<<2); public static final int SPEC_MASK = (1<<3); public NetEntity[] entities; public NetSound[] sounds; public byte numberOfSounds; public int time; public int spectatingPlayerId = -1; private BitArray entityBitArray; public BitArray deadPersistantEntities; private int numberOfBytes; private boolean hasDeadEntities; protected byte bits; /** * */ public NetGameUpdate() { entityBitArray = new BitArray(SeventhConstants.MAX_ENTITIES); entities = new NetEntity[SeventhConstants.MAX_ENTITIES]; deadPersistantEntities = new BitArray(SeventhConstants.MAX_PERSISTANT_ENTITIES); hasDeadEntities = true; numberOfBytes = entityBitArray.numberOfBytes(); } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { bits = buffer.getByte(); if( (bits & ENTITIES_MASK) != 0) { for(int i = 0; i < numberOfBytes; i++) { entityBitArray.setDataElement(i, buffer.getByte()); } for(int i = 0; i < entities.length; i++) { if(entityBitArray.getBit(i)) { entities[i] = BufferIO.readEntity(buffer); entities[i].id = i; } } } if( (bits & SOUND_MASK) != 0) { numberOfSounds = buffer.getByte(); sounds = new NetSound[numberOfSounds]; for(short i = 0; i < numberOfSounds; i++) { sounds[i] = NetSound.readNetSound(buffer); } } if( (bits & DEAD_ENTS_MASK) != 0) { hasDeadEntities = true; for(int i = 0; i < deadPersistantEntities.numberOfBytes(); i++) { deadPersistantEntities.setDataElement(i, buffer.getByte()); } } if( (bits & SPEC_MASK) != 0) { spectatingPlayerId = buffer.getUnsignedByte(); } time = buffer.getInt(); } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { bits = 0; if(entities != null && entities.length > 0) { bits |= ENTITIES_MASK; } if(numberOfSounds > 0) { bits |= SOUND_MASK; } if(hasDeadEntities) { bits |= DEAD_ENTS_MASK; } if(spectatingPlayerId > -1) { bits |= SPEC_MASK; } buffer.putByte(bits); if(entities != null && entities.length > 0) { entityBitArray.clear(); for(int i = 0; i < entities.length; i++) { if(entities[i]!=null) { entityBitArray.setBit(i); } } byte[] data = entityBitArray.getData(); for(int i = 0; i < data.length; i++) { buffer.putByte(data[i]); } for(short i = 0; i < entities.length; i++) { if(entities[i]!=null) { entities[i].write(buffer); } } } if(numberOfSounds > 0) { buffer.putByte(numberOfSounds); for(byte i = 0; i < numberOfSounds; i++) { sounds[i].write(buffer); } } if(hasDeadEntities) { byte[] data = deadPersistantEntities.getData(); for(int i = 0; i < data.length; i++) { buffer.putByte(data[i]); } } if(spectatingPlayerId > -1) { buffer.putUnsignedByte(spectatingPlayerId); } buffer.putInt(this.time); } /** * Set the number of sounds * * @param sounds */ public void setNetSounds(NetSound[] sounds) { this.sounds = sounds; this.numberOfSounds = (byte) sounds.length; } }
4,734
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetGameTypeInfo.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetGameTypeInfo.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.game.game_types.GameType.Type; /** * @author Tony * */ public class NetGameTypeInfo implements NetMessage { public static final NetGameTypeInfo newNetGameTypeInfo(Type gameType) { NetGameTypeInfo result = null; switch(gameType) { case CMD: result = new NetCommanderGameTypeInfo(); break; case CTF: result = new NetCtfGameTypeInfo(); break; case OBJ: case TDM: default: result = new NetGameTypeInfo(); } result.type = gameType.netValue(); return result; } public long maxTime; public int maxScore; public NetTeam alliedTeam; public NetTeam axisTeam; public byte type; /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { maxTime = buffer.getLong(); maxScore = buffer.getInt(); // type = buffer.getByte(); Handled by polymorphic handling of network types alliedTeam = new NetTeam(); alliedTeam.read(buffer); alliedTeam.id = 1; axisTeam = new NetTeam(); axisTeam.read(buffer); axisTeam.id = 2; } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { buffer.putLong(maxTime); buffer.putInt(maxScore); // buffer.putByte(type); alliedTeam.write(buffer); axisTeam.write(buffer); } }
1,804
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetGamePartialStats.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetGamePartialStats.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetGamePartialStats implements NetMessage { public NetPlayerPartialStat[] playerStats; public NetTeamStat alliedTeamStats; public NetTeamStat axisTeamStats; /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { byte len = buffer.getByteBits(BufferIO.numPlayerIdBits()); if(len > 0) { playerStats = new NetPlayerPartialStat[len]; for(byte i = 0; i < len; i++) { playerStats[i] = new NetPlayerPartialStat(); playerStats[i].read(buffer); } } alliedTeamStats = new NetTeamStat(); alliedTeamStats.read(buffer); alliedTeamStats.id = 1; axisTeamStats = new NetTeamStat(); axisTeamStats.read(buffer); axisTeamStats.id = 2; } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { if(playerStats != null) { byte len = (byte)playerStats.length; buffer.putByteBits(len, BufferIO.numPlayerIdBits()); for(byte i = 0; i < len; i++) { playerStats[i].write(buffer); } } else { buffer.putByteBits( (byte)0, BufferIO.numPlayerIdBits() ); } alliedTeamStats.write(buffer); axisTeamStats.write(buffer); } }
1,731
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetDroppedItem.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetDroppedItem.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; import seventh.network.messages.BufferIO; /** * A dropped item * * @author Tony * */ public class NetDroppedItem extends NetEntity { public NetDroppedItem() { this.type = Type.DROPPED_ITEM; } public Type droppedItem; /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); droppedItem = BufferIO.readType(buffer); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); BufferIO.writeType(buffer, droppedItem); } }
851
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetCommanderGameTypeInfo.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetCommanderGameTypeInfo.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; /** * @author Tony * */ public class NetCommanderGameTypeInfo extends NetGameTypeInfo { public NetSquad alliedSquad; public NetSquad axisSquad; @Override public void read(IOBuffer buffer) { super.read(buffer); this.alliedSquad = new NetSquad(); this.alliedSquad.read(buffer); this.axisSquad = new NetSquad(); this.axisSquad.read(buffer); } @Override public void write(IOBuffer buffer) { super.write(buffer); this.alliedSquad.write(buffer); this.axisSquad.write(buffer); } }
700
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetBombTarget.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetBombTarget.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; /** * El Bomba * * @author Tony * */ public class NetBombTarget extends NetEntity { public boolean isRotated; public NetBombTarget() { this.type = Type.BOMB_TARGET; } public boolean rotated90() { return isRotated; } public void rotate90() { isRotated=true; } /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); isRotated = buffer.getBooleanBit(); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); buffer.putBooleanBit(isRotated); } }
927
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetBomb.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetBomb.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; /** * El Bomba * * @author Tony * */ public class NetBomb extends NetEntity { public NetBomb() { this.type = Type.BOMB; } public int timeRemaining; /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); timeRemaining = buffer.getInt(); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); buffer.putInt(timeRemaining); } }
763
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetGameStats.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetGameStats.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; import seventh.network.messages.BufferIO; /** * @author Tony * */ public class NetGameStats implements NetMessage { public NetPlayerStat[] playerStats; public NetTeamStat alliedTeamStats; public NetTeamStat axisTeamStats; /** * */ public NetGameStats() { } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { byte len = buffer.getByteBits(BufferIO.numPlayerIdBits()); if(len > 0) { playerStats = new NetPlayerStat[len]; for(byte i = 0; i < len; i++) { playerStats[i] = new NetPlayerStat(); playerStats[i].read(buffer); } } alliedTeamStats = new NetTeamStat(); alliedTeamStats.read(buffer); alliedTeamStats.id = 1; axisTeamStats = new NetTeamStat(); axisTeamStats.read(buffer); axisTeamStats.id = 2; } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { if(playerStats != null) { byte len = (byte)playerStats.length; buffer.putByteBits(len, BufferIO.numPlayerIdBits()); for(byte i = 0; i < len; i++) { playerStats[i].write(buffer); } } else { buffer.putByteBits( (byte)0, BufferIO.numPlayerIdBits() ); } alliedTeamStats.write(buffer); axisTeamStats.write(buffer); } }
1,775
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetBase.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetBase.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; /** * @author Tony * */ public class NetBase extends NetEntity { public NetBase(Type type) { this.type = type; } public NetBase() { } @Override public void read(IOBuffer buffer) { super.read(buffer); } @Override public void write(IOBuffer buffer) { super.write(buffer); } }
499
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetMapDestructables.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetMapDestructables.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; /** * @author Tony * */ public class NetMapDestructables implements NetMessage { public int length; /** Should be viewed as Unsigned Bytes, they are stored in the form * of even index = x, odd index = y, example: [1,0,4,7] => tiles at: (1,0) and (4,7) */ public int[] tiles; @Override public void read(IOBuffer buffer) { this.length = buffer.getInt(); if(this.length > 0) { this.tiles = new int[this.length]; for(int i = 0; i < this.tiles.length; i += 2) { int x = buffer.getUnsignedByte(); int y = buffer.getUnsignedByte(); this.tiles[i + 0] = x; this.tiles[i + 1] = y; } } } @Override public void write(IOBuffer buffer) { buffer.putInt(this.length); if(this.length > 0) { for(int i = 0; i < this.tiles.length; i += 2) { buffer.putUnsignedByte(this.tiles[i + 0]); buffer.putUnsignedByte(this.tiles[i + 1]); } } } }
1,227
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetMapAdditions.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetMapAdditions.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; /** * Additions made to the Map by players * * @author Tony * */ public class NetMapAdditions implements NetMessage { public NetMapAddition[] tiles; @Override public void read(IOBuffer buffer) { int length = buffer.getInt(); if(length > 0) { this.tiles = new NetMapAddition[length]; for(int i = 0; i < this.tiles.length; i++) { NetMapAddition addition = new NetMapAddition(); addition.read(buffer); this.tiles[i] = addition; } } } @Override public void write(IOBuffer buffer) { if(this.tiles != null) { buffer.putInt(this.tiles.length); for(int i = 0; i < this.tiles.length; i++) { NetMapAddition add = this.tiles[i]; add.write(buffer); } } else { buffer.putInt(0); } } }
1,102
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetDoor.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetDoor.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.Type; import seventh.network.messages.BufferIO; /** * A Door * * @author Tony * */ public class NetDoor extends NetEntity { public byte hinge; public NetDoor() { this.type = Type.DOOR; } /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); this.orientation = BufferIO.readAngle(buffer); this.hinge = buffer.getByteBits(3); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); BufferIO.writeAngle(buffer, orientation); buffer.putByteBits(hinge, 3); } }
913
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetTeamStat.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetTeamStat.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import harenet.messages.NetMessage; /** * @author Tony * */ public class NetTeamStat implements NetMessage { public byte id; public int score; /* (non-Javadoc) * @see seventh.network.messages.NetMessage#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { // id = BufferIO.readTeamId(buffer); is assigned by order in packet score = buffer.getShort(); } /* (non-Javadoc) * @see seventh.network.messages.NetMessage#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { // BufferIO.writeTeamId(buffer, id); buffer.putShort( (short) score); } }
769
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetPlayerPartial.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetPlayerPartial.java
/* * see license.txt */ package seventh.game.net; import harenet.IOBuffer; import seventh.game.entities.Entity.State; import seventh.game.entities.Entity.Type; import seventh.game.weapons.Weapon.WeaponState; import seventh.network.messages.BufferIO; /** * This is a partial message for other entities that are NOT the local * player. * * @author Tony * */ public class NetPlayerPartial extends NetEntity { public NetPlayerPartial() { this.type = Type.PLAYER_PARTIAL; } public State state; public byte health; public NetWeapon weapon; public boolean isOperatingVehicle; public int vehicleId; /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(java.nio.ByteBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); orientation = BufferIO.readAngle(buffer); state = BufferIO.readState(buffer); health = buffer.getByteBits(7); /* If this player is in a vehicle, * send the vehicle ID in lieu of * weapon information */ if(state.isVehicleState()) { isOperatingVehicle = true; vehicleId = buffer.getUnsignedByte(); } else { readWeapon(buffer); } } /** * Reads in the {@link NetWeapon} * @param buffer */ protected void readWeapon(IOBuffer buffer) { weapon = new NetWeapon(); weapon.type = BufferIO.readType(buffer); weapon.weaponState = BufferIO.readWeaponState(buffer); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(java.nio.ByteBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); BufferIO.writeAngle(buffer, orientation); BufferIO.writeState(buffer, state); buffer.putByteBits(health, 7); /* If this player is in a vehicle, * send the vehicle ID in lieu of * weapon information */ if(state.isVehicleState()) { buffer.putUnsignedByte(vehicleId); } else { writeWeapon(buffer); } } /** * Writes out the {@link NetWeapon} * @param buffer */ protected void writeWeapon(IOBuffer buffer) { if(weapon != null) { BufferIO.writeType(buffer, weapon.type); BufferIO.writeWeaponState(buffer, weapon.weaponState); } else { BufferIO.writeType(buffer, Type.UNKNOWN); BufferIO.writeWeaponState(buffer, WeaponState.UNKNOWN); } } }
2,734
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NetTank.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/net/NetTank.java
/* * see license.txt */ package seventh.game.net; import seventh.game.entities.Entity.Type; import seventh.network.messages.BufferIO; import seventh.shared.SeventhConstants; import harenet.IOBuffer; /** * Tank information * * @author Tony * */ public class NetTank extends NetVehicle { public byte state; public short turretOrientation; public byte primaryWeaponState; public byte secondaryWeaponState; public int operatorId; /** */ public NetTank() { this(Type.SHERMAN_TANK); } /** * @param type the type of tank */ public NetTank(Type type) { this.type = type; this.operatorId = SeventhConstants.INVALID_PLAYER_ID; } /* (non-Javadoc) * @see seventh.game.net.NetEntity#read(harenet.IOBuffer) */ @Override public void read(IOBuffer buffer) { super.read(buffer); state = buffer.getByte(); orientation = BufferIO.readAngle(buffer); turretOrientation = BufferIO.readAngle(buffer); primaryWeaponState = buffer.getByte(); secondaryWeaponState = buffer.getByte(); operatorId = BufferIO.readPlayerId(buffer); } /* (non-Javadoc) * @see seventh.game.net.NetEntity#write(harenet.IOBuffer) */ @Override public void write(IOBuffer buffer) { super.write(buffer); buffer.putByte(state); BufferIO.writeAngle(buffer, orientation); BufferIO.writeAngle(buffer, turretOrientation); buffer.putByte(primaryWeaponState); buffer.putByte(secondaryWeaponState); BufferIO.writePlayerId(buffer, operatorId); } }
1,697
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Base.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/Base.java
/* * see license.txt */ package seventh.game.entities; import seventh.game.Game; import seventh.game.net.NetBase; import seventh.game.net.NetEntity; import seventh.game.weapons.Bullet; import seventh.map.Map; import seventh.math.Vector2f; import seventh.shared.SoundType; /** * Base in which the team must protect. * * @author Tony * */ public class Base extends Entity { private NetBase netBase; /** * @param position * @param game * @param type */ public Base(Game game, Vector2f position, Type type) { super(position, 0, game, type); this.netBase = new NetBase(getType()); Map map = game.getMap(); this.bounds.setSize(map.getTileWidth() * 2, map.getTileHeight() * 2); this.bounds.setLocation(position); int health = 100; this.setHealth(health); this.setMaxHealth(health); } @Override public void damage(Entity damager, int amount) { if(damager instanceof Bullet) { Bullet bullet = (Bullet) damager; bullet.kill(this); game.emitSound(bullet.getId(), SoundType.IMPACT_METAL, bullet.getCenterPos()); } super.damage(damager, amount); } @Override public NetEntity getNetEntity() { setNetEntity(netBase); return this.netBase; } }
1,404
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
DummyBotPlayerEntity.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/DummyBotPlayerEntity.java
/* * see license.txt */ package seventh.game.entities; import seventh.game.Game; import seventh.game.PlayerClass; import seventh.math.Vector2f; /** * Just stands there, so I can shoot them for testing purposes. * * @author Tony * */ public class DummyBotPlayerEntity extends PlayerEntity { /** * @param id * @param position * @param game */ public DummyBotPlayerEntity(int id, PlayerClass playerClass, Vector2f position, Game game) { super(id, playerClass, position, game); } }
538
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
HealthPack.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/HealthPack.java
/* * see license.txt */ package seventh.game.entities; import seventh.game.Game; import seventh.game.net.NetEntity; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; /** * Health pack which adds health to a Player's entity. * * @author Tony * */ public class HealthPack extends Entity { private NetEntity netEntity; /** * @param id * @param position * @param game */ public HealthPack(Vector2f position, final Game game) { super(position, 0, game, Type.HEALTH_PACK); this.onTouch = new OnTouchListener() { @Override public void onTouch(Entity me, Entity other) { if(other.isAlive() && other.getType().equals(Type.PLAYER) && !other.isAtMaxHealth()) { other.setHealth(other.getMaxHealth()); game.emitSound(getId(), SoundType.HEALTH_PACK_PICKUP, getCenterPos()); softKill(); } } }; this.bounds.width = 16; this.bounds.height = 16; this.netEntity = new NetEntity(); this.netEntity.type = Type.HEALTH_PACK; } /* (non-Javadoc) * @see seventh.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { setNetEntity(this.netEntity); return this.netEntity; } /* (non-Javadoc) * @see seventh.game.Entity#canTakeDamage() */ @Override public boolean canTakeDamage() { return false; } /* (non-Javadoc) * @see seventh.game.Entity#update(seventh.shared.TimeStep) */ @Override public boolean update(TimeStep timeStep) { game.doesTouchPlayers(this); return true; } }
1,809
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
DroppedItem.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/DroppedItem.java
/* * see license.txt */ package seventh.game.entities; import seventh.game.Game; import seventh.game.net.NetDroppedItem; import seventh.game.net.NetEntity; import seventh.game.weapons.Weapon; import seventh.math.Vector2f; import seventh.shared.TimeStep; /** * Represents a dropped item that can be picked up by a player. * * @author Tony * */ public class DroppedItem extends Entity { private NetDroppedItem netEntity; private Weapon droppedItem; private long timeToLive; /** * @param position * @param game */ public DroppedItem(Vector2f position, Game game, Weapon droppedItem) { super(position, 0, game, Type.DROPPED_ITEM); this.droppedItem = droppedItem; this.bounds.width = 24; this.bounds.height = 24; this.orientation = (float)Math.toRadians(game.getRandom().nextInt(360)); this.netEntity = new NetDroppedItem(); this.setNetEntity(netEntity); this.netEntity.type = Type.DROPPED_ITEM; this.netEntity.droppedItem = droppedItem.getType(); this.timeToLive = 1 * 60 * 1000; // stay on the ground for 1 minute } /* (non-Javadoc) * @see seventh.game.Entity#update(seventh.shared.TimeStep) */ @Override public boolean update(TimeStep timeStep) { super.update(timeStep); if(timeToLive > 0) { timeToLive -= timeStep.getDeltaTime(); } else { kill(null); } /* if we haven't been picked up yet, * lets check and see if any entities are trying * to pick us up */ if(isAlive()) { PlayerEntity[] players = game.getPlayerEntities(); int size = players.length; for(int i = 0; i < size; i++) { PlayerEntity ent = players[i]; if(canBePickedUpBy(ent)) { if(pickup(ent)) { break; } } } } return true; } /** * @return the droppedItem */ public Weapon getDroppedItem() { return droppedItem; } /* (non-Javadoc) * @see seventh.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { return this.netEntity; } /** * If this {@link DroppedItem} can be picked up by the supplied {@link PlayerEntity} * * @param ent * @return true if it can be picked up; false otherwise */ public boolean canBePickedUpBy(PlayerEntity ent) { if(isAlive()) { if(ent != null && ent.isAlive() && !ent.getType().isVehicle()) { return (ent.bounds.intersects(bounds)); } } return false; } /** * Have the supplied {@link PlayerEntity} pick up the {@link DroppedItem} * * @param ent * @return true if the player picked up the dropped item */ public boolean pickup(PlayerEntity ent) { if(ent.pickupItem(droppedItem)) { kill(ent); return true; } return false; } }
3,342
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Entity.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/Entity.java
/* * see license.txt */ package seventh.game.entities; import java.util.List; import leola.vm.types.LeoObject; import seventh.game.Game; import seventh.game.entities.vehicles.Vehicle; import seventh.game.net.NetEntity; import seventh.map.Map; import seventh.map.MapObject; import seventh.map.Tile; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.Debugable; import seventh.shared.Geom; import seventh.shared.TimeStep; import seventh.shared.WeaponConstants; /** * Base class for anything that is able to be interacted with in the game world. * * * @author Tony * */ public abstract class Entity implements Debugable { /** * Invalid entity ID */ public static final int INVALID_ENTITY_ID = Integer.MIN_VALUE; /** * The entities state * * @author Tony * */ public static enum State { IDLE, CROUCHING, WALKING, RUNNING, SPRINTING, ENTERING_VEHICLE, OPERATING_VEHICLE, EXITING_VEHICLE, /** * Entity is destroyed, and shouldn't be * removed (only DEAD will cause a removal) */ DESTROYED, /** * Entity is dead and should be removed */ DEAD, ; public byte netValue() { return (byte)ordinal(); } private static State[] values = values(); public static State fromNetValue(byte b) { return values[b]; } /** * @return number of bits it takes to represent this * enum */ public static int numOfBits() { return 4; } /** * @return true if we are in the vehicle operation states */ public boolean isVehicleState() { return this==OPERATING_VEHICLE|| this==ENTERING_VEHICLE|| this==EXITING_VEHICLE; } /* (non-Javadoc) * @see java.lang.Enum#toString() */ @Override public String toString() { return "\"" + name() + "\""; } } /** * Entity Type * * @author Tony * */ public static enum Type { PLAYER_PARTIAL, PLAYER, BULLET, EXPLOSION, FIRE, SMOKE, AMMO, ROCKET, // Alies Weapons THOMPSON, SPRINGFIELD, M1_GARAND, // Axis Weapons KAR98, MP44, MP40, // Shared Weapons RISKER, SHOTGUN, ROCKET_LAUNCHER, GRENADE, SMOKE_GRENADE, NAPALM_GRENADE, PISTOL, FLAME_THROWER, MG42, HAMMER, BOMB, BOMB_TARGET, LIGHT_BULB, DROPPED_ITEM, HEALTH_PACK, DOOR, /* Vehicles */ SHERMAN_TANK, PANZER_TANK, ALLIED_FLAG, AXIS_FLAG, ALLIED_BASE, AXIS_BASE, // Resources METAL, STONE, OIL, UNKNOWN, ; /** * @return the byte representation of this Type */ public byte netValue() { return (byte)this.ordinal(); } private static Type[] values = values(); /** * @param value the network value * @return the Type */ public static Type fromNet(byte value) { if(value < 0 || value >= values.length) { return UNKNOWN; } return values[value]; } /** * @return the number of bits to represent this * type */ public static int numOfBits() { return 6; } /** * @return true if this is a vehicle */ public boolean isVehicle() { return this == SHERMAN_TANK || this == PANZER_TANK; } /** * @return true if this is a player */ public boolean isPlayer() { return this == PLAYER || this == PLAYER_PARTIAL; } public boolean isDoor() { return this == DOOR; } public boolean isBase() { return this == ALLIED_BASE || this == AXIS_BASE; } /** * @return true if this is entity type can take damage */ public boolean isDamagable() { return isPlayer() || isVehicle() || isDoor() || isBase(); } /** * @return if this type is a projectile (such as a bullet) */ public boolean isProjectile() { return this == BULLET || this == ROCKET; } /** * @return if this type can cause damage to other entities */ public boolean isDamageInflictor() { return isProjectile() || this == EXPLOSION || this == FIRE; } /* (non-Javadoc) * @see java.lang.Enum#toString() */ @Override public String toString() { return "\"" + name() + "\""; } } public static float getAngleBetween(Vector2f a, Vector2f b) { return (float)Math.atan2(a.y-b.y,a.x-b.x); } /** * Listens for when an Entity is killed * @author Tony * */ public static interface KilledListener { void onKill(Entity entity, Entity killer); } /** * Listens for when an Entity is damaged * @author Tony * */ public static interface OnDamageListener { void onDamage(Entity damager, int amount); } /** * Listens for when an Entity is touched * * @author Tony * */ public static interface OnTouchListener { void onTouch(Entity me, Entity other); } public static interface OnMapObjectTouchListener { void onTouch(Entity me, MapObject object); } public KilledListener onKill; public OnDamageListener onDamage; public OnTouchListener onTouch; public OnMapObjectTouchListener onMapObjectTouch; protected Vector2f pos; protected Vector2f vel; protected Vector2f cache; private Vector2f centerPos; private Vector2f movementDir; protected Rectangle bounds; protected float orientation; protected Vector2f facing; protected State currentState; protected int speed; protected int collisionHeightMask; private Vector2f teleportPos; private boolean canTakeDamage; private boolean isAlive; private int health; private int maxHealth; protected Game game; private Type type; protected int id; private LeoObject scriptObj; /* if states become unweidly, convert to EntityStateMachine */ private long walkingTime; private static final long WALK_TIME = 150; // private long deadTime; // private static final long DEAD_TIME = 150; public static final int STANDING_HEIGHT_MASK = 0; public static final int CROUCHED_HEIGHT_MASK = 1; public int deadFrame; private Vector2f xCollisionTilePos, yCollisionTilePos; private Rectangle collisionRect; /** * @param position * @param speed * @param game * @param type */ public Entity(Vector2f position, int speed, Game game, Type type) { this(game.getNextEntityId(), position, speed, game, type); } /** * @param position * @param speed * @param game * @param type */ public Entity(int id, Vector2f position, int speed, Game game, Type type) { this.id = id; this.type = type; this.pos = position; this.speed = speed; this.game = game; this.collisionHeightMask = 1; this.currentState = State.IDLE; this.facing = new Vector2f(1,0); this.setOrientation(0); this.vel = new Vector2f(); this.isAlive = true; this.canTakeDamage = true; this.maxHealth = 100; this.health = this.maxHealth; this.movementDir = new Vector2f(); this.cache = new Vector2f(); this.bounds = new Rectangle(); this.bounds.setLocation(position); this.centerPos = new Vector2f(); this.scriptObj = LeoObject.valueOf(this); this.teleportPos = new Vector2f(); this.xCollisionTilePos = new Vector2f(); this.yCollisionTilePos = new Vector2f(); this.collisionRect = new Rectangle(); } /** * @return this {@link Entity} as a {@link LeoObject} */ public LeoObject asScriptObject() { return this.scriptObj; } /** * @return true if this entity can take damage */ public boolean canTakeDamage() { return this.canTakeDamage; } /** * @param canTakeDamage the canTakeDamage to set */ public void setCanTakeDamage(boolean canTakeDamage) { this.canTakeDamage = canTakeDamage; } /** * @return the height mask for if the entity is crouching or standing */ public int getHeightMask() { if( currentState == State.CROUCHING ) { return CROUCHED_HEIGHT_MASK; } return STANDING_HEIGHT_MASK; } /** * @return the id */ public int getId() { return id; } /** * @param type the type to set */ protected void setType(Type type) { this.type = type; } /** * @param type * @return true if the supplied type name is of the game {@link Type}. This * is used in Leola scripts to type checking */ public boolean isType(String type) { return getType().name().equalsIgnoreCase(type); } /** * @return true if this entity is a Player */ public boolean isPlayer() { return false; } /** * @return the type */ public Type getType() { return type; } /** * @return the bounds */ public Rectangle getBounds() { return bounds; } /** * @return the orientation */ public float getOrientation() { return orientation; } /** * @return the network friendly version of the orientation */ public short getNetOrientation() { return (short) Math.toDegrees(getOrientation()); } /** * @return the centerPos */ public Vector2f getCenterPos() { centerPos.set(pos.x + bounds.width/2, pos.y + bounds.height/2); return centerPos; } /** * @param orientation the orientation to set */ public void setOrientation(float orientation) { this.orientation = orientation; this.facing.set(1, 0); // make right vector Vector2f.Vector2fRotate(this.facing, /*Math.toRadians(d)*/ orientation, this.facing); } /** * @return the facing */ public Vector2f getFacing() { return facing; } /** * @return true if this entity is at max health */ public boolean isAtMaxHealth() { return this.health >= this.maxHealth; } /** * @return the maxHealth */ public int getMaxHealth() { return maxHealth; } /** * @param maxHealth the maxHealth to set */ public void setMaxHealth(int maxHealth) { this.maxHealth = maxHealth; } /** * @return the health */ public int getHealth() { return health; } /** * @param health the health to set */ public void setHealth(int health) { this.health = health; } public void moveTo(Vector2f pos) { this.pos.set(pos); this.bounds.setLocation(pos); } /** * Teleports this entity to the supplied location * * @param pos */ public void teleportTo(Vector2f pos) { this.teleportPos.set(pos); } /** * @return the movement direction */ public Vector2f getMovementDir() { return movementDir; } /** * @return the pos */ public Vector2f getPos() { return pos; } /** * @return the speed */ public int getSpeed() { return speed; } /** * @return the vel */ public Vector2f getVel() { return vel; } /** * @return the currentState */ public State getCurrentState() { return currentState; } /** * @return the isAlive */ public boolean isAlive() { return isAlive; } protected int calculateMovementSpeed() { return speed; } /** * Invoked when the x component collides with a map element * @param newX * @param oldX */ protected boolean collideX(int newX, int oldX) { return true; } /** * Invoked when the y component collides with a map element * @param newY * @param oldY */ protected boolean collideY(int newY, int oldY) { return true; } /** * Continue to check Y coordinate if X was blocked * @return true if we should continue collision checks */ protected boolean continueIfBlock() { return true; } /** * Adjusts the y movement if the player is at the edge of a collidable tile and there * is a free space * * @param collisionTilePos * @param deltaX * @param currentX * @param currentY * @return the adjusted y to move */ private int adjustY(Vector2f collisionTilePos, float deltaX, int currentX, int currentY) { Map map = game.getMap(); Tile collisionTile = map.getWorldCollidableTile((int)collisionTilePos.x, (int)collisionTilePos.y); if(collisionTile != null) { //DebugDraw.drawRectRelative(collisionTile.getBounds(), 0xff00ff00); int xIndex = collisionTile.getXIndex(); int yIndex = collisionTile.getYIndex(); int offset = 32; if(!map.checkTileBounds(xIndex, yIndex - 1) && !map.hasCollidableTile(xIndex, yIndex - 1)) { if(currentY < (collisionTile.getY()-(bounds.height-offset))) { //DebugDraw.drawRectRelative(map.getTile(0, xIndex, yIndex-1).getBounds(), 0xafff0000); return currentY - 1; } } if(!map.checkTileBounds(xIndex, yIndex + 1) && !map.hasCollidableTile(xIndex, yIndex + 1)) { if(currentY > (collisionTile.getY()+(collisionTile.getHeight()-offset))) { //DebugDraw.drawRectRelative(map.getTile(0, xIndex, yIndex+1).getBounds(), 0xaf0000ff); return currentY + 1; } } } else { // we're colliding with a map object collisionRect.set(bounds); collisionRect.x = currentX; collisionRect.y = currentY - 10; if(!collidesAgainstMapObject(collisionRect)) { return currentY - 1; } collisionRect.y = currentY + 10; if(!collidesAgainstMapObject(collisionRect)) { return currentY + 1; } } return currentY; } /** * Adjusts the x movement if the player is at the edge of a collidable tile and there * is a free space * * @param collisionTilePos * @param deltaY * @param currentX * @param currentY * @return the adjusted x to move */ private int adjustX(Vector2f collisionTilePos, float deltaY, int currentX, int currentY) { Map map = game.getMap(); Tile collisionTile = map.getWorldCollidableTile((int)collisionTilePos.x, (int)collisionTilePos.y); if(collisionTile != null) { //DebugDraw.drawRectRelative(collisionTile.getBounds(), 0xff00ff00); int xIndex = collisionTile.getXIndex(); int yIndex = collisionTile.getYIndex(); int offset = 32; if(!map.checkTileBounds(xIndex-1, yIndex) && !map.hasCollidableTile(xIndex-1, yIndex)) { if(currentX+bounds.width < (collisionTile.getX()+offset)) { //DebugDraw.drawRectRelative(map.getTile(0, xIndex-1, yIndex).getBounds(), 0xafff0000); return currentX - 1; } } if(!map.checkTileBounds(xIndex+1, yIndex) && !map.hasCollidableTile(xIndex+1, yIndex)) { if(currentX > (collisionTile.getX()+collisionTile.getWidth()-offset)) { //DebugDraw.drawRectRelative(map.getTile(0, xIndex+1, yIndex).getBounds(), 0xaf0000ff); return currentX + 1; } } } else { // we're colliding with a map object collisionRect.set(bounds); collisionRect.x = currentX - 10; collisionRect.y = currentY; if(!collidesAgainstMapObject(collisionRect)) { return currentX - 1; } collisionRect.x = currentX + 10; if(!collidesAgainstMapObject(collisionRect)) { return currentX + 1; } } return currentX; } private boolean checkCollision(int newX, int newY) { Map map = game.getMap(); boolean isBlocked = false; bounds.x = newX; if( map.rectCollides(bounds, collisionHeightMask) ) { isBlocked = collideX(newX, bounds.x); if(isBlocked) { bounds.x = (int)pos.x; } } else if(collidesAgainstEntity(bounds) || collidesAgainstMapObject(bounds)) { bounds.x = (int)pos.x; isBlocked = true; } bounds.y = newY; if( map.rectCollides(bounds, collisionHeightMask)) { isBlocked = collideY((int)newY, bounds.y); if(isBlocked) { bounds.y = (int)pos.y; } } else if(collidesAgainstEntity(bounds) || collidesAgainstMapObject(bounds)) { bounds.y = (int)pos.y; isBlocked = true; } return isBlocked; } /** * @param dt * @return true if blocked */ public boolean update(TimeStep timeStep) { boolean isBlocked = false; this.movementDir.zeroOut(); if(!this.teleportPos.isZero()) { moveTo(this.teleportPos); this.teleportPos.zeroOut(); return false; } if(this.isAlive && !this.vel.isZero()) { if(currentState != State.WALKING && currentState != State.SPRINTING) { currentState = State.RUNNING; } int movementSpeed = calculateMovementSpeed(); float dt = (float)timeStep.asFraction(); float deltaX = (vel.x * movementSpeed * dt); float deltaY = (vel.y * movementSpeed * dt); float newX = pos.x + deltaX; float newY = pos.y + deltaY; if(Math.abs(pos.x - newX) > 2.5) { this.movementDir.x = vel.x; } if(Math.abs(pos.y - newY) > 2.5) { this.movementDir.y = vel.y; } Map map = game.getMap(); bounds.x = (int)newX; if(map.rectCollides(bounds, collisionHeightMask, xCollisionTilePos)) { isBlocked = collideX((int)newX, bounds.x); if(isBlocked) { bounds.x = (int)pos.x; newX = pos.x; } } else if(collidesAgainstEntity(bounds) || collidesAgainstMapObject(bounds)) { bounds.x = (int)pos.x; newX = pos.x; isBlocked = true; } bounds.y = (int)newY; if(map.rectCollides(bounds, collisionHeightMask, yCollisionTilePos)) { isBlocked = collideY((int)newY, bounds.y); if(isBlocked) { bounds.y = (int)pos.y; newY = pos.y; } } else if(collidesAgainstEntity(bounds) || collidesAgainstMapObject(bounds)) { bounds.y = (int)pos.y; newY = pos.y; isBlocked = true; } if(isBlocked) { /* some things want to stop dead it their tracks * if a component is blocked */ if(!continueIfBlock()) { bounds.setLocation(pos); newX = pos.x; newY = pos.y; } /* * Otherwise determine if the character * is a couple pixels off and is snagged on * a corner, if so auto adjust them */ else { if(deltaX!=0 && deltaY==0) { newY = adjustY(xCollisionTilePos, deltaX, (int)(pos.x + deltaX), bounds.y); if(checkCollision((int)newX, (int)newY)) { newY = pos.y; } } else if(deltaX==0 && deltaY!=0) { newX = adjustX(yCollisionTilePos, deltaY, bounds.x, (int)(pos.y + deltaY)); if(checkCollision((int)newX, (int)newY)) { newX = pos.x; } } } } pos.x = newX; pos.y = newY; vel.zeroOut(); this.walkingTime = WALK_TIME; } else { if(this.walkingTime<=0 && currentState!=State.CROUCHING) { currentState = State.IDLE; } this.walkingTime -= timeStep.getDeltaTime(); } return isBlocked; } protected boolean collidesAgainstMapObject(Rectangle bounds) { List<MapObject> mapObjects = game.getCollidableMapObjects(); for(int i = 0; i < mapObjects.size(); i++) { MapObject object = mapObjects.get(i); if(object.isCollidable()) { if(object.isTouching(bounds)) { if(object.onTouch(game, this)) { return true; } } } } return false; } protected boolean collidesAgainstEntity(Rectangle bounds) { return collidesAgainstVehicle(bounds) || collidesAgainstDoor(bounds); } protected boolean collidesAgainstDoor(Rectangle bounds) { List<Door> doors = game.getDoors(); for(int i = 0; i < doors.size(); i++) { Door door = doors.get(i); if(door.isTouching(bounds)) { return true; } } return false; } /** * Determines if the bounds touches any vehicle * @param bounds * @return true if we collide with a vehicle */ protected boolean collidesAgainstVehicle(Rectangle bounds) { if(!getType().isPlayer()) { return false; } boolean collides = false; List<Vehicle> vehicles = game.getVehicles(); for(int i = 0; i < vehicles.size(); i++) { Vehicle vehicle = vehicles.get(i); if(vehicle.isAlive() && this != vehicle && this != vehicle.getOperator()) { /* determine if moving to this bounds we would touch * the vehicle */ collides = bounds.intersects(vehicle.getBounds()); /* if we touched, determine if we would be inside * the vehicle, if so, kill us */ if(collides) { // do a more expensive collision detection if(vehicle.isTouching(this)) { if(vehicle.isMoving() /*&& vehicle.getBounds().contains(bounds)*/) { kill(vehicle); } break; } else { collides = false; break; } } } } return collides; } /** * @param other * @return true if this entity is touching the other one */ public boolean isTouching(Entity other) { if(other != null) { return this.bounds.intersects(other.bounds); } return false; } /** * @param other * @return the distance from this entity to the other (squared) */ public float distanceFromSq(Entity other) { return Vector2f.Vector2fDistanceSq(getCenterPos(), other.getCenterPos()); } /** * @param position * @return the distance from this entity to the position (squared) */ public float distanceFromSq(Vector2f position) { return Vector2f.Vector2fDistanceSq(getCenterPos(), position); } /** * * @param target * @return true if this {@link Entity} is facing at the target {@link Vector2f} */ public boolean isFacing(Vector2f target) { double angle = Vector2f.Vector2fAngle(getFacing(), target); return Math.abs(angle) < Math.PI/4d; } /** * Does not broadcast that this entity * is dead. */ public void softKill() { this.isAlive = false; } /** * Kills this entity */ public void kill(Entity killer) { if (isAlive) { currentState = State.DEAD; health = 0; isAlive = false; if(onKill != null) { onKill.onKill(this, killer); } } } /** * Damages this entity * * @param damager * @param amount */ public void damage(Entity damager, int amount) { health -= amount; if(health <= 0) { kill(damager); } else { if (onDamage != null) { onDamage.onDamage(damager, amount); } } game.getStatSystem().onPlayerDamaged(this, damager, amount); } /** * @return the networked object representation of this {@link Entity} */ public abstract NetEntity getNetEntity(); /** * Sets the base {@link NetEntity} information * @param netEntity */ protected void setNetEntity(NetEntity netEntity) { netEntity.id = this.id; netEntity.posX = (short)this.pos.x; netEntity.posY = (short)this.pos.y; // netEntity.width = (byte)this.bounds.width; // netEntity.height = (byte)this.bounds.height; netEntity.orientation = getNetOrientation(); } /** * Picks the closest entity from the list to this one * @param entities * @return the closest entity to this one, null if the list is empty */ public <T extends Entity> T getClosest(List<T> entities) { if(entities==null || entities.isEmpty()) { return null; } if(entities.size() < 2) { return entities.get(0); } Vector2f myPos = getPos(); T closest = null; float closestDist = 0.0f; for(int i = 0; i < entities.size(); i++) { T other = entities.get(i); float dist = Vector2f.Vector2fDistanceSq(myPos, other.getPos()); if( (closest==null) || dist < closestDist ) { closestDist = dist; closest = other; } } return closest; } /** * @param tiles an empty list of tiles that is used as the returned list * @return calculates the line of sight, which returns a {@link List} of {@link Tile} this entity * is able to see */ public List<Tile> calculateLineOfSight(List<Tile> tiles) { Map map = game.getMap(); Geom.calculateLineOfSight(tiles, centerPos, getFacing(), WeaponConstants.DEFAULT_LINE_OF_SIGHT, map, getHeightMask(), cache); return tiles; } /* (non-Javadoc) * @see seventh.shared.Debugable#getDebugInformation(seventh.shared.Debugable.DebugEntryChain) */ @Override public DebugInformation getDebugInformation() { DebugInformation me = new DebugInformation(); me.add("id", getId()) .add("pos", getPos()) .add("vel", getVel()) .add("movementDir", getMovementDir()) .add("centerPos", getCenterPos()) .add("facing", getFacing()) .add("bounds", getBounds()) .add("orientation", getOrientation()) .add("state", getCurrentState()) .add("speed", getSpeed()) .add("isAlive", isAlive()) .add("health", getHealth()) .add("type", getType()); return me; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return getDebugInformation().toString(); } }
30,903
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Bomb.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/Bomb.java
/* * The Seventh * see license.txt */ package seventh.game.entities; import seventh.game.Game; import seventh.game.events.BombDisarmedEvent; import seventh.game.events.BombExplodedEvent; import seventh.game.events.BombPlantedEvent; import seventh.game.net.NetBomb; import seventh.game.net.NetEntity; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.EventDispatcher; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.Timer; /** * A Bomb is something that can be planted on a {@link BombTarget} and makes * it go boom! * * @author Tony * */ public class Bomb extends Entity { private Timer timer; private Timer plantTimer, disarmTimer; private Timer blowingupTimer, nextExplosionTimer; private NetBomb netBomb; private EventDispatcher dispatcher; private PlayerEntity planter, disarmer; private BombTarget bombTarget; private int splashWidth, maxSpread; private Rectangle blastRadius; private int tickMarker; /** * @param position * @param game * @param plantedOn -- the entity which this bomb is planted on */ public Bomb(Vector2f position, final Game game) { super(position, 0, game, Type.BOMB); this.bounds.width = 5; this.bounds.height = 5; this.netBomb = new NetBomb(); this.netBomb.id = getId(); setNetEntity(netBomb); // 30 second timer this.timer = new Timer(false, 30_000); this.timer.stop(); this.plantTimer = new Timer(false, 3_000); this.plantTimer.stop(); this.disarmTimer = new Timer(false, 5_000); this.disarmTimer.stop(); this.blowingupTimer = new Timer(false, 3_000); this.blowingupTimer.stop(); this.nextExplosionTimer = new Timer(true, 300); this.nextExplosionTimer.start(); this.dispatcher = game.getDispatcher(); this.blastRadius = new Rectangle(); this.splashWidth = 20; this.maxSpread = 40; this.tickMarker = 10; } /* (non-Javadoc) * @see seventh.game.Entity#update(leola.live.TimeStep) */ @Override public boolean update(TimeStep timeStep) { super.update(timeStep); this.timer.update(timeStep); this.plantTimer.update(timeStep); this.disarmTimer.update(timeStep); this.blowingupTimer.update(timeStep);; this.nextExplosionTimer.update(timeStep); /* check and see if the bomb timer has expired, * if so the bomb goes boom */ if(this.timer.isTime()) { if(!this.blowingupTimer.isUpdating()) { this.blowingupTimer.start(); dispatcher.queueEvent(new BombExplodedEvent(this, Bomb.this)); } if(this.nextExplosionTimer.isTime()) { game.newBigExplosion(getCenterPos(), this.planter, this.splashWidth, this.maxSpread, 200); } } if(this.timer.isUpdating()) { if(this.timer.getRemainingTime() < 10_000) { long trSec = this.timer.getRemainingTime()/1_000; if(trSec <= tickMarker) { game.emitSound(getId(), SoundType.BOMB_TICK, getPos()); tickMarker--; } } } else { tickMarker=10; } /* the bomb goes off for a while, creating * many expositions, once this expires we * kill the bomb */ if(this.blowingupTimer.isTime()) { this.timer.stop(); // ka-bom if(this.bombTarget!=null) { this.bombTarget.kill(this); } kill(this); } /* check and see if we are done planting this bomb */ if(this.plantTimer.isTime()) { this.timer.start(); dispatcher.queueEvent(new BombPlantedEvent(this, Bomb.this)); this.plantTimer.stop(); } /* check and see if the bomb has been disarmed */ if(this.disarmTimer.isTime()) { this.timer.stop(); dispatcher.queueEvent(new BombDisarmedEvent(this, Bomb.this)); this.disarmTimer.stop(); softKill(); if(bombTarget!=null) { bombTarget.reset(); } bombTarget = null; } return true; } /** * @return the estimated blast radius */ public Rectangle getBlastRadius() { /* the max spread of the blast could contain a splash width at either end, * so therefore we add the splashWidth twice */ int maxWidth = (this.splashWidth + this.maxSpread) * 4; this.blastRadius.setSize(maxWidth, maxWidth); this.blastRadius.centerAround(getCenterPos()); return this.blastRadius; } /** * @return the bombTarget */ public BombTarget getBombTarget() { return bombTarget; } /** * Plants this bomb on the supplied {@link BombTarget} * * @param planter * @param bombTarget */ public void plant(PlayerEntity planter, BombTarget bombTarget) { this.bombTarget = bombTarget; this.pos.set(bombTarget.getCenterPos()); if(this.planter == null) { this.planter = planter; if(this.planter != null) { this.plantTimer.start(); } } if(this.planter == null) { this.plantTimer.stop(); } } /** * @return true if this bomb is being planted */ public boolean isPlanting() { return this.planter != null && this.plantTimer.isUpdating(); } /** * @return true if this bomb is being disarmed */ public boolean isDisarming() { return this.disarmer != null && this.disarmTimer.isUpdating(); } /** * @return true if this bomb is blowing up right now */ public boolean isBlowingUp() { return this.blowingupTimer.isUpdating(); } /** * Stops planting the bomb */ public void stopPlanting() { this.planter = null; this.plantTimer.stop(); } /** * @return true if this bomb is planted on a bomb target */ public boolean isPlanted() { return this.timer.isUpdating(); } /** * @return the planter */ public PlayerEntity getPlanter() { return planter; } /** * @return the disarmer */ public PlayerEntity getDisarmer() { return disarmer; } /** * Disarm the bomb */ public void disarm(PlayerEntity entity) { if(this.disarmer == null) { this.disarmer = entity; if(this.disarmer!=null) { this.disarmTimer.start(); } } if(this.disarmer == null) { this.disarmTimer.stop(); } } /** * Stops disarming this bomb */ public void stopDisarming() { this.disarmer=null; this.disarmTimer.stop(); } /* (non-Javadoc) * @see seventh.game.Entity#canTakeDamage() */ @Override public boolean canTakeDamage() { return false; } /* (non-Javadoc) * @see seventh.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { this.netBomb.timeRemaining = (int) this.timer.getRemainingTime(); return this.netBomb; } }
8,444
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Door.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/Door.java
/* * see license.txt */ package seventh.game.entities; import seventh.game.Game; import seventh.game.SmoothOrientation; import seventh.game.net.NetDoor; import seventh.game.net.NetEntity; import seventh.game.weapons.Bullet; import seventh.math.Line; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.Timer; /** * A Door in the game world. It can be opened or closed. * * @author Tony * */ public class Door extends Entity { public static final int DOOR_WIDTH = 4; public static enum DoorHinge { NORTH_END, SOUTH_END, EAST_END, WEST_END, ; private static DoorHinge[] values = values(); public byte netValue() { return (byte)ordinal(); } public float getClosedOrientation() { switch(this) { case NORTH_END: return (float)Math.toRadians(270); case SOUTH_END: return (float)Math.toRadians(90); case EAST_END: return (float)Math.toRadians(180); case WEST_END: return (float)Math.toRadians(0); default: return 0; } } public Vector2f getRearHandlePosition(Vector2f pos, Vector2f rearHandlePos) { rearHandlePos.set(pos); final float doorWidth = DOOR_WIDTH; switch(this) { case NORTH_END: rearHandlePos.x += doorWidth; break; case SOUTH_END: rearHandlePos.x += doorWidth; break; case EAST_END: rearHandlePos.y += doorWidth; break; case WEST_END: rearHandlePos.y += doorWidth; break; default: } return rearHandlePos; } public Vector2f getRearHingePosition(Vector2f hingePos, Vector2f facing, Vector2f rearHingePos) { Vector2f hingeFacing = rearHingePos; //new Vector2f(); switch(this) { case NORTH_END: Vector2f.Vector2fPerpendicular(facing, hingeFacing); Vector2f.Vector2fMA(hingePos, hingeFacing, -DOOR_WIDTH/2, rearHingePos); break; case SOUTH_END: Vector2f.Vector2fPerpendicular(facing, hingeFacing); Vector2f.Vector2fMA(hingePos, hingeFacing, DOOR_WIDTH/2, rearHingePos); break; case EAST_END: Vector2f.Vector2fPerpendicular(facing, hingeFacing); Vector2f.Vector2fMA(hingePos, hingeFacing, DOOR_WIDTH/2, rearHingePos); break; case WEST_END: Vector2f.Vector2fPerpendicular(facing, hingeFacing); Vector2f.Vector2fMA(hingePos, hingeFacing, -DOOR_WIDTH/2, rearHingePos); break; default: } return rearHingePos; } public Vector2f getFrontHingePosition(Vector2f hingePos, Vector2f facing, Vector2f frontHingePos) { Vector2f hingeFacing = frontHingePos; //new Vector2f(); switch(this) { case NORTH_END: Vector2f.Vector2fPerpendicular(facing, hingeFacing); Vector2f.Vector2fMS(hingePos, hingeFacing, -DOOR_WIDTH/2, frontHingePos); break; case SOUTH_END: Vector2f.Vector2fPerpendicular(facing, hingeFacing); Vector2f.Vector2fMS(hingePos, hingeFacing, DOOR_WIDTH/2, frontHingePos); break; case EAST_END: Vector2f.Vector2fPerpendicular(facing, hingeFacing); Vector2f.Vector2fMS(hingePos, hingeFacing, DOOR_WIDTH/2, frontHingePos); break; case WEST_END: Vector2f.Vector2fPerpendicular(facing, hingeFacing); Vector2f.Vector2fMS(hingePos, hingeFacing, -DOOR_WIDTH/2, frontHingePos); break; default: } return frontHingePos; } public static DoorHinge fromNetValue(byte value) { for(DoorHinge hinge : values) { if(hinge.netValue() == value) { return hinge; } } return DoorHinge.NORTH_END; } public static DoorHinge fromVector(Vector2f facing) { if(facing.x > 0) { return DoorHinge.EAST_END; } if(facing.x < 0) { return DoorHinge.WEST_END; } if(facing.y > 0) { return DoorHinge.SOUTH_END; } if(facing.y < 0) { return DoorHinge.NORTH_END; } return DoorHinge.EAST_END; } } /** * Available door states * * @author Tony * */ public static enum DoorState { OPENED, OPENING, CLOSED, CLOSING, ; public byte netValue() { return (byte)ordinal(); } } private DoorState doorState; private DoorHinge hinge; private Vector2f frontDoorHandle, rearDoorHandle, frontHingePos, rearHingePos; private Rectangle handleTouchRadius, hingeTouchRadius, autoCloseRadius; private SmoothOrientation rotation; private float targetOrientation; private boolean isBlocked; private NetDoor netDoor; private Timer autoCloseTimer; /** * @param id * @param position * @param speed * @param game * @param type */ public Door(Vector2f position, Game game, Vector2f facing) { super(game.getNextPersistantId(), position, 0, game, Type.DOOR); this.doorState = DoorState.CLOSED; this.frontDoorHandle = new Vector2f(facing); this.frontHingePos = new Vector2f(); this.rearDoorHandle = new Vector2f(facing); this.rearHingePos = new Vector2f(); this.facing.set(facing); this.hinge = DoorHinge.fromVector(facing); this.handleTouchRadius = new Rectangle(48, 48); this.hingeTouchRadius = new Rectangle(48,48); this.autoCloseRadius = new Rectangle(128, 128); this.bounds.set(this.handleTouchRadius); this.bounds.setLocation(getPos()); this.hingeTouchRadius.centerAround(getPos()); this.autoCloseRadius.centerAround(getPos()); this.autoCloseTimer = new Timer(false, 5_000); this.autoCloseTimer.stop(); this.rotation = new SmoothOrientation(0.1); this.rotation.setOrientation(this.hinge.getClosedOrientation()); setOrientation(this.rotation.getOrientation()); setDoorOrientation(); this.netDoor = new NetDoor(); setCanTakeDamage(true); this.isBlocked = false; this.onTouch = new OnTouchListener() { @Override public void onTouch(Entity me, Entity other) { // does nothing, just makes it so the game will // acknowledge these two entities can touch each other } }; } private void setDoorOrientation() { this.frontHingePos = this.hinge.getFrontHingePosition(getPos(), this.rotation.getFacing(), this.frontHingePos); Vector2f.Vector2fMA(this.frontHingePos, this.rotation.getFacing(), 64, this.frontDoorHandle); this.rearHingePos = this.hinge.getRearHingePosition(getPos(), this.rotation.getFacing(), this.rearHingePos); Vector2f.Vector2fMA(this.rearHingePos, this.rotation.getFacing(), 64, this.rearDoorHandle); this.handleTouchRadius.centerAround(this.frontDoorHandle); } @Override public boolean update(TimeStep timeStep) { // if the door gets blocked by an Entity, // we stop the door. Once the Entity moves // we continue opening the door. // The door can act as a shield to the entity float currentRotation = this.rotation.getOrientation(); switch(this.doorState) { case OPENING: { this.rotation.setDesiredOrientation(this.targetOrientation); this.rotation.update(timeStep); setDoorOrientation(); if(this.game.doesTouchPlayers(this)) { if(!this.isBlocked) { this.game.emitSound(getId(), SoundType.DOOR_OPEN_BLOCKED, getPos()); } this.isBlocked = true; this.rotation.setOrientation(currentRotation); setDoorOrientation(); } else if(!this.rotation.moved()) { this.doorState = DoorState.OPENED; this.isBlocked = false; } break; } case CLOSING: { this.rotation.setDesiredOrientation(this.targetOrientation); this.rotation.update(timeStep); setDoorOrientation(); if(this.game.doesTouchPlayers(this)) { if(!this.isBlocked) { this.game.emitSound(getId(), SoundType.DOOR_CLOSE_BLOCKED, getPos()); } this.isBlocked = true; this.rotation.setOrientation(currentRotation); setDoorOrientation(); } else if(!this.rotation.moved()) { this.doorState = DoorState.CLOSED; this.isBlocked = false; } break; } case OPENED: { // part of the gameplay -- auto close // the door after a few seconds this.autoCloseTimer.update(timeStep); if(this.autoCloseTimer.isOnFirstTime()) { if(!isPlayerNear()) { close(this); this.autoCloseTimer.stop(); } else { this.autoCloseTimer.reset(); } } break; } default: { this.isBlocked = false; } } setOrientation(this.rotation.getOrientation()); //DebugDraw.fillRectRelative((int)getPos().x, (int)getPos().y, 5, 5, 0xffff0000); //DebugDraw.drawLineRelative(this.frontHingePos, this.frontDoorHandle, 0xffffff00); //DebugDraw.drawLineRelative(this.rearHingePos, this.rearDoorHandle, 0xffffff00); //DebugDraw.drawRectRelative(autoCloseRadius, 0xffff0000); //DebugDraw.drawStringRelative("State: " + this.doorState, (int)getPos().x, (int)getPos().y, 0xffff00ff); //DebugDraw.drawStringRelative("Orientation: C:" + (int)Math.toDegrees(this.rotation.getOrientation()) + " D:" + (int)Math.toDegrees(this.rotation.getDesiredOrientation()) , (int)getPos().x, (int)getPos().y + 20, 0xffff00ff); return false; } public boolean isOpened() { return this.doorState == DoorState.OPENED; } public boolean isOpening() { return this.doorState == DoorState.OPENING; } public boolean isClosed() { return this.doorState == DoorState.CLOSED; } public boolean isClosing() { return this.doorState == DoorState.CLOSING; } public void handleDoor(Entity ent) { if(isOpened()) { close(ent); } else if(isClosed()) { open(ent); } else if(this.isBlocked) { if(isOpening()) { close(ent); } else { open(ent); } } } public void open(Entity ent) { open(ent, false); } public void open(Entity ent, boolean force) { if(this.doorState != DoorState.OPENED || this.doorState != DoorState.OPENING || this.doorState != DoorState.CLOSING) { if(!canBeHandledBy(ent) && !force) { return; } this.autoCloseTimer.reset(); this.doorState = DoorState.OPENING; this.game.emitSound(getId(), SoundType.DOOR_OPEN, getPos()); Vector2f entPos = ent.getCenterPos(); Vector2f hingePos = this.frontDoorHandle;//getPos(); // figure out what side the entity is // of the door hinge, depending on their // side, we set the destinationOrientation switch(this.hinge) { case NORTH_END: case SOUTH_END: if(entPos.x < hingePos.x) { this.targetOrientation = (float)Math.toRadians(0); } else if(entPos.x > hingePos.x) { this.targetOrientation = (float)Math.toRadians(180); } break; case EAST_END: case WEST_END: if(entPos.y < hingePos.y) { this.targetOrientation = (float)Math.toRadians(90); } else if(entPos.y > hingePos.y) { this.targetOrientation = (float)Math.toRadians(270); } break; default: break; } } } public void close(Entity ent) { close(ent, false); } public void close(Entity ent, boolean force) { if(this.doorState != DoorState.CLOSED || this.doorState != DoorState.OPENING || this.doorState != DoorState.CLOSING) { if(!canBeHandledBy(ent) && !force) { return; } this.doorState = DoorState.CLOSING; this.targetOrientation = this.hinge.getClosedOrientation(); this.game.emitSound(getId(), SoundType.DOOR_CLOSE, getPos()); } } @Override public void damage(Entity damager, int amount) { if(damager instanceof Bullet) { Bullet bullet = (Bullet) damager; bullet.kill(this); game.emitSound(bullet.getId(), SoundType.IMPACT_WOOD, bullet.getCenterPos()); } } /** * Test if the supplied {@link Entity} is within reach to close or open this door. * * @param ent * @return true if the Entity is within reach to to close/open this door */ public boolean canBeHandledBy(Entity ent) { //DebugDraw.fillRectRelative(handleTouchRadius.x, handleTouchRadius.y, handleTouchRadius.width, handleTouchRadius.height, 0xff00ff00); //DebugDraw.fillRectRelative(hingeTouchRadius.x, hingeTouchRadius.y, hingeTouchRadius.width, hingeTouchRadius.height, 0xff00ff00); // we can close our selves :) if(ent==this) { return true; } return this.handleTouchRadius.intersects(ent.getBounds()) || this.hingeTouchRadius.intersects(ent.getBounds()) ; } /** * @return true only if there is a player some what near this door (such that * it wouldn't be able to close or open properly) */ public boolean isPlayerNear() { PlayerEntity[] playerEntities = game.getPlayerEntities(); for(int i = 0; i < playerEntities.length; i++) { Entity other = playerEntities[i]; if(other != null) { if(this.autoCloseRadius.contains(other.getBounds())) { return true; } } } return false; } /** * Test if the supplied {@link Entity} touches the door * * @param ent * @return true if the Entity is within reach to to close/open this door */ @Override public boolean isTouching(Entity ent) { return isTouching(ent.getBounds()); } public boolean isTouching(Rectangle bounds) { boolean isTouching = Line.lineIntersectsRectangle(this.frontHingePos, this.frontDoorHandle, bounds) || Line.lineIntersectsRectangle(this.rearHingePos, this.rearDoorHandle, bounds); // if(isTouching) { // DebugDraw.fillRectRelative(bounds.x, bounds.y, bounds.width, bounds.height, 0xff00ff00); // DebugDraw.drawLineRelative(getPos(), this.frontDoorHandle, 0xffffff00); // DebugDraw.drawLineRelative(this.rearHingePos, this.rearDoorHandle, 0xffffff00); // } return isTouching; } /** * @return the isBlocked */ public boolean isBlocked() { return isBlocked; } /** * @return the frontDoorHandle */ public Vector2f getHandle() { return frontDoorHandle; } @Override public NetEntity getNetEntity() { this.setNetEntity(netDoor); this.netDoor.hinge = this.hinge.netValue(); return this.netDoor; } }
18,677
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
LightBulb.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/LightBulb.java
/* * see license.txt */ package seventh.game.entities; import seventh.game.Game; import seventh.game.net.NetEntity; import seventh.game.net.NetLight; import seventh.math.Vector2f; import seventh.math.Vector3f; /** * @author Tony * */ public class LightBulb extends Entity { private NetLight netEntity; private Vector3f color; private float luminacity; private int size; /** * @param position * @param speed * @param game * @param type */ public LightBulb(Vector2f position, Game game) { super(game.getNextPersistantId(), position, 0, game, Type.LIGHT_BULB); this.bounds.width = 5; this.bounds.height = 5; this.bounds.centerAround(position); this.color = new Vector3f(0.3f, 0.3f, 0.7f); this.luminacity = 0.25f; this.size = 512; // this.size = 5; this.netEntity = new NetLight(); setNetEntity(netEntity); } /** * @param size the size to set */ public void setSize(int size) { this.size = size; } /** * @return the size */ public int getSize() { return size; } /** * @param luminacity the luminacity to set */ public void setLuminacity(float luminacity) { this.luminacity = luminacity; } /** * @return the luminacity */ public float getLuminacity() { return luminacity; } /** * @param color the color to set */ public void setColor(Vector3f color) { this.color.set(color); } public void setColor(float r, float g, float b) { this.color.set(r,g,b);; } /** * @return the color */ public Vector3f getColor() { return color; } /* (non-Javadoc) * @see seventh.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { this.netEntity.r = (short) (255 * color.x); this.netEntity.g = (short) (255 * color.y); this.netEntity.b = (short) (255 * color.z); this.netEntity.luminacity = (short) (255 * luminacity); this.netEntity.size = (short)size; return this.netEntity; } }
2,303
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
BombTarget.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/BombTarget.java
/* * The Seventh * see license.txt */ package seventh.game.entities; import seventh.game.Game; import seventh.game.Team; import seventh.game.net.NetBombTarget; import seventh.game.net.NetEntity; import seventh.math.Vector2f; /** * A {@link BombTarget} is something that a {@link Bomb} can blow up. This is * used for objective game types. A {@link BombTarget} may be a Radio communication * or something like that. * * @author Tony * */ public class BombTarget extends Entity { private NetBombTarget netBombTarget; private Bomb bomb; private Team owner; /** * @param position * @param game */ public BombTarget(Team owner, Vector2f position, Game game) { super(game.getNextPersistantId(), position, 0, game, Type.BOMB_TARGET); this.owner = owner; this.bounds.width = 64; this.bounds.height = 32; this.bounds.setLocation(position); this.netBombTarget = new NetBombTarget(); setNetEntity(netBombTarget); } /** * @return the owner */ public Team getOwner() { return owner; } /** * Rotates the bomb target by 90 degrees, this will only * do it once */ public BombTarget rotate90() { int width = this.bounds.width; this.bounds.width = this.bounds.height; this.bounds.height = width; this.netBombTarget.rotate90(); return this; } /* (non-Javadoc) * @see seventh.game.Entity#canTakeDamage() */ @Override public boolean canTakeDamage() { /* don't allow bullets and such to * hurt this */ return false; } /* (non-Javadoc) * @see seventh.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { return this.netBombTarget; } /** * Attaches a bomb to this * @param bomb */ public void attachBomb(Bomb bomb) { if(this.bomb==null) { this.bomb = bomb; } } /** * Detaches the bomb */ public void reset() { this.bomb = null; } /** * Determines if the supplied {@link Entity} can plant/disarm * this {@link BombTarget} * @param handler * @return true if the supplied {@link Entity} is able to plant/disarm */ public boolean canHandle(Entity handler) { return this.bounds.intersects(handler.getBounds()); } /** * @return if the bomb is planted */ public boolean bombActive() { return this.bomb != null && this.bomb.isPlanted(); } /** * @return if a player is planting a bomb */ public boolean bombPlanting() { return this.bomb != null && this.bomb.isPlanting(); } /** * @return if a player is disarming the bomb */ public boolean bombDisarming() { return this.bomb==null || this.bomb.isDisarming(); } /** * @return true if a bomb is already associated with this */ public boolean isBombAttached() { return this.bomb != null; } /** * @return true if the bomb is currently detonating and * destroying this target */ public boolean isBeingDestroyed() { return this.bomb != null && this.bomb.isBlowingUp(); } /** * @return the bomb */ public Bomb getBomb() { return bomb; } }
3,527
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Flag.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/Flag.java
/* * see license.txt */ package seventh.game.entities; import seventh.game.Game; import seventh.game.net.NetEntity; import seventh.game.net.NetFlag; import seventh.math.Vector2f; import seventh.shared.SeventhConstants; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.Timer; /** * @author Tony * */ public class Flag extends Entity { private PlayerEntity carriedBy; private NetFlag netFlag; private final Vector2f spawnLocation; private Timer resetTimer; /** * @param id * @param position * @param game * @param type */ public Flag(final Game game, Vector2f position, Type type) { super(game.getNextPersistantId(), position, 0, game, type); this.spawnLocation = new Vector2f(position); this.bounds.width = SeventhConstants.FLAG_WIDTH; this.bounds.height = SeventhConstants.FLAG_HEIGHT; this.bounds.setLocation(position); this.carriedBy = null; this.netFlag = new NetFlag(type); this.resetTimer = new Timer(false, 20_000); } /* (non-Javadoc) * @see seventh.game.Entity#update(seventh.shared.TimeStep) */ @Override public boolean update(TimeStep timeStep) { if(this.carriedBy != null && !this.carriedBy.isAlive()) { drop(); } this.resetTimer.update(timeStep); if(isBeingCarried()) { this.resetTimer.stop(); this.pos.set(this.carriedBy.getCenterPos()); this.bounds.centerAround(this.pos); } else { if(this.resetTimer.isExpired()) { returnHome(); } game.doesTouchPlayers(this); } return true; } public void drop() { if(isBeingCarried()) { Vector2f flagPos = new Vector2f(this.carriedBy.getFacing()); Vector2f.Vector2fMA(this.carriedBy.getCenterPos(), flagPos, 40, flagPos); /* do not allow this to be dropped here */ if(game.getMap().pointCollides((int)flagPos.x, (int)flagPos.y)) { flagPos.set(this.carriedBy.getCenterPos()); } this.pos.set(flagPos); this.bounds.centerAround(this.pos); this.carriedBy.dropFlag(); game.emitSound(getId(), SoundType.WEAPON_DROPPED, flagPos); this.resetTimer.reset(); this.resetTimer.start(); } this.carriedBy = null; } /** * @return true if the flag is at its home base */ public boolean isAtHomeBase() { return Vector2f.Vector2fApproxEquals(this.pos, getSpawnLocation()); } /** * Returns to the home base */ public void returnHome() { drop(); this.pos.set(getSpawnLocation()); this.bounds.centerAround(this.pos); } /** * @return the carriedBy */ public PlayerEntity getCarriedBy() { return carriedBy; } /** * Set who is carrying this flag * @param player */ public void carriedBy(PlayerEntity player) { if(!isBeingCarried() && player.isAlive()) { this.carriedBy = player; this.carriedBy.pickupFlag(this); } } /** * @return true if this flag is currently being carried */ public boolean isBeingCarried() { return this.carriedBy != null && this.carriedBy.isAlive(); } /** * @return the spawnLocation */ public Vector2f getSpawnLocation() { return spawnLocation; } public NetFlag getNetFlag() { this.setNetEntity(netFlag); this.netFlag.carriedBy = isBeingCarried() ? carriedBy.getId() : SeventhConstants.INVALID_PLAYER_ID; return this.netFlag; } /* (non-Javadoc) * @see seventh.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { return getNetFlag(); } }
4,242
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
PlayerEntity.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/PlayerEntity.java
/* * see license.txt */ package seventh.game.entities; import static seventh.shared.SeventhConstants.ENTERING_VEHICLE_TIME; import static seventh.shared.SeventhConstants.EXITING_VEHICLE_TIME; import static seventh.shared.SeventhConstants.MAX_PRIMARY_WEAPONS; import static seventh.shared.SeventhConstants.MAX_STAMINA; import static seventh.shared.SeventhConstants.PLAYER_HEARING_RADIUS; import static seventh.shared.SeventhConstants.PLAYER_HEIGHT; import static seventh.shared.SeventhConstants.PLAYER_MIN_SPEED; import static seventh.shared.SeventhConstants.PLAYER_SPEED; import static seventh.shared.SeventhConstants.PLAYER_WIDTH; import static seventh.shared.SeventhConstants.RECOVERY_TIME; import static seventh.shared.SeventhConstants.RUN_DELAY_TIME; import static seventh.shared.SeventhConstants.SPRINT_DELAY_TIME; import static seventh.shared.SeventhConstants.SPRINT_SPEED_FACTOR; import static seventh.shared.SeventhConstants.STAMINA_DECAY_RATE; import static seventh.shared.SeventhConstants.STAMINA_RECOVER_RATE; import static seventh.shared.SeventhConstants.WALK_SPEED_FACTOR; import java.util.List; import seventh.game.Controllable; import seventh.game.Game; import seventh.game.Inventory; import seventh.game.Player; import seventh.game.PlayerClass; import seventh.game.PlayerClass.WeaponEntry; import seventh.game.SoundEventPool; import seventh.game.SurfaceTypeToSoundType; import seventh.game.Team; import seventh.game.entities.vehicles.Vehicle; import seventh.game.events.SoundEmittedEvent; import seventh.game.net.NetEntity; import seventh.game.net.NetPlayer; import seventh.game.net.NetPlayerPartial; import seventh.game.weapons.Bullet; import seventh.game.weapons.FlameThrower; import seventh.game.weapons.GrenadeBelt; import seventh.game.weapons.Hammer; import seventh.game.weapons.Kar98; import seventh.game.weapons.M1Garand; import seventh.game.weapons.MP40; import seventh.game.weapons.MP44; import seventh.game.weapons.Pistol; import seventh.game.weapons.Risker; import seventh.game.weapons.RocketLauncher; import seventh.game.weapons.Shotgun; import seventh.game.weapons.Smoke; import seventh.game.weapons.Springfield; import seventh.game.weapons.Thompson; import seventh.game.weapons.Weapon; import seventh.map.Map; import seventh.map.Tile; import seventh.map.Tile.SurfaceType; import seventh.math.Line; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.Geom; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.WeaponConstants; /** * A controllable {@link Entity} by either AI or a Player. * * @author Tony * */ public class PlayerEntity extends Entity implements Controllable { /** * The keys/actions that a player can make * * @author Tony * */ public static enum Keys { UP (1<<0), DOWN (1<<1), LEFT (1<<2), RIGHT (1<<3), WALK (1<<4), FIRE (1<<5), RELOAD (1<<6), WEAPON_SWITCH_UP (1<<7), WEAPON_SWITCH_DOWN (1<<8), THROW_GRENADE (1<<9), SPRINT (1<<10), CROUCH (1<<11), USE (1<<12), DROP_WEAPON (1<<13), MELEE_ATTACK (1<<14), IRON_SIGHTS (1<<15), ; private Keys(int value) { this.value = value; } private int value; /** * @return the value */ public int getValue() { return value; } public boolean isDown(int keys) { return (value & keys) > 0; } } private NetPlayer player; private NetPlayerPartial partialPlayer; private Team team; private int previousKeys; private float previousOrientation; private Inventory inventory; private long invinceableTime; private int lineOfSight; private int hearingRadius; private Rectangle hearingBounds, visualBounds; private float stamina; private boolean completedRecovery; protected Vector2f inputVel; private boolean firing; private long runTime, recoveryTime; private boolean wasSprinting; private Vector2f enemyDir; private BombTarget bombTarget; private Vehicle operating; private boolean isFlashlightOn; private long vehicleTime; private Rectangle headshot, limbshot; private Vector2f bulletDir; private int speedMultiplier, damageMultiplier; /** * @param position * @param speed * @param game */ public PlayerEntity(int id, PlayerClass playerClass, Vector2f position, Game game) { super(id, position, PLAYER_SPEED, game, Type.PLAYER); this.player = new NetPlayer(); this.player.id = id; this.partialPlayer = new NetPlayerPartial(); this.partialPlayer.id = id; this.bounds.set(position, PLAYER_WIDTH, PLAYER_HEIGHT); this.inputVel = new Vector2f(); this.enemyDir = new Vector2f(); this.headshot = new Rectangle(4, 4); this.limbshot = new Rectangle(10, 10); this.bulletDir = new Vector2f(); this.inventory = new Inventory(MAX_PRIMARY_WEAPONS); this.hearingBounds = new Rectangle(PLAYER_HEARING_RADIUS, PLAYER_HEARING_RADIUS); this.stamina = MAX_STAMINA; this.visualBounds = new Rectangle(2000, 2000); this.speedMultiplier = playerClass.getSpeedMultiplier(); this.damageMultiplier = playerClass.getDamageMultiplier(); setLineOfSight(WeaponConstants.DEFAULT_LINE_OF_SIGHT); setHearingRadius(PLAYER_HEARING_RADIUS); setMaxHealth(getMaxHealth() + playerClass.getHealthMultiplier()); setHealth(getMaxHealth()); } /** * Apply the player class * * @param playerClass * @param activeWeapon * @return true if success, false otherwise */ public void setPlayerClass(PlayerClass playerClass, Type activeWeapon) { if(!playerClass.isAvailableWeapon(activeWeapon)) { activeWeapon = playerClass.getDefaultPrimaryWeapon().getTeamWeapon(getTeam()); } this.inventory.clear(); WeaponEntry weaponEntry = playerClass.getAvailableWeaponEntry(activeWeapon); Weapon currentWeapon = createWeapon(weaponEntry); if(currentWeapon != null) { this.inventory.addItem(currentWeapon); } List<WeaponEntry> weapons = playerClass.getDefaultWeapons(); for(int i = 0; i < weapons.size(); i++) { WeaponEntry entry = weapons.get(i); Weapon weapon = createWeapon(entry); if(weapon != null) { this.inventory.addItem(weapon); } } checkLineOfSightChange(); } private Weapon createWeapon(WeaponEntry entry) { Weapon weapon = null; switch(entry.type.getTeamWeapon(getTeam())) { case SPRINGFIELD: case KAR98: weapon = isAlliedPlayer() ? new Springfield(game, this) : new Kar98(game, this); break; case THOMPSON: case MP40: weapon = isAlliedPlayer() ? new Thompson(game, this) : new MP40(game, this); break; case M1_GARAND: case MP44: weapon = isAlliedPlayer() ? new M1Garand(game, this) : new MP44(game, this); break; case PISTOL: weapon = new Pistol(game, this); break; case HAMMER: weapon = new Hammer(game, this); break; case SHOTGUN: weapon = new Shotgun(game, this); break; case RISKER: weapon = new Risker(game, this); break; case ROCKET_LAUNCHER: weapon = new RocketLauncher(game, this); break; case FLAME_THROWER: weapon = new FlameThrower(game, this); break; case GRENADE: weapon = GrenadeBelt.newFrag(game, this, entry.ammoBag); break; case SMOKE_GRENADE: weapon = GrenadeBelt.newSmoke(game, this, entry.ammoBag); break; default: } if(weapon != null && entry.ammoBag > -1) { weapon.setTotalAmmo(entry.ammoBag); } return weapon; } /* (non-Javadoc) * @see seventh.game.Entity#kill(seventh.game.Entity) */ @Override public void kill(Entity killer) { unuse(); super.kill(killer); } /** * Drops the flag if carrying one */ public void dropFlag() { this.inventory.dropFlag(); } /** * Drops the currently held item * @param makeSound */ public void dropItem(boolean makeSound) { if(this.inventory.isCarryingFlag()) { dropFlag(); } else { Weapon weapon = this.inventory.currentItem(); if(weapon != null) { this.inventory.removeItem(weapon); this.inventory.nextItem(); Vector2f weaponPos = new Vector2f(getFacing()); Vector2f.Vector2fMA(getCenterPos(), weaponPos, 40, weaponPos); game.newDroppedItem(weaponPos, weapon); if(makeSound) { game.emitSound(getId(), SoundType.WEAPON_DROPPED, weaponPos); } } } } /** * Picks up an item * * @param item * @return true if the item was picked up */ public boolean pickupItem(Weapon weapon) { Type type = weapon.getType(); if(inventory.hasItem(type)) { Weapon myWeapon = inventory.getItem(type); myWeapon.addAmmo(weapon.getTotalAmmo()); game.emitSound(getId(), SoundType.AMMO_PICKUP, getPos()); return true; } else { if(inventory.addItem(weapon)) { weapon.setOwner(this); game.emitSound(getId(), SoundType.WEAPON_PICKUP, getPos()); return true; } } return false; } /** * Attempts to pick up the {@link DroppedItem} * * @param item * @return true if the player picked up the {@link DroppedItem} */ public boolean pickupDroppedItem(DroppedItem item) { return item.pickup(this); } /** * Pickup a flag * * @param flag */ public void pickupFlag(Flag flag) { this.inventory.pickupFlag(flag); } /** * @param lineOfSight the lineOfSight to set */ public void setLineOfSight(int lineOfSight) { this.lineOfSight = lineOfSight; } /** * @param radius the hearing range */ public void setHearingRadius(int radius) { this.hearingRadius = radius; } /** * @return the damageMultiplier */ public int getDamageMultiplier() { return damageMultiplier; } /** * @return the hearingRadius */ public int getHearingRadius() { return hearingRadius; } /** * @return the lineOfSight */ public int getLineOfSight() { return lineOfSight; } /** * @return the current held weapons distance */ public int getCurrentWeaponDistance() { Weapon weapon = inventory.currentItem(); if(weapon != null) { return weapon.getBulletRange(); } return 0; } /** * @return the current held weapons distance squared */ public int getCurrentWeaponDistanceSq() { Weapon weapon = inventory.currentItem(); if(weapon != null) { return weapon.getBulletRange() * weapon.getBulletRange(); } return 0; } /** * @return the stamina */ public byte getStamina() { return (byte)stamina; } @Override public boolean isPlayer() { return true; } public boolean isAlliedPlayer() { return getTeam().isAlliedTeam(); } public boolean isAxisPlayer() { return getTeam().isAxisTeam(); } /** * @return the isFlashlightOn */ public boolean isFlashlightOn() { return isFlashlightOn; } /** * @param invinceableTime the invinceableTime to set */ public void setInvinceableTime(long invinceableTime) { this.invinceableTime = invinceableTime; } /* (non-Javadoc) * @see palisma.game.Entity#damage(palisma.game.Entity, int) */ @Override public void damage(Entity damager, int amount) { boolean isInviceable = this.invinceableTime > 0; /* if the damager is a bullet, we should * determine the entrance wound, as it will * impact the amount of damage done. */ if(damager instanceof Bullet) { Bullet bullet = (Bullet) damager; PlayerEntity damageOwner = null; Entity owner = bullet.getOwner(); if(owner instanceof PlayerEntity) { damageOwner = (PlayerEntity)owner; } Vector2f center = getCenterPos(); Vector2f bulletCenter = bullet.getCenterPos(); this.headshot.centerAround(center); // determine which body part the bullet hit Vector2f.Vector2fMA(bulletCenter, bullet.getTargetVel(), 35, this.bulletDir); if(Line.lineIntersectsRectangle(bulletCenter, this.bulletDir, this.headshot)) { // headshots deal out a lot of damage amount *= 3; if(damageOwner != null) { game.emitSoundFor(damageOwner.getId(), SoundType.HEADSHOT, bullet.getPos(), damageOwner.getId()); } } else { // limb shots are not as lethal // right side Vector2f.Vector2fPerpendicular(getFacing(), cache); Vector2f.Vector2fMA(center, cache, 10, cache); this.limbshot.centerAround(cache); if(Line.lineIntersectsRectangle(bulletCenter, this.bulletDir, this.limbshot)) { amount /= 2; } // left side Vector2f.Vector2fPerpendicular(getFacing(), cache); Vector2f.Vector2fMS(center, cache, 10, cache); this.limbshot.centerAround(cache); if(Line.lineIntersectsRectangle(bulletCenter, this.bulletDir, this.limbshot)) { amount /= 2; } if(damageOwner != null) { game.emitSoundFor(damageOwner.getId(), SoundType.HIT_INDICATOR, bullet.getPos(), damageOwner.getId()); } } //DebugDraw.drawLineRelative(bullet.getCenterPos(), this.bulletDir, 0xff00ffff); game.emitSound(bullet.getId(), SoundType.IMPACT_FLESH, bullet.getPos()); if(damageOwner != null) { game.emitSoundFor(damageOwner.getId(), SoundType.IMPACT_FLESH, damageOwner.getPos(), damageOwner.getId()); } if(!bullet.isPiercing() || isInviceable) { bullet.kill(this); } } if(!isInviceable) { super.damage(damager, amount); } } /* (non-Javadoc) * @see palisma.game.Entity#update(leola.live.TimeStep) */ @Override public boolean update(TimeStep timeStep) { updateInvincibleTime(timeStep); updateVehicleTime(timeStep); boolean blocked = false; if(!isOperatingVehicle()) { updateVelocity(timeStep); blocked = super.update(timeStep); updateMovementSounds(timeStep); updateStamina(timeStep); updateWeapons(timeStep); updateBombTargetUse(timeStep); } else { this.operating.operate(this); moveTo(this.operating.getCenterPos()); } /*{ Vector2f center = getCenterPos(); headshot.centerAround(center); Vector2f.Vector2fPerpendicular(getFacing(), cache); Vector2f.Vector2fMA(center, cache, 10, cache); this.limbshot.centerAround(cache); DebugDraw.drawRectRelative(limbshot, 0xff0000ff); Vector2f.Vector2fPerpendicular(getFacing(), cache); Vector2f.Vector2fMS(center, cache, 10, cache); this.limbshot.centerAround(cache); DebugDraw.drawRectRelative(limbshot, 0xff0000ff); DebugDraw.drawRectRelative(bounds, 0xff00ffff); DebugDraw.drawRectRelative(headshot, 0xff00ffff); }*/ return blocked; } /** * Updates the {@link Entity#vel} with the inputs * * @param timeStep */ protected void updateVelocity(TimeStep timeStep) { this.vel.set(inputVel); } /** * Handles the invincible time * @param timeStep */ protected void updateInvincibleTime(TimeStep timeStep) { if(this.invinceableTime>0) { this.invinceableTime-=timeStep.getDeltaTime(); } } /** * Handles the vehicle time * @param timeStep */ protected void updateVehicleTime(TimeStep timeStep) { if(this.vehicleTime>0) { this.vehicleTime -= timeStep.getDeltaTime(); } else { if(currentState == State.ENTERING_VEHICLE) { currentState = State.OPERATING_VEHICLE; } else if(currentState == State.EXITING_VEHICLE) { Vehicle vehicle = getVehicle(); Rectangle area = new Rectangle(300, 300); area.centerAround(vehicle.getCenterPos()); Vector2f newPos = game.findFreeRandomSpotNotIn(this, area, vehicle.getOBB()); /* we can't find an area around the tank to exit it, * so lets just keep inside the tank */ if(newPos == null) { currentState = State.OPERATING_VEHICLE; } else { this.operating.stopOperating(this); this.operating = null; setCanTakeDamage(true); currentState = State.IDLE; moveTo(newPos); } } else { if(isOperatingVehicle()) { currentState = State.OPERATING_VEHICLE; } } } } /** * Handles stamina * * @param timeStep */ protected void updateStamina(TimeStep timeStep) { if(currentState != State.SPRINTING) { stamina += STAMINA_RECOVER_RATE; if(stamina > MAX_STAMINA) { stamina = MAX_STAMINA; } /* if are not sprinting anymore, * start recovering */ if(recoveryTime > 0) { recoveryTime -= timeStep.getDeltaTime(); if(recoveryTime <= 0) { completedRecovery = true; } } } else { stamina -= STAMINA_DECAY_RATE; if(stamina < 0) { stamina = 0; currentState = State.RUNNING; recoveryTime = RECOVERY_TIME; } } } /** * Handles the weapon updates * * @param timeStep */ protected void updateWeapons(TimeStep timeStep) { Weapon weapon = inventory.currentItem(); if(weapon!=null) { if(firing) { beginFire(); } weapon.update(timeStep); } if(inventory.hasGrenades()) { GrenadeBelt grenades = inventory.getGrenades(); grenades.update(timeStep); } } /** * Checks to see if we need to stop planting/disarming a {@link BombTarget} * * @param timeStep */ protected void updateBombTargetUse(TimeStep timeStep) { // if we are planting/defusing, make sure // we are still over the bomb if(this.bombTarget != null) { if(!this.bombTarget.isAlive()) { this.bombTarget = null; } else { Bomb bomb = this.bombTarget.getBomb(); if(bomb != null && (bomb.isPlanting() || bomb.isDisarming()) ) { // if we are not, stop planting/defusing if(!bounds.intersects(this.bombTarget.getBounds())) { unuse(); } } } } } /** * Handles making movement sounds * * @param timeStep */ protected void updateMovementSounds(TimeStep timeStep) { /* make walking sounds */ if( !inputVel.isZero() && (currentState==State.RUNNING||currentState==State.SPRINTING) ) { if ( runTime <= 0 ) { Vector2f soundPos = getCenterPos(); int x = (int)soundPos.x; int y = (int)soundPos.y; SurfaceType surface = game.getMap().getSurfaceTypeByWorld(x, y); if(surface != null) { game.emitSound(getId(), SurfaceTypeToSoundType.toSurfaceSoundType(surface) , soundPos); } else { game.emitSound(getId(), SoundType.SURFACE_NORMAL , soundPos); } if(currentState == State.SPRINTING) { if(stamina > 0) { runTime = SPRINT_DELAY_TIME; game.emitSound(getId(), SoundType.RUFFLE, soundPos); } else { runTime = RUN_DELAY_TIME; } } else { runTime = RUN_DELAY_TIME; } /* if we are near end of stamina, breadth hard */ if (stamina <= STAMINA_DECAY_RATE) { game.emitSound(getId(), SoundType.BREATH_HEAVY, soundPos); } /* if we have recovered enough stamina, let out a lite breadth */ if(completedRecovery) { game.emitSound(getId(), SoundType.BREATH_LITE, soundPos); completedRecovery = false; } } else { runTime -= timeStep.getDeltaTime(); } } else { runTime=0; } } /* (non-Javadoc) * @see palisma.game.Entity#calculateMovementSpeed() */ @Override protected int calculateMovementSpeed() { /* The player's speed is impacted by: * 1) the state of the player (walking, running or sprinting) * 2) the weapon he is currently wielding */ int mSpeed = this.speed + this.speedMultiplier; if(currentState==State.WALKING) { mSpeed = (int)( (float)this.speed * WALK_SPEED_FACTOR); } else if(currentState == State.SPRINTING) { if(stamina > 0) { mSpeed = (int)( (float)this.speed * SPRINT_SPEED_FACTOR); } } Weapon weapon = inventory.currentItem(); if(weapon!=null) { mSpeed -= (weapon.getWeaponWeight()); } if(mSpeed < PLAYER_MIN_SPEED) { mSpeed = PLAYER_MIN_SPEED; } return mSpeed; } /** * @return the inventory */ public Inventory getInventory() { return inventory; } /** * @return the team */ public Team getTeam() { return team; } /** * @param team the team to set */ public void setTeam(Team team) { this.team = team; if(this.team != null) { Player player = team.getPlayerById(this.id); setPlayerClass(player.getPlayerClass(), player.getWeaponClass()); } } /* * (non-Javadoc) * @see seventh.game.Controllable#handleUserCommand(seventh.game.UserCommand) */ @Override public void handleUserCommand(int keys, float orientation) { if(isOperatingVehicle()) { /* The USE key is the one that enters/exit * the vehicles */ if(Keys.USE.isDown(previousKeys) && !Keys.USE.isDown(keys)) { if(currentState==State.OPERATING_VEHICLE&&!this.operating.isMoving()) { leaveVehicle(); } } else { /* this additional check makes sure we are not * entering/exiting the vehicle and controlling * it */ if(currentState==State.OPERATING_VEHICLE) { this.operating.handleUserCommand(keys, orientation); } } previousKeys = keys; } else { if( Keys.FIRE.isDown(keys) ) { firing = true; } else if(Keys.FIRE.isDown(previousKeys)) { endFire(); firing = false; } if(Keys.THROW_GRENADE.isDown(keys)) { pullGrenadePin(); } if(Keys.THROW_GRENADE.isDown(previousKeys) && !Keys.THROW_GRENADE.isDown(keys)) { throwGrenade(); } if(Keys.USE.isDown(keys)) { use(); } else { unuse(); if(Keys.USE.isDown(previousKeys)) { useSingle(); } } if(Keys.MELEE_ATTACK.isDown(keys)) { meleeAttack(); } else if(Keys.MELEE_ATTACK.isDown(previousKeys)) { doneMeleeAttack(); } if(Keys.DROP_WEAPON.isDown(previousKeys) && !Keys.DROP_WEAPON.isDown(keys)) { dropWeapon(); } if(Keys.RELOAD.isDown(keys)) { reload(); } if(Keys.WALK.isDown(keys)) { walk(); } else { stopWalking(); } /* ============================================ * Handles the movement of the character * ============================================ */ if(Keys.UP.isDown(keys)) { moveUp(); } else if(Keys.DOWN.isDown(keys)) { moveDown(); } else { noMoveY(); } if(Keys.LEFT.isDown(keys)) { moveLeft(); } else if (Keys.RIGHT.isDown(keys)) { moveRight(); } else { noMoveX(); } if(Keys.SPRINT.isDown(keys)) { if(!inputVel.isZero() && currentState != State.WALKING) { sprint(); } } else { stopSprinting(); } if(Keys.CROUCH.isDown(keys)) { crouch(); } else { standup(); } if(Keys.WEAPON_SWITCH_UP.isDown(keys)) { nextWeapon(); } else if (Keys.WEAPON_SWITCH_DOWN.isDown(keys)) { prevWeapon(); } if(previousOrientation != orientation) { setOrientation(orientation); } this.previousKeys = keys; this.previousOrientation = orientation; } } /* (non-Javadoc) * @see seventh.game.Entity#setOrientation(float) */ @Override public void setOrientation(float orientation) { if(isSprinting()) { return; } if(inventory != null) { Weapon weapon = inventory.currentItem(); if(weapon==null || !weapon.isMeleeAttacking()) { super.setOrientation(orientation); } } else { super.setOrientation(orientation); } } /** * Go in the walking position (makes no sounds) */ public void walk() { if(currentState!=State.DEAD) { currentState = State.WALKING; } } /* * (non-Javadoc) * @see seventh.game.Controllable#stopWalking() */ public void stopWalking() { if(currentState==State.WALKING) { currentState = State.RUNNING; } } /* * (non-Javadoc) * @see seventh.game.Controllable#crouch() */ public void crouch() { if(currentState == State.IDLE) { Weapon weapon = this.inventory.currentItem(); if(weapon==null||!weapon.isHeavyWeapon()) { game.emitSound(getId(), SoundType.RUFFLE, getCenterPos()); this.currentState = State.CROUCHING; } } } /* * (non-Javadoc) * @see seventh.game.Controllable#standup() */ public void standup() { if(currentState==State.CROUCHING) { game.emitSound(getId(), SoundType.RUFFLE, getCenterPos()); this.currentState = State.IDLE; } } /* * (non-Javadoc) * @see seventh.game.Controllable#sprint() */ public void sprint() { /* * We only allow sprinting in very special cases: * 1) you are not dead * 2) you have enough stamina * 3) you are not firing your weapon * 4) you are not currently using a Rocket Launcher * 5) recovery time has been met * 6) you are not reloading */ if(currentState!=State.DEAD && stamina > 0 && !firing && !wasSprinting && recoveryTime <= 0) { Weapon weapon = this.inventory.currentItem(); boolean isReady = weapon != null ? weapon.isReady() : true; if(weapon == null || !weapon.isHeavyWeapon() && isReady) { if(currentState!=State.SPRINTING) { game.emitSound(getId(), SoundType.RUFFLE, getCenterPos()); } currentState = State.SPRINTING; return; } } wasSprinting = true; currentState = State.RUNNING; } public void stopSprinting() { this.wasSprinting = false; if(!inputVel.isZero() && currentState != State.WALKING) { currentState = State.RUNNING; } } /** * @return true if we are entering a vehicle */ public boolean isEnteringVehicle() { return this.currentState == State.ENTERING_VEHICLE; } /** * @return true if we are exiting the vehicle */ public boolean isExitingVehicle() { return this.currentState == State.EXITING_VEHICLE; } /** * @return true if we are walking */ public boolean isWalking() { return this.currentState == State.WALKING; } /** * @return true if we are running */ public boolean isRunning() { return this.currentState == State.RUNNING; } /** * @return true if we are sprinting */ public boolean isSprinting() { return this.currentState == State.SPRINTING; } /* * (non-Javadoc) * @see seventh.game.Controllable#reload() */ public boolean reload() { Weapon weapon = this.inventory.currentItem(); if(weapon!=null) { return weapon.reload(); } return false; } /** * @return true if we are currently reloading a weapon */ public boolean isReloading() { Weapon weapon = this.inventory.currentItem(); if(weapon!=null) { return weapon.isReloading(); } return false; } /** * @return true if we are currently switching weapons */ public boolean isSwitchingWeapon() { Weapon weapon = this.inventory.currentItem(); if(weapon!=null) { return weapon.isSwitchingWeapon(); } return false; } /** * @return true if we are currently melee attacking */ public boolean isMeleeAttacking() { Weapon weapon = this.inventory.currentItem(); if(weapon!=null) { return weapon.isMeleeAttacking(); } return false; } /* * (non-Javadoc) * @see seventh.game.Controllable#meleeAttack() */ public boolean meleeAttack() { Weapon weapon = this.inventory.currentItem(); if(weapon != null && !weapon.isHeavyWeapon()) { return weapon.meleeAttack(); } return false; } /* * (non-Javadoc) * @see seventh.game.Controllable#doneMeleeAttack() */ public void doneMeleeAttack() { Weapon weapon = this.inventory.currentItem(); if(weapon != null) { weapon.doneMelee(); } } /* * (non-Javadoc) * @see seventh.game.Controllable#beginFire() */ public boolean beginFire() { Weapon weapon = this.inventory.currentItem(); if(weapon!=null) { return weapon.beginFire(); } return false; } /* * (non-Javadoc) * @see seventh.game.Controllable#endFire() */ public boolean endFire() { Weapon weapon = this.inventory.currentItem(); if(weapon!=null) { return weapon.endFire(); } return false; } /** * @return true if the weapon is being fired */ public boolean isFiring() { Weapon weapon = this.inventory.currentItem(); if(weapon!=null) { return weapon.isFiring(); } return false; } /* * (non-Javadoc) * @see seventh.game.Controllable#pullGrenadePin() */ public boolean pullGrenadePin() { if(inventory.hasGrenades()) { GrenadeBelt grenades = inventory.getGrenades(); return grenades.pullPin(); } return false; } /* * (non-Javadoc) * @see seventh.game.Controllable#throwGrenade() */ public boolean throwGrenade() { if(inventory.hasGrenades()) { GrenadeBelt grenades = inventory.getGrenades(); return grenades.throwGrenade(); } return false; } /** * @return true if the current weapon can fire */ public boolean canFire() { Weapon weapon = this.inventory.currentItem(); if(weapon!=null) { return weapon.canFire(); } return false; } /* * (non-Javadoc) * @see seventh.game.Controllable#moveOrientation(float) */ public void moveOrientation(float value) { this.setOrientation(value); } /* * (non-Javadoc) * @see seventh.game.Controllable#noMoveY() */ public void noMoveY() { vel.y = 0; inputVel.y = 0; } /* * (non-Javadoc) * @see seventh.game.Controllable#moveUp() */ public void moveUp() { vel.y = -1; inputVel.y = -1; } /* * (non-Javadoc) * @see seventh.game.Controllable#moveDown() */ public void moveDown() { vel.y = 1; inputVel.y = 1; } /* * (non-Javadoc) * @see seventh.game.Controllable#noMoveX() */ public void noMoveX() { vel.x = 0; inputVel.x = 0; } /* * (non-Javadoc) * @see seventh.game.Controllable#moveLeft() */ public void moveLeft() { vel.x = -1; inputVel.x = -1; } /* * (non-Javadoc) * @see seventh.game.Controllable#moveRight() */ public void moveRight() { vel.x = 1; inputVel.x = 1; } /* * (non-Javadoc) * @see seventh.game.Controllable#nextWeapon() */ public void nextWeapon() { Weapon weapon = inventory.nextItem(); if(weapon!=null) { weapon.setSwitchingWeaponState(); if(weapon.isHeavyWeapon()) { standup(); } checkLineOfSightChange(); } } /* * (non-Javadoc) * @see seventh.game.Controllable#prevWeapon() */ public void prevWeapon() { Weapon weapon = inventory.prevItem(); if(weapon!=null) { weapon.setSwitchingWeaponState(); if(weapon.isHeavyWeapon()) { standup(); } checkLineOfSightChange(); } } public void armWeapon(Weapon weapon) { if(weapon != null) { if(inventory.hasItem(weapon.getType())) { inventory.equipItem(weapon.getType()); weapon.setSwitchingWeaponState(); if(weapon.isHeavyWeapon()) { standup(); } checkLineOfSightChange(); } } } /** * Determines if this entity is currently planting a bomb * @return true if planting. */ public boolean isPlantingBomb() { if(this.bombTarget != null) { Bomb bomb = this.bombTarget.getBomb(); if(bomb != null && bomb.isPlanting() ) { return bounds.intersects(this.bombTarget.getBounds()); } } return false; } /** * Determines if this entity is currently defusing a bomb * @return true if defusing. */ public boolean isDefusingBomb() { if(this.bombTarget != null) { Bomb bomb = this.bombTarget.getBomb(); if(bomb != null && bomb.isDisarming() ) { return bounds.intersects(this.bombTarget.getBounds()); } } return false; } /** * Determines if this entity is currently throwing a grenade (the pin has been * pulled) * @return true if pin is pulled on the grenade */ public boolean isThrowingGrenade() { return this.inventory.getGrenades().isPinPulled(); } /** * Handles a {@link BombTarget}, meaning this will either plant or disarm * the {@link BombTarget}. * * @param target */ protected void handleBombTarget(BombTarget target) { if(target!=null) { if(target.getOwner().equals(getTeam())) { if(target.bombActive()) { Bomb bomb = target.getBomb(); bomb.disarm(this); game.emitSound(getId(), SoundType.BOMB_DISARM, getPos()); } } else { if(!target.isBombAttached()) { Bomb bomb = game.newBomb(target); bomb.plant(this, target); target.attachBomb(bomb); game.emitSound(getId(), SoundType.BOMB_PLANT, getPos()); } } } } protected void handleDoor(Door door) { door.handleDoor(this); } /** * Drop the players current weapon, and if there is a weapon * near, and we have a full inventory */ public void dropWeapon() { // if we have a full inventory, and there is a weapon // near this entity, replace the dropped item with the near weapon DroppedItem itemNearMe = game.getArmsReachDroppedWeapon(this); if(itemNearMe != null) { if(this.inventory.isPrimaryFull()) { dropItem(true); } pickupDroppedItem(itemNearMe); armWeapon(itemNearMe.getDroppedItem()); } else { dropItem(true); } } /** * For actions that rely on a button press. This differs * from use() because use() relies on a button being held down, * as this relies on the press (the button is pushed and once * released this method is activated). */ public void useSingle() { Door door = game.getArmsReachDoor(this); if(door != null) { handleDoor(door); } } /** * Use can be used for either planting a bomb, or disarming it. */ public void use() { if(isOperatingVehicle()) { if(vehicleTime <= 0) { leaveVehicle(); } } else { if(this.bombTarget == null) { this.bombTarget = game.getArmsReachBombTarget(this); if(this.bombTarget != null) { handleBombTarget(this.bombTarget); } } if(this.bombTarget == null) { Vehicle vehicle = game.getArmsReachOperableVehicle(this); if(vehicle != null) { if(vehicleTime <= 0) { operateVehicle(vehicle); } } } } } /* * (non-Javadoc) * @see seventh.game.Controllable#unuse() */ public void unuse() { if(this.bombTarget != null) { Bomb bomb = this.bombTarget.getBomb(); if(bomb != null) { if(bomb.isPlanting()) { bomb.stopPlanting(); bomb.softKill(); this.bombTarget.reset(); } else if(bomb.isDisarming()) { bomb.stopDisarming(); } } this.bombTarget = null; } } /** * Updates the line of sight (LOS) depending * on the current {@link Weapon} */ private void checkLineOfSightChange() { Weapon weapon = inventory.currentItem(); if(weapon !=null) { setLineOfSight(weapon.getLineOfSight()); } } /** * Determines if both {@link PlayerEntity} are on the same team. * @param other * @return true if both {@link PlayerEntity} are on the same team */ public boolean isOnTeamWith(PlayerEntity other) { Team othersTeam = other.getTeam(); if(othersTeam != null) { if(this.team != null) { return this.team.getId() == othersTeam.getId(); } } return false; } /** * If this {@link PlayerEntity} is currently holding a specific * weapon type. * * @param weaponType * @return true if the current active weapon is of the supplied type */ public boolean isYielding(Type weaponType) { Weapon weapon = this.inventory.currentItem(); return (weapon != null && weapon.getType().equals(weaponType)); } /** * If this {@link PlayerEntity} is operating a {@link Vehicle} * @return true if operating a {@link Vehicle} */ public boolean isOperatingVehicle() { return this.operating != null && this.operating.isAlive(); } private void beginLeaveVehicle() { this.vehicleTime = EXITING_VEHICLE_TIME; this.currentState = State.EXITING_VEHICLE; } /** * Leaves the {@link Vehicle} */ public void leaveVehicle() { beginLeaveVehicle(); } /** * Operates the vehicle * * @param vehicle */ public void operateVehicle(Vehicle vehicle) { this.operating = vehicle; this.operating.operate(this); this.vehicleTime = ENTERING_VEHICLE_TIME; this.currentState = State.ENTERING_VEHICLE; setCanTakeDamage(false); } /** * @return the {@link Vehicle} this {@link PlayerEntity} is operating */ public Vehicle getVehicle() { return this.operating; } /** * Retrieves the sounds heard by an Entity * @param soundEvents * @param soundsHeard (the out parameter) * @return the same instance as soundsHeard, just returned for convenience */ public List<SoundEmittedEvent> getHeardSounds(SoundEventPool soundEvents, List<SoundEmittedEvent> soundsHeard) { this.hearingBounds.centerAround(getCenterPos()); int size = soundEvents.numberOfSounds(); for(int i = 0; i < size; i++) { SoundEmittedEvent event = soundEvents.getSound(i); if((this.hearingBounds.contains(event.getPos()) && event.getForEntityId() < 0) || this.id == event.getForEntityId()) { soundsHeard.add(event); } } return soundsHeard; } @Override public List<Tile> calculateLineOfSight(List<Tile> tiles) { Map map = game.getMap(); Geom.calculateLineOfSight(tiles, getCenterPos(), getFacing(), getLineOfSight(), map, getHeightMask(), cache); int tileSize = tiles.size(); List<Door> doors = game.getDoors(); int doorSize = doors.size(); Vector2f centerPos = getCenterPos(); for(int j = 0; j < doorSize; j++ ) { Door door = doors.get(j); if(this.visualBounds.intersects(door.getBounds())) { for(int i = 0; i < tileSize; i++) { Tile tile = tiles.get(i); if(Line.lineIntersectLine(centerPos, tile.getCenterPos(), door.getPos(), door.getHandle())) { tile.setMask(Tile.TILE_INVISIBLE); } } } } /* List<Smoke> smoke = game.getSmokeEntities(); int smokeSize = smoke.size(); if(smokeSize > 0) { for(int j = 0; j < smokeSize; j++) { Smoke s = smoke.get(j); if(this.visualBounds.intersects(s.getBounds())) { for(int i = 0; i < tileSize; i++) { Tile tile = tiles.get(i); if(tile.getMask() > 0) { if(Line.lineIntersectsRectangle(centerPos, tile.getCenterPos(), s.getBounds())) { tile.setMask(Tile.TILE_INVISIBLE); } } } } } }*/ return tiles; } /** * Hides players that are behind smoke */ protected void pruneEntitiesBehindSmoke(List<Entity> entitiesInView) { int entitySize = entitiesInView.size(); List<Smoke> smoke = game.getSmokeEntities(); int smokeSize = smoke.size(); Vector2f centerPos = getCenterPos(); if(entitySize > 0 && smokeSize > 0) { for(int j = 0; j < smokeSize; j++) { Smoke s = smoke.get(j); if(this.visualBounds.intersects(s.getBounds())) { for(int i = 0; i < entitySize;) { Entity ent = entitiesInView.get(i); if(ent.getType()==Type.PLAYER && Line.lineIntersectsRectangle(ent.getCenterPos(), centerPos, s.getBounds())) { entitiesInView.remove(i); entitySize--; } else { i++; } } } } } } /** * Given the game state, retrieve the {@link Entity}'s in the current entities view. * @param game * @return a list of {@link Entity}s that are in this players view */ public List<Entity> getEntitiesInView(Game game, List<Entity> entitiesInView) { /* * Calculate all the visuals this player can see */ Map map = game.getMap(); Entity[] entities = game.getEntities(); Vector2f centerPos = getCenterPos(); this.visualBounds.centerAround(centerPos); if(isOperatingVehicle()) { getVehicle().calculateLineOfSight(game.tilesInLineOfSight); } else { calculateLineOfSight(game.tilesInLineOfSight); } for(int i = 0; i < entities.length; i++) { Entity ent = entities[i]; if(ent==null /*|| !ent.isAlive()*/) { continue; } Type entType = ent.getType(); boolean isCalculatedEntity = entType==Type.PLAYER; if(isCalculatedEntity && game.isEnableFOW()) { if(ent.getId() != id) { Vector2f pos = ent.getCenterPos(); Vector2f.Vector2fSubtract(pos, centerPos, this.enemyDir); Vector2f.Vector2fNormalize(this.enemyDir, this.enemyDir); if(!game.isEntityReachable(ent, centerPos, this.enemyDir)) { continue; } // if(map.lineCollides(pos, centerPos)) { // continue; // } int px = (int)pos.x; int py = (int)pos.y; // check center of entity Tile tile = map.getWorldTile(0, px, py); if(tile!=null) { if (tile.getMask() > 0) { entitiesInView.add(ent); continue; } } // make this a rectangle int width = ent.getBounds().width; // 4 int height = ent.getBounds().height; // 4 // offset a bit to because for whatever // reason entities butted against the lower right // corner become hidden px = (int)ent.getPos().x;//width/4; // 3 py = (int)ent.getPos().y;//+height/4; // check upper right corner tile = map.getWorldTile(0, px+width, py); if(tile!=null) { if (tile.getMask() > 0) { //tile.getCollisionMask().pointCollide(hearingBounds, px, py) entitiesInView.add(ent); continue; } } // check lower right corner tile = map.getWorldTile(0, px+width, py+height); if(tile!=null) { if (tile.getMask() > 0) { entitiesInView.add(ent); continue; } } // check lower left corner tile = map.getWorldTile(0, px, py+height); if(tile!=null) { if (tile.getMask() > 0) { entitiesInView.add(ent); continue; } } // check upper left corner tile = map.getWorldTile(0, px, py); if(tile!=null) { if (tile.getMask() > 0) { entitiesInView.add(ent); continue; } } } } else { /* We don't always send every entity over the wire */ Type type = ent.getType(); switch(type) { case BOMB: Bomb bomb = (Bomb)ent; if(bomb.isPlanted()) { entitiesInView.add(ent); } break; /*case ALLIED_FLAG: case AXIS_FLAG: entitiesInView.add(ent); break;*/ case LIGHT_BULB: case BOMB_TARGET: /* don't add */ //break; we must add this, scripts // may add these items well after the initial // NetGameState message was sent default: { if(visualBounds.intersects(ent.getBounds())) { entitiesInView.add(ent); } } } } } pruneEntitiesBehindSmoke(entitiesInView); return entitiesInView; } /* (non-Javadoc) * @see palisma.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { return getNetPlayerPartial(); } /** * Read the state * @return the {@link NetPlayer} */ public NetPlayer getNetPlayer() { setNetEntity(player); player.orientation = (short) Math.toDegrees(this.orientation); player.state = currentState; if(inventory.hasGrenades()) { GrenadeBelt belt = inventory.getGrenades(); player.grenades = (byte)belt.getNumberOfGrenades(); player.isSmokeGrenades = belt.getType() == Type.SMOKE_GRENADE; } else { player.grenades = 0; } player.health = (byte)getHealth(); player.isOperatingVehicle = isOperatingVehicle(); if(player.isOperatingVehicle) { player.vehicleId = this.operating.getId(); } Weapon weapon = inventory.currentItem(); if(weapon!=null) { player.weapon = weapon.getNetWeapon(); } else { player.weapon = null; } return player; } /** * Gets the Partial network update. The {@link NetPlayerPartial} is used for Players * that are NOT the local player * @return the {@link NetPlayerPartial} */ public NetPlayerPartial getNetPlayerPartial() { setNetEntity(partialPlayer); partialPlayer.orientation = getNetOrientation(); partialPlayer.state = currentState; partialPlayer.health = (byte)getHealth(); player.isOperatingVehicle = isOperatingVehicle(); if(player.isOperatingVehicle) { player.vehicleId = this.operating.getId(); } Weapon weapon = inventory.currentItem(); if(weapon!=null) { partialPlayer.weapon = weapon.getNetWeapon(); } else { partialPlayer.weapon = null; } return partialPlayer; } }
58,833
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
DroppedResource.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/DroppedResource.java
/* * see license.txt */ package seventh.game.entities; import seventh.game.Game; import seventh.game.net.NetEntity; import seventh.math.Vector2f; /** * @author Tony * */ public class DroppedResource extends Entity { private PlayerEntity carriedBy; private int amount; /** * @param position * @param game * @param type */ public DroppedResource(Vector2f position, Game game, Type type) { super(game.getNextEntityId(), position, 0, game, type); this.carriedBy = null; } /** * @return the carriedBy */ public PlayerEntity getCarriedBy() { return carriedBy; } /** * @return if this is being carried by a player */ public boolean isBeingCarried() { return this.carriedBy != null; } /** * Set who is carrying this flag * @param player */ public void carriedBy(PlayerEntity player) { if(!isBeingCarried() && player.isAlive()) { this.carriedBy = player; // this.carriedBy.pickupFlag(this); // TODO: Pick up the resource } } /* (non-Javadoc) * @see seventh.game.entities.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { // TODO Auto-generated method stub return null; } }
1,381
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
PanzerTank.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/vehicles/PanzerTank.java
/* * see license.txt */ package seventh.game.entities.vehicles; import seventh.game.Game; import seventh.math.Vector2f; /** * A German Panzer Tank * * @author Tony * */ public class PanzerTank extends Tank { /** * @param position * @param game */ public PanzerTank(Vector2f position, Game game, long timeToKill) { super(Type.PANZER_TANK, position, game, timeToKill); } }
419
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
ShermanTank.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/vehicles/ShermanTank.java
/* * see license.txt */ package seventh.game.entities.vehicles; import seventh.game.Game; import seventh.math.Vector2f; /** * An allied Sherman tank * * @author Tony * */ public class ShermanTank extends Tank { /** * @param position * @param game */ public ShermanTank(Vector2f position, Game game, long timeToKill) { super(Type.SHERMAN_TANK, position, game, timeToKill); } }
424
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Vehicle.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/vehicles/Vehicle.java
/** * */ package seventh.game.entities.vehicles; import seventh.game.Controllable; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.PlayerEntity; import seventh.game.weapons.Bullet; import seventh.math.OBB; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.Timer; import seventh.shared.WeaponConstants; /** * Something a Player can ride * * @author Tony * */ public abstract class Vehicle extends Entity implements Controllable { protected final Rectangle operateHitBox; protected final OBB vehicleBB; protected final Vector2f center; protected int aabbWidth, aabbHeight; private PlayerEntity operator; private Timer killTimer; private Entity killer; /** * @param position * @param speed * @param game * @param type */ public Vehicle(Vector2f position, int speed, Game game, Type type, long timeToKill) { super(game.getNextPersistantId(), position, speed, game, type); this.operateHitBox = new Rectangle(); this.vehicleBB = new OBB(); this.center = new Vector2f(); this.killTimer = new Timer(false, timeToKill < 0 ? Long.MAX_VALUE : timeToKill); } /* (non-Javadoc) * @see seventh.game.Entity#kill(seventh.game.Entity) */ @Override public void kill(Entity killer) { if(this.currentState!=State.DESTROYED && this.currentState!=State.DEAD) { this.killTimer.start(); this.currentState = State.DESTROYED; this.killer = killer; if(hasOperator()) { getOperator().kill(killer); } } } @Override public void damage(Entity damager, int amount) { if(damager instanceof Bullet) { Bullet bullet = (Bullet) damager; bullet.kill(this); game.emitSound(bullet.getId(), SoundType.IMPACT_METAL, bullet.getCenterPos()); } super.damage(damager, amount); } /* (non-Javadoc) * @see seventh.game.Entity#update(seventh.shared.TimeStep) */ @Override public boolean update(TimeStep timeStep) { if(isDestroyed()) { return false; } boolean blocked = super.update(timeStep); updateOperateHitBox(); killTimer.update(timeStep); if(killTimer.isOnFirstTime()) { super.kill(killer); } return blocked; } /** * @return the vehicleBB */ public OBB getOBB() { return vehicleBB; } /** * Synchronize the {@link OBB} with the current orientation and position * of the vehicle * * @param orientation * @param pos */ protected void syncOOB(float orientation, Vector2f pos) { center.set(pos); center.x += aabbWidth/2f; center.y += aabbHeight/2f; vehicleBB.update(orientation, center); } /** * Updates the operation hit box to keep up * with any type of movement */ protected void updateOperateHitBox() { operateHitBox.x = bounds.x - WeaponConstants.VEHICLE_HITBOX_THRESHOLD/2; operateHitBox.y = bounds.y - WeaponConstants.VEHICLE_HITBOX_THRESHOLD/2; } /** * @return true if this vehicle is moving */ public boolean isMoving() { return currentState == State.RUNNING; } /** * Determines if the supplied {@link Entity} can operate this {@link Vehicle} * @param operator * @return true if the {@link Entity} is close enough to operate this {@link Vehicle} */ public boolean canOperate(Entity operator) { if(!isAlive() || isDestroyed()) { return false; } return !hasOperator() && this.operateHitBox.intersects(operator.getBounds()); } /** * @return the operator */ public PlayerEntity getOperator() { return operator; } /** * @return true if there is an operator */ public boolean hasOperator() { return this.operator != null && this.operator.isAlive(); } /** * @param operator the operator to set */ public void operate(PlayerEntity operator) { if(!hasOperator()) { beginOperating(); } this.operator = operator; } /** * The {@link PlayerEntity} has stopped operating this {@link Vehicle} * @param operator */ public void stopOperating(PlayerEntity operator) { this.operator = null; endOperating(); } protected void beginOperating() { } protected void endOperating() { } /* (non-Javadoc) * @see seventh.game.Entity#isTouching(seventh.game.Entity) */ @Override public boolean isTouching(Entity other) { // first check the cheap AABB if(bounds.intersects(other.getBounds())) { if(other instanceof Vehicle) { Vehicle otherVehicle = (Vehicle)other; return this.vehicleBB.intersects(otherVehicle.vehicleBB); } else { return this.vehicleBB.intersects(other.getBounds()); } } return false; } /** * @return true if the current state is destroyed */ public boolean isDestroyed() { return getCurrentState()==State.DESTROYED; } }
5,743
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Tank.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/entities/vehicles/Tank.java
/** * */ package seventh.game.entities.vehicles; import java.util.List; import seventh.game.Game; import seventh.game.SmoothOrientation; import seventh.game.SoundEmitter; import seventh.game.entities.Entity; import seventh.game.entities.PlayerEntity.Keys; import seventh.game.net.NetEntity; import seventh.game.net.NetTank; import seventh.game.weapons.Bullet; import seventh.game.weapons.Explosion; import seventh.game.weapons.MG42; import seventh.game.weapons.Rocket; import seventh.game.weapons.RocketLauncher; import seventh.game.weapons.Weapon; import seventh.map.Map; import seventh.map.Tile; import seventh.math.FastMath; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.DebugDraw; import seventh.shared.EaseInInterpolation; import seventh.shared.Geom; import seventh.shared.SeventhConstants; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.Timer; import seventh.shared.WeaponConstants; /** * Represents a Tank * * @author Tony * */ public class Tank extends Vehicle { private final NetTank netTank; private int previousKeys; private float previousOrientation; private long nextMovementSound; private boolean isFiringPrimary; private boolean isFiringSecondary; private boolean isRetracting; private float throttle; private float turretOrientation; private float desiredTurretOrientation; private float lastValidOrientation; private long throttleStartTime; private long throttleWarmupTime; private float desiredOrientation; private Weapon primaryWeapon; private Weapon secondaryWeapon; private Vector2f turretFacing; private SmoothOrientation turretSmoother; private int armor; private Timer blowupTimer, explosionTimer; private boolean isDying; private boolean isStopping; private boolean isStopped; private Entity killer; private EaseInInterpolation stopEase; private Vector2f previousVel; private SoundEmitter idleEngineSnd, moveSnd, turretRotateSnd, refDownSnd; /** * @param type * @param position * @param game */ protected Tank(Type type, Vector2f position, final Game game, long timeToKill) { super(position, WeaponConstants.TANK_MOVEMENT_SPEED, game, type, timeToKill); this.turretFacing = new Vector2f(); this.netTank = new NetTank(type); this.netTank.id = getId(); this.blowupTimer = new Timer(false, 3_800); this.explosionTimer = new Timer(true, 450); this.isDying = false; this.stopEase = new EaseInInterpolation(WeaponConstants.TANK_MOVEMENT_SPEED, 0f, 800); this.previousVel = new Vector2f(); this.idleEngineSnd = new SoundEmitter(8_500, true); this.moveSnd = new SoundEmitter(5_800, true); this.turretRotateSnd = new SoundEmitter(800, true); this.refDownSnd = new SoundEmitter(1_500, true); this.primaryWeapon = new RocketLauncher(game, this) { @Override protected void emitFireSound() { game.emitSound(getOwnerId(), SoundType.TANK_FIRE, getPos()); } @Override public boolean beginFire() { boolean isFired = super.beginFire(); if(isFired) { weaponTime = 3_000; } return isFired; } @Override protected Vector2f newRocketPosition() { this.bulletsInClip = 500; Vector2f ownerDir = getTurretFacing(); Vector2f ownerPos = owner.getCenterPos(); Vector2f pos = new Vector2f(); float x = ownerDir.y * 5.0f; float y = -ownerDir.x * 5.0f; Vector2f.Vector2fMA(ownerPos, ownerDir, 145.0f, pos); pos.x += x; pos.y += y; return pos; } @Override protected Vector2f calculateVelocity(Vector2f facing) { return super.calculateVelocity(getTurretFacing()); } @Override protected Rocket newRocket() { Rocket rocket = super.newRocket(); rocket.setOwnerHeightMask(CROUCHED_HEIGHT_MASK); rocket.setOrientation(turretOrientation); rocket.setOwner(getOperator()); return rocket; } }; this.secondaryWeapon = new MG42(game, this) { @Override protected Vector2f newBulletPosition() { Vector2f ownerDir = getTurretFacing(); Vector2f ownerPos = owner.getCenterPos(); Vector2f pos = new Vector2f(); float x = ownerDir.y * 1.0f; float y = -ownerDir.x * 1.0f; Vector2f.Vector2fMA(ownerPos, ownerDir, 145.0f, pos); pos.x += x; pos.y += y; return pos; } @Override protected Bullet newBullet() { Bullet bullet = super.newBullet(); bullet.setOwner(getOperator()); return bullet; } @Override protected Vector2f calculateVelocity(Vector2f facing) { return super.calculateVelocity(getTurretFacing()); } }; bounds.width = WeaponConstants.TANK_AABB_WIDTH; bounds.height = WeaponConstants.TANK_AABB_HEIGHT; aabbWidth = bounds.width; aabbHeight = bounds.height; this.orientation = 0; this.desiredOrientation = this.orientation; this.turretSmoother = new SmoothOrientation(Math.toRadians(1.5f)); this.armor = 200; vehicleBB.setBounds(WeaponConstants.TANK_WIDTH, WeaponConstants.TANK_HEIGHT); syncOOB(getOrientation(), position); operateHitBox.width = bounds.width + WeaponConstants.VEHICLE_HITBOX_THRESHOLD; operateHitBox.height = bounds.height + WeaponConstants.VEHICLE_HITBOX_THRESHOLD; onTouch = new OnTouchListener() { @Override public void onTouch(Entity me, Entity other) { /* kill the other players */ if(hasOperator()) { if(other != getOperator()) { if (other.getType().isPlayer()) { other.kill(getOperator()); } } } } }; } /* (non-Javadoc) * @see seventh.game.Entity#collideX(int, int) */ @Override protected boolean collideX(int newX, int oldX) { return false; } /* (non-Javadoc) * @see seventh.game.Entity#collideY(int, int) */ @Override protected boolean collideY(int newY, int oldY) { return false; } /* * (non-Javadoc) * * @see seventh.game.PlayerEntity#update(seventh.shared.TimeStep) */ @Override public boolean update(TimeStep timeStep) { DebugDraw.drawRectRelative(bounds.x, bounds.y, bounds.width, bounds.height, 0xffffff00); DebugDraw.drawOOBRelative(vehicleBB, 0xff00ff00); DebugDraw.fillRectRelative((int)pos.x, (int)pos.y, 5, 5, 0xffff0000); DebugDraw.fillRectRelative((int)vehicleBB.topLeft.x, (int)vehicleBB.topLeft.y, 5, 5, 0xff1f0000); DebugDraw.fillRectRelative((int)vehicleBB.topRight.x, (int)vehicleBB.topRight.y, 5, 5, 0xffff0000); DebugDraw.fillRectRelative((int)vehicleBB.bottomLeft.x, (int)vehicleBB.bottomLeft.y, 5, 5, 0xff001f00); DebugDraw.fillRectRelative((int)vehicleBB.bottomRight.x, (int)vehicleBB.bottomRight.y, 5, 5, 0xff00ff00); DebugDraw.drawStringRelative("" + vehicleBB.topLeft, bounds.x, bounds.y+240, 0xffff0000); DebugDraw.drawStringRelative("" + vehicleBB.bottomLeft, bounds.x, bounds.y+220, 0xffff0000); DebugDraw.drawStringRelative(String.format(" Tracks: %3.2f : %3.2f", Math.toDegrees(this.orientation), Math.toDegrees(this.desiredOrientation)), (int)getPos().x, (int)getPos().y-20, 0xffff0000); DebugDraw.drawStringRelative(String.format(" Current: %3.2f : %3.2f", Math.toDegrees(this.turretOrientation), Math.toDegrees(desiredTurretOrientation)), getPos(), 0xffff0000); if(isDestroyed()) { return false; } if( checkIfDying(timeStep) ) { return false; } boolean isBlocked = false; if(hasOperator()) { // this.primaryWeapon.setOwner(getOperator()); // this.secondaryWeapon.setOwner(getOperator()); makeMovementSounds(timeStep); } { updateOrientation(timeStep); updateTurretOrientation(timeStep); updateWeapons(timeStep); this.vel.set(this.facing); Vector2f.Vector2fMult(vel, this.throttle, vel); Vector2f.Vector2fNormalize(vel, vel); isBlocked = movementUpdate(timeStep); } updateOperateHitBox(); syncOOB(orientation, pos); game.doesVehicleTouchPlayers(this); return isBlocked; } private boolean checkIfDying(TimeStep timeStep) { if(this.isDying) { this.blowupTimer.update(timeStep); this.explosionTimer.update(timeStep); if(this.explosionTimer.isTime()) { game.newBigExplosion(getCenterPos(), this, 20, 80, 100); } if(this.blowupTimer.isTime()) { super.kill(killer); this.isDying = false; } } return this.isDying; } /** * @param dt * @return true if blocked */ private boolean movementUpdate(TimeStep timeStep) { if(isDestroyed()) { return false; } boolean isBlocked = false; boolean hasThrottle = ! this.vel.isZero(); if(!hasThrottle && !this.isStopped) { this.isStopping = true; //game.emitSound(getId(), SoundType.TANK_REV_DOWN, getCenterPos()); } if(isAlive() && (hasThrottle || this.isStopping) ) { if(currentState != State.WALKING && currentState != State.SPRINTING) { currentState = State.RUNNING; } if(this.throttleWarmupTime < 600) { this.throttleWarmupTime += timeStep.getDeltaTime(); if(hasOperator() && this.throttleWarmupTime > 590) { game.emitSound(getOperator().getId(), SoundType.TANK_REV_UP, getCenterPos()); } } else { this.throttleStartTime -= timeStep.getDeltaTime(); if(this.isStopping) { this.vel.set(this.previousVel); this.stopEase.update(timeStep); if(this.stopEase.isExpired()) { this.isStopping = false; this.isStopped = true; return isBlocked; } } else { this.stopEase.reset(90f, 0f, 800); this.isStopped = false; this.previousVel.set(this.vel); if(hasOperator()) { // game.emitSound(getOperator().getId(), SoundType.TANK_MOVE1, getCenterPos()); } } float normalSpeed = this.isStopping ? this.stopEase.getValue() : 90f; final float movementSpeed = this.throttleStartTime > 0 ? 160f : normalSpeed; float dt = (float)timeStep.asFraction(); float newX = pos.x + vel.x * movementSpeed * dt; float newY = pos.y + vel.y * movementSpeed * dt; newX = Math.max(0, newX); newY = Math.max(0, newY); Map map = game.getMap(); boolean isXBlocked = false; boolean isYBlocked = false; bounds.x = (int)newX; if( map.rectCollides(bounds) ) { vehicleBB.setLocation(newX+WeaponConstants.TANK_AABB_WIDTH/2f, vehicleBB.center.y); isBlocked = map.rectCollides(vehicleBB); if(isBlocked) { bounds.x = (int)pos.x; isXBlocked = true; } } if(!isBlocked) { vehicleBB.setLocation(newX+WeaponConstants.TANK_AABB_WIDTH/2f, vehicleBB.center.y); if(collidesAgainstVehicle(bounds)) { bounds.x = (int)pos.x; isBlocked = true; isXBlocked = true; } } bounds.y = (int)newY; if( map.rectCollides(bounds)) { vehicleBB.setLocation(vehicleBB.center.x, newY+WeaponConstants.TANK_AABB_HEIGHT/2f); isBlocked = map.rectCollides(vehicleBB); if(isBlocked) { bounds.y = (int)pos.y; isYBlocked = true; } } if(!isBlocked) { vehicleBB.setLocation(vehicleBB.center.x, newY+WeaponConstants.TANK_AABB_HEIGHT/2f); if(collidesAgainstVehicle(bounds)) { bounds.y = (int)pos.y; isBlocked = true; isYBlocked = true; } } /* some things want to stop dead it their tracks * if a component is blocked */ if(isBlocked && !continueIfBlock()) { bounds.x = (int)pos.x; bounds.y = (int)pos.y; isXBlocked = isYBlocked = true; } // pos.x = bounds.x; // pos.y = bounds.y; pos.x = isXBlocked ? pos.x : newX; pos.y = isYBlocked ? pos.y : newY; vel.zeroOut(); // this.walkingTime = WALK_TIME; } } else { // if(this.walkingTime<=0 && currentState!=State.CROUCHING) { // currentState = State.IDLE; // } // // this.walkingTime -= timeStep.getDeltaTime(); this.currentState = State.IDLE; this.throttleWarmupTime = 0; this.throttleStartTime = 200; } return isBlocked; } /* (non-Javadoc) * @see seventh.game.Entity#continueIfBlock() */ @Override protected boolean continueIfBlock() { return false; } /* (non-Javadoc) * @see seventh.game.Entity#collidesAgainstVehicle(seventh.math.Rectangle) */ @Override protected boolean collidesAgainstVehicle(Rectangle bounds) { boolean collides = false; List<Vehicle> vehicles = game.getVehicles(); for(int i = 0; i < vehicles.size(); i++) { Vehicle vehicle = vehicles.get(i); if(vehicle.isAlive() && this != vehicle) { /* determine if moving to this bounds we would touch * the vehicle */ collides = bounds.intersects(vehicle.getBounds()); /* if we touched, determine if we would be inside * the vehicle, if so, kill us */ if(collides) { // do a more expensive collision detection if(vehicle.isTouching(this)) { return true; } } } } return false; } protected void updateOrientation(TimeStep timeStep) { if(this.vel.x > 0 || this.vel.x < 0) { float deltaMove = 0.55f * (float)timeStep.asFraction(); if(this.vel.x < 0) { deltaMove *= -1; } this.desiredOrientation = this.orientation; this.desiredOrientation += deltaMove; if(this.desiredOrientation<0) { this.desiredOrientation=FastMath.fullCircle-this.desiredOrientation; } else if(this.desiredOrientation>FastMath.fullCircle) { float remainder = this.desiredOrientation-FastMath.fullCircle; this.desiredOrientation=remainder; } float newOrientation = this.desiredOrientation; Map map = game.getMap(); if(map.rectCollides(bounds) || collidesAgainstVehicle(bounds)) { this.vehicleBB.rotateTo(newOrientation); /* If we collide, then revert back to a valid orientation */ if(map.rectCollides(vehicleBB)|| collidesAgainstVehicle(bounds)) { this.orientation = this.lastValidOrientation; return; } } this.lastValidOrientation = this.orientation; this.orientation = newOrientation; this.desiredOrientation = newOrientation; this.facing.set(1, 0); // make right vector Vector2f.Vector2fRotate(this.facing, orientation, this.facing); } } protected void updateTurretOrientation(TimeStep timeStep) { this.turretSmoother.setDesiredOrientation(this.desiredTurretOrientation); this.turretSmoother.setOrientation(this.turretOrientation); this.turretSmoother.update(timeStep); if(this.turretSmoother.moved()) { this.turretRotateSnd.play(game, getId(), SoundType.TANK_TURRET_MOVE, getPos()); } this.turretOrientation = this.turretSmoother.getOrientation(); this.turretFacing.set(this.turretSmoother.getFacing()); } /** * Update the {@link Weapon}s * @param timeStep */ protected void updateWeapons(TimeStep timeStep) { if(this.isFiringPrimary) { this.primaryWeapon.beginFire(); } this.primaryWeapon.update(timeStep); if(this.isFiringSecondary) { this.secondaryWeapon.beginFire(); } this.secondaryWeapon.update(timeStep); } protected void makeMovementSounds(TimeStep timeStep) { if (nextMovementSound <= 0) { // SoundType snd = SoundType.TANK_MOVE1; // if (isRetracting) { // snd = SoundType.TANK_START_MOVE; // } isRetracting = !isRetracting; // game.emitSound(getId(), snd, getCenterPos()); nextMovementSound = 700;// 1500; } else { nextMovementSound -= timeStep.getDeltaTime(); /* if ((currentState == State.RUNNING || currentState == State.SPRINTING)) { nextMovementSound -= timeStep.getDeltaTime(); } else { nextMovementSound = 1; }*/ } this.idleEngineSnd.update(timeStep); this.moveSnd.update(timeStep); this.turretRotateSnd.update(timeStep); this.refDownSnd.update(timeStep); if(currentState==State.IDLE) { this.idleEngineSnd.play(game, getId(), SoundType.TANK_IDLE, getCenterPos()); this.moveSnd.reset(); } else { this.moveSnd.play(game, getId(), SoundType.TANK_MOVE, getCenterPos()); this.idleEngineSnd.reset(); } } /* * (non-Javadoc) * * @see seventh.game.PlayerEntity#damage(seventh.game.Entity, int) */ @Override public void damage(Entity damager, int amount) { if (damager instanceof Explosion) { amount = 1; } else if(damager instanceof Rocket) { //amount /= 2; } else if (damager instanceof Bullet) { amount = 0; } else { amount /= 10; } armor -= amount; if(armor < 0) { super.damage(damager, amount); } else { if(damager instanceof Bullet) { Bullet bullet = (Bullet) damager; bullet.kill(this); game.emitSound(bullet.getId(), SoundType.IMPACT_METAL, bullet.getCenterPos()); } } } /** * Set this tank to destroyed */ public void disable() { this.currentState = State.DESTROYED; } /* (non-Javadoc) * @see seventh.game.Entity#kill(seventh.game.Entity) */ @Override public void kill(Entity killer) { this.killer = killer; this.isDying = true; this.explosionTimer.start(); this.blowupTimer.start(); if(hasOperator()) { getOperator().kill(killer); } } public void rotateAround(Vector2f pos, float radians) { vehicleBB.center.x = pos.x + vehicleBB.width/2; vehicleBB.center.y = pos.y + vehicleBB.height/2; vehicleBB.rotateAround(pos, radians); center.set(vehicleBB.center); this.pos.x = center.x - aabbWidth/2; this.pos.y = center.y - aabbHeight/2; bounds.centerAround(center); this.orientation = radians; this.desiredOrientation = radians; } public void setOrientationNow(float desiredOrientation) { final float fullCircle = FastMath.fullCircle; if(desiredOrientation < 0) { desiredOrientation += fullCircle; } this.orientation = desiredOrientation; this.desiredOrientation = desiredOrientation; syncOOB(this.orientation, pos); } public void setTurretOrientationNow(float desiredOrientation) { final float fullCircle = FastMath.fullCircle; if(desiredOrientation < 0) { desiredOrientation += fullCircle; } this.turretOrientation = desiredOrientation; this.desiredTurretOrientation = desiredOrientation; } /* * (non-Javadoc) * * @see seventh.game.PlayerEntity#setOrientation(float) */ @Override public void setOrientation(float orientation) { final float fullCircle = FastMath.fullCircle; if(desiredOrientation < 0) { desiredOrientation += fullCircle; } this.desiredOrientation = orientation; } /* (non-Javadoc) * @see seventh.game.Controllable#handleUserCommand(seventh.game.UserCommand) */ @Override public void handleUserCommand(int keys, float orientation) { if( Keys.FIRE.isDown(keys) ) { isFiringPrimary = true; } else if(Keys.FIRE.isDown(previousKeys)) { endPrimaryFire(); isFiringPrimary = false; } if(Keys.THROW_GRENADE.isDown(keys)) { isFiringSecondary = true; } else if(Keys.THROW_GRENADE.isDown(previousKeys)) { endSecondaryFire(); isFiringSecondary = false; } /* ============================================ * Handles the movement of the tank * ============================================ */ if(Keys.LEFT.isDown(keys)) { maneuverLeft(); } else if(Keys.RIGHT.isDown(keys)) { maneuverRight(); } else { stopManeuvering(); } if(Keys.MELEE_ATTACK.isDown(keys) || Keys.UP.isDown(keys)) { forwardThrottle(); } else if(Keys.DOWN.isDown(keys)) { backwardThrottle(); } else { stopThrottle(); } if(previousOrientation != orientation) { setTurretOrientation(orientation); } this.previousKeys = keys; this.previousOrientation = orientation; } /* (non-Javadoc) * @see seventh.game.Entity#calculateLineOfSight() */ @Override public List<Tile> calculateLineOfSight(List<Tile> tiles) { Map map = game.getMap(); Geom.calculateLineOfSight(tiles, getCenterPos(), getTurretFacing(), WeaponConstants.TANK_DEFAULT_LINE_OF_SIGHT, map, getHeightMask(), cache); return tiles; } /** * Begins the primary fire * @return */ public boolean beginPrimaryFire() { return this.primaryWeapon.beginFire(); } /** * Ends the primary fire * @return */ public boolean endPrimaryFire() { return this.primaryWeapon.endFire(); } /** * Begins firing the secondary fire * @return */ public boolean beginSecondaryFire() { return this.secondaryWeapon.beginFire(); } /** * Ends the secondary fire * @return */ public boolean endSecondaryFire() { return this.secondaryWeapon.endFire(); } /** * Adds throttle */ public void forwardThrottle() { this.throttle = 1; } /** * Reverse throttle */ public void backwardThrottle() { this.throttle = -1; } /** * Stops the throttle */ public void stopThrottle() { this.throttle = 0; } /** * Maneuvers the tracks to the left */ public void maneuverLeft() { this.vel.x = -1; if(game.getRandom().nextInt(5)==4) this.turretRotateSnd.play(game, getId(), SoundType.TANK_SHIFT, getCenterPos()); //this.refDownSnd.play(game, getId(), SoundType.TANK_REV_UP, getCenterPos()); } /** * Maneuvers the tracks to the right */ public void maneuverRight() { this.vel.x = 1; if(game.getRandom().nextInt(5)==4) this.turretRotateSnd.play(game, getId(), SoundType.TANK_SHIFT, getCenterPos()); //this.refDownSnd.play(game, getId(), SoundType.TANK_REV_UP, getCenterPos()); } /** * Stops maneuvering the tracks */ public void stopManeuvering() { this.vel.x = 0; } @Override protected void beginOperating() { game.emitSound(getId(), SoundType.TANK_ON, getCenterPos()); } @Override protected void endOperating() { game.emitSound(getId(), SoundType.TANK_OFF, getCenterPos()); } /** * Sets the turret to the desired orientation. * @param desiredOrientation the desired orientation in Radians */ public void setTurretOrientation(float desiredOrientation) { final float fullCircle = FastMath.fullCircle; if(desiredOrientation < 0) { desiredOrientation += fullCircle; } this.desiredTurretOrientation = desiredOrientation; } /** * @return the turretOrientation */ public float getTurretOrientation() { return turretOrientation; } /** * @return the turretFacing */ public Vector2f getTurretFacing() { return turretFacing; } /* (non-Javadoc) * @see seventh.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { super.setNetEntity(netTank); netTank.state = getCurrentState().netValue(); netTank.operatorId = hasOperator() ? this.getOperator().getId() : SeventhConstants.INVALID_PLAYER_ID; netTank.turretOrientation = (short)Math.toDegrees(turretOrientation); netTank.primaryWeaponState = primaryWeapon.getState().netValue(); netTank.secondaryWeaponState = secondaryWeapon.getState().netValue(); return netTank; } }
29,652
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
AbstractGameTypeScript.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/AbstractGameTypeScript.java
/* * see license.txt */ package seventh.game.game_types; import java.util.ArrayList; import java.util.List; import leola.vm.Leola; import leola.vm.types.LeoArray; import leola.vm.types.LeoObject; import seventh.math.Vector2f; import seventh.shared.Cons; import seventh.shared.Scripting; /** * Loads an game type script file * * @author Tony * */ public abstract class AbstractGameTypeScript { private Leola runtime; /** * */ public AbstractGameTypeScript(Leola runtime) { this.runtime = runtime; loadCore(); } /** * @return the runtime */ protected Leola getRuntime() { return runtime; } protected void loadCore() { Scripting.loadScript(runtime, "./assets/maps/core.leola"); } /** * Parses the spawn points for a team * @param config * @param teamSpawnPoints * @return a list of spawn points */ protected List<Vector2f> loadSpawnPoint(LeoObject config, String teamSpawnPoints) { List<Vector2f> spawnPoints = new ArrayList<Vector2f>(); LeoObject scriptSpawns = config.getObject(teamSpawnPoints); if(LeoObject.isTrue(scriptSpawns)) { if(!scriptSpawns.isArray()) { Cons.println(teamSpawnPoints + " must be an array"); } else { LeoArray a = scriptSpawns.as(); for(int i = 0; i < a.size(); i++) { Vector2f v = (Vector2f)a.get(i).getValue(); spawnPoints.add(v); } } } return spawnPoints; } /** * @param mapFile * @param maxScore * @param matchTime * @return * @throws Exception */ public abstract GameType loadGameType(String mapFile, int maxScore, long matchTime) throws Exception; }
1,889
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
GameType.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/GameType.java
/* * see license.txt */ package seventh.game.game_types; import java.util.List; import leola.vm.Leola; import seventh.game.Game; import seventh.game.Player; import seventh.game.PlayerClass; import seventh.game.Players; import seventh.game.Team; import seventh.game.net.NetGamePartialStats; import seventh.game.net.NetGameStats; import seventh.game.net.NetGameTypeInfo; import seventh.game.net.NetTeamStat; import seventh.math.Vector2f; import seventh.shared.Debugable; import seventh.shared.EventDispatcher; import seventh.shared.TimeStep; /** * @author Tony * */ public interface GameType extends Debugable { public static enum Type { TDM("Team Death Match"), OBJ("Objective Based Match"), CTF("Capture The Flag"), CMD("Commander"), SVR("Survivor") ; private String displayName; /** * */ private Type(String displayName) { this.displayName = displayName; } /** * @return the displayName */ public String getDisplayName() { return displayName; } /** * @return the network value */ public byte netValue() { return (byte)ordinal(); } public static int numOfBits() { return 4; } private static final Type[] values = values(); public static Type fromNet(byte value) { if(value<0 || value >= values.length) { return TDM; } return values[value]; } public static Type toType(String gameType) { Type result = TDM; if(gameType != null) { if("obj".equalsIgnoreCase(gameType.trim())) { result = OBJ; } else if ("ctf".equalsIgnoreCase(gameType.trim())) { result = CTF; } else if ("cmd".equalsIgnoreCase(gameType.trim())) { result = CMD; } else if("svr".equalsIgnoreCase(gameType.trim())) { result = SVR; } } return result; } } public static enum GameState { INTERMISSION, IN_PROGRESS, WINNER, TIE, ; public byte netValue() { return (byte)ordinal(); } } public void start(Game game); public GameState update(Game game, TimeStep timeStep); public void registerListeners(Game game, EventDispatcher dispatcher); public Team getAlliedTeam(); public Team getAxisTeam(); public void playerJoin(Player player); public void playerLeft(Player player); public boolean switchPlayerClass(Player player, PlayerClass playerClass); public Leola getRuntime(); public Team getAttacker(); public Team getDefender(); public Team getTeam(Player player); public Team getEnemyTeam(Player player); public boolean switchTeam(Player player, byte teamId); public long getMatchTime(); public int getMaxScore(); public long getRemainingTime(); public boolean isInProgress(); public Type getType(); public Player getNextPlayerToSpectate(Players players, Player spectator); public Player getPrevPlayerToSpectate(Players players, Player spectator); public NetGameTypeInfo getNetGameTypeInfo(); public NetGamePartialStats getNetGamePartialStats(); public NetGameStats getNetGameStats(); public NetTeamStat getAlliedNetTeamStats(); public NetTeamStat getAxisNetTeamStats(); public List<Vector2f> getAlliedSpawnPoints(); public List<Vector2f> getAxisSpawnPoints(); }
3,917
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
AbstractTeamGameType.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/AbstractTeamGameType.java
/* * The Seventh * see license.txt */ package seventh.game.game_types; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import leola.vm.Leola; import leola.vm.types.LeoObject; import seventh.game.Game; import seventh.game.Player; import seventh.game.PlayerClass; import seventh.game.Players; import seventh.game.Team; import seventh.game.entities.Entity; import seventh.game.entities.PlayerEntity; import seventh.game.events.GameEndEvent; import seventh.game.events.PlayerKilledEvent; import seventh.game.events.PlayerKilledListener; import seventh.game.events.RoundEndedEvent; import seventh.game.events.RoundEndedListener; import seventh.game.events.RoundStartedEvent; import seventh.game.events.RoundStartedListener; import seventh.game.net.NetGamePartialStats; import seventh.game.net.NetGameStats; import seventh.game.net.NetGameTypeInfo; import seventh.game.net.NetPlayerPartialStat; import seventh.game.net.NetPlayerStat; import seventh.game.net.NetTeamStat; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.Cons; import seventh.shared.EventDispatcher; import seventh.shared.TimeStep; import seventh.shared.Timer; /** * @author Tony * */ public abstract class AbstractTeamGameType implements GameType { /** * Time it take to warm up to when the game is ready to * start being played */ public static final int WARMUP_TIME = 5_000; /** * The team indexes */ protected static final int AXIS=0, ALLIED=1; private final int maxScore; private final long matchTime; private long timeRemaining; private Team[] teams; private GameState gameState; private Type type; private List<Team> highScoreTeams; private Random random; /** * A Huge hack to work around the frame * delay for counting deaths for players (queue'd up eventdispatcher event) * and the fact that the game has ended. We want to * delay the game ending by one frame. */ private int numberOfFramesForGameEnd; private boolean gameEnded; private EventDispatcher dispatcher; protected Leola runtime; // avoid GC, so we create data members :\ private List<Vector2f> alliedSpawnPoints, axisSpawnPoints; private Rectangle spawnBounds; private Timer warmupTimer; private Game game; /** * @param type * @param runtime * @param maxScore * @param matchTime */ public AbstractTeamGameType(GameType.Type type, Leola runtime, List<Vector2f> alliedSpawnPoints, List<Vector2f> axisSpawnPoints, int maxScore, long matchTime) { this.type = type; this.runtime = runtime; this.alliedSpawnPoints = alliedSpawnPoints; this.axisSpawnPoints = axisSpawnPoints; this.matchTime = matchTime; this.maxScore = maxScore; this.timeRemaining = this.matchTime; this.teams = new Team[2]; this.teams[AXIS] = Team.newAxisTeam(); this.teams[ALLIED] = Team.newAlliedTeam(); this.highScoreTeams = new ArrayList<Team>(2); this.gameState = GameState.INTERMISSION; this.random = new Random(); this.spawnBounds = new Rectangle(300, 300); this.warmupTimer = new Timer(false, WARMUP_TIME); } /** * For sub classes to override with their own {@link NetGameTypeInfo} * if necessary * * @return the {@link NetGameTypeInfo} */ protected NetGameTypeInfo createNetGameTypeInfo() { return new NetGameTypeInfo(); } protected NetGameStats createNetGameStats() { return new NetGameStats(); } protected NetGamePartialStats createNetGamePartialStats() { return new NetGamePartialStats(); } /* (non-Javadoc) * @see seventh.game.type.GameType#registerListeners(seventh.game.GameInfo, leola.frontend.listener.EventDispatcher) */ @Override public void registerListeners(final Game game, EventDispatcher dispatcher) { this.game = game; this.dispatcher = dispatcher; dispatcher.addEventListener(RoundEndedEvent.class, new RoundEndedListener() { @Override public void onRoundEnded(RoundEndedEvent event) { executeCallbackScript("onRoundEnded", game); executeCallbackScript("coreDestroy", game); } }); dispatcher.addEventListener(RoundStartedEvent.class, new RoundStartedListener() { @Override public void onRoundStarted(RoundStartedEvent event) { executeCallbackScript("onRoundStarted", game); executeCallbackScript("coreInit", game); } }); dispatcher.addEventListener(PlayerKilledEvent.class, new PlayerKilledListener() { @Override public void onPlayerKilled(PlayerKilledEvent event) { onPlayerDeath(event); } }); doRegisterListeners(game, dispatcher); } /** * Used by the inherited game types to implement. * * @param game * @param dispatcher */ protected abstract void doRegisterListeners(final Game game, EventDispatcher dispatcher); /** * Defaults to dropping any held weapons/items * * @param event */ protected void onPlayerDeath(PlayerKilledEvent event) { final PlayerEntity ent = event.getPlayer().getEntity(); final Entity killer = event.getKilledBy(); ent.dropFlag(); /* suicides don't leave weapons */ if(killer != ent) { if(ent.isYielding(seventh.game.entities.Entity.Type.FLAME_THROWER)) { game.addGameTimer(new Timer(false, 20) { public void onFinish(Timer timer) { game.newBigFire(ent.getCenterPos(), ent, 1); game.newBigExplosion(ent.getCenterPos(), ent, 30, 10, 1); } }); } else { ent.dropItem(false); } } } /** * Executes the callback function * * @param functionName * @param game */ private void executeCallbackScript(String functionName, Game game) { LeoObject function = runtime.get(functionName); if(LeoObject.isTrue(function)) { LeoObject result = function.call(game.asScriptObject()); if(result.isError()) { Cons.println("*** ERROR: Calling '" + functionName + "' - " + result.toString()); } } } /* (non-Javadoc) * @see seventh.game.type.GameType#getType() */ @Override public Type getType() { return type; } @Override public Leola getRuntime() { return this.runtime; } /* (non-Javadoc) * @see seventh.game.type.GameType#isInProgress() */ @Override public boolean isInProgress() { return GameState.IN_PROGRESS == getGameState() || (this.numberOfFramesForGameEnd < 2); } public Team getAlliedTeam() { return this.teams[ALLIED]; } public Team getAxisTeam() { return this.teams[AXIS]; } /* (non-Javadoc) * @see seventh.game.type.GameType#getAlliedSpawnPoints() */ @Override public List<Vector2f> getAlliedSpawnPoints() { return this.alliedSpawnPoints; } /* (non-Javadoc) * @see seventh.game.type.GameType#getAxisSpawnPoints() */ @Override public List<Vector2f> getAxisSpawnPoints() { return this.axisSpawnPoints; } protected Team getRandomTeam() { if(random.nextBoolean()) { return getAxisTeam(); } return getAlliedTeam(); } /** * @return the random */ protected Random getRandom() { return random; } /* (non-Javadoc) * @see seventh.game.type.GameType#getNextPlayerToSpectate(seventh.game.Player) */ @Override public Player getNextPlayerToSpectate(Players players, Player spectator) { if(spectator.isPureSpectator()||spectator.isCommander()) { return players.getNextAlivePlayerFrom(spectator.getSpectating()); } Player player = spectator.getSpectating(); return player!=null ? spectator.getTeam().getNextAlivePlayerFrom(player) : spectator.getTeam().getAlivePlayer(); } /* (non-Javadoc) * @see seventh.game.type.GameType#getPrevPlayerToSpectate(seventh.game.Players, seventh.game.Player) */ @Override public Player getPrevPlayerToSpectate(Players players, Player spectator) { if(spectator.isPureSpectator()||spectator.isCommander()) { return players.getPrevAlivePlayerFrom(spectator.getSpectating()); } Player player = spectator.getSpectating(); return player!=null ? spectator.getTeam().getPrevAlivePlayerFrom(player) : spectator.getTeam().getAlivePlayer(); } /** * @param gameState the gameState to set */ protected void setGameState(GameState gameState) { this.gameState = gameState; } /** * @return the gameState */ protected GameState getGameState() { return gameState; } /** * @return the dispatcher */ protected EventDispatcher getDispatcher() { return dispatcher; } /* (non-Javadoc) * @see seventh.game.type.GameType#getMatchTime() */ @Override public long getMatchTime() { return this.matchTime; } /* (non-Javadoc) * @see seventh.game.type.GameType#getMaxScore() */ @Override public int getMaxScore() { return this.maxScore; } /* (non-Javadoc) * @see seventh.game.type.GameType#getRemainingTime() */ @Override public long getRemainingTime() { return this.timeRemaining; } /** * Resets the remaining time to the original match time */ protected void resetRemainingTime() { this.timeRemaining = this.matchTime; } /* (non-Javadoc) * @see palisma.game.type.GameType#playerJoin(palisma.game.Player) */ @Override public void playerJoin(Player player) { // check and see if they are already on a team byte teamId = player.getTeamId(); if(teamId != Team.SPECTATOR_TEAM_ID) { switch(teamId) { case Team.ALLIED_TEAM_ID: { if(!joinTeam(teams[ALLIED], player)) { if(!joinTeam(teams[AXIS], player)) { // TODO Player couldn't join any team?? } } break; } case Team.AXIS_TEAM_ID: { if(!joinTeam(teams[AXIS], player)) { if(!joinTeam(teams[ALLIED], player)) { // TODO Player couldn't join any team?? } } break; } default: { throw new IllegalArgumentException("Illegal Team value: " + teamId); } } } // if not, then try to balance out the teams else { Team teamWithLeast = null; if(teams[ALLIED].getTeamSize() > teams[AXIS].getTeamSize()) { teamWithLeast = teams[AXIS]; } else if(teams[ALLIED].getTeamSize() < teams[AXIS].getTeamSize()) { teamWithLeast = teams[ALLIED]; } if(teamWithLeast==null) { teamWithLeast = teams[this.random.nextInt(2)]; } if(joinTeam(teamWithLeast, player)) { // TODO ?? } } } /* (non-Javadoc) * @see palisma.game.type.GameType#playerLeft(palisma.game.Player) */ @Override public void playerLeft(Player player) { for(int i = 0; i < teams.length; i++) { Team team = teams[i]; team.removePlayer(player); } } /* * (non-Javadoc) * @see palisma.game.type.GameType#update(leola.live.TimeStep) */ @Override public GameState update(Game game, TimeStep timeStep) { this.warmupTimer.update(timeStep); if(!this.warmupTimer.isExpired()) { return GameState.INTERMISSION; } this.timeRemaining -= timeStep.getDeltaTime(); /** * A Huge hack to work around the frame * delay for counting deaths for players (queue'd up eventdispatcher event) * and the fact that the game has ended. We want to * delay the game ending by one frame. */ if(getGameState() != GameState.IN_PROGRESS) { this.numberOfFramesForGameEnd++; } else { this.numberOfFramesForGameEnd = 0; } GameState gameState = doUpdate(game, timeStep); checkEndGame(game, gameState); return gameState; } /** * Determine if the game has ended, and if it has, distribute a message * * @param game * @param gameState */ private void checkEndGame(Game game, GameState gameState) { if(gameState!=GameState.IN_PROGRESS) { if(!gameEnded) { this.dispatcher.queueEvent(new GameEndEvent(this, game.getNetGameStats())); this.gameEnded = true; } } } /** * Spawns the player at a random spawn point for their team. * * @param player * @param game */ protected void spawnPlayer(Player player, Game game) { List<Vector2f> spawnPoints = (player.getTeamId() == Team.ALLIED_TEAM_ID) ? getAlliedSpawnPoints() : getAxisSpawnPoints(); Vector2f spawnPosition = findSpawnPosition(player, game, spawnPoints); game.spawnPlayerEntity(player.getId(), spawnPosition); } private Vector2f findSpawnPosition(Player player, Game game, List<Vector2f> spawnPoints) { Vector2f spawnPosition = new Vector2f(-1,-1); int size = spawnPoints.size(); if(size > 0) { int startingPosition = random.nextInt(spawnPoints.size()); for(int i = 0; i < size; i++) { spawnPosition.set(spawnPoints.get(startingPosition)); if(isSafeSpawnPosition(player, spawnPosition, game)) { return spawnPosition; } startingPosition = (startingPosition + 1) % size; } } return spawnPosition; } /** * Determines if the supplied spawn point is safe enough to spawn to. * * @param player * @param spawnPosition * @param game * @return true if it's safe */ private boolean isSafeSpawnPosition(Player player, Vector2f spawnPosition, Game game) { Team enemy = getEnemyTeam(player); spawnBounds.centerAround(spawnPosition); if(enemy!=null) { List<Player> players = enemy.getPlayers(); for(int i = 0; i < players.size(); i++) { Player p = players.get(i); if(p.isAlive()) { if(spawnBounds.contains(p.getEntity().getBounds())) { return false; } } } } return true; } /** * Check and see if it's time to respawn players * * @param timeStep * @param game */ protected void checkRespawns(TimeStep timeStep, Game game) { if (GameState.IN_PROGRESS == getGameState()) { Player[] players = game.getPlayers().getPlayers(); for (int i = 0; i < players.length; i++) { Player player = players[i]; if (player != null) { if (player.canSpawn()) { player.updateSpawnTime(timeStep); if (player.readyToSpawn()) { spawnPlayer(player, game); } } } } } } /** * Checks to see if any players should be spectating, because they are dead * * @param timeStep * @param game */ protected void checkSpectating(TimeStep timeStep, Game game) { Player[] players = game.getPlayers().getPlayers(); for (int i = 0; i < players.length; i++) { Player player = players[i]; if (player != null) { if(player.isCommander()) { continue; } if (!player.isPureSpectator() && !player.isSpectating() && player.isDead()) { player.applyLookAtDeathDelay(); } player.updateLookAtDeathTime(timeStep); if (!player.isPureSpectator() && !player.isSpectating() && player.readyToLookAwayFromDeath()) { Player spectateMe = getNextPlayerToSpectate(game.getPlayers(), player); player.setSpectating(spectateMe); } } } } /** * Do the actual logic for handling this game type * * @param game * @param timeStep * @return the resulting {@link GameState} */ protected abstract GameState doUpdate(Game game, TimeStep timeStep); /** * @return the winning teams (if multiple, it means a tie) */ public List<Team> getWinners() { return new ArrayList<Team>(getTeamsWithHighScore()); } /** * @return the team(s) with the highest score */ public List<Team> getTeamsWithHighScore() { this.highScoreTeams.clear(); int axisScore = this.teams[AXIS].getScore(); int alliedScore = this.teams[ALLIED].getScore(); if(axisScore > alliedScore) { this.highScoreTeams.add(teams[AXIS]); } else if (alliedScore > axisScore) { this.highScoreTeams.add(teams[ALLIED]); } else { this.highScoreTeams.add(this.teams[AXIS]); this.highScoreTeams.add(this.teams[ALLIED]); } return this.highScoreTeams; } @Override public Team getAttacker() { return getAlliedTeam().isAttacker() ? getAlliedTeam() : getAxisTeam(); } @Override public Team getDefender() { return getAlliedTeam().isDefender() ? getAlliedTeam() : getAxisTeam(); } /* (non-Javadoc) * @see palisma.game.type.GameType#getTeam(palisma.game.Player) */ @Override public Team getTeam(Player player) { for(int i = 0; i < this.teams.length; i++) { Team team = this.teams[i]; if(team.onTeam(player)) { return team; } } return null; } @Override public Team getEnemyTeam(Player player) { Team a = player.getTeam(); if(a==null) { return null; } if(a.getId()==this.teams[0].getId()) { return this.teams[1]; } return this.teams[0]; } protected boolean joinTeam(Team team, Player player) { Team otherTeam = team.getId() == Team.ALLIED_TEAM_ID ? getAxisTeam() : getAlliedTeam(); leaveTeam(otherTeam, player); team.addPlayer(player); return true; } protected boolean leaveTeam(Team team, Player player) { team.removePlayer(player); return true; } /* (non-Javadoc) * @see seventh.game.type.GameType#switchPlayerClass(seventh.game.Player, seventh.game.PlayerClass) */ @Override public boolean switchPlayerClass(Player player, PlayerClass playerClass) { if(playerClass == PlayerClass.Default) { player.setPlayerClass(playerClass); return true; } return false; } /* (non-Javadoc) * @see palisma.game.type.GameType#switchTeam(palisma.game.Player, byte) */ @Override public boolean switchTeam(Player player, byte teamId) { boolean assigned = false; Team currentTeam = getTeam(player); if(currentTeam != null && currentTeam.getId() != teamId) { if(leaveTeam(currentTeam, player)) { assigned = true; } } for(int i = 0; i < this.teams.length; i++) { Team team = this.teams[i]; if(team.getId() == teamId) { if(joinTeam(team, player)) { assigned = true; } } } return assigned; } /* (non-Javadoc) * @see palisma.game.type.GameType#getNetGameTypeInfo() */ @Override public NetGameTypeInfo getNetGameTypeInfo() { NetGameTypeInfo gameTypeInfo = createNetGameTypeInfo(); gameTypeInfo.type = type.netValue(); gameTypeInfo.maxScore = maxScore; gameTypeInfo.maxTime = matchTime; gameTypeInfo.alliedTeam = this.teams[ALLIED].getNetTeam(); gameTypeInfo.axisTeam = this.teams[AXIS].getNetTeam(); return gameTypeInfo; } /** * @return just returns the networked game statistics */ @Override public NetGameStats getNetGameStats() { NetGameStats gameStats = createNetGameStats(); gameStats.playerStats = new NetPlayerStat[game.getPlayers().getNumberOfPlayers()]; Player[] players = game.getPlayers().getPlayers(); int j = 0; for(int i = 0; i < players.length; i++) { Player player = players[i]; if(player != null) { gameStats.playerStats[j++] = player.getNetPlayerStat(); } } gameStats.alliedTeamStats = getAlliedNetTeamStats(); gameStats.axisTeamStats = getAxisNetTeamStats(); return gameStats; } /** * @return returns the networked game (partial) statistics */ @Override public NetGamePartialStats getNetGamePartialStats() { NetGamePartialStats gamePartialStats = createNetGamePartialStats(); gamePartialStats.playerStats = new NetPlayerPartialStat[game.getPlayers().getNumberOfPlayers()]; Player[] players = game.getPlayers().getPlayers(); int j = 0; for(int i = 0; i < players.length; i++) { Player player = players[i]; if(player != null) { gamePartialStats.playerStats[j++] = player.getNetPlayerPartialStat(); } } gamePartialStats.alliedTeamStats = getAlliedNetTeamStats(); gamePartialStats.axisTeamStats = getAxisNetTeamStats(); return gamePartialStats; } /* (non-Javadoc) * @see seventh.game.type.GameType#getAlliedNetTeamStats() */ @Override public NetTeamStat getAlliedNetTeamStats() { return this.teams[ALLIED].getNetTeamStats(); } /* (non-Javadoc) * @see seventh.game.type.GameType#getAxisNetTeamStats() */ @Override public NetTeamStat getAxisNetTeamStats() { return this.teams[AXIS].getNetTeamStats(); } /* (non-Javadoc) * @see seventh.shared.Debugable#getDebugInformation() */ @Override public DebugInformation getDebugInformation() { DebugInformation me = new DebugInformation(); me.add("game_type", getType().name()) .add("match_time", new Date(getMatchTime()).toString()) .add("max_score", getMaxScore()) .add("remaining_time", getRemainingTime() / 1000) .add("allied_spawn_points", getAlliedSpawnPoints()) .add("axis_spawn_points", getAxisSpawnPoints()) .add("teams", new Team[] { getAlliedTeam(), getAxisTeam() }); return me; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return getDebugInformation().toString(); } }
25,142
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
CaptureTheFlagScript.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/ctf/CaptureTheFlagScript.java
/* * see license.txt */ package seventh.game.game_types.ctf; import java.io.File; import java.util.ArrayList; import java.util.List; import leola.vm.Leola; import leola.vm.types.LeoObject; import seventh.game.game_types.AbstractGameTypeScript; import seventh.game.game_types.GameType; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.Cons; /** * Loads an Capture The Flag rules script * * @author Tony * */ public class CaptureTheFlagScript extends AbstractGameTypeScript { /** * */ public CaptureTheFlagScript(Leola runtime) { super(runtime); } /** * @param mapFile * @param maxScore * @param matchTime * @return * @throws Exception */ public GameType loadGameType(String mapFile, int maxScore, long matchTime) throws Exception { List<Vector2f> alliedSpawnPoints = new ArrayList<>(); List<Vector2f> axisSpawnPoints = new ArrayList<>(); Vector2f alliedFlagSpawn = new Vector2f(); Vector2f axisFlagSpawn = new Vector2f(); Rectangle alliedHomeBase = new Rectangle(); Rectangle axisHomeBase = new Rectangle(); long spawnDelay = 10_000; File scriptFile = new File(mapFile + ".ctf.leola"); if(!scriptFile.exists()) { Cons.println("*** ERROR -> No associated script file for 'Capture The Flag' game type. Looking for: " + scriptFile.getName()); } else { LeoObject config = getRuntime().eval(scriptFile); if(LeoObject.isTrue(config)) { alliedSpawnPoints = loadSpawnPoint(config, "alliedSpawnPoints"); axisSpawnPoints = loadSpawnPoint(config, "axisSpawnPoints"); alliedFlagSpawn = (Vector2f)config.getObject("alliedFlagSpawn").getValue(); axisFlagSpawn = (Vector2f)config.getObject("axisFlagSpawn").getValue(); alliedHomeBase = (Rectangle)config.getObject("alliedHomeBase").getValue(); axisHomeBase = (Rectangle)config.getObject("axisHomeBase").getValue(); if(config.hasObject("spawnDelay")) { spawnDelay = config.getObject("spawnDelay").asLong(); } } } GameType gameType = new CaptureTheFlagGameType(getRuntime(), alliedSpawnPoints, axisSpawnPoints, maxScore, matchTime, alliedFlagSpawn, axisFlagSpawn, alliedHomeBase, axisHomeBase, spawnDelay); return gameType; } }
2,645
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
CaptureTheFlagGameType.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/ctf/CaptureTheFlagGameType.java
/* * see license.txt */ package seventh.game.game_types.ctf; import java.util.List; import leola.vm.Leola; import seventh.game.Game; import seventh.game.PlayerInfo; import seventh.game.Team; import seventh.game.entities.Entity; import seventh.game.entities.Entity.OnTouchListener; import seventh.game.entities.Flag; import seventh.game.entities.PlayerEntity; 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.PlayerKilledEvent; import seventh.game.events.PlayerKilledListener; import seventh.game.events.RoundEndedEvent; import seventh.game.events.RoundStartedEvent; import seventh.game.game_types.AbstractTeamGameType; import seventh.game.net.NetCtfGameTypeInfo; import seventh.game.net.NetGameTypeInfo; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.EventDispatcher; import seventh.shared.EventMethod; import seventh.shared.TimeStep; /** * Capture the Flag game type. * * @author Tony * */ public class CaptureTheFlagGameType extends AbstractTeamGameType { class FlagOnTouchListener implements OnTouchListener { Flag flag; FlagOnTouchListener(Flag flag) { this.flag = flag; } @Override public void onTouch(Entity me, Entity other) { if(!flag.isBeingCarried()) { if(other.getType()==seventh.game.entities.Entity.Type.PLAYER) { PlayerEntity otherPlayer = (PlayerEntity)other; if(otherPlayer.isAlive()) { /* * Now, based on which team the player is on, * we determine what to do with the flag. * * If the player is on an opposing team, they * force the flag back to their home base */ int teamId = otherPlayer.getTeam().getId(); if( (teamId==Team.ALLIED_TEAM_ID && flag.getType()==seventh.game.entities.Entity.Type.ALLIED_FLAG) || (teamId==Team.AXIS_TEAM_ID && flag.getType()==seventh.game.entities.Entity.Type.AXIS_FLAG) ) { flag.carriedBy(otherPlayer); getDispatcher().queueEvent(new FlagStolenEvent(this, flag, otherPlayer.getId())); } else { if(!flag.isAtHomeBase()) { flag.returnHome(); getDispatcher().queueEvent(new FlagReturnedEvent(this, flag, otherPlayer.getId())); } } } } } } } private Flag axisFlag, alliedFlag; private Vector2f alliedFlagSpawn, axisFlagSpawn; private Rectangle alliedHomeBase, axisHomeBase; private long spawnDelay; private NetCtfGameTypeInfo gameTypeInfo; /** * @param runtime * @param maxScore * @param matchTime */ public CaptureTheFlagGameType(Leola runtime, List<Vector2f> alliedSpawnPoints, List<Vector2f> axisSpawnPoints, int maxScore, long matchTime, Vector2f alliedFlagSpawn, Vector2f axisFlagSpawn, Rectangle alliedHomeBase, Rectangle axisHomeBase, long spawnDelay) { super(Type.CTF, runtime, alliedSpawnPoints, axisSpawnPoints, maxScore, matchTime); this.alliedFlagSpawn = alliedFlagSpawn; this.axisFlagSpawn = axisFlagSpawn; this.alliedHomeBase = alliedHomeBase; this.axisHomeBase = axisHomeBase; this.spawnDelay = spawnDelay; this.gameTypeInfo.axisHomeBase = this.axisHomeBase; this.gameTypeInfo.alliedHomeBase = this.alliedHomeBase; this.gameTypeInfo.axisFlagSpawn = this.axisFlagSpawn; this.gameTypeInfo.alliedFlagSpawn = this.alliedFlagSpawn; } @Override protected NetGameTypeInfo createNetGameTypeInfo() { this.gameTypeInfo = new NetCtfGameTypeInfo(); return this.gameTypeInfo; } /** * @return the alliedHomeBase */ public Rectangle getAlliedHomeBase() { return alliedHomeBase; } /** * @return the axisHomeBase */ public Rectangle getAxisHomeBase() { return axisHomeBase; } /** * @return the alliedFlag */ public Flag getAlliedFlag() { return alliedFlag; } /** * @return the axisFlag */ public Flag getAxisFlag() { return axisFlag; } /* (non-Javadoc) * @see palisma.game.type.GameType#registerListeners(leola.frontend.listener.EventDispatcher) */ @Override protected void doRegisterListeners(final Game game, EventDispatcher dispatcher) { this.alliedFlag = game.newAlliedFlag(this.alliedFlagSpawn); this.alliedFlag.onTouch = new FlagOnTouchListener(this.alliedFlag); this.axisFlag = game.newAxisFlag(this.axisFlagSpawn); this.axisFlag.onTouch = new FlagOnTouchListener(this.axisFlag); dispatcher.addEventListener(FlagCapturedEvent.class, new FlagCapturedListener() { @Override @EventMethod public void onFlagCapturedEvent(FlagCapturedEvent event) { if(isInProgress()) { PlayerInfo carrier = game.getPlayerById(event.getPlayerId()); if(carrier !=null) { carrier.getTeam().score(1); } } } }); dispatcher.addEventListener(FlagReturnedEvent.class, new FlagReturnedListener() { @Override @EventMethod public void onFlagReturnedEvent(FlagReturnedEvent event) { } }); dispatcher.addEventListener(PlayerKilledEvent.class, new PlayerKilledListener() { @Override public void onPlayerKilled(PlayerKilledEvent event) { event.getPlayer().applySpawnDelay(spawnDelay); } }); } /* (non-Javadoc) * @see seventh.game.game_types.GameType#start(seventh.game.Game) */ @Override public void start(Game game) { setGameState(GameState.IN_PROGRESS); getDispatcher().queueEvent(new RoundStartedEvent(this)); } /* (non-Javadoc) * @see seventh.game.game_types.GameType#update(leola.live.TimeStep) */ @Override protected GameState doUpdate(Game game, TimeStep timeStep) { if(GameState.IN_PROGRESS == getGameState()) { List<Team> leaders = getTeamsWithHighScore(); if(this.getRemainingTime() <= 0 || (leaders.get(0).getScore() >= getMaxScore()) ) { if(leaders.size() > 1) { setGameState(GameState.TIE); getDispatcher().queueEvent(new RoundEndedEvent(this, null, game.getNetGameStats())); } else { setGameState(GameState.WINNER); getDispatcher().queueEvent(new RoundEndedEvent(this, leaders.get(0), game.getNetGameStats())); } } checkRespawns(timeStep, game); checkSpectating(timeStep, game); } if (GameState.IN_PROGRESS == getGameState()) { /* Check and see if this flag has been * captured */ if(this.axisFlag.isBeingCarried()) { if(this.axisFlag.getBounds().intersects(axisHomeBase)) { getDispatcher().queueEvent(new FlagCapturedEvent(this, this.axisFlag, this.axisFlag.getCarriedBy().getId())); this.axisFlag.returnHome(); } } if(this.alliedFlag.isBeingCarried()) { if(this.alliedFlag.getBounds().intersects(alliedHomeBase)) { getDispatcher().queueEvent(new FlagCapturedEvent(this, this.alliedFlag, this.alliedFlag.getCarriedBy().getId())); this.alliedFlag.returnHome(); } } } return getGameState(); } }
8,999
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
TeamDeathMatchGameType.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/tdm/TeamDeathMatchGameType.java
/* * see license.txt */ package seventh.game.game_types.tdm; import java.util.List; import leola.vm.Leola; import seventh.game.Game; import seventh.game.Player; import seventh.game.PlayerInfo; import seventh.game.Team; import seventh.game.events.PlayerKilledEvent; import seventh.game.events.PlayerKilledListener; import seventh.game.events.RoundEndedEvent; import seventh.game.events.RoundStartedEvent; import seventh.game.game_types.AbstractTeamGameType; import seventh.math.Vector2f; import seventh.shared.EventDispatcher; import seventh.shared.EventMethod; import seventh.shared.TimeStep; /** * @author Tony * */ public class TeamDeathMatchGameType extends AbstractTeamGameType { /** * @param maxKills * @param matchTime */ public TeamDeathMatchGameType(Leola runtime, List<Vector2f> alliedSpawns, List<Vector2f> axisSpawns, int maxKills, long matchTime) { super(Type.TDM, runtime, alliedSpawns, axisSpawns, maxKills, matchTime); } /* (non-Javadoc) * @see palisma.game.type.GameType#registerListeners(leola.frontend.listener.EventDispatcher) */ @Override protected void doRegisterListeners(final Game game, EventDispatcher dispatcher) { dispatcher.addEventListener(PlayerKilledEvent.class, new PlayerKilledListener() { @Override @EventMethod public void onPlayerKilled(PlayerKilledEvent event) { if(isInProgress()) { PlayerInfo killer = game.getPlayerById(Integer.valueOf((int)(event.getKillerId()))); if(killer!=null) { Player killed = event.getPlayer(); if(killed != null) { // killing yourself or a teammate causes // a negative score if(killer.getId() == killed.getId() || killer.getTeam() == killed.getTeam()) { killed.getTeam().score(-1); return; } } killer.getTeam().score(1); } } } }); } /* (non-Javadoc) * @see seventh.game.game_types.GameType#start(seventh.game.Game) */ @Override public void start(Game game) { setGameState(GameState.IN_PROGRESS); getDispatcher().queueEvent(new RoundStartedEvent(this)); } /* * (non-Javadoc) * @see palisma.game.type.GameType#update(leola.live.TimeStep) */ @Override protected GameState doUpdate(Game game, TimeStep timeStep) { if(GameState.IN_PROGRESS == getGameState()) { List<Team> leaders = getTeamsWithHighScore(); boolean isUnlimitedScore = getMaxScore() <= 0; if(this.getRemainingTime() <= 0 || (leaders.get(0).getScore() >= getMaxScore() && !isUnlimitedScore) ) { if(leaders.size() > 1) { setGameState(GameState.TIE); getDispatcher().queueEvent(new RoundEndedEvent(this, null, game.getNetGameStats())); } else { setGameState(GameState.WINNER); getDispatcher().queueEvent(new RoundEndedEvent(this, leaders.get(0), game.getNetGameStats())); } } checkRespawns(timeStep, game); } return getGameState(); } }
3,652
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
TeamDeathMatchScript.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/tdm/TeamDeathMatchScript.java
/* * see license.txt */ package seventh.game.game_types.tdm; import java.io.File; import java.util.ArrayList; import java.util.List; import leola.vm.Leola; import leola.vm.types.LeoObject; import seventh.game.game_types.AbstractGameTypeScript; import seventh.game.game_types.GameType; import seventh.math.Vector2f; import seventh.shared.Cons; /** * Loads an Team Death Match rules script * * @author Tony * */ public class TeamDeathMatchScript extends AbstractGameTypeScript { /** * */ public TeamDeathMatchScript(Leola runtime) { super(runtime); } /** * @param mapFile * @param maxScore * @param matchTime * @return * @throws Exception */ public GameType loadGameType(String mapFile, int maxScore, long matchTime) throws Exception { List<Vector2f> alliedSpawnPoints = new ArrayList<>(); List<Vector2f> axisSpawnPoints = new ArrayList<Vector2f>(); File scriptFile = new File(mapFile + ".tdm.leola"); if(!scriptFile.exists()) { Cons.println("*** ERROR -> No associated script file for team death match game type. Looking for: " + scriptFile.getName()); } else { LeoObject config = getRuntime().eval(scriptFile); if(LeoObject.isTrue(config)) { alliedSpawnPoints = loadSpawnPoint(config, "alliedSpawnPoints"); axisSpawnPoints = loadSpawnPoint(config, "axisSpawnPoints"); } } GameType gameType = new TeamDeathMatchGameType(getRuntime(), alliedSpawnPoints, axisSpawnPoints, maxScore, matchTime); return gameType; } }
1,721
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
CommanderGameType.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/cmd/CommanderGameType.java
/* * see license.txt */ package seventh.game.game_types.cmd; import java.util.List; import leola.vm.Leola; import leola.vm.types.LeoArray; import leola.vm.types.LeoObject; import seventh.game.Game; import seventh.game.Player; import seventh.game.PlayerClass; import seventh.game.Team; import seventh.game.entities.Base; import seventh.game.events.RoundStartedEvent; import seventh.game.game_types.AbstractTeamGameType; import seventh.game.net.NetCommanderGameTypeInfo; import seventh.game.net.NetGameTypeInfo; import seventh.game.net.NetSquad; import seventh.math.Vector2f; import seventh.shared.EventDispatcher; import seventh.shared.TimeStep; /** * Commander Game Type. * * Concept: * * 2 - AIGroup leaders for each team (they don't control any characters, but manage resources and * command FireTeams * * Resources: * Ammo * Tanks * Respawns * Location of Spawns * Material (for building walls, ?) * * @author Tony * */ public class CommanderGameType extends AbstractTeamGameType { private Base alliedBase; private Base axisBase; private Vector2f alliedBasePos, axisBasePos; private Squad alliedSquad, axisSquad; /** * @param type * @param runtime * @param alliedSpawnPoints * @param axisSpawnPoints * @param maxScore * @param matchTime */ public CommanderGameType(Leola runtime, List<Vector2f> alliedSpawnPoints, List<Vector2f> axisSpawnPoints, int maxScore, long matchTime, LeoObject config) { super(Type.CMD, runtime, alliedSpawnPoints, axisSpawnPoints, maxScore, matchTime); this.alliedBasePos = getVector2f(config, "alliedBasePos"); this.axisBasePos = getVector2f(config, "axisBasePos"); this.alliedSquad = new Squad(getAlliedTeam(), 4, 4, 4, 4); this.axisSquad = new Squad(getAxisTeam(), 4, 4, 4, 4); } private Vector2f getVector2f(LeoObject config, String name) { LeoObject v = config.getObject(name); Vector2f result = new Vector2f(); if(!LeoObject.isTrue(v)) { return result; } if(v.isMap() || v.isClass() || v.isNativeClass()) { result.x = v.getObject("x").asFloat(); result.y = v.getObject("y").asFloat(); } else if(v.isArray()) { LeoArray array = v.as(); result.x = array.get(0).asFloat(); result.y = array.get(1).asFloat(); } return result; } private Squad getSquad(Player player) { if(getAlliedTeam().onTeam(player)) { return alliedSquad; } if(getAxisTeam().onTeam(player)) { return axisSquad; } return null; } private Squad getSquad(Team team) { if(getAlliedTeam().getId() == team.getId()) { return alliedSquad; } if(getAxisTeam().getId() == team.getId()) { return axisSquad; } return null; } @Override protected NetGameTypeInfo createNetGameTypeInfo() { NetCommanderGameTypeInfo netGameTypeInfo = new NetCommanderGameTypeInfo(); netGameTypeInfo.alliedSquad = new NetSquad(); netGameTypeInfo.axisSquad = new NetSquad(); return netGameTypeInfo; } /* (non-Javadoc) * @see seventh.game.game_types.AbstractTeamGameType#getNetGameTypeInfo() */ @Override public NetGameTypeInfo getNetGameTypeInfo() { NetCommanderGameTypeInfo netGameTypeInfo = (NetCommanderGameTypeInfo) super.getNetGameTypeInfo(); List<Player> allies = this.getAlliedTeam().getPlayers(); for(int i = 0; i < allies.size(); i++) { Player p = allies.get(i); if(p != null) { netGameTypeInfo.alliedSquad.playerClasses[p.getId()] = p.getPlayerClass(); } } List<Player> axis = this.getAxisTeam().getPlayers(); for(int i = 0; i < axis.size(); i++) { Player p = axis.get(i); if(p != null) { netGameTypeInfo.axisSquad.playerClasses[p.getId()] = p.getPlayerClass(); } } return netGameTypeInfo; } @Override protected void doRegisterListeners(Game game, EventDispatcher dispatcher) { if(this.alliedBase != null) { this.alliedBase.softKill(); } if(this.axisBase != null) { this.axisBase.softKill(); } this.alliedBase = game.newAlliedBase(alliedBasePos); this.axisBase = game.newAxisBase(axisBasePos); } @Override protected boolean joinTeam(Team team, Player player) { Squad squad = getSquad(team); if(squad != null) { if(squad.assignPlayer(player, squad.getAvailableClass())) { return super.joinTeam(team, player); } } return false; } @Override protected boolean leaveTeam(Team team, Player player) { Squad squad = getSquad(team); if(squad != null) { squad.unassignPlayer(player); } return super.leaveTeam(team, player); } @Override public boolean switchPlayerClass(Player player, PlayerClass playerClass) { Squad squad = getSquad(player); if(squad == null) { return false; } squad.unassignPlayer(player); if(squad.assignPlayer(player, playerClass)) { return true; } playerClass = squad.getAvailableClass(); if(playerClass != null) { if(squad.assignPlayer(player, playerClass)) { return true; } } return false; } @Override public void start(Game game) { setGameState(GameState.IN_PROGRESS); getDispatcher().queueEvent(new RoundStartedEvent(this)); } @Override protected GameState doUpdate(Game game, TimeStep timeStep) { GameState gameState = getGameState(); if(gameState == GameState.IN_PROGRESS) { checkRespawns(timeStep, game); // first check for a tie if(!this.alliedBase.isAlive() && !this.axisBase.isAlive()) { setGameState(GameState.TIE); } else { if(!this.alliedBase.isAlive()) { getAxisTeam().setScore(1); setGameState(GameState.WINNER); } if(!this.axisBase.isAlive()) { getAlliedTeam().setScore(1); setGameState(GameState.WINNER); } } } return getGameState(); } }
7,092
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Squad.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/cmd/Squad.java
/* * see license.txt */ package seventh.game.game_types.cmd; import seventh.game.Player; import seventh.game.PlayerClass; import seventh.game.Team; /** * @author Tony * */ public class Squad { private final int maxEngineers, maxScouts, maxInfantry, maxDemolition; private Team team; private int numEngineers, numScouts, numInfantry, numDemolition; /** * @param maxEngineers * @param maxScouts * @param maxInfantry * @param maxDemolition */ public Squad(Team team, int maxEngineers, int maxScouts, int maxInfantry, int maxDemolition) { this.team = team; this.maxEngineers = maxEngineers; this.maxScouts = maxScouts; this.maxInfantry = maxInfantry; this.maxDemolition = maxDemolition; } /** * Assign the Player to the team squad * * @param player * @return true if successful, otherwise false */ public boolean assignPlayer(Player player, PlayerClass playerClass) { if(playerClass == PlayerClass.Engineer) { if(numEngineers + 1 < maxEngineers) { numEngineers++; player.setPlayerClass(playerClass); return true; } } if(playerClass == PlayerClass.Scout) { if(numScouts + 1 < maxScouts) { numScouts++; player.setPlayerClass(playerClass); return true; } } if(playerClass == PlayerClass.Infantry) { if(numInfantry + 1 < maxInfantry) { numInfantry++; player.setPlayerClass(playerClass); return true; } } if(playerClass == PlayerClass.Demolition) { if(numDemolition + 1 < maxDemolition) { numDemolition++; player.setPlayerClass(playerClass); return true; } } return false; } public void unassignPlayer(Player player) { PlayerClass playerClass = player.getPlayerClass(); if(playerClass == PlayerClass.Engineer) { numEngineers--; } else if(playerClass == PlayerClass.Scout) { numScouts--; } else if(playerClass == PlayerClass.Infantry) { numInfantry--; } else if(playerClass == PlayerClass.Demolition) { numDemolition--; } } public PlayerClass getAvailableClass() { if(numEngineers + 1 < maxEngineers) { return PlayerClass.Engineer; } if(numScouts + 1 < maxScouts) { return PlayerClass.Scout; } if(numInfantry + 1 < maxInfantry) { return PlayerClass.Infantry; } if(numDemolition + 1 < maxDemolition) { return PlayerClass.Demolition; } return null; } }
3,122
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
CommanderScript.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/cmd/CommanderScript.java
/* * see license.txt */ package seventh.game.game_types.cmd; import java.io.File; import java.util.ArrayList; import java.util.List; import leola.vm.Leola; import leola.vm.types.LeoMap; import leola.vm.types.LeoObject; import seventh.game.game_types.AbstractGameTypeScript; import seventh.game.game_types.GameType; import seventh.math.Vector2f; import seventh.shared.Cons; /** * Loads an Commander rules script * * @author Tony * */ public class CommanderScript extends AbstractGameTypeScript { /** * */ public CommanderScript(Leola runtime) { super(runtime); } /** * @param mapFile * @param maxScore * @param matchTime * @return * @throws Exception */ public GameType loadGameType(String mapFile, int maxScore, long matchTime) throws Exception { List<Vector2f> alliedSpawnPoints = new ArrayList<>(); List<Vector2f> axisSpawnPoints = new ArrayList<Vector2f>(); LeoObject config = null; File scriptFile = new File(mapFile + ".cmd.leola"); if(!scriptFile.exists()) { Cons.println("*** ERROR -> No associated script file for Commander game type. Looking for: " + scriptFile.getName()); } else { config = getRuntime().eval(scriptFile); if(LeoObject.isTrue(config)) { alliedSpawnPoints = loadSpawnPoint(config, "alliedSpawnPoints"); axisSpawnPoints = loadSpawnPoint(config, "axisSpawnPoints"); } } GameType gameType = new CommanderGameType(getRuntime(), alliedSpawnPoints, axisSpawnPoints, maxScore, matchTime, config==null ? new LeoMap() : config); return gameType; } }
1,877
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
SurvivalGameType.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/svr/SurvivalGameType.java
/* * see license.txt */ package seventh.game.game_types.svr; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import leola.vm.Leola; import leola.vm.types.LeoNativeFunction; import leola.vm.types.LeoObject; import leola.vm.util.ClassUtil; import seventh.ai.basic.AILeolaLibrary; import seventh.ai.basic.Brain; import seventh.ai.basic.DefaultAISystem; import seventh.ai.basic.actions.Action; import seventh.game.Game; import seventh.game.Player; import seventh.game.Team; import seventh.game.entities.PlayerEntity; import seventh.game.events.PlayerKilledEvent; import seventh.game.events.PlayerKilledListener; import seventh.game.events.RoundEndedEvent; import seventh.game.events.RoundStartedEvent; import seventh.game.events.RoundStartedListener; import seventh.game.events.GameEvent; import seventh.game.events.GameEvent.EventType; import seventh.game.game_types.AbstractTeamGameType; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.EventDispatcher; import seventh.shared.SeventhConstants; import seventh.shared.TimeStep; import seventh.shared.Timer; /** * @author Tony * */ public class SurvivalGameType extends AbstractTeamGameType { private GameState currentGameState; private List<Player> availablePlayers; private boolean joinAllies; private boolean gameTypeInitialized; private Game game; private Timer startTimer; /** * @param runtime * @param alliedSpawnPoints * @param axisSpawnPoints * @param maxScore * @param matchTime */ public SurvivalGameType(Leola runtime, List<Vector2f> alliedSpawnPoints, List<Vector2f> axisSpawnPoints, int maxScore, long matchTime) { super(Type.SVR, runtime, alliedSpawnPoints, axisSpawnPoints, maxScore, matchTime); this.availablePlayers = new ArrayList<>(); this.startTimer = new Timer(false, 5_000).stop(); this.currentGameState = GameState.IN_PROGRESS; this.joinAllies = true; this.gameTypeInitialized = false; addMethod("completeMission"); addMethod("failedMission"); addMethod("aiCommand", int.class, Action.class); addMethod("spawnEnemy", Rectangle.class); addMethod("playSound", String.class); addMethod("doIn", long.class, LeoObject.class); } private void addMethod(String methodName, Class<?> ... params) { LeoNativeFunction func = new LeoNativeFunction(ClassUtil.getMethodByName(SurvivalGameType.class, methodName, params), this); runtime.put(func.getMethodName().toString(), func); } public void doIn(long time, LeoObject action) { if(game!=null) { game.addGameTimer(false, time, action); } } public void completeMission() { this.currentGameState = GameState.WINNER; getAlliedTeam().score(1); } public void failedMission() { this.currentGameState = GameState.WINNER; getAxisTeam().score(1); } public void aiCommand(int playerId, Action action) { DefaultAISystem aiSystem = (DefaultAISystem) game.getAISystem(); Brain brain = aiSystem.getBrain(playerId); if(brain!=null) { brain.doAction(action); } } public void playSound(String path) { if(game!=null) { game.getDispatcher().queueEvent(new GameEvent(this, EventType.CustomSound, null, null, 0f, path, 0, 0, null)); } } public int spawnEnemy(Rectangle bounds) { Vector2f spawn = game.findFreeRandomSpot(new Rectangle(SeventhConstants.PLAYER_WIDTH, SeventhConstants.PLAYER_HEIGHT), bounds); if(spawn != null) { return spawnEnemy(spawn.x, spawn.y); } return spawnEnemy(0f, 0f); } public int spawnEnemy(float x, float y) { Player player = null; Iterator<Player> it = this.availablePlayers.iterator(); while(it.hasNext()) { player = it.next(); it.remove(); break; } if(player != null) { PlayerEntity entity = game.spawnPlayerEntity(player.getId(), new Vector2f(x, y)); if(entity != null) { return player.getId(); } } return -1; } @Override public void playerJoin(Player player) { player.commitSuicide(); player.resetStats(); if(!gameTypeInitialized) { int teamId = player.getTeamId(); if(teamId == Team.ALLIED_TEAM_ID) { joinTeam(getAlliedTeam(), player); } else if(teamId == Team.AXIS_TEAM_ID) { joinTeam(getAxisTeam(), player); } else { joinTeam(getAlliedTeam(), player); } } else { if(!joinAllies && player.isBot()) { joinTeam(getAxisTeam(), player); } else { joinTeam(getAlliedTeam(), player); } } } @Override public void start(final Game game) { this.game = game; AILeolaLibrary aiLib = new AILeolaLibrary(game.getAISystem()); this.runtime.loadLibrary(aiLib, "ai"); this.startTimer.start(); } private void initializeGame(Game game) { this.gameTypeInitialized = true; game.killAll(); final int maxAlliedTeamSize = 0; // spawn allied bots first for(int i = getAlliedTeam().getTeamSize(); i < maxAlliedTeamSize; i++) { int id = game.addBot("[b] Allied Soldier"); if(id > -1) { game.playerSwitchedTeam(id, Team.ALLIED_TEAM_ID); } } // for(Player player : getAlliedTeam().getPlayers()) { // super.spawnPlayer(player, game); // } this.joinAllies = false; for(int i = getAxisTeam().getTeamSize(); i < SeventhConstants.MAX_PLAYERS - maxAlliedTeamSize; i++) { int id = game.addBot("[b] Axis Soldier"); if(id > -1) { game.playerSwitchedTeam(id, Team.AXIS_TEAM_ID); } } } @Override protected void spawnPlayer(Player player, Game game) { // don't do anything, spawning of players is handled // by scripts } @Override protected void doRegisterListeners(final Game game, EventDispatcher dispatcher) { dispatcher.addEventListener(PlayerKilledEvent.class, new PlayerKilledListener() { @Override public void onPlayerKilled(PlayerKilledEvent event) { Player player = event.getPlayer(); if(!availablePlayers.contains(player) && player.getTeamId() == Team.AXIS_TEAM_ID) { availablePlayers.add(player); } if(getAlliedTeam().isTeamDead() && startTimer.isExpired()) { //failedMission(); getDispatcher().queueEvent(new RoundEndedEvent(this, getAxisTeam(), game.getNetGameStats())); //setGameState(GameState.INTERMISSION); startTimer.reset().start(); } } }); dispatcher.addEventListener(RoundStartedEvent.class, new RoundStartedListener() { @Override public void onRoundStarted(RoundStartedEvent event) { for(Player player : getAlliedTeam().getPlayers()) { SurvivalGameType.super.spawnPlayer(player, game); } } }); } @Override protected GameState doUpdate(Game game, TimeStep timeStep) { this.startTimer.update(timeStep); if(this.startTimer.isOnFirstTime()) { availablePlayers.clear(); initializeGame(game); for(Player player : getAxisTeam().getPlayers()) { availablePlayers.add(player); } getDispatcher().queueEvent(new RoundStartedEvent(this)); } checkSpectating(timeStep, game); return this.currentGameState; } }
8,520
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
SurvivorScript.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/svr/SurvivorScript.java
/* * see license.txt */ package seventh.game.game_types.svr; import java.io.File; import java.util.ArrayList; import java.util.List; import leola.vm.Leola; import leola.vm.types.LeoObject; import seventh.game.game_types.AbstractGameTypeScript; import seventh.game.game_types.GameType; import seventh.math.Vector2f; import seventh.shared.Cons; /** * Loads Survivor rules script * * @author Tony * */ public class SurvivorScript extends AbstractGameTypeScript { /** * */ public SurvivorScript(Leola runtime) { super(runtime); } /** * @param mapFile * @param maxScore * @param matchTime * @return * @throws Exception */ public GameType loadGameType(String mapFile, int maxScore, long matchTime) throws Exception { List<Vector2f> alliedSpawnPoints = new ArrayList<>(); List<Vector2f> axisSpawnPoints = new ArrayList<Vector2f>(); File scriptFile = new File(mapFile + ".svr.leola"); if(!scriptFile.exists()) { Cons.println("*** ERROR -> No associated script file for Survivor game type. Looking for: " + scriptFile.getName()); } else { LeoObject config = getRuntime().eval(scriptFile); if(LeoObject.isTrue(config)) { alliedSpawnPoints = loadSpawnPoint(config, "alliedSpawnPoints"); axisSpawnPoints = loadSpawnPoint(config, "axisSpawnPoints"); } } GameType gameType = new SurvivalGameType(getRuntime(), alliedSpawnPoints, axisSpawnPoints, maxScore, matchTime); return gameType; } }
1,684
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
BombTargetObjective.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/obj/BombTargetObjective.java
/* * The Seventh * see license.txt */ package seventh.game.game_types.obj; import seventh.game.Game; import seventh.game.GameInfo; import seventh.game.entities.Bomb; import seventh.game.entities.BombTarget; import seventh.math.Vector2f; /** * @author Tony * */ public class BombTargetObjective implements Objective { private BombTarget target; private Vector2f position; private String name; private boolean rotated; /** * @param name */ public BombTargetObjective(Vector2f position) { this(position, null, false); } /** * @param position * @param name */ public BombTargetObjective(Vector2f position, String name, Boolean rotated) { this.position = position; this.name = name != null ? name : "Bomb Target"; this.rotated = rotated != null && rotated; } /* (non-Javadoc) * @see seventh.game.game_types.Objective#reset(seventh.game.Game) */ @Override public void reset(Game game) { if(target!=null) { Bomb bomb = target.getBomb(); if(bomb!=null) { bomb.softKill(); } target.reset(); /* bug with onKill if the bomb is * already 'dead' it doesn't invoke the * onKill callback */ if( target.onKill != null ) { target.onKill.onKill(target, target); } } init(game); } /* (non-Javadoc) * @see seventh.game.game_types.Objective#init(seventh.game.Game) */ @Override public void init(Game game) { target = game.newBombTarget(game.getGameType().getDefender(), position); if(rotated) { target.rotate90(); } } /* (non-Javadoc) * @see seventh.game.game_types.Objective#isCompleted(seventh.game.Game) */ @Override public boolean isCompleted(GameInfo game) { return target != null && !target.isAlive(); } /* (non-Javadoc) * @see seventh.game.game_types.Objective#isInProgress(seventh.game.GameInfo) */ @Override public boolean isInProgress(GameInfo game) { return target != null && (target.bombActive()||target.isBeingDestroyed()); } /* (non-Javadoc) * @see seventh.game.game_types.Objective#getName() */ @Override public String getName() { return this.name; } }
2,516
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Objective.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/obj/Objective.java
/* * The Seventh * see license.txt */ package seventh.game.game_types.obj; import seventh.game.Game; import seventh.game.GameInfo; /** * @author Tony * */ public interface Objective { /** * Reset the objective * @param game */ public void reset(Game game); /** * Initializes the objective * @param game */ public void init(Game game); /** * Determines if the objective is completed * @param game * @return true if completed, false otherwise */ public boolean isCompleted(GameInfo game); /** * Determines if the objective is in progress, i.e., the * defenders must take action to destroy/defend it. (such as * a bomb is planted and the defenders must disarm it). * @param game * @return true if the objective is in progress which requires * the defenders to take action. */ public boolean isInProgress(GameInfo game); /** * The {@link Objective}'s name. This text is displayed * on the players HUD. * * @return the name of the objective. */ public String getName(); }
1,167
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
ObjectiveGameType.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/obj/ObjectiveGameType.java
/* * The Seventh * see license.txt */ package seventh.game.game_types.obj; import java.util.ArrayList; import java.util.List; import leola.vm.Leola; import seventh.game.Game; import seventh.game.Player; import seventh.game.Team; import seventh.game.events.RoundEndedEvent; import seventh.game.events.RoundStartedEvent; import seventh.game.game_types.AbstractTeamGameType; import seventh.game.game_types.GameType; import seventh.math.Vector2f; import seventh.shared.EventDispatcher; import seventh.shared.TimeStep; /** * Accomplish an objective to win * * @author Tony * */ public class ObjectiveGameType extends AbstractTeamGameType { private int currentRound; private int minimumObjectivesToComplete; private List<Objective> outstandingObjectives; private List<Objective> completedObjectives; private long roundDelayTime; private long currentDelayTime; private boolean inIntermission; private Team attacker, defender; /** * @param maxScore * @param roundTime */ public ObjectiveGameType(Leola runtime, List<Objective> objectives, List<Vector2f> alliedSpawnPoints, List<Vector2f> axisSpawnPoints, int minimumObjectivesToComplete, int maxScore, long roundTime, long roundDelayTime, byte defenderTeamId) { super(GameType.Type.OBJ, runtime, alliedSpawnPoints, axisSpawnPoints, maxScore, roundTime); this.outstandingObjectives = objectives; this.minimumObjectivesToComplete = minimumObjectivesToComplete; this.currentRound = 0; this.roundDelayTime = roundDelayTime; this.currentDelayTime = roundDelayTime; this.inIntermission = true; this.completedObjectives = new ArrayList<Objective>(this.outstandingObjectives.size()); if(defenderTeamId == Team.ALLIED_TEAM_ID) { this.attacker = getAxisTeam(); this.defender = getAlliedTeam(); } else { this.defender = getAxisTeam(); this.attacker = getAlliedTeam(); } this.attacker.setAttacker(true); this.defender.setDefender(true); } /** * @return the attacker */ @Override public Team getAttacker() { return attacker; } /** * @return the defender */ @Override public Team getDefender() { return defender; } /* (non-Javadoc) * @see seventh.game.game_types.GameType#start(seventh.game.Game) */ @Override public void start(Game game) { setGameState(GameState.IN_PROGRESS); int size = this.outstandingObjectives.size(); for(int i = 0; i < size; i++) { this.outstandingObjectives.get(i).init(game); } } /* (non-Javadoc) * @see seventh.game.game_types.GameType#update(leola.live.TimeStep) */ @Override protected GameState doUpdate(Game game, TimeStep timeStep) { if(this.inIntermission) { this.currentDelayTime -= timeStep.getDeltaTime(); if(this.currentDelayTime <= 0) { startRound(game); } } else { // If there are objectives that are in progress // we must force the attackers to disarm them, // even if all the attackers are dead int numberOfObjectivesInProgress = 0; // if we are currently playing, check // and see if the objectives have been completed int size = this.outstandingObjectives.size(); for(int i = 0; i < size; i++) { Objective obj = this.outstandingObjectives.get(i); if (obj.isCompleted(game)) { this.completedObjectives.add(obj); } else if(obj.isInProgress(game)) { numberOfObjectivesInProgress++; } } this.outstandingObjectives.removeAll(this.completedObjectives); if(this.completedObjectives.size() >= this.minimumObjectivesToComplete) { endRound(attacker, game); } else if(this.outstandingObjectives.isEmpty() && this.completedObjectives.size() > 0) { endRound(attacker, game); } else if( defender.isTeamDead() && defender.teamSize() > 0) { endRound(attacker, game); } else if(getRemainingTime() <= 0 ) { endRound(defender, game); } else if( (attacker.isTeamDead() && attacker.teamSize() > 0) && (numberOfObjectivesInProgress+this.completedObjectives.size() < this.minimumObjectivesToComplete) ) { //&& (!this.outstandingObjectives.isEmpty() ? numberOfObjectivesInProgress < this.outstandingObjectives.size() : true) ) { endRound(defender, game); } else { checkSpectating(timeStep, game); } } return this.currentRound >= this.getMaxScore() ? GameState.WINNER : GameState.IN_PROGRESS; } /* (non-Javadoc) * @see seventh.game.game_types.AbstractTeamGameType#isInProgress() */ @Override public boolean isInProgress() { return super.isInProgress() && (!this.inIntermission || this.currentDelayTime == this.roundDelayTime); } /** * End the round * * @param winner * @param game */ private void endRound(Team winner, Game game) { this.currentRound++; this.currentDelayTime = this.roundDelayTime; this.inIntermission = true; // give a point to the winner if(winner!=null) { winner.score(1); } getDispatcher().queueEvent(new RoundEndedEvent(this, winner, game.getNetGameStats())); } private void startRound(Game game) { this.inIntermission = false; game.killAll(); int size = this.completedObjectives.size(); for(int i = 0; i < size; i++) { this.completedObjectives.get(i).reset(game); } size = this.outstandingObjectives.size(); for(int i = 0; i < size; i++) { outstandingObjectives.get(i).reset(game); } this.outstandingObjectives.addAll(completedObjectives); this.completedObjectives.clear(); // if we are done with intermission, lets go // ahead and spawn the players Player[] players = game.getPlayers().getPlayers(); for (int i = 0; i < players.length; i++) { Player player = players[i]; if (player != null) { if(!player.isPureSpectator() && !player.isCommander()) { spawnPlayer(player, game); } } } resetRemainingTime(); getDispatcher().queueEvent(new RoundStartedEvent(this)); } /* (non-Javadoc) * @see seventh.game.game_types.GameType#registerListeners(seventh.game.Game, leola.frontend.listener.EventDispatcher) */ @Override protected void doRegisterListeners(Game game, EventDispatcher dispatcher) { } }
7,809
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
ObjectiveScript.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/game_types/obj/ObjectiveScript.java
/* * see license.txt */ package seventh.game.game_types.obj; import java.io.File; import java.util.ArrayList; import java.util.List; import leola.vm.Leola; import leola.vm.types.LeoArray; import leola.vm.types.LeoNativeClass; import leola.vm.types.LeoObject; import seventh.game.Team; import seventh.game.game_types.AbstractGameTypeScript; import seventh.game.game_types.GameType; import seventh.math.Vector2f; import seventh.shared.Cons; /** * Loads an {@link Objective} script * * @author Tony * */ public class ObjectiveScript extends AbstractGameTypeScript { /** * */ public ObjectiveScript(Leola runtime) { super(runtime); } /** * @param mapFile * @param maxScore * @param matchTime * @return * @throws Exception */ public GameType loadGameType(String mapFile, int maxScore, long matchTime) throws Exception { List<Objective> objectives = new ArrayList<>(); List<Vector2f> alliedSpawnPoints = new ArrayList<>(); List<Vector2f> axisSpawnPoints = new ArrayList<Vector2f>(); byte defenders = Team.AXIS_TEAM_ID; int minimumObjectivesToComplete = 1; File scriptFile = new File(mapFile + ".obj.leola"); if(!scriptFile.exists()) { Cons.println("*** ERROR -> No associated script file for objective game type. Looking for: " + scriptFile.getName()); } else { LeoObject config = getRuntime().eval(scriptFile); if(LeoObject.isTrue(config)) { LeoObject scriptedObjectives = config.getObject("objectives"); if(LeoObject.isTrue(scriptedObjectives)) { switch(scriptedObjectives.getType()) { case ARRAY: { LeoArray array = scriptedObjectives.as(); for(int i = 0; i < array.size(); i++) { LeoObject o = array.get(i); if (o instanceof LeoNativeClass) { if(o.getValue() instanceof Objective) { Objective objective = (Objective)o.getValue(); objectives.add(objective); } else { Cons.println(((LeoNativeClass) o).getNativeClass() + " is not of type: " + Objective.class.getName()); } } } break; } case NATIVE_CLASS: { LeoObject o = scriptedObjectives; if(o.getValue() instanceof Objective) { Objective objective = (Objective)o.getValue(); objectives.add(objective); } else { Cons.println(((LeoNativeClass) o).getNativeClass() + " is not of type: " + Objective.class.getName()); } break; } default: { Cons.println("*** ERROR -> objectives must either be an Array of objectives or a Java class or custom Leola class"); } } } LeoObject scriptedDefenders = config.getObject("defenders"); if(LeoObject.isTrue(scriptedDefenders)) { switch(scriptedDefenders.getType()) { case INTEGER: case LONG: case REAL: defenders = (byte)scriptedDefenders.asInt(); break; case STRING: if(Team.ALLIED_TEAM_NAME.equalsIgnoreCase(scriptedDefenders.toString())) { defenders = Team.ALLIED_TEAM_ID; } break; default:{ Cons.println("*** ERROR -> defenders must either be a 2(for allies) or 4(for axis) or 'allies' or 'axis' values"); } } } alliedSpawnPoints = loadSpawnPoint(config, "alliedSpawnPoints"); axisSpawnPoints = loadSpawnPoint(config, "axisSpawnPoints"); if(config.hasObject("minimumObjectivesToComplete")) { minimumObjectivesToComplete = config.getObject("minimumObjectivesToComplete").asInt(); } else { minimumObjectivesToComplete = objectives.size(); } } } final long timeBetweenRounds = 10_000L; GameType gameType = new ObjectiveGameType(getRuntime(), objectives, alliedSpawnPoints, axisSpawnPoints, minimumObjectivesToComplete, maxScore, matchTime, timeBetweenRounds, defenders); return gameType; } }
5,354
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Pistol.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Pistol.java
/* * The Seventh * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.WeaponConstants; /** * @author Tony * */ public class Pistol extends Weapon { private boolean endFire; /** * @param game * @param owner */ public Pistol(Game game, Entity owner) { super(game, owner, Type.PISTOL); this.damage = 14; this.reloadTime = 2500; this.clipSize = 9; this.totalAmmo = 27; this.spread = 11; this.bulletsInClip = this.clipSize; this.weaponWeight = WeaponConstants.PISTOL_WEIGHT; this.lineOfSight = WeaponConstants.PISTOL_LINE_OF_SIGHT; this.endFire = true; applyScriptAttributes("pistol"); } /* (non-Javadoc) * @see palisma.game.Weapon#update(leola.live.TimeStep) */ @Override public void update(TimeStep timeStep) { super.update(timeStep); } @Override public boolean isPrimary() { return false; } @Override public boolean reload() { boolean reloaded = super.reload(); if(reloaded) { game.emitSound(getOwnerId(), SoundType.PISTOL_RELOAD, getPos()); } return reloaded; } @Override public boolean beginFire() { if (canFire()) { game.emitSound(getOwnerId(), SoundType.PISTOL_FIRE, getPos()); newBullet(); bulletsInClip--; weaponTime = 200; setFireState(); return true; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } this.endFire = false; return false; } /* (non-Javadoc) * @see palisma.game.Weapon#endFire() */ @Override public boolean endFire() { this.endFire = true; if(isFiring()) { game.emitSound(getOwnerId(), SoundType.BULLET_SHELL, owner.getPos()); } return false; } @Override public boolean canFire() { return super.canFire() && this.endFire; } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(palisma.game.Direction) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return spread(facing, spread); } }
2,793
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
FlameThrower.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/FlameThrower.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.WeaponConstants; /** * @author Tony * */ public class FlameThrower extends Weapon { private int emitRatePerSec; private boolean isDoneFiring; /** * @param game * @param owner * @param type */ public FlameThrower(Game game, Entity owner) { super(game, owner, Type.FLAME_THROWER); this.bulletsInClip = 255; this.spread = 1; this.emitRatePerSec = 18; this.isDoneFiring = true; this.lineOfSight = WeaponConstants.FLAME_THROWER_LINE_OF_SIGHT; this.weaponWeight = WeaponConstants.FLAME_THROWER_WEIGHT; setBulletSpawnDistance(35); } @Override public boolean isHeavyWeapon() { return true; } protected Vector2f newBulletPosition() { Vector2f ownerDir = owner.getFacing(); Vector2f ownerPos = owner.getPos(); Vector2f pos = new Vector2f(ownerPos); Vector2f.Vector2fMA(pos, ownerDir, getBulletSpawnDistance(), pos); return pos; } @Override public boolean beginFire() { if(canFire()) { newFire(); if(isDoneFiring) { game.emitSound(getOwnerId(), SoundType.FLAMETHROWER_SHOOT, getPos()); } isDoneFiring = false; weaponTime = 1000/this.emitRatePerSec; bulletsInClip--; setFireState(); return true; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } return false; } @Override public boolean endFire() { this.isDoneFiring = true; return super.endFire(); } @Override protected Vector2f calculateVelocity(Vector2f facing) { return facing.createClone(); } }
2,148
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
GunSwing.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/GunSwing.java
/** * */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.PlayerEntity; import seventh.math.Line; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; /** * Attacking by swinging a gun * * @author Tony * */ public class GunSwing { private long swingTime; private long currentSwingTime; private long waitTime; private Vector2f swing; private int swingAngle; private float swingLength; private boolean hitSomeone, endSwing; private Game game; private Entity owner; private int damage; private Rectangle hitBox; /** * @param game * @param owner */ public GunSwing(Game game, Entity owner) { this.game = game; this.owner = owner; this.swingTime = 500; this.currentSwingTime = 0; this.swingLength = 40.0f; this.swing = new Vector2f(); this.hitSomeone = false; this.endSwing = true; this.damage = 100; this.hitBox = new Rectangle(); this.hitBox.setSize(64, 64); } public void setOwner(Entity owner) { this.owner = owner; } /** * Determines if the swing is hitting anyone */ private void doesSwingTouchPlayers() { swing.set(1,0); Vector2f.Vector2fRotate(swing, Math.toRadians(swingAngle), swing); Vector2f origin = owner.getCenterPos(); Vector2f.Vector2fMA(origin, swing, swingLength, swing); PlayerEntity[] playerEntities = game.getPlayerEntities(); for(int i = 0; i < playerEntities.length; i++) { Entity other = playerEntities[i]; if(other == null) { continue; } if(other == owner) { continue; } if(!other.canTakeDamage()) { continue; } /* first do an inexpensive check */ if(!hitBox.intersects(other.getBounds())) { continue; } if(Line.lineIntersectsRectangle(origin, swing, other.getBounds())) { other.damage(owner, damage); game.emitSound(owner.getId(), SoundType.MELEE_HIT, origin); hitSomeone = true; } } } /** * Updates the state * * @param timeStep */ public void update(TimeStep timeStep) { if(isSwinging()) { this.waitTime = 300; this.currentSwingTime -= timeStep.getDeltaTime(); if(!hitSomeone) { doesSwingTouchPlayers(); } int numberOfTicks = (int)(swingTime/timeStep.getDeltaTime()); if(numberOfTicks == 0) { numberOfTicks = 1; } swingAngle = (swingAngle + ( 45 / numberOfTicks )) % 360; } else { /* decay the wait time until we can swing again */ this.waitTime -= timeStep.getDeltaTime(); } } /** * @return if we can swing */ public boolean canSwing() { return currentSwingTime <= 0 && this.waitTime <= 0 && endSwing; } /** * @return true if we are currently swinging */ public boolean isSwinging() { return this.currentSwingTime > 0; } /** * Starts a swing * @return true if started, false otherwise */ public boolean beginSwing() { if(canSwing()) { float orientation = owner.getOrientation(); swingAngle = (int)Math.toDegrees(orientation);// % 360; Vector2f origin = owner.getCenterPos(); hitBox.centerAround(origin); currentSwingTime = swingTime; game.emitSound(owner.getId(), SoundType.MELEE_SWING, owner.getCenterPos()); hitSomeone = false; endSwing = false; return true; } return false; } /** * Done swinging */ public void endSwing() { endSwing = true; } }
4,652
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Bullet.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Bullet.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.SurfaceTypeToSoundType; import seventh.game.entities.Entity; import seventh.game.net.NetBullet; import seventh.game.net.NetEntity; import seventh.map.Map; import seventh.map.MapObject; import seventh.map.Tile.SurfaceType; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; /** * @author Tony * */ public class Bullet extends Entity { private Entity owner; protected Vector2f targetVel; private Vector2f previousPos, delta, origin; private int damage; private NetBullet netBullet; private int ownerHeightMask; private int maxDistance; private boolean piercing; private Entity lastEntityTouched; private static class BulletOnTouchListener implements Entity.OnTouchListener { @Override public void onTouch(Entity me, Entity other) { Bullet bullet = (Bullet)me; Type otherType = other.getType(); if(otherType.isDamagable()) { if(other != bullet.lastEntityTouched && other.canTakeDamage()) { other.damage(me, bullet.getDamage()); bullet.lastEntityTouched = other; } } } } private static class BulletOnMapObjectTouchListener implements OnMapObjectTouchListener { private Game game; public BulletOnMapObjectTouchListener(Game game) { this.game = game; } @Override public void onTouch(Entity bullet, MapObject object) { game.emitSound(bullet.getId(), SurfaceTypeToSoundType.toImpactSoundType(object.geSurfaceType()), bullet.getCenterPos()); bullet.kill(bullet); } } /** * @param position * @param speed * @param game * @param owner */ public Bullet(Vector2f position, int speed, final Game game, Entity owner, Vector2f targetVel, int damage, boolean isPiercing) { super(position, speed, game, Type.BULLET); this.owner = owner; this.targetVel = targetVel; this.damage = damage; this.bounds.width = 4; this.bounds.height = 4; this.bounds.setLocation(getPos()); this.setOrientation(owner.getOrientation()); this.netBullet = new NetBullet(); this.netBullet.damage = (byte)damage; this.netBullet.id = getId(); this.netBullet.type = Type.BULLET; this.previousPos = new Vector2f(); this.delta = new Vector2f(); this.origin = new Vector2f(position); this.onTouch = new BulletOnTouchListener(); this.onMapObjectTouch = new BulletOnMapObjectTouchListener(game); this.ownerHeightMask = owner.getHeightMask(); this.piercing = isPiercing; this.maxDistance = 5000; } /** * @return the maxDistance */ public int getMaxDistance() { return maxDistance; } /** * Sets the max distance * @param maxDistance */ public void setMaxDistance(int maxDistance) { /* adds a little bit of a fuzzy distance so that the bullets don't * all destroy equally */ this.maxDistance = maxDistance + game.getRandom().nextInt(64); } /** * @return the piercing */ public boolean isPiercing() { return piercing; } /** * @return the height mask for if the entity is crouching or standing */ public int getOwnerHeightMask() { return ownerHeightMask; } /** * @param ownerHeightMask the ownerHeightMask to set */ public void setOwnerHeightMask(int ownerHeightMask) { this.ownerHeightMask = ownerHeightMask; } /** * @return the targetVel */ public Vector2f getTargetVel() { return targetVel; } /** * @return the damage points of this bullet */ public int getDamage() { return damage; } /** * @return the owner */ public Entity getOwner() { return owner; } /** * @param owner the owner to set */ public void setOwner(Entity owner) { this.owner = owner; } /** * Emits an impact sound depending on the collision tile * @param x * @param y */ protected void emitImpactSound(int x, int y) { SurfaceType surface = game.getMap().getSurfaceTypeByWorld(x,y); if(surface != null) { SoundType sound = SurfaceTypeToSoundType.toImpactSoundType(surface); game.emitSound(getId(), sound, getPos()); } else { game.emitSound(getId(), SoundType.IMPACT_DEFAULT, getPos()); } } /* (non-Javadoc) * @see palisma.game.Entity#collideX(int, int) */ @Override protected boolean collideX(int newX, int oldX) { kill(this); /* adjust so it offsets to the correct tile * get the bullet direction and adjust to mid-tile */ int adjustX = (newX - oldX) * 12; emitImpactSound(newX + adjustX, bounds.y); return true; } /* (non-Javadoc) * @see palisma.game.Entity#collideY(int, int) */ @Override protected boolean collideY(int newY, int oldY) { kill(this); /* adjust so it offsets to the correct tile * get the bullet direction and adjust to mid-tile */ int adjustY = (newY - oldY) * 12; emitImpactSound(bounds.x, newY + adjustY); return true; } /* (non-Javadoc) * @see palisma.game.Entity#update(leola.live.TimeStep) */ @Override public boolean update(TimeStep timeStep) { boolean isBlocked = false; vel.set(targetVel); Map map = this.game.getMap(); float dt = (float)timeStep.asFraction(); previousPos.set(pos); int newX = Math.round(pos.x + vel.x * speed * dt); int newY = Math.round(pos.y + vel.y * speed * dt); delta.x = newX - previousPos.x; delta.y = newY - previousPos.y; int dx = delta.x < 0 ? -1 : delta.x > 0 ? 1 : 0; int dy = delta.y < 0 ? -1 : delta.y > 0 ? 1 : 0; int heightMask = getOwnerHeightMask(); if(dx != 0 || dy != 0) { do { if(bounds.x != newX) { if(dx==0) { break; } bounds.x += dx; if( map.rectCollides(bounds, heightMask) ) { isBlocked = collideX(bounds.x, bounds.x-dx); if(isBlocked) { bounds.x -= dx; } } } if(bounds.y != newY && !isBlocked) { if(dy==0) { break; } bounds.y += dy; if( map.rectCollides(bounds, heightMask)) { isBlocked = collideY(bounds.y, bounds.y-dy); if(isBlocked) { bounds.y -= dy; } } } if( bounds.y < 0 || bounds.x < 0 || (bounds.y > map.getMapHeight() + 80) || (bounds.x > map.getMapWidth() + 80)) { kill(this); break; } else { if(collidesAgainstEntity(bounds) || collidesAgainstMapObject(bounds)) { break; } } /* if this has traveled the max distance, kill it */ delta.set(bounds.x, bounds.y); float distanceTraveledSq = Vector2f.Vector2fDistanceSq(origin, delta); int maxDistance = getMaxDistance(); if(distanceTraveledSq > (maxDistance*maxDistance) ) { kill(this); break; } } while(!isBlocked && (bounds.x != newX || bounds.y != newY)); } else { if(!collidesAgainstEntity(bounds)) { if(collidesAgainstMapObject(bounds)) { kill(this); } } } getPos().set(bounds.x, bounds.y); return isBlocked; } @Override protected boolean collidesAgainstEntity(Rectangle bounds) { if(game.doesTouchPlayers(this, origin, targetVel) && !this.piercing) { return true; } if(game.doesTouchVehicles(this)) { return true; } if(game.doesTouchDoors(this)) { return true; } if(game.doesTouchBases(this)) { return true; } return false; } @Override protected boolean collidesAgainstMapObject(Rectangle bounds) { if(game.doesTouchMapObject(this)) { return true; } return false; } /* (non-Javadoc) * @see seventh.game.entities.Entity#isTouching(seventh.game.entities.Entity) */ @Override public boolean isTouching(Entity other) { if(other==owner) { return false; } return super.isTouching(other); } /* (non-Javadoc) * @see palisma.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { return getNetBullet(); } /** * @return the netBullet */ public NetBullet getNetBullet() { setNetEntity(netBullet); netBullet.damage = (byte)this.damage; netBullet.ownerId = this.owner.getId(); // netBullet.targetVelX = this.targetVel.x; // netBullet.targetVelY = this.targetVel.y; netBullet.type = getType(); return netBullet; } }
10,706
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Weapon.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Weapon.java
/* * see license.txt */ package seventh.game.weapons; import java.util.Random; import leola.vm.exceptions.LeolaRuntimeException; import leola.vm.types.LeoMap; import leola.vm.types.LeoObject; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.game.entities.PlayerEntity; import seventh.game.net.NetWeapon; import seventh.math.Vector2f; import seventh.shared.Config; import seventh.shared.Cons; import seventh.shared.SoundType; import seventh.shared.TimeStep; /** * Represents a Weapon. * * @author Tony * */ public abstract class Weapon { public enum WeaponState { READY, FIRING, WAITING, RELOADING, FIRE_EMPTY, MELEE_ATTACK, SWITCHING, UNKNOWN ; public byte netValue() { return (byte)ordinal(); } private static WeaponState[] values = values(); public static WeaponState fromNet(byte value) { if(value < 0 || value >= values.length) { return UNKNOWN; } return values[value]; } public static int numOfBits() { return 4; } } protected long weaponTime; protected int damage; protected long reloadTime; protected int weaponWeight; protected int clipSize; protected int bulletsInClip; protected int totalAmmo; protected int spread; protected int lineOfSight; protected int bulletRange; private WeaponState weaponState; protected Entity owner; protected Game game; protected NetWeapon netWeapon; private Random random; private final Type type; private GunSwing gunSwing; private float bulletSpawnDistance, rocketSpawnDistance, grenadeSpawnDistance; private int damageMultiplier; /** * @param game * @param owner * @param type */ public Weapon(Game game, Entity owner, Type type) { this.type = type; this.game = game; this.owner = owner; this.netWeapon = new NetWeapon(); this.netWeapon.type = type; this.random = new Random(); this.weaponState = WeaponState.READY; this.gunSwing = new GunSwing(game, owner); this.bulletSpawnDistance = 15.0f; this.rocketSpawnDistance = 40.0f; this.grenadeSpawnDistance = 50.0f; this.bulletRange = 5000; } /** * Sets the weapons properties. * @param weaponName * @return the attributes if available, otherwise null */ protected LeoMap applyScriptAttributes(String weaponName) { Config config = game.getConfig().getConfig(); try { LeoObject values = config.get("weapons", weaponName); if(values!=null&&values.isMap()) { LeoMap attributes = values.as(); this.damage = attributes.getInt("damage"); this.reloadTime = attributes.getInt("reload_time"); this.clipSize = attributes.getInt("clip_size"); this.totalAmmo = attributes.getInt("total_ammo"); this.bulletsInClip = this.clipSize; this.spread = attributes.getInt("spread"); this.bulletRange = attributes.getInt("bullet_range"); return attributes; } } catch(LeolaRuntimeException e) { Cons.print("*** Error reading the weapons configuration: " + e); } return null; } /** * If this is a primary weapon or not * @return true if this is a primary weapon */ public boolean isPrimary() { return true; } /** * If this weapon is huge, which prevents the user * from taking certain actions * * @return true if this weapon is yuge */ public boolean isHeavyWeapon() { return false; } /** * @param owner the owner to set */ public void setOwner(Entity owner) { this.owner = owner; this.gunSwing.setOwner(owner); if(owner instanceof PlayerEntity) { this.damageMultiplier = ((PlayerEntity)owner).getDamageMultiplier(); } } /** * @param bulletsInClip the bulletsInClip to set */ public void setBulletsInClip(int bulletsInClip) { this.bulletsInClip = bulletsInClip; } /** * @param totalAmmo the totalAmmo to set */ public void setTotalAmmo(int totalAmmo) { this.totalAmmo = totalAmmo; } /** * @return the type */ public Type getType() { return type; } /** * @return the weaponWeight in pounds */ public int getWeaponWeight() { return weaponWeight; } /** * @return the weaponSightDistance */ public int getLineOfSight() { return lineOfSight; } public int getOwnerId() { return this.owner.getId(); } /** * @return the bulletRange */ public int getBulletRange() { return bulletRange; } /** * @return the owners center position */ public Vector2f getPos() { return this.owner.getCenterPos(); } public void update(TimeStep timeStep) { if ( weaponTime > 0 ) { weaponTime -= timeStep.getDeltaTime(); } else if (!this.isLoaded() && totalAmmo > 0) { reload(); } else { setReadyState(); } gunSwing.update(timeStep); } /** * Swing the gun for a melee attack * @return true if we were able to swing */ public boolean meleeAttack() { if(weaponState == WeaponState.READY) { if(this.gunSwing.beginSwing()) { setMeleeAttack(); this.gunSwing.endSwing(); return true; } } return false; } public void doneMelee() { //if(this.gunSwing.isSwinging()) { this.gunSwing.endSwing(); } } /** * @return true if we are currently melee attacking */ public boolean isMeleeAttacking() { return this.gunSwing.isSwinging(); } /** * @return true if this weapon is ready to fire/use */ public boolean isReady() { return weaponState == WeaponState.READY; } /** * @return true if this weapon is switching */ public boolean isSwitchingWeapon() { return weaponState == WeaponState.SWITCHING; } /** * @return true if this weapon is currently firing */ public boolean isFiring() { return weaponState == WeaponState.FIRING; } /** * @return true if this weapon is currently reloading */ public boolean isReloading() { return weaponState == WeaponState.RELOADING; } /** * @return the bulletsInClip */ public int getBulletsInClip() { return bulletsInClip; } /** * @return the totalAmmo */ public int getTotalAmmo() { return totalAmmo; } /** * @return the clipSize */ public int getClipSize() { return clipSize; } protected void setMeleeAttack() { weaponState = WeaponState.MELEE_ATTACK; weaponTime = 200; } protected void setReadyState() { this.weaponState = WeaponState.READY; } protected void setReloadingState() { weaponState = WeaponState.RELOADING; } protected void setWaitingState() { weaponState = WeaponState.WAITING; } public void setSwitchingWeaponState() { weaponState = WeaponState.SWITCHING; weaponTime = 900; game.emitSound(getOwnerId(), SoundType.WEAPON_SWITCH, getPos()); } protected void setFireState() { weaponState = WeaponState.FIRING; // this.fired = false; } protected void setFireEmptyState() { if(getState() != Weapon.WeaponState.FIRE_EMPTY) { game.emitSound(getOwnerId(), SoundType.EMPTY_FIRE, getPos()); } this.weaponTime = 500; weaponState = WeaponState.FIRE_EMPTY; // this.fired = false; } /** * @return the weaponState */ public WeaponState getState() { return weaponState; } /** * Invoked for when the trigger is held down * @return true if the weapon discharged */ public boolean beginFire() { return false; } /** * Invoked when the trigger is done being pulled. * @return true if the weapon discharged */ public boolean endFire() { return false; } /** * @return true if this weapon is loaded and ready to fire */ public boolean canFire() { return weaponTime <= 0 && bulletsInClip > 0; } /** * @return true if this weapon is ready for a melee attack at this moment. */ public boolean canMelee() { return this.gunSwing.canSwing(); } /** * @return true if any bullets are current in the clip */ public boolean isLoaded() { return bulletsInClip > 0; } /** * Calculates the velocity of the projectile discharged from the weapon. * @param facing * @return the velocity */ protected abstract Vector2f calculateVelocity(Vector2f facing); /** * Attempts to reload the weapon * @return true if reloading was activated; false otherwise */ public boolean reload() { if (bulletsInClip < clipSize && weaponTime <= 0) { if(totalAmmo > 0) { weaponTime = reloadTime; bulletsInClip = (totalAmmo < clipSize) ? totalAmmo : clipSize; totalAmmo -= bulletsInClip; setReloadingState(); return true; } } return false; } public void addAmmo(int amount) { totalAmmo += amount; } /** * @return the damageMultiplier */ public int getDamageMultiplier() { return damageMultiplier; } /** * @param bulletSpawnDistance the bulletSpawnDistance to set */ public void setBulletSpawnDistance(float bulletSpawnDistance) { this.bulletSpawnDistance = bulletSpawnDistance; } /** * @return the distance of the bullet spawn point from the owners origin */ public float getBulletSpawnDistance() { return this.bulletSpawnDistance; } /** * @return the position where the bullet spawns */ protected Vector2f newBulletPosition() { Vector2f ownerDir = owner.getFacing(); Vector2f ownerPos = owner.getCenterPos(); Vector2f pos = new Vector2f(ownerPos.x + ownerDir.x * getBulletSpawnDistance() , ownerPos.y + ownerDir.y * getBulletSpawnDistance()); return pos; } /** * @return creates a new {@link Bullet} that is not piercing */ protected Bullet newBullet() { return newBullet(false); } /** * Creates a new {@link Bullet} * @param isPiercing * @return the {@link Bullet} */ protected Bullet newBullet(boolean isPiercing) { Vector2f pos = newBulletPosition(); Vector2f vel = calculateVelocity(owner.getFacing()); final int speed = 1500 + (random.nextInt(10) * 100); Bullet bullet = new Bullet(pos, speed, game, owner, vel, damage + getDamageMultiplier(), isPiercing); bullet.setMaxDistance(getBulletRange()); game.addEntity(bullet); game.getStatSystem().onBulletFired(owner); return bullet; } /** * @param rocketSpawnDistance the rocketSpawnDistance to set */ public void setRocketSpawnDistance(float rocketSpawnDistance) { this.rocketSpawnDistance = rocketSpawnDistance; } /** * The distance from the owners location where the rocket is spawned * @return the distance from the owner to where the rocket is spawned */ public float getRocketSpawnDistance() { return this.rocketSpawnDistance; } /** * @return the position where the new Rocket is spawned */ protected Vector2f newRocketPosition() { Vector2f ownerDir = owner.getFacing(); Vector2f ownerPos = owner.getCenterPos(); Vector2f pos = new Vector2f(ownerPos.x + ownerDir.x * getRocketSpawnDistance(), ownerPos.y + ownerDir.y * getRocketSpawnDistance()); return pos; } /** * Spawns a new {@link Rocket} * @return the {@link Rocket} */ protected Rocket newRocket() { Vector2f pos = newRocketPosition(); Vector2f vel = calculateVelocity(owner.getFacing()); final int speed = 650; final int splashDamage = 80; Rocket bullet = new Rocket(pos, speed, game, owner, vel, damage, splashDamage); game.addEntity(bullet); game.getStatSystem().onBulletFired(owner); return bullet; } /** * @param grenadeSpawnDistance the grenadeSpawnDistance to set */ public void setGrenadeSpawnDistance(float grenadeSpawnDistance) { this.grenadeSpawnDistance = grenadeSpawnDistance; } /** * @return the distance the grenade spawns from the owners origin */ public float getGenadeSpawnDistance() { return this.grenadeSpawnDistance; } /** * Spawns a new grenade * @param timePinPulled the time the pin was pulled (effects distance) * @return the {@link Grenade} */ protected Entity newGrenade(Type grenadeType, int timePinPulled) { Vector2f ownerDir = owner.getFacing(); Vector2f ownerPos = owner.getCenterPos(); Vector2f pos = new Vector2f(ownerPos.x + ownerDir.x * getGenadeSpawnDistance() , ownerPos.y + ownerDir.y * getGenadeSpawnDistance()); Vector2f vel = calculateVelocity(owner.getFacing()); final int maxSpeed = 250; int speed = Math.min(120 + (timePinPulled*7), maxSpeed); Entity grenade = null; switch(grenadeType) { case NAPALM_GRENADE: grenade = new NapalmGrenade(pos, speed, game, owner, vel, damage); break; case SMOKE_GRENADE: grenade = new SmokeGrenade(pos, speed, game, owner, vel); break; default: { grenade = new Grenade(pos, speed, game, owner, vel, damage); } } game.addEntity(grenade); return grenade; } /** * Adds a new {@link Explosion} * @param pos * @param owner * @param splashDamage * @return the {@link Explosion} */ protected Explosion newExplosion(Vector2f pos, int splashDamage) { return game.newExplosion(pos, owner, splashDamage); } /** * Creates a new {@link Fire} * * @return the {@link Fire} */ protected Fire newFire() { Vector2f pos = newBulletPosition(); Vector2f vel = calculateVelocity(owner.getFacing()); final int speed = 230 + (random.nextInt(10) * 1); Fire fire = new Fire(pos, speed, game, owner, vel, damage); game.addEntity(fire); return fire; } /** * Calculates the accuracy of the shot based on the owner {@link Entity}'s weaponState. * * <p> * The more still you are, the more accurate you are. * * @param facing * @param standardAccuracy * @return the altered 'standardAccuracy' value */ protected int calculateAccuracy(Vector2f facing, int standardAccuracy) { int newAccuracy = standardAccuracy; switch(owner.getCurrentState()) { case CROUCHING: newAccuracy = standardAccuracy / 5; break; case IDLE: newAccuracy = standardAccuracy / 2; break; case RUNNING: newAccuracy = standardAccuracy + (standardAccuracy/4); break; case SPRINTING: newAccuracy = standardAccuracy * 3; break; case WALKING: newAccuracy = standardAccuracy - (standardAccuracy/4); break; default: newAccuracy = standardAccuracy * 10; } if(newAccuracy<0) { newAccuracy = 0; } return newAccuracy; } /** * Calculates a random velocity given a facing and a maxSpread value. * @param facing * @param maxSpread * @return a rotated vector of the supplied facing randomized between -maxSpread and maxSpread */ protected Vector2f spread(Vector2f facing, int maxSpread) { maxSpread = calculateAccuracy(facing, maxSpread); double rd = Math.toRadians(random.nextInt(maxSpread)); int sd = random.nextInt(2); return sd>0 ? facing.rotate(rd) : facing.rotate(-rd); } public NetWeapon getNetWeapon() { netWeapon.ammoInClip = (byte)bulletsInClip; netWeapon.totalAmmo = (short)totalAmmo; netWeapon.weaponState = weaponState; return this.netWeapon; } }
18,124
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Springfield.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Springfield.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.WeaponConstants; /** * @author Tony * */ public class Springfield extends Weapon { private boolean reloading; private boolean wasReloading; private boolean endFire; /** * @param game * @param owner */ public Springfield(Game game, Entity owner) { super(game, owner, Type.SPRINGFIELD); this.damage = 100; this.reloadTime = 1200; this.clipSize = 5; this.totalAmmo = 35; this.spread = 5; this.bulletsInClip = this.clipSize; this.weaponWeight = WeaponConstants.SPRINGFIELD_WEIGHT; this.lineOfSight = WeaponConstants.SPRINGFIELD_LINE_OF_SIGHT; this.reloading = false; this.endFire = true; applyScriptAttributes("springfield"); } /* (non-Javadoc) * @see palisma.game.Weapon#update(leola.live.TimeStep) */ @Override public void update(TimeStep timeStep) { super.update(timeStep); if (reloading && bulletsInClip < clipSize) { reload(); } else { reloading = false; if(wasReloading) { game.emitSound(getOwnerId(), SoundType.SPRINGFIELD_RECHAMBER, getPos()); wasReloading = false; } } } /* (non-Javadoc) * @see palisma.game.Weapon#reload() */ @Override public boolean reload() { if (bulletsInClip < clipSize && weaponTime <= 0) { if ( totalAmmo > 0) { weaponTime = reloadTime; bulletsInClip++; totalAmmo--; reloading = true; wasReloading = true; setReloadingState(); game.emitSound(getOwnerId(), SoundType.SPRINGFIELD_RELOAD, getPos()); return true; } } // else { // setWaitingState(); // } return false; } /* (non-Javadoc) * @see palisma.game.Weapon#beginFire() */ @Override public boolean beginFire() { if ( canFire() ) { game.emitSound(getOwnerId(), SoundType.SPRINGFIELD_FIRE, getPos()); game.emitSound(getOwnerId(), SoundType.SPRINGFIELD_RECHAMBER, getPos()); newBullet(true); bulletsInClip--; weaponTime = 1300; setFireState(); return true; } else if (reloading) { reloading = false; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } this.endFire = false; return false; } /* (non-Javadoc) * @see palisma.game.Weapon#endFire() */ @Override public boolean endFire() { this.endFire = true; if(isFiring()) { game.emitSound(getOwnerId(), SoundType.BULLET_SHELL, owner.getPos()); } return false; } @Override public boolean canFire() { return super.canFire() && this.endFire; } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(palisma.game.Direction) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return spread(facing, spread); } }
3,900
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Smoke.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Smoke.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.net.NetEntity; import seventh.game.net.NetSmoke; import seventh.map.Map; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.TimeStep; /** * @author Tony * */ public class Smoke extends Entity { private NetSmoke netEntity; private long torchTime; private Vector2f targetVel; /** * @param position * @param speed * @param game * @param type */ public Smoke(Vector2f position, int speed, Game game, final Vector2f targetVel) { super(position, speed, game, Type.SMOKE); this.targetVel = targetVel; this.bounds.width = 4; this.bounds.height = 4; this.torchTime = 10_000; this.netEntity = new NetSmoke(); this.collisionHeightMask = 0; } /* (non-Javadoc) * @see palisma.game.Entity#update(leola.live.TimeStep) */ @Override public boolean update(TimeStep timeStep) { this.vel.set(this.targetVel); boolean isBlocked = super.update(timeStep); Map map = game.getMap(); // grow the hit box // TODO: Hide players who // are within the bounds of smoke // to prevent cheating!! if(bounds.width < 64) { bounds.width += 1; if( map.rectCollides(bounds, 0) ) { isBlocked = true; bounds.width -= 1; } } if(bounds.height < 64) { bounds.height += 1; if( map.rectCollides(bounds, 0)) { isBlocked = true; bounds.height -= 1; } } torchTime -= timeStep.getDeltaTime(); if(torchTime <= 0 ) { kill(this); } if(this.speed > 0) { this.speed -= 1; } int min = 10; if(speed < min) { speed = min; } //DebugDraw.drawRectRelative(this.bounds, 0x0a00ffff); return isBlocked; } protected void decreaseSpeed(float factor) { speed = (int)(speed * factor); } /* (non-Javadoc) * @see palisma.game.Entity#collideX(int, int) */ @Override protected boolean collideX(int newX, int oldX) { this.targetVel.x = -this.targetVel.x; this.speed = (int)(this.speed * 0.7f); return true; } /* (non-Javadoc) * @see palisma.game.Entity#collideY(int, int) */ @Override protected boolean collideY(int newY, int oldY) { this.targetVel.y = -this.targetVel.y; this.speed = (int)(this.speed * 0.7f); return true; } @Override protected boolean collidesAgainstEntity(Rectangle bounds) { return false; } /* (non-Javadoc) * @see seventh.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { return getNetSmokeEntity(); } public NetEntity getNetSmokeEntity() { setNetEntity(netEntity); return this.netEntity; } }
3,387
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Explosion.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Explosion.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.net.NetEntity; import seventh.game.net.NetExplosion; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; /** * @author Tony * */ public class Explosion extends Entity { private int damage; private Entity owner; private NetExplosion netEntity; private long explositionTime; private Rectangle center; private boolean checkedDestructableTiles; /** * @param position * @param speed * @param game * @param type */ public Explosion(Vector2f position, int speed, Game game, Entity owner, final int damage) { super(position, speed, game, Type.EXPLOSION); bounds.width = 60; bounds.height = 60; bounds.centerAround(position); center = new Rectangle(); center.width = bounds.width/3; center.height = bounds.height/3; center.centerAround(position); this.damage = damage; this.owner = owner; game.emitSound(getId(), SoundType.EXPLOSION, getCenterPos()); this.explositionTime = 550; this.checkedDestructableTiles = false; this.netEntity = new NetExplosion(); this.onTouch = new OnTouchListener() { @Override public void onTouch(Entity me, Entity other) { if(other.getType() != Type.EXPLOSION && other.canTakeDamage()) { /* if this poor fellow is caught in the center * of the blast they feel the full effect */ if(other.getBounds().intersects(center)) { other.damage(Explosion.this, damage); } else { /* splash damage is applied each frame, * very deadly */ other.damage(Explosion.this, 2); } } } }; } /** * @return the owner */ public Entity getOwner() { return owner; } /** * @return the damage */ public int getDamage() { return damage; } /* (non-Javadoc) * @see palisma.game.Entity#update(leola.live.TimeStep) */ @Override public boolean update(TimeStep timeStep) { super.update(timeStep); if(!this.checkedDestructableTiles) { Vector2f center = getPos(); game.removeTileAtWorld((int)center.x, (int)center.y); this.checkedDestructableTiles = true; } game.doesTouchPlayers(this); explositionTime -= timeStep.getDeltaTime(); if(explositionTime <= 0 ) { kill(this); } return false; } /* (non-Javadoc) * @see seventh.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { return getNetExplotionEntity(); } public NetEntity getNetExplotionEntity() { setNetEntity(netEntity); // this.netEntity.damage = (byte)this.damage; if(this.owner!=null) { this.netEntity.ownerId = this.owner.getId(); } return this.netEntity; } }
3,581
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Hammer.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Hammer.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.PlayerInfo; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.WeaponConstants; /** * Allows a player to construct things * * @author Tony * */ public class Hammer extends Weapon { private Vector2f tilePos; private boolean endFire; /** * @param game * @param owner * @param type */ public Hammer(Game game, Entity owner) { super(game, owner, Type.HAMMER); this.tilePos = new Vector2f(); this.endFire = true; this.bulletsInClip = 1; this.weaponWeight = WeaponConstants.HAMMER_WEIGHT; this.lineOfSight = WeaponConstants.HAMMER_LINE_OF_SIGHT; } /** * Attempts to build a tile */ private boolean placeTile() { if(owner != null) { Vector2f.Vector2fMA(owner.getCenterPos(), owner.getFacing(), 38f, tilePos); // TODO: Pick the current tile the user has // TODO: Only allow if current weapon is Hammer PlayerInfo player = game.getPlayerById(owner.getId()); if(player != null) { return game.addTile(player.getActiveTile(), tilePos); } } return false; } @Override public boolean beginFire() { if(canFire() && placeTile()) { game.emitSound(getOwnerId(), SoundType.HAMMER_SWING, getPos()); weaponTime = 300; setFireState(); this.endFire = false; return true; } return false; } @Override public boolean endFire() { this.endFire = true; return super.endFire(); } @Override public boolean canFire() { return super.canFire() && this.endFire; } @Override protected Vector2f calculateVelocity(Vector2f facing) { return spread(facing, 0); } }
2,197
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
M1Garand.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/M1Garand.java
/* * The Seventh * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.WeaponConstants; /** * @author Tony * */ public class M1Garand extends Weapon { private boolean endFire; /** * @param game * @param owner * @param type */ public M1Garand(Game game, Entity owner) { super(game, owner, Type.M1_GARAND); this.damage = 50; this.reloadTime = 1500; this.clipSize = 8; this.totalAmmo = 40; this.bulletsInClip = this.clipSize; this.spread = 8; this.lineOfSight = WeaponConstants.M1GARAND_LINE_OF_SIGHT; this.weaponWeight = WeaponConstants.M1GARAND_WEIGHT; this.endFire = true; applyScriptAttributes("m1_garand"); } /* (non-Javadoc) * @see seventh.game.Weapon#reload() */ @Override public boolean reload() { boolean reloaded = false; if(bulletsInClip<=0) { reloaded = super.reload(); if(reloaded) { game.emitSound(getOwnerId(), SoundType.M1_GARAND_RELOAD, getPos()); } } return reloaded; } /* (non-Javadoc) * @see palisma.game.Weapon#beginFire() */ @Override public boolean beginFire() { if(canFire()) { newBullet(); weaponTime = 200; bulletsInClip--; if(bulletsInClip==0) { game.emitSound(getOwnerId(), SoundType.M1_GARAND_LAST_FIRE, getPos()); } else { game.emitSound(getOwnerId(), SoundType.M1_GARAND_FIRE, getPos()); } setFireState(); return true; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } this.endFire = false; return false; } @Override public boolean endFire() { this.endFire = true; if(isFiring()) { game.emitSound(getOwnerId(), SoundType.BULLET_SHELL, owner.getPos()); } return false; } @Override public boolean canFire() { return super.canFire() && this.endFire; } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(palisma.game.Direction) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return spread(facing, spread); } }
2,838
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
MG42.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/MG42.java
/* * see license.txt */ package seventh.game.weapons; import leola.vm.types.LeoMap; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.WeaponConstants; /** * The mechs rail gun * * @author Tony * */ public class MG42 extends Weapon { private int roundsPerSecond; private long heatTime; private long maxHeat; /** * @param game * @param owner * @param type */ public MG42(Game game, Entity owner) { super(game, owner, Type.MG42); this.roundsPerSecond = 15; this.damage = 40; this.reloadTime = 1600; this.clipSize = 30; this.totalAmmo = 180; this.spread = 10; this.maxHeat = 3000; this.bulletsInClip = this.clipSize; this.lineOfSight = WeaponConstants.THOMPSON_LINE_OF_SIGHT; this.weaponWeight = WeaponConstants.THOMPSON_WEIGHT; applyScriptAttributes("railgun"); } /* (non-Javadoc) * @see seventh.game.weapons.Weapon#applyScriptAttributes(java.lang.String) */ @Override protected LeoMap applyScriptAttributes(String weaponName) { LeoMap attributes = super.applyScriptAttributes(weaponName); if(attributes!=null) { this.roundsPerSecond = attributes.getInt("rounds_per_second"); this.maxHeat = attributes.getInt("max_heat"); } return attributes; } /* (non-Javadoc) * @see seventh.game.weapons.Weapon#update(seventh.shared.TimeStep) */ @Override public void update(TimeStep timeStep) { super.update(timeStep); if(isFiring()) { this.heatTime += timeStep.getDeltaTime(); } else if(this.heatTime > 0) { this.heatTime -= timeStep.getDeltaTime(); } } /** * @return true if this gun is over heated */ public boolean isOverheated() { return this.heatTime >= this.maxHeat; } /* (non-Javadoc) * @see seventh.game.weapons.Weapon#reload() */ @Override public boolean reload() { return false; } /* (non-Javadoc) * @see palisma.game.Weapon#beginFire() */ @Override public boolean beginFire() { if(canFire() && !isOverheated()) { newBullet(); game.emitSound(getOwnerId(), SoundType.MG42_FIRE, getPos()); weaponTime = 1000/roundsPerSecond; setFireState(); return true; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } return false; } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(palisma.game.Direction) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return spread(facing, spread); } }
3,104
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
MP40.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/MP40.java
/* * see license.txt */ package seventh.game.weapons; import leola.vm.types.LeoMap; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.WeaponConstants; /** * @author Tony * */ public class MP40 extends Weapon { private int roundsPerSecond; /** * @param game * @param owner */ public MP40(Game game, Entity owner) { super(game, owner, Type.MP40); this.roundsPerSecond = 7; this.damage = 20; this.reloadTime = 1800; this.clipSize = 32; this.totalAmmo = 190; this.spread = 9; this.bulletsInClip = this.clipSize; this.lineOfSight = WeaponConstants.MP40_LINE_OF_SIGHT; this.weaponWeight = WeaponConstants.MP40_WEIGHT; applyScriptAttributes("mp40"); } /* (non-Javadoc) * @see seventh.game.weapons.Weapon#applyScriptAttributes(java.lang.String) */ @Override protected LeoMap applyScriptAttributes(String weaponName) { LeoMap attributes = super.applyScriptAttributes(weaponName); if(attributes!=null) { this.roundsPerSecond = attributes.getInt("rounds_per_second"); } return attributes; } /* (non-Javadoc) * @see seventh.game.Weapon#reload() */ @Override public boolean reload() { boolean reloaded = super.reload(); if(reloaded) { game.emitSound(getOwnerId(), SoundType.MP40_RELOAD, getPos()); } return reloaded; } /* (non-Javadoc) * @see palisma.game.Weapon#beginFire() */ @Override public boolean beginFire() { if(canFire()) { newBullet(); game.emitSound(getOwnerId(), SoundType.MP40_FIRE, getPos()); weaponTime = 1000/roundsPerSecond; bulletsInClip--; setFireState(); return true; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } return false; } /* (non-Javadoc) * @see seventh.game.weapons.Weapon#endFire() */ @Override public boolean endFire() { if(isFiring()) { game.emitSound(getOwnerId(), SoundType.BULLET_SHELL, owner.getPos()); } return super.endFire(); } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(palisma.game.Direction) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return spread(facing, spread); } }
2,869
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
RocketLauncher.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/RocketLauncher.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.WeaponConstants; /** * @author Tony * */ public class RocketLauncher extends Weapon { private boolean endFire; /** * @param game * @param owner */ public RocketLauncher(Game game, Entity owner) { super(game, owner, Type.ROCKET_LAUNCHER); this.damage = 120; this.reloadTime = 0; this.clipSize = 5; this.totalAmmo = 0; this.bulletsInClip = this.clipSize; this.lineOfSight = WeaponConstants.RPG_LINE_OF_SIGHT; this.weaponWeight = WeaponConstants.RPG_WEIGHT; this.endFire = true; applyScriptAttributes("rocket_launcher"); } @Override public boolean isHeavyWeapon() { return true; } /** * Emits the fire rocket sound */ protected void emitFireSound() { game.emitSound(getOwnerId(), SoundType.RPG_FIRE, getPos()); } /* * (non-Javadoc) * @see seventh.game.weapons.Weapon#beginFire() */ @Override public boolean beginFire() { if(canFire()) { newRocket(); emitFireSound(); bulletsInClip--; weaponTime = 1500; setFireState(); return true; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } // else { // setWaitingState(); // } return false; } /* (non-Javadoc) * @see palisma.game.Weapon#endFire() */ @Override public boolean endFire() { this.endFire = true; return false; } /* * (non-Javadoc) * @see seventh.game.weapons.Weapon#canFire() */ @Override public boolean canFire() { return super.canFire() && this.endFire; } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(palisma.game.Direction) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return facing.createClone(); } }
2,305
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Kar98.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Kar98.java
/* * The Seventh * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.WeaponConstants; /** * @author Tony * */ public class Kar98 extends Weapon { private boolean wasReloading; private boolean endFire; /** * @param game * @param owner */ public Kar98(Game game, Entity owner) { super(game, owner, Type.KAR98); this.damage = 100; this.reloadTime = 2500; this.clipSize = 5; this.totalAmmo = 35; this.bulletsInClip = this.clipSize; this.spread = 5; this.weaponWeight = WeaponConstants.KAR98_WEIGHT; this.lineOfSight = WeaponConstants.KAR98_LINE_OF_SIGHT; this.endFire = true; applyScriptAttributes("kar98"); } /* (non-Javadoc) * @see palisma.game.Weapon#update(leola.live.TimeStep) */ @Override public void update(TimeStep timeStep) { super.update(timeStep); if(wasReloading) { //game.emitSound(getOwnerId(), SoundType.KAR98_RECHAMBER, getPos()); if(weaponTime<=0) { wasReloading = false; game.emitSound(getOwnerId(), SoundType.KAR98_RECHAMBER, getPos()); } } } /* (non-Javadoc) * @see palisma.game.Weapon#reload() */ @Override public boolean reload() { boolean reloaded = super.reload(); if(reloaded) { wasReloading = true; game.emitSound(getOwnerId(), SoundType.KAR98_RELOAD, getPos()); } return reloaded; } @Override public boolean beginFire() { if ( canFire() ) { game.emitSound(getOwnerId(), SoundType.KAR98_FIRE, getPos()); game.emitSound(getOwnerId(), SoundType.KAR98_RECHAMBER, getPos()); newBullet(true); bulletsInClip--; weaponTime = 900; setFireState(); return true; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } this.endFire = false; return false; } /* (non-Javadoc) * @see palisma.game.Weapon#endFire() */ @Override public boolean endFire() { this.endFire = true; if(isFiring()) { game.emitSound(getOwnerId(), SoundType.BULLET_SHELL, owner.getPos()); } return false; } @Override public boolean canFire() { return super.canFire() && this.endFire; } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(palisma.game.Direction) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return spread(facing, spread); } }
3,220
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Fire.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Fire.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.net.NetEntity; import seventh.game.net.NetFire; import seventh.map.Map; import seventh.math.Rectangle; import seventh.math.Vector2f; import seventh.shared.TimeStep; /** * @author Tony * */ public class Fire extends Entity { private int damage; private Entity owner; private NetFire netEntity; private long torchTime; private Vector2f targetVel; /** * @param position * @param speed * @param game * @param type */ public Fire(Vector2f position, int speed, Game game, Entity owner, final Vector2f targetVel, final int damage) { super(position, speed, game, Type.FIRE); bounds.width = 8; bounds.height = 8; this.damage = damage; this.owner = owner; this.torchTime = 3_000; this.targetVel = targetVel; this.collisionHeightMask = 0; this.netEntity = new NetFire(); this.onTouch = new OnTouchListener() { @Override public void onTouch(Entity me, Entity other) { if(other.getType() == Type.PLAYER && other.canTakeDamage()) { other.damage(Fire.this, 2); } decreaseSpeed(0.0f); } }; } /** * @return the owner */ public Entity getOwner() { return owner; } /** * @return the damage */ public int getDamage() { return damage; } /* (non-Javadoc) * @see seventh.game.weapons.Bullet#getOwnerHeightMask() */ // @Override // protected int getOwnerHeightMask() { // return 1; // } /* (non-Javadoc) * @see palisma.game.Entity#update(leola.live.TimeStep) */ @Override public boolean update(TimeStep timeStep) { this.vel.set(this.targetVel); boolean isBlocked = super.update(timeStep); Map map = game.getMap(); // grow the hit box // TODO: Hide players who // are within the bounds of smoke // to prevent cheating!! if(bounds.width < 64) { bounds.width += 1; if( map.rectCollides(bounds, 0) ) { isBlocked = true; bounds.width -= 1; } } if(bounds.height < 64) { bounds.height += 1; if( map.rectCollides(bounds, 0)) { isBlocked = true; bounds.height -= 1; } } torchTime -= timeStep.getDeltaTime(); if(torchTime <= 0 ) { kill(this); } if(this.speed > 0) { this.speed -= 1; } if(speed < 0) { speed = 0; } game.doesTouchPlayers(this); // DebugDraw.drawRectRelative(this.bounds, 0x0a00ffff); return isBlocked; } @Override protected boolean collidesAgainstEntity(Rectangle bounds) { return collidesAgainstDoor(bounds) || collidesAgainstVehicle(bounds); } protected void decreaseSpeed(float factor) { speed = (int)(speed * factor); } /* (non-Javadoc) * @see palisma.game.Entity#collideX(int, int) */ @Override protected boolean collideX(int newX, int oldX) { // this.targetVel.x = -this.targetVel.x; this.speed = (int)(this.speed * 0.7f); return true; } /* (non-Javadoc) * @see palisma.game.Entity#collideY(int, int) */ @Override protected boolean collideY(int newY, int oldY) { // this.targetVel.y = -this.targetVel.y; this.speed = (int)(this.speed * 0.7f); return true; } /* (non-Javadoc) * @see seventh.game.Entity#getNetEntity() */ @Override public NetEntity getNetEntity() { return getNetFireEntity(); } public NetEntity getNetFireEntity() { setNetEntity(netEntity); this.netEntity.ownerId = this.owner.getId(); return this.netEntity; } }
4,509
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Thompson.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Thompson.java
/* * see license.txt */ package seventh.game.weapons; import leola.vm.types.LeoMap; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.WeaponConstants; /** * @author Tony * */ public class Thompson extends Weapon { private int roundsPerSecond; /** * @param game * @param owner */ public Thompson(Game game, Entity owner) { super(game, owner, Type.THOMPSON); this.roundsPerSecond = 7; this.damage = 21; this.reloadTime = 1600; this.clipSize = 30; this.totalAmmo = 180; this.spread = 8; this.bulletsInClip = this.clipSize; this.lineOfSight = WeaponConstants.THOMPSON_LINE_OF_SIGHT; this.weaponWeight = WeaponConstants.THOMPSON_WEIGHT; applyScriptAttributes("thompson"); this.bulletsInClip = this.clipSize; } /* (non-Javadoc) * @see seventh.game.weapons.Weapon#applyScriptAttributes(java.lang.String) */ @Override protected LeoMap applyScriptAttributes(String weaponName) { LeoMap attributes = super.applyScriptAttributes(weaponName); if(attributes!=null) { this.roundsPerSecond = attributes.getInt("rounds_per_second"); } return attributes; } /* (non-Javadoc) * @see seventh.game.Weapon#reload() */ @Override public boolean reload() { boolean reloaded = super.reload(); if(reloaded) { game.emitSound(getOwnerId(), SoundType.THOMPSON_RELOAD, getPos()); } return reloaded; } /* (non-Javadoc) * @see palisma.game.Weapon#beginFire() */ @Override public boolean beginFire() { if(canFire()) { newBullet(); game.emitSound(getOwnerId(), SoundType.THOMPSON_FIRE, getPos()); weaponTime = 1000/roundsPerSecond; bulletsInClip--; setFireState(); return true; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } return false; } @Override public boolean endFire() { if(isFiring()) { game.emitSound(getOwnerId(), SoundType.BULLET_SHELL, owner.getPos()); } return super.endFire(); } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(palisma.game.Direction) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return spread(facing, spread); } }
2,863
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
NapalmGrenade.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/NapalmGrenade.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.math.Vector2f; /** * @author Tony * */ public class NapalmGrenade extends Grenade { /** * @param position * @param speed * @param game * @param owner * @param targetVel * @param damage */ public NapalmGrenade(Vector2f position, int speed, final Game game, final Entity owner, Vector2f targetVel, final int damage) { super(position, speed, game, owner, targetVel, damage); setType(Type.NAPALM_GRENADE); this.onKill = new KilledListener() { @Override public void onKill(Entity entity, Entity killer) { game.newBigFire(getCenterPos(), owner, damage); } }; } }
894
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Rocket.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Rocket.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.net.NetBullet; import seventh.game.net.NetRocket; import seventh.math.Vector2f; /** * @author Tony * */ public class Rocket extends Bullet { private NetRocket netRocket; /** * @param position * @param speed * @param game * @param owner * @param targetVel * @param damage * @param splashDamage */ public Rocket(final Vector2f position, final int speed, final Game game, final Entity owner, final Vector2f targetVel, final int damage, final int splashDamage) { super(position, speed, game, owner, targetVel, damage, false ); this.setOrientation(owner.getOrientation()); this.bounds.width = 8; this.bounds.height = 10; this.netRocket = new NetRocket(); setType(Type.ROCKET); this.onKill = new KilledListener() { @Override public void onKill(Entity entity, Entity killer) { final int splashWidth = 20; final int maxSpread = 25; game.newBigExplosion(position, owner, splashWidth, maxSpread, splashDamage); } }; } /** * Do nothing, rockets shouldn't make impact sounds (the * explosions do that for us) */ @Override protected void emitImpactSound(int x, int y) { // Hack, piggie back off of this code to destroy // any destructable terrain at these coordinates. // we only emit an impact sound when we hit terrain, // so this is safe to put here game.removeTileAtWorld(x, y); } /* (non-Javadoc) * @see seventh.game.weapons.Bullet#getNetBullet() */ @Override public NetBullet getNetBullet() { this.setNetEntity(netRocket); return netRocket; } }
2,108
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Shotgun.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Shotgun.java
/* * see license.txt */ package seventh.game.weapons; import leola.vm.types.LeoMap; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.WeaponConstants; /** * @author Tony * */ public class Shotgun extends Weapon { private int numberOfPellets; private int nextShotTime; private boolean reloading; private boolean wasReloading; private boolean endFire; /** * @param game * @param owner */ public Shotgun(Game game, Entity owner) { super(game, owner, Type.SHOTGUN); this.numberOfPellets = 8; this.damage = 40; this.reloadTime = 1100; this.nextShotTime = 1300; this.clipSize = 5; this.totalAmmo = 35; this.spread = 20; this.bulletsInClip = this.clipSize; this.lineOfSight = WeaponConstants.SHOTGUN_LINE_OF_SIGHT; this.weaponWeight = WeaponConstants.SHOTGUN_WEIGHT; this.reloading =false; this.endFire = true; applyScriptAttributes("shotgun"); } /* (non-Javadoc) * @see seventh.game.weapons.Weapon#applyScriptAttributes(java.lang.String) */ @Override protected LeoMap applyScriptAttributes(String weaponName) { LeoMap attributes = super.applyScriptAttributes(weaponName); if(attributes!=null) { this.numberOfPellets = attributes.getInt("number_of_pellets"); this.nextShotTime = attributes.getInt("next_shot_time"); } return attributes; } /* (non-Javadoc) * @see palisma.game.Weapon#update(leola.live.TimeStep) */ @Override public void update(TimeStep timeStep) { super.update(timeStep); if (reloading && bulletsInClip < clipSize) { reload(); } else { reloading = false; if(wasReloading) { game.emitSound(getOwnerId(), SoundType.SHOTGUN_PUMP, getPos()); wasReloading = false; } } } /* (non-Javadoc) * @see palisma.game.Weapon#reload() */ @Override public boolean reload() { if (bulletsInClip < clipSize && weaponTime <= 0) { if ( totalAmmo > 0) { weaponTime = reloadTime; bulletsInClip++; totalAmmo--; reloading = true; wasReloading = true; setReloadingState(); game.emitSound(getOwnerId(), SoundType.SHOTGUN_RELOAD, getPos()); return true; } } // else { // setWaitingState(); // } return false; } /* (non-Javadoc) * @see palisma.game.Weapon#beginFire() */ @Override public boolean beginFire() { if ( canFire() ) { for(int i = 0; i < numberOfPellets; i++) { newBullet(); } game.emitSound(getOwnerId(), SoundType.SHOTGUN_FIRE, getPos()); game.emitSound(getOwnerId(), SoundType.SHOTGUN_PUMP, getPos()); bulletsInClip--; weaponTime = nextShotTime; setFireState(); return true; } else if (reloading) { reloading = false; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } this.endFire = false; return false; } /* (non-Javadoc) * @see palisma.game.Weapon#endFire() */ @Override public boolean endFire() { this.endFire = true; if(isFiring()) { game.emitSound(getOwnerId(), SoundType.SHOTGUN_SHELL, getPos()); } return false; } @Override public boolean canFire() { return super.canFire() && this.endFire; } /** * the buck-shot spray shouldn't get unweildly, we have to tame it a bit. */ @Override protected int calculateAccuracy(Vector2f facing, int standardAccuracy) { int newAccuracy = super.calculateAccuracy(facing, standardAccuracy); if(newAccuracy>(spread*2)) { newAccuracy=spread*2; } if(newAccuracy<spread) { newAccuracy = spread; } return newAccuracy; } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(palisma.game.Direction) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return spread(facing, spread); } }
5,117
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Risker.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Risker.java
/* * see license.txt */ package seventh.game.weapons; import leola.vm.types.LeoMap; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.WeaponConstants; /** * @author Tony * */ public class Risker extends Weapon { private boolean reloading; private boolean wasReloading; private boolean endFire; private int burst, burstCount; private boolean firing; private long burstRate, burstTime; /** * @param game * @param owner */ public Risker(Game game, Entity owner) { super(game, owner, Type.RISKER); this.damage = 34; // this.reloadTime = 1200; this.reloadTime = 3000; this.clipSize = 21; this.totalAmmo = 42; this.spread = 6; this.burst = 3; this.burstRate=70; this.bulletsInClip = this.clipSize; this.weaponWeight = WeaponConstants.RISKER_WEIGHT; this.lineOfSight = WeaponConstants.RISKER_LINE_OF_SIGHT; this.reloading = false; this.endFire = true; applyScriptAttributes("risker"); this.burstCount = burst; } /* (non-Javadoc) * @see seventh.game.weapons.Weapon#applyScriptAttributes(java.lang.String) */ @Override protected LeoMap applyScriptAttributes(String weaponName) { LeoMap attributes = super.applyScriptAttributes(weaponName); if(attributes!=null) { this.burst = attributes.getInt("burst"); this.burstRate = attributes.getInt("burst_rate"); } return attributes; } /* (non-Javadoc) * @see palisma.game.Weapon#update(leola.live.TimeStep) */ @Override public void update(TimeStep timeStep) { super.update(timeStep); if (reloading && bulletsInClip < clipSize) { reload(); } else { reloading = false; if(wasReloading) { // game.emitSound(getOwnerId(), SoundType.RISKER_RECHAMBER, getPos()); wasReloading = false; } } if(firing) { burstTime-=timeStep.getDeltaTime(); if(burstTime<=0 && bulletsInClip>0) { game.emitSound(getOwnerId(), SoundType.RISKER_FIRE, getPos()); newBullet(false); bulletsInClip--; burstCount--; burstTime=burstRate; if(burstCount<=0) { burstCount = burst; this.firing = false; game.emitSound(getOwnerId(), SoundType.BULLET_SHELL, owner.getPos()); } } } } /* (non-Javadoc) * @see palisma.game.Weapon#reload() */ @Override public boolean reload() { /*if (bulletsInClip < clipSize && weaponTime <= 0) { if ( totalAmmo > 0) { weaponTime = reloadTime; bulletsInClip++; totalAmmo--; reloading = true; wasReloading = true; setReloadingState(); game.emitSound(getOwnerId(), SoundType.RISKER_RELOAD, getPos()); return true; } }*/ boolean reloaded = super.reload(); if(reloaded) { game.emitSound(getOwnerId(), SoundType.RISKER_RELOAD, getPos()); } return reloaded; } /* (non-Javadoc) * @see palisma.game.Weapon#beginFire() */ @Override public boolean beginFire() { if ( canFire() ) { //game.emitSound(getOwnerId(), SoundType.RISKER_FIRE, getPos()); //game.emitSound(getOwnerId(), SoundType.RISKER_RECHAMBER, getPos()); //for(int i = 0; i < 3; i++) { // newBullet(false); // bulletsInClip--; //} weaponTime = 900; this.firing = true; setFireState(); return true; } else if (reloading) { reloading = false; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } this.endFire = false; return false; } /* (non-Javadoc) * @see palisma.game.Weapon#endFire() */ @Override public boolean endFire() { this.endFire = true; return false; } @Override public boolean canFire() { return super.canFire() && this.endFire; } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(palisma.game.Direction) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return spread(facing, spread); } }
5,280
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
MP44.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/MP44.java
/* * see license.txt */ package seventh.game.weapons; import leola.vm.types.LeoMap; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.WeaponConstants; /** * @author Tony * */ public class MP44 extends Weapon { private int roundsPerSecond; /** * @param game * @param owner */ public MP44(Game game, Entity owner) { super(game, owner, Type.MP44); this.damage = 30; // this.reloadTime = 1200; this.reloadTime = 3000; this.clipSize = 21; this.totalAmmo = 42; this.spread = 6; this.bulletsInClip = this.clipSize; this.lineOfSight = WeaponConstants.MP44_LINE_OF_SIGHT; this.weaponWeight = WeaponConstants.MP44_WEIGHT; applyScriptAttributes("mp44"); } /* (non-Javadoc) * @see seventh.game.weapons.Weapon#applyScriptAttributes(java.lang.String) */ @Override protected LeoMap applyScriptAttributes(String weaponName) { LeoMap attributes = super.applyScriptAttributes(weaponName); if(attributes!=null) { this.roundsPerSecond = attributes.getInt("rounds_per_second"); } return attributes; } /* (non-Javadoc) * @see seventh.game.Weapon#reload() */ @Override public boolean reload() { boolean reloaded = super.reload(); if(reloaded) { game.emitSound(getOwnerId(), SoundType.MP44_RELOAD, getPos()); } return reloaded; } /* (non-Javadoc) * @see palisma.game.Weapon#beginFire() */ @Override public boolean beginFire() { if(canFire()) { newBullet(); game.emitSound(getOwnerId(), SoundType.MP44_FIRE, getPos()); weaponTime = 1000/roundsPerSecond; bulletsInClip--; setFireState(); return true; } else if (bulletsInClip <= 0 ) { setFireEmptyState(); } return false; } /* (non-Javadoc) * @see seventh.game.weapons.Weapon#endFire() */ @Override public boolean endFire() { if(isFiring()) { game.emitSound(getOwnerId(), SoundType.BULLET_SHELL, owner.getPos()); } return super.endFire(); } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(palisma.game.Direction) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return spread(facing, spread); } }
2,880
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
SmokeGrenade.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/SmokeGrenade.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; import seventh.shared.Timer; /** * @author Tony * */ public class SmokeGrenade extends Grenade { private Timer emitSmokeTimer; private Timer timeToLive; /** * @param position * @param speed * @param game * @param owner * @param targetVel * @param damage */ public SmokeGrenade(Vector2f position, int speed, final Game game, Entity owner, Vector2f targetVel) { super(position, speed, game, owner, targetVel, 0); setType(Type.SMOKE_GRENADE); this.emitSmokeTimer = new Timer(true, 800).stop(); this.timeToLive = new Timer(false, 10_000 + (game.getRandom().nextInt(10) * 100)).stop(); this.onKill = new KilledListener() { @Override public void onKill(Entity entity, Entity killer) { // final Timer smokeEmitter = new Timer(true, 500) { // public void onFinish(Timer timer) { // Vector2f vel = new Vector2f(1, 0); // Vector2f.Vector2fRotate(vel, Math.toRadians(game.getRandom().nextInt(360)), vel); // game.newSmoke(getPos(), 10, vel, getOwner()); // } // }; // // smokeEmitter.start(); // game.addGameTimer(smokeEmitter); // // final Timer timeToLive = new Timer(false, 5_000 + (game.getRandom().nextInt(10) * 100)) { // public void onFinish(Timer timer) { // smokeEmitter.stop(); // } // }; // // game.addGameTimer(timeToLive); } }; } /* (non-Javadoc) * @see seventh.game.weapons.Grenade#update(seventh.shared.TimeStep) */ @Override public boolean update(TimeStep timeStep) { this.emitSmokeTimer.update(timeStep); this.timeToLive.update(timeStep); if(this.emitSmokeTimer.isOnFirstTime()) { Vector2f vel = new Vector2f(1, 0); Vector2f.Vector2fRotate(vel, Math.toRadians(game.getRandom().nextInt(360)), vel); game.newSmoke(getPos().createClone(), 50, vel, getOwner()); } if(this.timeToLive.isTime()) { kill(this); } if(this.isAlive() && !this.timeToLive.isUpdating()) { return super.update(timeStep); } return true; } @Override protected void onBlowUp() { this.emitSmokeTimer.expire().start(); this.timeToLive.start(); game.emitSound(getId(), SoundType.SMOKE_GRENADE, getCenterPos()); } }
3,015
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
GrenadeBelt.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/GrenadeBelt.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.game.entities.Entity.Type; import seventh.math.Vector2f; import seventh.shared.SoundType; import seventh.shared.TimeStep; /** * The grenade belt holds a set of grenades for launching. * * @author Tony * */ public class GrenadeBelt extends Weapon { public static GrenadeBelt newFrag(Game game, Entity owner, int amount) { GrenadeBelt belt = new GrenadeBelt(game, owner, Type.GRENADE); belt.bulletsInClip = amount; return belt; } public static GrenadeBelt newSmoke(Game game, Entity owner, int amount) { GrenadeBelt belt = new GrenadeBelt(game, owner, Type.SMOKE_GRENADE); belt.bulletsInClip = amount; return belt; } private final int nextShotTime; private int timePinPulled; private boolean isPinPulled; /** * @param game * @param owner */ public GrenadeBelt(Game game, Entity owner) { this(game, owner, Type.GRENADE); } /** * @param game * @param owner * @param grenadeType */ public GrenadeBelt(Game game, Entity owner, Type grenadeType) { super(game, owner, grenadeType); this.nextShotTime = 600; this.damage = 100; this.bulletsInClip = 3; this.totalAmmo = 0; this.clipSize = 0; applyScriptAttributes("grenade_belt"); } @Override public boolean isPrimary() { return false; } public int getNumberOfGrenades() { return this.bulletsInClip; } /** * @return if the pin is pulled */ public boolean isPinPulled() { return this.isPinPulled; } public boolean pullPin() { return beginFire(); } /** * Throws a grenade */ public boolean throwGrenade() { beginFire(); return endFire(); } /* (non-Javadoc) * @see palisma.game.Weapon#update(leola.live.TimeStep) */ @Override public void update(TimeStep timeStep) { super.update(timeStep); if(this.isPinPulled) { this.timePinPulled++; } } /* (non-Javadoc) * @see palisma.game.Weapon#beginFire() */ @Override public boolean beginFire() { if(!this.isPinPulled && canFire()) { this.isPinPulled = true; game.emitSound(getOwnerId(), SoundType.GRENADE_PINPULLED, getPos()); return true; } return super.beginFire(); } /* (non-Javadoc) * @see palisma.game.Weapon#endFire() */ @Override public boolean endFire() { if ( canFire() ) { newGrenade(getType(), timePinPulled); game.emitSound(getOwnerId(), SoundType.GRENADE_THROW, getPos()); bulletsInClip--; weaponTime = nextShotTime; isPinPulled = false; timePinPulled = 0; setFireState(); return true; } return false; } /* (non-Javadoc) * @see palisma.game.Weapon#calculateVelocity(leola.live.math.Vector2f) */ @Override protected Vector2f calculateVelocity(Vector2f facing) { return facing.createClone(); } }
3,483
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
Grenade.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/weapons/Grenade.java
/* * see license.txt */ package seventh.game.weapons; import seventh.game.Game; import seventh.game.entities.Entity; import seventh.math.Vector2f; import seventh.shared.TimeStep; /** * @author Tony * */ public class Grenade extends Bullet { private long blowUpTime; private final int splashWidth; private final int maxSpread; // private final int flightSpeed; /** * @param position * @param speed * @param game * @param type */ public Grenade(final Vector2f position, final int speed, final Game game, final Entity owner, final Vector2f targetVel, final int damage) { super(position, speed, game, owner, targetVel, damage, false ); this.setOrientation(owner.getOrientation()); this.bounds.width = 5; this.bounds.height = 5; this.blowUpTime = 1500; this.splashWidth = 15; this.maxSpread = 25; // this.flightSpeed = 80; setType(Type.GRENADE); this.onKill = new KilledListener() { @Override public void onKill(Entity entity, Entity killer) { game.newBigExplosion(getCenterPos(), owner, splashWidth, maxSpread, damage); } }; this.onTouch = new OnTouchListener() { @Override public void onTouch(Entity me, Entity other) { /* the grenade is being thrown over collidables */ //if(speed < flightSpeed) { targetVel.x = -targetVel.x; targetVel.y = -targetVel.y; decreaseSpeed(0.4f); } } }; } /* (non-Javadoc) * @see seventh.game.weapons.Bullet#getOwnerHeightMask() */ @Override public int getOwnerHeightMask() { return Entity.STANDING_HEIGHT_MASK; } protected void decreaseSpeed(float factor) { speed = (int)(speed * factor); } /* (non-Javadoc) * @see palisma.game.Entity#collideX(int, int) */ @Override protected boolean collideX(int newX, int oldX) { /* the grenade is being thrown over collidables */ // if(this.speed > flightSpeed) { // return false; // } this.targetVel.x = -this.targetVel.x; this.speed = (int)(this.speed * 0.7f); return true; } /* (non-Javadoc) * @see palisma.game.Entity#collideY(int, int) */ @Override protected boolean collideY(int newY, int oldY) { // if(this.speed < flightSpeed) { // return false; // } this.targetVel.y = -this.targetVel.y; this.speed = (int)(this.speed * 0.7f); return true; } /* (non-Javadoc) * @see palisma.game.Bullet#update(leola.live.TimeStep) */ @Override public boolean update(TimeStep timeStep) { boolean isBlocked = super.update(timeStep); this.blowUpTime -= timeStep.getDeltaTime(); if(this.speed > 0) { this.speed -= 5; } if(this.blowUpTime <= 0) { onBlowUp(); } return isBlocked; } protected void onBlowUp() { kill(this); } }
3,531
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
PlayerJoinedListener.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/events/PlayerJoinedListener.java
/* * see license.txt */ package seventh.game.events; import seventh.shared.EventListener; import seventh.shared.EventMethod; /** * Listens for {@link PlayerJoinedEvent}s * * @author Tony * */ public interface PlayerJoinedListener extends EventListener { @EventMethod public void onPlayerJoined(PlayerJoinedEvent event); }
342
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
PlayerLeftListener.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/events/PlayerLeftListener.java
/* * see license.txt */ package seventh.game.events; import seventh.shared.EventListener; import seventh.shared.EventMethod; /** * Listens for {@link PlayerLeftEvent}s * * @author Tony * */ public interface PlayerLeftListener extends EventListener { @EventMethod public void onPlayerLeft(PlayerLeftEvent event); }
334
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z
FlagReturnedListener.java
/FileExtraction/Java_unseen/tonysparks_seventh/src/seventh/game/events/FlagReturnedListener.java
/* * see license.txt */ package seventh.game.events; import seventh.shared.EventListener; import seventh.shared.EventMethod; /** * A flag has been captured * * @author Tony * */ public interface FlagReturnedListener extends EventListener { @EventMethod public void onFlagReturnedEvent(FlagReturnedEvent event); }
333
Java
.java
tonysparks/seventh
49
30
7
2014-05-05T22:57:09Z
2019-11-27T01:44:13Z