Spawning random fruits in Snake Game

时间:2016-07-11 20:50:02

标签: java

I am trying to spawn random colour fruits for a snake game I developed.

However instead of the fruits spawning with a different colour every time, it blinks at random.

Here is the code I used:

private void drawTile(int x, int y, TileType type, Graphics g) {
    /*
     * Because each type of tile is drawn differently, it's easiest
     * to just run through a switch statement rather than come up with some
     * overly complex code to handle everything.
     */

    switch (type) {

    /*
     * A fruit is depicted as a small red circle that with a bit of padding
     * on each side.
     */
        case Fruit:
            Random rn = new Random();
            int answer = rn.nextInt(4) + 1;

            switch (answer) {
                case 1:
                    g.setColor(Color.BLUE);
                    break;
                case 2:
                    g.setColor(Color.GREEN);
                    break;
                case 3:
                    g.setColor(Color.red);
                    break;
                default:
                    g.setColor(Color.YELLOW);
                    break;
            }

            g.fillOval(x + 2, y + 2, TILE_SIZE - 4, TILE_SIZE - 4);
            break;

I think it blinks at random because the screen is constantly refreshing.

0 个答案:

没有答案