Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tkinter as GUI
- import random
- import json
- import os
- from tkinter import messagebox
- from cryptography.fernet import Fernet
- import requests
- class SlotMachine:
- # Constants
- KEY_FILE = "key.key"
- SAVE_FILE = "savegame.json"
- NBP_API_URL = "https://api.nbp.pl/api/exchangerates/rates/A"
- SYMBOLS = ["π", "π", "π", "π", "β"]
- SYMBOL_CHANCES = {"π": 40, "π": 30, "π": 15, "π": 10, "β": 5}
- MULTIPLIERS = {"π": 1.2, "π": 1.5, "π": 2, "π": 2.5, "β": 5}
- BET_OPTIONS = [5, 10, 15]
- # Szyfrowanie danych
- @staticmethod
- def generate_key():
- if not os.path.exists(SlotMachine.KEY_FILE):
- key = Fernet.generate_key()
- with open(SlotMachine.KEY_FILE, "wb") as key_file:
- key_file.write(key)
- @staticmethod
- def load_key():
- if not os.path.exists(SlotMachine.KEY_FILE):
- raise FileNotFoundError("Key not found! Please generate security key first!")
- with open(SlotMachine.KEY_FILE, "rb") as key_file:
- return key_file.read()
- def encrypt_data(self, data):
- key = self.load_key()
- fernet = Fernet(key)
- json_data = json.dumps(data).encode("utf-8")
- encrypted_data = fernet.encrypt(json_data)
- return encrypted_data
- def decrypt_data(self, encrypted_data):
- key = self.load_key()
- fernet = Fernet(key)
- decrypted_data = fernet.decrypt(encrypted_data).decode("utf-8")
- return json.loads(decrypted_data)
- def __init__(self, root):
- self.root = root
- self.root.title("Lucky Machine")
- self.root.geometry("600x700")
- self.generate_key()
- self.spins = self.create_spin_area()
- self.credits = 0
- self.current_bet = 0
- self.exchange_rates = {}
- self.initialize_ui()
- # Load or initialize game state
- self.load_or_initialize()
- def initialize_ui(self):
- self.credit_label = GUI.Label(self.root, text="Credits: 0", font=("Arial", 16))
- self.credit_label.grid(row=4, column=0, columnspan=3, pady=10)
- self.result_label = GUI.Label(self.root, text="", font=("Arial", 16))
- self.result_label.grid(row=9, column=0, columnspan=3, pady=10)
- self.create_bet_buttons()
- self.create_utility_buttons()
- def create_bet_buttons(self):
- for i, bet in enumerate(SlotMachine.BET_OPTIONS):
- GUI.Button(self.root, text=f"Play for {bet} credits", font=("Arial", 14),
- command=lambda b=bet: self.start_game(b)).grid(row=5, column=i, padx=10, pady=10)
- def create_utility_buttons(self):
- buttons = [
- ("Add Credits", self.add_credits),
- ("Withdraw Credits", self.withdraw_credits),
- ("Chances", self.show_chances),
- ("Save and Exit", self.save_and_exit),
- ("Multiplier", self.show_multipliers)
- ]
- for i, (text, command) in enumerate(buttons):
- GUI.Button(self.root, text=text, font=("Arial", 14), command=command).grid(row=6 + i, column=1, pady=10)
- def create_spin_area(self):
- return [[GUI.Label(self.root, text=random.choice(SlotMachine.SYMBOLS), font=("Arial", 32), width=4, height=2)
- for _ in range(3)] for _ in range(3)]
- def load_or_initialize(self):
- if os.path.exists(self.SAVE_FILE):
- if messagebox.askyesno("Load game", "Do you want to continue saved game?"):
- self.load_game()
- return
- self.initialize_credits()
- def initialize_credits(self):
- def submit_credits():
- try:
- credits = int(credit_entry.get())
- if credits <= 0:
- raise ValueError("Your credits can't be less than 0!")
- self.credits = credits
- self.credit_label.config(text=f"Credits: {self.credits}")
- credit_window.destroy()
- except ValueError as e:
- messagebox.showerror("Error!", str(e))
- credit_window = GUI.Toplevel(self.root)
- credit_window.title("Enter your credits")
- GUI.Label(credit_window, text="Enter how many credits do you have:").pack(pady=10)
- credit_entry = GUI.Entry(credit_window, font=("Arial", 14))
- credit_entry.pack(pady=5)
- GUI.Button(credit_window, text="Submit credits", command=submit_credits).pack(pady=10)
- def save_and_exit(self):
- save_data = {"credits": self.credits}
- encrypted_data = self.encrypt_data(save_data)
- with open(self.SAVE_FILE, "wb") as file:
- file.write(encrypted_data)
- messagebox.showinfo("Save and exit", "Game has been saved successfully!")
- self.root.destroy()
- def load_game(self):
- with open(self.SAVE_FILE, "rb") as file:
- encrypted_data = file.read()
- save_data = self.decrypt_data(encrypted_data)
- self.credits = save_data.get("credits", 0)
- self.credit_label.config(text=f"Credits: {self.credits}")
- messagebox.showinfo("Game loaded!", "Your saved game has been loaded!")
- def add_credits(self):
- def submit_add_credits():
- try:
- additional_credits = int(add_credits_entry.get())
- if additional_credits <= 0:
- raise ValueError("Enter value higher than zero!")
- self.credits += additional_credits
- self.credit_label.config(text=f"Credits: {self.credits}")
- add_credits_window.destroy()
- except ValueError as e:
- messagebox.showerror("Error", str(e))
- add_credits_window = GUI.Toplevel(self.root)
- add_credits_window.title("Add credits")
- GUI.Label(add_credits_window, text="Enter how many credits are you depositing:").pack(pady=10)
- add_credits_entry = GUI.Entry(add_credits_window, font=("Arial", 14))
- add_credits_entry.pack(pady=5)
- GUI.Button(add_credits_window, text="Submit", command=submit_add_credits).pack(pady=10)
- def start_game(self, bet):
- if self.credits < bet:
- messagebox.showerror("Not enough credits!", "You don't have enough credits to bet!")
- return
- self.credits -= bet
- self.credit_label.config(text=f"Credits: {self.credits}")
- self.result_label.config(text="")
- self.current_bet = bet
- self.animate_spin()
- def animate_spin(self):
- for i in range(3):
- for j in range(3):
- self.spins[i][j].config(text=self.get_random_symbol())
- self.root.after(100, self.check_result)
- def check_result(self):
- symbols = [[self.spins[i][j].cget("text") for j in range(3)] for i in range(3)]
- if self.is_winner(symbols):
- self.show_winner(symbols)
- else:
- self.result_label.config(text="Bad luck!\nTry again!", fg="red")
- def is_winner(self, symbols):
- # Checking rows, columns, and diagonals for matching symbols
- for row in symbols:
- if row[0] == row[1] == row[2]:
- return True
- for col in range(3):
- if symbols[0][col] == symbols[1][col] == symbols[2][col]:
- return True
- if symbols[0][0] == symbols[1][1] == symbols[2][2]:
- return True
- if symbols[0][2] == symbols[1][1] == symbols[2][0]:
- return True
- return False
- def show_winner(self, symbols):
- symbol = symbols[0][0]
- winnings = int(self.current_bet * SlotMachine.MULTIPLIERS[symbol])
- self.credits += winnings
- self.credit_label.config(text=f"Credits: {self.credits}")
- self.result_label.config(text=f"Lucky you! You won {winnings} credits with {symbol}", fg="green")
- def get_random_symbol(self):
- roll = random.randint(1, 100)
- for symbol, chance in SlotMachine.SYMBOL_CHANCES.items():
- if roll <= chance:
- return symbol
- roll -= chance
- return SlotMachine.SYMBOLS[-1] # fallback to last symbol
- # Start the game
- root = GUI.Tk()
- slot_machine = SlotMachine(root)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement