我写的大部分代码我只是遇到了一些困难。我应该创建一些代码,这些代码将在绘图板上随机走动,直到它离开屏幕。我可以让它工作一点点,但我觉得这是不正确的。任何帮助将不胜感激。
这是我的代码到目前为止我最关心的问题是它有星星的walkingRandom方法
public class RandomWalk {
// DrawingPanel will have dimensions DIM by DIM
public static final int DIM = 400;
// Start the random walk in the center of the screen
public static final int CENTER = DIM / 2;
// how big should the cursor appear?
public static final int CURSOR_DIM = 10;
// how long should the cursor saty in one place?
public static final int SLEEP_TIME = 5; // milliseconds
public static void main( String[] args ) {
DrawingPanel panel = new DrawingPanel( DIM, DIM );
Random rand = new Random();
walkRandomly( panel, rand );
}
/**
* Draw a random walk on the panel.
* Stop as soon as you walk off the panel.
* Each random step should go only in one
* of these directions: left, right, up, down.
* @param panel a DrawingPanel to draw the
* random walk on
* @param rand a Java Random object to be
* used to generate random steps
*/
public static void walkRandomly( DrawingPanel panel, Random rand ) {
Graphics g = panel.getGraphics();
// start in center of panel
int x = CENTER;
int y = CENTER;
// Randomly step left, right, up, or down
// until cursor goes off screen.
while ( onScreen( x, y ) ) {
// Draw the cursor in BLACK
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
// Wait a bit.
panel.sleep( SLEEP_TIME );
// Show a shadow version of the cursor
g.setColor(Color.GRAY);
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
// Choose a new location for the cursor
//*********************************
if (rand.nextInt() < DIM - 300){
x--;
} else if (rand.nextInt() < DIM / 2){
x++;
} else if (rand.nextInt() < DIM - 100){
y--;
} else if (rand.nextInt() < DIM) {
y++;
}
//*********************************
// draw the cursor at its new location
g.setColor(Color.BLACK);
g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
}
}
/**
* determine whether (x, y) is a point on the panel.
* @param x the x-coord of the cursor
* @param y the y-coord of the cursor
* @return true if (x,y) is on the screen,
* false if (x,y) is off the screen
*/
public static boolean onScreen( int x, int y ) {
// x/y high = 400, x/y low = 0
//*********************************
return (x <= DIM && x >= 0 || y <= DIM && y >= 0);
}
}
答案 0 :(得分:0)
您的代码存在一些问题。你没有在你的问题中澄清,但我认为:
CURSOR_DIM
,而不是更少(这是你的例子中似乎发生的事情)问题主要出在方法walkRandomly
上,我建议您按如下方式选择下一个方向:
// Choose a new location for the cursor
int direction = rand.nextInt(4); //0=left, 1=right, 2=up, 3=down
if (direction == 0){
x -= CURSOR_DIM; //The step should be equal to the cursor width, not 1
} else if (direction == 1){
x += CURSOR_DIM;
} else if (direction == 2){
//you usually subtract to go up, the origin being the upper-left corner
y -= CURSOR_DIM;
} else if (direction == 3) {
y += CURSOR_DIM;
}
还有另外两个问题:
您在循环的开头和结尾处将光标绘制为黑色,这是多余的。您可以删除其中一个并获得相同的结果。
在onScreen
方法中,等于x
的{{1}}和y
值应返回false,因为通常图像/数组的边界为0到{ {1}} 独家。此外,您应该用AND替换DIM
,因为光标应该在x和y范围内,而不是OR。
DIM
希望有所帮助