A user should never reach into another user directly. When a user wants to talk, it asks the mediator to do the work. This is the heart of the pattern: the User is decoupled from every other User and only knows about its room.
Implement User.send(message). It must ask the room to broadcast the message on this user's behalf, passing this user as the sender.
Because broadcast already skips the sender, calling send delivers the message to everyone else and never back to the caller.
class User:
def __init__(self, name):
self.name = name
self.inbox = []
self.room = None
def send(self, message):
"""Ask the room to broadcast this message on the user's behalf."""
# TODO: call self.room.broadcast with this user as the sender
pass
class ChatRoom:
def __init__(self):
self.users = []
def register(self, user):
self.users.append(user)
user.room = self
def broadcast(self, sender, message):
for user in self.users:
if user is not sender:
user.inbox.append(message)
The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
A user should never reach into another user directly. When a user wants to talk, it asks the mediator to do the work. This is the heart of the pattern: the User is decoupled from every other User and only knows about its room.
Implement User.send(message). It must ask the room to broadcast the message on this user's behalf, passing this user as the sender.
Because broadcast already skips the sender, calling send delivers the message to everyone else and never back to the caller.
Press Run Tests or ββ© to check your solution.