2D array in a class containing an object : error updating...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Planplan
Forum Newbie
Posts: 3
Joined: Sat Feb 25, 2006 1:57 pm

2D array in a class containing an object : error updating...

Post by Planplan »

Hello!
I'm not new in PHP, but here is my first try with a class (already use Java and C++, a while ago)
Sorry if my english is strange, but I'm french ;)
I'm trying to code a class for a map, for a game (with a "Field of View" for characters).
So I use a 2D array containing the object Cell, but I have a problem, seem that each time I try to modify "seen" for a cell, all cell are modfied... Maybe my constructor is wrong... I try a lot of thing but I must admit I don't know what I could try now...
Here my code, wish you could help me ;)

Code: Select all

<?php

class Cell
{
	public $tile = '.';
	public $seen = false;
}

class Map
{
	private $largeur;
	private $hauteur;
	private $cells = array();

	public function __construct($largeur, $hauteur)
	{
		$this->largeur = $largeur;
		$this->hauteur = $hauteur;
		$this->cells = array_fill(0, $largeur, array_fill(0, $hauteur, new Cell()));
	}

	public function onMap($x, $y)
	{
		return ($x >= 0 && $x < $this -> largeur && $y >= 0 && $y < $this -> hauteur);
	}

	public function setSeen($x, $y)
	{
		if(!Map::onMap($x, $y)) return;

		$this -> cells[$x][$y] -> seen = true;
	}

	public function display()
	{
		echo '<pre>';
		for($x = 0; $x < $this -> largeur; $x++)
		{
			for($y = 0; $y < $this -> hauteur; $y++)
			{
				if($this -> cells[$x][$y] -> seen)
				{
					//mvaddch($y, $x, $this -> cells[$x][$y] -> tile);
					echo $this -> cells[$x][$y] -> tile;
				}
				else
				{
					//mvaddch(y,x,' ');
					echo '#';
				}
				//--- Seem to be a problem here ---
				$this -> cells[$x][$y] -> seen = false;
			}
			echo '<br />';
		}
		echo '</pre>';
	}
}


//-----------------------------------------------------------------------------------------------------------------------------

$map = new Map(20, 20);
$map -> setSeen(5, 5);
$map -> display();

?>
Thanks in advance!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

yeah, your constructor is at fault due to it only passing a single instance of Cell around. Looks like you'll have to fill your grid "manually"
Post Reply