Java-Gaming.org    
Featured games (91)
games approved by the League of Dukes
Games in Showcase (579)
games submitted by our members
Games in WIP (500)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  While loop help  (Read 1431 times)
0 Members and 1 Guest are viewing this topic.
Offline Nicky-G-

Senior Newbie





« Posted 2012-08-14 02:54:47 »

Hey everyone, I'm trying to make a simple rock, paper, scissors game using JButtons and a simple random AI. I believe I have everything in order but the order of execution in my main. I'm trying to display the games options, wait for the user to select an option, next have the computer randomly select an option, then have the game compare the two choices then see who has won and display a score on the top of the window.

I think I need to tackle this problem with a nested while loops. I think I need to create a Boolean for my first while loop so that the program runs normally and then have my second while look wait for input from the user to execute the rest of the code. I've been stumped for some days so I thought I ask for help. If someone could point me the right direction I would be very appreciative!

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  
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;


public class GamePanel implements ActionListener{
   
   static int playersco = 0;
   static int compsco = 0;
   
   static int player = 0;
   static int comp;
   String playerroc, playersis, playerpap ;
   static String compprint, comproc, comppap, compsis;
   JButton roc, pap, sis;
   JPanel selectpanel, gamtex, compout;
   static JLabel playerscore;
   JLabel compscore;
   JLabel compchoice;
   
   public JPanel ContentPane(){
     
      JPanel masterPanel = new JPanel();
      masterPanel.setLayout(null);
     
      gamtex = new JPanel();
      gamtex.setLayout(null);
      gamtex.setLocation(100, 10);
      gamtex.setSize(155,20);
      gamtex.setBackground(Color.yellow);
      masterPanel.add(gamtex);
     
      playerscore = new JLabel(""+ playersco +" Player");
      playerscore.setLocation(0,0);
      playerscore.setSize(90,20);
      playerscore.setHorizontalAlignment(0);
      gamtex.add(playerscore);
     
      compscore = new JLabel(""+compsco+" Computer");
      compscore.setLocation(20,0);
      compscore.setSize(190,20);
      compscore.setHorizontalAlignment(0);
      gamtex.add(compscore);
     
      compout = new JPanel();
      compout.setLayout(null);
      compout.setLocation(130,35);
      compout.setSize(110,100);
      masterPanel.add(compout);
      //compout.setBackground(Color.DARK_GRAY);
     
      compchoice = new JLabel(compprint);
      compchoice.setLocation(0,0);
      compchoice.setSize(85,20);
      compout.add(compchoice);
     
      selectpanel = new JPanel();
      selectpanel.setLayout(null);
      selectpanel.setLocation(0,15);
      selectpanel.setSize(100,190);
      //selectpanel.setBackground(Color.green);
     masterPanel.add(selectpanel);
     
      roc = new JButton("Rock");
      roc.setLocation(10,5);
      roc.setSize(80,30);
      roc.addActionListener(this);
      selectpanel.add(roc);
     
      pap = new JButton("Paper");
      pap.setLocation(10,45);
      pap.setSize(80,30);
      pap.addActionListener(this);
      selectpanel.add(pap);
     
      sis = new JButton("Sissors");
      sis.setLocation(10,85);
      sis.setSize(80,30);
      sis.addActionListener(this);
      selectpanel.add(sis);
     
      masterPanel.setOpaque(true);
      return masterPanel;
   }
   
