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

2019/1/26

Variable Passing

1
2
northernlights176 northernlights176

2019/1/26

#
Hello I have created a game that allows the user to take on the role of a psychologist that has two possible choices to make. I want to take whichever choice is used and create a results screen that shows the percentage of each choice made by different users. Where I am stuck is passing variables between the world sets. I have created world class game scene and four subclasses of that game scene but am unable to keep the variable values created within each game scene to carry over to the results screen. I have created getter and setter methods within each scene but cannot figure this out. I did not include my code within this initial post as it is quite lengthy. Any help would be greatly appreciated!
danpost danpost

2019/1/26

#
You will probably want to hold all of a user's choices in an array, then pass the array around from world to world or assign the array to an array in any world you proceed to.
northernlights176 northernlights176

2019/1/27

#
Hello Thank you so much for the reply. I am going to go ahead and post one scene of my code and the code for the results screen so if you have a chance you can see what I have done and tell me why it is not working. I am also having one more issue with getting the 'patients' name to display once and the compiled results to display properly along with that 'patients' name.
;import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class InsanityPlea here.
 * 
 * @Nicholas Ferry
 * @1.00
 */
public class BariatricSurgery extends GameScene
{

    /*INSTANCE VARIABLES*/
    // Counters and name storing variable for calculating UserInfo
    private static int denialCounter;
    private static int approvalCounter;
    private String bariatricPatientName;
    private static int bariatricChoiceCounter;
    private static boolean bariatricChecker; // records which choice is made
    
    //Button objects for game buttons
    public LeftBariatricButton leftButton;
    public RightBariatricButton rightButton;
    
    //Array variables for storing the patient name, stories and questions for the player
    private String[] patientNames = {"Casper","Mark","Jack"};
    private String[] bariatricStories = new String[3];
    private String[] questions = new String[3];
    
    // variable for storing the story number and patient to be randomly generated
    private int storyIndex;
    
    /**
     * Constructor for objects of class InsanityPlea.
     * 
     */
    public BariatricSurgery()
    {
        denialCounter = 0;
        approvalCounter = 0;
        bariatricChoiceCounter = 0;
        bariatricChecker = true;
        leftButton = new LeftBariatricButton("leftBariatricButton.png");
        addObject( leftButton, 125, 375 );
        rightButton = new RightBariatricButton("rightBariatricButton.png");
        addObject( rightButton, 450, 375 );
        storiesArrayInput(); 
        questionsArrayInput();
        indexSetter();
    } // end constructor
    
    /**
     * Act method for class. Calls two methods, the story display method that displays
     * the patients story and the question for the user, and finally
     * the finalSceneWrapUp method that detects which choice the
     * user makes
     */
    public void act()
    {
        playSound();    
        storyAndQuestionsDisplay();
        approvalCounterSetter();
        denialCounterSetter();
        patientNameSetter();
        choiceCounterSetter();
        setBariatricChecker();
        finalSceneWrapUp();
    }//end act method
    
    /**
     * Method to store the questions in their corresponding array variable
     * named questions
     */
    public void questionsArrayInput()
    {
        questions[0] = "a";
        questions[1] = "b";
        questions[2] = "c";
    }// end method questionsArrayInput
    /**
     * Method to store story string objects into the instance array 
     * bariatricStories. 
     */
    public void storiesArrayInput()
    {
        bariatricStories[0] = "x";
        bariatricStories[1] = "y";
        bariatricStories[2] = "z";             
        
    } // end method storiesArrayInput
    
    /**
     * Method that gives the story index variable 
     * a random integer between 0 and 2 for future use through the scene 
     */
    public void indexSetter()
    {
        storyIndex = Greenfoot.getRandomNumber(3);
        
    }// end method indexSetter
    
    /**
     * Getter method for the storyIndex variable
     */
    public int getIndex()
    {
        return storyIndex; 
    } // end method getIndex
       
