Looking for an appropriate design pattern - java

I have a game that tracks user stats after every match, such as how far they travelled, how many times they attacked, how far they fell, etc, and my current implementations looks somewhat as follows (simplified version):
Class Player{
int id;
public Player(){
int id = Math.random()*100000;
PlayerData.players.put(id,new PlayerData());
}
public void jump(){
//Logic to make the user jump
//...
//call the playerManager
PlayerManager.jump(this);
}
public void attack(Player target){
//logic to attack the player
//...
//call the player manager
PlayerManager.attack(this,target);
}
}
Class PlayerData{
public static HashMap<int, PlayerData> players = new HashMap<int,PlayerData>();
int id;
int timesJumped;
int timesAttacked;
}
public void incrementJumped(){
timesJumped++;
}
public void incrementAttacked(){
timesAttacked++;
}
}
Class PlayerManager{
public static void jump(Player player){
players.get(player.getId()).incrementJumped();
}
public void incrementAttacked(Player player, Player target){
players.get(player.getId()).incrementAttacked();
}
}
So I have a PlayerData class which holds all of the statistics, and brings it out of the player class because it isn't part of the player logic. Then I have PlayerManager, which would be on the server, and that controls the interactions between players (a lot of the logic that does that is excluded so I could keep this simple). I put the calls to the PlayerData class in the Manager class because sometimes you have to do certain checks between players, for instance if the attack actually hits, then you increment "attackHits".
The main problem (in my opinion, correct me if I'm wrong) is that this is not very extensible. I will have to touch the PlayerData class if I want to keep track of a new stat, by adding methods and fields, and then I have to potentially add more methods to my PlayerManager, so it isn't very modulized.
If there is an improvement to this that you would recommend, I would be very appreciative. Thanks.

I am not at all an expert in design patterns. But this is what I think might be useful:
To add actions to the player, you might wanna look at the Strategy Pattern. Just google for it and you will get lot of examples.
Here is an attempt by me:
For updating the player stats, I guess Observer Pattern will be helpful.
The Observer Pattern defines one-to-many dependency between objects so
that when one object changes state, all of its dependents are notified
and updated automatically.
It enforces loose coupling so that future changes are easy.
(You will have to read about Observer Pattern and also will have to see some examples. It is not as straight forward as Strategy.)

Due to the fact that you said you want to be able to add new stats and actions later, I would tend to make a stats object that doesn't need to know anything about the game it's recording. The advantage is that the Stats class would never need to change as you added new features.
public interface Stats {
void incrementStat(Object subject, String stat);
int getStat(Object subject, String stat);
}
You Player implementation would look something like:
public void jump() {
// Logic to make the player jump...
stats.incrementStat(this, "jump");
}
Of course, what you're trading for that flexibility is static type-checking on those increment methods. But in cases like this I tend to think the simplicity is worth it. In addition to removing tons of boiler plate from the PlayerData and PlayerManager classes, you also end up with a reusable component, and you can get rid of the cyclic dependency between PlayerManager and Player.

Related

Java - Choosing the design pattern - 2 interfaces with same methods, except one has an extra parameter

So I have 2 interfaces (show below), 1 for regular/free kits and another one for purchasable kits. They both contain 2 methods, but in the "getIcon" method for purchasable kits, I need the player's profile as a parameter so I can check if they have bought the kit.
What is the best design pattern to use to link these 2 interfaces? and can you possibly show me the code to do it?
The 2 interfaces:
public interface Kits {
void giveKit(Player player);
Item getIcon();
}
public interface PurchasableKits {
void giveKit(Player player);
Item getIcon(Profile profile);
}
I attempted to use the adapter pattern but it doesn't seem right because the "getIcon" method is taking in a profile as a parameter but it doesn't get used.
public class KitAdapter implements PurchasableKits {
private Kits kits;
public KitAdapter(Kits kits) {
this.kits = kits;
}
#Override
public void givetKit(Player player){
kits.giveKit(player);
}
#Override
public void getIcon(Profile profile){
kits.getIcon();
}
}
Thanks in advance
You have 1 interface PurchasableKits. A free Kit would implement the interface and call getIcon(null).
The red flag is that the 2 interfaces are almost exactly the same. No design pattern will get you out of the situation that creates.
That's a tricky question because of the rules of the inheritance and cyclic inheritance avoided in java.
I don't believe that you need to interfaces, you could do something like this:
public interface Kits {
void giveKit(Player player);
//a vargars usage
Item getIcon(Profile... p);
}
public class ConcreteClass implements Kits{
#Override
public void giveKit(Player player) {
// TODO Auto-generated method stub
}
#Override
public Item getIcon(Profile... o) {
//This is the ugly thing of this method. You must check the sent params.
//However I think it is better than send a null param, as the clean code suggest to avoid
if(o.length == 0)
System.out.println("without profile");
else
System.out.println("With profile");
return null;
}
}
public class Main {
public static void main(String[] args) {
ConcreteClass my = new ConcreteClass();
my.getIcon();
my.getIcon(new Profile());
}
}
The output:
without profile
With profile
So I have 2 interfaces (show below), 1 for regular/free kits and another one for purchasable kits. They both contain 2 methods, but in the "getIcon" method for purchasable kits, I need the player's profile as a parameter so I can check if they have bought the kit.
Whether or not the profile is needed in the getIcon(...) method is an implementation detail of those Kits that are purchasable. I would just have a Kit interface that has the following definition:
public interface Kit {
void giveKit(Player player);
Item getIcon(Profile profile);
}
So every time you wanted to get the icon you would pass in the Profile and it would be up to the kits that are purchasable to look at the profile. The free ones would just ignore the argument. That you sometimes pass in null and sometimes not means that you know beforehand whether or not it is free which means that something is wrong with your model.
Couple of other comments about your code. Just my opinions:
Concrete classes tend to be nouns. Interfaces tend to be verbs. Maybe KitHandler instead of Kit?
Class names tend to be singular so then you can put them in a list. Maybe Kit (or KitHandler) would be better so you can create a List<Kit> kits = ....
I used get methods to return fields which means that they typically don't take arguments. Maybe getIcon should be generateIcon(...)?

How to set a single entity invisible to a player?

After much research and much time wasted, I still can't find out how to hide an entity to a player.
What I'm trying to do is create a disguise command. I've now gotten everything worked out, except the issue is that the entity is still visible, and once stationary you can't interact with anything because the mob's hitbox is in the way. I want to hide the entity from the player so that you can do this. I know with players you can use Player#hidePlayer(), but this does not work with entities. I've tried using solutions such as this, but it gave an error while following the example. (And many things were depreciated, so I assumed it was out of date. I'm using Spigot 1.11.2). Any help would be very much appreciated.
PS: If you're wondering why I don't just use an already made plugin, it's because none of them work from what I've found.
To accomplish what you want, you must use packets to cancel what the player sees.
I strongly recommend ProtocolLib, have it in your server and use in your plugin.
Bearing that in mind, Bukkit user Comphenix has developed a class for protocollib to hide entities. You can find it in github.
Comphenix also provides an example of usage, as you can see below:
public class ExampleMod extends JavaPlugin {
private EntityHider entityHider;
private static final int TICKS_PER_SECOND = 20;
#Override
public void onEnable() {
entityHider = new EntityHider(this, Policy.BLACKLIST);
}
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
final Player player = (Player) sender;
final Sheep sheep = player.getWorld().spawn(player.getLocation(), Sheep.class);
// Show a particular entity
entityHider.toggleEntity(player, sheep);
getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
#Override
public void run() {
entityHider.toggleEntity(player, sheep);
}
}, 10 * TICKS_PER_SECOND);
}
return true;
}
}