   public void actionPerformed(ActionEvent e){
     
      if(e.getSource() == roc ){
         
         player = 1;
         
      }else if(e.getSource() == pap){
     
         player = 2;
         
      }else if(e.getSource() == sis){
         
         player = 3;
         
      }
     
   
   }
   
   
   public static  void comprandom(){
     
      Random randomGenerator = new Random();
       int randomInt = randomGenerator.nextInt(3);
       if(randomInt == 1){
         
          comp = 4;
          compprint = "Sissors!";
         
       }else if(randomInt == 2){
         
          comp = 5 ;
          compprint = "Rock!";
         
       }else
       {
          comp = 6 ;
          compprint = "Paper!";
         
       }
   }
   

     
   public static  void gamebrain()
   {
      if(player == 1 && comp == 4 ){
         playersco = playersco +1;
         playerscore.setText(""+ playersco +" Player");
      }else if( player == 2 &&  comp == 5) {
         playersco = playersco +1;
         playerscore.setText(""+ playersco +" Player");
      }else if( player == 3 && comp == 6){
         playersco = playersco +1;
         playerscore.setText(""+ playersco +" Player");
      }else{compsco = compsco + 1;}
   }

   
   private static void showgame(){
     
      JFrame frame = new JFrame("Rock, Paper, Sissors");
     
      GamePanel show = new GamePanel();
      frame.setContentPane(show.ContentPane());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(280, 190);
      frame.setVisible(true);
     
   }
   
   public static void main(String[] args){
     
   while(){
       showgame();
       
       while(!(player == 0)){
             gamebrain();
               comprandom();
       }
             
   }
       
     
         
   
   }


}
Offline StumpyStrust
« Reply #1 - Posted 2012-08-14 04:22:42 »

Search game loops on this forum if you are more serious about making games.

If you are just using Swing/AWT, you can do all this with actionListeners and will not need a loop. Every time the user selects either roc, pap, or sis, do the AI stuff, compare the AIs choice with the player, and display who won. If you want more fancy animations or anything then you will need to look into the game loops.

Offline ReBirth
« Reply #2 - Posted 2012-08-14 04:25:56 »

Don't use while inside your main() method. Just simply call showGame(). Since human select first, put your comprandom() and gamebrain() in order inside actionPerformed(). That will make comp to pick after human clicks a button and process the comparison.

After all your game shouldn't run, am i right? 'player' is 0 since begin.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline jonjava
« Reply #3 - Posted 2012-08-14 04:56:57 »

http://www.java-gaming.org/topics/best-place-to-start-java2d-game/26165/msg/228281/view.html#msg228281

http://www.java-gaming.org/index.php?topic=24220.0

The "public static void main(String[] args)" method is only ever used to start an application. It is there because the java compiler always looks for it from where to begin execution of a program.

It only gets executed once, at the very start of the program.

What you should do is this:

1  
2  
3  
public static void main(String[] args){
   new GamePanel();
}


in general, "public static void main()" should be the ONLY static method in your program.

E.g your comprandom, gamebrain and showgame methods should all be NON-static. and your GamePanel class should handle the while loop.

E.g: inside GamePanel you could have a method like this:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
public void run() {
   while (isRunning) {
       gameBrain();
       comprandom();
       showGame();

       try {
            Thread.sleep(20);
       } catch (Excpetion e) {}
   }
}


And you could start this loop by calling it inside GamePanels constructor. A construcor is a method inside the class that has the same name as the class.

E.g:
1  
2  
3  
4  
public GamePanel() {
   isRunning = true;
   run();
}


Constructors are called automatically when an object of that class is created.

To create objects from a class, you use the "new" keyword (like we did in the main() method).

1  
2  
3  
public static void main(String[] args){
    new GamePanel();
}


[EDIT]: Try and keep away from static as much as possible! Arguably static things are completely useless and unnecessary - use them when you know what you're doing. For a thing like this, you should absolutely never EVER use static like this. Java is an object oriented language - use it as such :]

Offline sproingie
« Reply #4 - Posted 2012-08-14 05:17:57 »

Arguably static things are completely useless and unnecessary

I think a little API called LWJGL would beg to differ.

All categorical statements are false!   persecutioncomplex
Offline StumpyStrust
« Reply #5 - Posted 2012-08-14 07:55:58 »

Ehh static non-static if it works it works.

Offline jonjava
« Reply #6 - Posted 2012-08-14 10:28:15 »

Ehh static non-static if it works it works.
<a href="http://www.youtube.com/v/umDr0mPuyQc?version=3&amp;hl=en_US&amp;start=" target="_blank">http://www.youtube.com/v/umDr0mPuyQc?version=3&amp;hl=en_US&amp;start=</a>