    /**
     * Method to dislay the patient story # based on the number stored in the 
     * storyIndex variable 
     */
    public void storyAndQuestionsDisplay()
    {
        showText(bariatricStories[storyIndex], 250, 50); 
        showText(questions[storyIndex], 50, 100);
    }//end storyDisplay method
   
    /**
     * Final method that stores the corresponding patient inside the 
     * bariatricPatientName String variable for further use in calculating 
     * the results of the game.
     */
    public void finalSceneWrapUp()
    {              
        if (Greenfoot.mouseClicked(leftButton))
        {
            Greenfoot.setWorld(new ResultsScene());
            bariatricChecker = true;
            approvalCounter++;
            bariatricChoiceCounter++;
        } // end if
        
        if( Greenfoot.mouseClicked(rightButton))
        {
            Greenfoot.setWorld(new ResultsScene());
            bariatricChecker = false;
            denialCounter++;
            bariatricChoiceCounter++;
        }// end else if
        
        
    }// end method finalSceneWrapUp
    
    /**
     * Method that sets the denialCounter 
     */
    public void denialCounterSetter()
    {
        this.denialCounter = denialCounter;
    } // end method denialCounterSetter
    
    /**
     * Method that sets the approvalCounter
     */
    public void approvalCounterSetter()
    {
        this.approvalCounter = approvalCounter;
    } // end method approvalCounterSetter
    
    /**
     * Method that retrieves the denial counter for use in the results caluclator
     */
    public int denailCounterGetter()
    {
        return denialCounter;
    } // end method denialCounterGetter
    
    /**
     * Method that retrieves the approval counter for use in the results caluclator
     */
    public int approvalCounterGetter()
    {
        return approvalCounter;
    } // end method approvalCounterGetter
    
    /**
     * Setter method for the patient name store variable
     */
    public void patientNameSetter()
    {
        bariatricPatientName = patientNames[storyIndex];
    } // end method patientNameSetter
    
    /**
     * Getter method for the patient name store variable
     */
    public String patientNameGetter()
    {
        return bariatricPatientName;
    } // end method
    
    /**
     * Setter method for the choice counter
     */
    public void choiceCounterSetter()
    {
        this.bariatricChoiceCounter = bariatricChoiceCounter;
    } // end method choiceCounterSetter
    
    /**
     * Getter method for the choice counter
     */
    public int choiceCounterGetter()
    {
        return bariatricChoiceCounter;
    } // end method choiceCounterGetter
    
    /**
     * Setter method for the checker variable
     */ 
    public void setBariatricChecker()
    {
        this.bariatricChecker = bariatricChecker;
    }// end method setBariatricChecker
    
    /**
     * Getter method for the checker variable
     */
    public boolean getBariatricChecker()
    {
        return bariatricChecker;
    } // end method getBariatricChecker
} // end class Bariatric surgery

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

