Java-Gaming.org    
Featured games (91)
games approved by the League of Dukes
Games in Showcase (576)
games submitted by our members
Games in WIP (497)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1] 2
  ignore  |  Print  
  Figuring out the Mouse Listener  (Read 2508 times)
0 Members and 1 Guest are viewing this topic.
Offline Majeh

Senior Newbie





« Posted 2011-04-26 00:13:53 »

I'm taking a java class and have to make a Black Jack game for the final and I wanted to implement a GUI for it. Only problem is I don't really know how to use the Mouse Listener. Or rather, I don't know how to get it to do what I want it to do. For now all I want to do is draw a string when I button is clicked or pressed. I can get it to print in the command line but it won't draw the string. I'm also going off of the experience I got from making a pong game for my midterm so I don't know if some of this stuff is needed for a game like Black Jack. Here's what I got to start off with if it helps you at all, any help is appreciated.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
public class BlackJack extends JPanel implements Runnable, KeyListener, MouseListener {

    private JButton button = new JButton("This is a JButton");
    boolean buttonClicked;


    public BlackJack() {
            JFrame frame = new JFrame("BlackJack");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new FlowLayout());
            frame.setSize(500,500);
            button.addMouseListener(this);
            frame.add(button);
            frame.setVisible(true);
            button.setVisible(true);


    }



    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        if(buttonClicked)
        {
            g.setColor(Color.BLACK);
            g.drawString("The button was clicked", 50,50);
        }
    }

    public void mouseClicked(MouseEvent e) {
       
        if(e.getSource().equals(button))
        {
            if(!buttonClicked)
                buttonClicked = true;
            else
                buttonClicked = false;

        }
       
    }

    public void start(){
        Thread th = new Thread (this);
        th.start ();
    }

    public void run(){

        while(true)
        {
            try
            {
                Thread.sleep (25);
            }
            catch (InterruptedException ex){}
        }
       
    }


I think that's all I need to put up for this. Anything else I have so far is just empty key and mouse listener methods.
Offline SimonH
« Reply #1 - Posted 2011-04-26 01:11:44 »

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
    public void run(){

        while(true)
        {
            repaint(); // <--- add this line
           try
            {
                Thread.sleep (25);
            }
            catch (InterruptedException ex){}
        }    
    }

That should solve your immediate problem, but if someone clicks and releases in less than 25ms (unlikely) then it won't work!

People make games and games make people
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #2 - Posted 2011-04-26 01:35:59 »

And you can replace these lines:
1  
2  
3  
4  
if(!buttonClicked)
    buttonClicked = true;
else
    buttonClicked = false;

with this 1 line:
1  
buttonClicked = !buttonClicked;

Grin

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Majeh

Senior Newbie





« Reply #3 - Posted 2011-04-26 07:37:40 »

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
    public void run(){

        while(true)
        {
            repaint(); // <--- add this line
           try
            {
                Thread.sleep (25);
            }
            catch (InterruptedException ex){}
        }    
    }

That should solve your immediate problem, but if someone clicks and releases in less than 25ms (unlikely) then it won't work!

Ah. I completely forgot about the repaint(), sadly that didn't fix it. After having the time to mess with it a bit I found that the paintcomponent isn't doing anything at all, and with the setLayout thing it sets the button in the center of the frame and can't really change it's location, and without the layout, the button takes up the whole panel. I thought about making the frame and everything in the main class like I did with my pong game and scrap the constructor but then I wouldn't be able to use the button in the Black Jack class. I'm kinda at a loss of what to do lol.
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #4 - Posted 2011-04-26 07:53:30 »

Does anything call the start() method? If nothing calls it, then your thread isn't initialized, therefore you have no loop.

Offline loom_weaver

JGO Coder


Medals: 17



« Reply #5 - Posted 2011-04-26 08:00:41 »

Assuming your BlackJack game is single player (i.e. not-networked) and uses minimal animation, I would suggest not using any threading at all and take out all references to Runnable, Thread, run(), etc.

This will:
a) simplify your program and remove a lot of potential problems that threading can cause with painting
b) allow you to focus on painting and get a better understanding on how Java passive rendering works
Offline Majeh

Senior Newbie





« Reply #6 - Posted 2011-04-26 08:49:22 »

