Holy crap Batman! It's the beginnings of refactoring the basic puzzle

stuff into Narya.


git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@2876 542714f4-19e9-0310-aa3c-eee0fc999fb1
This commit is contained in:
Michael Bayne
2003-11-26 01:42:34 +00:00
parent 0601c94e42
commit 54eaddb27d
53 changed files with 9395 additions and 0 deletions
@@ -0,0 +1,237 @@
//
// $Id: DropBlockSprite.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.client;
import java.awt.Rectangle;
import com.threerings.puzzle.Log;
/**
* The drop block sprite represents a block of multiple pieces that can be
* rotated to any of the four cardinal compass directions. As such, it
* may span multiple columns or rows depending on its orientation. The
* block has a "central" piece around which it rotates, with the other
* pieces referred to as "external" pieces.
*/
public class DropBlockSprite extends DropSprite
{
/**
* Constructs a drop block sprite and starts it dropping.
*
* @param view the board view upon which this sprite will be displayed.
* @param col the column of the central piece.
* @param row the row of the central piece.
* @param orient the orientation of the sprite.
* @param pieces the pieces displayed by the sprite.
*/
public DropBlockSprite (
DropBoardView view, int col, int row, int orient, int[] pieces)
{
super(view, col, row, pieces, 0);
_orient = orient;
}
/**
* Constructs a drop block sprite and starts it dropping.
*
* @param view the board view upon which this sprite will be displayed.
* @param col the column of the central piece.
* @param row the row of the central piece.
* @param orient the orientation of the sprite.
* @param pieces the pieces displayed by the sprite.
* @param renderOrder the rendering order of the sprite.
*/
public DropBlockSprite (
DropBoardView view, int col, int row, int orient, int[] pieces,
int renderOrder)
{
super(view, col, row, pieces, 0, renderOrder);
_orient = orient;
}
// documentation inherited
protected void init ()
{
super.init();
setOrientation(_orient);
}
/**
* Returns an array of the row numbers containing the block pieces.
* The first index is the row of the central piece. The array is
* cached and re-used internally and so the caller should make their
* own copy if they care to modify it.
*/
public int[] getRows ()
{
return _rows;
}
/**
* Returns an array of the column numbers containing the block pieces.
* The first index is the column of the central piece. The array is
* cached and re-used internally and so the caller should make their
* own copy if they care to modify it.
*/
public int[] getColumns ()
{
return _cols;
}
/**
* Returns the bounds of the block in board piece coordinates. The
* bounds rectangle is cached and re-used internally and so the caller
* should make their own copy if they care to modify it.
*/
public Rectangle getBoardBounds ()
{
return _dbounds;
}
/**
* Returns the row the external piece is located in.
*/
public int getExternalRow ()
{
return _erow;
}
/**
* Returns the column the external piece is located in.
*/
public int getExternalColumn ()
{
return _ecol;
}
// documentation inherited
public void setColumn (int col)
{
super.setColumn(col);
updateDropInfo();
}
// documentation inherited
public void setRow (int row)
{
super.setRow(row);
updateDropInfo();
}
// documentation inherited
public void setBoardLocation (int row, int col)
{
super.setBoardLocation(row, col);
updateDropInfo();
}
/**
* Updates the sprite image offset to reflect the direction in which
* the external piece is hanging.
*/
public void setOrientation (int orient)
{
super.setOrientation(orient);
int edx = 0, edy = 0;
if (orient == NORTH) {
edy = -1;
} else if (orient == WEST) {
edx = -1;
}
// update the sprite image offset
setRowOffset(edy);
setColumnOffset(edx);
// update the external piece position and drop block bounds
updateDropInfo();
}
// documentation inherited
public void toString (StringBuffer buf)
{
super.toString(buf);
buf.append(", erow=").append(_erow);
buf.append(", ecol=").append(_ecol);
}
/**
* Re-calculates the external piece position and bounds of the drop
* block.
*/
protected void updateDropInfo ()
{
// update the external piece location
_erow = calculateExternalRow();
_ecol = calculateExternalColumn();
// update the piece row and column arrays
_rows[0] = _row;
_rows[1] = _erow;
_cols[0] = _col;
_cols[1] = _ecol;
// calculate the drop block board bounds
int maxrow = Math.max(_row, _erow);
int mincol = Math.min(_col, _ecol);
int bpwid, bphei;
if (_orient == NORTH || _orient == SOUTH) {
bpwid = 1;
bphei = 2;
} else {
bpwid = 2;
bphei = 1;
}
// create the bounds rectangle if necessary
_dbounds.setBounds(mincol, maxrow, bpwid, bphei);
}
/**
* Returns the row the external piece is located in based on the
* current central piece location and sprite orientation.
*/
protected int calculateExternalRow ()
{
if (_orient == NORTH) {
return (_row - 1);
} else if (_orient == SOUTH) {
return (_row + 1);
} else {
return _row;
}
}
/**
* Returns the column the external piece is located in based on the
* current central piece location and sprite orientation.
*/
protected int calculateExternalColumn ()
{
if (_orient == WEST) {
return (_col - 1);
} else if (_orient == EAST) {
return (_col + 1);
} else {
return _col;
}
}
/** The drop block bounds in board coordinates. */
protected Rectangle _dbounds = new Rectangle();
/** The drop block piece rows. */
protected int[] _rows = new int[2];
/** The drop block piece columns. */
protected int[] _cols = new int[2];
/** The external piece location in board coordinates. */
protected int _ecol, _erow;
}
@@ -0,0 +1,370 @@
//
// $Id: DropBoardView.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.client;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.util.Iterator;
import com.samskivert.swing.Label;
import com.threerings.media.image.Mirage;
import com.threerings.media.sprite.Sprite;
import com.threerings.yohoho.client.YoUI;
import com.threerings.puzzle.util.PuzzleContext;
import com.threerings.puzzle.Log;
import com.threerings.puzzle.client.PuzzleBoardView;
import com.threerings.puzzle.client.ScoreAnimation;
import com.threerings.puzzle.data.Board;
import com.threerings.puzzle.data.PuzzleConfig;
import com.threerings.puzzle.drop.data.DropBoard;
import com.threerings.puzzle.drop.data.DropConfig;
import com.threerings.puzzle.drop.data.DropPieceCodes;
/**
* The drop board view displays a drop puzzle game in progress for a
* single player.
*/
public abstract class DropBoardView extends PuzzleBoardView
implements DropPieceCodes
{
/** The color used to render normal scoring text. */
public static final Color SCORE_COLOR = Color.white;
/** The color used to render chain reward scoring text. */
public static final Color CHAIN_COLOR = Color.yellow;
/**
* Constructs a drop board view.
*/
public DropBoardView (PuzzleContext ctx, int pwid, int phei)
{
super(ctx);
// save off piece dimensions
_pwid = pwid;
_phei = phei;
// determine distance to float score animations
_scoreDist = 2 * _phei;
}
/**
* Initializes the board with the board dimensions.
*/
public void init (PuzzleConfig config)
{
DropConfig dconfig = (DropConfig)config;
// save off the board dimensions in pieces
_bwid = dconfig.getBoardWidth();
_bhei = dconfig.getBoardHeight();
super.init(config);
}
/**
* Returns the width in pixels of a single board piece.
*/
public int getPieceWidth ()
{
return _pwid;
}
/**
* Returns the height in pixels of a single board piece.
*/
public int getPieceHeight ()
{
return _phei;
}
/**
* Called by the {@link DropSprite} to populate <code>pos</code> with
* the screen coordinates in pixels at which a piece at <code>(col,
* row)</code> in the board should be drawn. Derived classes may wish
* to override this method to allow specialised positioning of
* sprites.
*/
public void getPiecePosition (int col, int row, Point pos)
{
pos.setLocation(col * _pwid, (row * _phei) - _roff);
}
/**
* Called by the {@link DropSprite} to get the dimensions of the area
* that will be occupied by rendering a piece segment of the given
* orientation and length whose bottom-leftmost corner is at
* <code>(col, row)</code>.
*/
public Dimension getPieceSegmentSize (int col, int row, int orient, int len)
{
if (orient == NORTH || orient == SOUTH) {
return new Dimension(_pwid, len * _phei);
} else {
return new Dimension(len * _pwid, _phei);
}
}
/**
* Dirties the rectangle encompassing the piece segment with the given
* direction and length whose bottom-leftmost corner is at <code>(col,
* row)</code>.
*/
public void dirtySegment (int dir, int col, int row, int len)
{
int x = _pwid * col, y = (_phei * row) - _roff;
int wid = (dir == VERTICAL) ? _pwid : len * _pwid;
int hei = (dir == VERTICAL) ? _phei * len : _phei;
_remgr.invalidateRegion(x, y, wid, hei);
}
/**
* Dirties the rectangle encompassing the specified piece in the
* board.
*/
public void dirtyPiece (int col, int row)
{
_remgr.invalidateRegion(_pwid * col, (_phei * row) - _roff,
_pwid, _phei);
}
/**
* Dirties a rectangular region of pieces.
*/
public void dirtyPieces (int xx, int yy, int width, int height)
{
_remgr.invalidateRegion(xx*_pwid, yy*_phei, width*_pwid, height*_phei);
}
/**
* Returns the image used to display the given piece at coordinates
* <code>(0, 0)</code> with an orientation of {@link #NORTH}. This
* serves as a convenience routine for those puzzles that don't bother
* rendering their pieces differently when placed at different board
* coordinates or in different orientations.
*/
public Mirage getPieceImage (int piece)
{
return getPieceImage(piece, 0, 0, NORTH);
}
/**
* Returns the image used to display the given piece at the specified
* column and row with the given orientation.
*/
public abstract Mirage getPieceImage (
int piece, int col, int row, int orient);
// documentation inherited
public void setBoard (Board board)
{
// when a new board arrives, we want to remove all drop sprites
// so that they don't modify the new board with their old ideas
for (Iterator iter = _actionSprites.iterator(); iter.hasNext(); ) {
Sprite s = (Sprite) iter.next();
if (s instanceof DropSprite) {
// remove it from _sprites safely
iter.remove();
// but then use the standard removal method
removeSprite(s);
}
}
super.setBoard(board);
_dboard = (DropBoard)board;
}
/**
* Creates a new drop sprite used to animate the given pieces falling
* in the specified column.
*/
public DropSprite createPieces (int col, int row, int[] pieces, int dist)
{
return new DropSprite(this, col, row, pieces, dist);
}
/**
* Creates and returns an animation which makes use of a label sprite
* that is assigned a path that floats it a short distance up the
* view, with the label initially centered within the view.
*
* @param score the score text to display.
* @param color the color of the text.
*/
public ScoreAnimation createScoreAnimation (String score, Color color)
{
return createScoreAnimation(
score, color, MEDIUM_FONT_SIZE, 0, _bhei - 1, _bwid, _bhei);
}
/**
* Creates and returns an animation showing the specified score
* floating up the view, with the label initially centered within the
* view.
*
* @param score the score text to display.
* @param color the color of the text.
* @param fontSize the size of the text; a value between 0 and {@link
* #getPuzzleFontSizeCount} - 1.
*/
public ScoreAnimation createScoreAnimation (
String score, Color color, int fontSize)
{
return createScoreAnimation(
score, color, fontSize, 0, _bhei - 1, _bwid, _bhei);
}
/**
* Creates and returns an animation showing the specified score
* floating up the view.
*
* @param score the score text to display.
* @param color the color of the text.
* @param x the left coordinate in board coordinates of the rectangle
* within which the score is to be centered.
* @param y the bottom coordinate in board coordinates of the
* rectangle within which the score is to be centered.
* @param width the width in board coordinates of the rectangle within
* which the score is to be centered.
* @param height the height in board coordinates of the rectangle
* within which the score is to be centered.
*/
public ScoreAnimation createScoreAnimation (
String score, Color color, int x, int y, int width, int height)
{
return createScoreAnimation(
score, color, MEDIUM_FONT_SIZE, x, y, width, height);
}
/**
* Creates and returns an animation showing the specified score
* floating up the view.
*
* @param score the score text to display.
* @param color the color of the text.
* @param fontSize the size of the text; a value between 0 and {@link
* #getPuzzleFontSizeCount} - 1.
* @param x the left coordinate in board coordinates of the rectangle
* within which the score is to be centered.
* @param y the bottom coordinate in board coordinates of the
* rectangle within which the score is to be centered.
* @param width the width in board coordinates of the rectangle within
* which the score is to be centered.
* @param height the height in board coordinates of the rectangle
* within which the score is to be centered.
*/
public ScoreAnimation createScoreAnimation (String score, Color color,
int fontSize, int x, int y,
int width, int height)
{
// create the score animation
ScoreAnimation anim =
createScoreAnimation(score, color, fontSize, x, y);
// position the label within the specified rectangle
Dimension lsize = anim.getLabel().getSize();
Point pos = new Point();
centerRectInBoardRect(
x, y, width, height, lsize.width, lsize.height, pos);
anim.setLocation(pos.x, pos.y);
return anim;
}
/**
* Populates <code>pos</code> with the most appropriate screen
* coordinates to center a rectangle of the given width and height (in
* pixels) within the specified rectangle (in board coordinates).
*
* @param bx the bounding rectangle's left board coordinate.
* @param by the bounding rectangle's bottom board coordinate.
* @param bwid the bounding rectangle's width in board coordinates.
* @param bhei the bounding rectangle's height in board coordinates.
* @param rwid the width of the rectangle to position in pixels.
* @param rhei the height of the rectangle to position in pixels.
* @param pos the point to populate with the rectangle's final
* position.
*/
protected void centerRectInBoardRect (
int bx, int by, int bwid, int bhei, int rwid, int rhei, Point pos)
{
getPiecePosition(bx, by + 1, pos);
pos.x += (((bwid * _pwid) - rwid) / 2);
pos.y -= ((((bhei * _phei) - rhei) / 2) + rhei);
// constrain to fit wholly within the board bounds
pos.x = Math.max(Math.min(pos.x, _bounds.width - rwid), 0);
}
/**
* Rotates the given drop block sprite to the specified orientation,
* updating the image as necessary. Derived classes that make use of
* block dropping functionality should override this method to do the
* right thing.
*/
public void rotateDropBlock (DropBlockSprite sprite, int orient)
{
// nothing for now
}
// documentation inherited
public void paintBetween (Graphics2D gfx, Rectangle dirtyRect)
{
gfx.translate(0, -_roff);
renderBoard(gfx, dirtyRect);
renderRisingPieces(gfx, dirtyRect);
gfx.translate(0, _roff);
}
// documentation inherited
public Dimension getPreferredSize ()
{
int wid = _bwid * _pwid;
int hei = _bhei * _phei;
return new Dimension(wid, hei);
}
/**
* Renders the row of rising pieces to the given graphics context.
* Sub-classes that make use of board rising functionality should
* override this method to draw the rising piece row.
*/
protected void renderRisingPieces (Graphics2D gfx, Rectangle dirtyRect)
{
// nothing for now
}
/**
* Sets the board rising offset to the given y-position.
*/
protected void setRiseOffset (int y)
{
if (y != _roff) {
_roff = y;
_remgr.invalidateRegion(_bounds);
}
}
/** The drop board. */
protected DropBoard _dboard;
/** The piece dimensions in pixels. */
protected int _pwid, _phei;
/** The board rising offset. */
protected int _roff;
/** The board dimensions in pieces. */
protected int _bwid, _bhei;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,23 @@
//
// $Id: DropPanel.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.client;
import com.threerings.puzzle.data.BoardSummary;
/**
* Puzzles using the drop services need implement this interface to
* display drop puzzle related information.
*/
public interface DropPanel
{
/**
* Sets the next block to be displayed.
*/
public void setNextBlock (int[] pieces);
/**
* Updates the board summary display for the given player.
*/
public void setSummary (int pidx, BoardSummary summary);
}
@@ -0,0 +1,566 @@
//
// $Id: DropSprite.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.client;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import com.samskivert.util.ObserverList;
import com.threerings.util.DirectionUtil;
import com.threerings.media.image.Mirage;
import com.threerings.media.sprite.Sprite;
import com.threerings.media.tile.TileManager;
import com.threerings.puzzle.Log;
/**
* The drop sprite is a sprite that displays one or more pieces falling
* toward the bottom of the board.
*/
public class DropSprite extends Sprite
{
/**
* Constructs a drop sprite and starts it dropping.
*
* @param view the board view upon which this sprite will be displayed.
* @param col the column of the sprite.
* @param row the row of the bottom-most piece.
* @param pieces the pieces displayed by the sprite.
* @param dist the distance the sprite is to drop in rows.
*/
public DropSprite (
DropBoardView view, int col, int row, int[] pieces, int dist)
{
this(view, col, row, pieces, dist, -1);
}
/**
* Constructs a drop sprite and starts it dropping.
*
* @param view the board view upon which this sprite will be displayed.
* @param col the column of the sprite.
* @param row the row of the bottom-most piece.
* @param pieces the pieces displayed by the sprite.
* @param dist the distance the sprite is to drop in rows.
* @param renderOrder the render order.
*/
public DropSprite (
DropBoardView view, int col, int row, int[] pieces, int dist,
int renderOrder)
{
_view = view;
_col = col;
_row = row;
_pieces = pieces;
_dist = (dist == 0) ? 1 : dist;
_orient = NORTH;
_unit = _view.getPieceHeight();
setRenderOrder(renderOrder);
}
// documentation inherited
protected void init ()
{
super.init();
// size the bounds to fit our pieces
updateBounds();
// set up the piece location
setBoardLocation(_row, _col);
// calculate vertical render offset based on the number of pieces
setRowOffset(-(_pieces.length - 1));
}
/**
* Returns the remaining number of columns to drop.
*/
public int getDistance ()
{
return _dist;
}
/**
* Returns the column the piece is located in.
*/
public int getColumn ()
{
return _col;
}
/**
* Returns the row the piece is located in.
*/
public int getRow ()
{
return _row;
}
/**
* Returns the pieces the sprite is displaying.
*/
public int[] getPieces ()
{
return _pieces;
}
/**
* Returns the velocity of this sprite.
*/
public float getVelocity ()
{
return _vel;
}
/**
* Sets the row and column the piece is located in.
*/
public void setBoardLocation (int row, int col)
{
_row = row;
_col = col;
updatePosition();
}
/**
* Sets the column the piece is located in.
*/
public void setColumn (int col)
{
_col = col;
updatePosition();
}
/**
* Set the row the piece is located in.
*/
public void setRow (int row)
{
_row = row;
updatePosition();
}
/**
* Sets the column offset of the sprite image.
*/
public void setColumnOffset (int count)
{
_offx = count;
updateRenderOffset();
updateRenderOrigin();
}
/**
* Sets the row offset of the sprite image.
*/
public void setRowOffset (int count)
{
_offy = count;
updateRenderOffset();
updateRenderOrigin();
}
/**
* Sets the pieces the sprite is displaying.
*/
public void setPieces (int[] pieces)
{
_pieces = pieces;
}
/**
* Sets the velocity of this sprite. The time at which the current
* row was entered is modified so that the sprite position will remain
* the same when calculated using the new velocity since the piece
* sprite may have its velocity modified in the middle of a row
* traversal.
*/
public void setVelocity (float velocity)
{
// bail if we've already got the requested velocity
if (_vel == velocity) {
return;
}
if (_rowstamp > 0) {
// get our current distance along the row
long now = _view.getTimeStamp();
float pctdone = getPercentDone(now);
// revise the current row entry time to account for the new velocity
float travpix = pctdone * _unit;
long msecs = (long)(travpix / velocity);
_rowstamp = now - msecs;
}
// update the velocity
_vel = velocity;
}
/**
* Starts the piece dropping toward the next row.
*/
public void drop ()
{
// Log.info("Dropping piece [piece=" + this + "].");
// drop one row by default
if (_dist <= 0) {
_dist = 1;
}
if (_stopstamp > 0) {
// we're dropping from a stand-still
long delta = _view.getTimeStamp() - _stopstamp;
_rowstamp += delta;
_stopstamp = 0;
} else {
// we're continuing a previous drop, so make use of any
// previously existing time
_rowstamp = _endstamp;
}
}
/**
* Returns true if this drop sprite is dropping, false if it has been
* {@link #stop}ped or has not yet been {@link #drop}ped.
*/
public boolean isDropping ()
{
return (_stopstamp == 0) && (_rowstamp != 0);
}
/**
* Stops the piece from dropping.
*/
public void stop ()
{
if (_stopstamp == 0) {
_stopstamp = _view.getTimeStamp();
// Log.info("Stopped piece [piece=" + this + "].");
}
}
/**
* Puts the drop sprite into (or takes it out of) bouncing
* mode. Bouncing mode is used to put the sprite into limbo after it
* lands but before we commit the landing, giving the user a last
* moment change move or rotate the piece. While the sprite is
* "bouncing" it will be rendered one pixel below it's at rest state.
*/
public void setBouncing (boolean bouncing)
{
if (_bouncing = bouncing) {
// if we've activated bouncing, shift the sprite slightly to
// illustrate its new state
shiftForBounce();
// to prevent funny business in the event that we were a long
// ways past the end of the row when we landed, we warp the
// sprite back to the exact point of landing for the purposes
// of the bounce and any subsequent antics
_endstamp = _rowstamp = _view.getTimeStamp();
// Log.info("Adjusted rowstap due to bounce " +
// "[time=" + _endstamp + "].");
}
}
/**
* Returns true if this sprite is bouncing.
*/
public boolean isBouncing ()
{
return _bouncing;
}
/**
* Updates the sprite's location to illustrate that it is currently in
* the "bouncing" state.
*/
protected void shiftForBounce ()
{
setLocation(_ox, _srcPos.y+1);
}
// documentation inherited
public boolean inside (Shape shape)
{
return shape.contains(_bounds);
}
/**
* Returns a value between <code>0.0</code> and <code>1.0</code>
* representing how far the piece has moved toward the next row
* as of the given time stamp.
*/
public float getPercentDone (long timestamp)
{
// if we've never been ticked and so haven't yet initialized our
// row start timestamp, just let the caller know that we've not
// traversed our row at all
if (_rowstamp == 0) {
return 0.0f;
}
long msecs = Math.max(0, timestamp - _rowstamp);
float travpix = msecs * _vel;
float pctdone = (travpix / _unit);
// Log.info("getPercentDone [timestamp=" + timestamp +
// ", rowstamp=" + _rowstamp + ", msecs=" + msecs +
// ", travpix=" + travpix + ", pctdone=" + pctdone +
// ", vel=" + _vel + "].");
return pctdone;
}
// documentation inherited
public void paint (Graphics2D gfx)
{
// get the column and row increment based on the sprite's orientation
int oidx = _orient/2;
int incx = ORIENT_DX[oidx];
int incy = ORIENT_DY[oidx];
// determine offset from the start of each actual row and column
int dx = _ox - _srcPos.x, dy = _oy - _srcPos.y;
int pcol = _col, prow = _row;
for (int ii = 0; ii < _pieces.length; ii++) {
// ask the board for the render position of this piece
_view.getPiecePosition(pcol, prow, _renderPos);
// draw the piece image
paintPieceImage(gfx, ii, pcol, prow, _orient,
_renderPos.x + dx, _renderPos.y + dy);
// increment the target column and row
pcol += incx;
prow += incy;
}
}
/**
* Paints the specified piece with the supplied parameters.
*/
protected void paintPieceImage (Graphics2D gfx, int pieceidx,
int col, int row, int orient, int x, int y)
{
Mirage image = _view.getPieceImage(_pieces[pieceidx], col, row, orient);
image.paint(gfx, x, y);
}
// documentation inherited
public void tick (long timestamp)
{
super.tick(timestamp);
// initialize our rowstamp if we haven't done so already
if (_rowstamp == 0) {
_rowstamp = timestamp;
}
// if we're bouncing or paused, do nothing here
if (_bouncing || _stopstamp > 0) {
return;
}
PieceMovedOp pmop = null;
// figure out how far along the current board coordinate we should be
float pctdone = getPercentDone(timestamp);
if (pctdone >= 1.0f) {
// note that we've reached the next row
advancePosition();
// update remaining drop distance
_dist--;
// calculate any remaining time to be used
long used = (long)(_unit / _vel);
_endstamp = _rowstamp + used;
_rowstamp = _endstamp;
// update our percent done because we've moved down a row
pctdone -= 1.0;
// inform observers that we've reached our destination
pmop = new PieceMovedOp(this, timestamp, _col, _row);
}
// Log.info("Drop sprite tick [dist=" + _dist + ", pctdone=" + pctdone +
// ", row=" + _row + ", col=" + _col + "].");
// constrain the sprite's position to the destination row
pctdone = Math.min(pctdone, 1.0f);
// calculate the latest sprite position
int nx = _srcPos.x + (int)((_destPos.x - _srcPos.x) * pctdone);
int ny = _srcPos.y + (int)((_destPos.y - _srcPos.y) * pctdone);
// only update the sprite's location if it actually moved
if (_ox != nx || _oy != ny) {
setLocation(nx, ny);
}
// lastly notify our observers if we made it to the next row
if (pmop != null) {
_observers.apply(pmop);
}
}
/**
* Called when the sprite has finished traversing its current row to
* advance its board coordinates to the next row.
*/
protected void advancePosition ()
{
setRow(_row + 1);
// Log.info("Moved to row " + _row);
}
// documentation inherited
public void fastForward (long timeDelta)
{
if (_rowstamp > 0) {
_rowstamp += timeDelta;
}
}
// documentation inherited
public void toString (StringBuffer buf)
{
super.toString(buf);
buf.append(", orient=").append(DirectionUtil.toShortString(_orient));
buf.append(", row=").append(_row);
buf.append(", col=").append(_col);
buf.append(", offx=").append(_offx);
buf.append(", offy=").append(_offy);
buf.append(", dist=").append(_dist);
}
/**
* Updates internal pixel coordinates used when the piece is moving.
*/
protected void updatePosition ()
{
_view.getPiecePosition(_col, _row, _srcPos);
_view.getPiecePosition(_col, _row+1, _destPos);
setLocation(_srcPos.x, _srcPos.y);
}
// documentation inherited
public void setOrientation (int orient)
{
invalidate();
super.setOrientation(orient);
updateBounds();
invalidate();
}
/**
* Updates the bounds for this sprite based on the sprite display
* dimensions in the view.
*/
protected void updateBounds ()
{
Dimension size = _view.getPieceSegmentSize(
_col, _row, _orient, _pieces.length);
_bounds.width = size.width;
_bounds.height = size.height;
}
/**
* Adjusts our render origin such that our location is not in the
* upper left of the sprite's rendered image but is in fact offset by
* some number of rows and columns.
*/
protected void updateRenderOffset ()
{
_oxoff = -(_view.getPieceWidth() * _offx);
_oyoff = -(_view.getPieceHeight() * _offy);
}
/** Used to dispatch {@link DropSpriteObserver#pieceMoved}. */
protected static class PieceMovedOp implements ObserverList.ObserverOp
{
public PieceMovedOp (DropSprite sprite, long when, int col, int row)
{
_sprite = sprite;
_when = when;
_col = col;
_row = row;
}
public boolean apply (Object observer)
{
if (observer instanceof DropSpriteObserver) {
((DropSpriteObserver)observer).pieceMoved(
_sprite, _when, _col, _row);
}
return true;
}
protected DropSprite _sprite;
protected long _when;
protected int _col, _row;
}
/** The default piece velocity. */
protected static final float DEFAULT_VELOCITY = 30f/1000f;
/** The time at which we started the current row. */
protected long _rowstamp;
/** The time at which we reached the end of the previous row. */
protected long _endstamp;
/** The time at which we were stopped en route to our next row. */
protected long _stopstamp;
/** The board view upon which this sprite is displayed. */
protected DropBoardView _view;
/** The unit distance the sprite moves to reach the next row. */
protected int _unit;
/** The screen coordinates of the top-left of the row currently
* occupied by the sprite. */
protected Point _srcPos = new Point();
/** The screen coordinates of the top-left of the row toward which the
* sprite is falling. */
protected Point _destPos = new Point();
/** The piece render position; used as working data when determining
* where to render each piece in the sprite. */
protected Point _renderPos = new Point();
/** The number of rows remaining to drop. */
protected int _dist;
/** The piece velocity. */
protected float _vel = DEFAULT_VELOCITY;
/** The offsets in columns or rows at which the piece is rendered. */
protected int _offx, _offy;
/** The current piece location in the board. */
protected int _row, _col;
/** The pieces this sprite is displaying. */
protected int[] _pieces;
/** Indicates that the drop sprite is bouncing; see {@link
* #setBouncing}. */
protected boolean _bouncing;
// used to compute the column and row increment while rendering the
// sprite's pieces based on its orientation
// W N E S
protected static final int[] ORIENT_DX = { -1, 0, 1, 0 };
protected static final int[] ORIENT_DY = { 0, -1, 0, 1 };
}
@@ -0,0 +1,16 @@
//
// $Id: DropSpriteObserver.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.client;
/**
* Provides notifications for drop puzzle specific stuff.
*/
public interface DropSpriteObserver
{
/**
* Called when the drop sprite has moved completely to the specified
* board coordinates.
*/
public void pieceMoved (DropSprite sprite, long when, int col, int row);
}
@@ -0,0 +1,93 @@
//
// $Id: NextBlockView.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.client;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.border.Border;
import com.threerings.media.image.Mirage;
import com.threerings.util.DirectionCodes;
/**
* The next block view displays an image representing the next drop block
* to appear in the game.
*/
public class NextBlockView extends JComponent
implements DirectionCodes
{
/**
* Constructs a next block view.
*/
public NextBlockView (DropBoardView view, int pwid, int phei, int orient)
{
// save things off
_view = view;
_pwid = pwid;
_phei = phei;
_orient = orient;
// configure the component
setOpaque(false);
}
/**
* Sets the pieces displayed by the view.
*/
public void setPieces (int[] pieces)
{
_pieces = pieces;
repaint();
}
// documentation inherited
public void paintComponent (Graphics g)
{
super.paintComponent(g);
// draw the pieces
Graphics2D gfx = (Graphics2D)g;
if (_pieces != null) {
Dimension size = getSize();
int xpos = (_orient == VERTICAL) ? 0 : (size.width - _pwid);
int ypos = (_orient == VERTICAL) ? (size.height - _phei) : 0;
for (int ii = 0; ii < _pieces.length; ii++) {
Mirage image = _view.getPieceImage(_pieces[ii]);
image.paint(gfx, xpos, ypos);
if (_orient == VERTICAL) {
ypos -= _phei;
} else {
xpos -= _pwid;
}
}
}
}
// documentation inherited
public Dimension getPreferredSize ()
{
int wid = (_orient == VERTICAL) ? _pwid : (2 * _pwid);
int hei = (_orient == VERTICAL) ? (2 * _phei) : _phei;
return new Dimension(wid, hei);
}
/** The drop board view from which we obtain piece images. */
protected DropBoardView _view;
/** The pieces displayed by this view. */
protected int[] _pieces;
/** The piece dimensions in pixels. */
protected int _pwid, _phei;
/** The view orientation; one of {@link #HORIZONTAL} or {@link
* #VERTICAL}. */
protected int _orient;
}
@@ -0,0 +1,152 @@
//
// $Id: ByteDropBoard.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.data;
import java.util.Arrays;
import com.threerings.puzzle.Log;
/**
* The byte drop board extends the {@link DropBoard}, making use of a
* <code>byte</code> array of pieces to store the board contents.
*/
public class ByteDropBoard extends DropBoard
{
/**
* Constructs an empty byte drop board for use when unserializing.
*/
public ByteDropBoard ()
{
this(null, 0, 0);
}
/**
* Constructs a byte drop board of the given dimensions with its
* pieces initialized to 0.
*/
public ByteDropBoard (int bwid, int bhei)
{
this(new byte[bwid*bhei], bwid, bhei);
fill(PIECE_NONE);
}
/**
* Constructs a byte drop board of the given dimensions with its
* pieces initialized to the given piece.
*/
public ByteDropBoard (int bwid, int bhei, byte piece)
{
this(new byte[bwid*bhei], bwid, bhei);
fill(piece);
}
/**
* Constructs a byte drop board with the given board and dimensions.
*/
public ByteDropBoard (byte[] board, int bwid, int bhei)
{
_board = board;
_bwid = bwid;
_bhei = bhei;
}
// documentation inherited from interface
public int getPiece (int col, int row)
{
try {
return _board[(row*_bwid) + col];
} catch (Exception e) {
Log.warning("Failed getting piece [col=" + col +
", row=" + row + ", error=" + e + "].");
Log.logStackTrace(e);
return -1;
}
}
// documentation inherited from interface
public void fill (int piece)
{
Arrays.fill(_board, (byte)piece);
}
/**
* Sets the board data and board dimensions.
*/
public void setBoard (byte[] board, int bwid, int bhei)
{
_board = board;
_bwid = bwid;
_bhei = bhei;
}
/**
* Sets the board pieces.
*/
public void setBoard (byte[] board)
{
int size = (_bwid*_bhei);
if (board.length < size) {
Log.warning("Attempt to set board with invalid data size " +
"[len=" + board.length + ", expected=" + size + "].");
return;
}
_board = board;
}
// documentation inherited from interface
public boolean setPiece (int col, int row, int piece)
{
if (col >= 0 && row >= 0 && col < _bwid && row < _bhei) {
_board[(row*_bwid) + col] = (byte)piece;
return true;
} else {
Log.warning("Attempt to set piece outside board bounds " +
"[col=" + col + ", row=" + row + ", p=" + piece + "].");
return false;
}
}
// documentation inherited from interface
public void copyInto (DropBoard board)
{
// make sure the target board is a valid target
if (board.getWidth() != _bwid || board.getHeight() != _bhei) {
Log.warning("Can't copy board into destination board with " +
"different dimensions [src=" + this +
", dest=" + board + "].");
return;
}
// copy our pieces directly into the board, avoiding any unsightly
// object allocation which is largely the point of this method,
// after all.
byte[] dest = ((ByteDropBoard)board).getBoard();
System.arraycopy(_board, 0, dest, 0, (_bwid*_bhei));
}
// documentation inherited
public Object clone ()
{
ByteDropBoard board = (ByteDropBoard)super.clone();
int size = _bwid*_bhei;
board._board = new byte[size];
System.arraycopy(_board, 0, board._board, 0, size);
return board;
}
/**
* Returns the raw board data associated with this board. One
* shouldn't fiddle about with this unless one knows what one is
* doing.
*/
public byte[] getBoard ()
{
return _board;
}
/** The board data. */
protected byte[] _board;
}
@@ -0,0 +1,738 @@
//
// $Id: DropBoard.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.data;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.Arrays;
import org.apache.commons.lang.Strings;
import com.threerings.util.DirectionCodes;
import com.threerings.util.DirectionUtil;
import com.threerings.puzzle.Log;
import com.threerings.puzzle.data.Board;
import com.threerings.puzzle.drop.client.DropControllerDelegate;
import com.threerings.puzzle.drop.data.DropPieceCodes;
import com.threerings.puzzle.drop.util.DropBoardUtil;
/**
* An abstract class that provides for various useful logical operations
* to be enacted on a two-dimensional board and provides an easier
* mechanism for referencing pieces by position.
*/
public abstract class DropBoard extends Board
implements DropPieceCodes
{
/** The rotation constant for rotation around a central piece. */
public static final int RADIAL_ROTATION = 0;
/** The rotation constant for rotation wherein the block occupies the
* same columns when rotating. */
public static final int INPLACE_ROTATION = 1;
/** An operation that does naught but clear pieces, which proves to be
* generally useful. */
public static final PieceOperation CLEAR_OP = new PieceOperation () {
public boolean execute (DropBoard board, int col, int row) {
board.setPiece(col, row, PIECE_NONE);
return true;
}
};
/**
* An interface to be implemented by classes that would like to apply
* some operation to each piece in a column or row segment in the
* board.
*/
public interface PieceOperation
{
/**
* Called for each piece in the board segment the operation is
* being applied to.
*
* @return true if the operation should continue to be applied if
* being applied to multiple pieces, or false if it should
* terminate after this application.
*/
public boolean execute (DropBoard board, int col, int row);
}
/**
* Returns the width of the board in columns.
*/
public int getWidth()
{
return _bwid;
}
/**
* Returns the height of the board in rows.
*/
public int getHeight()
{
return _bhei;
}
/**
* Returns the piece at the given column and row in the board.
*/
public abstract int getPiece (int col, int row);
/**
* Returns the distance the piece at the given column and row can drop
* until it hits a non-empty piece (defined as {@link #PIECE_NONE}).
*/
public int getDropDistance (int col, int row)
{
int dist = 0;
for (int yy = row + 1; yy < _bhei; yy++) {
if (getPiece(col, yy) != PIECE_NONE) {
return dist;
}
dist++;
}
return dist;
}
/**
* Returns whether the given row in the board is empty.
*/
public boolean isRowEmpty (int row)
{
for (int col = 0; col < _bwid; col++) {
if (getPiece(col, row) != PIECE_NONE) {
return false;
}
}
return true;
}
/**
* Returns whether all of the pieces at the given coordinates can be
* dropped one row.
*/
public boolean isValidDrop (int[] rows, int[] cols, float pctdone)
{
int bottom = _bhei - 1;
for (int ii = 0; ii < rows.length; ii++) {
// pieces at bottom can't be dropped
if (rows[ii] >= bottom) {
return false;
}
// pieces with pieces below them can't be dropped
int row = rows[ii] + 1;
if (row >= 0 && getPiece(cols[ii], row) != PIECE_NONE) {
return false;
}
}
return true;
}
/**
* Returns true if the specified coordinate is within the bounds of
* the board, false if it is not.
*/
public boolean inBounds (int col, int row)
{
return (col >= 0 && row >= 0 && col < getWidth() && row < getHeight());
}
/**
* Returns whether the specified block in the board is empty. The
* block is allowed to occupy space off the top of the board as long
* as it is within the horizontal board bounds.
*
* @param x the left coordinate of the block.
* @param y the bottom coordinate of the block.
* @param wid the width of the block.
* @param hei the height of the block.
*/
public boolean isBlockEmpty (int col, int row, int wid, int hei)
{
for (int ypos = row; ypos > (row - hei); ypos--) {
for (int xpos = col; xpos < (col + wid); xpos++) {
// only allow movement off the top of the board that's
// within the horizontal screen bounds and in a column
// that's not topped out
if (ypos < 0) {
if ((xpos < 0 || xpos >= _bwid) ||
(getPiece(xpos, 0) != PIECE_NONE)) {
return false;
} else {
continue;
}
}
// don't allow movement outside the side or bottom bounds
if (xpos < 0 ||
xpos >= _bwid ||
ypos >= _bhei) {
return false;
}
// make sure no piece is present
if (getPiece(xpos, ypos) != PIECE_NONE) {
return false;
}
}
}
return true;
}
/**
* Rotates the given block in the given direction and returns its
* final state as <code>(orient, col, row)</code>, where
* <code>orient</code> is the final orientation of the drop block;
* <code>col</code> and <code>row</code> are the final column and row
* coordinates, respectively, of the central drop block piece.
*/
public int[] getForgivingRotation (
int[] rows, int[] cols, int orient, int dir, int rtype, float pctdone)
{
int px = cols[0], py = rows[0];
int epx = cols[1], epy = rows[1];
// Log.info("Starting rotation [px=" + px + ", py=" + py +
// ", orient=" + orient + ", pctdone=" + pctdone + "].");
// try rotating the block in the given direction through all four
// possible orientations
for (int ii = 0; ii < 4; ii++) {
int oidx = orient/2;
// adjust the position of the central piece
px += ROTATE_DX[rtype][dir][oidx];
py += ROTATE_DY[rtype][dir][oidx];
// update the orientation
orient = DropBoardUtil.getRotatedOrientation(orient, dir);
oidx = orient/2;
// because isBlockEmpty() always assumes the origin of the
// block is in the lower-left, we need to adjust the
// coordinates of the drop block's "central" piece accordingly
int ox = px + ORIENT_ORIGIN_DX[oidx];
int oy = py + ORIENT_ORIGIN_DY[oidx];
// if we're less than 50 percent through with our fall, we
// want to check our current coordinates for validity; if
// we're more, we want to check the row below our current
// coordinates
if (pctdone > 0.5) {
oy += 1;
}
// try each of three coercions: nothing, one left, one right
for (int c = 0; c < COERCE_DX.length; c++) {
int cx = COERCE_DX[c];
// check if our hypothetical new coordinates are empty
if (isBlockEmpty(ox + cx, oy,
ORIENT_WIDTHS[oidx], ORIENT_HEIGHTS[oidx])) {
// Log.info("Block is empty [ox=" + ox + ", cx=" + cx +
// ", oy=" + oy + ", oidx=" + oidx +
// ", orient=" + DirectionUtil.toShortString(orient) +
// ", owid=" + ORIENT_WIDTHS[oidx] +
// ", ohei=" + ORIENT_HEIGHTS[oidx] + "].");
return new int[] { orient, px + cx, py };
}
}
// if our piece is facing south and we're using radial
// rotation then we need to try popping the piece up a row to
// check for a fit
if (rtype == RADIAL_ROTATION && orient == SOUTH) {
// check if our hypothetical new coordinates are empty
if (isBlockEmpty(ox, oy - 1,
ORIENT_WIDTHS[oidx], ORIENT_HEIGHTS[oidx])) {
// Log.info("Popped-up block is empty [ox=" + ox +
// ", oy=" + (oy - 1) + ", oidx=" + oidx +
// ", orient=" + DirectionUtil.toShortString(orient) +
// ", owid=" + ORIENT_WIDTHS[oidx] +
// ", ohei=" + ORIENT_HEIGHTS[oidx] +
// ", bhei=" + _bhei + "].");
return new int[] { orient, px, py - 1 };
}
}
}
// this should never happen since even in the most tightly
// constrained case where the block is entirely surrounded by
// other pieces there are always two valid orientations.
Log.warning("**** We're horked and couldn't rotate at all!");
// System.exit(0);
return null;
}
/**
* Returns a {@link Point} object containing the coordinates to place
* the bottom-left of the given block at after moving it the given
* distance on the x- and y-axes, or <code>null</code> if the move is
* not valid. Note that only the final block position is checked.
*
* @param board the board the piece is moving within.
* @param col the leftmost column of the block.
* @param row the bottommost row of the block.
* @param wid the width of the block.
* @param hei the height of the block.
* @param dx the distance to move the block in columns.
* @param dy the distance to move the block in rows.
* @param pctdone the percentage of the inter-block distance that the
* piece has fallen thus far.
*/
public Point getForgivingMove (
int col, int row, int wid, int hei, int dx, int dy, float pctdone)
{
// try placing the block in the desired position and, failing
// that, at the same horizontal position but one row farther down
int xpos = col + dx, ypos = row + dy;
// if we're above the halfway mark, we check our current neighbors
// to see if we can move there; if we're below the halfway mark we
// check the next row down
if (pctdone >= 0.5) {
ypos += 1;
}
// if the block we wish to occupy is empty, we're all good
return (isBlockEmpty(xpos, ypos, wid, hei)) ?
new Point(xpos, row + dy) : null;
}
/**
* Populates the given array with the column levels for this board.
*/
public void getColumnLevels (byte[] columns)
{
int bwid = getWidth(), bhei = getHeight();
for (int col = 0; col < bwid; col++) {
int dist = getDropDistance(col, -1);
columns[col] = (byte)(bhei - dist);
}
}
/**
* Called by the {@link DropControllerDelegate} when it's time to
* apply a rising row of pieces to the board. Shifts all of the
* pieces in the given board up one row and places the given row of
* pieces at the bottom of the board.
*/
public void applyRisingPieces (int[] pieces)
{
// shift all pieces up one row
int end = _bhei - 1;
for (int yy = 0; yy < end; yy++) {
for (int xx = 0; xx < _bwid; xx++) {
setPiece(xx, yy, getPiece(xx, yy + 1));
}
}
// apply the row pieces to the board
int ypos = _bhei - 1;
for (int xx = 0; xx < _bwid; xx++) {
setPiece(xx, ypos, pieces[xx]);
}
}
/**
* Returns true if the specified row (which count down, with zero at
* the top of the board) contains any pieces.
*
* @param row the row to check for pieces.
* @param blankPiece the blank piece value, non-instances of which
* will be sought.
*/
public boolean rowContainsPieces (int row, int blankPiece)
{
for (int x = 0; x < _bwid; x++) {
if (getPiece(x, row) != blankPiece) {
return true;
}
}
return false;
}
/**
* Fills the board contents with the given piece.
*/
public abstract void fill (int piece);
/**
* Sets the piece at the given coordinates.
*
* @return true if the piece was set, false if it was invalid.
*/
public abstract boolean setPiece (int col, int row, int piece);
/**
* Sets the pieces within the specified rectangle to the given piece.
*/
public void setRect (int x, int y, int width, int height, int piece)
{
for (int yy = y; yy > (y - height); yy--) {
for (int xx = x; xx < (x + width); xx++) {
setPiece(xx, yy, piece);
}
}
}
/**
* Sets the pieces in the given board segment to the specified piece.
*
* @param dir the direction of the segment; one of {@link #HORIZONTAL}
* or {@link #VERTICAL}.
* @param col the starting column of the segment.
* @param row the starting row of the segment.
* @param len the length of the segment in pieces.
* @param piece the piece to set in the segment.
*
* @return false if the segment was only partially applied because
* some pieces were outside the bounds of the board, true if it was
* completely applied.
*/
public boolean setSegment (int dir, int col, int row, int len, int piece)
{
_setPieceOp.init(piece);
applyOp(dir, col, row, len, _setPieceOp);
return !_setPieceOp.getError();
}
/**
* Sets the pieces in the given board segment to the specified pieces.
*
* @param dir the direction of the segment; one of {@link #HORIZONTAL}
* or {@link #VERTICAL}.
* @param col the starting column of the segment.
* @param row the starting row of the segment.
* @param piece the piece to set in the segment.
*/
public void setSegment (int dir, int col, int row, int[] pieces)
{
_setSegmentOp.init(dir, pieces);
applyOp(dir, col, row, pieces.length, _setSegmentOp);
}
/**
* Applies a specified {@link PieceOperation} to all pieces in the
* specified row or column starting at the specified coordinates and
* spanning the remainder of the row or column (depending on the
* application direction) in the board.
*
* @param dir the direction to iterate in; one of {@link #HORIZONTAL}
* or {@link #VERTICAL}.
* @param col the starting column of the segment.
* @param row the starting row of the segment.
* @param op the piece operation to apply to each piece.
*/
public void applyOp (int dir, int col, int row, PieceOperation op)
{
int len = (dir == HORIZONTAL) ? _bwid - col : row + 1;
applyOp(dir, col, row, len, op);
}
/**
* Applies a specified {@link PieceOperation} to all pieces in a row
* or column segment starting at the specified coordinates and of the
* specified length in the board.
*
* @param dir the direction to iterate in; one of {@link #HORIZONTAL}
* or {@link #VERTICAL}.
* @param col the starting leftmost column of the segment.
* @param row the starting bottommost row of the segment.
* @param len the number of pieces in the segment.
* @param op the piece operation to apply to each piece.
*/
public void applyOp (int dir, int col, int row, int len, PieceOperation op)
{
if (dir == HORIZONTAL) {
int end = Math.min(col + len, _bwid);
for (int ii = col; ii < end; ii++) {
if (!op.execute(this, ii, row)) {
break;
}
}
} else {
int end = Math.max(row - len, -1);
for (int ii = row; ii > end; ii--) {
if (!op.execute(this, col, ii)) {
break;
}
}
}
}
/**
* Applies a specified {@link PieceOperation} to the specified piece
* in the board.
*
* @param col the column of the piece.
* @param row the row of the piece.
* @param op the piece operation to apply to the piece.
*/
public void applyOp (int col, int row, PieceOperation op)
{
op.execute(this, col, row);
}
// documentation inherited from interface
public void dump ()
{
dumpAndCompare(null);
}
// documentation inherited from interface
public void dumpAndCompare (Board other)
{
if (other != null && !(other instanceof DropBoard)) {
throw new IllegalArgumentException(
"Can't compare drop board to non-drop-board.");
}
DropBoard dother = (DropBoard)other;
int padwid = getPadWidth();
if (other != null) {
// padwid = (padwid * 2) + 1;
padwid *= 2;
}
for (int y = 0; y < _bhei; y++) {
StringBuffer buf = new StringBuffer();
for (int x = 0; x < _bwid; x++) {
int piece = getPiece(x, y);
String str = formatPiece(piece);
if (dother != null) {
int opiece = dother.getPiece(x, y);
if (opiece != piece) {
str += "|" + formatPiece(opiece);
}
}
buf.append(Strings.rightPad(str, padwid));
}
Log.warning(buf.toString());
}
}
/**
* Returns the number of characters to which a single piece should be
* padded when dumping the board for debugging purposes.
*/
protected int getPadWidth ()
{
return DEFAULT_PAD_WIDTH;
}
/**
* Returns a string representation of the given piece for use when
* dumping the board.
*/
protected String formatPiece (int piece)
{
return (piece == PIECE_NONE) ? "." : String.valueOf(piece);
}
/** Returns a string representation of this instance. */
public String toString ()
{
StringBuffer buf = new StringBuffer();
buf.append("[wid=").append(_bwid);
buf.append(", hei=").append(_bhei);
return buf.append("]").toString();
}
// documentation inherited from interface
public boolean equals (Board other)
{
// make sure we're comparing the same class type
if (!this.getClass().getName().equals(other.getClass().getName())) {
throw new IllegalArgumentException(
"Can't compare board of different class types " +
"[src=" + this.getClass().getName() +
", other=" + other.getClass().getName() + "].");
}
// we're certainly not equal if our dimensions differ
DropBoard dother = (DropBoard)other;
if (dother.getWidth() != _bwid ||
dother.getHeight() != _bhei) {
return false;
}
// check each board piece
for (int xx = 0; xx < _bwid; xx++) {
for (int yy = 0; yy < _bhei; yy++) {
if (getPiece(xx, yy) != dother.getPiece(xx, yy)) {
return false;
}
}
}
// we're equal
return true;
}
/**
* Returns whether the given coordinates are within the board bounds.
*/
public boolean isValidPosition (int x, int y)
{
return (x >= 0 &&
y >= 0 &&
x < _bwid &&
y < _bhei);
}
/**
* Returns the bounds of this board. Note that a single rectangle is
* re-used internally and so the caller should not modify the
* returned rectangle.
*/
public Rectangle getBounds ()
{
if (_bounds == null) {
_bounds = new Rectangle(0, 0, _bwid, _bhei);
}
return _bounds;
}
/**
* Returns the size of the board in pieces.
*/
public int size ()
{
return (_bwid*_bhei);
}
/**
* Copies the contents of this board directly into the supplied board,
* overwriting the destination board in its entirety.
*/
public abstract void copyInto (DropBoard board);
/** An operation that sets the pieces in a board segment to a
* specified array of pieces. */
protected static class SetSegmentOperation implements PieceOperation
{
/**
* Sets the array of pieces to be placed in the board segment.
*/
public void init (int dir, int[] pieces)
{
_dir = dir;
_pieces = pieces;
_idx = (dir == HORIZONTAL) ? _pieces.length - 1 : 0;
}
// documentation inherited
public boolean execute (DropBoard board, int col, int row)
{
if (_dir == HORIZONTAL) {
board.setPiece(col, row, _pieces[_idx--]);
} else {
board.setPiece(col, row, _pieces[_idx++]);
}
return true;
}
/** The orientation in which the pieces are to be placed. */
protected int _dir;
/** The current piece index. */
protected int _idx;
/** The pieces to set in the board. */
protected int[] _pieces;
}
/** An operation that sets all pieces to a specified piece. */
protected static class SetPieceOperation implements PieceOperation
{
/**
* Sets the piece to be placed in the board segment.
*/
public void init (int piece)
{
_piece = piece;
_error = false;
}
/**
* Returns true if we attempted to set a piece outside the bounds
* of the board during the course of our operation.
*/
public boolean getError ()
{
return _error;
}
// documentation inherited
public boolean execute (DropBoard board, int col, int row)
{
if (!board.setPiece(col, row, _piece)) {
_error = true;
}
return true;
}
/** The piece to set in the board. */
protected int _piece;
/** Set to true if an error occurred setting a piece. */
protected boolean _error;
}
/** The board dimensions in pieces. */
protected int _bwid, _bhei;
/** The bounds of this board. */
protected transient Rectangle _bounds;
// used to reconfigure the block when rotating it
protected static final int[][][] ROTATE_DX = {
// W N E S W N E S
{{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }}, // RADIAL
{{ -1, 1, 0, 0 }, { -1, 0, 0, 1 }}, // INPLACE
// CCW CW
};
// used to reconfigure the block when rotating it
protected static final int[][][] ROTATE_DY = {
// W N E S W N E S
{{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }}, // RADIAL
{{ -1, 0, 0, 1 }, { 0, 0, -1, 1 }}, // INPLACE
// CCW CW
};
// used to compute the bounds of the isBlockEmpty() block based on the
// drop block's orientation and "root" block position
protected static final int[] ORIENT_WIDTHS = { 2, 1, 2, 1 };
protected static final int[] ORIENT_HEIGHTS = { 1, 2, 1, 2 };
// used to compute the origin of the isBlockEmpty() block based on the
// drop block's orientation and "root" block position
protected static final int[] ORIENT_ORIGIN_DX = { -1, 0, 0, 0 };
protected static final int[] ORIENT_ORIGIN_DY = { 0, 0, 0, 1 };
// used to coerce the block when rotating either a space to the left
// or right (or not at all)
protected static final int[] COERCE_DX = { 0, 1, -1 };
/** The operation used to set the pieces in a board segment. */
protected static final SetSegmentOperation _setSegmentOp =
new SetSegmentOperation();
/** The operation used to set a piece in a board segment. */
protected static final SetPieceOperation _setPieceOp =
new SetPieceOperation();
/** The number of characters to which each board piece should be
* padded when outputting for debug purposes. */
protected static final int DEFAULT_PAD_WIDTH = 3;
}
@@ -0,0 +1,71 @@
//
// $Id: DropBoardSummary.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.data;
import com.threerings.puzzle.data.Board;
import com.threerings.puzzle.data.BoardSummary;
/**
* Provides a summary of a {@link DropBoard}.
*/
public class DropBoardSummary extends BoardSummary
{
/** The row levels for each column. */
public byte[] columns;
/**
* Constructs an empty drop board summary for use when un-serializing.
*/
public DropBoardSummary ()
{
// nothing for now
}
/**
* Constructs a drop board summary that retrieves board information
* from the supplied board when summarizing.
*/
public DropBoardSummary (Board board)
{
super(board);
// create the columns array
columns = new byte[_dboard.getWidth()];
}
/**
* Returns the column number of the column within the given column
* range that contains the most pieces.
*/
public int getHighestColumn (int startx, int endx)
{
byte value = columns[startx];
int idx = startx;
for (int xx = startx + 1; xx <= endx; xx++) {
if (columns[xx] > value) {
value = columns[xx];
idx = xx;
}
}
return idx;
}
// documentation inherited
public void setBoard (Board board)
{
super.setBoard(board);
_dboard = (DropBoard)board;
}
// documentation inherited
public void summarize ()
{
// update the board column levels
_dboard.getColumnLevels(columns);
}
/** The drop board we're summarizing. */
protected transient DropBoard _dboard;
}
@@ -0,0 +1,21 @@
//
// $Id: DropCodes.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.data;
import com.threerings.puzzle.data.PuzzleGameCodes;
/**
* Contains codes used by the drop game services.
*/
public interface DropCodes extends PuzzleGameCodes
{
/** The message bundle identifier for drop puzzle messages. */
public static final String DROP_MESSAGE_BUNDLE = "puzzle.drop";
/** The name of the control stream that provides drop pieces. */
public static final String DROP_STREAM = "drop";
/** The name of the control stream that provides rise pieces. */
public static final String RISE_STREAM = "rise";
}
@@ -0,0 +1,17 @@
//
// $Id: DropConfig.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.data;
/**
* Provides access to the configuration information for a drop puzzle
* game.
*/
public interface DropConfig
{
/** Returns the board width in pieces. */
public int getBoardWidth ();
/** Returns the board height in pieces. */
public int getBoardHeight ();
}
@@ -0,0 +1,23 @@
//
// $Id: DropLogic.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.data;
/**
* Describes the features and configuration desired for a given drop
* puzzle game.
*/
public interface DropLogic
{
/**
* Returns whether the puzzle game would like to make use of the
* manipulable block dropping functionality.
*/
public boolean useBlockDropping ();
/**
* Returns whether the puzzle game would like to make use of the
* rising board functionality.
*/
public boolean useBoardRising ();
}
@@ -0,0 +1,19 @@
//
// $Id: DropPieceCodes.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.data;
import com.threerings.util.DirectionCodes;
/**
* The drop piece codes interface contains constants common to the drop
* game package.
*/
public interface DropPieceCodes extends DirectionCodes
{
/** The piece constant denoting an empty board piece. */
public static final byte PIECE_NONE = -1;
/** The number of pieces in a drop block. */
public static final int DROP_BLOCK_PIECE_COUNT = 2;
}
@@ -0,0 +1,43 @@
//
// $Id: SegmentInfo.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.data;
import com.samskivert.util.StringUtil;
import com.threerings.util.DirectionCodes;
/**
* Describes a segment of pieces in a {@link DropBoard}.
*/
public class SegmentInfo
{
/** The segment's direction; one of {@link DirectionCodes#HORIZONTAL}
* or {@link DirectionCodes#VERTICAL}. */
public int dir;
/** The segment's lower-left board coordinates. */
public int x, y;
/** The segment's length in pieces. */
public int len;
/**
* Constructs a segment info object.
*/
public SegmentInfo (int dir, int x, int y, int len)
{
this.dir = dir;
this.x = x;
this.y = y;
this.len = len;
}
/**
* Returns a string representation of this instance.
*/
public String toString ()
{
return StringUtil.fieldsToString(this);
}
}
@@ -0,0 +1,151 @@
//
// $Id: ShortDropBoard.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.data;
import java.util.Arrays;
import com.threerings.puzzle.Log;
/**
* The short drop board extends the {@link DropBoard}, making use of a
* <code>short</code> array of pieces to store the board contents.
*/
public class ShortDropBoard extends DropBoard
{
/**
* Constructs an empty short drop board for use when unserializing.
*/
public ShortDropBoard ()
{
this(null, 0, 0);
}
/**
* Constructs a short drop board of the given dimensions with its
* pieces initialized to PIECE_NONE.
*/
public ShortDropBoard (int bwid, int bhei)
{
this(new short[bwid*bhei], bwid, bhei);
fill(PIECE_NONE);
}
/**
* Constructs a short drop board of the given dimensions with its
* pieces initialized to the given piece.
*/
public ShortDropBoard (int bwid, int bhei, short piece)
{
this(new short[bwid*bhei], bwid, bhei);
fill(piece);
}
/**
* Constructs a short drop board with the given board and dimensions.
*/
public ShortDropBoard (short[] board, int bwid, int bhei)
{
_board = board;
_bwid = bwid;
_bhei = bhei;
}
// documentation inherited from interface
public int getPiece (int col, int row)
{
try {
return _board[(row*_bwid) + col];
} catch (Exception e) {
Log.warning("Failed getting piece [col=" + col +
", row=" + row + ", error=" + e + "].");
Log.logStackTrace(e);
return -1;
}
}
// documentation inherited from interface
public void fill (int piece)
{
Arrays.fill(_board, (short)piece);
}
/**
* Sets the board data and board dimensions.
*/
public void setBoard (short[] board, int bwid, int bhei)
{
_board = board;
_bwid = bwid;
_bhei = bhei;
}
/**
* Sets the board pieces.
*/
public void setBoard (short[] board)
{
int size = (_bwid*_bhei);
if (board.length < size) {
Log.warning("Attempt to set board with invalid data size " +
"[len=" + board.length + ", expected=" + size + "].");
return;
}
_board = board;
}
// documentation inherited from interface
public boolean setPiece (int col, int row, int piece)
{
if (col >= 0 && row >= 0 && col < _bwid && row < _bhei) {
_board[(row*_bwid) + col] = (short)piece;
return true;
} else {
Log.warning("Attempt to set piece outside board bounds " +
"[col=" + col + ", row=" + row + ", p=" + piece + "].");
return false;
}
}
// documentation inherited from interface
public void copyInto (DropBoard board)
{
// make sure the target board is a valid target
if (board.getWidth() != _bwid || board.getHeight() != _bhei) {
Log.warning("Can't copy board into destination board with " +
"different dimensions [src=" + this +
", dest=" + board + "].");
return;
}
// copy our pieces directly into the board, avoiding any unsightly
// object allocation which is largely the point of this method,
// after all.
short[] dest = ((ShortDropBoard)board).getBoard();
System.arraycopy(_board, 0, dest, 0, (_bwid*_bhei));
}
// documentation inherited
public Object clone ()
{
int size = _bwid*_bhei;
short[] data = new short[size];
System.arraycopy(_board, 0, data, 0, size);
return new ShortDropBoard(data, _bwid, _bhei);
}
/**
* Returns the raw board data associated with this board. One
* shouldn't fiddle about with this unless one knows what one is
* doing.
*/
public short[] getBoard ()
{
return _board;
}
/** The board data. */
protected short[] _board;
}
@@ -0,0 +1,174 @@
//
// $Id: DropManagerDelegate.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.server;
import java.util.List;
import com.threerings.util.MessageBundle;
import com.threerings.crowd.data.PlaceConfig;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.parlor.game.GameManager;
import com.threerings.puzzle.Log;
import com.threerings.puzzle.data.Board;
import com.threerings.puzzle.data.BoardSummary;
import com.threerings.puzzle.data.PuzzleCodes;
import com.threerings.puzzle.data.PuzzleObject;
import com.threerings.puzzle.server.PuzzleManager;
import com.threerings.puzzle.server.PuzzleManagerDelegate;
import com.threerings.puzzle.drop.data.DropBoard;
import com.threerings.puzzle.drop.data.DropBoardSummary;
import com.threerings.puzzle.drop.data.DropCodes;
import com.threerings.puzzle.drop.data.DropConfig;
import com.threerings.puzzle.drop.data.DropLogic;
import com.threerings.puzzle.drop.util.DropPieceProvider;
import com.threerings.puzzle.drop.util.PieceDropLogic;
import com.threerings.puzzle.drop.util.PieceDropper;
/**
* Provides the necessary support for a puzzle game that involves a
* two-dimensional board containing pieces, with new pieces either falling
* into the board as a "drop block", or rising into the bottom of the
* board in new piece rows, groups of blocks can be "broken" and garbage
* can be sent to other players' boards as a result. This is implemented
* as a delegate so that the natural hierarchy need not be twisted to
* differentiate between puzzles that use piece dropping and those that
* don't. Because we have need to structure our hierarchy around things
* like whether a puzzle is a duty puzzle, this becomes necessary.
*
* <p> A puzzle game using these services will then need to extend this
* delegate, implementing the necessary methods to customize it for the
* particulars of their game and then register it with their game manager
* via {@link GameManager#addDelegate}.
*
* <p> It also keeps track of, for each player, board level information,
* and player game status. Miscellaneous utility routines are provided
* for checking things like whether the game is over, whether a player is
* still active in the game, and so forth.
*
* <p> Derived classes are likely to want to override {@link
* #getPieceDropLogic}.
*/
public abstract class DropManagerDelegate extends PuzzleManagerDelegate
implements PuzzleCodes, DropCodes
{
/**
* Provides the delegate with a reference to the manager for which it
* is delegating as well as the logic object that it uses to determine
* how to manage the drop puzzle.
*/
public DropManagerDelegate (PuzzleManager puzmgr, DropLogic logic)
{
super(puzmgr);
// save off the puzzle manager
_puzmgr = puzmgr;
// configure the game-specific settings
_usedrop = logic.useBlockDropping();
_userise = logic.useBoardRising();
if (_usedrop && _userise) {
Log.warning("Can't use dropping blocks and board rising "+
"functionality simultaneously in a drop puzzle game! " +
"Falling back to straight dropping.");
_userise = false;
}
}
// documentation inherited
public void didInit (PlaceConfig config)
{
_dconfig = (DropConfig)config;
// save things off
_bwid = _dconfig.getBoardWidth();
_bhei = _dconfig.getBoardHeight();
super.didInit(config);
}
// documentation inherited
public void didStartup (PlaceObject plobj)
{
super.didStartup(plobj);
// initialize the drop board array
_dboards = new DropBoard[_puzmgr.getPlayerCount()];
// create the piece dropper if appropriate
PieceDropLogic pdl = getPieceDropLogic();
if (pdl != null) {
_dropper = new PieceDropper(pdl);
}
}
// documentation inherited
public void gameWillStart ()
{
super.gameWillStart();
// get casted references to all player drop boards
Board[] board = _puzmgr.getBoards();
for (int ii = 0; ii < _puzmgr.getPlayerCount(); ii++) {
_dboards[ii] = (DropBoard)board[ii];
}
}
/**
* Drops any pieces that need dropping on the given player's board and
* returns whether any pieces were dropped.
*/
protected boolean dropPieces (DropBoard board)
{
return (_dropper.dropPieces(board, null).size() > 0);
}
/**
* Returns the piece drop logic used to drop any pieces that need
* dropping in the board.
*/
protected PieceDropLogic getPieceDropLogic ()
{
return null;
}
/**
* This method should be called by derived classes whenever the player
* successfully places a drop block.
*/
protected void placedBlock (int pidx)
{
// update the player's board levels
_puzmgr.updateBoardSummary(pidx);
}
/** The puzzle manager. */
protected PuzzleManager _puzmgr;
/** The drop game board for each player. */
protected DropBoard[] _dboards;
/** The drop game config object. */
protected DropConfig _dconfig;
/** Whether the game is using drop block functionality. */
protected boolean _usedrop;
/** Whether the game is using board rising functionality. */
protected boolean _userise;
/** The board dimensions in pieces. */
protected int _bwid, _bhei;
/** The piece dropper used to drop pieces in the board if the puzzle
* chooses to make use of piece dropping functionality. */
protected PieceDropper _dropper;
/** Used to limit the maximum number of board update loops permitted
* before assuming something's gone horribly awry and aborting. */
protected static final int MAX_UPDATE_LOOPS = 100;
}
@@ -0,0 +1,46 @@
//
// $Id: DropBoardUtil.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.util;
import com.threerings.util.DirectionCodes;
import com.threerings.puzzle.drop.data.DropBoard;
public class DropBoardUtil
implements DirectionCodes
{
/**
* Returns the orientation resulting from rotating the block in the
* given direction the specified number of times.
*
* @param orient the current orientation.
* @param dir the direction to rotate in; one of <code>CW</code> or
* <code>CCW</code>.
* @param count the number of rotations to perform.
*
* @return the rotated orientation.
*/
public static int getRotatedOrientation (int orient, int dir, int count)
{
for (int ii = 0; ii < (count % 4); ii++) {
orient = getRotatedOrientation(orient, dir);
}
return orient;
}
/**
* Returns the orientation resulting from rotating the block in
* the given direction.
*
* @param orient the current orientation.
* @param dir the direction to rotate in; one of <code>CW</code> or
* <code>CCW</code>.
*
* @return the rotated orientation.
*/
public static int getRotatedOrientation (int orient, int dir)
{
return (orient + ((dir == CW) ? 2 : 6)) % DIRECTION_COUNT;
}
}
@@ -0,0 +1,53 @@
//
// $Id: DropGameUtil.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.util;
import java.awt.event.KeyEvent;
import com.threerings.util.KeyTranslatorImpl;
import com.threerings.puzzle.drop.client.DropControllerDelegate;
import com.threerings.puzzle.util.PuzzleGameUtil;
/**
* Drop puzzle game related utilities.
*/
public class DropGameUtil
{
/**
* Returns a key translator configured with mappings suitable for a
* drop puzzle game.
*/
public static KeyTranslatorImpl getKeyTranslator ()
{
// start with the standard puzzle key mappings
KeyTranslatorImpl xlate = PuzzleGameUtil.getKeyTranslator();
// add all press key mappings
xlate.addPressCommand(KeyEvent.VK_LEFT,
DropControllerDelegate.MOVE_BLOCK_LEFT,
MOVE_RATE, MOVE_DELAY);
xlate.addPressCommand(KeyEvent.VK_RIGHT,
DropControllerDelegate.MOVE_BLOCK_RIGHT,
MOVE_RATE, MOVE_DELAY);
xlate.addPressCommand(KeyEvent.VK_UP,
DropControllerDelegate.ROTATE_BLOCK_CCW, 0);
xlate.addPressCommand(KeyEvent.VK_DOWN,
DropControllerDelegate.ROTATE_BLOCK_CW, 0);
xlate.addPressCommand(KeyEvent.VK_SPACE,
DropControllerDelegate.START_DROP_BLOCK, 0);
// add all release key mappings
xlate.addReleaseCommand(KeyEvent.VK_SPACE,
DropControllerDelegate.END_DROP_BLOCK);
return xlate;
}
/** The move key repeat rate in moves per second. */
protected static final int MOVE_RATE = 7;
/** The delay in milliseconds before the move keys begin to repeat. */
protected static final long MOVE_DELAY = 300L;
}
@@ -0,0 +1,23 @@
//
// $Id: DropPieceProvider.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.util;
/**
* Does something extraordinary.
*/
public interface DropPieceProvider
{
/**
* Get the next piece to add to the drop board.
*/
public int getNextPiece ()
throws OutOfPiecesException;
/**
* I lost my touch.
*/
public static class OutOfPiecesException extends Exception
{
}
}
@@ -0,0 +1,163 @@
//
// $Id: PieceDestroyer.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.util;
import java.util.ArrayList;
import java.util.List;
import com.threerings.puzzle.drop.data.DropBoard;
import com.threerings.puzzle.drop.data.DropBoard.PieceOperation;
import com.threerings.puzzle.drop.data.DropPieceCodes;
import com.threerings.puzzle.drop.data.SegmentInfo;
/**
* Handles destroying contiguous piece segments in a drop board.
*/
public class PieceDestroyer
implements DropPieceCodes
{
/**
* An interface to be implemented by specific puzzles to detail the
* parameters and methodology by which pieces are destroyed in the
* puzzle board.
*/
public interface DestroyLogic
{
/**
* Returns the minimum length of a contiguously piece segment that
* should be destroyed.
*/
public int getMinimumLength ();
/**
* Returns whether piece <code>a</code> is equivalent to piece
* <code>b</code> for the purposes of including it in a contiguous
* piece segment to be destroyed.
*/
public boolean isEquivalent (int a, int b);
}
/**
* Constructs a piece destroyer that destroys pieces as specified by
* the supplied destroy logic.
*/
public PieceDestroyer (DestroyLogic logic)
{
_logic = logic;
}
/**
* Destroys all pieces in the given board that are in contiguous rows
* or columns of pieces, returning a list of {@link SegmentInfo}
* objects detailing the destroyed piece segments. Note that a single
* list is used internally to gather the segment info, and so callers
* that care to modify the list should create their own copy; also,
* the pieces in the segments may overlap, i.e., two segments may
* contain the same piece.
*/
public List destroyPieces (DropBoard board, PieceOperation destroyOp)
{
// find all horizontally-oriented destroyed segments
int bwid = board.getWidth(), bhei = board.getHeight();
_destroyed.clear();
int end = bwid - _logic.getMinimumLength() + 1;
for (int yy = (bhei - 1); yy >= 0; yy--) {
int xx = 0;
while (xx < end) {
xx += findSegment(board, HORIZONTAL, xx, yy);
}
}
// find all vertically-oriented destroyed segments
end = _logic.getMinimumLength() - 2;
for (int xx = 0; xx < bwid; xx++) {
int yy = bhei - 1;
while (yy > end) {
yy -= findSegment(board, VERTICAL, xx, yy);
}
}
// destroy the pieces
int size = _destroyed.size();
for (int ii = 0; ii < size; ii++) {
SegmentInfo si = (SegmentInfo)_destroyed.get(ii);
board.applyOp(si.dir, si.x, si.y, si.len, destroyOp);
}
return _destroyed;
}
/**
* Searches for a contiguously colored piece segment with the
* specified orientation and root coordinates in the supplied board
* and returns the length of the segment traversed.
*/
protected int findSegment (DropBoard board, int dir, int x, int y)
{
_lengthOp.reset();
board.applyOp(dir, x, y, _lengthOp);
int len = _lengthOp.getLength();
if (len >= _logic.getMinimumLength()) {
_destroyed.add(new SegmentInfo(dir, x, y, len));
}
return len;
}
/**
* A piece operation that calculates the length of the contiguous
* piece segment to which it is applied.
*/
protected class SegmentLengthOperation
implements PieceOperation
{
/**
* Resets the operation for application to a new piece segment.
*/
public void reset ()
{
_len = 0;
}
/**
* Returns the length of the contiguous piece segment.
*/
public int getLength ()
{
return _len;
}
// documentation inherited
public boolean execute (DropBoard board, int col, int row)
{
int piece = board.getPiece(col, row);
if (_len == 0) {
_len = 1;
_piece = piece;
return (piece != PIECE_NONE);
} else if (_logic.isEquivalent(piece, _piece)) {
_len++;
return true;
} else {
return false;
}
}
/** The root segment piece. */
protected int _piece;
/** The segment length in pieces. */
protected int _len;
}
/** The puzzle-specific destroy logic with which we do our business. */
protected DestroyLogic _logic;
/** The piece operation used to determine segment length. */
protected SegmentLengthOperation _lengthOp = new SegmentLengthOperation();
/** The list of destroyed piece segments. */
protected ArrayList _destroyed = new ArrayList();
}
@@ -0,0 +1,61 @@
//
// $Id: PieceDropLogic.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.util;
import com.threerings.util.DirectionCodes;
import com.threerings.puzzle.drop.data.DropBoard;
/**
* An interface to be implemented by games that would like to be able to
* drop their pieces during game play.
*/
public interface PieceDropLogic
{
/**
* Should the board always be filled?
*
* @return false for normal behavior.
*/
public boolean boardAlwaysFilled ();
/**
* Returns whether the given piece is potentially droppable.
*/
public boolean isDroppablePiece (int piece);
/**
* Returns whether the given piece has constraints upon it that
* impact its droppability.
*/
public boolean isConstrainedPiece (int piece);
/**
* Returns whether the given piece terminates a column climb when
* determining the height of a piece column to be dropped.
*
* @param allowConst whether to allow dropping constrained pieces
* (though only in the first encountered constrained block.)
* @param piece the piece to consider.
* @param pre whether the climbability check is being performed
* before the height is incremented, or after.
*/
public boolean isClimbablePiece (
boolean allowConst, int piece, boolean pre);
/**
* Returns the x-axis coordinate of the specified edge of the
* given constrained piece.
*
* <p> TODO: This should go away once the sword and sail games
* have standardized on WEST/EAST or BLOCK_LEFT/BLOCK_RIGHT to
* reference block edges.
*
* @param board the board to search.
* @param col the column of the constrained piece.
* @param row the row of the constrained piece.
* @param dir the edge direction to find; one of {@link
* DirectionCodes#LEFT} or {@link DirectionCodes#RIGHT}.
*/
public int getConstrainedEdge (DropBoard board, int col, int row, int dir);
}
@@ -0,0 +1,340 @@
//
// $Id: PieceDropper.java,v 1.1 2003/11/26 01:42:34 mdb Exp $
package com.threerings.puzzle.drop.util;
import java.util.ArrayList;
import java.util.List;
import com.samskivert.util.StringUtil;
import com.threerings.puzzle.Log;
import com.threerings.puzzle.drop.data.DropBoard;
import com.threerings.puzzle.drop.data.DropPieceCodes;
/**
* Handles dropping pieces in a board.
*/
public class PieceDropper
implements DropPieceCodes
{
/**
* A class to hold information detailing the pieces to be dropped
* in a particular column.
*/
public static class PieceDropInfo
{
/** The starting row of the bottom piece being dropped. */
public int row;
/** The column number. */
public int col;
/** The distance to drop the pieces. */
public int dist;
/** The pieces to be dropped. */
public int[] pieces;
/**
* Constructs a piece drop info object.
*/
public PieceDropInfo (int col, int row, int dist)
{
this.col = col;
this.row = row;
this.dist = dist;
}
/** Returns a string representation of this instance. */
public String toString ()
{
return StringUtil.fieldsToString(this);
}
}
/**
* Constructs a piece dropper that uses the supplied piece drop logic
* to specialise itself for a particular puzzle.
*/
public PieceDropper (PieceDropLogic logic)
{
_logic = logic;
}
/**
* Destructively modifies the supplied board to contain pieces dropped
* in the first of potentially multiple drop positions and returns a
* list of {@link PieceDropInfo} objects detailing all column segments
* to be dropped. Note that a single list is used internally to store
* the drop info objects, and so callers that care to do anything
* long-term with the drop info should create their own copy of the
* list or somesuch.
*
* @param DropPieceProvider if the board should always be filled
* (as specified by the PieceDropLogic) this will provide
* information on the newly filled in pieces.
*/
public List dropPieces (DropBoard board, DropPieceProvider provider)
{
int bhei = board.getHeight(), bwid = board.getWidth();
_drops.clear();
for (int yy = bhei - 1; yy >= 0; yy--) {
for (int xx = 0; xx < bwid; xx++) {
// find all drops in this column
getColumnDrops(board, _drops, xx, yy);
}
}
if (_logic.boardAlwaysFilled()) {
addFillingDrops(board, provider, _drops);
}
return _drops;
}
/**
* Analyzes but does not modify the supplied board and returns a list
* of {@link PieceDropInfo} objects detailing all column segments to
* be dropped. Note that a single list is used internally to store
* the drop info objects, and so callers that care to do anything
* long-term with the drop info should create their own copy of the
* list or somesuch.
*
* @param DropPieceProvider if the board should always be filled
* (as specified by the PieceDropLogic) this will provide
* information on the newly filled in pieces.
*/
public List getDroppedPieces (DropBoard board, DropPieceProvider provider)
{
// grab a snapshot of the board within which we're dropping
// pieces to avoid modifying the source board directly while we're
// figuring out what to drop where
if (_board == null) {
_board = (DropBoard)board.clone();
} else {
board.copyInto(_board);
}
return dropPieces(_board, provider);
}
/**
* Populates the <code>drops</code> list with {@link PieceDropInfo}
* objects detailing the column segments to be dropped per empty space
* below. Destructively modifies the given board to reflect the final
* positions of the column segments once dropped.
*/
protected void getColumnDrops (DropBoard board, List drops, int x, int y)
{
// skip empty or fixed pieces
int piece = board.getPiece(x, y);
if (!_logic.isDroppablePiece(piece)) {
return;
}
if (_logic.isConstrainedPiece(piece)) {
// get the distance to drop the block
int dist = getBlockDropDistance(board, x, y);
if (dist == 0) {
return;
}
// scoot along the bottom edge of the block dropping each column
int bwid = board.getWidth();
int start = _logic.getConstrainedEdge(board, x, y, LEFT);
int end = _logic.getConstrainedEdge(board, x, y, RIGHT);
for (int xpos = start; xpos <= end; xpos++) {
addDropInfo(board, drops, true, xpos, y, dist);
}
} else {
// get the distance to drop the pieces
int dist = board.getDropDistance(x, y);
if (dist == 0) {
return;
}
// add the column segment to the list of drops
addDropInfo(board, drops, false, x, y, dist);
}
}
/**
* Adds a {@link PieceDropInfo} object to the drop list detailing
* dropping of the column segment at the specified location.
*
* @param board the working board.
* @param allowConst whether to allow dropping constrained pieces in
* the specified column segment.
* @param x the column x-coordinate.
* @param y the column segment bottom y-coordinate.
* @param dist the distance to drop the pieces.
*/
protected void addDropInfo (DropBoard board, List drops,
boolean allowConst, int x, int y, int dist)
{
// sanity check our column
if (x < 0 || x >= board.getWidth()) {
Log.warning("Requested to add bogus drop info [board=" + board +
", drops=" + StringUtil.toString(drops) +
", allowConst=" + allowConst +
", x=" + x + ", y=" + y + ", dist=" + dist + "].");
Thread.dumpStack();
}
// traverse up the column looking for an empty or block piece
// that will terminate this column segment
int height = getDropHeight(board, allowConst, x, y, dist);
// create the piece drop info object
PieceDropInfo pdi = new PieceDropInfo(x, y, dist);
// copy in the relevant pieces
pdi.pieces = new int[height];
int idx = 0;
for (int yy = y; yy > (y - height); yy--) {
pdi.pieces[idx++] = board.getPiece(x, yy);
}
// update the working copy of the board with the eventual
// piece locations
dropPieces(board, pdi);
// add the column segment to the pot
drops.add(pdi);
}
/**
* If we want to keep the board filled at all times,
* this method will be called to create drop objects for the
* newly-filled in pieces.
*/
protected void addFillingDrops (
DropBoard board, DropPieceProvider provider, List drops)
{
boolean out = false;
// drop in new pieces for empty spaces at the top
for (int xx=0, bwid=board.getWidth(); xx < bwid; xx++) {
// get the distance to drop the pieces
int dist = board.getDropDistance(xx, -1);
if (dist != 0) {
PieceDropInfo pdi = new PieceDropInfo(xx, -1, dist);
pdi.pieces = new int[dist];
for (int ii=0; ii < dist; ii++) {
try {
pdi.pieces[ii] = provider.getNextPiece();
} catch (DropPieceProvider.OutOfPiecesException oop) {
// well, how far did we get?
int[] something = new int[ii];
System.arraycopy(pdi.pieces, 0, something, 0, ii);
pdi.pieces = something;
out = true;
break;
}
}
dropPieces(board, pdi);
drops.add(pdi);
// if we're outta pieces, bail.
if (out) {
return;
}
}
}
}
/**
* Returns the height of the piece segment to be dropped at the
* given coordinates.
*/
protected int getDropHeight (
DropBoard board, boolean allowConst, int x, int y, int dist)
{
int height = 0;
for (int yy = y; yy >= 0; yy--) {
int curpiece = board.getPiece(x, yy);
if (!_logic.isClimbablePiece(allowConst, curpiece, true)) {
return height;
}
height++;
if (!_logic.isClimbablePiece(allowConst, curpiece, false)) {
return height;
}
}
return height;
}
/**
* Updates the given board to reflect the eventual destination of the
* given pieces.
*/
protected void dropPieces (DropBoard board, PieceDropInfo pdi)
{
// clear out the original piece positions
if (!board.setSegment(
VERTICAL, pdi.col, pdi.row, pdi.pieces.length, PIECE_NONE)) {
Log.warning("Bogosity encountered when clearing pieces for drop " +
"[bwid=" + board.getWidth() +
", bhei=" + board.getHeight() + ", pdi=" + pdi + "].");
}
// place the pieces in their destination positions
applyPieces(board, pdi);
}
/**
* Returns the number of spaces the block whose bottom edge
* contains the specified coordinate can be dropped based on the
* contents of the given board. The droppable distance for a
* block is determined by finding the minimum drop distance across
* all columns the block spans.
*/
protected int getBlockDropDistance (DropBoard board, int x, int y)
{
// get the smallest drop distance across all of the block columns
int bwid = board.getWidth();
int start = Math.max(_logic.getConstrainedEdge(board, x, y, LEFT), 0);
int end = Math.min(
_logic.getConstrainedEdge(board, x, y, RIGHT), bwid - 1);
int dist = board.getHeight() - 1;
for (int xpos = start; xpos <= end; xpos++) {
dist = Math.min(dist, board.getDropDistance(xpos, y));
}
return dist;
}
/**
* Applies the pieces in the given piece drop info object to the given
* board at their eventual destination positions.
*/
protected void applyPieces (DropBoard board, PieceDropInfo pdi)
{
int start = pdi.row, end = (pdi.row - pdi.pieces.length);
int idx = 0;
boolean error = false;
for (int yy = (start + pdi.dist); yy > (end + pdi.dist); yy--) {
error = !board.setPiece(pdi.col, yy, pdi.pieces[idx++]) || error;
}
if (error) {
Log.warning("Bogosity encountered while applying dropped " +
"pieces to board [bwid=" + board.getWidth() +
", bhei=" + board.getHeight() + ", pdi=" + pdi + "].");
}
}
/** The piece drop logic used to allow puzzle-specific piece dropping
* hooks. */
protected PieceDropLogic _logic;
/** The list of piece drop info objects detailing the piece drops
* resulting from the last call to {@link #getDroppedPieces}. */
protected ArrayList _drops = new ArrayList();
/** The board on which pieces are being dropped. */
protected DropBoard _board;
}