// Photon.java Copyright (c) 2004 brising.com import java.awt.Point; /** I travel across a field of GameButtons of various kinds. */ public class Photon extends Object implements Runnable { // INSTANCE VARIABLES ///////////////////////////////////////////////////////// GamePanel hoGamePanel; Point hpDirection; Point hpLocation; // CONSTRUCTORS /////////////////////////////////////////////////////////////// public Photon ( Point apLocation, Point apDirection, GamePanel aoGamePanel ) { hpDirection = new Point(apDirection); hpLocation = new Point(apLocation); hoGamePanel = aoGamePanel; } // PUBLIC INSTANCE METHODS //////////////////////////////////////////////////// /** Begin my travels. */ public void run ( ) { GameButton oGameButton = currentButton(); oGameButton.initiate(); while ((oGameButton = nextButton()).isPropagating()) {/* do nothing, but propagate through space */} oGameButton.terminate(); } // PROTECTED INSTANCE METHODS ///////////////////////////////////////////////// /** Which button am I currently in? */ protected GameButton currentButton ( ) { return getButton(hpLocation.x, hpLocation.y); } /** Get the button at the given coordinates. */ protected GameButton getButton ( int aiX, int aiY ) { return hoGamePanel.getButton(aiX, aiY); } /** Propagate to the next button. I do this by looking at the three buttons ahead of me: one directly in front, one diagonally to the left, one diagonally to the right. The combination of their occupiedness is combined into an integer, which is used to switch to the appropriate code. Return the next button in my travels. */ protected GameButton nextButton ( ) { int iXDirection = hpDirection.x; int iYDirection = hpDirection.y; int iXLocation = hpLocation.x+iXDirection; int iYLocation = hpLocation.y+iYDirection; int iState = 0x0 | ((getButton(iXLocation-iYDirection,iYLocation-iXDirection) .isOccupied()) ? 1 : 0) << 0 | ((getButton(iXLocation,iYLocation) .isOccupied()) ? 1 : 0) << 1 | ((getButton(iXLocation+iYDirection,iYLocation+iXDirection) .isOccupied()) ? 1 : 0) << 2; switch (iState) { default: throw new RuntimeException ("Unknown case in nextButton(): " +iState ); case 0: // go forward case 2: // go forward case 3: // go forward case 6: // go forward case 7: // go forward hpLocation.x += iXDirection; hpLocation.y += iYDirection; break; case 1: // turn one direction hpDirection.x = iYDirection; hpDirection.y = iXDirection; break; case 4: // turn the other direction hpDirection.x = -iYDirection; hpDirection.y = -iXDirection; break; case 5: // turn around and go back hpDirection.x = -iXDirection; hpDirection.y = -iYDirection; break; } return currentButton(); } }