This site requires JavaScript, please enable it in your browser!
Greenfoot back
SportingLife7
SportingLife7 wrote ...

2022/1/16

How can i generate each brick in a sequence when the run button pressed?

SportingLife7 SportingLife7

2022/1/16

#
Hi, im trying to generate the lines of bricks for my brick breaker game in a sequence, I tried using greenfoot delay but it lagged the program and caused glitches. Any help appreciated :)
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;

/**
 * The game board. The board had a paddle that can move.
 * 
 * @author mik
 * @version 1.0
 */

public class Board extends World
{
    private Paddle paddle;
    private int startStars = 2500;

    /**
     * Constructor for objects of class Board.
     * adds in the paddle, the counters etc.
     * 
     */
    public Board()
    {    
        super(460, 520, 1); // all  of these will be put in this order the first will be the top layer of the screen, the following will be under it like the asteroid going on top of the healthbar
        GreenfootImage background = getBackground();//use this to add text, the first line before the equal sign
        background.setColor(Color.BLACK);
        background.fill();
        createStars(startStars);

        setPaintOrder ( Ball.class, Smoke.class, PowerUps.class  );
        paddle = new Paddle();
        addObject ( paddle, getWidth() / 2, getHeight() - 40);
        ballIsOut();
         buildBricks(1);

    }

    /**
     * Add a given number of stars to our world.
     */
    private void createStars(int number) 
    {
        GreenfootImage background = getBackground();
        for(int i = 0; i < number; i++) 
        {
            int x = Greenfoot.getRandomNumber(getWidth());
            int y = Greenfoot.getRandomNumber(getHeight());
            int r = Greenfoot.getRandomNumber(256);
            int g = Greenfoot.getRandomNumber(256);
            int b = Greenfoot.getRandomNumber(256);
            background.setColor(new Color(r,g,b));
            background.fillOval(x, y, 4 , 4); //the two two controls the size of my stars!
            //we add the same r value to make it gray if we would have many then we would get rainbow!
        }
    }

    /**
     * checks to see what the score, is
     * checks to see what level it is
     * checks to see if cheat keys are pressed
     * checks to see if it is time to advance to a new level
     * picks random numbers and if it is a certain range it drops a power up
     */
    public void act()
    {
        
    }

    /**
     * checks to see if the ball is out
     */
    public void ballIsOut()
    {

        paddle.newBall();

    }
    // /**
    // * this is to get our brick info back!
    // */
    // public Brick getBrick()
    // {
    // return brick;
    // }
    /**
     * checks to see what level it currently is and if it needs to advance.
     */
    public void checkLevel()
    {

    }

    /**
     * creates the scoreboard for between levels.
     */
    public void levelBoard()
    {

    }

    /**
     * initializes the construction of levels
     */
    public void levelAdvance()
    {

    }

    /**
     * builds the bricks 1 by 1 for each of the levels
     */
    public void buildBricks (int numberOfRows) //public void buildBricks (int numberOfRows)
    {  

        for (int i = 0; i < 7; i++)
            for (int b = 0; b < 3; b++)
                addObject (new Brick (), 75 + i*50, 100 + 40*b);
        //Greenfoot.delay(1); // this is not the most effective way to create the block by blco effect we need
        // also need to figure out how to make rows of bricks (ask the guys for help)


    }

    /**
     * separate method for a special level design
     */
    public void levelSix()
    {

    }
    /**
     * separate method for a level design with bricks that need to be hit twice.
     */
    public void levelSeven()
    {

    }

    /**
     * cheat keys to advance levels.
     */
    public void cheats()
    {

    }

    /**
     * resets all factors involved with level advance.
     */

    public void reset()
    {

    }
    /**
     * This method is called when the game is over to display the final score.
     */
    public void gameOver() 
    {

    }
}
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * The ball of the game. It moves and bounces off the walls and the paddle.
 * 
 * @author mik
 * @version 1.0
 */
public class Ball extends Actor
{
    private int deltaX;         // x movement speed
    private int deltaY;         // y movement speed
    private int count = 2;
    public static int BALL_COUNT = 0;
    public  static int score = 0;
    public static int levelScore = 0;
    private Counter scoreKeeper;
    private boolean stuck = true;   // stuck to paddle
    public static boolean brokenBrick = false;
    public static boolean ultimateBall = false;
    public static int timer = 251;
    public int timerReset = 250;