Offline Roquen
« Reply #7 - Posted 2012-08-14 10:45:17 »

Self inconsistent statement are awesome.
Offline tom
« Reply #8 - Posted 2012-08-14 14:36:52 »

Static methods that do not produce side effects are fantastic!

Offline Nicky-G-

Senior Newbie





« Reply #9 - Posted 2012-08-14 16:10:47 »

Whoa, I never expected such detailed responses. Thank you guys for the clearly and well explained answers! But, what is this argument between non-static, static, and who cares stuff? I know Micheal Scott feels strongly against the whole it doesn't matter approach.

I reason why I choose to use statics everywhere was because Eclipse told me to do it  Cry
I actually had no idea why it wanted me to do it, but after listening to Eclipse's suggestions my program would run without any problems so I thought I was doing good. I guess I was super wrong.

The reason why I made player == 0, ReBirth, was so that the game would start the player off with nothing and then as soon as the player chose something it would change it's value, then the game would compare that value against the computers randomized value. But, nope that isn't true. Thanks for pointing that out, because I know it would of caused a headache later.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline ReBirth
« Reply #10 - Posted 2012-08-14 16:24:37 »

You can set player to 0 when the result of current match popped.

Offline sproingie
« Reply #11 - Posted 2012-08-14 16:34:21 »

Eclipse didn't tell you to make everything static.  You tried calling non-static methods from a static context, and the compiler complained.  So the "obvious" fix was just to make everything static, rather than create a non-static context, i.e. instantiate an object.

Every time I see yet another person say "Eclipse made me do X" or "I put this in and Eclipse wouldn't take it", I become more convinced that newbies simply shouldn't ever be taught with IDEs.  It's not the IDE's fault, but it certainly isn't helping anyone learn.
Offline coltonoscopy

Junior Member


Medals: 2



« Reply #12 - Posted 2012-08-14 17:04:01 »

Eclipse didn't tell you to make everything static.  You tried calling non-static methods from a static context, and the compiler complained.  So the "obvious" fix was just to make everything static, rather than create a non-static context, i.e. instantiate an object.

Every time I see yet another person say "Eclipse made me do X" or "I put this in and Eclipse wouldn't take it", I become more convinced that newbies simply shouldn't ever be taught with IDEs.  It's not the IDE's fault, but it certainly isn't helping anyone learn.

I agree. Having built a significant amount of my game's ancestral engine code with GCC and the command prompt, I can say that taught me a lot about spotting bugs and figuring out the right thing to do without an IDE's guidance. Now I just abuse the crap out of using NetBeans Cheesy

Colton

Straight flippin.
Offline StumpyStrust
« Reply #13 - Posted 2012-08-14 17:07:49 »

I leaned how to code java with notepad first then I jumped up to notepad++ I was suck a boss. I actually had this guy in my data structures class that was wondering why all his stuff sometimes had to have static in everything and face palmed. He ended up getting a higher grade.  Angry

I am not saying static does not matter as it does obviously. Its just that there are many places where use can use it without causing any issues. If I am coding something that will be used by others and needs re-usability, I will do everything properly. For me it seems that when you want really good clean documentation, code, and readability, then you start dropping all the short cuts and hackyness.

Offline coltonoscopy

Junior Member


Medals: 2



« Reply #14 - Posted 2012-08-14 17:12:43 »

I leaned how to code java with notepad first then I jumped up to notepad++ I was suck a boss. I actually had this guy in my data structures class that was wondering why all his stuff sometimes had to have static in everything and face palmed. He ended up getting a higher grade.  Angry

I am not saying static does not matter as it does obviously. Its just that there are many places where use can use it without causing any issues. If I am coding something that will be used by others and needs re-usability, I will do everything properly. For me it seems that when you want really good clean documentation, code, and readability, then you start dropping all the short cuts and hackyness.

Indeed. I'd like to think there's a time and a place to use static methods and when not to use them, even if you can get away with either more or less of the time. Currently, my engine has a few static methods, but 99% of the whole thing is non-static. A couple examples I have are a few pixel map to image functions, as well as functions between two of my procedural generators that allow them to work together without needing to instantiate both of them. Aside from that, we ain't havin none of that static Cheesy

