forked from rperson/hockey-team-selection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhockey_team_balancer_gui.py
More file actions
289 lines (202 loc) · 6.36 KB
/
hockey_team_balancer_gui.py
File metadata and controls
289 lines (202 loc) · 6.36 KB
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import pandas as pd
import random
from dataclasses import dataclass
from copy import deepcopy
import tkinter as tk
from tkinter import filedialog, messagebox
# -----------------------------
# Player Class
# -----------------------------
@dataclass
class Player:
name: str
rank: int
position: str
# -----------------------------
# Config
# -----------------------------
FORWARDS_TARGET = 6
DEFENCE_TARGET = 4
ITERATIONS = 7000
TEAM_A_NAME = "Light Team"
TEAM_B_NAME = "Dark Team"
TEAM_A_JERSEY = "LIGHT"
TEAM_B_JERSEY = "DARK"
OUTPUT_FILE = "game_night_teams.xlsx"
# -----------------------------
# Helpers
# -----------------------------
def is_selected(value):
if pd.isna(value):
return False
return str(value).strip().upper() in ["TRUE", "1", "YES", "Y"]
def empty_team():
return {"F": [], "D": [], "total": 0}
def can_add(team, pos):
if pos == "F":
return len(team["F"]) < FORWARDS_TARGET
if pos == "D":
return len(team["D"]) < DEFENCE_TARGET
return False
def assign_player(team, player, pos):
team[pos].append(player)
team["total"] += player.rank
# -----------------------------
# Core Optimizer
# -----------------------------
def attempt_build(players_list):
random.shuffle(players_list)
team_a = empty_team()
team_b = empty_team()
for player in players_list:
options = []
for team in [team_a, team_b]:
if player.position == "F":
if can_add(team, "F"):
options.append((team, "F"))
elif player.position == "D":
if can_add(team, "D"):
options.append((team, "D"))
else: # FLEX
if can_add(team, "F"):
options.append((team, "F"))
if can_add(team, "D"):
options.append((team, "D"))
if not options:
options = [
(team_a, "F"),
(team_b, "F"),
(team_a, "D"),
(team_b, "D")
]
best_move = None
best_diff = float("inf")
for team, pos in options:
proj_a = team_a["total"]
proj_b = team_b["total"]
if team == team_a:
proj_a += player.rank
else:
proj_b += player.rank
diff = abs(proj_a - proj_b)
if diff < best_diff:
best_diff = diff
best_move = (team, pos)
assign_player(best_move[0], player, best_move[1])
return team_a, team_b
# -----------------------------
# Run Full Build
# -----------------------------
def build_teams(input_file):
df = pd.read_excel(input_file)
required_columns = {"Selected", "Name", "Rank", "Position"}
if not required_columns.issubset(df.columns):
raise ValueError("Excel must contain Selected, Name, Rank, Position")
players = []
for _, row in df.iterrows():
if not is_selected(row["Selected"]):
continue
players.append(
Player(
name=row["Name"],
rank=int(row["Rank"]),
position=row["Position"].strip().upper()
)
)
if len(players) < 10:
raise ValueError("Not enough selected players")
best = None
best_diff = float("inf")
for _ in range(ITERATIONS):
a, b = attempt_build(players.copy())
diff = abs(a["total"] - b["total"])
if diff < best_diff:
best_diff = diff
best = (deepcopy(a), deepcopy(b))
if best_diff == 0:
break
return best[0], best[1], best_diff
# -----------------------------
# Export Workbook
# -----------------------------
def export_workbook(team_a, team_b, diff):
def build_df(team, jersey):
rows = []
for pos in ["F", "D"]:
for p in team[pos]:
rows.append({
"Name": p.name,
"Rank": p.rank,
"Position": pos,
"Jersey": jersey
})
return pd.DataFrame(rows)
df_light = build_df(team_a, TEAM_A_JERSEY)
df_dark = build_df(team_b, TEAM_B_JERSEY)
summary = {
"Metric": [
"Light Team Total Rank",
"Dark Team Total Rank",
"Skill Difference"
],
"Value": [
team_a["total"],
team_b["total"],
diff
]
}
df_summary = pd.DataFrame(summary)
with pd.ExcelWriter(OUTPUT_FILE, engine="openpyxl") as writer:
df_light.to_excel(writer, sheet_name=TEAM_A_NAME, index=False)
df_dark.to_excel(writer, sheet_name=TEAM_B_NAME, index=False)
df_summary.to_excel(writer, sheet_name="Summary", index=False)
# -----------------------------
# GUI
# -----------------------------
def select_file():
file_path = filedialog.askopenfilename(
filetypes=[("Excel Files", "*.xlsx")]
)
if file_path:
file_label.config(text=file_path)
generate_button.config(state="normal")
def generate_teams():
try:
input_file = file_label.cget("text")
team_a, team_b, diff = build_teams(input_file)
export_workbook(team_a, team_b, diff)
status_label.config(
text=f"✔ Teams Created Successfully!\nSkill Difference: {diff}",
fg="green"
)
messagebox.showinfo(
"Success",
f"Workbook created:\n{OUTPUT_FILE}"
)
except Exception as e:
status_label.config(text="❌ Error Occurred", fg="red")
messagebox.showerror("Error", str(e))
# -----------------------------
# Build Window
# -----------------------------
root = tk.Tk()
root.title("Hockey Team Balancer")
root.geometry("460x300")
root.resizable(False, False)
title = tk.Label(root, text="🏒 Hockey Team Balancer", font=("Arial", 16, "bold"))
title.pack(pady=10)
select_button = tk.Button(root, text="Select Excel File", command=select_file, width=25)
select_button.pack(pady=5)
file_label = tk.Label(root, text="No file selected", wraplength=420)
file_label.pack(pady=5)
generate_button = tk.Button(
root,
text="Generate Balanced Teams",
command=generate_teams,
width=25,
state="disabled"
)
generate_button.pack(pady=15)
status_label = tk.Label(root, text="", font=("Arial", 11))
status_label.pack(pady=10)
root.mainloop()