Compare commits

..

2 Commits

36 changed files with 837 additions and 426 deletions

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>ace-of-shades</artifactId>
<groupId>nl.andrewlalis</groupId>
<version>0.5.0</version>
<version>0.6.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -9,10 +9,15 @@ import nl.andrewlalis.aos_client.view.GameRenderer;
import nl.andrewlalis.aos_core.model.Player;
import nl.andrewlalis.aos_core.model.Team;
import nl.andrewlalis.aos_core.model.World;
import nl.andrewlalis.aos_core.model.tools.Grenade;
import nl.andrewlalis.aos_core.model.tools.Gun;
import nl.andrewlalis.aos_core.model.tools.Knife;
import nl.andrewlalis.aos_core.net.data.DataTypes;
import nl.andrewlalis.aos_core.net.data.PlayerDetailUpdate;
import nl.andrewlalis.aos_core.net.data.WorldUpdate;
import nl.andrewlalis.aos_core.net.data.tool.GrenadeData;
import nl.andrewlalis.aos_core.net.data.tool.GunData;
import nl.andrewlalis.aos_core.net.data.tool.KnifeData;
import java.io.IOException;
@ -23,7 +28,7 @@ public class Client {
private final MessageTransceiver messageTransceiver;
private World world;
private Player myPlayer;
private Player player;
private final GameRenderer renderer;
private final SoundManager soundManager;
@ -46,7 +51,7 @@ public class Client {
this.messageTransceiver.start();
this.chatManager.bindTransceiver(this.messageTransceiver);
while (this.myPlayer == null || this.world == null) {
while (this.player == null || this.world == null) {
try {
System.out.println("Waiting for server response and player registration...");
Thread.sleep(100);
@ -88,10 +93,12 @@ public class Client {
player.setPosition(p.getPosition());
player.setOrientation(p.getOrientation());
player.setVelocity(p.getVelocity());
player.setGun(new Gun(this.world.getGunTypes().get(p.getGunTypeName())));
if (player.getVelocity().mag() > 0) {
this.soundManager.playWalking(player, myPlayer);
this.soundManager.playWalking(player, null);
}
player.getTools().clear();
player.getTools().add(p.getSelectedTool().toTool(this.world));
player.setSelectedToolIndex(0);
}
}
for (var t : update.getTeamUpdates()) {
@ -100,7 +107,7 @@ public class Client {
team.setScore(t.getScore());
}
}
this.soundManager.play(update.getSoundsToPlay(), myPlayer);
this.soundManager.play(update.getSoundsToPlay(), null);
}
public void setWorld(World world) {
@ -108,11 +115,11 @@ public class Client {
}
public void setPlayer(Player player) {
this.myPlayer = player;
this.player = player;
}
public Player getPlayer() {
return myPlayer;
return this.player;
}
/**
@ -121,19 +128,34 @@ public class Client {
* @param update The updated player information from the server.
*/
public void updatePlayer(PlayerDetailUpdate update) {
if (this.myPlayer == null) return;
this.myPlayer.setHealth(update.getHealth());
this.myPlayer.setReloading(update.isReloading());
this.myPlayer.setGun(new Gun(this.myPlayer.getGun().getType(), update.getGunCurrentClipBulletCount(), update.getGunClipCount()));
if (this.player != null) {
this.player.setHealth(update.getHealth());
this.player.getTools().clear();
for (var td : update.getTools()) {
if (td instanceof KnifeData knifeData) {
this.player.getTools().add(new Knife());
} else if (td instanceof GunData gunData) {
this.player.getTools().add(new Gun(
this.world.getGunTypeById(gunData.getTypeId()),
gunData.getCurrentClipBulletCount(),
gunData.getClipCount(),
gunData.isReloading()
));
} else if (td instanceof GrenadeData grenadeData) {
this.player.getTools().add(new Grenade(grenadeData.getGrenades(), grenadeData.getMaxGrenades()));
}
}
this.player.setSelectedToolIndex(update.getSelectedToolIndex());
}
}
/**
* Sends a player control state message to the server, which indicates that
* the player's controls have been updated, due to a key or mouse event.
*/
public void sendPlayerState() {
public void sendControlState() {
try {
this.messageTransceiver.sendData(DataTypes.PLAYER_CONTROL_STATE, myPlayer.getId(), myPlayer.getState().toBytes());
this.messageTransceiver.sendData(DataTypes.PLAYER_CONTROL_STATE, this.player.getId(), this.player.getState().toBytes());
} catch (IOException e) {
e.printStackTrace();
}

View File

@ -28,7 +28,7 @@ public class PlayerKeyListener extends KeyAdapter {
s.setReloading(false);
s.setSneaking(false);
s.setSprinting(false);
this.client.sendPlayerState();
this.client.sendControlState();
if (e.getKeyChar() == '/') this.chatManager.appendToChat('/');
}
} else if (this.chatManager.isChatting()) {
@ -63,8 +63,12 @@ public class PlayerKeyListener extends KeyAdapter {
state.setSprinting(true);
} else if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
state.setSneaking(true);
} else if (e.getKeyCode() == KeyEvent.VK_Q) {
state.setSelectingPreviousTool(true);
} else if (e.getKeyCode() == KeyEvent.VK_E) {
state.setSelectingNextTool(true);
}
this.client.sendPlayerState();
this.client.sendControlState();
}
@Override
@ -85,7 +89,11 @@ public class PlayerKeyListener extends KeyAdapter {
state.setSprinting(false);
} else if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
state.setSneaking(false);
} else if (e.getKeyCode() == KeyEvent.VK_Q) {
state.setSelectingPreviousTool(false);
} else if (e.getKeyCode() == KeyEvent.VK_E) {
state.setSelectingNextTool(false);
}
this.client.sendPlayerState();
this.client.sendControlState();
}
}

View File

@ -8,6 +8,15 @@ import javax.swing.event.MouseInputAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
/**
* Listens for changes to the player's mouse state. This handles the following
* possible control events:
* <ul>
* <li>Pressing the mouse to use the player's weapon.</li>
* <li>Scrolling the mouse wheel to zoom in or out.</li>
* <li>Moving the mouse to change the player's orientation.</li>
* </ul>
*/
public class PlayerMouseListener extends MouseInputAdapter {
private static final float MOUSE_UPDATES_PER_SECOND = 60.0f;
private static final long MS_PER_MOUSE_UPDATE = (long) (1000.0f / MOUSE_UPDATES_PER_SECOND);
@ -25,16 +34,16 @@ public class PlayerMouseListener extends MouseInputAdapter {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
client.getPlayer().getState().setShooting(true);
client.sendPlayerState();
client.getPlayer().getState().setUsingTool(true);
client.sendControlState();
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
client.getPlayer().getState().setShooting(false);
client.sendPlayerState();
client.getPlayer().getState().setUsingTool(false);
client.sendControlState();
}
}
@ -54,7 +63,7 @@ public class PlayerMouseListener extends MouseInputAdapter {
client.getPlayer().getState().setMouseLocation(centeredMouseLocation);
long now = System.currentTimeMillis();
if (now - this.lastMouseMove > MS_PER_MOUSE_UPDATE) {
client.sendPlayerState();
client.sendControlState();
this.lastMouseMove = now;
}
}
@ -64,10 +73,10 @@ public class PlayerMouseListener extends MouseInputAdapter {
Vec2 c = new Vec2(this.gamePanel.getWidth() / 2.0f, this.gamePanel.getHeight() / 2.0f);
Vec2 centeredMouseLocation = new Vec2(e.getX(), e.getY()).sub(c);
client.getPlayer().getState().setMouseLocation(centeredMouseLocation);
client.getPlayer().getState().setShooting(true);
client.getPlayer().getState().setUsingTool(true);
long now = System.currentTimeMillis();
if (now - this.lastMouseMove > MS_PER_MOUSE_UPDATE) {
client.sendPlayerState();
client.sendControlState();
this.lastMouseMove = now;
}
}

View File

@ -1,8 +1,9 @@
package nl.andrewlalis.aos_client.view;
import nl.andrewlalis.aos_client.net.ChatManager;
import nl.andrewlalis.aos_client.Client;
import nl.andrewlalis.aos_client.net.ChatManager;
import nl.andrewlalis.aos_core.model.*;
import nl.andrewlalis.aos_core.model.tools.Grenade;
import nl.andrewlalis.aos_core.model.tools.Gun;
import nl.andrewlalis.aos_core.net.chat.ChatMessage;
import nl.andrewlalis.aos_core.net.chat.ChatType;
@ -84,7 +85,7 @@ public class GamePanel extends JPanel {
* @param world The world to render.
*/
private void drawWorld(Graphics2D g2, World world) {
Player myPlayer = client.getPlayer();
Player myPlayer = this.client.getPlayer();
if (myPlayer == null) return;
double scale = this.scales[this.scaleIndex];
AffineTransform pre = g2.getTransform();
@ -193,7 +194,9 @@ public class GamePanel extends JPanel {
Color playerColor = p.getTeam() != null ? p.getTeam().getColor() : Color.BLACK;
g2.setColor(playerColor);
g2.fill(dot);
this.drawGun(g2, p.getGun());
if (p.getSelectedTool() instanceof Gun gun) {
this.drawGun(g2, gun);
}
g2.setTransform(pre);
}
}
@ -204,7 +207,7 @@ public class GamePanel extends JPanel {
* @param gun The gun to draw.
*/
private void drawGun(Graphics2D g2, Gun gun) {
g2.setColor(Color.decode(gun.getType().getColor()));
g2.setColor(Color.decode(gun.getType().color()));
Rectangle2D.Double gunBarrel = new Rectangle2D.Double(
0,
0.5,
@ -302,21 +305,35 @@ public class GamePanel extends JPanel {
Player myPlayer = this.client.getPlayer();
if (myPlayer == null) return;
int lineHeight = this.getHeight() - 10;
g2.setColor(Color.WHITE);
if (myPlayer.isReloading()) {
g2.drawString("Reloading...", 5, this.getHeight() - 10);
if (myPlayer.getSelectedTool() != null) {
g2.drawString(myPlayer.getSelectedTool().getName(), 5, lineHeight);
lineHeight -= 10;
}
Gun gun = myPlayer.getGun();
g2.drawString("Clips: " + gun.getClipCount() + " / " + gun.getType().getMaxClipCount(), 5, this.getHeight() - 20);
g2.drawString("Bullets: " + gun.getCurrentClipBulletCount() + " / " + gun.getType().getClipSize(), 5, this.getHeight() - 30);
g2.setColor(Color.GREEN);
g2.drawString(String.format("Health: %.1f", myPlayer.getHealth()), 5, this.getHeight() - 40);
int y = this.getHeight() - 60;
if (myPlayer.getSelectedTool() instanceof Gun gun) {
if (gun.isReloading()) {
g2.drawString("Reloading...", 5, lineHeight);
lineHeight -= 10;
}
g2.drawString("Clips: " + gun.getClipCount() + " / " + gun.getType().maxClipCount(), 5, lineHeight);
lineHeight -= 10;
g2.drawString("Bullets: " + gun.getCurrentClipBulletCount() + " / " + gun.getType().clipSize(), 5, lineHeight);
lineHeight -= 10;
} else if (myPlayer.getSelectedTool() instanceof Grenade grenade) {
g2.drawString(grenade.getGrenadesRemaining() + " / " + grenade.getMaxGrenades() + " grenades", 5, lineHeight);
lineHeight -= 10;
}
g2.setColor(Color.GREEN);
g2.drawString(String.format("Health: %.1f", myPlayer.getHealth()), 5, lineHeight);
lineHeight -= 10;
for (Team t : world.getTeams().values()) {
g2.setColor(t.getColor());
g2.drawString("Team " + t.getName() + ": " + t.getScore(), 5, y);
y -= 15;
g2.drawString("Team " + t.getName() + ": " + t.getScore(), 5, lineHeight);
lineHeight -= 15;
}
}
}

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>ace-of-shades</artifactId>
<groupId>nl.andrewlalis</groupId>
<version>0.5.0</version>
<version>0.6.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -4,9 +4,10 @@ module aos_core {
exports nl.andrewlalis.aos_core.net to aos_server, aos_client;
exports nl.andrewlalis.aos_core.net.chat to aos_client, aos_server;
exports nl.andrewlalis.aos_core.net.data to aos_server, aos_client;
exports nl.andrewlalis.aos_core.net.data.tool to aos_server, aos_client;
exports nl.andrewlalis.aos_core.model to aos_server, aos_client;
exports nl.andrewlalis.aos_core.model.tools to aos_client, aos_server;
exports nl.andrewlalis.aos_core.model.tools to aos_server, aos_client;
exports nl.andrewlalis.aos_core.geom to aos_server, aos_client;
exports nl.andrewlalis.aos_core.util to aos_server, aos_client;

View File

@ -7,17 +7,17 @@ import nl.andrewlalis.aos_core.model.tools.Gun;
* Represents a single projectile bullet fired from a player's gun. When shot by
* a player, a newly-spawned bullet will be initialized with a velocity in the
* general direction of the gun, with some perturbation according to the gun's
* accuracy and player's sprinting/sneaking status.
* inaccuracy and player's sprinting/sneaking status.
*/
public class Bullet extends PhysicsObject {
private final int playerId;
private final Player player;
private final Gun gun;
public Bullet(Player player, float sneakAccuracyModifier, float sprintAccuracyModifier) {
public Bullet(Player player, Gun gun, float sneakAccuracyModifier, float sprintAccuracyModifier) {
this.playerId = player.getId();
this.player = player;
this.gun = player.getGun();
this.gun = gun;
this.setPhysicsProperties(sneakAccuracyModifier, sprintAccuracyModifier);
}
@ -34,14 +34,14 @@ public class Bullet extends PhysicsObject {
.add(player.getOrientation().perp().mul(Player.RADIUS))
);
this.setOrientation(player.getOrientation());
float accuracy = player.getGun().getType().getAccuracy();
float inaccuracy = this.gun.getType().inaccuracy();
if (player.isSneaking()) {
accuracy *= sneakAccuracyModifier;
inaccuracy *= sneakAccuracyModifier;
} else if (player.isSprinting()) {
accuracy *= sprintAccuracyModifier;
inaccuracy *= sprintAccuracyModifier;
}
Vec2 perturbation = Vec2.random(-1, 1).mul(accuracy);
Vec2 localVelocity = this.getOrientation().add(perturbation).mul(player.getGun().getType().getBulletSpeed());
Vec2 perturbation = Vec2.random(-1, 1).mul(inaccuracy);
Vec2 localVelocity = this.getOrientation().add(perturbation).mul(this.gun.getType().bulletSpeed());
this.setVelocity(player.getVelocity().add(localVelocity));
}

View File

@ -2,42 +2,38 @@ package nl.andrewlalis.aos_core.model;
import nl.andrewlalis.aos_core.geom.Vec2;
import nl.andrewlalis.aos_core.model.tools.Gun;
import nl.andrewlalis.aos_core.model.tools.GunType;
import nl.andrewlalis.aos_core.model.tools.Knife;
import nl.andrewlalis.aos_core.model.tools.Tool;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CopyOnWriteArrayList;
public class Player extends PhysicsObject implements Comparable<Player> {
public static final float MOVEMENT_THRESHOLD = 0.001f; // Threshold for stopping movement. Speeds slower than this are reduced to 0.
public static final float RADIUS = 0.5f; // Collision radius, in meters.
public static final float TOOL_CHANGE_TIME = 0.5f; // Cooldown when swapping weapons, in seconds.
private final int id;
private final String name;
private Team team;
private PlayerControlState state;
private Gun gun;
private final List<Tool> tools;
private int selectedToolIndex;
private float health;
private transient long lastShot;
private transient long reloadingStartedAt;
private boolean reloading;
private transient long lastResupply;
private transient long lastToolChange;
// Stats
private transient int killCount;
private transient int deathCount;
private transient int shotCount;
private transient int resupplyCount;
private transient int killStreak;
public Player(int id, String name, Team team, GunType gunType, float maxHealth) {
public Player(int id, String name, Team team, float maxHealth) {
this.id = id;
this.name = name;
this.team = team;
this.state = new PlayerControlState();
this.gun = new Gun(gunType);
this.health = maxHealth;
this.useWeapon();
this.lastShot = System.currentTimeMillis();
this.tools = new CopyOnWriteArrayList<>();
this.tools.add(new Knife());
this.selectedToolIndex = 0;
}
public int getId() {
@ -64,56 +60,47 @@ public class Player extends PhysicsObject implements Comparable<Player> {
this.team = team;
}
public Gun getGun() {
return gun;
public List<Tool> getTools() {
return this.tools;
}
public void setGun(Gun gun) {
this.gun = gun;
public Tool getSelectedTool() {
if (this.tools.isEmpty()) return null;
return this.tools.get(this.selectedToolIndex);
}
public boolean canChangeSelectedTool() {
return System.currentTimeMillis() - this.lastToolChange > TOOL_CHANGE_TIME * 1000;
}
public void setSelectedToolIndex(int index) {
if (index > this.tools.size() - 1) {
index = 0;
} else if (index < 0) {
index = this.tools.size() - 1;
}
this.selectedToolIndex = index;
this.lastToolChange = System.currentTimeMillis();
}
public void selectNextTool() {
this.setSelectedToolIndex(this.selectedToolIndex + 1);
}
public void selectPreviousTool() {
this.setSelectedToolIndex(this.selectedToolIndex - 1);
}
public void setHealth(float health) {
this.health = health;
}
public void setReloading(boolean reloading) {
this.reloading = reloading;
}
public boolean canUseWeapon() {
return this.state.isShooting() &&
!this.state.isReloading() &&
!this.reloading &&
this.gun.getCurrentClipBulletCount() > 0 &&
this.lastShot + ((long) (this.gun.getType().getShotCooldownTime() * 1000)) < System.currentTimeMillis() &&
public boolean canUseGun() {
return this.state.isUsingTool() &&
this.getSelectedTool() instanceof Gun gun && gun.isUsable() &&
(this.getTeam() == null || this.getTeam().getSpawnPoint().dist(this.getPosition()) > Team.SPAWN_RADIUS);
}
public void useWeapon() {
this.lastShot = System.currentTimeMillis();
this.gun.decrementBulletCount();
this.shotCount++;
}
public void startReloading() {
this.reloading = true;
this.reloadingStartedAt = System.currentTimeMillis();
}
public void finishReloading() {
this.gun.reload();
this.reloading = false;
}
public boolean isReloadingComplete() {
long msSinceStart = System.currentTimeMillis() - this.reloadingStartedAt;
return msSinceStart > this.gun.getType().getReloadTime() * 1000;
}
public boolean isReloading() {
return reloading;
}
public boolean canResupply(float resupplyCooldown) {
return this.team != null &&
this.team.getSupplyPoint().dist(this.getPosition()) < Team.SUPPLY_POINT_RADIUS &&
@ -121,10 +108,11 @@ public class Player extends PhysicsObject implements Comparable<Player> {
}
public void resupply(float maxHealth) {
this.lastResupply = System.currentTimeMillis();
this.gun.refillClips();
for (Tool t : this.tools) {
t.resupply();
}
this.health = maxHealth;
this.resupplyCount++;
this.lastResupply = System.currentTimeMillis();
}
public float getHealth() {
@ -137,7 +125,9 @@ public class Player extends PhysicsObject implements Comparable<Player> {
public void respawn(float maxHealth) {
this.resupply(maxHealth);
this.gun.emptyCurrentClip();
for (Tool t : this.tools) {
t.reset();
}
if (this.team != null) {
this.setPosition(this.team.getSpawnPoint().add(Vec2.random(-Team.SPAWN_RADIUS / 2, Team.SPAWN_RADIUS / 2)));
}
@ -153,43 +143,6 @@ public class Player extends PhysicsObject implements Comparable<Player> {
!this.state.isSneaking();
}
public int getKillCount() {
return killCount;
}
public int getDeathCount() {
return deathCount;
}
public int getShotCount() {
return shotCount;
}
public int getResupplyCount() {
return resupplyCount;
}
public int getKillStreak() {
return killStreak;
}
public void incrementDeathCount() {
this.deathCount++;
this.killStreak = 0;
}
public void incrementKillCount() {
this.killCount++;
this.killStreak++;
}
public void resetStats() {
this.killCount = 0;
this.deathCount = 0;
this.shotCount = 0;
this.resupplyCount = 0;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;

View File

@ -1,11 +1,15 @@
package nl.andrewlalis.aos_core.model;
import nl.andrewlalis.aos_core.geom.Vec2;
import nl.andrewlalis.aos_core.net.data.DataTypes;
import java.io.Serializable;
import java.nio.ByteBuffer;
/**
* This object represents the player's controls at a given point in time. This
* object is sent by the client to the server each time the client's inputs
* change somehow.
*/
public class PlayerControlState implements Serializable {
boolean movingLeft;
boolean movingRight;
@ -14,9 +18,12 @@ public class PlayerControlState implements Serializable {
boolean sprinting;
boolean sneaking;
boolean shooting;
boolean usingTool;
boolean reloading;
boolean selectingPreviousTool;
boolean selectingNextTool;
Vec2 mouseLocation;
public boolean isMovingLeft() {
@ -67,12 +74,12 @@ public class PlayerControlState implements Serializable {
this.sneaking = sneaking;
}
public boolean isShooting() {
return shooting;
public boolean isUsingTool() {
return usingTool;
}
public void setShooting(boolean shooting) {
this.shooting = shooting;
public void setUsingTool(boolean usingTool) {
this.usingTool = usingTool;
}
public boolean isReloading() {
@ -83,6 +90,22 @@ public class PlayerControlState implements Serializable {
this.reloading = reloading;
}
public boolean isSelectingPreviousTool() {
return selectingPreviousTool;
}
public void setSelectingPreviousTool(boolean selectingPreviousTool) {
this.selectingPreviousTool = selectingPreviousTool;
}
public boolean isSelectingNextTool() {
return selectingNextTool;
}
public void setSelectingNextTool(boolean selectingNextTool) {
this.selectingNextTool = selectingNextTool;
}
public Vec2 getMouseLocation() {
return mouseLocation;
}
@ -98,10 +121,12 @@ public class PlayerControlState implements Serializable {
if (this.movingRight) flags |= 2;
if (this.movingForward) flags |= 4;
if (this.movingBackward) flags |= 8;
if (this.shooting) flags |= 16;
if (this.usingTool) flags |= 16;
if (this.reloading) flags |= 32;
if (this.sprinting) flags |= 64;
if (this.sneaking) flags |= 128;
if (this.selectingPreviousTool) flags |= 256;
if (this.selectingNextTool) flags |= 512;
buffer.putInt(flags);
buffer.putFloat(this.mouseLocation.x());
buffer.putFloat(this.mouseLocation.y());
@ -116,10 +141,12 @@ public class PlayerControlState implements Serializable {
s.movingRight = (flags & 2) > 0;
s.movingForward = (flags & 4) > 0;
s.movingBackward = (flags & 8) > 0;
s.shooting = (flags & 16) > 0;
s.usingTool = (flags & 16) > 0;
s.reloading = (flags & 32) > 0;
s.sprinting = (flags & 64) > 0;
s.sneaking = (flags & 128) > 0;
s.selectingPreviousTool = (flags & 256) > 0;
s.selectingNextTool = (flags & 512) > 0;
s.mouseLocation = new Vec2(buffer.getFloat(), buffer.getFloat());
return s;
}

View File

@ -14,7 +14,7 @@ public class Team implements Serializable {
private final byte id;
private final String name;
private final java.awt.Color color;
private final Color color;
private final Vec2 spawnPoint;
private final Vec2 supplyPoint;
private final Vec2 orientation;

View File

@ -43,6 +43,13 @@ public class World implements Serializable {
return gunTypes;
}
public GunType getGunTypeById(byte id) {
for (var t : this.gunTypes.values()) {
if (t.id() == id) return t;
}
return null;
}
public Map<Integer, Player> getPlayers() {
return this.players;
}

View File

@ -0,0 +1,56 @@
package nl.andrewlalis.aos_core.model.tools;
/**
* The grenade tool, when equipped, allows the player to throw grenades into the
* world, if there are some grenades available.
*/
public class Grenade implements Tool {
private final int maxGrenades;
private int grenades;
public Grenade(int grenades, int maxGrenades) {
this.grenades = grenades;
this.maxGrenades = maxGrenades;
}
public Grenade() {
this(3, 3);
}
public int getGrenadesRemaining() {
return grenades;
}
public int getMaxGrenades() {
return maxGrenades;
}
/**
* @return The name of the tool, as it should be shown to the players.
*/
@Override
public String getName() {
return "Grenade";
}
@Override
public void use() {
this.grenades--;
}
@Override
public void resupply() {
this.grenades = this.maxGrenades;
}
@Override
public void reset() {
this.resupply();
}
@Override
public boolean isUsable() {
return this.grenades > 0;
}
}

View File

@ -1,8 +1,9 @@
package nl.andrewlalis.aos_core.model.tools;
import java.io.Serializable;
public class Gun implements Serializable {
/**
* A type of tool that, when equipped, allows the player to shoot bullets.
*/
public class Gun implements Tool {
GunType type;
/**
@ -14,14 +15,21 @@ public class Gun implements Serializable {
*/
private int clipCount;
public Gun(GunType type, int currentClipBulletCount, int clipCount) {
private transient long lastShot;
private transient long reloadingStartedAt;
private boolean reloading;
public Gun(GunType type, int currentClipBulletCount, int clipCount, boolean reloading) {
this.type = type;
this.currentClipBulletCount = currentClipBulletCount;
this.clipCount = clipCount;
this.reloading = reloading;
this.lastShot = System.currentTimeMillis();
}
public Gun(GunType type) {
this(type, 0, type.getMaxClipCount());
this(type, 0, type.maxClipCount(), false);
}
public GunType getType() {
@ -36,10 +44,6 @@ public class Gun implements Serializable {
return clipCount;
}
public void refillClips() {
this.clipCount = this.type.getMaxClipCount();
}
public void decrementBulletCount() {
this.currentClipBulletCount = Math.max(this.currentClipBulletCount - 1, 0);
}
@ -52,10 +56,59 @@ public class Gun implements Serializable {
return this.clipCount > 0;
}
public boolean isReloading() {
return reloading;
}
public void startReloading() {
this.reloading = true;
this.reloadingStartedAt = System.currentTimeMillis();
}
public boolean isReloadingComplete() {
return this.reloading && (System.currentTimeMillis() - this.reloadingStartedAt) > this.type.reloadTime() * 1000;
}
public void reload() {
if (this.clipCount > 0) {
this.clipCount--;
this.currentClipBulletCount = this.type.getClipSize();
}
this.currentClipBulletCount = this.type.clipSize();
}
this.reloading = false;
}
/**
* @return The name of the tool, as it should be shown to the players.
*/
@Override
public String getName() {
return this.getType().name();
}
@Override
public void use() {
this.lastShot = System.currentTimeMillis();
this.currentClipBulletCount--;
}
@Override
public void resupply() {
this.clipCount = this.type.maxClipCount();
}
@Override
public boolean isUsable() {
return !this.reloading &&
this.currentClipBulletCount > 0 &&
(this.lastShot + (long) (this.type.shotCooldownTime() * 1000)) < System.currentTimeMillis();
}
@Override
public void reset() {
this.reloading = false;
this.currentClipBulletCount = this.type.clipSize();
this.clipCount = this.type.maxClipCount();
this.lastShot = 0;
this.reloadingStartedAt = 0;
}
}

View File

@ -3,120 +3,20 @@ package nl.andrewlalis.aos_core.model.tools;
import java.io.Serializable;
/**
* Relatively constant configuration information about a particular type of gun,
* while not including state data for any single gun.
* Information about a particular type of gun.
*/
public class GunType implements Serializable {
/**
* The name of this type of gun. Should be unique among all guns in a world.
*/
private final String name;
/**
* The category of gun.
*/
private final GunCategory category;
/**
* The color of this type of gun, in hex.
*/
private final String color;
/**
* Maximum number of clips a player can carry when using this gun.
*/
private final int maxClipCount;
/**
* Number of bullets in each clip.
*/
private final int clipSize;
/**
* Number of bullets that are fired simultaneously per round. Usually only
* shotguns fire multiple.
*/
private final int bulletsPerRound;
/**
* How accurate shots from this gun are. 0 = never miss, 1 = complete random.
*/
private final float accuracy;
/**
* How long (in seconds) to wait after each shot, before another is shot.
*/
private final float shotCooldownTime;
/**
* How long (in seconds) for reloading a new clip.
*/
private final float reloadTime;
/**
* How fast the bullet travels (in m/s).
*/
private final float bulletSpeed;
/**
* How much damage the bullet does for a direct hit.
*/
private final float baseDamage;
/**
* How fast the gun pushes the player backwards when shot (in m/s).
*/
private final float recoil;
public GunType(String name, GunCategory category, String color, int maxClipCount, int clipSize, int bulletsPerRound, float accuracy, float shotCooldownTime, float reloadTime, float bulletSpeed, float baseDamage, float recoil) {
this.name = name;
this.category = category;
this.color = color;
this.maxClipCount = maxClipCount;
this.clipSize = clipSize;
this.bulletsPerRound = bulletsPerRound;
this.accuracy = accuracy;
this.shotCooldownTime = shotCooldownTime;
this.reloadTime = reloadTime;
this.bulletSpeed = bulletSpeed;
this.baseDamage = baseDamage;
this.recoil = recoil;
}
public String getName() {
return name;
}
public GunCategory getCategory() {
return category;
}
public String getColor() {
return color;
}
public int getMaxClipCount() {
return maxClipCount;
}
public int getClipSize() {
return clipSize;
}
public int getBulletsPerRound() {
return bulletsPerRound;
}
public float getAccuracy() {
return accuracy;
}
public float getShotCooldownTime() {
return shotCooldownTime;
}
public float getReloadTime() {
return reloadTime;
}
public float getBulletSpeed() {
return bulletSpeed;
}
public float getBaseDamage() {
return baseDamage;
}
public float getRecoil() {
return recoil;
}
}
public record GunType (
byte id,
String name,
GunCategory category,
String color,
int maxClipCount,
int clipSize,
int bulletsPerRound,
float inaccuracy,
float shotCooldownTime,
float reloadTime,
float bulletSpeed,
float baseDamage,
float recoil
) implements Serializable {}

View File

@ -0,0 +1,45 @@
package nl.andrewlalis.aos_core.model.tools;
public class Knife implements Tool {
/**
* @return The name of the tool, as it should be shown to the players.
*/
@Override
public String getName() {
return "Knife";
}
/**
* Uses the tool.
*/
@Override
public void use() {
}
/**
* Resupplies the tool, when a player is resupplied at their team's area.
*/
@Override
public void resupply() {
}
/**
* Resets the tool to its preferred initial state. This is useful for things
* like respawning.
*/
@Override
public void reset() {
}
/**
* @return True if the player may use the tool to perform an action, or
* false if it's not possible to do so.
*/
@Override
public boolean isUsable() {
return true;
}
}

View File

@ -0,0 +1,35 @@
package nl.andrewlalis.aos_core.model.tools;
import java.io.Serializable;
/**
* Represents some sort of usable tool item that players can equip and use.
*/
public interface Tool extends Serializable {
/**
* @return The name of the tool, as it should be shown to the players.
*/
String getName();
/**
* Uses the tool.
*/
void use();
/**
* Resupplies the tool, when a player is resupplied at their team's area.
*/
void resupply();
/**
* Resets the tool to its preferred initial state. This is useful for things
* like respawning.
*/
void reset();
/**
* @return True if the player may use the tool to perform an action, or
* false if it's not possible to do so.
*/
boolean isUsable();
}

View File

@ -1,105 +1,86 @@
package nl.andrewlalis.aos_core.net.data;
import nl.andrewlalis.aos_core.model.Player;
import nl.andrewlalis.aos_core.model.tools.Grenade;
import nl.andrewlalis.aos_core.model.tools.Gun;
import nl.andrewlalis.aos_core.model.tools.Knife;
import nl.andrewlalis.aos_core.model.tools.Tool;
import nl.andrewlalis.aos_core.net.data.tool.GrenadeData;
import nl.andrewlalis.aos_core.net.data.tool.GunData;
import nl.andrewlalis.aos_core.net.data.tool.KnifeData;
import nl.andrewlalis.aos_core.net.data.tool.ToolData;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class PlayerDetailUpdate {
public static final int BYTES = Float.BYTES + 1 + 5 * Integer.BYTES;
private final float health;
private final boolean reloading;
private final int gunMaxClipCount;
private final int gunClipSize;
private final int gunBulletsPerRound;
private final int gunCurrentClipBulletCount;
private final int gunClipCount;
private final List<ToolData> tools;
private final int selectedToolIndex;
public PlayerDetailUpdate(Player player) {
this.health = player.getHealth();
this.reloading = player.isReloading();
this.gunMaxClipCount = player.getGun().getType().getMaxClipCount();
this.gunClipSize = player.getGun().getType().getClipSize();
this.gunBulletsPerRound = player.getGun().getType().getBulletsPerRound();
this.gunCurrentClipBulletCount = player.getGun().getCurrentClipBulletCount();
this.gunClipCount = player.getGun().getClipCount();
this.tools = new ArrayList<>(player.getTools().size());
int toolIndex = 0;
for (int i = 0; i < player.getTools().size(); i++) {
var t = player.getTools().get(i);
if (t instanceof Knife k) {
this.tools.add(new KnifeData(k));
} else if (t instanceof Gun g) {
this.tools.add(new GunData(g));
} else if (t instanceof Grenade g) {
this.tools.add(new GrenadeData(g));
}
if (t.equals(player.getSelectedTool())) {
toolIndex = i;
}
}
this.selectedToolIndex = toolIndex;
}
private PlayerDetailUpdate(float health, boolean reloading, int gunMaxClipCount, int gunClipSize, int gunBulletsPerRound, int gunCurrentClipBulletCount, int gunClipCount) {
private PlayerDetailUpdate(float health, List<ToolData> tools, int selectedToolIndex) {
this.health = health;
this.reloading = reloading;
this.gunMaxClipCount = gunMaxClipCount;
this.gunClipSize = gunClipSize;
this.gunBulletsPerRound = gunBulletsPerRound;
this.gunCurrentClipBulletCount = gunCurrentClipBulletCount;
this.gunClipCount = gunClipCount;
this.tools = tools;
this.selectedToolIndex = selectedToolIndex;
}
public float getHealth() {
return health;
}
public boolean isReloading() {
return reloading;
public List<ToolData> getTools() {
return tools;
}
public int getGunMaxClipCount() {
return gunMaxClipCount;
}
public int getGunClipSize() {
return gunClipSize;
}
public int getGunBulletsPerRound() {
return gunBulletsPerRound;
}
public int getGunCurrentClipBulletCount() {
return gunCurrentClipBulletCount;
}
public int getGunClipCount() {
return gunClipCount;
}
@Override
public String toString() {
return "PlayerDetailUpdate{" +
"health=" + health +
", reloading=" + reloading +
", gunMaxClipCount=" + gunMaxClipCount +
", gunClipSize=" + gunClipSize +
", gunBulletsPerRound=" + gunBulletsPerRound +
", gunCurrentClipBulletCount=" + gunCurrentClipBulletCount +
", gunClipCount=" + gunClipCount +
'}';
public int getSelectedToolIndex() {
return this.selectedToolIndex;
}
public byte[] toBytes() {
ByteBuffer buffer = ByteBuffer.allocate(BYTES);
buffer.putFloat(health);
buffer.put((byte) (this.reloading ? 1 : 0));
buffer.putInt(this.gunMaxClipCount);
buffer.putInt(this.gunClipSize);
buffer.putInt(this.gunBulletsPerRound);
buffer.putInt(this.gunCurrentClipBulletCount);
buffer.putInt(this.gunClipCount);
int size = Float.BYTES + 2 * Integer.BYTES;
for (var td : this.tools) {
size += 1 + td.getByteSize();
}
ByteBuffer buffer = ByteBuffer.allocate(size);
buffer.putFloat(this.health);
buffer.putInt(this.selectedToolIndex);
buffer.putInt(this.tools.size());
for (var td : this.tools) {
td.write(buffer);
}
return buffer.array();
}
public static PlayerDetailUpdate fromBytes(byte[] bytes) {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
return new PlayerDetailUpdate(
buffer.getFloat(),
buffer.get() == 1,
buffer.getInt(),
buffer.getInt(),
buffer.getInt(),
buffer.getInt(),
buffer.getInt()
);
float health = buffer.getFloat();
int selectedToolIndex = buffer.getInt();
int toolCount = buffer.getInt();
List<ToolData> tools = new ArrayList<>(toolCount);
for (int i = 0; i < toolCount; i++) {
tools.add(ToolData.read(buffer));
}
return new PlayerDetailUpdate(health, tools, selectedToolIndex);
}
}

View File

@ -2,38 +2,52 @@ package nl.andrewlalis.aos_core.net.data;
import nl.andrewlalis.aos_core.geom.Vec2;
import nl.andrewlalis.aos_core.model.Player;
import nl.andrewlalis.aos_core.model.tools.Grenade;
import nl.andrewlalis.aos_core.model.tools.Gun;
import nl.andrewlalis.aos_core.model.tools.Knife;
import nl.andrewlalis.aos_core.net.data.tool.GrenadeData;
import nl.andrewlalis.aos_core.net.data.tool.GunData;
import nl.andrewlalis.aos_core.net.data.tool.KnifeData;
import nl.andrewlalis.aos_core.net.data.tool.ToolData;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* The data that's sent to all clients about a player, and contains only the
* information needed to render the player on the screen.
*/
public class PlayerUpdate {
public static final int BYTES = Integer.BYTES + 6 * Float.BYTES + 1;
private final int id;
private final Vec2 position;
private final Vec2 orientation;
private final Vec2 velocity;
private final String gunTypeName;
private final ToolData selectedTool;
public PlayerUpdate(Player player) {
this.id = player.getId();
this.position = player.getPosition();
this.orientation = player.getOrientation();
this.velocity = player.getVelocity();
this.gunTypeName = player.getGun().getType().getName();
if (player.getSelectedTool() instanceof Knife knife) {
this.selectedTool = new KnifeData(knife);
} else if (player.getSelectedTool() instanceof Gun gun) {
this.selectedTool = new GunData(gun);
} else if (player.getSelectedTool() instanceof Grenade grenade) {
this.selectedTool = new GrenadeData(grenade);
} else {
throw new IllegalArgumentException("Invalid selected tool.");
}
}
public PlayerUpdate(int id, Vec2 position, Vec2 orientation, Vec2 velocity, String gunTypeName) {
public PlayerUpdate(int id, Vec2 position, Vec2 orientation, Vec2 velocity, ToolData selectedTool) {
this.id = id;
this.position = position;
this.orientation = orientation;
this.velocity = velocity;
this.gunTypeName = gunTypeName;
this.selectedTool = selectedTool;
}
public int getId() {
@ -52,8 +66,8 @@ public class PlayerUpdate {
return velocity;
}
public String getGunTypeName() {
return gunTypeName;
public ToolData getSelectedTool() {
return selectedTool;
}
public void write(DataOutputStream out) throws IOException {
@ -64,8 +78,10 @@ public class PlayerUpdate {
out.writeFloat(this.orientation.y());
out.writeFloat(this.velocity.x());
out.writeFloat(this.velocity.y());
out.writeInt(this.gunTypeName.length());
out.writeBytes(this.gunTypeName);
out.writeInt(1 + this.selectedTool.getByteSize());
ByteBuffer buffer = ByteBuffer.allocate(1 + this.selectedTool.getByteSize());
this.selectedTool.write(buffer);
out.write(buffer.array());
}
public static PlayerUpdate read(DataInputStream in) throws IOException {
@ -73,8 +89,9 @@ public class PlayerUpdate {
Vec2 position = Vec2.read(in);
Vec2 orientation = Vec2.read(in);
Vec2 velocity = Vec2.read(in);
int gunTypeNameLength = in.readInt();
String gunTypeName = new String(in.readNBytes(gunTypeNameLength));
return new PlayerUpdate(id, position, orientation, velocity, gunTypeName);
int toolByteSize = in.readInt();
ByteBuffer buffer = ByteBuffer.wrap(in.readNBytes(toolByteSize));
ToolData tool = ToolData.read(buffer);
return new PlayerUpdate(id, position, orientation, velocity, tool);
}
}

View File

@ -75,12 +75,7 @@ public class WorldUpdate {
}
public byte[] toBytes() throws IOException {
int size = 3 * Integer.BYTES + // List size integers.
this.playerUpdates.size() * PlayerUpdate.BYTES +
this.bulletUpdates.size() * BulletUpdate.BYTES +
this.teamUpdates.size() * TeamUpdate.BYTES +
this.soundsToPlay.size() * SoundData.BYTES;
ByteArrayOutputStream out = new ByteArrayOutputStream(size);
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
DataOutputStream dataOut = new DataOutputStream(out);
dataOut.writeInt(this.playerUpdates.size());
for (var u : this.playerUpdates) {

View File

@ -0,0 +1,52 @@
package nl.andrewlalis.aos_core.net.data.tool;
import nl.andrewlalis.aos_core.model.World;
import nl.andrewlalis.aos_core.model.tools.Grenade;
import nl.andrewlalis.aos_core.model.tools.Tool;
import java.nio.ByteBuffer;
public class GrenadeData extends ToolData {
private int grenades;
private int maxGrenades;
public GrenadeData() {
super((byte) 1);
}
public GrenadeData(Grenade grenade) {
this();
this.grenades = grenade.getGrenadesRemaining();
this.maxGrenades = grenade.getMaxGrenades();
}
public int getGrenades() {
return grenades;
}
public int getMaxGrenades() {
return maxGrenades;
}
@Override
public int getByteSize() {
return 2 * Integer.BYTES;
}
@Override
protected void putData(ByteBuffer buffer) {
buffer.putInt(this.grenades);
buffer.putInt(this.maxGrenades);
}
@Override
protected void getData(ByteBuffer buffer) {
this.grenades = buffer.getInt();
this.maxGrenades = buffer.getInt();
}
@Override
public Tool toTool(World world) {
return new Grenade(this.grenades, this.maxGrenades);
}
}

View File

@ -0,0 +1,92 @@
package nl.andrewlalis.aos_core.net.data.tool;
import nl.andrewlalis.aos_core.model.World;
import nl.andrewlalis.aos_core.model.tools.Gun;
import nl.andrewlalis.aos_core.model.tools.Tool;
import java.nio.ByteBuffer;
public class GunData extends ToolData {
private byte typeId;
private boolean reloading;
private int clipCount;
private int currentClipBulletCount;
private int bulletsPerRound;
private int clipSize;
private int maxClipCount;
public GunData() {
super((byte) 0);
}
public GunData(Gun gun) {
this();
this.typeId = gun.getType().id();
this.reloading = gun.isReloading();
this.clipCount = gun.getClipCount();
this.currentClipBulletCount = gun.getCurrentClipBulletCount();
this.bulletsPerRound = gun.getType().bulletsPerRound();
this.clipSize = gun.getType().clipSize();
this.maxClipCount = gun.getType().maxClipCount();
}
public byte getTypeId() {
return typeId;
}
public boolean isReloading() {
return reloading;
}
public int getClipCount() {
return clipCount;
}
public int getCurrentClipBulletCount() {
return currentClipBulletCount;
}
public int getBulletsPerRound() {
return bulletsPerRound;
}
public int getClipSize() {
return clipSize;
}
public int getMaxClipCount() {
return maxClipCount;
}
@Override
public int getByteSize() {
return 2 * Byte.BYTES + 5 * Integer.BYTES;
}
@Override
protected void putData(ByteBuffer buffer) {
buffer.put(this.getTypeId());
buffer.put((byte) (this.reloading ? 1 : 0));
buffer.putInt(this.clipCount);
buffer.putInt(this.currentClipBulletCount);
buffer.putInt(this.bulletsPerRound);
buffer.putInt(this.clipSize);
buffer.putInt(this.maxClipCount);
}
@Override
protected void getData(ByteBuffer buffer) {
this.typeId = buffer.get();
this.reloading = buffer.get() == 1;
this.clipCount = buffer.getInt();
this.currentClipBulletCount = buffer.getInt();
this.bulletsPerRound = buffer.getInt();
this.clipSize = buffer.getInt();
this.maxClipCount = buffer.getInt();
}
@Override
public Tool toTool(World world) {
return new Gun(world.getGunTypeById(this.getTypeId()), this.currentClipBulletCount, this.clipCount, this.reloading);
}
}

View File

@ -0,0 +1,37 @@
package nl.andrewlalis.aos_core.net.data.tool;
import nl.andrewlalis.aos_core.model.World;
import nl.andrewlalis.aos_core.model.tools.Knife;
import nl.andrewlalis.aos_core.model.tools.Tool;
import java.nio.ByteBuffer;
public class KnifeData extends ToolData {
public KnifeData() {
super((byte) 2);
}
public KnifeData(Knife knife) {
super((byte) 2);
}
@Override
public int getByteSize() {
return 1;
}
@Override
protected void putData(ByteBuffer buffer) {
buffer.put((byte) 0);
}
@Override
protected void getData(ByteBuffer buffer) {
buffer.get();
}
@Override
public Tool toTool(World world) {
return new Knife();
}
}

View File

@ -0,0 +1,66 @@
package nl.andrewlalis.aos_core.net.data.tool;
import nl.andrewlalis.aos_core.model.World;
import nl.andrewlalis.aos_core.model.tools.Tool;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
public abstract class ToolData {
private static final Map<Byte, Class<? extends ToolData>> dataMapping = new HashMap<>();
static {
dataMapping.put((byte) 0, GunData.class);
dataMapping.put((byte) 1, GrenadeData.class);
dataMapping.put((byte) 2, KnifeData.class);
}
private final byte toolType;
public ToolData(byte toolType) {
this.toolType = toolType;
}
public void write(ByteBuffer buffer) {
buffer.put(this.toolType);
this.putData(buffer);
}
public static ToolData read(ByteBuffer buffer) {
byte type = buffer.get();
var dataClass = dataMapping.get(type);
if (dataClass == null) {
System.err.println("Invalid tool data type byte.");
return null;
}
try {
var data = dataClass.getConstructor().newInstance();
data.getData(buffer);
return data;
} catch (ReflectiveOperationException e) {
e.printStackTrace();
return null;
}
}
public abstract int getByteSize();
/**
* Writes data for this tool data object into the given buffer.
* @param buffer The byte buffer to write data into.
*/
protected abstract void putData(ByteBuffer buffer);
/**
* Reads data for this tool data object from the given buffer.
* @param buffer The byte buffer to read data from.
*/
protected abstract void getData(ByteBuffer buffer);
/**
* Converts this data back into a Tool instance.
* @param world The world in which the tool is being used.
* @return The tool that this data represents.
*/
public abstract Tool toTool(World world);
}

8
network.md Normal file
View File

@ -0,0 +1,8 @@
# Networking Protocol
In order to make Ace of Shades as performant as possible, the application makes use of a custom, rather low-level system of communication between the server and client. This document explains how this protocol works.
## Tick Updates
Every time the server computes one game tick, it sends a packet to each client. This packet includes the following information:
- Updated position, velocity, and orientation data for all physics objects.
-

View File

@ -7,7 +7,7 @@
<groupId>nl.andrewlalis</groupId>
<artifactId>ace-of-shades</artifactId>
<packaging>pom</packaging>
<version>0.5.0</version>
<version>0.6.0</version>
<modules>
<module>server</module>
<module>client</module>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>ace-of-shades</artifactId>
<groupId>nl.andrewlalis</groupId>
<version>0.5.0</version>
<version>0.6.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>ace-of-shades</artifactId>
<groupId>nl.andrewlalis</groupId>
<version>0.5.0</version>
<version>0.6.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -1,7 +1,12 @@
package nl.andrewlalis.aos_server;
import nl.andrewlalis.aos_core.geom.Vec2;
import nl.andrewlalis.aos_core.model.*;
import nl.andrewlalis.aos_core.model.Barricade;
import nl.andrewlalis.aos_core.model.Player;
import nl.andrewlalis.aos_core.model.Team;
import nl.andrewlalis.aos_core.model.World;
import nl.andrewlalis.aos_core.model.tools.Grenade;
import nl.andrewlalis.aos_core.model.tools.Gun;
import nl.andrewlalis.aos_core.model.tools.GunCategory;
import nl.andrewlalis.aos_core.model.tools.GunType;
import nl.andrewlalis.aos_core.net.Message;
@ -9,6 +14,7 @@ import nl.andrewlalis.aos_core.net.PlayerUpdateMessage;
import nl.andrewlalis.aos_core.net.Type;
import nl.andrewlalis.aos_core.net.chat.SystemChatMessage;
import nl.andrewlalis.aos_core.net.data.DataTypes;
import nl.andrewlalis.aos_core.model.PlayerControlState;
import nl.andrewlalis.aos_core.net.data.PlayerDetailUpdate;
import nl.andrewlalis.aos_core.net.data.WorldUpdate;
import nl.andrewlalis.aos_core.util.ByteUtils;
@ -59,8 +65,10 @@ public class Server {
}
private void initWorld() {
byte gunTypeId = 0;
for (var gs : this.settings.getGunSettings()) {
this.world.getGunTypes().put(gs.getName(), new GunType(
gunTypeId++,
gs.getName(),
GunCategory.valueOf(gs.getCategory().toUpperCase()),
gs.getColor(),
@ -136,7 +144,9 @@ public class Server {
team = t;
}
}
Player p = new Player(id, name, team, this.world.getGunTypes().get(this.settings.getPlayerSettings().getDefaultGun()), settings.getPlayerSettings().getMaxHealth());
Player p = new Player(id, name, team, settings.getPlayerSettings().getMaxHealth());
p.getTools().add(new Gun(this.world.getGunTypes().get(this.settings.getPlayerSettings().getDefaultGun())));
p.getTools().add(new Grenade(3, 3));
this.world.getPlayers().put(p.getId(), p);
String message = p.getName() + " connected.";
this.broadcastMessage(new SystemChatMessage(SystemChatMessage.Level.INFO, message));
@ -204,7 +214,6 @@ public class Server {
for (Team t : this.world.getTeams().values()) {
t.resetScore();
for (Player p : t.getPlayers()) {
p.resetStats();
p.respawn(settings.getPlayerSettings().getMaxHealth());
}
}

View File

@ -2,6 +2,7 @@ package nl.andrewlalis.aos_server;
import nl.andrewlalis.aos_core.geom.Vec2;
import nl.andrewlalis.aos_core.model.*;
import nl.andrewlalis.aos_core.model.tools.Gun;
import nl.andrewlalis.aos_core.model.tools.GunCategory;
import nl.andrewlalis.aos_core.net.chat.SystemChatMessage;
import nl.andrewlalis.aos_core.net.data.SoundData;
@ -71,7 +72,7 @@ public class WorldUpdater extends Thread {
private void updatePlayers(float t) {
for (Player p : this.world.getPlayers().values()) {
this.updatePlayerMovement(p, t);
this.updatePlayerShooting(p);
this.updatePlayerInteraction(p);
p.setHealth(Math.min(p.getHealth() + server.getSettings().getPlayerSettings().getHealthRegenRate() * t, server.getSettings().getPlayerSettings().getMaxHealth()));
this.worldUpdate.addPlayer(p);
}
@ -183,33 +184,40 @@ public class WorldUpdater extends Thread {
}
}
private void updatePlayerShooting(Player p) {
if (p.canUseWeapon()) {
for (int i = 0; i < p.getGun().getType().getBulletsPerRound(); i++) {
Bullet b = new Bullet(p, server.getSettings().getPlayerSettings().getSneakAccuracyModifier(), server.getSettings().getPlayerSettings().getSprintAccuracyModifier());
private void updatePlayerInteraction(Player p) {
if ((p.getState().isSelectingNextTool() ^ p.getState().isSelectingPreviousTool()) && p.canChangeSelectedTool()) {
if (p.getState().isSelectingNextTool()) p.selectNextTool();
if (p.getState().isSelectingPreviousTool()) p.selectPreviousTool();
return; // Don't immediately do any action with the newly-selected tool.
}
if (p.getSelectedTool() instanceof Gun gun) {
if (p.canUseGun()) {
for (int i = 0; i < gun.getType().bulletsPerRound(); i++) {
Bullet b = new Bullet(p, gun, server.getSettings().getPlayerSettings().getSneakAccuracyModifier(), server.getSettings().getPlayerSettings().getSprintAccuracyModifier());
this.world.getBullets().add(b);
this.worldUpdate.addBullet(b);
}
SoundType soundType = SoundType.SHOT_SMG;
if (p.getGun().getType().getCategory() == GunCategory.RIFLE) {
if (gun.getType().category() == GunCategory.RIFLE) {
soundType = SoundType.SHOT_RIFLE;
} else if (p.getGun().getType().getCategory() == GunCategory.SHOTGUN) {
} else if (gun.getType().category() == GunCategory.SHOTGUN) {
soundType = SoundType.SHOT_SHOTGUN;
} else if (p.getGun().getType().getCategory() == GunCategory.MACHINE) {
} else if (gun.getType().category() == GunCategory.MACHINE) {
soundType = ThreadLocalRandom.current().nextFloat() < 0.8f ? SoundType.SHOT_MACHINE_GUN_1 : SoundType.SHOT_MACHINE_GUN_2;
}
this.worldUpdate.addSound(new SoundData(p.getPosition(), 1.0f, soundType));
p.useWeapon();
p.setVelocity(p.getVelocity().add(p.getOrientation().mul(-1 * p.getGun().getType().getRecoil())));
gun.use();
p.setVelocity(p.getVelocity().add(p.getOrientation().mul(-1 * gun.getType().recoil())));
}
if (p.getState().isReloading() && !p.isReloading() && p.getGun().canReload()) {
p.startReloading();
if (p.getState().isReloading() && !gun.isReloading() && gun.canReload()) {
gun.startReloading();
}
if (p.isReloading() && p.isReloadingComplete()) {
p.finishReloading();
if (gun.isReloading() && gun.isReloadingComplete()) {
gun.reload();
this.worldUpdate.addSound(new SoundData(p.getPosition(), 1.0f, SoundType.RELOAD));
}
}
}
private void updateBullets(float t) {
List<Bullet> bulletsToRemove = new ArrayList<>();
@ -255,18 +263,16 @@ public class WorldUpdater extends Thread {
if (dist < Player.RADIUS && (p.getTeam() == null || p.getTeam().getSpawnPoint().dist(p.getPosition()) > Team.SPAWN_RADIUS)) {
// Player was shot!
float damage = (float) (((Player.RADIUS - dist) / Player.RADIUS) * b.getGun().getType().getBaseDamage());
float damage = (float) (((Player.RADIUS - dist) / Player.RADIUS) * b.getGun().getType().baseDamage());
p.takeDamage(damage);
if (p.getHealth() == 0.0f) {
Player shooter = this.world.getPlayers().get(b.getPlayerId());
this.server.broadcastMessage(new SystemChatMessage(SystemChatMessage.Level.SEVERE, p.getName() + " was shot by " + shooter.getName() + "."));
this.worldUpdate.addSound(new SoundData(p.getPosition(), 1.0f, SoundType.DEATH));
shooter.incrementKillCount();
if (shooter.getTeam() != null) {
shooter.getTeam().incrementScore();
this.worldUpdate.addTeam(shooter.getTeam());
}
p.incrementDeathCount();
p.respawn(server.getSettings().getPlayerSettings().getMaxHealth());
}
}

View File

@ -19,13 +19,13 @@ public class GunsCommand implements Command, ChatCommand {
@Override
public void execute(String[] args) {
for (var gunType : this.server.getWorld().getGunTypes().values()) {
System.out.println(gunType.getName());
System.out.println(gunType.name());
}
}
@Override
public void execute(ClientHandler handler, Player player, String[] args) {
String msg = handler.getServer().getWorld().getGunTypes().values().stream().map(GunType::getName).collect(Collectors.joining(", "));
String msg = handler.getServer().getWorld().getGunTypes().values().stream().map(GunType::name).collect(Collectors.joining(", "));
handler.send(new SystemChatMessage(SystemChatMessage.Level.INFO, msg));
}
}

View File

@ -1,6 +1,5 @@
package nl.andrewlalis.aos_server.command;
import nl.andrewlalis.aos_core.model.Player;
import nl.andrewlalis.aos_server.Server;
import java.util.stream.Collectors;
@ -21,13 +20,12 @@ public class ListPlayersCommand implements Command {
String message = this.server.getWorld().getPlayers().values().stream()
.sorted()
.map(player -> String.format(
"%d | %s Team: %s, Health: %.1f / %.1f, Gun: %s",
"%d | %s Team: %s, Health: %.1f / %.1f",
player.getId(),
player.getName(),
player.getTeam() == null ? "none" : player.getTeam().getName(),
player.getHealth(),
this.server.getSettings().getPlayerSettings().getMaxHealth(),
player.getGun().getType().getName()
this.server.getSettings().getPlayerSettings().getMaxHealth()
))
.collect(Collectors.joining("\n"));
System.out.println(message);

View File

@ -6,8 +6,6 @@ import nl.andrewlalis.aos_core.model.tools.GunType;
import nl.andrewlalis.aos_core.net.chat.SystemChatMessage;
import nl.andrewlalis.aos_server.ClientHandler;
import java.util.Locale;
public class GunCommand implements ChatCommand {
@Override
public void execute(ClientHandler handler, Player player, String[] args) {
@ -18,7 +16,7 @@ public class GunCommand implements ChatCommand {
String gunName = String.join(" ", args);
GunType gunType = null;
for (GunType type : handler.getServer().getWorld().getGunTypes().values()) {
if (type.getName().equalsIgnoreCase(gunName)) {
if (type.name().equalsIgnoreCase(gunName)) {
gunType = type;
break;
}
@ -27,7 +25,16 @@ public class GunCommand implements ChatCommand {
handler.send(new SystemChatMessage(SystemChatMessage.Level.WARNING, "Unknown gun name. Use /guns to see available guns."));
return;
}
player.setGun(new Gun(gunType));
handler.send(new SystemChatMessage(SystemChatMessage.Level.INFO, "Changed gun to " + player.getGun().getType().getName() + "."));
boolean gunSet = false;
for (int i = 0; i < player.getTools().size(); i++) {
if (player.getTools().get(i) instanceof Gun) {
player.getTools().set(i, new Gun(gunType));
gunSet = true;
}
}
if (!gunSet) {
player.getTools().add(new Gun(gunType));
}
handler.send(new SystemChatMessage(SystemChatMessage.Level.INFO, "Changed gun to " + gunType.name() + "."));
}
}

View File

@ -7,7 +7,8 @@ import nl.andrewlalis.aos_server.ClientHandler;
public class KillDeathRatioCommand implements ChatCommand {
@Override
public void execute(ClientHandler handler, Player player, String[] args) {
float ratio = player.getKillCount() / ((float) player.getDeathCount());
handler.send(new SystemChatMessage(SystemChatMessage.Level.INFO, String.format("Your Kill/Death ratio is %.2f.", ratio)));
// float ratio = player.getKillCount() / ((float) player.getDeathCount());
// handler.send(new SystemChatMessage(SystemChatMessage.Level.INFO, String.format("Your Kill/Death ratio is %.2f.", ratio)));
handler.send(new SystemChatMessage(SystemChatMessage.Level.WARNING, "K/D command not yet implemented."));
}
}

View File

@ -0,0 +1,9 @@
package nl.andrewlalis.aos_server.model;
public class PlayerStatistics {
private transient int killCount;
private transient int deathCount;
private transient int shotCount;
private transient int resupplyCount;
private transient int killStreak;
}

View File

@ -52,9 +52,9 @@ player-settings:
max-health: 100
# How quickly players regenerate health, in points per second. Set to 0 to disable regeneration.
health-regen-rate: 1.0
# How much sneaking affects gun accuracy. Values less than 0 increase accuracy, and greater than 0 decrease accuracy.
# How much sneaking affects gun inaccuracy. Values less than 0 increase inaccuracy, and greater than 0 decrease inaccuracy.
sneak-accuracy-modifier: 0.5
# How much sprinting affects gun accuracy. Values less than 0 increase accuracy, and greater than 0 decrease accuracy.
# How much sprinting affects gun inaccuracy. Values less than 0 increase inaccuracy, and greater than 0 decrease inaccuracy.
sprint-accuracy-modifier: 1.5
# Should be the name of one of the guns defined in "gun-settings".
default-gun: M1 Garand
@ -78,7 +78,7 @@ gun-settings:
max-clip-count: 4 # The maximum number of clips which a player can hold for this gun.
clip-size: 30 # The number of rounds in each clip.
bullets-per-round: 1 # The number of bullets spawned for each round fired.
accuracy: 0.10 # The accuracy of the gun, or rather deviation. Increase this to decrease accuracy.
inaccuracy: 0.10 # The inaccuracy of the gun, or rather deviation. Increase this to decrease inaccuracy.
shot-cooldown-time: 0.05 # How many seconds to wait after shooting before you can shoot again.
reload-time: 1.2 # How many seconds to wait while reloading.
bullet-speed: 90 # How fast the bullets from this gun fly, in meters per second.
@ -91,7 +91,7 @@ gun-settings:
max-clip-count: 5
clip-size: 16
bullets-per-round: 1
accuracy: 0.20
inaccuracy: 0.20
shot-cooldown-time: 0.25
reload-time: 1.0
bullet-speed: 40
@ -104,7 +104,7 @@ gun-settings:
max-clip-count: 3
clip-size: 500
bullets-per-round: 1
accuracy: 0.10
inaccuracy: 0.10
shot-cooldown-time: 0.04
reload-time: 3
bullet-speed: 60
@ -117,7 +117,7 @@ gun-settings:
max-clip-count: 3
clip-size: 100
bullets-per-round: 1
accuracy: 0.08
inaccuracy: 0.08
shot-cooldown-time: 0.03
reload-time: 3.5
bullet-speed: 80
@ -130,7 +130,7 @@ gun-settings:
max-clip-count: 10
clip-size: 8
bullets-per-round: 1
accuracy: 0.02
inaccuracy: 0.02
shot-cooldown-time: 0.75
reload-time: 0.75
bullet-speed: 150
@ -143,7 +143,7 @@ gun-settings:
max-clip-count: 8
clip-size: 6
bullets-per-round: 5
accuracy: 0.15
inaccuracy: 0.15
shot-cooldown-time: 0.5
reload-time: 2.0
bullet-speed: 75