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

2014/2/14

Someone please explain this code to me

yutiroe yutiroe

2014/2/14

#
My friend sent me a code to help me work on my own memory game, but i have trouble understanding the code, and my friend are currently out of the country, so I really need someone to help and explain the code to me.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.*;
import java.util.*;

/**
 * Write a description of class GuessingGame here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class GuessingGame  extends World
{
        // Total number of cells must be even
    private static int numCellsX = 6;  
    private static int numCellsY = 6;
    private static int screenX = numCellsX+5;
    private static int screenY = numCellsY+2;
    private static int cellSize = 60;
    private Tile prevTileFlipped;
    private int numTilesToUnflip;

    /**
     * Constructor for objects of class GuessingGame.
     * 
     */
    public GuessingGame()
    {    
        
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(screenX, screenY, cellSize); 
        GreenfootImage gfi = new GreenfootImage(screenX*cellSize, screenY*cellSize);
        gfi.setColor(Color.white);
        gfi.fill();
        gfi.setColor(Color.black);
        int end = numCellsY*cellSize-1;
        for (int i=1; i <= numCellsX; i++)
            gfi.drawLine(i*cellSize, 0, i*cellSize, end);
        end = numCellsX*cellSize-1;
        for (int i=1; i <= numCellsY; i++)
            gfi.drawLine(0, i*cellSize, end, i*cellSize);
        setBackground(gfi);
        for (int i=0; i < numCellsX; i++)
            for (int j=0; j < numCellsY; j++) 
                addObject(new Tile(), i, j);
        reset();
        prevTileFlipped = null;
        numTilesToUnflip = numCellsX*numCellsY;
    }
    
    public void setPrevTileFlipped(Tile tile) {
        prevTileFlipped = tile;
    }
    public Tile getPrevTileFlipped() {
        return prevTileFlipped;
    }
    public void reset() {
        java.util.List list = getObjects(null);
        int id = 0;
        for (int i=list.size(); i > 0; id++) {
            for (int j=0; j < 2; j++) {
                Tile tile = (Tile)(list.remove(Greenfoot.getRandomNumber(i--)));
                tile.setID(id);
                tile.setFlipped(false);
                tile.showImage();
            }
        }
    }
    public void foundTilePair() {
        numTilesToUnflip -= 2;
        if (numTilesToUnflip == 0) {
            addObject(new Bee(),0,5);
            Greenfoot.playSound("applause.wav");
        }
    }
    public int getScreenX() {
        return screenX;
    }
    public int getScreenY() {
        return screenY;
    }
}
yutiroe yutiroe

2014/2/14

#
The part I don't understand the most is the following
public void reset() {  
        java.util.List list = getObjects(null);  
        int id = 0;  
        for (int i=list.size(); i > 0; id++) {  
            for (int j=0; j < 2; j++) {  
                Tile tile = (Tile)(list.remove(Greenfoot.getRandomNumber(i--)));  
                tile.setID(id);  
                tile.setFlipped(false);  
                tile.showImage();  
            }  
        }  
    } 
i simply don't understand how does he manage to make the number set in the tiles, always how does he make sure every number will have a pair. Plus how is every number are in a random place every time.
yutiroe yutiroe

2014/2/14

#
This is the tiles code, which i always want to ask how does he get the tiles to disappear when the numbers are a match, more like how does the program know when the number are a match.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.*;

