Basic Slot Machine

This was a challenge topic during a course that I’ve been taking over on Bob Tabor’s page. I had a lot of fun with this even in it’s basic nature. It’s using a simple Web Form for a slot machine. Now the graphics aren’t as good as the slots in Vegas. That wasn’t the point of this exercise. Like is said earlier I’m a big fan of going back over past things I’ve learned to see if I missed anything. And to have some fun in this case.

In the past I’ve been making relying on using global variables in my programs. That was just a work around for me being lazy and not passing my variables and values from method to method and doing work on them. So seeing the need to fix this I made that a concentration on this challenge.

Take note right away that this is just a very simple form. The program structure is very simple with the helper methods being in a single Default.aspx and a single code behind file. I did a pretty good job of describing what’s going on and when in the code comments. So take a look. If you have any questions just let me know.. šŸ™‚

So the basic workings of the slot machine is once the page loads the player has $100 and can bet any amount they choose. As long as they aren’t betting more than what’s in their purse. You get winnings based on how many cherries show up or if you get all 7’s which is the jackpot. The program utilizes a single dimensional array that hold the slot machine reels and performs various logic to see what / if any winnings are supposed to occur. If any winnings then the purse amount is increased, any losses then the purse amount decreased, and the purse amount is constantly stored in the browsers ViewState.

Program Screenshot

Main Default.aspx Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BasicSlotMachine.Default" %>

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">

        <asp:Image ID="slotOneImage" runat="server" CssClass="auto-style1" Height="150px" Width="150px" />
        <asp:Image ID="slotTwoImage" runat="server" CssClass="auto-style1" Height="150px" Width="150px" />
        <asp:Image ID="slotThreeImage" runat="server" CssClass="auto-style1" Height="150px" Width="150px" />
        <br />
        <br />
        <asp:Label ID="yourBetLabel" runat="server" Font-Names="Arial" Text="Your Bet:"></asp:Label>
        <asp:TextBox ID="betAmountTextBox" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="pullLeverButton" runat="server" Font-Names="Arial" OnClick="leverPullButton_Click" Text="Pull The Lever!" />
        <br />
        <br />
        <asp:Label ID="resultLabel" runat="server" Font-Names="Arial"></asp:Label>
        <br />
        <br />
        <asp:Label ID="moneyLabel" runat="server" Font-Names="Arial"></asp:Label>
        <br />
        <br />
        <asp:Label ID="rulesLabel" runat="server" Font-Names="Arial"></asp:Label>
        <br />
        <br />
        <asp:Label ID="testLabel" runat="server"></asp:Label>


