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

2017/1/21

Making this code easier?

Hoppa Hoppa

2017/1/21

#
Hi, I got the following code in MyWorld, character and scroller
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
 * Wereld klasse.
 * Hierin worden alle objecten in de wereld geplaatst.
 * 
 * 
 * 
 * @author Jochen De Saedeleer
 * @version 16012017
 */
public class MyWorld extends World
{
    private Background img0, img1, img2; // Hierdoor kan de achtergrond in de scrolling geplaatst worden.

    // Hier wordt gebruik gemaakt van een array voor het plaatsen van de X-coördinaten van de onderstaanden objecten in de scrolling wereld.
    private int[] GeleBoomX = { 300, 700, 1200, 2000, }; // de Coordinaten op de X-as waar de bomen zich gaan bevinden die IN de scroll zitten.
    private int[] SteenX = { 340, 600, 870, 1402 };
    private int[] BlockX = { 1300 }; 
    // Vijanden
    private int[] Monster1X = { 380 };
    private int[] Monster2X = { 735 };
    private int[] SpikeX = { 1885, 2000,2016,2032,2048,2064,2080,2096 };

    // Platformen
    private int[] PlatformX = { 1450, 1578, 1706, };
    private int[] PlatformblockX = { 1815, };
    private int[] BewegendPlatformX = { 1950, 2150 };
    private int manX;
    private int[] SterX = { 340 };

    /**
     * Constructor for objects of class MyWorld.
     * 
     */
    public MyWorld()
    {    
        // Create a new world with 1000x400 cells with a cell size of 1x1 pixels. False zorgt ervoor dat het mannetje de rand niet raakt.
        super(1000, 400, 1, false); // True is bounded en false is unbounded

        img0 = new Background(); // maakt een achtergrond aan
        addObject( img0, getWidth()/2, getHeight()/2 ); // hierdoor wordt de image mooi gecentreerd in de wereld

        img1 = new Background(); // maakt een achtergrond aan MAAR aan de rechterkant van de afbeelding die niet zichtbaar is maar gescrollt
        addObject( img1, getWidth() + getWidth()/2 , getHeight()/2 );

        img2 = new Background(); // maakt een achtergrond aan MAAR aan de rechterkant van de afbeelding die niet zichtbaar is maar gescrollt
        addObject( img2, getWidth()*2 + getWidth()/2 , getHeight()/2 );

        addObject(new Hoofdplatform(), -63, 385);
        addObject(new Hoofdplatform(), 65, 385);
        addObject(new Hoofdplatform(), 193, 385);
        addObject(new Hoofdplatform(), 321, 385);
        addObject(new Hoofdplatform(), 449, 385);
        addObject(new Hoofdplatform(), 577, 385);
        addObject(new Hoofdplatform(), 705, 385);
        addObject(new Hoofdplatform(), 833, 385);
        addObject(new Hoofdplatform(), 961, 385);

        for(int t=0; t<GeleBoomX.length; t++) { // GeleBoom start bij 0 en gaat altijd 1 omhoog( zie lijst bovenaan ). als de boom kleiner is dan de lengte van de lijst blijft hij opbouwen tot hij het einde bereikt.
            addObject(new GeleBoom(), GeleBoomX[t], 331); // 331 = de Y-as waar die zich bevind
        }

        for(int t=0; t<BewegendPlatformX.length; t++) { // GeleBoom start bij 0 en gaat altijd 1 omhoog( zie lijst bovenaan ). als de boom kleiner is dan de lengte van de lijst blijft hij opbouwen tot hij het einde bereikt.
            addObject(new BewegendPlatform(), BewegendPlatformX[t], 331); // 331 = de Y-as waar die zich bevind
        }

        for(int t=0; t<SterX.length; t++) { // GeleBoom start bij 0 en gaat altijd 1 omhoog( zie lijst bovenaan ). als de boom kleiner is dan de lengte van de lijst blijft hij opbouwen tot hij het einde bereikt.
            addObject(new Ster(), SterX[t], 200); // 331 = de Y-as waar die zich bevind
        }

        for(int t=0; t<SteenX.length; t++) { // GeleBoom start bij 0 en gaat altijd 1 omhoog( zie lijst bovenaan ). als de boom kleiner is dan de lengte van de lijst blijft hij opbouwen tot hij het einde bereikt.
            addObject(new Steen(), SteenX[t], 357);
            if (t==3) {
                addObject(new Steen(), SteenX[t], 325);
            }
        }

        // Vijanden
        for(int t=0; t<Monster1X.length; t++) { // GeleBoom start bij 0 en gaat altijd 1 omhoog( zie lijst bovenaan ). als de boom kleiner is dan de lengte van de lijst blijft hij opbouwen tot hij het einde bereikt.
            addObject(new Monster1(), Monster1X[t], 347);
        }

        for(int t=0; t<Monster2X.length; t++) { // GeleBoom start bij 0 en gaat altijd 1 omhoog( zie lijst bovenaan ). als de boom kleiner is dan de lengte van de lijst blijft hij opbouwen tot hij het einde bereikt.
            addObject(new Monster2(), Monster2X[t], 349);
        }

        for(int t=0; t<SpikeX.length; t++) { // GeleBoom start bij 0 en gaat altijd 1 omhoog( zie lijst bovenaan ). als de boom kleiner is dan de lengte van de lijst blijft hij opbouwen tot hij het einde bereikt.
            addObject(new Spike(), SpikeX[t], 360);
        }

        // Platformen
        for(int t=0; t<BlockX.length; t++) { // GeleBoom start bij 0 en gaat altijd 1 omhoog( zie lijst bovenaan ). als de boom kleiner is dan de lengte van de lijst blijft hij opbouwen tot hij het einde bereikt.
            addObject(new Block(), BlockX[t], 350);
        }

        for(int t=0; t<PlatformX.length; t++) { // GeleBoom start bij 0 en gaat altijd 1 omhoog( zie lijst bovenaan ). als de boom kleiner is dan de lengte van de lijst blijft hij opbouwen tot hij het einde bereikt.
            addObject(new Platform(), PlatformX[t], 295);
        }

        for(int t=0; t<PlatformblockX.length; t++) { // GeleBoom start bij 0 en gaat altijd 1 omhoog( zie lijst bovenaan ). als de boom kleiner is dan de lengte van de lijst blijft hij opbouwen tot hij het einde bereikt.
            addObject(new Platformblock(), PlatformblockX[t], 370);
            if (t==0) {
                addObject(new Platformblock(), PlatformblockX[t], 310);
                addObject(new Platformblock(), PlatformblockX[t], 250);
            }
        }

        addObject(new mannetje(), 80, 346); // Deze moet onderaan staan, zodat het mannetje niet vermenigvuldigd wordt in de methode hierboven. Hierdoor gaat het mannetje VOOR de bomen komen en niet erachter lopen.
    }