/**
 * Write a description of class Tile here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Tile  extends Actor
{
    private boolean flipped = false;
    private int id;
    public Tile() {
        super();
        id = 0;
    }
    public void showImage() {
        World w = getWorld();
        int cellSize=getWorld().getCellSize();
        GreenfootImage gfi = new GreenfootImage(cellSize, cellSize);
        if (flipped) {
            gfi.setColor(Color.white);
            gfi.fillRect(1,1,cellSize-1,cellSize-1);
            gfi.setColor(Color.black);
            gfi.setFont(new Font("Arial",Font.BOLD,30));
            gfi.drawString(""+id, 15, 36);
        }
        else 
            gfi.drawImage(new GreenfootImage("ball.png"), 0, 0);
        setImage(gfi);
    }
    public void setID(int newID) {
        id = newID;
    }
    public int getID() {
        return id;
    }
    /**
     * Act - do whatever the Tile wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        // Add your action code here
        if (Greenfoot.mouseClicked(this) && !this.flipped) { 
           GuessingGame world = (GuessingGame) getWorld();
            Tile prevTile = world.getPrevTileFlipped();
            if (prevTile != null) {
                if (prevTile != this) {
                    this.flipped = true;
                    this.showImage();
                    Greenfoot.delay(20);
                    world.setPrevTileFlipped(null);
                    if (prevTile.getID() == this.id) {
                        world.foundTilePair();
                        Greenfoot.playSound("apert.wav");
                    }
                    else {
                        this.flipped = prevTile.flipped = false;
                        this.showImage();
                        prevTile.showImage();
                        Greenfoot.playSound("apert2.wav");
                    }
                }
            }
            else {
                this.flipped = true;
                this.showImage();
                world.setPrevTileFlipped(this);
            }
        }
    }    
    public void setFlipped(boolean s) {
        flipped = s;
    }
}
danpost danpost

2014/2/14

#
Line 59 of the GuessingGame class is what is incrementing the 'id' field. This value is passed to two Tiles (because of the loop at line 60) at line 62 (the value of the Tile object's IDs are compared at line 55 of the Tile class when a second Tile object is clicked on). Line 61 of the GuessingGame class randomly chooses Tile objects from the list, which is what mixes up the Tile objects.
danpost danpost

2014/2/14

#
This would be my version using covers (like your initial code post was trying to do). I used un-named Actors, so this is the entire working code:
import greenfoot.*;

public class Board extends World
{
    private Actor firstChoice, secondChoice; // to hold the choices

    public Board()
    {
        super(6, 6, 80);
        // create background image
        GreenfootImage bg = new GreenfootImage(80, 80);
        bg.fill();
        bg.setColor(java.awt.Color.white);
        bg.fillRect(1, 1, 78, 78);
        setBackground(bg);
        // reset the game
        reset();
    }

    private void reset()
    {
        removeObjects(getObjects(null)); // clear the world of actors
        // add the number actors
        for (int i=0; i<6; i++) for (int j=0; j<6; j++)
        {
            Actor actor = new Actor(){};
            actor.setImage(new GreenfootImage(""+((i*6+j)/2+1), 48, java.awt.Color.black, null));
            actor.getImage().setTransparency(255-((i*6+j)/2)); // like numbered actors will have like image transparencies
            addObject(actor, i, j);
        }
        // shuffle the number actors
        Actor root = (Actor)getObjectsAt(0, 0, null).get(0);
        for (int i=0; i<100; i++)
        {
            Actor swapper = (Actor)getObjects(null).get(Greenfoot.getRandomNumber(getObjects(null).size()));
            root.setLocation(swapper.getX(), swapper.getY());
            swapper.setLocation(0, 0);
            root = swapper;
        }
        // add covers
        for (int i=0; i<6; i++) for (int j=0; j<6; j++) addObject(getNewCover(), i, j);
    }

    private Actor getNewCover()
    {
        Actor cover = new Actor(){};
        GreenfootImage image = new GreenfootImage(70, 70);
        image.fill();
        image.setColor(java.awt.Color.lightGray);
        image.fillRect(5, 5, 59, 59);
        cover.setImage(image);
        return cover;
    }

    public void act()
    {
        if (secondChoice == null && Greenfoot.mouseClicked(null))
        {
            MouseInfo mouse = Greenfoot.getMouseInfo();
            if (mouse == null) return;
            Actor mouseActor = mouse.getActor();
            if (mouseActor == null || getObjectsAt(mouseActor.getX(), mouseActor.getY(), null).size() != 2) return;
            int x = mouseActor.getX(), y = mouseActor.getY();
            removeObject(mouseActor); // remove cover from world
            mouseActor = (Actor)getObjectsAt(x, y, null).get(0); // get actor cover was covering
            if (firstChoice == null)
            {
                firstChoice = mouseActor;
                return;
            }
            secondChoice = mouseActor;
            // here is where I compare the two selections (quite a cheat)
            if (firstChoice.getImage().getTransparency() == secondChoice.getImage().getTransparency())
            {
                // play 'correct' sound  // add to score  // etc.
                Greenfoot.delay(50);
                // remove matching pair
                removeObject(firstChoice);
                removeObject(secondChoice);
            }
            else
            {
                // play 'wrong' sound // etc.
                Greenfoot.delay(50);
                // cover up non-matching pair
                addObject(getNewCover(), firstChoice.getX(), firstChoice.getY());
                addObject(getNewCover(), secondChoice.getX(), secondChoice.getY());
            }
            // reeset choosing cycle
            firstChoice = null;
            secondChoice = null;
        }
        if (getObjects(null).isEmpty()) reset(); // reset field if cleared
    }
}
Mint_Green Mint_Green

2014/2/18

#
01.public void reset() { 02. java.util.List list = getObjects(null); 03. int id = 0; 04. for (int i=list.size(); i > 0; id++) { 05. for (int j=0; j < 2; j++) { 06. Tile tile = (Tile)(list.remove(Greenfoot.getRandomNumber(i--))); 07. tile.setID(id); 08. tile.setFlipped(false); 09. tile.showImage(); 10. } 11. } 12. } How will you make sure that each generated number has a pair of tiles? This is sort of incomplete to me...
danpost danpost

2014/2/18

#
(1) the method declaration statement (2) 'list' will be a list of all actor object in the world (3) initialize id to zero (4) (a) local int 'i' field set to length of list (b) 'id' will be incremented each time block is executed (c) 'i' must be greater than zero to execute (5) execute inner block twice (this is what makes two actors get the same 'id' value) (6) get random actor from list (removing it from the list and adjusting 'i', the current size of list) (7) assign the chosen tile the current 'id' (8) set tile to not show its value (9) update the image of the tile (10) repeat for a second actor (refer to 5) (next tile with same 'id') (11) repeat until all tiles are taken care of (refer to 4) (next randomly chosen pair) It is somewhat confusing the way it is written (although it does what it is supposed to do). The main confusion comes from how the 'for' on line 4 is utilized. The code could be re-written many ways, such as:
public void reset() {
    java.util.List list = getObjects(Tile.class);
    for (int id=0; id<list.size(); id++)
    {
        Tile tile = (Tile)removeObject(Greenfoot.getRandomNumber(list.size());
        tile.setID(id/2);
        tile.setFlippd(false);
        tile.showImage();
    }
}
I felt no need for the extra int 'i' field to track the number of tiles left in the list. Also, using 'id/2' was a much easier way to have paired tiles get the same 'id' value.
You need to login to post a reply.