/**
 * Write a description of class ResultsScene here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class ResultsScene extends GameScene
{

    /* INSTANCE VARIABLES */
    private InsanityPlea insanityScene;
    private int insane;
    private int sane;
    private int insanityChoicesMade;
    private int insanityIndex;
    private boolean insanityCheck;
    private String[] insanityPatientNames = {"Robb","Austin","Dan"};
    
    private BariatricSurgery bariatricScene;
    private int bariatricApproval;
    private int bariatricDenial;
    private int bariatricIndex;
    private int bariatricChoicesMade;
    private boolean bariatricCheck;
    private String[] bariatricPatientNames = {"Casper","Mark","Jack"};
    
    /*
    private PowerOfAttorney poaScene;
    private int poaApproval;
    private int poaDenial;
    private int poaChoicesMade;
    private String poaPatient;
    */
    

    /**
     * Constructor for objects of class ResultsScene.
     * 
     */
    public ResultsScene()
    {
        insane = 0;
        sane = 0;
        insanityChoicesMade = 0;
        insanityIndex = 0;
        insanityCheck = true;
        
        bariatricApproval = 0;
        bariatricDenial = 0;
        bariatricChoicesMade = 0;
        bariatricIndex = 0;
        bariatricCheck = true;
        
        
        insanityScene = new InsanityPlea();
        bariatricScene = new BariatricSurgery();
        //poaScene = new PowerOfAttorney();
    } // end constructor for class ResultsScene

    /**
     * Act method for the results screen page
     */
    public void act()
    {
        updateAndDisplayResults();
        variableGetterAndSetter();
    } // end act method

    /**
     * Method to retrieve all the information from previous scenes to create variables
     * that will be used to calculate the end results
     * 
     */
    public void variableGetterAndSetter()
    {
        insane = insanityScene.insanityCounterGetter();
        sane = insanityScene.saneCounterGetter();
        insanityChoicesMade = insanityScene.choiceCounterGetter();
        insanityCheck = insanityScene.getInsanityChecker();
        insanityIndex = insanityScene.indexGetter();
        
        bariatricApproval = bariatricScene.approvalCounterGetter();
        bariatricDenial = bariatricScene.denailCounterGetter();
        bariatricChoicesMade = bariatricScene.choiceCounterGetter();
        bariatricCheck = bariatricScene.getBariatricChecker();
        bariatricIndex = bariatricScene.getIndex();
        
        /*
        poaApproval = poaScene.
        poaDenial = poaScene.
        poaChoicesMade = poaScene.
        poaPatient = poaScene. 
        */
    } // end method variableGetterAndSetter

    /**
     * Method to calculate the Results board
     */
    public void updateAndDisplayResults()
    {
        if( UserInfo.isStorageAvailable() )
        {
            UserInfo myInfo = UserInfo.getMyInfo();
            
            //Set variables for user info storage
            myInfo.setInt(0, insane);
            myInfo.setInt(1, sane);
            myInfo.setInt(2, insanityChoicesMade);
            
            
            myInfo.setInt(3, bariatricApproval);
            myInfo.setInt(4, bariatricDenial);
            myInfo.setInt(5, bariatricChoicesMade);
            
            
            /* create local variables for calculating choice percentage
            double insanityPct = Math.round( 100 * ( (double)insanityChoicesMade / (double)insane));
            double sanePct = Math.round( 100 * ( (double)insanityChoicesMade / (double)sane));
            double bariatricApprovalPct = Math.round( 100 * ( (double)bariatricChoicesMade / (double)bariatricApproval));
            double bariatricDenialPct = Math.round( 100 * ( (double)bariatricChoicesMade / (double)bariatricDenial));
            */
            
            // create variables for column points to enable consistancy 
            int column1xpos = 125;
            int column2xpos = 220;
            int column3xpos = 310;
            int column4xpos = 420;
            int column5xpos = 525;
            
            int columnYpos1 = 1*getWidth()/8;
            int columnYpos2 = (1*getWidth()/8) + 75;        
            
            showText( "User", 50, 25);
            showText( "Patient", column1xpos, 25);
            showText( "Insane %", column2xpos, 25);
            showText( "Sane %", column3xpos, 25);
            showText( "Approval %", column4xpos, 25);
            showText( "Denial %", column5xpos, 25);
            
            //create a list of the top five users         
            List<UserInfo> topUsersInfo = new ArrayList( myInfo.getTop(5) );
            
            int totalInsanityChoicesAllUsers = 0;
            int totalSaneChoicesAllUsers = 0;
            int totalInsanityOverallChoiceCountAllUsers = 0;
            
            int totalBariatricApprovalChoicesAllUsers = 0;
            int totalBariatricDenialChoicesAllUsers = 0;
            int totalBariatricOverallChoiceCountAllUsers = 0;
            
            int yDisplaypos = 50; 
            
            for ( UserInfo currentUserInfo : topUsersInfo )
            {
                int totalChoicesInsanityCurrentUser = currentUserInfo.getInt(2);
                int totalInsaneCountCurrentUser = currentUserInfo.getInt(0);
                int totalSaneCountCurrentUser = currentUserInfo.getInt(1);
                
                int totalChoicesBariatricCurrentUser = currentUserInfo.getInt(5);
                int totalApprovalsMadeCurrentUser = currentUserInfo.getInt(3);
                int totalDenialsMadeCurrentUser = currentUserInfo.getInt(4);
                
                double currentInsanityPct = Math.round( 100 * ( (double)totalChoicesInsanityCurrentUser / totalInsaneCountCurrentUser));
                double currentSanePct = Math.round( 100 * ( (double)totalChoicesInsanityCurrentUser / totalSaneCountCurrentUser));
                double currentBariatricApprovalPct = Math.round( 100 * ( (double)totalChoicesBariatricCurrentUser / totalApprovalsMadeCurrentUser));
                double currentBariatricDenialPct = Math.round( 100 * ( (double)totalChoicesBariatricCurrentUser / totalDenialsMadeCurrentUser));
                
                showText("" + currentUserInfo.getUserName(), 10, yDisplaypos);
                
                for(int k = 0; k < 3; k++)
                {
                    showText(insanityPatientNames[k], column1xpos, columnYpos1);
                    
                    if( k ==insanityIndex && insanityCheck)
                    {
                        showText("" + currentInsanityPct, column2xpos, columnYpos1);
                        columnYpos1 += 25;
                    } // end inner if
                    if(k == insanityIndex && !insanityCheck) 
                    {
                        showText("" + currentSanePct, column3xpos, columnYpos1);
                        columnYpos1 += 25;
                    }// end inner if 
                    
                
                 } // end inner for
                 
                for( int n = 0; n < 3; n++)
                    {
                        showText(bariatricPatientNames[n], column1xpos, columnYpos2);
                        
                        if( n == bariatricIndex && bariatricCheck )
                        {
                          showText("" + currentBariatricApprovalPct, column4xpos, columnYpos2);  
                          columnYpos2 += 25;
                        } // end if4
                        
                        if( n == bariatricIndex && !bariatricCheck )
                        {
                            showText("" + currentBariatricDenialPct, column5xpos, columnYpos2);
                            columnYpos2 += 25;
                        }// end if
                    } // end for loop
                    
                totalInsanityChoicesAllUsers = totalInsanityChoicesAllUsers + totalInsaneCountCurrentUser;
                totalSaneChoicesAllUsers = totalSaneChoicesAllUsers + totalSaneCountCurrentUser;
                totalInsanityOverallChoiceCountAllUsers = totalInsanityOverallChoiceCountAllUsers + totalChoicesInsanityCurrentUser;
                
                totalBariatricApprovalChoicesAllUsers = totalBariatricApprovalChoicesAllUsers + totalApprovalsMadeCurrentUser;
                totalBariatricDenialChoicesAllUsers = totalBariatricDenialChoicesAllUsers + totalDenialsMadeCurrentUser;
                totalBariatricOverallChoiceCountAllUsers = totalBariatricOverallChoiceCountAllUsers + totalChoicesBariatricCurrentUser;                                             
                
                yDisplaypos += 25;
            } // end enhanced for
            
            double overallInsanityPct = Math.round( 100 * ( (double)totalInsanityOverallChoiceCountAllUsers / (double)totalInsanityChoicesAllUsers));
            double overallSanePct = Math.round( 100 * ( (double)totalInsanityOverallChoiceCountAllUsers / (double)totalSaneChoicesAllUsers));
            double overallBariatricApprovalPct = Math.round( 100 * ( (double)totalBariatricOverallChoiceCountAllUsers / (double)totalBariatricApprovalChoicesAllUsers));
            double overallBariatricDenialPct = Math.round( 100 * ( (double)totalBariatricOverallChoiceCountAllUsers / (double)totalBariatricDenialChoicesAllUsers));
            
            // y variables for name printingg consistancy
            int columnYpos3 = 200;
            int columnYpos4 = 275;
            
            // reprint insanity names for overall %
            for( int i = 0; i < 3; i++)
            {
                showText(insanityPatientNames[i], column1xpos, columnYpos3);
                
                if( i ==insanityIndex && insanityCheck)
                    {
                        showText("" + overallInsanityPct, column2xpos, columnYpos3);
                        columnYpos3 += 25;
                    } // end inner if
                if(i == insanityIndex && !insanityCheck) 
                {
                   showText("" + overallSanePct, column3xpos, columnYpos3);
                   columnYpos3 += 25;
                }// end inner if 
            } // end for loop
            
            // reprint bariatric surgery patient names for overall %
            for( int j = 0;j < 3; j++)
            {
                
                
                if( j == bariatricIndex && bariatricCheck )
                {
                   showText("" + overallBariatricApprovalPct, column4xpos, columnYpos4);  
                   showText(bariatricPatientNames[j], column1xpos, columnYpos4);
                   columnYpos4 += 25;
                   continue;
                } // end if
                       
                if( j == bariatricIndex && !bariatricCheck )
                {
                   showText("" + overallBariatricDenialPct, column5xpos, columnYpos4);
                   showText(bariatricPatientNames[j], column1xpos, columnYpos4);
                   columnYpos4 += 25;
                   
                }// end if
                continue;
            } // end for loop
            
            int column6xpos = 220;
            int column7xpos = 320;
            int column8xpos = 420;
            int column9xpos = 525;
            
            showText("Overall %", column6xpos,175); 
            showText("Overall %", column7xpos, 175);
            showText("Overall %", column8xpos, 175);
            showText("Overall %", column9xpos, 175);
            
            
            

            
            
        }// end OUTERMOST if
        
    } // end method updateAndDisplayResults
}
danpost danpost

