-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
209 lines (165 loc) · 7.83 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
# -*- coding: utf-8 -*-
"""Contact main.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1W8fxdH9rn_2XE_PVSGAw_25YVnpF7Xpg
"""
# Libraries
import gensim
from gensim.models import word2vec
import pickle
import random
import editdistance
# Documents
!gdown 1OZ6Mx7SInm_G1nb620a8_FLR4gLMEq5l # downloads our trained model from google drive, only works on private drive unfortunately.
model_300 = gensim.models.Word2Vec.load('wiki_tr.embedding_300') # loads the model
!gdown 1OTBfHZ0wEsAUrrrOxFGSnkAuWvk8IHE6 # loads the sorted_lemmas.pkl from google drive
with open("/content/sorted_lemmas.pkl", "rb") as file:
sorted_lemmas = pickle.load(file)
def get_candidates(given_letters):
""" The function generates to candidate words according to the given letters. """
candidate_words = [[word, value] for word, value in sorted_lemmas if word.startswith(given_letters)]
if not candidate_words:
user_word = input("Üzgünüm, verdiğin harflerle başlayan bir kelime bulamadım. Kelimen neydi?")
for word, count in sorted_lemmas:
potential_words = []
if editdistance.distance(word, user_word) == 1:
potential_words.append(word)
if len(potential_words) < 20:
print("Kelimen bunlardan biri olabilir mi acaba? Belki yanlış yazmış olabilirsin. \n")
print(potential_words)
user_feedback = input("Kelimen bunlardan biri miydi?: (E/H)").lower
if user_feedback == "e":
print("O zaman ben kazandım.")
play_again(computer_guess, used_words, difficulty)
break
elif user_feedback == 'h':
print("Tebrik ederim! Oyunu sen kazandın!")
play_again(computer_guess, used_words, difficulty)
break
return candidate_words
def pick_candidate(candidate_words, difficulty, used_words):
""" The function picks a guess word from the candidate words list, based on the difficulty level. """
candidates = []
for candidate, count in candidate_words:
if candidate not in used_words:
candidates.append(candidate)
if difficulty < 2:
computer_guess = candidates[0]
elif difficulty == 2:
computer_guess = candidates[-1]
return computer_guess
def find_similar_word(computer_guess):
""" The function finds candidate similar words using the model"""
similar_words = model_300.wv.similar_by_word(computer_guess, topn=5)
candidate_similars = []
for similar_word, similarity in similar_words:
if similarity >= 0.65:
candidate_similars.append(similar_word)
return candidate_similars
def pick_similar_word(candidate_similars, used_words):
""" The function picks a similar word from the candidate similar words. Also, it filters the previous picked similars """
similars = []
for similar_word in candidate_similars:
if similar_word not in used_words:
similars.append(similar_word)
if not similars:
return None
final_similar = similars[0]
return final_similar
def generate_question(final_similar, computer_guess):
""" The function generates a question and asks it to the user. """
question = f"Bu {final_similar} ile ilişkili ya da ona yakın bir şey mi?"
return question
def get_letter(given_letters):
"""
The function gets a letter from the user and adds the given letter to the given letters.
It keeps iterating until a valid letter from A to Z is provided.
"""
fresh_letter = input("Haydi bana bir sonraki harfi söyle: ").lower().strip()
while not fresh_letter or not fresh_letter.isalpha() or len(fresh_letter) != 1:
fresh_letter = input("Bana bir harf söylemelisin (A-Z): ").lower().strip()
given_letters += fresh_letter
return given_letters
def get_difficulty_level():
"""The function gets the difficulty level from the user (1, or 2)"""
while True:
difficulty = input("Kolaydan zora bir zorluk seviyesi seçin: (1 ya da 2). : ")
if difficulty in ["1", "2"]:
return int(difficulty)
print("Geçersiz zorluk seviyesi. Lütfen sadece 1'den 2'ye kadar bir rakam girin.")
def get_user_guess(prompt, guess_attempts, computer_guess):
"""The function ges user_guess within a limited number of attempts.
It also gives clues like "You are very close!" when the user_guess is one letter away from the computer_guess or the computer_guess starts with the user_guess.
It also reminds the user the number of attempts left"""
for attempt in range(guess_attempts):
print(f"{guess_attempts - attempt} tahmin hakkınız kaldı.")
user_guess = input(prompt).lower()
if user_guess == computer_guess:
return user_guess
elif computer_guess.startswith(user_guess) and len(user_guess) > 5:
print("Çok yaklaştın!")
elif editdistance.distance(user_guess, computer_guess) == 1:
print("Çok yaklaştın!")
else:
print("Yanlış tahmin. Başka bir harfle dene.")
return False
def play_again(computer_guess, used_words, difficulty):
"""
Asks the user if they want to play again.
If yes, starts a new game loop.
If no, displays a farewell message.
"""
again = input("Tekrar oynamak ister misin? (E/H)")
if again.lower() == "e":
given_letters = input("O zaman haydi tekrar bir kelime tut ve ilk harfini söyle.: ")
print("Uyarı: Önceki turdaki kelimeleri dahil etmek ya da zorluk seviyesini değiştirmek istersen oyunu kapatıp açabilirsin.")
game_loop(given_letters, computer_guess, used_words, difficulty) # Recursive call to start a new game loop
else:
print("Pekala o zaman iyi günler!")
def game_loop(given_letters, computer_guess, used_words, difficulty):
"""The function iterates over the game if the user wants to continue."""
guess_attempts = 10 if difficulty == 1 else 5
while True:
candidates = get_candidates(given_letters)
computer_guess = pick_candidate(candidates, difficulty, used_words)
used_words.append(computer_guess)
#print("Computer guess:", computer_guess)
#print("used_words", used_words)
similar_words = find_similar_word(computer_guess)
similar_word = pick_similar_word(similar_words, used_words)
if similar_word is None:
print("Üzgünüm, düşündüğüm kelimeyi çağrıştıracak bir kelime bulamadım.")
play_again(computer_guess, used_words, difficulty)
break
used_words.append(similar_word)
#print("used words after similars", used_words)
question = generate_question(similar_word, computer_guess)
user_guess = get_user_guess(question, guess_attempts, computer_guess)
if user_guess == computer_guess:
print("Tebrikler! Kelimemi doğru tahmin ettin. Kazandın!")
continue
elif user_guess != computer_guess or user_guess == False or user_guess == None:
print(f"Aklımdan geçen kelime {computer_guess} idi. \n")
user_feedback = input("Kelimen bu muydu?: (E/H)").lower()
if user_feedback == "e":
print("Öyleyse ben kazandım!")
play_again(computer_guess, used_words, difficulty)
return
elif user_feedback == "h":
given_letters = get_letter(given_letters)
guess_attempts = 10 if difficulty == 1 else 5
continue
def play_contact():
""" Initiates the game """
print("Kontakt'a hoşgeldin!")
computer_guess = ''
user_word = ''
given_letters = input("Hazırsan başlayalım. Haydi bir kelime tut ve ilk harfini söyle: ")
difficulty = get_difficulty_level()
used_words = []
game_loop(given_letters, computer_guess, used_words, difficulty)
play_contact()
#control groups for some functions
#print(find_similar_word("parti"))
#print(get_candidates("liber"))