Question regarding classes/objects and static methods

Creating a super simple game and am stuck

Page 1 of 1

11 Replies - 1179 Views - Last Post: 02 August 2010 - 12:08 AM Rate Topic: -----

#1 iamfreshfish   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 11-September 09

Question regarding classes/objects and static methods

Posted 01 August 2010 - 11:41 AM

Hi all,
Hopefully someone can help me with a conceptual question. I am building a simple dice game that has the following classes:
Game class (main method, instantiates 2 player objects, starts GUI, ends game)
Player class (holds name, score, etc and has roll and hold methods)
GUI class (super simple GUI)

I would have posted the code but it has gotten messy and have run into too many problems with the static methods/variables as I kept getting erros about not being able to access this or that

Question:
Does the above scenario make sense?
How come I cannot access a variable from object player1.myTurn from the GUI class...it says player1 cant be found?

If anyone can shed some light on these questions and the above setup, that would be awesome
Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: Question regarding classes/objects and static methods

#2 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Question regarding classes/objects and static methods

Posted 01 August 2010 - 11:50 AM

The way I'm following it, it seems to make sense to me.

The Game Class makes sense, it's basically just a main method that runs the whole program. Player class makes sense as well. So what you would do is create two(or however many players you want) Player classes in the Game Class. The the GUI class will just be used to draw things? I think that makes sense.

Your question:
From what I can tell without seeing code, it makes sense.
So the Player1 Object is of type Player, correct?

So in the GUI class have you done something like this:
Player player1 = new Player();


That will create your player object.

So myTurn must be a method within the Player Class, correct? Is it set up something like this? (I'm just making it up I have no idea what it's suppose to do)
public boolean myTurn()
{
     return true;
}



If it's set up something like that, then you should be having no problems.

Perhaps just post the code where you try to use it and the code for that method?

Hope this helps!
Was This Post Helpful? 0
  • +
  • -

#3 japanir   User is offline

  • jaVanir
  • member icon

Reputation: 1014
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Question regarding classes/objects and static methods

Posted 01 August 2010 - 11:51 AM

The classes design seems ok.
But to really understand what the problems are, and offer help, we would have to see the code.
Or at leats, what methods are declared static? what variables are declared static?
Also, Did you declare a package for your classes? are all these classes under the same package in the same folder?
Was This Post Helpful? 0
  • +
  • -

#4 iamfreshfish   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 11-September 09

Re: Question regarding classes/objects and static methods

Posted 01 August 2010 - 12:03 PM

Thanks guys for the quick reply.
I'm somewhat embarrassed to post the code.

But to answer the questions:
a) I instantiated the 2 player objects in the Game class...
B) The Player class (hence the objects) have roll() and hold() methods and a myTurn variable
c) The GUI has a Roll button that when clicks is checking to see if it is Player1's turn ie if(player1.mTurn==true)

Does that shed some light on the error?
Was This Post Helpful? 0
  • +
  • -

#5 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Question regarding classes/objects and static methods

Posted 01 August 2010 - 12:12 PM

Oh, so what you're saying is mTurn is a variable?

Well that's not exactly the best OOP way to go about doing this.

So if mTurn is a boolean variable such as:
public boolean mTurn = true;



You would be better of having a getter method to get the value of the variable, such as:
public boolean getTurn()
{
    return mTurn;
}



Then when you would do something like this:
if(player1.mTurn()==true)


Was This Post Helpful? 0
  • +
  • -

#6 iamfreshfish   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 11-September 09

Re: Question regarding classes/objects and static methods

Posted 01 August 2010 - 12:37 PM

Yup, I'm re-writing the whole thing now and am using getters/setters to clean it up

What I think I got from your last post...is that I was creating the player objects from the game class...but trying to access the objects from the GUI class.

Now I'm going to instantiate the player objects from the GUI

Does that make sense?
Was This Post Helpful? 0
  • +
  • -

#7 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Question regarding classes/objects and static methods

Posted 01 August 2010 - 12:42 PM

View Postiamfreshfish, on 01 August 2010 - 03:37 PM, said:

Yup, I'm re-writing the whole thing now and am using getters/setters to clean it up

What I think I got from your last post...is that I was creating the player objects from the game class...but trying to access the objects from the GUI class.

Now I'm going to instantiate the player objects from the GUI

Does that make sense?


Well yes you have to instantiate the Object in the class you want to use it in.
Was This Post Helpful? 0
  • +
  • -

#8 iamfreshfish   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 11-September 09

Re: Question regarding classes/objects and static methods

Posted 01 August 2010 - 03:14 PM

ok...i fixed the format, cleaned it up and here is the code:

