FlappyTurtle/GameScreen.java

102 lines
3.0 KiB
Java

import java.awt.Color;
import java.util.List;
import java.util.ArrayList;
class GameScreen implements LinearColorAnimator.AnimationListener
{
private final static int LEVEL_TIME = 10;
private final List<Drawable> _drawables;
private final Bird _bird;
private final World _world;
private final LinearColorAnimator _backgroundAnimator;
private double _totalTime;
private int _try;
private int _level;
public GameScreen()
{
_drawables = new ArrayList<Drawable>();
_backgroundAnimator = new LinearColorAnimator(Color.BLACK, Color.WHITE, 1, this);
_backgroundAnimator.start();
_bird = new Bird(this);
_world = new World(this);
_totalTime = 0;
_try = 1;
}
/*
* Elapsed time is expected to be in ms
*/
public void update(double elapsed)
{
_bird.update(elapsed);
_world.update(elapsed);
_backgroundAnimator.update(elapsed);
_totalTime += elapsed;
System.out.print("\r" + _try + " - Time survived: " + (int)(_totalTime * 1e-3) + "s, " +
"speed: " + (int)_world.getSpeed() + "px/s");
if (_totalTime / (LEVEL_TIME * 1e3) > _level + 1)
{
++_level;
// Would be nice to add some more levels with different colors
if (_level == 1)
{
_world.setObstacleColor("grau");
_backgroundAnimator.setStart(Color.WHITE);
_backgroundAnimator.setEnd(Color.BLACK);
_backgroundAnimator.start();
}
}
Rectangle birdRect = _bird.getRect();
if (_world.checkCollision(_bird.getRect())
|| birdRect.getY() + birdRect.getHeight() > TurtleWelt.HEIGHT
|| birdRect.getY() + birdRect.getHeight() < 0)
{
System.out.print("\n");
++_try;
_totalTime = _level = 0;
_bird.reset();
_world.reset();
// If the background is currently not white, smoothly animate it back
if (_backgroundAnimator.getCurrentColor().getRGB() != Color.WHITE.getRGB())
{
_backgroundAnimator.setStart(_backgroundAnimator.getCurrentColor());
_backgroundAnimator.setEnd(Color.WHITE);
_backgroundAnimator.start();
}
}
}
public void onAnimationFinished()
{
if (_backgroundAnimator.getEnd().getRGB() == Color.BLACK.getRGB())
{
_world.setObstacleColor("weiss");
}
}
public void draw(Turtle turtle, double elapsed)
{
Color bg = _backgroundAnimator.getCurrentColor();
TurtleWelt.globaleWelt.bildschirmEinfaerben(bg.getRed(), bg.getGreen(), bg.getBlue());
for (Drawable d : _drawables)
{
d.draw(turtle, elapsed);
}
}
public void addDrawable(Drawable d)
{
_drawables.add(d);
}
public void jump()
{
_bird.jump();
}
}