|
1 | | -# Slot Machine |
| 1 | +# Python Slot Machine |
| 2 | +# user has balance |
| 3 | +# user can bet amount |
| 4 | + |
| 5 | +import random |
| 6 | + |
| 7 | +# Spin the slot machine (pick 3 random symbols) |
| 8 | +def spin_row(): |
| 9 | + # symbols are cherry, lemon, orange, watermelon, star, bell, seven |
| 10 | + symbols = ['🍒', '🍋', '🍊', '🍉', '⭐', '🔔', '7️⃣'] |
| 11 | + # choose 3 symbols randomly and return as a list |
| 12 | + return [random.choice(symbols) for _ in range(3)] |
| 13 | + |
| 14 | +# Decide how much the player wins |
| 15 | +def calculate_payout(row, bet): |
| 16 | + # All three match |
| 17 | + if row[0] == row[1] == row[2]: |
| 18 | + # Jackpot if all sevens |
| 19 | + if row[0] == '7️⃣': |
| 20 | + return bet * 10 # Jackpot # award 10 times the bet |
| 21 | + else: |
| 22 | + return bet * 5 # Three of a kind # award 5 times the bet |
| 23 | + # Any two match |
| 24 | + elif row[0] == row[1] or row[1] == row[2] or row[0] == row[2]: |
| 25 | + return bet * 2 # Two of a kind # award 2 times the bet |
| 26 | + # No match # no winnings |
| 27 | + return 0 |
| 28 | + |
| 29 | +def main(): |
| 30 | + # Initial balance for the player |
| 31 | + balance = 100 |
| 32 | + print("🎰 Welcome to the Python Slot Machine!") |
| 33 | + print(f"Starting balance: ${balance}") |
| 34 | + |
| 35 | + # Game loop - continues until player quits or runs out of money |
| 36 | + while balance > 0: |
| 37 | + print(f"\nYour balance: ${balance}") |
| 38 | + bet = input("Enter bet amount (0 to quit): ") |
| 39 | + |
| 40 | + # Check if input is a number |
| 41 | + if not bet.isdigit(): |
| 42 | + print("Please enter a number.") |
| 43 | + continue |
| 44 | + |
| 45 | + bet = int(bet) |
| 46 | + |
| 47 | + # Quit if bet is 0 |
| 48 | + if bet == 0: |
| 49 | + print("Thanks for playing! Goodbye.") |
| 50 | + break |
| 51 | + |
| 52 | + # Check if bet is valid |
| 53 | + # Bet cannot be more than balance or negative |
| 54 | + if bet > balance or bet < 0: |
| 55 | + print("Invalid bet amount.") |
| 56 | + continue |
| 57 | + |
| 58 | + # Deduct bet from balance |
| 59 | + balance -= bet |
| 60 | + |
| 61 | + # Spin the machine and display result |
| 62 | + row = spin_row() |
| 63 | + print("Spinning...") |
| 64 | + # Display the row |
| 65 | + print(" | ".join(row)) |
| 66 | + |
| 67 | + # Calculate winnings |
| 68 | + payout = calculate_payout(row, bet) |
| 69 | + # Update balance and display result |
| 70 | + if payout > 0: |
| 71 | + balance += payout |
| 72 | + print(f"🎉 You won ${payout}!") |
| 73 | + else: |
| 74 | + print("No win this time.") |
| 75 | + |
| 76 | + # Game over message |
| 77 | + print("\nGame over! Final balance:", balance) |
| 78 | + |
| 79 | +if __name__ == "__main__": |
| 80 | + main() |
| 81 | + |
0 commit comments