Skip to content

Commit 574982d

Browse files
committed
Refactor (simplify) define_wizards_schedule
1 parent fc6f5f4 commit 574982d

File tree

1 file changed

+20
-17
lines changed

1 file changed

+20
-17
lines changed

src/pycamp_bot/commands/wizard.py

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import random
22
from collections import defaultdict
33
from datetime import datetime, timedelta
4-
4+
from itertools import cycle
55
from telegram.ext import CommandHandler
66
from telegram.error import BadRequest
77
from pycamp_bot.models import Pycampista, WizardAtPycamp
@@ -75,24 +75,27 @@ def define_wizards_schedule(pycamp):
7575
Returns a dict whose keys are times and values are wizards (Pycampistas instances).
7676
7777
"""
78-
slots_list = compute_wizards_slots(pycamp)
79-
wizards_list = pycamp.get_wizards()
80-
n_wizards = wizards_list.count()
78+
all_wizards = pycamp.get_wizards()
79+
if all_wizards.count() == 0:
80+
return {}
81+
8182
wizard_per_slot = {}
82-
idx = 0
83-
for slot in slots_list:
84-
wizard = wizards_list[idx%n_wizards]
85-
n_iter = 0 # railguard
86-
while wizard.is_busy(*slot):
87-
logger.info('Magx {} con conflicto en el slot {}. Pruebo otro.'.format(wizard.username, slot))
88-
if n_iter == n_wizards:
89-
logger.warning('Queda el magx {} con conflicto en el slot {}'.format(wizard, slot))
90-
break
91-
idx += 1
92-
wizard = wizards_list[idx%n_wizards]
93-
n_iter += 1
83+
wizards_iter = cycle(all_wizards)
84+
for slot in compute_wizards_slots(pycamp):
85+
# Cycle through the wizards, asigning them to slots.
86+
wizard = next(wizards_iter)
87+
if wizard.is_busy(*slot):
88+
# If the target wizard is busy in this time slot, try to find another available wizard
89+
if all(w.is_busy(*slot) for w in all_wizards):
90+
# Nada que hacer, todos ocupados. Queda
91+
logger.warning(
92+
'Queda el magx {} con conflicto en el slot {}'.format(wizard.username, slot)
93+
)
94+
else:
95+
# Sigo hasta el próximo que esté disponible
96+
continue
9497
wizard_per_slot[slot] = wizard
95-
idx += 1
98+
9699
return wizard_per_slot
97100

98101

0 commit comments

Comments
 (0)