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

2021/4/30

UserInfo not working

Ned Ned

2021/4/30

#
Can anybody figure out why my UserInfo code isn't working? I'm using it to save the players progress. It will save if you just reset the scenario, but not if you refresh the page. Here's the link and the relevant code.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class MenuWorld extends World implements KeyInputObserver {
    
    private final LevelButton[] buttons;
    
    /**
     * Constructor for objects of class MenuWorld.
     */
    public MenuWorld() {
        super(700, 700, 1);
        buttons = new LevelButton[2];
        prepare();
        if (UserInfo.getMyInfo() != null) {
            for (int i = 0; i <= UserInfo.getMyInfo().getInt(0); i++) {
                buttons[i].unlock();
            }
        } else {
            throw new IllegalArgumentException("UserInfo required");
        }
    }

    /**
     * Prepare the world for the start of the program.
     * That is: create the initial objects and add them to the world.
     */
    private void prepare() {
        buttons[0] = new LevelButton(1, true);
        buttons[1] = new LevelButton(2);
        addObject(buttons[0], 100, 100);
        addObject(buttons[1], 300, 100);
        
    }

    public void startLevel(int level) {
        switch (level) {
            case 1:
                Greenfoot.setWorld(new GameWorld1(this));
                break;
            case 2:
                Greenfoot.setWorld(new GameWorld2(this));
                break;
            
        }
    }

    public void unlockLevel(int level) {
        if (level < buttons.length) {
            buttons[level].unlock();
            if (UserInfo.getMyInfo() != null && UserInfo.getMyInfo().getInt(0) < level) {
                UserInfo.getMyInfo().setInt(0, level);
            }
        }
    }
    
}

Ned Ned

2021/4/30

#
The LevelButtons are buttons that call startLevel when they are clicked on if they are unlocked. unlockLevel gets called by the gameWorlds when they are complete.
RcCookie RcCookie

2021/4/30

#
After you change a value in an UserInfo object you have to call „store()“ on it. If you change multiple values you may only call it once in the end. In your case you have to store the info after changing it in unlockLevel().
Ned Ned

2021/5/1

#
Thanks!
You need to login to post a reply.