    /**
     * Act. Move if we're not stuck.
     */
    public void act() 
    {
        if (!stuck) 
        {
            move();
            makeSmoke();
            checkOut();
            
        }
    }

    /**
     * Move the ball. Then check what we've hit.
     */
    public void move()
    {
        setLocation (getX() + deltaX, getY() + deltaY);
        checkPaddle();
        checkWalls();
        checkBricks();
    }

    /**
     * Check whether we've hit one of the three walls. Reverse direction if necessary.
     */
    private void checkWalls()
    {
        if (getX() == 0 || getX() == getWorld().getWidth()-1) {
            deltaX = -deltaX;
        }
        if (getY() == 0) {
            deltaY = -deltaY;
            turn(180);
        }
    }

    /**
     * Check whether we're out (bottom of screen). If we are, spawn a new ball on the paddle assuming we have lives left.
     */
    private void checkOut()
    {
        if (getY() == getWorld().getHeight()-1) {
            ((Board) getWorld()).ballIsOut();
            getWorld().removeObject(this);
            //Ball.BALL_COUNT--;
        }
    }

    /**
     * Check whether we are touching the paddle, and bounce off of it if we are.
     */
    private void checkPaddle()
    {
        Actor paddle = getOneIntersectingObject(Paddle.class);
        if (paddle != null) {
            deltaY = -deltaY;//flips the direction on the y-axis
            turn (180);
            int offset = getX() - paddle.getX();
            deltaX = deltaX + (offset/10);
            if (deltaX > 7) 
            {
                deltaX = 7;
            }
            if (deltaX < -7) 
            {
                deltaX = -7;
            }
        }            
    }

    /**
     * check whether we are touching a brick, and bounce off it if we are (and remove the brick we touched)
     * adds score if we remove a brick or hit a brick
     */

    private void checkBricks()
    {
        Actor brick = getOneIntersectingObject(Brick.class);
             if (brick != null) {
            deltaY = -deltaY;
            turn(180);
            int offset = getX() - brick.getX();
            deltaX = deltaX + (offset/10);
            if (deltaX > 7) {
                deltaX = 7;
            }
            if (deltaX < -7) {
                deltaX = -7;
            }
            
    }
}
    /**
     * check whether we are touching a brick of the other brick class (this was for making bricks that require 2 hits to destroy.
     * One hit changed the image, the second hit removed it.
     */    
    private void checkBricks2()
    {

    }

    /**
     * Move the ball a given distance sideways.
     */
    public void move(int dist)
    {
        setLocation (getX() + dist, getY());
    }

    /**
     * Put out a puff of smoke (only on every second call).
     */
    private void makeSmoke()
    {
        count--;
        if (count == 0) {
            getWorld().addObject ( new Smoke(), getX(), getY());
            count = 2;
        }
    }

    /**
     * Release the ball from the paddle. 
     */
    public void release()
    {
        deltaX = Greenfoot.getRandomNumber(11) - 5; //sets the intial angle when released from paddle
        deltaY = -5;  // controls the speed of the ball
        stuck = false;
    }
}
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;
/**
 * Write a description of class Brick here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Brick extends Actor
{
    public Board world = (Board) getWorld();
    public boolean removed = false;
    /**
     * bricks gonna be bricks, nothing is really done in this class becuase they just have an image set for them.
     * But you may do more in here.,
     */
    public Brick()
    {
        
    }
    
        /**
     * Act - do whatever the Brick wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    
    public void act() 
    {
        if (isTouching(Ball.class))
        {
            this.removed = true;
            getWorld().removeObject(this);
            //Greenfoot.playSound();
            
        }// Add your action code here.
    }    
    

}
danpost danpost

2022/1/16

#
If the Board world is your initial world, then you probably do not want to call buildBricks from the constructor. Greenfoot.delay does not work in your initial constructor. Actually, it only works if your scenario is already in a running state. Try adding the following method (which is automatically called by greenfoot when the scenario starts up) to the Board class:
public void started()
{
    if (Ball.levelScore == 0 && getObjects(Brick.class).isEmpty()) buildBricks(1);
}
(uncommenting lines in the buildBricks method and increasing the delay to about 4 or 5).
SportingLife7 SportingLife7

2022/1/16

#
Hi @danpost, first of all, thank you for your help. I added the code and removed the build bricks(1) from the constructor (also increased the delay), but it generates the entire lines of brick all at the same time, how can i make it so that each individual brick generates like a sequence (or maybe just each line generate in a sequence)?
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;

/**
 * The game board. The board had a paddle that can move.
 * 
 * @author mik
 * @version 1.0
 */

