package ptft; /* * JPtftCell.java * * Created on May 10, 2004, 5:38 PM */ import java.awt.*; import java.lang.reflect.Array; /** * A square cell which can paint itself using one of two different fields: * m_strategy inherited from JCell, and * m_ethnicity. To toggle the two views, use * toggleViews. * * @author Will Braynen */ public class JPtftCell extends JCell { // fields protected int m_ethnicity; protected NamedColorArray m_ethnicColors; protected boolean m_isStrategyDisplayed = true; /** Creates a new cell.*/ public JPtftCell( int row, int column, int cellWidth, NamedColorArray strategyColors, NamedColorArray ethnicColors ) { super (row, column, cellWidth, strategyColors); // set the fields m_ethnicColors = ethnicColors; setRandomEthnicity(); } // end constructor public boolean isStrategyDisplayed() { return m_isStrategyDisplayed; } public void toggleViews() { m_isStrategyDisplayed = ( ! m_isStrategyDisplayed ); } public void setRandomEthnicity() { setRandomEthnicity( null ); } /** * Pre-condition: any ethnicities[i] must be less than the total number of * ethnicities. * * @param ethnicities the array of ethnicities for the random pool; * for example, if m_ethnicColors has six colors * but you want to randomly pick only between * ethnicities 3 and 5, then ethnicities = { 3, 5 }. *

* If strategies is null or is empty, then picks * from the entire range of strategies. */ public void setRandomEthnicity( int[] ethnicities ) { if (null == ethnicities || 0 == ethnicities.length) { // pick from entire pool m_ethnicity = (int)(Math.random() * m_ethnicColors.getLength()); } else { m_ethnicity = getRandomNumber( ethnicities ); } } // end setRandomEthnicity public int getStrategy() { return getStrategy (null); } public int getStrategy( JPtftCell neighbor ) { // the cell is PTFT and we know the cell's neighbor if ((8 == m_strategy) && (null != neighbor)) { // if same color as neighbor, then return TFT // otherwise return AllD (AlwaysDefect) if (m_ethnicity == neighbor.m_ethnicity) return 6; // 6 = 110 = TFT else return 0; // 0 = 000 = AllD (AlwaysDefect) } else { return m_strategy; } } // end getStrategy public int getEthnicity() { return m_ethnicity; } // end getColor public void setEthnicity( int ethnicity ) { m_ethnicity = ethnicity; } // end setEthnicity public void paintComponent( Graphics g ) { g.setColor (m_isStrategyDisplayed ? m_strategyColors.getColor (m_strategy) : m_ethnicColors.getColor (m_ethnicity) ); g.fillRect (0, 0, m_width, m_width); } } // end class JPtftCell