Advertisement
xosski

Welcome to Vegas/slot machine

Dec 13th, 2024
13
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.21 KB | None | 0 0
  1. import tkinter as GUI
  2. import random
  3. import json
  4. import os
  5. from tkinter import messagebox
  6. from cryptography.fernet import Fernet
  7. import requests
  8.  
  9. class SlotMachine:
  10. # Constants
  11. KEY_FILE = "key.key"
  12. SAVE_FILE = "savegame.json"
  13. NBP_API_URL = "https://api.nbp.pl/api/exchangerates/rates/A"
  14. SYMBOLS = ["πŸ’", "πŸ‹", "🍌", "πŸ””", "⭐"]
  15. SYMBOL_CHANCES = {"πŸ’": 40, "πŸ‹": 30, "🍌": 15, "πŸ””": 10, "⭐": 5}
  16. MULTIPLIERS = {"πŸ’": 1.2, "πŸ‹": 1.5, "🍌": 2, "πŸ””": 2.5, "⭐": 5}
  17. BET_OPTIONS = [5, 10, 15]
  18.  
  19. # Szyfrowanie danych
  20. @staticmethod
  21. def generate_key():
  22. if not os.path.exists(SlotMachine.KEY_FILE):
  23. key = Fernet.generate_key()
  24. with open(SlotMachine.KEY_FILE, "wb") as key_file:
  25. key_file.write(key)
  26.  
  27. @staticmethod
  28. def load_key():
  29. if not os.path.exists(SlotMachine.KEY_FILE):
  30. raise FileNotFoundError("Key not found! Please generate security key first!")
  31. with open(SlotMachine.KEY_FILE, "rb") as key_file:
  32. return key_file.read()
  33.  
  34. def encrypt_data(self, data):
  35. key = self.load_key()
  36. fernet = Fernet(key)
  37. json_data = json.dumps(data).encode("utf-8")
  38. encrypted_data = fernet.encrypt(json_data)
  39. return encrypted_data
  40.  
  41. def decrypt_data(self, encrypted_data):
  42. key = self.load_key()
  43. fernet = Fernet(key)
  44. decrypted_data = fernet.decrypt(encrypted_data).decode("utf-8")
  45. return json.loads(decrypted_data)
  46.  
  47. def __init__(self, root):
  48. self.root = root
  49. self.root.title("Lucky Machine")
  50. self.root.geometry("600x700")
  51. self.generate_key()
  52.  
  53. self.spins = self.create_spin_area()
  54. self.credits = 0
  55. self.current_bet = 0
  56. self.exchange_rates = {}
  57.  
  58. self.initialize_ui()
  59.  
  60. # Load or initialize game state
  61. self.load_or_initialize()
  62.  
  63. def initialize_ui(self):
  64. self.credit_label = GUI.Label(self.root, text="Credits: 0", font=("Arial", 16))
  65. self.credit_label.grid(row=4, column=0, columnspan=3, pady=10)
  66.  
  67. self.result_label = GUI.Label(self.root, text="", font=("Arial", 16))
  68. self.result_label.grid(row=9, column=0, columnspan=3, pady=10)
  69.  
  70. self.create_bet_buttons()
  71. self.create_utility_buttons()
  72.  
  73. def create_bet_buttons(self):
  74. for i, bet in enumerate(SlotMachine.BET_OPTIONS):
  75. GUI.Button(self.root, text=f"Play for {bet} credits", font=("Arial", 14),
  76. command=lambda b=bet: self.start_game(b)).grid(row=5, column=i, padx=10, pady=10)
  77.  
  78. def create_utility_buttons(self):
  79. buttons = [
  80. ("Add Credits", self.add_credits),
  81. ("Withdraw Credits", self.withdraw_credits),
  82. ("Chances", self.show_chances),
  83. ("Save and Exit", self.save_and_exit),
  84. ("Multiplier", self.show_multipliers)
  85. ]
  86.  
  87. for i, (text, command) in enumerate(buttons):
  88. GUI.Button(self.root, text=text, font=("Arial", 14), command=command).grid(row=6 + i, column=1, pady=10)
  89.  
  90. def create_spin_area(self):
  91. return [[GUI.Label(self.root, text=random.choice(SlotMachine.SYMBOLS), font=("Arial", 32), width=4, height=2)
  92. for _ in range(3)] for _ in range(3)]
  93.  
  94. def load_or_initialize(self):
  95. if os.path.exists(self.SAVE_FILE):
  96. if messagebox.askyesno("Load game", "Do you want to continue saved game?"):
  97. self.load_game()
  98. return
  99. self.initialize_credits()
  100.  
  101. def initialize_credits(self):
  102. def submit_credits():
  103. try:
  104. credits = int(credit_entry.get())
  105. if credits <= 0:
  106. raise ValueError("Your credits can't be less than 0!")
  107. self.credits = credits
  108. self.credit_label.config(text=f"Credits: {self.credits}")
  109. credit_window.destroy()
  110. except ValueError as e:
  111. messagebox.showerror("Error!", str(e))
  112.  
  113. credit_window = GUI.Toplevel(self.root)
  114. credit_window.title("Enter your credits")
  115. GUI.Label(credit_window, text="Enter how many credits do you have:").pack(pady=10)
  116. credit_entry = GUI.Entry(credit_window, font=("Arial", 14))
  117. credit_entry.pack(pady=5)
  118. GUI.Button(credit_window, text="Submit credits", command=submit_credits).pack(pady=10)
  119.  
  120. def save_and_exit(self):
  121. save_data = {"credits": self.credits}
  122. encrypted_data = self.encrypt_data(save_data)
  123. with open(self.SAVE_FILE, "wb") as file:
  124. file.write(encrypted_data)
  125. messagebox.showinfo("Save and exit", "Game has been saved successfully!")
  126. self.root.destroy()
  127.  
  128. def load_game(self):
  129. with open(self.SAVE_FILE, "rb") as file:
  130. encrypted_data = file.read()
  131. save_data = self.decrypt_data(encrypted_data)
  132. self.credits = save_data.get("credits", 0)
  133. self.credit_label.config(text=f"Credits: {self.credits}")
  134. messagebox.showinfo("Game loaded!", "Your saved game has been loaded!")
  135.  
  136. def add_credits(self):
  137. def submit_add_credits():
  138. try:
  139. additional_credits = int(add_credits_entry.get())
  140. if additional_credits <= 0:
  141. raise ValueError("Enter value higher than zero!")
  142. self.credits += additional_credits
  143. self.credit_label.config(text=f"Credits: {self.credits}")
  144. add_credits_window.destroy()
  145. except ValueError as e:
  146. messagebox.showerror("Error", str(e))
  147.  
  148. add_credits_window = GUI.Toplevel(self.root)
  149. add_credits_window.title("Add credits")
  150. GUI.Label(add_credits_window, text="Enter how many credits are you depositing:").pack(pady=10)
  151. add_credits_entry = GUI.Entry(add_credits_window, font=("Arial", 14))
  152. add_credits_entry.pack(pady=5)
  153. GUI.Button(add_credits_window, text="Submit", command=submit_add_credits).pack(pady=10)
  154.  
  155. def start_game(self, bet):
  156. if self.credits < bet:
  157. messagebox.showerror("Not enough credits!", "You don't have enough credits to bet!")
  158. return
  159.  
  160. self.credits -= bet
  161. self.credit_label.config(text=f"Credits: {self.credits}")
  162. self.result_label.config(text="")
  163. self.current_bet = bet
  164.  
  165. self.animate_spin()
  166.  
  167. def animate_spin(self):
  168. for i in range(3):
  169. for j in range(3):
  170. self.spins[i][j].config(text=self.get_random_symbol())
  171. self.root.after(100, self.check_result)
  172.  
  173. def check_result(self):
  174. symbols = [[self.spins[i][j].cget("text") for j in range(3)] for i in range(3)]
  175. if self.is_winner(symbols):
  176. self.show_winner(symbols)
  177. else:
  178. self.result_label.config(text="Bad luck!\nTry again!", fg="red")
  179.  
  180. def is_winner(self, symbols):
  181. # Checking rows, columns, and diagonals for matching symbols
  182. for row in symbols:
  183. if row[0] == row[1] == row[2]:
  184. return True
  185. for col in range(3):
  186. if symbols[0][col] == symbols[1][col] == symbols[2][col]:
  187. return True
  188. if symbols[0][0] == symbols[1][1] == symbols[2][2]:
  189. return True
  190. if symbols[0][2] == symbols[1][1] == symbols[2][0]:
  191. return True
  192. return False
  193.  
  194. def show_winner(self, symbols):
  195. symbol = symbols[0][0]
  196. winnings = int(self.current_bet * SlotMachine.MULTIPLIERS[symbol])
  197. self.credits += winnings
  198. self.credit_label.config(text=f"Credits: {self.credits}")
  199. self.result_label.config(text=f"Lucky you! You won {winnings} credits with {symbol}", fg="green")
  200.  
  201. def get_random_symbol(self):
  202. roll = random.randint(1, 100)
  203. for symbol, chance in SlotMachine.SYMBOL_CHANCES.items():
  204. if roll <= chance:
  205. return symbol
  206. roll -= chance
  207. return SlotMachine.SYMBOLS[-1] # fallback to last symbol
  208.  
  209.  
  210. # Start the game
  211. root = GUI.Tk()
  212. slot_machine = SlotMachine(root)
  213. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement