Python Project: Building a Slot Machine from Scratch

Jul 12, 2024

Python Project: Building a Slot Machine from Scratch

Purpose of the Project

  • Teach basic Python syntax and language features
  • Explain how to structure a program
  • Guide through deciding starting points and building components
  • Aimed at those with a little experience in Python but not confident in writing their own projects.

Project Overview

  • Project: Text-based slot machine
  • Process:
    • User deposits money
    • User bets on 1-3 lines of the slot machine
    • Determine winnings based on lines matched
    • Adjust balance based on winnings or losses
    • Continue playing until user decides to cash out or runs out of money.

Disclaimer

  • Project is not encouraging real gambling; no real money involved.

Program Structure and Components

  1. Setting Up the Project
    • Function to collect user deposit.
    • Use of while loop to ensure a valid amount is entered.
    • Conversion from string to int and validation.
import random

def deposit():
    while True:
        amount = input("What would you like to deposit? $")
        if amount.isdigit():
            amount = int(amount)
            if amount > 0:
                break
            else:
                print("Amount must be greater than zero.")
        else:
            print("Please enter a number.")
    return amount
  1. Collecting User Inputs
    • Function to get the number of lines to bet on using similar while loop logic.
    • Ensuring number of lines is within the predefined range using global constants.
MAX_LINES = 3


def get_number_of_lines():
    while True:
        lines = input(f"Enter the number of lines to bet on (1-{MAX_LINES}): ")
        if lines.isdigit():
            lines = int(lines)
            if 1 <= lines <= MAX_LINES:
                break
            else:
                print("Enter a valid number of lines.")
        else:
            print("Please enter a number.")
    return lines
  1. Getting Bet Amount
    • Function to get the bet amount per line.
    • Ensuring bet is within the minimum and maximum range.
    • Checking if the bet amount does not exceed the current balance.
MIN_BET = 1
MAX_BET = 100


def get_bet(balance):
    while True:
        amount = input(f"What would you like to bet on each line? $")
        if amount.isdigit():
            amount = int(amount)
            if MIN_BET <= amount <= MAX_BET:
                if amount * lines <= balance:
                    return amount
                else:
                    print(f"You do not have enough to bet that amount. Your current balance is ${balance}.")
            else:
                print(f"Amount must be between ${MIN_BET} and ${MAX_BET}.")
        else:
            print("Please enter a number.")
  1. Generating Slot Machine Spin
    • Define the structure of slot machine
    • Use of random module to randomly select values based on symbols dictionary.
    • Function to generate the spin outcome using nested loops and random selection.
ROWS = 3
COLS = 3

SYMBOL_COUNT = {
    "A": 2,
    "B": 4,
    "C": 6,
    "D": 8
}


def get_slot_machine_spin(rows, cols, symbols):
    all_symbols = []
    for symbol, symbol_count in symbols.items():
        for _ in range(symbol_count):
            all_symbols.append(symbol)

    columns = []
    for col in range(cols):
        current_symbols = all_symbols[:]
        column = []
        for row in range(rows):
            value = random.choice(current_symbols)
            current_symbols.remove(value)
            column.append(value)
        columns.append(column)

    return columns
  1. Printing Slot Machine
    • Format the output to correctly represent the slot machine grid.
    • Transpose columns to rows for better readability.
def print_slot_machine(columns):
    for row in range(len(columns[0])):
        for i, column in enumerate(columns):
            if i != len(columns) - 1:
                print(column[row], end=" | ")
            else:
                print(column[row])
  1. Checking Winnings
    • Determine if the user won based on the lines they bet on.
    • Calculate winnings based on symbol values and bet amount.
SYMBOL_VALUE = {
    "A": 5,
    "B": 4,
    "C": 3,
    "D": 2
}


def check_winnings(columns, lines, bet, values):
    winnings = 0
    winning_lines = []
    for line in range(lines):
        symbol = columns[0][line]
        for column in columns:
            if column[line] != symbol:
                break
        else:
            winnings += values[symbol] * bet
            winning_lines.append(line + 1)

    return winnings, winning_lines
  1. Main Function and Game Loop
    • Integrate all components into a main function that manages user balance and game rounds.
    • Allow user to keep playing or quit.
def main():
    balance = deposit()
    while True:
        print(f"Current balance is ${balance}")
        answer = input("Press enter to play (q to quit): ")
        if answer == "q":
            break
        lines = get_number_of_lines()
        bet = get_bet(balance)
        total_bet = bet * lines

        print(f"You are betting ${bet} on {lines} lines. Total bet is equal to ${total_bet}")

        slots = get_slot_machine_spin(ROWS, COLS, SYMBOL_COUNT)
        print_slot_machine(slots)
        winnings, winning_lines = check_winnings(slots, lines, bet, SYMBOL_VALUE)
        print(f"You won ${winnings}.")
        print(f"You won on lines:", *winning_lines)
        balance += winnings - total_bet

    print(f"You left with ${balance}")


main()

Summary

  • Introduced several Python features (functions, loops, conditionals, random selection, string formatting, etc.)
  • Explained principles of modular programming by breaking down the problem into manageable components.
  • Consolidated individual functions into a cohesive program that allows continuous play of the slot machine.