2019/1/27

#
Your ResultsScene object seems to be creating new instances of type BariatricSurgury and InsanityPlea (lines 283 and 284). Neither could be a world that was previously active and all instance fields in them are at their initial state (not equal to any that are in a world that was already active and completed). Only a previously active world of those types would contain the results you are trying to get. You could add setter methods to assign worlds to them so that when you create a results world in one of those type worlds, you can set the field to that world. As an alternative, you can pass the world using a parameter to the ResultsScene constructor, where the field could then be set.
northernlights176 northernlights176

2019/1/29

#
I have attached the below image to represent how I would like the game flow to go. With that being said, the alternative option would be best to use where I pass the world, and its variables to the results scene. Now I do understand this analytically, but I am having trouble understanding it programatically. Can you by chance provide an example of how to do this?
danpost danpost

2019/1/29

#
In your ResultsScreen class, add the following class field:
public static ResultsScreen resultsScreen;
In your TitleScreen constructor, add this line:
ResultsScreen.resultsScreen = new ResultsScreen();
In the ResultsScreen classs, make lines 239 and 247 public (instead of private) and remove lines 283 and 284. In your BariatricSurgery class constructor, add this:
ResultsScreen.resultsScreen.bariatricScene = this;
Do similarly in the InsanityPlea class. Finally, when going to the results world, use:
Greenfoot.setWorld(ResultsScreen.resultsScreen);
northernlights176 northernlights176