Does anything call the start() method? If nothing calls it, then your thread isn't initialized, therefore you have no loop.
I had it in the main but I guess I forgot to include the main in my post.
I decided to start over with this class and see if that would make a difference but paintComponent still isn't doing anything. All I have for it is this.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
public class BlackJack extends JPanel implements KeyListener, MouseListener {

    private JButton button = new JButton("This is a JButton");
    boolean buttonClicked;

    public BlackJack()
    {
        JFrame frame = new JFrame("BlackJack");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setVisible(true);
        frame.setSize(500,500);
        frame.addKeyListener(this);
        frame.addMouseListener(this);
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        g.setColor(Color.BLACK);
        g.fillRect(1, 1, getWidth(), getHeight());
    }

    public void run()
    {
        while(true)
        {
            repaint();
            try{
                Thread.sleep(1000);
            }
            catch(InterruptedException e){}

        }
    }
}

public static void main(String[] args) {
    BlackJack game = new BlackJack();
    game.run();
}


At this point I'm just trying to get it to draw anything...I could just be being very stupid about this as I am tired from work and it's almost 1am. Maybe I'll figure it out in the morning or something.
Offline philfrei
« Reply #7 - Posted 2011-04-26 10:12:28 »

I think the JFrame should be the outermost container. I'd instantiate the JFrame in my BlackJack class, then "add" a BlackJackJPanel (separate class, subclassing JPanel) to the JFrame, and put my button in the subclassed JPanel. You could also probably just put the button in the "content pane" of the JFrame and skip the JPanel.

When a Button is clicked, it's "listener" will call a method called "actionPerformed()" which is where you could set the state variable that the paintComponent() method refers to when it executes. But be sure and actually call a repaint() if you want paintComponent() to run.

Here's the tutorial on ActionListenter:
http://download.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
If you get stuck just trying to get basic stuff to display, there's this demo:
http://download.oracle.com/javase/tutorial/uiswing/examples/components/FrameDemoProject/src/components/FrameDemo.javaThey add a blank label, which is kind of silly. You could use a similar command to load your JButton.

 

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline JL235

JGO Coder


Medals: 10



« Reply #8 - Posted 2011-04-26 11:12:20 »

Swing's events are not thread safe, this means your thread calling 'repaint' can potentially be run simultaneously as the code in your mouse and keyboard listeners. Further Swing can call repaint at any time, such as when a window is resized. So you will have times where repaint is simultaneously called twice (once by your thread and once by Swing)!

So I'd advise looking into using action listeners for storing all of your code, and don't use threads at all. You can move the 'repaint' call into your action listeners so it's always repainted when clicked. This would also be more efficient since your not constantly repainting.

You can build it your way (using threads), but to do it properly involves thread locking to ensure you can't have repaint called simultaneously twice (and other threading bugs).

Offline Riven
« League of Dukes »

JGO Overlord


Medals: 605
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #9 - Posted 2011-04-26 14:30:09 »

to ensure you can't have repaint called simultaneously twice (and other threading bugs).

Just pointing out that although repaint() is called from the 'wrong thread', the actual painting will occur on the EventDispatchThread, so there won't be 'other threading bugs' as a result of his code, just the problem of painting too often. sometimes.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Majeh

Senior Newbie





« Reply #10 - Posted 2011-04-28 01:32:32 »

Alright, so I've pretty much figured out what I need to know for the action listener, I think. I'm still having troubles with what I want to do with the gui part. I tried making the frame and everything in the BlackJack constructor but then the paint component wouldn't do anything. If I made the frame and everything in main the paint component works but I'm not quite sure how to get the action listener to work if I have to add stuff to the gui from main. I'm pretty much learning this on my own as this isn't really covered in the class at all.
Should I be going with this?

I'd instantiate the JFrame in my BlackJack class, then "add" a BlackJackJPanel (separate class, subclassing JPanel) to the JFrame, and put my button in the subclassed JPanel.

The subclassing JPanel would be the "extends JPanel" part, right? We're just getting into super/sub classes and whatnot so I'm not sure if I completely understand it yet. So, if I did this, I'd need to instantiate the blackjackpanel and add it to the frame in blackjack and I'd be able to use the button and actionlistener and all that? Would I need to put the paintcomponent in the blackjackpanel too? Or could I leave it in the blackjack class?
Offline philfrei
« Reply #11 - Posted 2011-04-28 02:05:14 »

