write code for gambling machine on python with tkinter
- User
write code for gambling machine on python with tkinter
- Assistant
write code for gambling machine on python with tkinter
Here's a simple gambling machine (slot machine) implemented in Python using Tkinter. This program simulates a slot machine where you can spin the reels and win money based on matching symbols.
import tkinter as tk
from tkinter import messagebox
import random
class SlotMachine(tk.Tk):
def __init__(self):
super().__init__()
self.title("Slot Machine")
self.geometry("400x300")
self.resizable(False, False)
# Initialize player's balance
self.balance = 100 # Start with $100
# List of symbols to use on the reels
self.symbols = ['🍒', '🔔', '🍋', '⭐', '🍉', '7️⃣']
# Create the GUI components
self.create_widgets()
def create_widgets(self):
# Display the balance
self.balance_label = tk.Label(self, text=f"Balance: ${self.balance}", font=("Arial", 16))
self.balance_label.pack(pady=10)
# Frame to hold the slot reels
self.slot_frame = tk.Frame(self)
self.slot_frame.pack(pady=10)
# Labels for each reel
self.slot_labels = []
for _ in range(3):
label = tk.Label(self.slot_frame, text='❔', font=('Arial', 50))
label.pack(side=tk.LEFT, padx=5)
self.slot_labels.append(label)
# Spin button
self.spin_button = tk.Button(self, text='Spin', font=("Arial", 14), command=self.spin)
self.spin_button.pack(pady=20)
# Message label for displaying win/loss messages
self.message_label = tk.Label(self, text='', font=("Arial", 14))
self.message_label.pack(pady=10)
def spin(self):
if self.balance < 1:
messagebox.showwarning("Insufficient Balance", "You don't have enough balance to spin.")
return
# Deduct $1 for each spin
self.balance -= 1
self.update_balance()
# Spin the reels
reels = []
for label in self.slot_labels:
symbol = random.choice(self.symbols)
label.config(text=symbol)
reels.append(symbol)
# Evaluate the result
self.check_result(reels)
# Check if balance is depleted
if self.balance <= 0:
messagebox.showinfo("Game Over", "You have run out of money!")
self.spin_button.config(state=tk.DISABLED)
def update_balance(self):
self.balance_label.config(text=f"Balance: ${self.balance}")
def check_result(self, reels):
# Reset the message label
self.message_label.config(text='')
# Count occurrences of each symbol
counts = {symbol: reels.count(symbol) for symbol in set(reels)}
if len(set(reels)) == 1:
# All symbols match
win_amount = 50
self.balance += win_amount
self.update_balance()
self.message_label.config(text=f"Jackpot! You won ${win_amount}!", fg='green')
elif 2 in counts.values():
# Two symbols match
win_amount = 5
self.balance += win_amount
self.update_balance()
self.message_label.config(text=f"You matched two symbols! You won ${win_amount}!", fg='blue')
else:
# No symbols match
self.message_label.config(text="No match. Try again!", fg='red')
if __name__ == "__main__":
app = SlotMachine()
app.mainloop()
Initialization: The SlotMachine class initializes the main window, sets the title, size, and starting balance. It also defines the symbols that will appear on the reels.
Creating Widgets: The create_widgets method sets up the labels to display the balance, the slot reels, and the spin button. It also includes a message label to display win or loss messages after each spin.
Spinning the Reels: When the player clicks the "Spin" button, the spin method is called. This method checks if the player has enough balance to spin. It then deducts $1 from the balance and randomly selects a symbol for each reel.
Updating the Display: After spinning, the symbols on the reels are updated to show the new symbols. The balance is updated on the screen.
Checking Results: The check_result method analyzes the symbols on the reels to determine if the player has won:
Updating Balance and Messages: Based on the result, the player's balance is updated, and an appropriate message is displayed.
Game Over Condition: If the player's balance reaches $0, the spin button is disabled, and a "Game Over" message is displayed.
Install Python: Make sure you have Python 3 installed on your computer.
Save the Code: Copy the code above and save it in a file named slot_machine.py.
Run the Program: Open a terminal or command prompt, navigate to the directory where the file is saved, and run the command:
python slot_machine.py
Play the Game: The slot machine window will appear. Click the "Spin" button to play. Try to match symbols to win money. The game ends when your balance reaches $0.
You can customize the game by modifying the following:
Symbols: Add or remove symbols from the self.symbols list to change what's displayed on the reels.
Winning Amounts: Adjust the win_amount values in the check_result method to change how much money is won for each condition.
Starting Balance: Change self.balance = 100 to set a different starting balance for the player.
Cost Per Spin: Modify the amount deducted in the spin method (self.balance -= 1) to change how much each spin costs.
Add Sound Effects: Include sounds for spinning reels and winning.
Enhance Graphics: Use images instead of text symbols for the reels.
Multiple Bet Options: Allow players to bet different amounts per spin.
Persistent Balance: Save the player's balance to a file, so it persists between sessions.
Animations: Add animations to simulate the spinning of reels.
Feel free to expand and improve upon this basic slot machine to create a more engaging and feature-rich game!
Not yet included in a published release.