public class Board extends World
{
    private Paddle paddle;
    private int startStars = 2500;

    /**
     * Constructor for objects of class Board.
     * adds in the paddle, the counters etc.
     * 
     */
    public Board()
    {    
        super(460, 520, 1); // all  of these will be put in this order the first will be the top layer of the screen, the following will be under it like the asteroid going on top of the healthbar
        GreenfootImage background = getBackground();//use this to add text, the first line before the equal sign
        background.setColor(Color.BLACK);
        background.fill();
        createStars(startStars);

        setPaintOrder ( Ball.class, Smoke.class, PowerUps.class  );
        paddle = new Paddle();
        addObject ( paddle, getWidth() / 2, getHeight() - 40);
        ballIsOut();
       //buildBricks(1);

    }

    /**
     * Add a given number of stars to our world.
     */
    private void createStars(int number) 
    {
        GreenfootImage background = getBackground();
        for(int i = 0; i < number; i++) 
        {
            int x = Greenfoot.getRandomNumber(getWidth());
            int y = Greenfoot.getRandomNumber(getHeight());
            int r = Greenfoot.getRandomNumber(256);
            int g = Greenfoot.getRandomNumber(256);
            int b = Greenfoot.getRandomNumber(256);
            background.setColor(new Color(r,g,b));
            background.fillOval(x, y, 4 , 4); //the two two controls the size of my stars!
            //we add the same r value to make it gray if we would have many then we would get rainbow!
        }
    }
    public void started()
{
    if (Ball.levelScore == 0 && getObjects(Brick.class).isEmpty()) buildBricks(1);
}
    /**
     * checks to see what the score, is
     * checks to see what level it is
     * checks to see if cheat keys are pressed
     * checks to see if it is time to advance to a new level
     * picks random numbers and if it is a certain range it drops a power up
     */
    public void act()
    {
        
    }

    /**
     * checks to see if the ball is out
     */
    public void ballIsOut()
    {

        paddle.newBall();

    }
    // /**
    // * this is to get our brick info back!
    // */
    // public Brick getBrick()
    // {
    // return brick;
    // }
    /**
     * checks to see what level it currently is and if it needs to advance.
     */
    public void checkLevel()
    {

    }

    /**
     * creates the scoreboard for between levels.
     */
    public void levelBoard()
    {

    }

    /**
     * initializes the construction of levels
     */
    public void levelAdvance()
    {

    }

    /**
     * builds the bricks 1 by 1 for each of the levels
     */
    public void buildBricks (int numberOfRows) //public void buildBricks (int numberOfRows)
    {  

        for (int i = 0; i < 7; i++)
            for (int b = 0; b < 3; b++)
                addObject (new Brick (), 75 + i*50, 100 + 40*b);
                Greenfoot.delay(4);
                 // this is not the most effective way to create the block by blco effect we need
        // also need to figure out how to make rows of bricks (ask the guys for help)


    }

    /**
     * separate method for a special level design
     */
    public void levelSix()
    {

    }
    /**
     * separate method for a level design with bricks that need to be hit twice.
     */
    public void levelSeven()
    {

    }

    /**
     * cheat keys to advance levels.
     */
    public void cheats()
    {

    }

    /**
     * resets all factors involved with level advance.
     */

    public void reset()
    {

    }
    /**
     * This method is called when the game is over to display the final score.
     */
    public void gameOver() 
    {

    }
}
danpost danpost

2022/1/16

