From the post on the projects page, wordsearch, here is a basic design of a grid class that can be used to link together with the other aspects of a wordsearch game. This will be able to create a basic grid and populate it with characters.
The reason why I created the createGridRow function was because this class could be inherited and thus alter any aspects of the class to suit the future needs.
The
$this-> |
within the code references the local variables of the class and not any other variables e.g. local to that function.
The
chr(rand(0,25) + 97); |
means create a chr (character) from a random generated value within a range of 0 to 25 (26 letters in the English alphabet) and then add the value 97 to it, because the integer value of 97 – 125 are the ascii codes for a-z characters.
<?php class Grid { /* private section of the class grid */ // store the size and the grid private $_size = 0; private $_grid; /* the public section of the class grid */ // construct the grid with a given size public function __construct($size=0) { // set the private variables $this->_size = $size; $this->_grid = array(); for ($i =1; $i <= $this->_size; $i++) { // create each row of the grid with the class function createGridRow $this->_grid[$i] = $this->createGridRow(); } } // delete the grid public function __destruct() { // clear up the grid, each line and then the whole object. for ($i = 1; $i <= $this->_size; $i++) { unset($this->_grid[$i]); } unset($this->_grid); } /* createGridRow, this can be inherited and thus altered to create any type of character in the grid */ public function createGridRow() { $_grid_insert = array(); for ($j = 1; $j <= $this->_size; $j++) { $_grid_insert[$j] = chr(rand(0,25) + 97); } return $_grid_insert; } /* basic print out of a grid */ public function printOut() { echo "The grid<br/>"; for ($i = 1; $i <= $this->_size; $i++) { echo "$i .. "; for ($j = 1; $j <= $this->_size; $j++) { echo " $j = ".$this->_grid[$i][$j]; } echo "<br/>"; } } /* return the size of the grid */ public function returnSize() { return $this->_size; } /* insert a character into the grid at position X, Y and the character */ public function insertCharIntoGrid($pX, $pY, $char) { $this->_grid[$pY][$pX] = $char; } /* return the grid reference */ public function returnGrid() { return $this->_grid; } } $wordsearch_grid = new Grid(6); $wordsearch_grid->printOut(); ?> |
The output of the code as above is
The grid 1 .. 1 = l 2 = l 3 = z 4 = m 5 = h 6 = m 2 .. 1 = u 2 = r 3 = z 4 = s 5 = k 6 = y 3 .. 1 = f 2 = k 3 = j 4 = n 5 = k 6 = p 4 .. 1 = h 2 = p 3 = x 4 = o 5 = c 6 = q 5 .. 1 = s 2 = s 3 = x 4 = r 5 = u 6 = v 6 .. 1 = r 2 = f 3 = g 4 = q 5 = s 6 = o |