def testAddConnectionsAfterMsgSrc(self): # message source with no messages msgSrcEmpty = MsgSrc(self.conns) # pylint: disable=unused-variable msgSrc = MsgSrc(self.conns) msgSrc.setMsgs([ Jmai([1], initiatorWs=clientWs3), Jmai([2], initiatorWs=clientWs3) ]) self.assertGiTxQueueMsgs(self.txq, []) # Add websockets afterwards conns1 = Connections(self.txq) conns2 = Connections(self.txq) conns2.addConn(clientWs2) self.conns.addConnections(conns1) self.assertGiTxQueueMsgs(self.txq, []) self.conns.addConnections(conns2) self.assertGiTxQueueMsgs(self.txq, [ ClientTxMsg([1], {clientWs2}, initiatorWs=clientWs3), ClientTxMsg([2], {clientWs2}, initiatorWs=clientWs3) ]) conns1.addConn(clientWs1) self.assertGiTxQueueMsgs(self.txq, [ ClientTxMsg([1], {clientWs1}, initiatorWs=clientWs3), ClientTxMsg([2], {clientWs1}, initiatorWs=clientWs3) ])
def updateTotal(self): self._score = {teamId: 0 for teamId in self._teamIds} for turnWords in self._wordsByTurnId.values(): for word in turnWords: for teamId in word.score: self._score[teamId] += 1 self.setMsgs([Jmai(["SCORE", self._score], None)])
def _updateMsgSrc(self): self.playerStatusMsgSrc.setMsgs([ Jmai([ "PLAYER-STATUS", self.name, { "numConns": self.numConns(), "ready": self.ready, "turnsPlayed": self.turnsPlayed, } ], None), ])
def updateMsgs(self): """Figures out what messages to send to who based on internal state""" if self._state == WordState.IN_PLAY: assert self._privateMsgSrc msg1 = [ "TURN", self._turnId, self._wordId, { "team": self._player.team.teamNumber, "player": self._player.name, "state": self._state.name, "utcTimeout": self._utcTimeout } ] self._publicMsgSrc.setMsgs([Jmai(msg1, None)]) msg2 = msg1[:] # make a copy of msg1 msg2[3] = dict( msg1[3]) # Make a copy of the dict (and don't update # the dictionary in msg1) msg2[3].update({ "secret": self._secret, "disallowed": self._disallowed, }) self._privateMsgSrc.setMsgs([Jmai(msg2, None)]) return # If the turn isn't in play, there is no private messaging needed. if self._privateMsgSrc: self._privateMsgSrc.setMsgs([]) # Reset previous messages self._privateMsgSrc = None msg = [ "TURN", self._turnId, self._wordId, { "team": self._player.team.teamNumber, "player": self._player.name, "state": self._state.name, "secret": self._secret, "disallowed": self._disallowed, "score": self._score } ] self._publicMsgSrc.setMsgs([Jmai(msg, None)])
def testAddDelConnections(self): conns1 = Connections(self.txq) conns1.addConn(clientWs1) conns2 = Connections(self.txq) conns2.addConn(clientWs2) self.conns.addConnections(conns1) self.conns.addConnections(conns2) msgSrc = MsgSrc(self.conns) msgSrc.setMsgs([ Jmai([1], initiatorWs=clientWs3), Jmai([2], initiatorWs=clientWs3) ]) self.assertGiTxQueueMsgs(self.txq, [ ClientTxMsg([1], {clientWs1}, initiatorWs=clientWs3), ClientTxMsg([1], {clientWs2}, initiatorWs=clientWs3), ClientTxMsg([2], {clientWs1}, initiatorWs=clientWs3), ClientTxMsg([2], {clientWs2}, initiatorWs=clientWs3) ], anyOrder=True) self.conns.delConnections(conns1) clientWs4 = 104 conns3 = Connections(self.txq) conns3.addConn(clientWs3) conns3.addConn(clientWs4) self.conns.addConnections(conns3) self.assertGiTxQueueMsgs(self.txq, [ ClientTxMsg([1], {clientWs3, clientWs4}, initiatorWs=clientWs3), ClientTxMsg([2], {clientWs3, clientWs4}, initiatorWs=clientWs3) ], anyOrder=True)
def _gameOver(self): trace(Level.game, "Game Over") self.state = GameState.GAME_OVER # Update self._winnerTeamIds scoreByTeamId = self.turnMgr.totalScore maxScore = max(scoreByTeamId.values()) self._winnerTeamIds = [teamId for teamId, score in scoreByTeamId.items() if score == maxScore] self.gameOverMsgSrc.setMsgs([ Jmai(["GAME-OVER", self._winnerTeamIds], None), ]) self.publishGiStatus()
def updateState(self, newState): if self._state == newState: return self._state = newState if newState == TurnMgrState.KICKOFF_WAIT: self._waitForKickoffMsgSrc.setMsgs([ Jmai([ "WAIT-FOR-KICKOFF", self._curTurnId, self._activePlayer.name ], None), ]) else: self._waitForKickoffMsgSrc.setMsgs([])
def _updateMsgSrc(self): self.teamStatusMsgSrc.setMsgs([ Jmai(["TEAM-STATUS", self.teamNumber, list(self.members)], None), ])
def __init__(self, conns, hostParameters): super(HostParametersMsgSrc, self).__init__(conns) self.hostParameters = hostParameters self.setMsgs( [Jmai(["HOST-PARAMETERS"] + self.hostParameters.toJmsg(), None)])
def broadcast(self, jmsg, initiatorWs=None): """Send a message to all clients of a Plugin""" self.conns.send([Jmai(jmsg, initiatorWs)])
def test1MsgSrc1Websocket(self): """ Try various triggers of adding/removing MsgSrcs and Websockets """ self.assertGiTxQueueMsgs(self.txq, []) # Adding connections doesn't create a message self.conns.addConn(clientWs1) self.assertGiTxQueueMsgs(self.txq, []) # Adding msgSrc with no messages msgSrc1 = MsgSrc(self.conns) self.assertGiTxQueueMsgs(self.txq, []) # Set messages in msgSrc msgSrc1.setMsgs([ Jmai([1], initiatorWs=clientWs3), Jmai([2], initiatorWs=clientWs3) ]) self.assertGiTxQueueMsgs(self.txq, [ ClientTxMsg([1], {clientWs1}, initiatorWs=clientWs3), ClientTxMsg([2], {clientWs1}, initiatorWs=clientWs3) ]) # Adding msgSrc with previous messages msgSrc2 = MsgSrc(self.conns) msgSrc2.setMsgs( [Jmai([True], initiatorWs=None), Jmai([False], initiatorWs=None)]) self.assertGiTxQueueMsgs(self.txq, [ ClientTxMsg([True], {clientWs1}), ClientTxMsg([False], {clientWs1}) ]) # Adding a second connection self.conns.addConn(clientWs2) self.assertGiTxQueueMsgs(self.txq, [ ClientTxMsg([1], {clientWs2}, initiatorWs=clientWs3), ClientTxMsg([2], {clientWs2}, initiatorWs=clientWs3), ClientTxMsg([True], {clientWs2}, initiatorWs=None), ClientTxMsg([False], {clientWs2}, initiatorWs=None) ], anyOrder=True) # Adding msgSrc with state preset msgSrc2.setMsgs([Jmai(["yes"], initiatorWs=None)]) self.assertGiTxQueueMsgs( self.txq, [ClientTxMsg(["yes"], {clientWs1, clientWs2})]) # Delete msgSrc self.conns.delMsgSrc(msgSrc2) # Add another client self.conns.addConn(clientWs3) self.assertSetEqual(self.conns.msgSrcs, {msgSrc1}) self.assertGiTxQueueMsgs(self.txq, [ ClientTxMsg([1], {clientWs3}, initiatorWs=clientWs3), ClientTxMsg([2], {clientWs3}, initiatorWs=clientWs3) ], anyOrder=True) # Remove a client self.conns.delConn(clientWs2) self.assertGiTxQueueMsgs(self.txq, []) # Add msgSrc2 again self.conns.addMsgSrc(msgSrc2) self.assertGiTxQueueMsgs( self.txq, [ClientTxMsg(["yes"], {clientWs1, clientWs3}, initiatorWs=None)], anyOrder=True)
def processEvent(self, event): trace(Level.game, "processEvent", str(event), "in state", self.gameState) if isinstance(event, PlayerJoin): # A new player has joined assert isinstance(self.gameState, StateWaitingForPlayers) if len(self.playerByName) == self.hostParameters.numPlayers: self.processEvent(GameBegin()) return # Waiting for more players self.publishGiStatus() return if isinstance(event, GameBegin): assert isinstance(self.gameState, StateWaitingForPlayers) self.startGame() self.gameState = StateGameBegin() turnOrderNames = list(self.playerByName) random.shuffle(turnOrderNames) self.processEvent(StartRound(1, turnOrderNames, 0)) return if isinstance(event, StartRound): assert isinstance(self.gameState, (StateGameBegin, StateRoundStop)) self.gameState = StateRoundStart() self.newRound(event) self.gameState = StatePlayerTurn() self.publishGiStatus() return if isinstance(event, AdvanceTurn): self.currRound.turn.advance(event) return if isinstance(event, StopRound): assert isinstance(self.gameState, StatePlayerTurn) self.gameState = StateRoundStop() # Stop the current round (mark it as round-over) so that # irrelevant notifications are not sent out self.currRound.makeRoundOver() # Check if the end of game limit is hit. Trigger # GameOver in which case totalScore = self.totalScore() maxScore = max(totalScore.values()) if maxScore >= self.hostParameters.stopPoints: self.processEvent(GameOver()) return # Else, start a new round self.processEvent( StartRound(self.currRound.roundNum + 1, self.currRound.turn.playerNameInTurnOrder, turnIdx=(self.currRound.turn.turnIdx + 1) % self.hostParameters.numPlayers)) return if isinstance(event, GameOver): assert isinstance(self.gameState, StateRoundStop) self.gameState = StateGameOver() self.publishGiStatus() totalScore = self.totalScore() lowestScore = min(totalScore.values()) winners = [ name for name, score in totalScore.items() if score == lowestScore ] jmsg = ["GAME-OVER", winners] self.winners.setMsgs([Jmai(jmsg, initiatorWs=None)]) return if isinstance(event, Declare): assert isinstance(self.gameState, StatePlayerTurn) self.currRound.declare( event) # calculate points based on declaring self.processEvent(StopRound(self.currRound.roundParams.roundNum)) return trace(Level.error, "Invalid event received", str(event)) assert False
def setPostInitParams(self, conns): assert not self.msgSrc self.msgSrc = MsgSrc(conns) # Set the message to be sent to all clients in conns self.msgSrc.setMsgs( [Jmai(["HOST-PARAMETERS", dict(self.state)], None)])