Yes, "class BlackJackPanel extends JPanel" should work.

This is what I've done, but I am also a relative beginner, so hopefully some other folks will weigh in as well:

I have no paintComponent() method in the JFrame, but do have a paintComponent() in the JPanel (your BlackJackPanel in this case). Within my JPanel constructor, I do an "addMouseListener" & "addMouseMotionListener" and also I create a MenuBar and add ActionListeners to the menubar's JMenuItem objects. The ActionListeners are themselves created as inner classes. (But you could do it as an "anonymous" inner class. More terms to learn about. Oh joy!)

Something similar should work for a JButton instantiated and added to the BlackJackPanel. You can add an actionListener to your JButton.

Also, I do a "setSize" in the JFrame.

My 'in progress' puzzle game is Hexara, if you are curious. 'no sound' version of puzzle: http://www.hexara.com/gameNS.html (Discussion thread when I first presented the code is here:http://www.java-gaming.org/topics/hexara-work-in-progress/23676/view.html.)

For simply flipping cards, or displaying a message from a button, JPanels are fine. For more intense animation, a lot of folks get into using the Canvas, and there are some good tutorials from Oracle on that. But first things first.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #12 - Posted 2011-04-28 04:10:26 »

@philfrei
Just pointing out that JFrame doesn't even have a paintComponent(). That's only for JComponent and its subclasses Wink

Offline philfrei
« Reply #13 - Posted 2011-04-28 04:47:00 »

Doh! Thanks.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline Majeh

Senior Newbie





« Reply #14 - Posted 2011-04-28 08:44:34 »

Working a bit more with the action listener. In the blackJackPanel I have small menu bar set up and one of the options is to start a new black jack game. So clicking that would call the method in blackJack that starts running the game but I can't really do that cause I'd need to instantiate blackJack and doing that in blackJackPanel causes a stack overflow or something. I can easily just get it done by having the actionPerformed in blackJack do this but I was wondering if there was a way to do it from the panel class. Thanks for all your help guys, I really really appreciate it. Also, philfrei, your Hexara game looks pretty good. How long has it taken you to make that?
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #15 - Posted 2011-04-28 08:46:37 »

A stack overflow exception usually occurs due to infinite loops. Look over your code in your constructor and try pinpointing where an infinite loop might be started.

Offline Majeh

Senior Newbie





« Reply #16 - Posted 2011-04-28 09:03:44 »

I'm not too sure what would be causing an infinite loop in the constructor, maybe you can see it?
Here's what I got.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
public class BlackJackPanel extends JPanel implements ActionListener {

    BlackJack blackJack = new BlackJack();
    JButton button = new JButton("Button");
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("Stuff");
    JMenuItem menuStart = new JMenuItem("Start");
    JMenuItem menuExit = new JMenuItem("Exit");
    boolean buttonClicked;

    public BlackJackPanel(){
        button.addActionListener(this);
        menuStart.addActionListener(this);
        menuExit.addActionListener(this);
    }


    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.setColor(Color.blue);
        g.fillRect(1, 1, this.getWidth(), this.getHeight());
        g.setColor(Color.yellow);
        if(buttonClicked)
        {
            g.drawString("CATS a;kldsjf;lkadjfl;kadkj;fas", 50, 50);
        }

    }

    public void actionPerformed(ActionEvent e) {

        if(e.getSource().equals(button))
        {
            buttonClicked = !buttonClicked;
            repaint();
        }
        if(e.getSource().equals(menuStart))
        {

        }
        if(e.getSource().equals(menuExit))
            System.exit(0);
    }

}

public class BlackJack extends JPanel implements ActionListener, KeyListener, MouseListener {

    BlackJackPanel panel = new BlackJackPanel();
    private int credits;
    boolean validInput;
    Random myR = new Random();




    public BlackJack()
    {
        JFrame frame = new JFrame("BlackJack");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setSize(500,500);
        frame.add(panel);
        panel.add(panel.button);
        panel.menuBar.add(panel.menu);
        panel.menu.add(panel.menuStart);
        panel.menu.add(panel.menuExit);
        panel.menuStart.addActionListener(this);
        panel.menuExit.addActionListener(this);
        frame.setJMenuBar(panel.menuBar);
        frame.setVisible(true);

    }


    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource().equals(panel.menuStart))
        {
            run();
        }
    }
     
    public void run()
    {
        while(true)
        {

        }  
    }