    public void act()
    {
        if(!getObjects(mannetje.class).isEmpty()){ // Als de wereld NIET leeg is, gaat het mannetje de getX aanroepen van het mannetje.
            Actor man = (Actor)getObjects(mannetje.class).get(0);
            manX = man.getX(); 
            if (Greenfoot.isKeyDown("right") && manX > 400) {
                img0.scroll();
                img1.scroll();
                img2.scroll();

                List<GeleBoom> Gelebomen = getObjects(GeleBoom.class);
                for( int t=0; t<Gelebomen.size(); t++) {
                    GeleBoom geleboom = Gelebomen.get(t); // Alles in java = Object
                    geleboom.scroll();
                }

                List<Steen> Stenen = getObjects(Steen.class);
                for( int t=0; t<Stenen.size(); t++) {
                    Steen steen = Stenen.get(t); // Alles in java = Object
                    steen.scroll();
                }

                // Vijanden
                List<Monster1> Monsters1 = getObjects(Monster1.class);
                for( int t=0; t<Monsters1.size(); t++) {
                    Monster1 monster1 = Monsters1.get(t); // Alles in java = Object
                    monster1.scroll();
                }

                List<Monster2> Monsters2 = getObjects(Monster2.class);
                for( int t=0; t<Monsters2.size(); t++) {
                    Monster2 monster2 = Monsters2.get(t); // Alles in java = Object
                    monster2.scroll();
                }

                List<Spike> Spikes = getObjects(Spike.class);
                for( int t=0; t<Spikes.size(); t++) {
                    Spike spikes = Spikes.get(t); // Alles in java = Object
                    spikes.scroll();
                }

                // Platformen
                List<BewegendPlatform> BewegendPlatformen = getObjects(BewegendPlatform.class);
                for( int t=0; t<BewegendPlatformen.size(); t++) {
                    BewegendPlatform bewegendPlatform = BewegendPlatformen.get(t); // Alles in java = Object
                    bewegendPlatform.scroll();
                }

                List<Block> Blocken = getObjects(Block.class);
                for( int t=0; t<Blocken.size(); t++) {
                    Block block = Blocken.get(t); // Alles in java = Object
                    block.scroll();
                }

                List<Platform> Platformen = getObjects(Platform.class);
                for( int t=0; t<Platformen.size(); t++) {
                    Platform platform = Platformen.get(t); // Alles in java = Object
                    platform.scroll();
                }

                List<Platformblock> Platformenblock = getObjects(Platformblock.class);
                for( int t=0; t<Platformenblock.size(); t++) {
                    Platformblock platformblock = Platformenblock.get(t); // Alles in java = Object
                    platformblock.scroll();
                }
            }
        }
    }
}
Scroller Superclass
    public void scroll()
    {
        setLocation(getX()-5, getY());
    }
