Slot machine using Java programming language
In this post I will explain how to program a Slot Machine using Java programming language from scratch and the Swing graphic libraries. The Netbeans development environment is used for the project.
Function Math.random
This simple program uses the function (int) (Math.random () * 9) + 1; to create random numbers between 1 and 9.
int slot1 = (int) (Math.random() * 9) + 1; int slot2 = (int) (Math.random() * 9) + 1; int slot3 = (int) (Math.random() * 9) + 1;
The JOptionPane Object
I use a JOptionPane object to display the desired results or to allow the user to choose an option.
JOptionPane.showMessageDialog(this, "You win!! 15 Coins");
With the following instruction that allows the user to choose between the options given by the JOptionPanel object.
int n = JOptionPane.showConfirmDialog(
this,
"Would you like play again?",
"Slot Machine",
JOptionPane.YES_NO_OPTION);
The jackpot
The jackpot is 7 (30 Coins) in a row, then 9 (20 Coins) after 5 (15 Coins), you will also earn a bonus when you get any number in a row.
https://youtu.be/wgL6UNzAdmA
package SlotMachine;
import javax.swing.JOptionPane;
/**
*
* @author Menta
*/
public class Frame extends javax.swing.JFrame {
int coins = 10;
/**
* Creates new form Frame
*/
public Frame() {
initComponents();
}
private void buttonPlayMouseClicked(java.awt.event.MouseEvent evt) {
coins -= 1;
int slot1 = (int) (Math.random() * 9) + 1;
int slot2 = (int) (Math.random() * 9) + 1;
int slot3 = (int) (Math.random() * 9) + 1;
labelSlot1.setText(String.valueOf(slot1));
labelSlot2.setText(String.valueOf(slot2));
labelSlot3.setText(String.valueOf(slot3));
if (slot1 == slot2 && slot2 == slot3) {
switch (slot1) {
case 5:
coins += 15;
JOptionPane.showMessageDialog(this, "You win!! 15 Coins");
break;
case 7:
coins += 30;
JOptionPane.showMessageDialog(this, "You win!! 30 Coins");
break;
case 9:
coins += 20;
JOptionPane.showMessageDialog(this, "You win!! 20 Coins");
break;
default:
coins += slot1;
JOptionPane.showMessageDialog(this, "You win!! " + slot1 + " Coins");
}
}
labelCoin.setText("£" + String.valueOf(coins));
if (coins == 0) {
int n = JOptionPane.showConfirmDialog(
this,
"Would you like play again?",
"Slot Machine",
JOptionPane.YES_NO_OPTION);
if (n == 0) {
coins = 10;
labelCoin.setText("£" + String.valueOf(coins));
} else {
System.exit(0);
}
}
}
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frame().setVisible(true);
}
});
}



Publicar comentario