111 lines
2.8 KiB
Java
111 lines
2.8 KiB
Java
import java.util.ArrayList;
|
|
import java.util.Random;
|
|
|
|
class World implements Drawable
|
|
{
|
|
private static final int DISTANCE = 250;
|
|
private static final int START_SPEED = 150;
|
|
private static final int ACCELERATION = 2;
|
|
private static final int GAP_SIZE = 100;
|
|
|
|
private final ArrayList<Rectangle> _obstacles;
|
|
private String _obstacleColor;
|
|
private double _speed;
|
|
private final Random _random;
|
|
|
|
public World(GameScreen game)
|
|
{
|
|
game.addDrawable(this);
|
|
_random = new Random();
|
|
_obstacles = new ArrayList<Rectangle>();
|
|
reset();
|
|
}
|
|
|
|
public void reset()
|
|
{
|
|
_obstacles.clear();
|
|
_obstacleColor = "schwarz";
|
|
createObstacle(TurtleWelt.WIDTH);
|
|
_speed = START_SPEED;
|
|
}
|
|
|
|
public void setObstacleColor(String c)
|
|
{
|
|
for (Drawable d : _obstacles)
|
|
{
|
|
if (d instanceof Rectangle)
|
|
{
|
|
((Rectangle)d).setColor(c);
|
|
}
|
|
}
|
|
_obstacleColor = c;
|
|
}
|
|
|
|
private void createObstacle(int x)
|
|
{
|
|
// Position gap somewhere between 50px and HEIGHT - 50px
|
|
int gap = _random.nextInt(TurtleWelt.HEIGHT - GAP_SIZE - 100) + 50;
|
|
_obstacles.add(new Rectangle(x, 0, 30, gap, _obstacleColor, false));
|
|
_obstacles.add(new Rectangle(x, gap + GAP_SIZE, 30, TurtleWelt.HEIGHT, _obstacleColor, false));
|
|
}
|
|
|
|
public void update(double elapsed)
|
|
{
|
|
ArrayList<Rectangle> remove = new ArrayList<Rectangle>();
|
|
for (Rectangle r : _obstacles)
|
|
{
|
|
// Move all obstacles accoring to speed
|
|
r.setPos(r.getX() - (elapsed * 1e-3 * _speed), r.getY());
|
|
|
|
// Mark obstacles that are off screen for removal to avoid
|
|
// concurrent modifications
|
|
if (r.getX() < -r.getWidth())
|
|
{
|
|
remove.add(r);
|
|
}
|
|
}
|
|
for (Rectangle r : remove)
|
|
{
|
|
_obstacles.remove(r);
|
|
}
|
|
|
|
// Add a new obstacle after DISTANCE
|
|
Rectangle lastObstacle = _obstacles.get(_obstacles.size() - 1);
|
|
if (lastObstacle.getX() + lastObstacle.getWidth() < TurtleWelt.WIDTH - DISTANCE)
|
|
{
|
|
createObstacle(TurtleWelt.WIDTH);
|
|
}
|
|
|
|
// Increase speed according to acceleration
|
|
_speed += ACCELERATION * elapsed * 1e-3;
|
|
}
|
|
|
|
public boolean checkCollision(Rectangle r)
|
|
{
|
|
for (Rectangle o : _obstacles)
|
|
{
|
|
if (r.intersects(o))
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public void draw(Turtle t, double elapsed)
|
|
{
|
|
for (Rectangle r : _obstacles)
|
|
{
|
|
if (r.getX() < TurtleWelt.WIDTH)
|
|
{
|
|
r.draw(t, elapsed);
|
|
}
|
|
}
|
|
}
|
|
|
|
public double getSpeed()
|
|
{
|
|
return _speed;
|
|
}
|
|
}
|