Page 1 of 2
How do objects interact with eachother
Posted: Wed Mar 19, 2014 9:19 am
by hybris
Hi,
I'm trying to learn more about OO and classes and I thought it would be fun to do something with Visual representation so I thought to make a 10x10 grid with 1 or more "bacterias" that would move around the grid and bounce on the walls or attack or flee from other bacterias depending on how agressive they are...
I have some problem with the design though since I cannot figure out how to get the objects to interact:
So far I thought I would make a class for the grid with params x and y so I can create boards with different sizes.
The other class would be the bacteria with some different vars such as x and y position, direction (only up, down, left, right) and speed
however I also want a function like look where the "bacteria" collect information from the board object about what is in the Square above, below and to the sides of the bacteria).
How would I go about to create something like this?
(I know I could probably feed the information from the board to the bacteria everytime the bacteria move but is there a way for the object bacteria to request this information from the boardobject? (like if the bacteria can do 10 different things look, move, stay, hide...) but only one action per turn... I could feed the object bacteria with all info required all the time and only use the info i need every turn within the bacteria class... but I would rather have the bacteria to "ask the board" for only the specific info I want.
I'm not asking for full code just how I would do this in theory or even if it is possible.
Links to how objects interface with eachother would also be appreciated since I don't know what to search for.
Thanks

Re: How do objects interact with eachother
Posted: Thu Mar 20, 2014 11:27 am
by pickle
There shouldn't be functionality in the Bacteria class for determining what is in the cell above it. The Bacteria class should only be concerned with itself. The Bacteria class should access the Board class and inquire what is in a particular cell.
However, it's not manageable to make each Bacteria class have a separate instance of the Board. There should only be one Board object. However, in order to access that object, you can't simply use a class variable in your Bacteria objects. What you probably want to do is make the Board object a singleton class. A singleton class is one where you can create multiple Board objects, but they all refer to one instance. I won't get into it here - Google will help you.
Re: How do objects interact with eachother
Posted: Thu Mar 20, 2014 4:30 pm
by hybris
Hi thanks,
my idea was to create a class (bacteria) which objects behave like self-going robots when they are "released" onto the board. The "engine" within the bacteria would be a random generator from like 1 to 10 and depending on the outcome it would perform an action like move, stay, or look (ask the board what the surrounding cells contain and then perform an action based on that info).
I could skip to do the board as an object and instead create the board in the main loop and then spawn the bacterias in the main loop, then communication between the main loop is easy:
to send info from the main board to the bacteria:
bactria->gatherInfo($cellup_info, $celldown_info, $cellleft_info, $cell_right_info);
or to send info from the bacteria to the board
$bacteriaaction = bacteria->whatYourMove();
but what if I spawn 2 bacterias how do I comunicate between them inside the main loop? Can they have a function within the bacteria class to handle this or must I have an external function for that like:
if bacteria[1] and bacteria[2] is next to eachothers {
$b1=bacteria[1]->what_do_you_say();
$b2=bacteria[2]->what_do_you_say();
bacteria[1]->inc_msg($b2);
bacteria[2]->inc_msg($b1);
}
I know this is stupid and will lock the computer unless I use some exit function but I would like to spawn one or more object bacteria and then let them live their own lives and perform actions randomly like moving around on the grid and if they hit a wall change direction...
I thought I could do that if I do a condition loop within the class with a condition that is never met something like
while a > 0 {
a=1;
rnd 1 to 10
if 1 then $this->look()
if 2 then $this->move()
if 3 then $this->wait()
and so on
endif
$this->display()
}
if i do like the above would that result in small "robot bacterias" that move independently of eachother and if so how would that be handled on a cpu level (say the look function is complex and take 50ms to perform while the move is fast and take 1 ms to perform. If one bacteria get the random nr 1 3 times in a row it will mean that that bacteria will perform 3 actions in 150ms, if the other bacteria get 150 2s in a row (move) it will mean that bacteria will perform 150 actions in the same time the other bacteria performed 3 actions.
(This is actually what I want since it would be cool I think) EDIT: when using both my 2 braincells at the same time I think unless I do multithreading only one of the bacterias would move since the whileloop in the object that gets created first would probably lock the cpu? /EDIT
(The other approach i guess is to have the while loop within the main() and do it turn based so each bacteria perform one action every turn.)
Also say i create a food class would it be possible to have the food objects broadcast some info (come and eat me) to bacterias that are nearby?
Sorry for asking so unspecific, but Im quite new to php and OOP and I'm having a hard time to really understanding how to pass information between objects and what is possible and what is not..
Re: How do objects interact with eachother
Posted: Thu Mar 20, 2014 5:18 pm
by pickle
I think one of the fundamental misunderstandings you're having is how PHP operates. If you have a Bacteria object that is taking 50ms to do a task, then all other php tasks in that thread stop. There's no such thing as asynchronous actions between bits of PHP code that are run in the same thread.
A good analogy is gaming, where you've got real-time vs turn-based. It sounds like you want something to behave in real-time, where you start the program, and you've got all these different Bacteria that run on their own. In reality, with PHP, you'd be building a turn-based system where the main code runs through each Bacteria one at a time, asks what it wants to do, waits for the Bacteria to do it, then moves on to the next Bacteria.
How much experience do you have with PHP outside of OOP? I'm going to hazard a guess and say not very much. I'm not trying to be insulting, it's just normally when people want to get into PHP or OOP with PHP, they usually have pet projects that involve building a web site or web application. This application you're building is not very well suited for PHP. Sure it's possible to do, but it's not really PHP's bread-and-butter.
If you want to learn OOP as a concept, you're better off with Java, C++, or some other grade-A language that has excellent object-oriented constructs.
If you want to leart OOP in PHP, try building a web application. A common "Hello World" type application is a simple "to do" list.
Re: How do objects interact with eachother
Posted: Fri Mar 21, 2014 3:40 am
by hybris
Pickle thank You,
yes im quite new to PHP and OOP and i did some webpage where i used a class to create page objects and some other classes i could call... Now Im just trying to get a better understanding for objects and how they can interact and what limitations the PHP language has.
I do have a webrelated PHP question regarding the singleton... Can i use a singleton to carry over information between different users on the website without going trough the database. Im thinking of a function that shows logged in users where i create a singleton class user. When user 1 logs in the object is created. Then user 2 connects and is added to the object. If user 1 logout the object is still there until user 2 also logout then it is deconstructed... Would that be possible?
Thanks again for Your time. I really appreciate it.
Re: How do objects interact with eachother
Posted: Fri Mar 21, 2014 9:53 am
by pickle
A singleton object is not persistent - it will only exist during the time the PHP engine is running for your particular request. PHP is stateless by default. So every time you access a page, PHP loads, parses, and runs the requested PHP file, then completely forgets about you. The process repeats for every subsequent page.
Sessions, Cookies, and databases were included in the language to help maintain a state between subsequent page loads. However, sessions and cookies are bound to a particular user - there's no way to transfer information from one user's session/cookies to another user. For keeping track of logged-in users, you'll need to use a database. For every first-time page load, you create a row in your table. On every subsequent page load by that user (which you could safely key by their session_id), you update the last accessed time. To determine how many people are currently logged in, just do a count of the rows in that table that have been accessed in the last 5,10,30, or however many minutes you want.
Re: How do objects interact with eachother
Posted: Fri Mar 21, 2014 10:28 am
by hybris
Yeah thats sort of how I do it today. In the user table I have a time column and everytime a page is loaded or an action is performed by the user I update this time and then when I display active users its like time -10 minutes Idle time -30 minutes and logged out > 30 minutes.
I just wondered if there was any way to do this without going through the database but I guess not.
Thanks a bunch for your input, now I have a better understanding of what is possible and what is not.
1 thing that I still wonder though is if it is possible to send information directly between 2 objects using functions within the object class or if I must send all information between objects through an external function (like from the main loop)
This would (I think) be a way to send msg between 2 objects using what I mean an external function:
main()
apple1 = new fruit(apple);
apple2 = new fruit(apple);
if apple1 on square next to apple2 {
$tmp = apple1->get_msg();
apple2->inc_msg($tmp);
}
But is it possible to create a function within the class that sense if another apple is next to it and send a msg automatically ?
Re: How do objects interact with eachother
Posted: Fri Mar 21, 2014 10:59 am
by pickle
There's not really a good way. Every time you create a new apple, that variable has to be stored somewhere. When apple1 then wants to determine if there is an adjacent apple, it necessarily must be able to get information from the place in your code where those variables are stored. You can either do that by having the variables and accessing function in the global space (ie: not in a class), or you can use a singleton object to store and provide access to the variables.
The functionality for determining adjacency shouldn't be stored in the Apple class because it's outside the scope of the apple. Being adjacent is not something the Apple knows, because the Apple's "world" is just the apple. The Board is the object that can know if two Apple's are adjacent. Plus, what happens if you decide you want to make the board not a 2-dimensional plane, but rather a 3 dimensional matrix? As far as the Apple is concerned, it doesn't matter - it just wants to know if it's adjacent to something. The Board can then be recoded to account for a 3rd dimension. What happens if you decide to include Oranges? You shouldn't duplicate the functionality in the Orange class.
If I were doing this, I would implement the Board as a static class, so I could reference it like this:
Code: Select all
$have_neighbors = Board::hasNeighbors($this);
Then let the Board class do the work.
Re: How do objects interact with eachother
Posted: Mon Mar 24, 2014 12:47 pm
by hybris
Thanks a bunch Pickle,
i played around with a smallsystem where i created a robot class an armour class a board class and a weapon class and had the robots put on armour and weapon and battle it out.
Now I have a new question tough:
I want a backpack in the robot class so I declared the BP as an array and made a function addtobackpack($object) where i use count array to se if bp is full and if not i do array_push to add objects...
however i want a removefrombp($object) function but I dont know how to do that... any suggestions for how to do such a function?
Re: How do objects interact with eachother
Posted: Mon Mar 24, 2014 12:51 pm
by pickle
If the array is a simple numeric array, then you'll have to iterate through the array and check each item to see if it matches the passed object.
If the objects you're passing have a unique ID number, you could use that ID as the indices in the backpack. Then, when you want to remove a specific object, you could simply unset() that key.
Also, you don't need to use array_push(), you can just use the [] operator:
Code: Select all
function addtobackpack($object){
$this->BP[] = $object;
}
Re: How do objects interact with eachother
Posted: Mon Mar 24, 2014 3:39 pm
by hybris
Yeah I guess that would be faster too since I dont have to call a function.
What would be the best way to do a uniqe ID from a game creating point of view? Should I have some global function to assign uniqe id:s to all objects upon creation, or is it possible to assign a id to a object whithin the class (Im thinking in the __construct somehow) or should I go ahead with what I think namely to do it in my robotclass so the object gets an ID on pickup (since thats really only where it matters at least on the moment... later I probably want to assign id to objects in the gameworld (board) but then I could do a similar function within the class board... I dont think there will be a need to have the same id when carried as the object have in the world or am I missing something?
If each object that gets created shall have a uniqe ID how will i be sure not 2 ID are the same? I guess a global counter would be one way but say if I do a mmorpg (which I dont) there will be billions of items that is constructed and destructed.. I guess I could solve that with a function where i use a counter and then store the id from the destructed items in an array and then pick those first until the array is empty and then continue with the counter...
I have some stuff in the back of my head from school with some hashfunction that almost garantee a uniqe id but i totally forgot about it (or maybe Im remembering wrong... used to drink quite much back then so its mostly a blur hehe).
Re: How do objects interact with eachother
Posted: Mon Mar 24, 2014 3:50 pm
by pickle
I'm assuming you're not having any interaction with the database. You could use the uniqid() function to generate a unique id. Simply though, you could just use a counter variable.
I'd assign the ID to the object as soon as it's created. That ID should then stick with the object for as long as it exists.
I wouldn't worry too much about how this system would work when extrapolated to MMORPG scale. You've got to crawl before you can run - so just design for what you want now.
Re: How do objects interact with eachother
Posted: Mon Mar 24, 2014 4:36 pm
by hybris
Ok thanks

so I create id upon creation but my remove function wont work:
Code: Select all
public function RemoveFromBackpack($object){
$ItemsInBp=count($this->Backpack);
if($ItemsInBp>1){
for($i=0;$i<$ItemsInBp+1;$i++){
if($this->Backpack[$i] == $object){
unset($this->Backpack[$i]);
$this->Backpack[$i] = array_values($this->Backpack[$i]);
return true;}
}
} else{ echo "Cannot remove from an empty backpack"; return false;}
echo "Object not found in inventory"; return false;
}
It removes the objects but wont fix the array. If I place 3 items in the inventory and then remove them and print_r the array it says:
Array ( [0] => [1] => [2] => [3] => )
and then i add again:
Array ( [0] => [1] => [2] => [3] => [4] => weapon Object ( [ID:weapon:private] => 1))
it starts on 4...
i though array_values would fix it but no luck..
Re: How do objects interact with eachother
Posted: Mon Mar 24, 2014 4:40 pm
by hybris
nm found it... had the [$i] left in array_values
EDIT
$this->Backpack[$i] = array_values($this->Backpack[$i]);
Should be
$this->Backpack = array_values($this->Backpack);
/EDIT
Regarding the IDs Im not trying to make a mmo just wanted which way would be best design if you create and destroy many objects... the counter would sooner or later be very high number and I dont really see a point in having the same ID when passing the object between classes.. its enough the class currently holding the object to assign it an ID to differ from other objects of the same type that is held by the class(object)... or am i thinking wrong?
Like I have a board with 10 shoes and a human (with no shoe in inventory).. if the human pick up shoe 7 does it really matter if the ID in human backpack is shoe 1 and shoe 7 is removed from the world object? Then when the human drops the shoe in the future its world id maybe 102 (if more shoes were added)
If I want 1 ID that follows the object from creation I need to do it global right? I can spawn objects into the world but what if another object creates an object (like the human picks up a spell create food and use it to create food that appears in his backpack)
Re: How do objects interact with eachother
Posted: Mon Mar 24, 2014 4:46 pm
by pickle
If each object has a unique id, you shouldn't need to loop.
Your add function can look something like this:
Code: Select all
public function addToBackPack($id,$object){
$this->Backpack[$id] = $object;
}
// To call this function:
$Robot->addToBackPack($object->id,$object);
Notice how the id is being sent separately even though it exists in $object and could be accessed from the addToBackPack function. This is done to de-couple the step of determining the id from the $Robot class. This way, if you change the variable name, or the process to access it, you don't need to go into the $Robot class to update the functionality.
And your remove function can look like:
Code: Select all
public function removeFromBackpack($id){
unset($this->Backpack[$id]);
}