View Javadoc

1   /**********************************************
2    * Copyright (C) 2010 Lukas Laag
3    * This file is part of lib-gwt-svg-edu.
4    * 
5    * libgwtsvg-edu is free software: you can redistribute it and/or modify
6    * it under the terms of the GNU General Public License as published by
7    * the Free Software Foundation, either version 3 of the License, or
8    * (at your option) any later version.
9    * 
10   * libgwtsvg-edu is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   * 
15   * You should have received a copy of the GNU General Public License
16   * along with libgwtsvg-edu.  If not, see http://www.gnu.org/licenses/
17   **********************************************/
18  package org.vectomatic.svg.edu.client.maze;
19  
20  import java.util.Collection;
21  import java.util.HashMap;
22  import java.util.Map;
23  import java.util.Set;
24  
25  import com.google.gwt.user.client.Random;
26  
27  public abstract class Cell {
28  	protected Map<Cell, Boundary> boundaries;
29  	public Cell() {
30  		boundaries = new HashMap<Cell, Boundary>();
31  	}
32  	public abstract String getId();
33  	
34  	public Collection<Boundary> getBoundaries() {
35  		return boundaries.values();
36  	}
37  	public Set<Cell> getNeighbors() {
38  		return boundaries.keySet();
39  	}
40  	public Boundary getBoundary(Cell neighbor) {
41  		return boundaries.get(neighbor);
42  	}
43  	public boolean hasWall(Cell neighbor) {
44  		return boundaries.get(neighbor).hasWall();
45  	}
46  	public void setHasWall(Cell neighbor, boolean hasWall) {
47  		boundaries.get(neighbor).setHasWall(hasWall);
48  	}
49  	public boolean hasAllWalls() {
50  		for (Boundary boundary : boundaries.values()) {
51  			if (!boundary.hasWall()) {
52  				return false;
53  			}
54  		}
55  		return true;
56  	}
57  	public Cell getNeighborWithAllWalls() {
58  		int count = 0;
59      	for (Cell cell : getNeighbors()) {
60      		if (cell.hasAllWalls()) {
61      			count++;
62      		}
63      	}
64      	if (count > 0) {
65      		count = Random.nextInt(count);
66          	for (Cell cell : getNeighbors()) {
67          		if (cell.hasAllWalls()) {
68          			if (count == 0) {
69          				return cell;
70          			} else {
71                  		count--;
72          			}
73          		}
74          	}
75      	}
76      	return null;
77  	}
78  	
79  	@Override
80  	public String toString() {
81  		StringBuilder builder = new StringBuilder("[" + getId());
82  		if (boundaries.size() > 0) {
83  			builder.append(" : ");
84  		}
85  		for (Cell cell : boundaries.keySet()) {
86  			builder.append(cell.getId());
87  			builder.append(" ");
88  		}
89  		builder.append("]");
90  		return builder.toString();
91  	}
92  }