-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.py
165 lines (128 loc) · 5.19 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
import tkinter as tk
import random
import time
import socket
import keyboard
import datetime
class MatrixDrawer:
def __init__(self, master, matrix, max_score, score):
self.master = master
self.matrix = matrix
self.max_score = max_score
self.score = score
self.cell_size = 20
self.colors = ['white', 'red', 'blue', 'green']
self.score_label = tk.Label(master, text=f"Score: {self.score}")
self.score_label.pack()
self.max_score_label = tk.Label(master, text=f"Max Score: {self.max_score}")
self.max_score_label.pack()
self.canvas = tk.Canvas(master, width=len(matrix[0]) * self.cell_size, height=len(matrix) * self.cell_size)
self.canvas.pack()
self.draw_matrix()
self.calculate_score()
def set_matrix(self, new_matrix, new_max_score, new_score):
self.matrix = new_matrix
self.max_score = new_max_score
self.score = new_score
self.draw_matrix()
self.calculate_score()
def calculate_score(self):
self.score_label.config(text=f"Score: {self.score}")
self.max_score_label.config(text=f"Max Score: {self.max_score}")
def draw_matrix(self):
self.canvas.delete("all")
for i, row in enumerate(self.matrix):
for j, value in enumerate(row):
x1, y1 = j * self.cell_size, i * self.cell_size
x2, y2 = x1 + self.cell_size, y1 + self.cell_size
color = self.colors[value]
self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline='black')
def string_to_matrix(matrix_str):
"""
Преобразует строку в двумерный массив matrix.
Каждая строка строки представляет собой строку чисел, разделенных пробелами.
Строки разделены символом новой строки.
"""
rows = matrix_str.strip().split("\n")
matrix = [list(map(int, row.split())) for row in rows]
return matrix
def check_arrow_key_pressed():
if keyboard.is_pressed('up'):
return '1'
elif keyboard.is_pressed('down'):
return '2'
elif keyboard.is_pressed('left'):
return '3'
elif keyboard.is_pressed('right'):
return '4'
else:
return "5"
def recv_splitter(recv_string):
splited_string = recv_string.split(';')
return splited_string[0], splited_string[1], splited_string[2]
def start_game_screen():
# Создаем окно
start_root = tk.Tk()
start_root.title("Game Start")
# Переменная, которая будет установлена в True при начале игры
game_started = False
# Функция, вызываемая при нажатии на кнопку "Start"
def start_game():
nonlocal game_started
game_started = True
start_root.destroy() # Закрываем окно старта
# Создаем кнопку "Start"
button_start = tk.Button(start_root, text="Start", command=start_game)
button_start.pack()
# Запускаем цикл обработки событий Tkinter
start_root.wait_window()
return game_started
def endgame(root, score, maxscore, current_datetime):
for widget in root.winfo_children():
widget.destroy()
root.title("Game Over")
label_score = tk.Label(root, text=f"Score: {score}")
label_score.pack()
label_max_score = tk.Label(root, text=f"Max Score: {maxscore}")
label_max_score.pack()
label_datetime = tk.Label(root, text=f"Date and Time: {current_datetime}")
label_datetime.pack()
def exit_program():
root.destroy()
button_exit = tk.Button(root, text="Exit", command=exit_program)
button_exit.pack()
root.mainloop()
if __name__ == "__main__":
myIp = '127.0.0.1'
port = 11000
sock = socket.socket()
sock.connect((myIp, port))
print("Connected")
start_game_screen()
root = tk.Tk()
matrix_size = (20, 10)
data = sock.recv(1024).decode()
matrix, score, max_score = recv_splitter(data)
matrix = string_to_matrix(matrix)
print(matrix)
sock.send(bytes("1", encoding='utf-8'))
app = MatrixDrawer(root, matrix, max_score, score)
game_alive = True
current_datetime = ""
# Start the Tkinter main loop
while game_alive == True:
data = sock.recv(1024).decode()
if data == "101":
endgame(root, score, max_score, current_datetime)
game_alive = False
else:
matrix, score, max_score = recv_splitter(data)
matrix = string_to_matrix(matrix)
print(matrix)
app.set_matrix(matrix, score, max_score)
current_datetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Обновление главного окна Tkinter
root.update_idletasks()
root.update()
sended = check_arrow_key_pressed()
sock.send(bytes(sended, encoding='utf-8'))