#
In buildBricks method, you need curly brackets around the implementation within the inner for loop:
public void buildBricks(int numberOfRows)
{
    for (int b=0; b<numberOfRows; b++) for (int i=0; i<7; i++)
    {
        addObject (new Brick(), 75+i*50, 100+40*b);
        Greenfoot.delay(6);
    }
}
SportingLife7 SportingLife7

2022/1/16

#
Thank you @danpost that worked perfect. :)
SportingLife7 SportingLife7

2022/1/16

#
Wait, sorry I just had another question...? I added a score counter to the code and now it's lagging. Is there anything I can do to optimize the code so it won't do this?
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;

/**
 * The game board. The board had a paddle that can move.
 * 
 * @author mik
 * @version 1.0
 */

public class Board extends World
{
    private Paddle paddle;
    private int startStars = 2500;
    private Lives livesCounter;
    private Counter scoreCounter;
    public int round = 1;
    /**
     * Constructor for objects of class Board.
     * adds in the paddle, the counters etc.
     * 
     */
    public Board()
    {    
        super(460, 520, 1); // all  of these will be put in this order the first will be the top layer of the screen, the following will be under it like the asteroid going on top of the healthbar
        GreenfootImage background = getBackground();//use this to add text, the first line before the equal sign
        background.setColor(Color.BLACK);
        background.fill();
        createStars(startStars);

        setPaintOrder ( Ball.class, Smoke.class, PowerUps.class  );
        paddle = new Paddle();
        addObject ( paddle, getWidth() / 2, getHeight() - 40);
        ballIsOut();
        livesCounter = new Lives("Lives: ");
        addObject(livesCounter, 430, 500);
        //buildBricks(1);
        scoreCounter = new Counter("Score: ");
        addObject(scoreCounter, 70, 500 );
    }

    /**
     * Add a given number of stars to our world.
     */
    private void createStars(int number) 
    {
        GreenfootImage background = getBackground();
        for(int i = 0; i < number; i++) 
        {
            int x = Greenfoot.getRandomNumber(getWidth());
            int y = Greenfoot.getRandomNumber(getHeight());
            int r = Greenfoot.getRandomNumber(256);
            int g = Greenfoot.getRandomNumber(256);
            int b = Greenfoot.getRandomNumber(256);
            background.setColor(new Color(r,g,b));
            background.fillOval(x, y, 4 , 4); //the two two controls the size of my stars!
            //we add the same r value to make it gray if we would have many then we would get rainbow!
        }
    }

    public void started()
    {
        if (Ball.levelScore == 0 && getObjects(Brick.class).isEmpty()) buildBricks(1);
    }

    /**
     *  counts the lives, everytime we hit the bottom it goes up by the int
     */
    public void livesScore(int add)
    {
        livesCounter.add(-1);
        // score += add;
    }
    /**
     *  counts the score, everytime we hit a brick it goes up by the int
     */
    public void countScore(int add)
    {
        scoreCounter.add(20);
        // score += add;
    }
    /**
     * checks to see what the score, is
     * checks to see what level it is
     * checks to see if cheat keys are pressed
     * checks to see if it is time to advance to a new level
     * picks random numbers and if it is a certain range it drops a power up
     */
    public void act()
    {

    }

    /**
     * checks to see if the ball is out
     */
    public void ballIsOut()
    {

        paddle.newBall();

    }
    // /**
    // * this is to get our brick info back!
    // */
    // public Brick getBrick()
    // {
    // return brick;
    // }
    /**
     * checks to see what level it currently is and if it needs to advance.
     */
    public void checkLevel()
    {

    }

    /**
     * creates the scoreboard for between levels.
     */
    public void levelBoard()
    {

    }

    /**
     * initializes the construction of levels
     */
    public void levelAdvance()
    {

    }

    /**
     * builds the bricks 1 by 1 for each of the levels
     */
    public void buildBricks(int numberOfRows)
    {
        for (int b=0; b<numberOfRows; b++) for (int i=0; i<7; i++)
            {
                addObject (new Brick(), 75+i*50, 100+40*b);
                addObject (new Brick(), 75+i*50, 140+40*b);
                addObject (new Brick(), 75+i*50, 180+40*b);
                Greenfoot.delay(6);
            }
    }