My Character
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class testmannetje here.
 * 
 * @author Jochen De Saedeleer
 * @version 16012017
 */
public class mannetje extends Scroller
{
    private int speed = 3; // snelheid( in pixels ) waarmee het mannetje horizontaal loopt.
    private int vSpeed = 0; // V staat voor verticale speed, dus springen en vallen.
    private int acceleration = 1; //het mannetje gaat hierdoor vallen zoals bij de zwaartekracht( realistischer ).
    private boolean jumping;
    private int jumpStrength = 15; // Hoe hoger het aantal hoe hoger het mannetje springt.
    private int frame = 1; // de afbeeldingen per aantal die geladen worden.
    private int animationCounter = 0;

    private GreenfootImage manRechts2 = new GreenfootImage("manRechts2.png");
    private GreenfootImage manRechts3 = new GreenfootImage("manRechts3.png");
    private GreenfootImage manRechts4 = new GreenfootImage("manRechts4.png");
    private GreenfootImage manRechts5 = new GreenfootImage("manRechts5.png");
    private GreenfootImage manRechts6 = new GreenfootImage("manRechts6.png");

    private GreenfootImage manLinks2 = new GreenfootImage("manLinks2.png");
    private GreenfootImage manLinks3 = new GreenfootImage("manLinks3.png");
    private GreenfootImage manLinks4 = new GreenfootImage("manLinks4.png");
    private GreenfootImage manLinks5 = new GreenfootImage("manLinks5.png");
    private GreenfootImage manLinks6 = new GreenfootImage("manLinks6.png");

    public void act() 
    {
        checkKeys();
        checkFall();
        animationCounter++;
        checkRightWalls();
        checkLeftWalls();
    }   

    private void checkKeys()
    {
        if (Greenfoot.isKeyDown("left") ) // Als ik de linker keyarrow indruk gaat de afbeelding van het man-links laden en de methode moveLeft aanroepen
        {
            moveLeft();
        }
        
        if (Greenfoot.isKeyDown("right") ) // Dient om de animatie constant aan te sturen bij het gebruik van de rechterkey
        {
            animaterechts();
            if (getX() < 402) {
                moveRight();
            }
        }
        
        if (Greenfoot.isKeyDown("left") ) // Dient om de animatie constant aan te sturen bij het gebruik van de linkerkey
        {
            animatelinks();
        }

        if (Greenfoot.isKeyDown("space") && jumping == false){
            jump();
        }
    }

    private boolean checkRightWalls() // controleert de rechterkant van de muren. 
    {
        int spriteWidth = getImage().getWidth(); // berekent de omvang van de afbeelding
        int xDistance = (int)(spriteWidth/2); // berekent de grootte van de afbeelding en gaat aan de hand daarvan de eerste aanraking met het object berekenen.
        Actor rightWall = getOneObjectAtOffset(xDistance, 0, Hoofdplatform.class);
        if(rightWall == null)
        {
            return false;
        }
        else
        {
            stopByRightWall(rightWall);
            return true;
        }
    }