Offline philfrei
« Reply #17 - Posted 2011-04-28 11:12:21 »

Yikes.

You don't have to do an "implements ActionListener". Also I meant to make BlackJack.java the main file. Maybe the easiest thing is to hack up an example of the "template" that I use, with some of your code fragments. There are some simplifications here that are not the best Java form. But maybe this will be an ok learning structure that you can build from.

Thanks for thumbs up on Hexara. I started it a little over a year ago as a learning project. Been working on it part time, and hardly at all lately. I'm working on a little "wav scratcher" app as a way of learning more about sound at the moment.
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class BlackJack
{
    public static void main(String[] args)
    {
        JFrame frame = new GameFrame();
        frame.setDefaultCloseOperation(
                JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

class GameFrame extends JFrame
{
    GameFrame()
    {
        setTitle("Black Jack Project");
        setSize(500, 500);        
        BlackJackPanel bjp = new BlackJackPanel();
        add(bjp);
    }
}    

class BlackJackPanel extends JPanel
{
    boolean buttonClicked;
    JButton button;
   
    BlackJackPanel()
    {
        button = new JButton("Button");
        add(button);
        button.addActionListener(new ButtonListener());
    }
   
    public class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent arg0)
        {
            buttonClicked = !buttonClicked;
            repaint();
        }
    }
   
    public void paintComponent(Graphics g)
    {
        g.clearRect(0, 0, 500, 500);
        if (buttonClicked)
        {
            g.drawString("CATS a;kldsjf;lkadjfl;kadkj;fas", 50, 50);
        }
    }
}

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline Majeh

Senior Newbie





« Reply #18 - Posted 2011-04-28 19:48:23 »

Ah, thank you so much! I was wondering how I set where the button shows up. I messed around with it a bit earlier but I was never able to change the location of the button when everything is first initialized. It always stays center aligned at the top. It seems that I can set the location of it any time after it's started but if I do something like resize the window goes back to being at the top and centered.
I was also thinking of adding a little casino music or something but I'm not too worried about that.
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #19 - Posted 2011-04-29 03:12:07 »

In your code, you never add the JMenuItem's to your JMenu Wink
Ah didn't see your BlackJack class Cheesy

Anyway, I don't see anything wrong in your code. Could you give us the stack trace of that StackOverflowException?

Offline Majeh

Senior Newbie





« Reply #20 - Posted 2011-04-29 19:12:16 »

I don't think I'm getting that exception anymore but I'm getting some other error or something but I don't remember what it is. I'll see if I can post it after I get back from class.
Offline Majeh

Senior Newbie





« Reply #21 - Posted 2011-05-12 01:57:10 »

Alright, so due to lack of time to work on this, I'm gonna be do the gui as a side project and I'm gonna do this through text. I'm having trouble figuring out how to go about adding values from the cards to get the player/computer's score. So here's what I have.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
public class BlackJack {

    Player player = new Player();
    Player dealer = new Player();
    Deck deck = new Deck();
    boolean valid;
    enum Status {WON, LOST, CONTINUE};
    Status gameStatus = Status.CONTINUE;

    public void run()
    {
        JOptionPane.showMessageDialog(null, "Welcome to the wonderful world of Black Jack!");

        String temp = JOptionPane.showInputDialog("How much do you wish to"
                    + " sacrifice to the BlackJack gods?");

        while(!valid)
        {
            if( Double.parseDouble(temp) > 0.0){
                valid = !valid;
                player.setCredits(Double.parseDouble(temp));
                System.out.println("Your credits: " + player.getCredits());
            }
            else
            {
                temp = JOptionPane.showInputDialog("Invalid, enter a positive"
                        + " number or q to exit");
                if(temp.equals("q"))
                    System.exit(0);
            }
        }

        while(gameStatus.equals(gameStatus.CONTINUE))
        {
            valid = !valid;
            temp = JOptionPane.showInputDialog("How much you wanna bet bro?");
            while(!valid)
            {
                if(Double.parseDouble(temp) > 0.0 &&
                        Double.parseDouble(temp) <= player.getCredits())
                {
                    valid = !valid;
                    player.setBet(Double.parseDouble(temp));
                    System.out.println("Betting: " + player.getBet());
                    player.setCredits(player.getCredits() - player.getBet());
                }
                else
                {
                    temp = JOptionPane.showInputDialog("Invalid or insufficient"
                            + " funds, enter a positive number");
                }

            }
            System.out.println("Dealing Cards...");
            deck.shuffle();
           
            player.playerCards.add(deck.dealCard());
            dealer.playerCards.add(deck.dealCard());
            player.playerCards.add(deck.dealCard());
            dealer.playerCards.add(deck.dealCard());

            System.out.printf("Dealer shows: %s\nYou have: %s\n",
                    dealer.displaySecondCard(), player.displayHand());

            System.out.println(player.getCardValue());



        }
    }
}

public class Deck {

    private Card[] deck;
    private int currentCard;
    String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven",
            "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
    private static final int NUMBER_OF_CARDS = 52;
    private static final Random myR = new Random();

    public Deck()
    {
       
        String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};

        deck = new Card[NUMBER_OF_CARDS];
        currentCard = 0;

        for (int count = 0; count < deck.length; count++)
            deck[count] = new Card(faces[count % 13], suits[count / 13]);
    }

    public void shuffle()
    {

        currentCard = 0;

        for(int first = 0; first < deck.length; first++)
        {
            int second = myR.nextInt(NUMBER_OF_CARDS);

            Card temp = deck[first];
            deck[first] = deck[second];
            deck[second] = temp;
        }

    }

   

    public Card dealCard()
    {

        if(currentCard < deck.length)
            return deck[currentCard++];
        else
            return null;
    }

}

