I am trying to design a simple Soccer game. To keep things simple, I am having a SoccerField
to represent the field and a Player
class to represent an individual.
A SoccerField
will contain a list of players. A Player would belong to a SoccerField (Even though a player can exist by itself, during a game, a player will be part of a SoccerField). How can I represent this relationship? i.e. For moving a player, how can I would like to access the SoccerField boundaries as well as get other players in the SoccerField and validate if the cell is unoccupied.
// Say the Field is represented as a 2D Matrix
class SoccerField {
int maxRow;
int maxCol;
List<Player> players;
public SoccerField(int maxRow, int maxCol) {
this.maxRow = maxRow;
this.maxCol = maxCol;
this.players = new ArrayList<>();
}
public initializePlayers(int xPos, int yPos) {
Player player = new Player(xPos, yPos);
this.players.add(player);
}
}
class Player {
int xPosition;
int yPosition;
// How to represent that a player belongs to a SoccerField?
// Can I have a reference to the SoccerField in a player?
// SoccerField field; ----> Is this an acceptable design?
public Player(int xPosition, int yPosition) {
this.xPosition = xPosition;
this.yPosition = yPosition;
}
public move(int xPos, int yPos) {
// Validate that xPos and yPos exists within the Soccer Field
// If I have a reference to "SoccerField", I can validate the following
// 1. Check if a player moves to a valid cell
// 2. Check if a player does not occupy an already occupied cell
}
}
class Solution {
SoccerField soccerField = new SoccerField(5, 5);
Player player1 = soccerField.initializePlayer(0, 0);
Player player2 = soccerField.initializePlayer(1, 1);
// Now that I have player objects, I want to move the players
// Imagine a video game where I am taking control of a player and moving the player
player1.move(0,1);
player2.move(1,2);
}
Any suggestions on how can I better represent the above classes?