    private void stopByRightWall(Actor rightWall) // Het mannetje gaat automatisch stoppen bij het aanraken van de rechterkant van het object.
    {
        int wallWidth = rightWall.getImage().getWidth(); 
        int newX = rightWall.getX() - (wallWidth + getImage().getWidth())/2;
        setLocation(newX - 5, getY());
    }

    private boolean checkLeftWalls() // controleert de linkerkant van de muren.
    {
        int spriteWidth = getImage().getWidth();
        int xDistance = (int)(spriteWidth/-2); // berekent 
        Actor leftWall = getOneObjectAtOffset(xDistance, 0, Hoofdplatform.class);
        if(leftWall == null)
        {
            return false;
        }
        else
        {
            stopByLeftWall(leftWall);
            return true;
        }
    }

    private void stopByLeftWall(Actor leftWall) // Het mannetje gaat automatisch stoppen bij het aanraken van de linkerkant van het object.
    {
        int wallWidth = leftWall.getImage().getWidth();
        int newX = leftWall.getX() + (wallWidth + getImage().getWidth())/2;
        setLocation(newX + 5, getY());
    }

    private void moveRight()
    {
        setLocation(getX()+speed, getY()); // +speed, getY = de beweging naar rechts die uitgevoerd wordt op de horizontale lijn.
    }
    
    private void animaterechts()
    {
        if(animationCounter %5 == 0) // % van de hoeveelheid afbeeldingen die geladen worden( hoe hoger hoe sneller de animatie gebeurd )
        {
            animateRight();
        }
    }
    
    private void animatelinks()
    {
        if(animationCounter %5 == 0) // % van de hoeveelheid afbeeldingen die geladen worden( hoe hoger hoe sneller de animatie gebeurd )
        {
            animateLeft();
        }
    }

    private void moveLeft()
    {
        setLocation(getX()-speed, getY());
    }

    private void fall()
    {
        setLocation(getX(), getY() + vSpeed); // Laat het mannetje vallen met een snelheid die meer volgende de zwaartekracht werkt.
        if(vSpeed <=9)
        {
            vSpeed = vSpeed + acceleration; // De Vspeed ( snelheid ) + acceleration ( de zwaartekracht om het realistischer te maken ).
        }
        jumping = true;
    }

    private boolean onGround() // Als het mannetje de grond niet raakt, kan het niet springen. Pas vanaf dat het mannetje een grond raakt kan er gesprongen worden.
    {
        Actor ground = getOneObjectAtOffset (0, getImage().getHeight() / 2, Hoofdplatform.class); // Berekent de breedte en hoogte van de image / 2 om de juiste aanraking van de grond mogenlijk te maken.
        if(ground == null)
        {
            jumping = true;
            return false;
        }
        else
        {
            moveToGround(ground);
            return true;
        }
    }

    private void moveToGround(Actor ground)
    {
        int groundHeight = ground.getImage().getHeight();
        int newY = ground.getY() - (groundHeight + getImage().getHeight())/2; // De grootte van het mannetje wordt in 2 gedeeld, zodat deze het object het platform niet aanraakt in het midden, maar op de rand van zijn voeten.
        setLocation(getX(), newY);
        jumping = false;
    }

    private void checkFall() // Controleert of het mannetje de grond raakt, en laat deze dan stoppen. Als de 'onGround' niet herkent wordt, blijft hij vallen.
    {
        if(onGround())
        {
            vSpeed = 0;
        }
        else
        {
            fall();
        }
    }

    private void jump()
    {
        vSpeed = -jumpStrength; // Bij de jump gaat het mannetje verzwakken in jumpstrenght om zo een realistische val te maken ( anders blijft het op dezelfde hoogte )
        jumping = true;
        fall();
    }

    private void animateLeft() // De animatie dat het mannetje maakt als hij naar links stapt. Volgende afbeeldingen worden dan geladen en terug in een loop geplaatst.
    {
        if(frame == 1)
        {
            setImage(manLinks2);
        }
        else if(frame == 2)
        {
            setImage(manLinks3);
        }
        else if(frame == 3)
        {
            setImage(manLinks4);
        }
        else if(frame == 4)
        {
            setImage(manLinks5);
        }
        else if(frame == 5)
        {
            setImage(manLinks6);
            frame = 1;
            return;
        }
        frame++;
    }
    
