Advertisement
clear_e46

Wordle Python

May 10th, 2024
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.93 KB | Source Code | 0 0
  1. import customtkinter as ctk # Importing customtkinter library as ctk
  2. from CTkMessagebox import CTkMessagebox # Importing CTkMessagebox class from CTkMessagebox module
  3. import random # Importing random module for random word selection
  4. import PIL
  5. from PIL import Image
  6. from CTkMenuBar import CustomDropdownMenu, CTkTitleMenu # Add this import line
  7.  
  8. from CTkMenuBar import *
  9. class ModernWordleGUI:
  10. def __init__(self, master, word_list):
  11. # Initialize the GUI
  12. self.master = master # Master window
  13. self.word = random.choice(word_list).upper() # Select a random word from the list and convert it to uppercase
  14. self.word_list = word_list
  15. self.attempts = 0 # Initialize attempts counter
  16. self.current_guess = '' # Initialize current guess
  17. # Initialize the state of letters (default color)
  18. self.letters_state = {chr(i): 'light grey' for i in range(65, 91)}
  19. self.buttons = {} # Dictionary to store letter buttons
  20. self.master.bind("<Key>", self.key_pressed) # Bind key press event to key_pressed method
  21. self.master.bind("<Return>", lambda event: self.enter_key()) # Bind return key to enter_key method
  22. self.master.bind("<BackSpace>", lambda event: self.backspace()) # Bind backspace key to backspace method
  23. self.setup_gui()
  24.  
  25. def setup_gui(self):
  26. self.master.title("Wordle Game") # Set window title
  27. image = PIL.Image.open("photo.png")
  28. background_image = ctk.CTkImage(image, size=(600, 500))
  29. bg_lbl = ctk.CTkLabel(app, text="", image=background_image)
  30. bg_lbl.place(x=0, y=0)
  31. self.master.geometry("310x500") # Set window
  32.  
  33.  
  34.  
  35. self.guess_grid = [] # Initialize the guess grid
  36. for k in range(5):
  37. row = []
  38. for p in range(5):
  39. # Create label for displaying guesses
  40. label = ctk.CTkLabel(self.master, text=' ', font=('Gill Sans MT Condensed', 35), height=56,
  41. width=56, fg_color='black')
  42. label.grid(row=k, column=p, padx=3, pady=3) # Grid placement
  43. row.append(label)
  44. for i in range(5):
  45. row = []
  46. for j in range(5):
  47. # Create label for displaying guesses
  48. label = ctk.CTkLabel(self.master, text=' ', font=('Gill Sans MT Condensed', 35), height=50,
  49. width=50, fg_color='#BDB0B0')
  50. label.grid(row=i, column=j, padx=3, pady=3) # Grid placement
  51. row.append(label)
  52. self.guess_grid.append(row)
  53.  
  54. # Setup the keyboard
  55. self.setup_keyboard() # Call setup_keyboard method
  56.  
  57. # Create and place the submit button
  58. submit_btn = ctk.CTkButton(self.master, text="Submit", command=self.submit_guess,font=('Gill Sans MT Condensed', 18),
  59. fg_color='#848484', text_color='black')
  60. submit_btn.grid(row=7, columnspan=5, pady=10) # Grid placement
  61. self.buttons['Submit'] = submit_btn # Store the submit button in the buttons dictionary with the key 'Submit'
  62.  
  63. settings_icon = PIL.Image.open("icon.png")
  64. settings_photo = ctk.CTkImage(settings_icon)
  65. setting = ctk.CTkLabel(app, text="", image=settings_photo)
  66. setting.place(x=0, y=470)
  67.  
  68. # Add menu with restart option
  69.  
  70.  
  71.  
  72. def restart_game(self):
  73. # Method to restart the game
  74. self.attempts = 0
  75. self.current_guess = ''
  76. self.word = random.choice(self.word_list).upper()
  77. self.update_guess_display()
  78. for i in range(5):
  79. for j in range(5):
  80. label = self.guess_grid[i][j]
  81. label.configure(text=' ', fg_color='#BDB0B0') # Reset label text and foreground color
  82. for button_key, button in self.buttons.items():
  83. if button_key != 'Submit': # Exclude the "Submit" button
  84. button.configure(fg_color=self.letters_state[button.cget('text')])
  85. button.configure(state="normal")
  86.  
  87. def key_pressed(self, event):
  88. # Method to handle key presses for typing letters
  89. if event.char and event.char.isalpha(): # Check if the pressed key is a valid letter
  90. letter = event.char.lower() # Get the character of the key that was pressed and convert to lowercase
  91. self.press_key(letter) # Call press_key method with the pressed letter
  92.  
  93.  
  94. def setup_keyboard(self):
  95. # Setup the keyboard layout
  96.  
  97. keyboard_frame = ctk.CTkFrame(self.master, fg_color='#BDB0B0') # Create keyboard frame
  98. keyboard_frame.grid(row=6, columnspan=7, pady=15) # Grid placement
  99. rows = ['QWERTYUIOP', 'ASDFGHJKL', 'ZXCVBNM'] # Define keyboard rows
  100. for i, row in enumerate(rows):
  101. frame = ctk.CTkFrame(keyboard_frame, fg_color='transparent') # Create frame for each row
  102. frame.grid(row=i, pady=5) # Grid placement
  103. for letter in row:
  104. # Create button for each letter
  105. btn = ctk.CTkButton(frame, text=letter, command=lambda l=letter: self.press_key(l),
  106. font=('Gill Sans MT Condensed', 18), fg_color=self.letters_state[letter], text_color='black', width=13, height=18)
  107. self.buttons[letter] = btn # Store button in dictionary
  108. btn.pack(side='left', padx=2) # Pack button into frame
  109.  
  110. # Create and place backspace button
  111. backspace = ctk.CTkButton(frame, text='⌫', text_color='black',fg_color='transparent',command=self.backspace, font=('Gill Sans MT Condensed', 18), width=2, height=1)
  112. backspace.pack(side='left', padx=2) # Pack backspace button into frame
  113.  
  114. def press_key(self, event):
  115. # Method to handle key presses for typing letters
  116. if isinstance(event, str): # Check if event is a string (from button click)
  117. letter = event.lower() # Convert letter to lowercase
  118. else: # If event is not a string (from key press)
  119. letter = event.char.lower() # Get the character of the key that was pressed and convert to lowercase
  120.  
  121. if len(self.current_guess) < 5:
  122. self.current_guess += letter # Add pressed letter to current guess
  123. self.update_guess_display() # Update the display of current guess
  124. print(self.current_guess, "&&&", " ", letter, " word:", self.word) # Debug print statement
  125. if len(self.current_guess) == 5: # Check if the length of the current guess is 5
  126. self.buttons['Submit'].configure(fg_color='#C9C9C9') # Change the color of the submit button to red
  127.  
  128. def backspace(self, event=None):
  129. # Method to handle backspace key press
  130. if len(self.current_guess) > 0:
  131. self.current_guess = self.current_guess[:-1] # Remove last character from current guess
  132. self.update_guess_display() # Update the display of current guess
  133.  
  134. def enter_key(self, event=None):
  135. # Method to handle Enter key press
  136. self.submit_guess() # Call submit_guess method
  137.  
  138. def update_guess_display(self):
  139. # Method to update the display of current guess
  140. for i in range(5):
  141. char = self.current_guess[i].upper() if i < len(
  142. self.current_guess) else ' ' # Convert character to uppercase
  143. self.guess_grid[self.attempts][i].configure(text=char) # Update the text of the label
  144.  
  145. def submit_guess(self):
  146. # Method to submit the current guess
  147. self.buttons['Submit'].configure(fg_color='#848484')
  148. if len(self.current_guess) == 5: # Check if the current guess is of length 5
  149. if self.current_guess.lower() in self.word_list: # Check if the guess is in the word list
  150. self.check_guess(self.current_guess.upper()) # Call check_guess method with the guess in uppercase
  151. self.current_guess = '' # Reset current guess
  152. if all(lbl.cget('fg_color') == 'green' for lbl in
  153. self.guess_grid[self.attempts]): # Check if all labels are green
  154. self.end_game("Congratulations, you've won!") # Call end_game method with winning message
  155. elif self.attempts < 4: # Check if attempts are less than 4
  156. self.attempts += 1 # Increment attempts counter
  157. else:
  158. self.end_game(
  159. f"Game over, the word was {self.word}. You didn't guess the word in time!") # Call end_game method with game over message
  160. else:
  161. CTkMessagebox(title="Invalid Guess",
  162. message="Please enter a valid 5-letter word from the word list.") # Show message box for invalid guess
  163.  
  164. def check_guess(self, guess):
  165. # Method to check the current guess
  166. guessed_indices = [] # Initialize list to keep track of guessed indices
  167. for i, char in enumerate(guess):
  168. if char == self.word[i]:
  169. # Mark correct letter in the correct position as green
  170. self.guess_grid[self.attempts][i].configure(fg_color='green')
  171. self.buttons[char].configure(fg_color='green') # Change button color to green
  172. guessed_indices.append(i) # Add index to guessed_indices
  173. elif char in self.word and self.word.index(char) not in guessed_indices:
  174. # Mark correct letters in the wrong position as yellow
  175. self.guess_grid[self.attempts][i].configure(fg_color='#B3A036')
  176. self.buttons[char].configure(fg_color='#A1A636') # Change button color to yellow
  177. else:
  178. # Mark incorrect letters as light grey
  179. self.guess_grid[self.attempts][i].configure(fg_color='#747474')
  180. self.buttons[char].configure(fg_color='#747474') # Change button color to yellow
  181.  
  182. def end_game(self, message):
  183. # Get yes/no answers
  184. msg = CTkMessagebox(title="Exit?", message=message,
  185. option_1="Play again", option_2="Quit",justify= 'center', width=340,height=150,button_width= 50,button_height=30)
  186. response = msg.get()
  187.  
  188. if response == "Quit":
  189. self.master.destroy()
  190. else:
  191. self.restart_game()
  192.  
  193. # Removed the duplicate end_game function defined after the class definition
  194.  
  195. if __name__ == "__main__":
  196. app = ctk.CTk() # Create root window using customtkinter
  197. word_list = []
  198. with open("words.txt", "r") as words_file:
  199. lines = words_file.readlines() # Read all lines from the file into a list
  200. for line in lines:
  201. word_list.append(
  202. line.strip()) # Append each line (word) to the word_list after stripping any leading/trailing whitespace
  203.  
  204. apps = ModernWordleGUI(app, word_list) # Create game instance
  205. app.mainloop() # Start the main event loop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement