In that tutorial, you are going to discover how to create a Slot Machine for Android with Android Studio. A Slot Machine, also known as one-armed bandit, is a casino gambling machine with three or more reels which spin when a button is pushed. Our Slot Machine will have three reels. Note that you can also enjoy this tutorial in video on YouTube :

 

Our Slot Machine will have three reels which will display the following fruits’ images :

 

To start, we write the code of the layout of our Slot Machine. The layout consists to three images for each reel, a button to start to spin the reels and a TextView which will be useful to display a message to the user like : You win the big prize !!!


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/activity_main"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.ssaurel.slotmachine.MainActivity"
 android:background="#FFFFFF">

 <LinearLayout
  android:id="@+id/imgs"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:layout_centerHorizontal="true">

  <ImageView
   android:id="@+id/img1"
   android:layout_width="100dp"
   android:layout_height="100dp"
   android:layout_marginTop="50dp"
   android:src="@drawable/slot5"/>

  <ImageView
   android:id="@+id/img2"
   android:layout_width="100dp"
   android:layout_height="100dp"
   android:layout_marginTop="50dp"
   android:layout_marginLeft="15dp"
   android:layout_marginRight="15dp"
   android:src="@drawable/slot5"/>

  <ImageView
   android:id="@+id/img3"
   android:layout_width="100dp"
   android:layout_height="100dp"
   android:layout_marginTop="50dp"
   android:src="@drawable/slot5"/>

 </LinearLayout>

 <TextView
  android:id="@+id/msg"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginTop="50dp"
  android:layout_below="@id/imgs"
  android:layout_centerHorizontal="true"/>

 <Button
  android:id="@+id/btn"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Start"
  android:layout_marginTop="50dp"
  android:layout_below="@id/msg"
  android:layout_centerHorizontal="true"/>

</RelativeLayout>

Now, we are going to create the logic of our Slot Machine. The logic will be implemented in a Wheel object. To animate the reels, our Wheel class will extends the Thread from the Android SDK.

Thus, each wheel will be animated in a dedicated thread. We define a WheelListener interface to let the main activity to be notified when an image changes for the wheel.

The images which will be displayed by the wheel are defined in a static imgs array. The currentIndex property will let us to know the current image displayed by the wheel. The frameDuration property will be used to define the duration of a frame for the wheel. A frame is the time the wheel keep the same image. Finally, the startIn property will lets us to start the wheels in a delay defined in the constructor. Thus, each wheel could start at a different moment chosen randomly.

In the run method of our Wheel object, we make a pause a startIn milliseconds. The, we enter in a loop which will be active until the isStarted property be false. In the loop, we change the current image when a frame duration is passed. When we have displayed all the images, we return to the first image of the array.

When a new image is displayed, we notify the WheelListener object which has subscribed to the Wheel by calling the newImage method. That gives us the following code for the Wheel :


public class Wheel extends Thread {

 interface WheelListener {
  void newImage(int img);
 }

 private static int[] imgs = {R.drawable.slot1, R.drawable.slot2, R.drawable.slot3, R.drawable.slot4,
    R.drawable.slot5, R.drawable.slot6};
 public int currentIndex;
 private WheelListener wheelListener;
 private long frameDuration;
 private long startIn;
 private boolean isStarted;

 public Wheel(WheelListener wheelListener, long frameDuration, long startIn) {
   this.wheelListener = wheelListener;
   this.frameDuration = frameDuration;
   this.startIn = startIn;
   currentIndex = 0;
   isStarted = true;
 }

 public void nextImg() {
   currentIndex++;

   if (currentIndex == imgs.length) {
     currentIndex = 0;
   }
 }

 @Override
 public void run() {
   try {
     Thread.sleep(startIn);
   } catch (InterruptedException e) {
   }

   while(isStarted) {
     try {
       Thread.sleep(frameDuration);
     } catch (InterruptedException e) {
     }

     nextImg();

    if (wheelListener != null) {
      wheelListener.newImage(imgs[currentIndex]);
    }
   }
 }

 public void stopWheel() {
   isStarted = false;
 }
}

Last step for our Slot Machine Application is to write the Java code of the Main Activity. We declare three Wheel objects. One for each reel of our Slot Machine.

We create a static randomLong method to return a random long value between lower and upper values passed in parameters.

In the onCreate method we set an OnClickListener object on the button used to launch or stop the Slot Machine. We wheck the state of the Slot Machine stored in the isStarted boolean property. If the Slot Machine is started, we stop the three wheels by calling their stopWheel method. Then, we check the current image displayed to display the message to the user. If the three images are the same, the user wins the big prize !

If the Slot Machine is not started, we create the three wheels. For each wheel, we define a WheelListener interface implementation in each we are going to update the image displayed when the nextImg method is called. Like the wheels are executed in a dedicated thread, we need to define that the update of the User Interface will be made inside the UI Thread.

Finally, we start the wheels at a different moment by using the randomLong method. The code of the Main Activity will be like that :


public class MainActivity extends AppCompatActivity {

 private TextView msg;
 private ImageView img1, img2, img3;
 private Wheel wheel1, wheel2, wheel3;
 private Button btn;
 private boolean isStarted;

 public static final Random RANDOM = new Random();

 public static long randomLong(long lower, long upper) {
   return lower + (long) (RANDOM.nextDouble() * (upper - lower));
 }

 @Override
 protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   img1 = (ImageView) findViewById(R.id.img1);
   img2 = (ImageView) findViewById(R.id.img2);
   img3 = (ImageView) findViewById(R.id.img3);
   btn = (Button) findViewById(R.id.btn);
   msg = (TextView) findViewById(R.id.msg);

   btn.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View view) {
     if (isStarted) {
       wheel1.stopWheel();
       wheel2.stopWheel();
       wheel3.stopWheel();

       if (wheel1.currentIndex == wheel2.currentIndex && wheel2.currentIndex == wheel3.currentIndex) {
         msg.setText("You win the big prize");
       } else if (wheel1.currentIndex == wheel2.currentIndex || wheel2.currentIndex == wheel3.currentIndex
         || wheel1.currentIndex == wheel3.currentIndex) {
         msg.setText("Little Prize");
       } else {
         msg.setText("You lose");
       }

       btn.setText("Start");
       isStarted = false;

     } else {

       wheel1 = new Wheel(new Wheel.WheelListener() {
         @Override
         public void newImage(final int img) {
           runOnUiThread(new Runnable() {
             @Override
             public void run() {
               img1.setImageResource(img);
             }
           });
         }
       }, 200, randomLong(0, 200));

       wheel1.start();

       wheel2 = new Wheel(new Wheel.WheelListener() {
         @Override
         public void newImage(final int img) {
           runOnUiThread(new Runnable() {
             @Override
             public void run() {
               img2.setImageResource(img);
             }
           });
         }
       }, 200, randomLong(150, 400));

       wheel2.start();

       wheel3 = new Wheel(new Wheel.WheelListener() {
         @Override
         public void newImage(final int img) {
           runOnUiThread(new Runnable() {
             @Override
             public void run() {
               img3.setImageResource(img);
             }
           });
         }
       }, 200, randomLong(150, 400));

       wheel3.start();

       btn.setText("Stop");
       msg.setText("");
       isStarted = true;
     }
   }
  });
 }
}

You can enjoy your new Slot Machine Application for Android. Run your application and you should have the following screen on your Android device :