    /**
     * Return true if we can see an object of class 'clss' right where we are. 
     * False if there is no such object here.
     */
    public boolean canSee(Class clss)
    {
        Actor actor = getOneObjectAtOffset(0, 0, clss);
        return actor != null;        
    }
    
        /**
     * Try to grab an object of class 'clss'. This is only successful if there
     * is such an object where we currently are. Otherwise this method does
     * nothing.
     */
    public void get(Class clss)
    {
        Actor actor = getOneObjectAtOffset(0, 0, clss);
        if(actor != null) {
            getWorld().removeObject(actor);
        }
    }
    
    
    private void animateRight() // De animatie dat het mannetje maakt als hij naar rechts stapt. Volgende afbeeldingen worden dan geladen en terug in een loop geplaatst.
    {
        if(frame == 1)
        {
            setImage(manRechts2);
        }
        else if(frame == 2)
        {
            setImage(manRechts3);
        }
        else if(frame == 3)
        {
            setImage(manRechts4);
        }
        else if(frame == 4)
        {
            setImage(manRechts5);
        }
        else if(frame == 5)
        {
            setImage(manRechts6);
            frame = 1;
            return;
        }
        frame++;
    }
}

Now this works fine, but i got some questions about this.. Is it possible to shorten the following code?
addObject(new Hoofdplatform(), -63, 385);
        addObject(new Hoofdplatform(), 65, 385);
        addObject(new Hoofdplatform(), 193, 385);
        addObject(new Hoofdplatform(), 321, 385);
        addObject(new Hoofdplatform(), 449, 385);
        addObject(new Hoofdplatform(), 577, 385);
        addObject(new Hoofdplatform(), 705, 385);
        addObject(new Hoofdplatform(), 833, 385);
        addObject(new Hoofdplatform(), 961, 385);
The platform the character is standing on, is every time on the same Y-coördinate of '385' and with a width of 128 pixels also. 65 + 128 = 193, 193 + 128 = 321 and so on. Is their a code where i can just do some coding like 'addObject(new Hoofdplatform(), -63, 385 + getX 128pixels * 10 ) or something.. I know this code doesn't exist but its an idea about what i want. I want the code to be as easy as possible This is also a side-scroller and scrolling to the right works fine when walking, but he cant scroll back to the left.. I think this has to do something with the following code:
            if (Greenfoot.isKeyDown("right") && manX > 400)  {
                img0.scroll();
                img1.scroll();
                img2.scroll();
I tryed something like this
 (Greenfoot.isKeyDown("right") && manX > 400) || Greenfoot.isKeyDown("left") && manX  < 100)                    img0.scroll();
img1.scroll();
img2.scroll();
but that doesnt seems to work. Can someone provides me the code for those problems? I can than look into that code and see what i did wrong.. I tryed all different things but if i can see the code needed, i can look into that and see where to fix it Thanks in advance
Super_Hippo Super_Hippo

2017/1/21

#
1.
for (int i=0; i<9; i++) addObject(new Hoofdplatform(), -63 + 128*i, 385);
2. I think the problem is this line:
setLocation(getX()-5, getY());
This will scroll to one side no matter if the right or left key is pressed. Oh and if you want to shorten the animate methods, you can do it like this:
private GreenfootImage[] manLinks =
{
    new GreenfootImage("manLinks2.png"),
    new GreenfootImage("manLinks3.png"),
    new GreenfootImage("manLinks4.png"),
    new GreenfootImage("manLinks5.png"),
    new GreenfootImage("manLinks6.png")
};

private void animateLinks()
{
    if (animationCounter % 5 == 0)
    {
        setImage(manLinks[frame])
        frame = (frame+1) % 5;
    }
}
Super_Hippo Super_Hippo

2017/1/21

#
-- ignore this post --
Hoppa Hoppa

2017/1/21

#
Hi Super_Hippo Is there any simple way to let him also scroll to the left by pressing the left arrow? Or if there is to many code needed.. Or elseway Is it possible to let him walk to an 'invisble wall' so he can't get off the screen? The code
setLocation(getX()-5, getY());
is needed for moving my actors while scrolling. Thanks alot :)
Super_Hippo Super_Hippo