2019/2/7

#
Thanks for the reply! Do I place this code
Greenfoot.setWorld(ResultsScreen.resultsScreen);
within my bariatric surgery code here
public void finalSceneWrapUp()
    {              
        if (Greenfoot.mouseClicked(leftButton))
        {
            [u]Greenfoot.setWorld(new ResultsScene.ResultsScene());[/u]
            bariatricChecker = true;
            approvalCounter++;
            bariatricChoiceCounter++;
        } // end if
        
        if( Greenfoot.mouseClicked(rightButton))
        {
           [u] Greenfoot.setWorld(new ResultsScene())[/u];
            bariatricChecker = false;
            denialCounter++;
            bariatricChoiceCounter++;
        }// end else if
as when I do I get a cannot find symbol - class ResultsScene error.
danpost danpost

2019/2/7

#
That is because I spelled it wrong try changing all occurrences of "ResultsScreen" to "ResultsScene" and "resultsScreen" to "resultsScene".
northernlights176 northernlights176

2019/2/7

#
Hi danpost, I did realize this and changed all instances of it but even with this change, (line 5 in the above code), I am still getting this error. This is the only place that I am receiving this error however. Thank you so much for your time and expertise as this project is very important to me!
danpost danpost

2019/2/8

#
northernlights176 wrote...
I did realize this and changed all instances of it but even with this change, (line 5 in the above code), I am still getting this error. This is the only place that I am receiving this error however. Thank you so much for your time and expertise as this project is very important to me!
On line 5, the second 'R' should be 'r' (as in "ResutlsScene.resultsScene'). Also, line 13 should be the same as line 5.
northernlights176 northernlights176

2019/2/11

#
Ok fixed that error. I was calling a new results scene rather than referencing my created resultsScene object like you were saying. However I am getting a nullPointerException in this line of code (also in the bariatric) ResultsScene.resultsScene.insanityScene = this;:
    public InsanityPlea()
    {
        insanityCounter = 0;
        saneCounter = 0;
        insanityChoiceCounter = 0;
        insanityChecker = true;
        leftButton = new LeftInsanityButton("leftInsanityButton.png");
        addObject( leftButton, 125, 375 );
        rightButton = new RightInsanityButton("rightInsanityButton.png");
        addObject( rightButton, 450, 375 );
        storiesArrayInput(); 
        questionsArrayInput();
        indexSetter();
        ResultsScene.resultsScene.insanityScene = this;
In your previous reply when you outline which constructor value to add, was I supposed to add those value to the constructor arguments, or within the constructor method itself?
danpost danpost

2019/2/11

#
northernlights176 wrote...
I am getting a nullPointerException in this line of code (also in the bariatric) ResultsScene.resultsScene.insanityScene = this;:
One of the first things your project should do is assign a ResultsScene object to ResultsScene.resultsScene (as stated above).
northernlights176 northernlights176

2019/2/11

#
Yes I have done this in the Title Screen constructor as you suggested (see below).
public TitleScreen()
    {    
        // Create a new world with 600x400 cells with a cell size of 1x1 pixels.
        super(600, 400, 1); 
        ResultsScene.resultsScene = new ResultsScene();
        leftTitleButton = new LeftTitleButton("leftTitleButton.png");
        addObject( leftTitleButton, 125, 325);
        rightTitleButton = new RightTitleButton("rightTitleButton.png");
        addObject( rightTitleButton, 475, 325);
        
        bgMusic = new GreenfootSound("titleMusic.mp3");
    } // end class constructor
But none of the scenes will allow for instantiation and when I right click to do a new TitleScreen(); I get the nullPointerException pop-up.
danpost danpost

2019/2/11

#
northernlights176 wrote...
Yes I have done this in the Title Screen constructor as you suggested (see below). << Code Omitted >> But none of the scenes will allow for instantiation and when I right click to do a new TitleScreen(); I get the nullPointerException pop-up.
Please clear the terminal, recreate the error and copy/paste it in its entirety here.
northernlights176 northernlights176

2019/2/12

#
Will do. i have posted the exact output in the console when I first open the Greenfoot project:
java.lang.NullPointerException
	at InsanityPlea.<init>(InsanityPlea.java:49)
	at ResultsScene.<init>(ResultsScene.java:59)
	at TitleScreen.<init>(TitleScreen.java:26)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at greenfoot.core.Simulation.newInstance(Simulation.java:580)
	at greenfoot.platforms.ide.WorldHandlerDelegateIDE.lambda$instantiateNewWorld$0(WorldHandlerDelegateIDE.java:143)
	at greenfoot.core.Simulation.runQueuedTasks(Simulation.java:470)
	at greenfoot.core.Simulation.maybePause(Simulation.java:299)
	at greenfoot.core.Simulation.runContent(Simulation.java:190)
	at greenfoot.core.Simulation.run(Simulation.java:183)
There are more replies on the next page.
1
2