    /**
     * separate method for a special level design
     */
    public void levelSix()
    {

    }

    /**
     * separate method for a level design with bricks that need to be hit twice.
     */
    public void levelSeven()
    {

    }

    /**
     * cheat keys to advance levels.
     */
    public void cheats()
    {

    }

    /**
     * resets all factors involved with level advance.
     */

    public void reset()
    {

    }

    /**
     * This method is called when the game is over to display the final score.
     */
    public void gameOver() 
    {   
        addObject(new ScoreBoard(scoreCounter.getValue()), getWidth()/2, getHeight()/2); // the coordinates div
        // TODO: show the score board here. Currently missing.
    }
}
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.*;
/**
 * Write a description of class Brick here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Brick extends Actor
{
    public Board world = (Board) getWorld();
    public boolean removed = false;
    private int size;
    /**
     * bricks gonna be bricks, nothing is really done in this class becuase they just have an image set for them.
     * But you may do more in here.,
     */
    public Brick()
    {
        
    }
    
        /**
     * Act - do whatever the Brick wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    
    public void act() 
    {
       Board board = (Board) getWorld();
        if (isTouching(Ball.class))
        {
            this.removed = true;
            getWorld().removeObject(this);
            board.countScore((int)size*board.round/10);
            //Greenfoot.playSound();
            
        }// Add your action code here.
    }    
    

}
import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) import java.awt.Graphics; /** * Counter that displays a text and number. * * @author Michael Kolling * @version 1.0.1 */ public class Counter extends Actor { private static final Color textColor = new Color(255, 180, 150); private int value = 0; private int target = 0; private String text; private int stringLength; public Counter() { this(""); } public Counter(String prefix) { text = prefix; stringLength = (text.length() + 2) * 10; setImage(new GreenfootImage(stringLength, 16)); GreenfootImage image = getImage(); image.setColor(textColor); updateImage(); } public void act() { if(value < target) { value++; updateImage(); } else if(value > target) { value--; updateImage(); } } public void add(int score) { target += score; } public int getValue() { return target; } /** * Make the image */ private void updateImage() { GreenfootImage image = getImage(); image.clear(); image.drawString(text + value, 1, 12); } }
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.Calendar;

/**
 * Write a description of class ScoreBoard here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class ScoreBoard extends Actor
{
    public static final float FONT_SIZE = 48.0f;
    public static final int WIDTH = 400;
    public static final int HEIGHT = 300;
    
    /**
     * Create a score board with dummy result for testing.
     */
    public ScoreBoard()
    {
        this(100);
    }

    /**
     * Create a score board for the final result.
     */
    public ScoreBoard(int score)
    {
        makeImage("Game Over", "Score: ", score);
    }

    /**
     * Make the score board image.
     */
    private void makeImage(String title, String prefix, int score)
    {
        GreenfootImage image = new GreenfootImage(WIDTH, HEIGHT);

        image.setColor(new Color(255,255,255, 128)); // setting a color
        image.fillRect(0, 0, WIDTH, HEIGHT); // filiing the reactangle
        image.setColor(new Color(0, 0, 0, 128));
        image.fillRect(5, 5, WIDTH-10, HEIGHT-10); //smaller rectangle
        Font font = image.getFont();
        font = font.deriveFont(FONT_SIZE);
        image.setFont(font);
        image.setColor(Color.WHITE);
        image.drawString(title, 60, 100); 
        image.drawString(prefix + score, 60, 200); //using string concatenation with the prefix + score line
        setImage(image);
    }
}
danpost danpost

2022/1/16

#
SportingLife7 wrote...
I added a score counter to the code and now it's lagging. Is there anything I can do to optimize the code so it won't do this? << Code Omitted >>
I do not see anything in your codes that would cause lagging. I do, however, see a few lines that are unnecessary: Remove line 2 from Board class; remove lines 2 and 11 from Brick class; remove line 2 from Counter class; and, remove line 2 from ScoreBoard class.
SportingLife7 SportingLife7

2022/1/16

#
Thank you @danpost, its working better now. :)
You need to login to post a reply.