What is the (best)name or description of this "method linking" to other components

First off, sorry for the strange "title", but since I don't know the name, it's quite tough to describe in a short sentence.
I've been here many-many times before, however this is my first actual activity.
I usually search, read and fight my way trough what I want to know. However, I just can't seem to get to my answer this time, which I find pitty.
Lately I've read "Head First Design Patterns", which I can't recall it was covered in there. Also I've hit quite some Google terms in the box, but without the correct defenition. I just can't find the right combination of search-words to nail the answer.
I've got a question about the correct name of "forward sharing / linking"
of methods and their parameters.
I'm writing the JavaDocs comments to keep my code understandable, but I can't get the right term or Design Pattern name that fits to this.
But just asking this won't get me what I need i think. So I've got a little sample to demonstrate my question as BASIC as possible. I hope it is a bit understandable.
public class Framework()
{
private Game game = new Game();
public Framework()
{
loadComponents();
}
public void loadComponents()
{
// first loading framework requirements.. (lets say a button graphic)
game.load(); // lets start loading the game....
}
public static void main (String[] args)
{
new Framework();
}
}
public class Game()
{
private World world = new World();
public void load()
{
// now we load some of the basic graphics.. (lets say a few borders)
world.load(); // lets start loading the world!
}
}
public class World()
{
private Textures textures = new Textures();
public void load()
{
// now we load the worlds grid...
textures.load(); // ofcourse we need textures, lets load...
}
}
public class Textures()
{
public void load()
{
// loading the textures...
// end of this loading link.
}
}
In this example we started off in the Framework, called the load method in Game, then called the load method in World,
then called the load method in Textures. Lets make it a little simpler:
Framework.load()->Game.load()->World.load()->Texture.load();
But ofcourse we got more of these "links".
Framework.load()->Editor.load()->Entities.load();
Framework.input(Input input)->Game.input(Input input)->Player.input(Input input);
Framework.draw(Graphics2D g2d)->Game.draw(Graphics2D g2d)->World.draw(Graphics2D g2d);
How can I describe or call this "chaining/linking" the best? Becouse chaining in Java is like: Player.getLocation().setLocation(12,12).etc();
I hope my question is a little clear now,
thank you for your time in advance!
Edwin
I believe this is called the Delegator pattern