StartGame CLASS
import java.util.*;
public class StartGame
{

    public static void main(String[] args) {
        
        GUI newGame = new GUI();
        newGame.startGUI();
        
        //while (player1.score < 100 && player2.score < 100) {
            
        //}
        
    }
   
    
    
    public static void endGame(String x) {
        System.out.println("Game has ended...winner is: " + x);
    }
    

}



PLAYER CLASS
import java.util.*;
import java.io.*;

public class Player {

    String name;
    boolean myTurn = true;
    int score = 0;
    int turnTotal = 0;
    int x = 0; //random roll

    public void roll() {
        x = 0;
        myTurn = true;
        turnTotal = 0;

        Random roll = new Random();
        x = roll.nextInt(6) + 1;
        if(x == 1) {
            System.out.println("Sorry, you rolled a 1 :(/>");
            turnTotal=0;
            myTurn=false;
        }
        else {
            turnTotal += x;
            System.out.println("you rolled a " + x + " and your turnTotal is " + turnTotal);

        }
        if(score >=100) StartGame.endGame(name);

    }

    public void hold() {
        score += turnTotal;
    }
    
    public int getScore() {
        return score;
    }
    
    public boolean getTurn() {
        return myTurn;
    }
    
    public int getRoll() {
        return x;
    }
    public void setTurnTrue(boolean x) {
        myTurn = x;
    }
}




GUI CODE
/****************************************************************/
/*                      GUI                              */
/*                                                              */
/****************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
 * Summary description for GUI
 *
 */
public class GUI extends JFrame
{
    // Variables declaration
    private JLabel p1Label;
    private JLabel p1ScoreLabel;
    private JLabel rollLabel;
    private JLabel p2Label;
    private JLabel p2ScoreLabel;
    private JLabel jLabel6;
    private JLabel turnTotalLabel;
    private JButton rollBut;
    private JButton holdBut;
    private JPanel contentPane;
    
    // End of variables declaration


    public GUI()
    {
        super();
        initializeComponent();
        //
        // TODO: Add any constructor code after initializeComponent call
        //

        this.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always regenerated
     * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
     * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
     * to retrieve your design properly in future, before revising this method.
     */
    private void initializeComponent()
    {
        p1Label = new JLabel();
        p1ScoreLabel = new JLabel();
        rollLabel = new JLabel();
        p2Label = new JLabel();
        p2ScoreLabel = new JLabel();
        jLabel6 = new JLabel();
        turnTotalLabel = new JLabel();
        rollBut = new JButton();
        holdBut = new JButton();
        contentPane = (JPanel)this.getContentPane();

        //
        // p1Label
        //
        p1Label.setText("PLayer1");
        //
        // p1ScoreLabel
        //
        p1ScoreLabel.setText("P1 Score");
        //
        // rollLabel
        //
        rollLabel.setText("currentRoll");
        //
        // p2Label
        //
        p2Label.setText("Player2");
        //
        // p2ScoreLabel
        //
        p2ScoreLabel.setText("[email protected] Score");
        //
        // jLabel6
        //
        jLabel6.setText("Turn Total:");
        //
        // turnTotalLabel
        //
        turnTotalLabel.setText("0");
        //
        // rollBut
        //
        rollBut.setText("ROLL");
        rollBut.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                rollBut_actionPerformed(e);
            }

        });
        //
        // holdBut
        //
        holdBut.setText("HOLD");
        holdBut.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                holdBut_actionPerformed(e);
            }

        });
        //
        // contentPane
        //
        contentPane.setLayout(null);
        addComponent(contentPane, p1Label, 146,49,60,18);
        addComponent(contentPane, p1ScoreLabel, 213,48,60,18);
        addComponent(contentPane, rollLabel, 154,159,60,18);
        addComponent(contentPane, p2Label, 148,86,60,18);
        addComponent(contentPane, p2ScoreLabel, 216,88,60,18);
        addComponent(contentPane, jLabel6, 138,129,60,18);
        addComponent(contentPane, turnTotalLabel, 204,128,60,18);
        addComponent(contentPane, rollBut, 79,219,83,28);
        addComponent(contentPane, holdBut, 210,219,83,28);
        //
        // PigGUI
        //
        this.setTitle("PigGUI - extends JFrame");
        this.setLocation(new Point(93, 65));
        this.setSize(new Dimension(390, 300));
    }

    /** Add Component Without a Layout Manager (Absolute Positioning) */
    private void addComponent(Container container,Component c,int x,int y,int width,int height)
    {
        c.setBounds(x,y,width,height);
        container.add(c);
    }

    //
    // TODO: Add any appropriate code in the following Event Handling Methods
    //
    private void rollBut_actionPerformed(ActionEvent e)
    {
        if(player1.getTurn() == true) {
            player1.roll();
        }
        else {
            player2.roll();
        }
    }

    private void holdBut_actionPerformed(ActionEvent e)
    {
        if(player1.myTurn == true) {
            player1.hold();
        }
        else {
            player2.hold();
        }
        // TODO: Add any handling code here

    }

    //
    // TODO: Add any method code to meet your needs in the following area
    //






























 