2017/1/21

#
You could split what you tried into two parts and then either scroll it right or left (so using a + instead of the - when scrolling left).
Hoppa Hoppa

2017/1/21

#
Could you be kind to show me the code for that? I'm getting errors trying.. Sorry i'm very new @ this but want to learn from the correct code.
danpost danpost

2017/1/21

#
Hoppa wrote...
i'm very new @ this
You must be jochen! The code supplied above is not from someone who is new to this.
Hoppa Hoppa

2017/1/21

#
Hi Danpost! Its Jochen indeed :-). I have some problems logging into my other account so i made a new one.
(Greenfoot.isKeyDown("right") && manX > 400) || Greenfoot.isKeyDown("left") && manX  < 100)           
img0.scroll();
img1.scroll();
img2.scroll();
This was a code i heard from someone that could work, but doesnt seem to do it with me. I can't change this code any more because i am learning it for my project, but i just know that something like the code above must work... Any code you can help me with? some easy code i can understand? If its to difficult.. is their a way that the character just walk against some invisible wall while trying to move to the left? Else he just dissapears.. . My project will be finished if i can just fix this last problem i have :) Thanks in advance
danpost danpost

2017/1/21

#
You could check which key was found down in the Scroller Superclass to determine which way to scroll. However, your actors currently only wrap from left to right. They will need to be able to go both ways depending on their location. Do make sure that when wrapping, you are not placing them outside the non-wrapping area.
Hoppa Hoppa

2017/1/21

#
I understand the problem indeed. Is it easier to let my character instead move to an invisble wall if i walk to the left with some code? I tryed it already with placing an object on -10 x-coordinate and then it looks like he is walking into an invisble wall but then afcourse i got the problem that he is pulling the objects with it while scrolling. Some easy fix for that?
Super_Hippo Super_Hippo

2017/1/21

#
This is what I meant. Not sure if I understood you correctly, though.
if (Greenfoot.isKeyDown("right") && manX > 400)
{
    img0.scrollRight();
    img1.scrollRight();
    img2.scrollRight();
}
else if (Greenfoot.isKeyDown("left") && manX < 100)
{
    img0.scrollLeft();
    img1.scrollLeft();
    img2.scrollLeft();
}
public void scrollRight()
{
    setLocation(getX()-5, getY());
}

public void scrollLeft()
{
    setLocation(getX()+5, getY());
}
Hoppa Hoppa

2017/1/21

#
Hi Super_Hippo Thanks for giving the code already but that is the code i tryed and meant but doesnt seem to work. When i start the game all the objects scroll immediatly and push me away. I think the problem is inside the following List codes:
                List<BewegendPlatform> BewegendPlatformen = getObjects(BewegendPlatform.class);
                for( int t=0; t<BewegendPlatformen.size(); t++) {
                    BewegendPlatform bewegendPlatform = BewegendPlatformen.get(t); // Alles in java = Object
                }
and all the other lists If i use
bewegendPlatform.scrollRight();
the objects goes to the left fast and
bewegendPlatform.scrollLeft();
with that code my objects goes to the right when i press run without even moving I know the following code moves their location, but with the previous code i already used they were only moving when i pressed right after 400x. I just want the normal scrolling behavior in it. after 400x scrolling to the right and when my character moving left again the image scrolls back. Or else just let my character walks into an invisble wall when moving back because he is else walking outside the frame and then i lose him.
public void scrollRight()
{
    setLocation(getX()-5, getY());
}
 
public void scrollLeft()
{
    setLocation(getX()+5, getY());
}
danpost danpost

2017/1/21

#
Lines 50 through 52 restrict your actor from going more to the right than about 405 (like being blocked by an invisible wall; or at least it would look that way if you ignored everything else). Similar code could be used for when moving left (at line 44).
Hoppa Hoppa

2017/1/22

#
Thanks Danpost, Your a genius ;-). Such a simple code...
        if (Greenfoot.isKeyDown("left") ) // Dient om de animatie constant aan te sturen bij het gebruik van de linkerkey
        {
            animatelinks();
            if (getX() > 16) {
                moveLeft();
            }
        }
You need to login to post a reply.