-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
241 lines (209 loc) · 8.4 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import sys
from json import load
from random import randint
from collections import defaultdict
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5 import QtCore
from PyQt5 import QtGui
from mainGui import Ui_mainWindow
from keymap import keydata
wordArr = []
DEBUG = True
MAX_TRIALS = 6
STYLE_SHEET_STR = """
*:disabled {
background-color:rgb(30, 30, 30);
color: rgb(127, 127, 127);
}
*{
background-color: rgb(90, 90, 90);
color: white;
}
"""
with open("words.json", "r", encoding="utf-8") as fil:
wordArr = load(fil)["data"]
WORD_COU = len(wordArr)
class myWindow(QtWidgets.QMainWindow):
keyPressed = QtCore.pyqtSignal(QtCore.QEvent)
def __init__(self):
super(myWindow, self).__init__()
self.ui = Ui_mainWindow()
self.ui.setupUi(self)
self.setWindowIcon(QtGui.QIcon('img.png'))
self.keyPressed.connect(self.on_key)
self.wordsLabelLayouts = [self.ui.word_1, self.ui.word_2, self.ui.word_3, self.ui.word_4, self.ui.word_5, self.ui.word_6]
self.initApp()
def keyPressEvent(self, event):
super(myWindow, self).keyPressEvent(event)
self.keyPressed.emit(event)
def on_key(self, event):
if self.userStr and event.key() == QtCore.Qt.Key_Backspace:
self.userStr = self.userStr[:-1]
elif event.text().isalpha() and len(self.userStr) < 5:
self.userStr += event.text()
elif event.key() == QtCore.Qt.Key_Return:
if DEBUG:
print("Enter pressed")
if len(self.userStr) == 5:
self.game()
else:
self.errorMessage("Hata", "5 harflik bir kelime girin!")
self.printWord()
if DEBUG:
print(self.userStr)
def clear(self):
for layout in self.wordsLabelLayouts:
labels = [layout.itemAt(i).widget() for i in range(layout.count()) if type(layout.itemAt(i).widget()) == QtWidgets.QLabel]
for label in labels:
label.setText("_")
label.setStyleSheet("")
for object in self.keyboardKeys.values():
object.setStyleSheet("")
def printWord(self):
layout = self.wordsLabelLayouts[self.iWLL]
labels = [layout.itemAt(i).widget() for i in range(layout.count()) if type(layout.itemAt(i).widget()) == QtWidgets.QLabel]
for label in labels:
label.setText("_")
for (char, label) in zip(self.userStr, labels):
label.setText(char)
def colorize(self):
layout = self.wordsLabelLayouts[self.iWLL]
labels = [layout.itemAt(i).widget() for i in range(layout.count()) if type(layout.itemAt(i).widget()) == QtWidgets.QLabel]
for (label, color) in zip(labels, self.colorPatternArr):
label.setStyleSheet(color)
def colorizeKeyboard(self):
for object, color in zip(self.keyboardKeys.values(), self.keyboardStyles.values()):
object.setStyleSheet(color)
def inputWord(self):
if len(self.userStr) == 5:
if self.userStr in wordArr:
return self.userStr
else:
self.warningMessage(title=self.userStr, text="Bu kelime listede yok. Tekrar tahmin yapın.")
self.userStr = ""
self.printWord()
return None
def initApp(self):
self.colorPatternArr = []
mykeydata = keydata(self.ui)
self.keyboardKeys = mykeydata.keyData
self.keyboardStyles = {keyboardLetter: "" for keyboardLetter in self.keyboardKeys.keys()}
self.userStr = ""
self.iWLL = 0 # indice for self.wordsLabelLayouts
self.word = wordArr[randint(0, WORD_COU-1)]
self.attemptCou = 0
self.clear()
def play(self, selectedWord):
global wordArr
if self.inputWord() != None:
if self.checkWord(self.inputWord(), selectedWord):
return True
else:
self.attemptCou += 1
self.iWLL += 1
return False
else:
return None
def checkWord(self, userWord, selectedWord):
self.colorPatternArr = []
self.prohibitedIndexes = []
# Get the number of occurence each letter
letters = defaultdict(int)
for letter in selectedWord:
letters[letter] += 1
for i, (letterUser, letterSelected) in enumerate(zip(userWord, selectedWord)):
if DEBUG:
print(f"{i} {letterUser} {letterSelected}")
if letterUser == letterSelected:
self.colorPatternArr.append("color: rgb(56,118,29)")
self.keyboardStyles[letterUser] = "background-color: rgb(56,118,29)"
letters[letterUser] -= 1
self.prohibitedIndexes.append(i)
else:
self.colorPatternArr.append("color: rgb(54, 51, 51)")
self.keyboardStyles[letterUser] = "background-color: rgb(54, 51, 51)"
for i, (letterUser, letterSelected) in enumerate(zip(userWord, selectedWord)):
if letters[letterUser] > 0 and not (i in self.prohibitedIndexes):
self.colorPatternArr[i] = "color: rgb(241,194,50)"
self.keyboardStyles[letterUser] = "background-color: rgb(241,194,50)"
letters[letterUser] -= 1
self.colorize()
self.colorizeKeyboard()
if selectedWord == userWord:
return True
def infoMessage(self, title="Info", text="Text text"):
msg = QMessageBox()
msg.setWindowTitle(title)
msg.setWindowIcon(QtGui.QIcon('img.png'))
msg.setText(text)
msg.setIcon(QMessageBox.Information)
msg.setStandardButtons(QMessageBox.Ok)
btnOk = msg.button(QMessageBox.Ok)
btnOk.setText("Tamam")
msg.setStyleSheet(STYLE_SHEET_STR)
msg.exec_()
def warningMessage(self, title="Info", text="Text text"):
msg = QMessageBox()
msg.setWindowTitle(title)
msg.setWindowIcon(QtGui.QIcon('img.png'))
msg.setText(text)
msg.setIcon(QMessageBox.Warning)
msg.setStandardButtons(QMessageBox.Ok)
btnOk = msg.button(QMessageBox.Ok)
btnOk.setText("Tamam")
msg.setStyleSheet(STYLE_SHEET_STR)
msg.exec_()
def errorMessage(self, title="Error", text="An error occured"):
msg = QMessageBox()
msg.setWindowTitle(title)
msg.setWindowIcon(QtGui.QIcon('img.png'))
msg.setText(text)
msg.setIcon(QMessageBox.Critical)
msg.setStandardButtons(QMessageBox.Ok)
btnOk = msg.button(QMessageBox.Ok)
btnOk.setText("Tamam")
msg.setStyleSheet(STYLE_SHEET_STR)
msg.exec_()
def confirmationMsg(self, title="Question", text="Are you sure doing xyz?"):
msg = QMessageBox()
msg.setWindowTitle(title)
msg.setWindowIcon(QtGui.QIcon('img.png'))
msg.setText(text)
msg.setIcon(QMessageBox.Question)
msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msg.setDefaultButton(QMessageBox.Yes)
btnYes = msg.button(QMessageBox.Yes)
btnYes.setText("Evet")
btnNo = msg.button(QMessageBox.No)
btnNo.setText("Hayır")
msg.setStyleSheet(STYLE_SHEET_STR)
answer = msg.exec_()
return answer == QMessageBox.Yes
def game(self):
try:
if self.play(self.word):
self.infoMessage(title="Kazandınız", text=f"{self.word} kelimesini başarıyla buldunuz.")
if self.confirmationMsg(title="Wordle", text="Tekrar oynamak ister misiniz?"):
self.initApp()
else:
sys.exit()
elif self.attemptCou < MAX_TRIALS:
self.userStr = ""
elif self.attemptCou >= MAX_TRIALS:
self.errorMessage(title="Kaybettiniz", text=f"Seçilen kelime: {self.word} idi.")
if self.confirmationMsg(title="Wordle", text="Tekrar oynamak ister misiniz?"):
self.initApp()
else:
sys.exit()
except Exception as ex:
self.errorMessage(text=str(ex))
def app():
app = QtWidgets.QApplication(sys.argv)
app.setStyle('Fusion')
win = myWindow()
win.show()
sys.exit(app.exec_())
if __name__ == "__main__":
app()