Creating Annotations in Java like Mockito's before

In processing I have several functions that change the properties of applet to draw stuff, for instance:
public void resetBackground(PApplet pApplet){
pApplet.fill(175);
pApplet.noStroke();
pApplet.rect(0,0,100,100);
}
But I want these functions to preserve the state of the pApplet after the function call, for that I have something like:
public void resetBackground(PApplet pApplet){
SaveAndRestoreDefaults saveAndRestoreDefaults = new SaveAndRestoreDefaults(pApplet);
// Code that changes state.
saveAndRestoreDefaults.restoreOriginals();
}
Now this works for me but I would like this not to clutter my code here but rather be annotation driven, something like:
#PreserveState
public void resetBackground(){
// code that changes state.
}
I have done a little research on it but it seems to be not an easy task. The googling took me to AOP and I don't want to spend time to learn that. Is there an easier way to achieve the same?
Thanks :)
I'd strongly recommend staying in Processing, instead of reaching into the underlying virtual machine API (just because you run it in java, doesn't mean every implementation of Processing has a JVM. Processing.js comes to mind).
Just make a state class and keep track that way:
class SketchState {
color background_color, stroke_color, fill_color;
SketchState(color bg, color st, color fl) {
sketch = s; background_color = bg; stroke_color = st; fill_color = fl;
}
}
ArrayList<SketchState> stateCache = new ArrayList<SketchState>();
void cacheState() {
stateCache.add(new SketchState(...));
}
void restoreState() {
SketchState rest = stateCache.remove(stateCache.size()-1);
background(rest.background_color);
stroke(rest.stroke_color);
fill(rest.fill_color);
}
and add whatever other state aspects you want saved to that class.

What OO structure should I use to describe animal's behaviors?

I have a Java assignment in which my professor requires me to use a LeJOS NXT to make a robot that simulates a certain animal's behaviors. I chose to develop a dragon. All the possible behaviors that I've come up so far is:
Turning around if it's too close to an obstacle.
Going to sleep when battery is low.
Pushing an object if touches.
If it's too bright, find a dark spot.
etc.
I'm now quite confused because I don't know whether to develop it sequentially in one class or to split all the dragon's behaviors into different classes. Please have a look at my explanation below.
Instead of writing everything inside one class like this:
Dragon.java
public class Dragon {
LightSensor ls = new LightSensor
public static main(String args[]) {
while (!BUTTON.Escape.IsPressed()) {
if (this.closeToObject()) {
this.turnAround();
}
// more conditions
}
}
private boolean closeToObject() {
//TODO
return false;
}
private void turnAround() {
//TODO
}
//... more methods
}
However, I want to make it appears to be more object-oriented as the course is meant to help us gain more OOP skills. So what my second option is to create action classes that extends Dragon's Behavior abstract class like this (roughly):
Dragon.java
public class Dragon {
Detect detect = new Detect(); // carry all the detection methods: distance, sound, etc.
TurnAround turnAround = new TurnAround();
public static main(String args[]) {
while (!BUTTON.Escape.IsPressed()) {
if (detect.tooCloseToObject()) {
turnAround.prepare(); // beep beep alert
turnAround.setDerection(true); // e.g. turn right
turnAround.turn();
}
}
}
}
DragonBehaviors.java
abstract class DragonBehavior {
abstract void prepare();
public void setDirection(boolean direction) {
//...
}
}
TurnAround.java
public class TurnAround extends DragonBehaviors {
String direction;
public void TurnAround() {}
public void prepare() {
// sound alert
}
public void setDirection(boolean direction) {
if (direction) this.direction = "Right";
else this.direction = "Left";
}
public void turn() {
// TODO
}
}
The code above is roughly a draft, don't focus on it. Eventually, I want to ask if my idea about the OO structure above is reasonable, otherwise it's much easier to develop the whole thing in one class, but it has nothing to do with OOP. I also have several group members to make the code finished, so I think it could be better if we share the classes to develop in an OOP way.
Which way should I go in this circumstance?
I appreciate all the comments (:
Your choice of extracting different actions into classes with common super class is IMHO reasonable. However I would make Dragon class only aware of the DragonBehavior abstract class, not the subclasses. This way you can add and remove behaviours to the dragon without actually changing it.
How? Look at Chain-of-responsibility pattern - each behaviour has its place in the chain. If behaviour decides to activate itself (i.e. perform something) it may or may not allow further behaviours to be triggered. Moreover, you can and remove behaviours (even at runtime!) and rearrange them to change the precedence (is pushing the obstacle more or less important than going to sleep?).

Categories