By the way, I do love Notepad++.... that's what I was coding in for a long while before I jumped on the NetBeans bandwagon.

Straight flippin.
Offline jonjava
« Reply #15 - Posted 2012-08-14 17:34:12 »

I reason why I choose to use statics everywhere was because Eclipse told me to do it  Cry
I actually had no idea why it wanted me to do it, but after listening to Eclipse's suggestions my program would run without any problems so I thought I was doing good. I guess I was super wrong.

As sproingie said, it's because you tried to use non-static methods in a static contest.

WTF does this mean, you say? It simply means that you tried calling non-static methods inside a static method. (non-static methods live outside objects while normal methods live inside objects.)

HOW Did I end up doing that, you say? Because a java program is started from the "public static void main()" method, you thought you'd put your game logic and loops in there - this is a big nono. Only use the "public static void main()' to start off something (I.e, create an object) - it should have NOTHING to do with the actual program itself!

You could also have a "start()" method in your GamePanel class to start it off instead of it starting itself when it is created (through the constructor). To call methods inside objects you simply append a . at the end of their name + the method you want to call.

E.g:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
class GamePanel {
   boolean isRunning = false;

   public void start() {
      isRunning = true;
      run();
   }

   public void run() {
      while (isRunning) {
         // Do Game logic
     }
   }
}


1  
2  
3  
4  
5  
6  
7  
8  
9  
public static void main(String[] args) {
   /* the public static void main() method doesn't need to be inside the GamePanel class. */
   
   // Create object
  GamePanel myObject = new GamePanel();
 
   // Set it off
  myObject.start();
}

Offline sproingie
« Reply #16 - Posted 2012-08-14 17:47:49 »

One thing I like about Scala ... no static contexts.  Main is a singleton object that extends App.

1  
2  
3  
object Hello extends App {
   println("Hello world")
}

Offline Nicky-G-

Senior Newbie





« Reply #17 - Posted 2012-08-15 19:31:31 »

Thanks everyone for the input. I was able to get my game running the way that I want it to and I took out all of the statics that shouldn't of been, but I'm still having a problem with my loop. My loop right now is empty, as I implemented all of the actions of the game into my ActionPerformed method. What I would like to know is can I get my game running through a Loop? I ready the tutorials and played around and just got things going in infinite loops.

Also, I'm planning to add some very, very simple graphics to the game. If I can't use my current loop for my game logic and updates can I use this loop for the graphics?

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  
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;


public class GamePanel implements ActionListener{
   private boolean isRunning = false;
   int playersco = 0;
   int compsco = 0;
   
   int player;
   int comp;
   String playerroc, playersis, playerpap ;
   String compprint, comproc, comppap, compsis;
   JButton roc, pap, sis;
   JPanel selectpanel, gamtex, compout;
   JLabel playerscore;
   JLabel compscore;
   JLabel compchoice;
   
