常数
public final int DIMENSIONS = 4;
public final int MOVE_RIGHT = 1;
public final int MOVE_LEFT = 2;
public final int MOVE_UP = 3;
public final int MOVE_DOWN = 4;
主要的
PuzzleFrame board;
void setup(){
size(401,401);
board = new PuzzleFrame();
background(100);
}
void draw(){
background(100);
board.draw();
}
void keyPressed()
{
if(key == CODED)
{
if(keyCode == RIGHT) board.moveTile(MOVE_RIGHT);
if(keyCode == LEFT) board.moveTile(MOVE_LEFT);
if(keyCode == UP) board.moveTile(MOVE_UP);
if(keyCode == DOWN) board.moveTile(MOVE_DOWN);
}
}
创建拼图框架的类
class PuzzleFrame{
private Tile[][] puzzleFrame;
private Tile[][] solvedPuzzleFrame;
public PuzzleFrame()
{
puzzleFrame = new Tile[DIMENSIONS][DIMENSIONS];
solvedPuzzleFrame = new Tile[DIMENSIONS][DIMENSIONS];
int tileNumber = 1;
for(int i = 0; i < DIMENSIONS; i++)
{
for(int j = 0; j < DIMENSIONS; j++)
{
puzzleFrame[i][j] = new Tile(tileNumber, j*100, i*100);
solvedPuzzleFrame[i][j] = new Tile(tileNumber, j*100, i*100);
tileNumber++;
}
}
}
public void draw()
{
for(int i = 0; i < DIMENSIONS; i++)
{
for(int j = 0; j < DIMENSIONS; j++)
{
puzzleFrame[i][j].draw();
}
}
}
public void moveTile(int side)
{
if(isMoveAllowed(side))
{
switch(side)
{
case MOVE_RIGHT:
{
for(int i = 0; i < DIMENSIONS; i++)
{
for(int j = 0; j < DIMENSIONS; j++)
{
if(puzzleFrame[i][j].getTileNumber() == DIMENSIONS*DIMENSIONS)
{
Tile tempTile = puzzleFrame[i][j];
puzzleFrame[i][j] = puzzleFrame[i][j-1];
puzzleFrame[i][j-1] = tempTile;
System.out.println("right");
break;
}
}
}
break;
}
}
}
}
private boolean isMoveAllowed(int side)
{
switch(side)
{
case MOVE_RIGHT:
{
for(int i = 0; i < DIMENSIONS; i++)
{
for(int j = 0; j < DIMENSIONS; j++)
{
if(puzzleFrame[i][j].getTileNumber() == DIMENSIONS*DIMENSIONS)
{
if(j > 0) return true;
}
}
}
break;
}
}
return false;
}
}
用于创建拼图框架的 tile 类
class Tile{
private final int mTileNumber;
private final int width = 100;
private final int height = 100;
private String number = "";
private int xpos;
private int ypos;
private int xOffSet;
private int yOffSet;
public Tile(int tileNumber, int xpos, int ypos)
{
mTileNumber = tileNumber;
number += tileNumber;
textSize(64);
this.xpos = xpos; this.ypos = ypos;
xOffSet = 30;
yOffSet = 70;
if(mTileNumber >= 10)
{
xOffSet = 10;
}
}
public void draw()
{
if(mTileNumber == DIMENSIONS*DIMENSIONS)
{
}
else
{
strokeWeight(2);
fill(255);
rect(xpos, ypos, width, height);
fill(0);
text(number, xpos+xOffSet, ypos+yOffSet);
}
}
public int getTileNumber()
{
return mTileNumber;
}
}
我正在尝试制作 15 个益智游戏,但我遇到的问题是,当我按下箭头键 RIGHT 时,puzzleFrame 数组的内容会发生变化(我通过调试器在 Eclipse 中检查了它)但在处理绘制的图像时保持不变。现在我的代码只包含一个允许向右滑动图块的函数。老实说,我不明白为什么即使数组的内容发生了变化,图像仍然保持不变。