Object creration in Tic tac toe - oop

I am creating a two player game and I want to be able to restrict users from creating additional player objects.
public class Player {
Symbol symbol;
public Player() {
symbol = Symbol.X;
}
}
If I have a public constructor like this, users can keep creating objects and there will be no way to restrict this?
Edit:
Extracting players from an enum
public enum Symbol {
X, O;
}
I want to be able to get the symbol from here and assign it to player object when creating it.

You can use the factory pattern:
class Player {
private static int players = 0;
private Player(...) {
...
}
public static Player newPlayer(...) {
if (players < MAX_PLAYERS) {
players++;
return new Player(...);
}
throw new TooManyPlayersException(...);
}
}

Related

How to change values of variables using methods?

I am having troubles incrementing the value of my instance variables. I tried making a method so that for every pet I buy, it will add that much to how many I already have. But when I print dogs variable, it says 0 even though I added 2. I'd appreciate any help. Thanks!
public class myStuff
static int dogs;
static int cats;
public static void main(String[] args) {
myStuff.buy(dogs, 2);
System.out.println(dogs);
}
public static void buy(int pet, int howMany) {
pet = pet + howMany;
}
}
you cant do that in java, since it is pass-by-value
In Java, method parameters are passed by value (which means the value of dogsin your case is passed in the first Place, but never touched). Objects however, are manipulated by reference. So, if you want to increase the number of pets, you could use a class Pet with a value count
public class Pet {
private int count;
public Pet(int count) {
this.count = count;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
If you then pass an instance of Pet to your buy function and increase the count via setCount, the value will be saved.

I have an issue with casting Player to a MyPlayer

Hello I started learning to code minecraft bukkit plugins just few days a go, so please don't blame me if my issue is stiupid. I want to create a new MyPlayer class that will be Player subclass. I have already figured out that Player's root is org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer so I can make somethink like this: public class OticPlayer extends org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer. I want MyClass to contain all of his parent methods, but add some it's own. The problem is when i use: Bukkit.getPlayerExact(arg3[1]) it return the reference to a Player type object. I have a Lobby class with method addPlayer(MyPlayer arg0), so I need a reference to the MyPlayer type object, not Player. When I will try to cast a Player type reference to MyPlayer, it's throws an exception: java.lang.ClassCastException: org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer cannot be cast to me.gtddd.my.MyPlayer. I need to pass MyPlayer type reference to the addPlayer() method, because I want to make some kind of stats system (K/D/A), each of these stats must be a pool accesable, by MyPlayer type object. So how can I cast Player to MyPlayer? Example code that generates this problem:
package test;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_12_R1.CraftServer;
import org.bukkit.plugin.java.JavaPlugin;
import me.gtddd.otic.OticPlayer;
import net.minecraft.server.v1_12_R1.EntityPlayer;
public class MyPlayer extends org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer {
public MyPlayer(CraftServer server, EntityPlayer entity) {
super(server, entity);
}
int kills = 0;
int deaths = 0;
int assists = 0;
public int getKda() {
return kills/deaths/assists;
}
}
public class Lobby {
MyPlayer[] players = new MyPlayer[10];
public void addPlayer(MyPlayer arg0) {
players[players.length] = arg0;
}
public MyPlayer getPlayer(int slot) {
return players[slot-1];
}
}
public class Main extends JavaPlugin {
#Override
public void onEnable() {
Lobby lobby1 = new Lobby();
MyPlayer player = (MyPlayer) Bukkit.getPlayerExact("Notch");
lobby1.addPlayer(player);
System.out.println(lobby1.getPlayer(1).getKda());
}
}
I looked lot to find the answer, but I was not able to find anythink what would satisfy me. From top: Thanks for all answers! If somethink is unclear ask.
Instead of extending a Player, you should create a Wrapper around Bukkit's Player Object, more specifically wrapping the Player's Name or UUID (recommended) as it's not possible to edit Bukkit's Player instances without a lot of effort, it's implementation is very obscure, and you won't be able to include your MyPlayer in Bukkit's server.
So, for example, you could create a MyPlayer as following:
class MyPlayer {
private String playerName;
public MyPlayer(Player player) {
playerName = player.getDisplayName(); //Something like this to store the player
}
//More of your code, for example counting the kills
public Player recoverPlayerObject() {
return Bukkit.getPlayer(playerName);
}
And if you want to do things like adding a kill to the player, and then teleporting him, you could use your MyPlayer instance to modify your players' attributes, and using the recoverPlayerObject if you need to interact directly with Bukkit Player object.
For more information on Wrapper/Decorator, Iluwatar has a very nice Github repository about Design Patterns, including the Decorator.

Why is this subclass' parent method call not polymorphic?

I've been dabbling in Dlang recently as C++ just wasn't quite sitting right with me after having used Python for so long. While dabbling, I came across what I thought would be a very simple exercise in polymorphism. I suppose how you would expect something to work and what it actually does are two entirely different things for reasons an end user probably can't comprehend. That being said, here is the source code of my "sandbox.D":
import std.stdio;
class Animal {
string voice = "--silence--";
void speak() {
writeln(this.voice);
}
}
class Dog : Animal {
string voice = "Whoof!";
}
int main() {
auto a = new Animal();
auto d = new Dog();
writeln(a.voice); // Prints "--silence--"
writeln(d.voice); // Prints "Whoof!"
a.speak(); // Prints "--silence--"
d.speak(); // Prints "--silence--" NOT "Whoof!"
return 0;
}
I guess my issue is why the "this" keyword just doesn't seem to be functioning how you would expect it to in the C++ successor language.
Methods are polymorphic, variables aren't. So instead of making the voice a variable, you want to override speak in the child.
Also, the auto return type doesn't work with polymorphism, you need to actually specify the types. (The reason is that auto return makes a function template in the compiler, which in theory could have multiple overridable slots in the function table, so it just doesn't try to put it in.)
So try this out:
import std.stdio;
class Animal {
void speak() { // changed to void instead of auto
writeln("--silence--");
}
}
class Dog : Animal {
override void speak() { // the override tells it to override the base method
writeln("woof");
}
}
int main() {
auto d = new Dog();
d.speak();
return 0;
}
If you have a lot of shared functionality and want to reuse one function with slight changes in child classes, you might make a method instead of a variable that just returns something.
Like string voice() { return "woof"; }, then it can be overridden in children.
Another way is to use template this parameter:
import std.stdio;
class Animal {
string voice;
void speak(this C)() {
writeln((cast(C)this).voice);
}
}
class Dog : Animal {
string voice = "Whoof!";
}
int main() {
auto a = new Animal();
auto d = new Dog();
a.speak(); // Prints ""
d.speak(); // Prints "Whoof!"
return 0;
}
Or when you do not need to have voice as a member:
import std.stdio;
class Animal {
static immutable voice = "";
void speak(this C)() {
writeln(C.voice);
}
}
class Dog : Animal {
static immutable voice = "Whoof!";
}
int main() {
auto a = new Animal();
auto d = new Dog();
a.speak(); // Prints ""
d.speak(); // Prints "Whoof!"
return 0;
}

Accesing arraylist property from another class using constructor

So i have a class that makes an array list for me and i need to access it in another class through a constructor but i don't know what to put into the constructor because all my methods in that class are just for manipulating that list. im either getting a null pointer exception or a out of bounds exception. ive tried just leaving the constructor empty but that dosent seem to help. thanks in advance. i would show you code but my professor is very strict on academic dishonesty so i cant sorry if that makes it hard.
You are confusing the main question, with a potential solution.
Main Question:
I have a class ArrayListOwnerClass with an enclosed arraylist property or field.
How should another class ArrayListFriendClass access that property.
Potential Solution:
Should I pass the arraylist from ArrayListOwnerClass to ArrayListFriendClass,
in the ArrayListFriendClass constructor ?
It depends on what the second class does with the arraylist.
Instead of passing the list thru the constructor, you may add functions to read or change, as public, the elements of the hidden internal arraylist.
Note: You did not specify a programming language. I'll use C#, altought Java, C++, or similar O.O.P. could be used, instead.
public class ArrayListOwnerClass
{
protected int F_Length;
protected ArrayList F_List;
public ArrayListOwnerClass(int ALength)
{
this.F_Length = ALength;
this.F_List = new ArrayList(ALength);
// ...
} // ArrayListOwnerClass(...)
public int Length()
{
return this.F_Length;
} // int Length(...)
public object getAt(int AIndex)
{
return this.F_List[AIndex];
} // object getAt(...)
public void setAt(int AIndex, object AValue)
{
this.F_List[AIndex] = AValue;
} // void setAt(...)
public void DoOtherStuff()
{
// ...
} // void DoOtherStuff(...)
// ...
} // class ArrayListOwnerClass
public class ArrayListFriendClass
{
public void UseArrayList(ArrayListOwnerClass AListOwner)
{
bool CanContinue =
(AListOwner != null) && (AListOwner.Length() > 0);
if (CanContinue)
{
int AItem = AListOwner.getAt(5);
DoSomethingWith(Item);
} // if (CanContinue)
} // void UseArrayList(...)
public void AlsoDoesOtherStuff()
{
// ...
} // void AlsoDoesOtherStuff(...)
// ...
} // class ArrayListFriendClass
Note, that I could use an indexed property.

Single reference into multiple objects

I am a bit lot about what to do in an OO/DB relation...
Here is the DB model :
CREATE TABLE User
Id
CREATE TABLE Location
userId
// EDIT oups, wrong !
// placeId
// Should be :
seatId
CREATE TABLE Game
locationId
Now some code :
class User
{
private Location locations[]; // need this for several reasons...
public function loadFromDatabase()
{
// Load data from DB
// ...
result = DB::query("SELECT Id FROM Locations WHERE userId="+this->Id);
foreach(result)
{
l = new Location();
l->loadFromDatabase(result);
locations[] = l;
}
}
}
class Location
{
private User user;
public function loadFromDatabase()
{
...
}
}
class Game
{
private Location location;
public loadFromDatabase()
{
/*
Here comes the problem :
how to have a reference to a location
created by the User class ?
*/
}
}
A User play Games in several Locations.
EDIT : And for each location the user plays on seat. Or on another seat...
When I want to know where a game has been played I access Game.location. And when I want to know who played it, I access Game.location.user
Here is my problem : I want the Game.location to be the same reference to one of the User.locations and I do not know how to do this...
And, globally, I feel something wrong about my code...
Any help ?
Thanks
Since you have a placeId in your Location table, I assume there is a Place table which describes what the places actually are, while the Location table simply represents the many-to-many mapping between users and places.
In that case, Location doesn't need to have an Id of its own and doesn't need to be a class, but Place does.
To load just one instance of each object from the database, cache the instances in a static map inside each class.
class Place
{
// Static
private static Place loadedPlaces[];
public static function get(id)
{
if (!loadedPlaces[id])
{
loadedPlaces[id] = new Place(id);
loadedPlaces[id]->loadFromDatabase();
}
return loadedPlaces[id];
}
// Non-static
private id;
public function loadFromDatabase()
{
// ...
}
}
Then to get references to places for the properties of a user or a game, you just access them via the static method.
class User
{
public function loadFromDatabase()
{
result = DB::query("SELECT placeId FROM Locations WHERE userId="+this->Id);
foreach(result)
{
places[] = Place::get(result);
}
}
}
class Game
{
public function loadFromDatabase()
{
place = Place::get(place);
}
}
This uses:
Lazy initialization, because places are only loaded when they are needed.
Multiton pattern, because there is only one instance of each place by id.
Not quite a factory method, because there's no object hierarchy involved.