   public JPanel ContentPane(){
     
      JPanel masterPanel = new JPanel();
      masterPanel.setLayout(null);
     
      gamtex = new JPanel();
      gamtex.setLayout(null);
      gamtex.setLocation(100, 10);
      gamtex.setSize(155,20);
      gamtex.setBackground(Color.yellow);
      masterPanel.add(gamtex);
     
      playerscore = new JLabel(""+ playersco +" Player");
      playerscore.setLocation(0,0);
      playerscore.setSize(90,20);
      playerscore.setHorizontalAlignment(0);
      gamtex.add(playerscore);
     
      compscore = new JLabel(""+compsco+" Computer");
      compscore.setLocation(20,0);
      compscore.setSize(190,20);
      compscore.setHorizontalAlignment(0);
      gamtex.add(compscore);
     
      compout = new JPanel();
      compout.setLayout(null);
      compout.setLocation(130,35);
      compout.setSize(110,100);
      masterPanel.add(compout);
      //compout.setBackground(Color.DARK_GRAY);
     
      compchoice = new JLabel(compprint);
      compchoice.setLocation(0,0);
      compchoice.setSize(85,20);
      compout.add(compchoice);
     
      selectpanel = new JPanel();
      selectpanel.setLayout(null);
      selectpanel.setLocation(0,15);
      selectpanel.setSize(100,190);
      //selectpanel.setBackground(Color.green);
     masterPanel.add(selectpanel);
     
      roc = new JButton("Rock");
      roc.setLocation(10,5);
      roc.setSize(80,30);
      roc.addActionListener(this);
      selectpanel.add(roc);
     
      pap = new JButton("Paper");
      pap.setLocation(10,45);
      pap.setSize(80,30);
      pap.addActionListener(this);
      selectpanel.add(pap);
     
      sis = new JButton("Sissors");
      sis.setLocation(10,85);
      sis.setSize(80,30);
      sis.addActionListener(this);
      selectpanel.add(sis);
     
      masterPanel.setOpaque(true);
      return masterPanel;
   

   
   }
   

   
   public void actionPerformed(ActionEvent e){
     
      if(e.getSource() == roc ){
         
         player = 1;
         
      }else if(e.getSource() == pap){
     
         player = 2;
         
      }else if(e.getSource() == sis){
         
         player = 3;
         
      }
     
      comprandom();
      gamebrain();
     
   }
   
   
   public void comprandom(){
     
      Random randomGenerator = new Random();
       int randomInt = randomGenerator.nextInt(3);
       if(randomInt == 1){
         
          comp = 4;
          compchoice.setText("Sicssors!");
         
       }else if(randomInt == 2){
         
          comp = 5 ;
          compchoice.setText("Rock!");
         
       }else
       {
          comp = 6 ;
         compchoice.setText("Paper!");
      }
   }
   

     
   public void gamebrain()
   {
      if((player == 1 && comp == 4) ||( player == 3 && comp == 6)||( player == 2 &&  comp ==5 )){
         playersco = playersco +1;
         playerscore.setText(""+ playersco +" Player");
     
      }else if( (player == 1 && comp == 5) ||(player == 2 && comp == 6) ||(player == 3 && comp == 4) ){
     
         playerscore.setText(""+ playersco +" Player");
      }
     
      else{
         compscore.setText(""+ compsco +" Computer");
         compsco = compsco + 1;}
   }

   
   private void showgame(){
     
      JFrame frame = new JFrame("Rock, Paper, Scissors");
      frame.setContentPane(ContentPane());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(280, 190);
      frame.setVisible(true);
     
   }
   
   public void run() {
   
     
      showgame();
      while(isRunning){
   
         
         
         
         
      try{
         Thread.sleep(20);
           
         }catch(Exception e){}
   }
   }
   
   public GamePanel(){
      isRunning = true;
      run();
   }
   public static void main(String[] args){

      new GamePanel();
       }
             
   }
       


Ok, time for me to get back to messin' around!
Offline philfrei
« Reply #18 - Posted 2012-08-15 22:57:48 »

If all of the game play visuals are in response to GUI events, then having the redraw of your screen come about due to calls to actionPerformed() could be fine. No game loop is needed, though one might be used.

If you want additional animation, then you will need some sort of game loop operating concurrently. The game loop will have to do its standard thing of updating the animation, then rendering it. If the animation is in response to a change in game state (in other words, changes that occur in your actionPerformed() method), then there is a technique commonly used to obtain the needed information.

1) When an actionPerformed() executes, update variables that hold the game state.

2) In the game loop, in the update part, consult these game state variables and then decide what to do.

It is common to mark variables that are consulted from concurrent threads (as you will have in the above scenario) with the keyword volatile. This helps ensure that all threads always see the most current values in these variables.

"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
Pages: [1]
  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 (37 views)
2014-04-15 18:08:23

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

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

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

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

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

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

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

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

CJLetsGame (200 views)
2014-04-01 02:16:10
List of Learning Resources
by SHC
2014-04-18 03:17:39

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
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!