Default.aspx Code Behind Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BasicSlotMachine
    public partial class Default : System.Web.UI.Page
        // Random object that will be used throughout the project. Defined as a class variable for true randomness upon
        // program runtime.
        Random random = new Random();

        protected void Page_Load(object sender, EventArgs e)
            // Setting the text on the rules label.
            rulesLabel.Text = "1 Cherry - x2 Your Bet<br />2 Cherries - x3 Your Bet<br />3 Cherries - x4 Your Bet<br /><br />3 7's - Jackpot x100 Your Bet" +
                "<br /><br />HOWEVER<br /><br />If you even have one BAR you win nothing";

            if (!Page.IsPostBack)
                // Displaying the reels on program load. Simulting like you're walking up to a previously used slot machine.
                string[] reels = new string[] { spinReels(), spinReels(), spinReels() };

                // Setting the players initial purse amount to 100 dollars and saving to view state.
                ViewState.Add("PlayersMoney", 100);

                // Displaying the reel images on the screen for the first time.

                // Using a helper method to display the players initial purse amount.

        private string spinReels()
            // String array holding the names of all possible slot machine images.
            string[] reelImage = new string[] { "Lemon", "Seven", "Cherry", "Bar", "Diamond", "Watermellon", "Orange", "HorseShoe", "Plum", "Clover", "Bell", "Strawberry" };

            // Returning a randomly selected image from the array.
            return reelImage[random.Next(reelImage.GetLength(0))];

        private void displayImages(string[] reels)
            //Displaying each slot reel image from the array parameter.
            slotOneImage.ImageUrl = "~/SlotImages/" + reels[0] + ".png";
            slotTwoImage.ImageUrl = "~/SlotImages/" + reels[1] + ".png";
            slotThreeImage.ImageUrl = "~/SlotImages/" + reels[2] + ".png";

        // Helper method used to update the players purse amount label.
        private void displayPlayerPurse()
            // Pulling the players purse amount from view state and displaying it.
            moneyLabel.Text = String.Format("Players Money: {0:C2}", ViewState["PlayersMoney"]);

        protected void leverPullButton_Click(object sender, EventArgs e)
            // Variable declaration to hold the bet amount.
            double betAmount = checkBetAmount();

            // Getting the amount of money the player has.
            double playersMoney = double.Parse(ViewState["PlayersMoney"].ToString());

            // Checking to see if the players entered an invalid bet amount.
            if (betAmount == 0)
                resultLabel.Text = "Sorry you must enter a valid bet amount.";

            // Checking to see if the bet amount exceeds the money the player has.
            else if (betAmount > playersMoney)
                resultLabel.Text = "Sorry you can't bet that much.";

            // If the player doesn't overbet and has enough money proceed to play.

        private void playGame(double betAmount)
            // Passing the bet amount into the pull lever method to begin the game.
            double winnings = pullLever(betAmount);

            // Adjusting the players money amount based on a win or loss.
            adjustPlayersMoney(betAmount, winnings);

            //Display the players bet and winnings, if any, to the screen.
            displayResult(betAmount, winnings);

            // Displaying the players purse amount.

        private double checkBetAmount()
            // Variable to hold the parsed bet amount.
            double bet;

            // Trimming any spaces in the textbox entry.
            if (betAmountTextBox.Text.Trim().Length == 0)
                return 0;

            // Attempting to parse the textbox entry into a number.
            if (!double.TryParse(betAmountTextBox.Text, out bet))
                return 0;
                return bet;

        private double pullLever(double betAmount)
            // Array that will hold the images from the current spin.
            // This variable can be passed around to different methods for evaluation.
            string[] reels = new string[] { spinReels(), spinReels(), spinReels() };

            // Display the reels on the screen.

            // Need to evaluate the spin images and determine the multiplier.
            double multiplier = evaluateSpin(reels);

            // Returning the bet amount * multiplier for any winnings, if any.
            return betAmount * multiplier;

        // Method used to evaluate the value of the reel images and return the amount.
        private double evaluateSpin(string[] reels)
            // Using various bool methods to evaluate the images.
            if (isbar(reels)) return 0;     // Looking for any bar images.

            if (isJackpot(reels)) return 100;       // Looking for the jackpot images.

            // Looking for the amount of cherry images. If cherry images come back return the multiplier amount.
            int multiplier = 0;
            if (isWinner(reels, out multiplier)) return multiplier;

            // If none of the images are anything of value then return 0.
            return 0;

        // Method used to see if there are any bars in the images.
        private bool isbar(string[] reels)
            // Looking for the bar images.
            if (reels[0].Contains("Bar") || reels[1].Contains("Bar") || reels[2].Contains("Bar"))
                return true;
                return false;

        // Method to see if all the reels have sevens to equal a jackpot.
        private bool isJackpot(string[] reels)
            // Looking for the seven images.
            if (reels[0].Contains("Seven") && reels[1].Contains("Seven") && reels[2].Contains("Seven"))
                return true;
                return false;

        // Method to start the process of determining the cherry count.
        private bool isWinner(string[] reels, out int multiplier)
            // Calling on the method to determine the mutiplier amount and return true or false.
            multiplier = determineMultiplier(reels);

            // Return true if the multiplier is greater than 0.
            if (multiplier > 0) return true;
            return false;

        // Method used to determine the multiplier based on the cherry count.
        private int determineMultiplier(string[] reels)
            // Calling the method to evaluate the images and determine the cherry count.
            int cherryCount = determineCherryCount(reels);

            // Checking the value of cherryCount and returning a set value for the reward.
            if (cherryCount == 0) return 0;
            if (cherryCount == 1) return 2;
            if (cherryCount == 2) return 3;
            if (cherryCount == 3) return 4;

            // If no cherries return nothing.
            return 0;

        // Method used to evaluate the reel images and return the cherry count.
        private int determineCherryCount(string[] reels)
            // Variable to hold the cherry count.
            int cherryCount = 0;

            //Looking for cherry images on the reels and updating the cherry count.
            if (reels[0].Contains("Cherry")) cherryCount++;
            if (reels[1].Contains("Cherry")) cherryCount++;
            if (reels[2].Contains("Cherry")) cherryCount++;

            // Returning the cherry count value.
            return cherryCount;

        // Method used to adjust the players purse amount based on the bet and any possible winnings.
        private void adjustPlayersMoney(double betAmount, double winnings)
            // Getting the players money amount from viewstate.
            double playersMoney = double.Parse(ViewState["PlayersMoney"].ToString());

            //Deducting the bet amount from the players money.
            playersMoney -= betAmount;

            // Adding the players winnings, if any, to the players money amount.
            playersMoney += winnings;

            //Re-saving the new amount to view state.
            ViewState["PlayersMoney"] = playersMoney;

        // Method used to update the result label on the screen.
        private void displayResult(double betAmount, double winnings)
            resultLabel.Text = "";

            if (winnings > 0)
                resultLabel.Text = String.Format("You bet {0:C} and won {1:C}.", betAmount, winnings);
                resultLabel.Text = String.Format("Sorry you lost {0:C}. Better luck next time", betAmount);

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s