可以说我必须在for循环内使用if语句,并且for循环在特定条件下触发,而if语句仅在for循环达到特定阶段时才触发。
例如,条件是一个计数器,该计数器在发生某些事情(例如,球从屏幕上掉下来)时进行计数。每次球越过屏幕时,都会一圈绘制一个圆圈。当第一行中的圆圈到达屏幕的末端时,圆圈开始出现在第一行下方的第二行中。但是第二行对我不起作用,我已经用if语句实现了。
float BallY = 50; // y value of the ball float BallX = 260; // x value of the ball float ScoreX = 52; float ScoreY = 40; int counter; void setup() { size(512, 348); //width and height of screen counter = 0; } void draw() { frameRate(600); background(255); fill(0); ellipse(BallX, BallY, 15, 15); //ball that will fall BallY++; //ball's y value increases each frame if (BallY > height) //if ball's y value is greater than the screen { BallY = 0; //reset the y value of the ball back to 0 counter++; } for (int i = 0; i < counter; i++) { ellipse(ScoreX + i * 80, 40, 40, 40); // draw circles in the first row one by one if( ScoreX + i * 80 > width) // if the circles cross the width { i = 0; //reset i to be 0 ellipse(ScoreX + i * 80, 80, 40, 40); // draw circles in the second row } }}
if语句仅在第一行的球越过宽度时才触发,但是整个游戏只是停止而不是在该行触发,似乎是问题所在?
初步建议:学习正确的Java编码约定,学习如何缩进代码,以及命名变量。
对您的代码进行轻微的重写应该可以使可读的修正:
int scoreStartX = 52; int scoreStartY = 40; int scoreBallSize = 40; // scorePosX/Y means the position the score-ball should be drawn scorePosX = scoreStartX; // scoreStartX/Y = starting position of score balls scorePosY = scoreStartY; for (int i = 0; i < score; i++) { ellipse(scorePosX , scorePosY , scoreBallSize , scoreBallSize); // increment the positions, and wrap to next col if over screen width scorePosX += scoreBallSize ; if( scorePosX > screenWidth) { // next score ball position is beyond the screen scorePosX = scoreStartX; scorePosY += scoreBallSize; } }
进一步重构代码以使用诸如Point之类的东西来表示坐标
Point scoreStartPos = new Point(52, 40); int scoreBallSize = 40; Point scorePos = new Point(scoreStartPos ); for (int i = 0; i < score; i++) { drawCircle(scorePos, scoreBallSize); // a little helper method makes your code easier to read // increment the positions, and wrap to next col if over screen width scorePos.translate( +scoreBallSize, 0); if( scorePos.getX() > screenWidth) { // next score ball position is beyond the screen scorePos.setLocation(scoreStartPoint.getX(), scorePos.getY() + scoreBallSize); } }