forked from gabriellerosa/rede2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
226 lines (164 loc) · 6.28 KB
/
client.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
import socket
import os
import pickle
import inquirer
import unicodedata
import time
from rich.console import Console
from rich.text import Text
import rich.spinner as spinner
from rich import box
from rich.table import Table
from termcolor import colored
from config import *
console = Console()
wordle = '[green]W[yellow]O[white]R[green]D[yellow]L[white]E'
selected_difficulty = None
def remove_accents(word):
return unicodedata.normalize('NFKD', word).encode('ASCII', 'ignore').decode()
def show_table(board, secret_word):
print('\n\n')
table = Table(
show_header=False,
title=wordle,
box=box.SQUARE,
show_lines=True,
)
freq = {}
for letter in secret_word:
freq[letter] = freq.get(letter, 0) + 1
for tried_word in board:
freq_c = freq.copy()
validated_word = list()
for i in range(len(tried_word)):
color = 'white'
# Se a dificuldade for média, compara-se as letras ignorando os acentos
if selected_difficulty == 'Média':
if (remove_accents(tried_word[i]) == remove_accents(secret_word[i])):
color = 'green'
freq_c[tried_word[i]] -= 1
else:
if (tried_word[i] == secret_word[i]):
color = 'green'
freq_c[tried_word[i]] -= 1
validated_word.append({
'letter': tried_word[i],
'color': color
})
for i in range(len(tried_word)):
color = 'white'
# Se a dificuldade for média, compara-se as letras ignorando os acentos
if selected_difficulty == 'Média':
if (remove_accents(tried_word[i]) != remove_accents(secret_word[i]) and remove_accents(tried_word[i]) in remove_accents(secret_word) and freq_c[tried_word[i]]):
validated_word[i]['color'] = 'yellow'
freq_c[tried_word[i]] -= 1
else:
if (tried_word[i] != secret_word[i] and tried_word[i] in secret_word) and freq_c[tried_word[i]]:
validated_word[i]['color'] = 'yellow'
freq_c[tried_word[i]] -= 1
table.add_row(
*[
Text(
letter['letter'],
style='bold ' + letter['color']
)
for letter in validated_word
],
)
for i in range(len(board), 6):
table.add_row(*[f" " for letter in secret_word])
console.print(table, justify='center')
print('\n\n')
def clearConsole():
command = 'clear'
# Verifica se o sistema operacional é Windows
if os.name in ('nt', 'dos'):
command = 'cls'
os.system(command)
# Cria um socket TCP/IP
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Conecta o socket no host e porta especificados
try:
with console.status('[bold green]Conectando-se ao servidor...') as status:
spinner = spinner.Spinner('line')
for _ in range(10):
spinner.update()
time.sleep(0.1)
socket.connect((HOST, PORT))
console.log(
'[bold green]Conexão estabelecida com o servidor! :white_check_mark:')
time.sleep(1)
except ConnectionRefusedError:
console.log('O servidor não está rodando!', style='bold red')
exit()
while True:
clearConsole()
# Mensagem recebida do servidor
received_message = socket.recv(BUFF_SIZE)
# Carrega o dicionario usando pickle.loads()
received_message = pickle.loads(received_message)
msg_type = received_message['type']
# Dicionário que será enviado ao servidor
message = dict()
message['type'] = ''
message['content'] = ''
# Escolha de nickname
if (msg_type == 'nickname_selection'):
console.print('Bem vindo ao ' + wordle + '!\n')
print('Escolha um nickname para começar a jogar!\n')
nickname = input('Nickname: ')
message['type'] = 'nickname_selection'
message['content'] = nickname
# Escolha de dificuldade
elif (msg_type == 'difficulty_selection'):
questions = [inquirer.List(
'difficulty',
message=received_message['content'],
choices=['Médio', 'Difícil'],
carousel=True
)]
selected_difficulty = inquirer.prompt(questions)['difficulty']
colored_difficulty = colored(
selected_difficulty,
'green' if selected_difficulty == 'Médio'
else 'red'
)
print('Você escolheu a dificuldade ' + colored_difficulty + '!\n')
message['type'] = 'difficulty_selection'
message['content'] = selected_difficulty
# Tentativa de adivinhação
elif (msg_type == 'guess'):
show_table(received_message['board'], received_message['secret_word'])
print()
guess = input('Sua tentativa: ').strip().replace(' ', '').upper()
message['type'] = 'guess'
message['content'] = guess
# Resultado da tentativa
elif (msg_type == 'guess_result'):
show_table(received_message['board'], received_message['secret_word'])
print()
if (received_message['content']['game_over']):
if (not received_message['content']['winner']):
console.print('Suas tentativas se esgorataram! :disappointed:',
justify='center', style='bold red')
console.print(
'A palavra era: [bold green]' + received_message['secret_word'], justify='center')
else:
console.print('Parabéns, você acertou! :tada: :tada: :smiley:',
justify='center', style='bold green')
print('\n\n')
message['type'] = 'game_over'
message['content'] = ''
message = pickle.dumps(message)
socket.send(message)
break
console.print(
received_message['content']['message'], justify='center', style='bold red')
print('\n\n')
guess = input('Sua tentativa: ')
guess = guess.strip().replace(' ', '').upper()
message['type'] = 'guess'
message['content'] = guess
# Envia a mensagem ao servidor
message = pickle.dumps(message)
socket.send(message)