|
Lab3e Copy, paste and run this program - It does not
do anything yet.
1. Random numbers are numbers that the computer makes up for us. Most
games have random things. 2. We need to create an object for the random number. This is needed
only once in a program. Random rd
= new Random(); /// new line Please read this lesson. rd.nextInt(x) is the command to
generate a random number between 0 and (x -
1). 4. Inside the actionPerformed method, inside the conditional for b1 add these 2 lines
Now try your program - click many times - you will see the number change
| |||||
|
Fancy changes We can make the program change based on the random number using color. 1. Try this example. Add this conditional BEFORE the setText line
Try it - When/why does the background of the JTextField change as you are clicking the JButton? 2. Try this instead - paste it over the if..else we just added - now you get one color for even numbers and one color for odd numbers
Try it - I like this one better. Use whichever one you like.
| |||||
|
Creating a little game 1. Add these lines where we create objects
2. Add these to the end of the container.add section
3. compile and run - you see the new JButton and the new JTextField but
the button does not work yet
4. It would be nice to let the program tell us who wins.
5. It would be nice to keep track of how many times you beat the
computer.
Add these in the appropriate locations.
L3 = new JLabel(""); b. Add it to the container container.add(L3); 6. Add these inside the getSource == b2. Be very careful, because they go in different places. This goes before the if(a > b) conditional total = total+1; This goes inside the braces of if(a > b) conditional wins = wins+1; This goes after the nest if..elses L3.setText(total+" games you win "+wins+" times"); Try the game now. there are still some flaws that we need to fix. Can you find them? | |||||
|
Fixing flaws 1. We want to force the player to click their button first so we turn
off b2 until b1 is clicked. 2. Before the end brace of the conditional getSource ==
b1 add these lines 3. Before the end brace of the conditional getSource == b2
add these lines Try it now - the player is forced to click JButtons in a certain
order. | |||||
|
Making game more friendly At present, to restart the game, you must quit and then run it again. We are going to add a "reset score" JButton 1. Add b3 to your JButton declarations Compile and run. You should see the reset JButton but it does nothing yet. Now comes the logic part. What do we want to reset? Add this inside the actionPerfomed method at the end.
Try the program now. it should be pretty good. | |||||
|
Assignment save Lab3e1 as Lab3e2 - 60 points. Colorize, add fonts and icons and make it look good.
Lab3e3 40points Instead a single number, we are going to roll dice. There are some changes needed 1. Random numbers are now 1 ... 6 Here are some pics of my sample - I did not use any colors, fonts or icons. We are going use this Lab again.
|