//============================= Testing ================================//
//=                                                                    =//
//= The following main method is just for testing this class you built.=//
//= After testing,you may simply delete it.                            =//
//======================================================================//
    public static void startGUI()
    {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        }
        catch (Exception ex)
        {
            System.out.println("Failed loading L&F: ");
            System.out.println(ex);
        }
        PigPlayer player1 = new PigPlayer(1);
        PigPlayer player2 = new PigPlayer(2);
        player1.setTurnTrue(true);
        player2.setTurnTrue(false);
        new GUI();
    }
//= End of Testing =


}



Still getting stuck with the player1 object not being found despite me instantiating the player 1 object from within the GUI class

This post has been edited by iamfreshfish: 01 August 2010 - 03:15 PM

Was This Post Helpful? 0
  • +
  • -

#9 japanir   User is offline

  • jaVanir
  • member icon

Reputation: 1014
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Question regarding classes/objects and static methods

Posted 01 August 2010 - 04:32 PM

Perhaps I miss it, but it seems that you don't declare any Player Objects in your code.
in your GUI class you have this code:
private void holdBut_actionPerformed(ActionEvent e)  

152     {  

153         if(player1.myTurn == true) {  

154             player1.hold();  

155         }  

156         else {  

157             player2.hold();  

158         }  

159         // TODO: Add any handling code here  

160    

161     }  

where you refer player1 and player2, but you never declare such variables in that class.
you should add a declaration for these members:
Player player1;
Player player2;

and then initiate them in the constructor:
player1 = new Player(/*params..*/);
player2 = new Player(/*params..*/);


Also, in the test class you declare PigPlayer Object, But you didn't post the code.. did you declare such class?
remember, that unless you pass player1 and player2 (you declared in the test class) as parameters to the gui class, the GUI class will NOT recognize nor use them.
Was This Post Helpful? 0
  • +
  • -

#10 eZACKe   User is offline

  • Garbage Collector

Reputation: 120
  • View blog
  • Posts: 1,278
  • Joined: 01-June 09

Re: Question regarding classes/objects and static methods

Posted 01 August 2010 - 05:20 PM

View Postiamfreshfish, on 01 August 2010 - 06:14 PM, said:

Still getting stuck with the player1 object not being found despite me instantiating the player 1 object from within the GUI class


Is this what you mean by "instantiate the player1 object from within the GUI class"?

public static void startGUI()
    {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        }
        catch (Exception ex)
        {
            System.out.println("Failed loading L&F: ");
            System.out.println(ex);
        }
        PigPlayer player1 = new PigPlayer(1);
        PigPlayer player2 = new PigPlayer(2);
        player1.setTurnTrue(true);
        player2.setTurnTrue(false);
        new GUI();
    }



That's the only place I see you make a player1 Object, but that's of type PigPlayer. Even if it were of type Player, it wouldn't get the job done because as far as I'm concerned, this is not your "GUI Class". This Class is your driver. A driver is a class in which the program gets run.

Your GUI Class is the one called "GUI". You need to make Player Objects within that class as well or you will not be able to use Player methods.

If you just add some Player objects such as
Player player1 = new Player();
Player player2 = new Player();


then it should work.

Post back when you have given that a try.

This post has been edited by eZACKe: 01 August 2010 - 05:22 PM

Was This Post Helpful? 0
  • +
  • -

#11 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Question regarding classes/objects and static methods

Posted 01 August 2010 - 06:35 PM

Every class (in most of the cases) should have only ONE static method wich is
public static void main(String[] args)
that is used for unit testing

The main class that runn the whole application should have a static void main() method which will have a few (bettween 2 to 10 lines)
Was This Post Helpful? 2
  • +
  • -

#12 YasuoDancez   User is offline

  • D.I.C Head

Reputation: 20
  • View blog
  • Posts: 135
  • Joined: 30-September 09

Re: Question regarding classes/objects and static methods

Posted 02 August 2010 - 12:08 AM

View Postpbl, on 01 August 2010 - 05:35 PM, said:

Every class (in most of the cases) should have only ONE static method wich is
public static void main(String[] args)
that is used for unit testing

The main class that runn the whole application should have a static void main() method which will have a few (bettween 2 to 10 lines)

What about constants?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1