public class Player extends Deck{

    private double bet;
    private double credits;
    private double insurance;
    boolean hasBlackJack, hasInsurance;
    public ArrayList< Card > playerCards = new ArrayList< Card >();

   
    public double getBet()
    {
        return bet;

    }

    public void setBet(double num)
    {
        bet = num;
    }

    public double getCredits()
    {
        return credits;
    }

    public void setCredits(double num)
    {
        credits = num;
    }

    public double getInsurance()
    {
        return insurance;
    }

    public void setInsurance(double num)
    {
        insurance = num;
    }

    public String displaySecondCard()
    {
        return String.format("%s", playerCards.get(1));
    }

    public String displayHand()
    {
        return String.format("%s,  %s", playerCards.get(0), playerCards.get(1));
    }


    public int getCardValue()
    {
        int pointValue = 0;
        for(int j = 0; j < 2; j++)
        {
            for(int i = 0; i < faces.length; i++)
            {
                if(faces[i].equals("Ace"))
                {
                    pointValue += 11;
                    break;
                }
                if(faces[i].equals("Two"))
                {
                    pointValue += 2;
                    break;
                }
                if(faces[i].equals("Three"))
                {
                    pointValue += 3;
                    break;
                }
                if(faces[i].equals("Four"))
                {
                    pointValue += 4;
                    break;
                }
                if(faces[i].equals("Five"))
                {
                    pointValue += 5;
                    break;
                }
                if(faces[i].equals("Six"))
                {
                    pointValue += 6;
                    break;
                }
                if(faces[i].equals("Seven"))
                {
                    pointValue += 7;
                    break;
                }
                if(faces[i].equals("Eight"))
                {
                    pointValue += 8;
                    break;
                }
                if(faces[i].equals("Nine"))
                {
                    pointValue += 9;
                    break;
                }
                else
                    pointValue += 10;

            }
        }
        return pointValue;
    }


I've been messing with it for around 3-4 hours and can't figure it out. Any help is appreciated.
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #22 - Posted 2011-05-12 02:53:34 »

Instead of looking through every line of code you have, you could tell us exactly what's not working correctly so we can find the problem easier. Wink

Offline Majeh

Senior Newbie





« Reply #23 - Posted 2011-05-12 04:17:41 »

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
 public int getCardValue()
    {
        int pointValue = 0;
        for(int j = 0; j < 2; j++)
        {
            for(int i = 0; i < faces.length; i++)
            {
                if(faces[i].equals("Ace"))
                {
                    pointValue += 11;
                    break;
                }
                if(faces[i].equals("Two"))
                {
                    pointValue += 2;
                    break;
                }
                if(faces[i].equals("Three"))
                {
                    pointValue += 3;
                    break;
                }
                if(faces[i].equals("Four"))
                {
                    pointValue += 4;
                    break;
                }
                if(faces[i].equals("Five"))
                {
                    pointValue += 5;
                    break;
                }
                if(faces[i].equals("Six"))
                {
                    pointValue += 6;
                    break;
                }
                if(faces[i].equals("Seven"))
                {
                    pointValue += 7;
                    break;
                }
                if(faces[i].equals("Eight"))
                {
                    pointValue += 8;
                    break;
                }
                if(faces[i].equals("Nine"))
                {
                    pointValue += 9;
                    break;
                }
                else
                    pointValue += 10;
 
            }
        }
        return pointValue;
    }


This is pretty much the part I'm trying to figure out. I was wanting to maybe set a value for the card in the card class, but I couldn't really get it working, so I tried doing this. But this just looks at the faces string array of the deck class and I want it to be looking at the cards dealt to the player. I tried using the array I'm using for the cards for the player doing playerCards.get(i).equals() but it wants an object and so I can't do that either.
Offline ReBirth
« Reply #24 - Posted 2011-05-12 04:26:52 »

hmm it's only me or everyone can't see posted code above?

Offline Majeh

Senior Newbie





« Reply #25 - Posted 2011-05-12 04:45:45 »

Should I try reposting it?
Offline philfrei
« Reply #26 - Posted 2011-05-12 06:34:00 »

I can see the code. But I don't see a Card class defined. I do see the use of a Card[]. So, I assume it must be around somewhere.

So, how do you assign text to the card? Why not assign a point value at the same time? I'd assume a card could easily have a private "instance variable" to hold the point value, as well as a public getter and setter for the same.

But there are a lot of other things that don't make sense to me. Why is there an outer loop with "j" in your hand point totaller? I see no references to "j" and don't understand why you would want to total up your points multiple times. Or do a multiplication, if you do.

More seriously, why does Player extend Deck? Usually with an "extends" you have what they refer to in Head First Java lessons as an "is a" relationship. A "player" generally isn't thought of as a particular case/example of a deck of cards. A player might hold some cards in a hand. Just saying.

"Greetings my friends! We are all interested in the future, for that is where you and I are going to spend the rest of our lives!" -- The Amazing Criswell
Offline ra4king

JGO Kernel


Medals: 322
Projects: 2
Exp: 4 years


I'm the King!


« Reply #27 - Posted 2011-05-12 12:51:10 »

Well playerCards.get(i) would return an object of Card. As philfrei noticed, you haven't shown us a Card class. The Card class could be useful to store the name and point value of each card. So you would be able to do:
1  
2  
3  
4  
int points = 0;
for(Card c : playerCards) {
    points += c.getValue();
}

Offline ReBirth
« Reply #28 - Posted 2011-05-12 13:40:09 »

Should I try reposting it?
Seems only me who can't see it so no need. maybe some problem here. All code after BlackJack class code are blank and I can't select anything. Not happen on other threads though.

Offline Majeh

Senior Newbie





« Reply #29 - Posted 2011-05-12 20:28:49 »

Oops, didn't realize I didn't put the Card class up.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
public class Card{

    private String face;
    private String suit;


    public Card(String cardFace, String cardSuit)
    {
        face = cardFace;
        suit = cardSuit;
    }


    @Override
    public String toString()
    {
        return face + " of " + suit;
    }
}


I was pretty tired when I was trying to work on this last night so that's why some parts look pretty nonsensical .
Pages: [1] 2
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

xsi3rr4x (12 views)
2014-04-15 18:08:23

BurntPizza (11 views)
2014-04-15 03:46:01

UprightPath (24 views)
2014-04-14 17:39:50

UprightPath (10 views)
2014-04-14 17:35:47

Porlus (27 views)
2014-04-14 15:48:38

tom_mai78101 (49 views)
2014-04-10 04:04:31

BurntPizza (108 views)
2014-04-08 23:06:04

tom_mai78101 (208 views)
2014-04-05 13:34:39

trollwarrior1 (176 views)
2014-04-04 12:06:45

CJLetsGame (182 views)
2014-04-01 02:16:10
List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:05:20
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!