diff src/plugins/plugin_misc_tarot.py @ 878:36c6495d86b0

plugin card_game: update to use the new XMLUI mechanism: TODO: the new round is not starting after the scores have been displayed
author souliane <souliane@mailoo.org>
date Wed, 26 Feb 2014 02:17:43 +0100
parents 8f335c03eebb
children 1a759096ccbd
line wrap: on
line diff
--- a/src/plugins/plugin_misc_tarot.py	Wed Feb 26 02:13:29 2014 +0100
+++ b/src/plugins/plugin_misc_tarot.py	Wed Feb 26 02:17:43 2014 +0100
@@ -21,9 +21,11 @@
 from logging import debug, info, warning, error
 from twisted.words.xish import domish
 from twisted.words.protocols.jabber import jid
+from twisted.internet import defer
 from wokkel import data_form
 
-from sat.tools.xml_tools import dataForm2XMLUI
+from sat.memory import memory
+from sat.tools import xml_tools
 from sat_frontends.tools.games import TarotCard
 from time import time
 import random
@@ -53,6 +55,7 @@
 
     def __init__(self, host):
         info(_("Plugin Tarot initialization"))
+        self._sessions = memory.Sessions()
         self.inheritFromRoomGame(host)
         RoomGame._init_(self, host, PLUGIN_INFO, (NS_CG, CG_TAG),
                           game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None},
@@ -61,7 +64,6 @@
         host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self.prepareRoom)  # args: players, room_jid, profile
         host.bridge.addMethod("tarotGameCreate", ".plugin", in_sign='sass', out_sign='', method=self.createGame)  # args: room_jid, players, profile
         host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self.playerReady)  # args: player, referee, profile
-        host.bridge.addMethod("tarotGameContratChoosed", ".plugin", in_sign='ssss', out_sign='', method=self.contratChoosed)  # args: player, referee, contrat, profile
         host.bridge.addMethod("tarotGamePlayCards", ".plugin", in_sign='ssa(ss)s', out_sign='', method=self.play_cards)  # args: player, referee, cards, profile
         host.bridge.addSignal("tarotGamePlayers", ".plugin", signature='ssass')  # args: room_jid, referee, players, profile
         host.bridge.addSignal("tarotGameStarted", ".plugin", signature='ssass')  # args: room_jid, referee, players, profile
@@ -78,6 +80,9 @@
         for suit in ["pique", "coeur", "carreau", "trefle"]:
             for value in map(str, range(1, 11)) + ["valet", "cavalier", "dame", "roi"]:
                 self.deck_ordered.append(TarotCard((suit, value)))
+        self.__choose_contrat_id = host.registerCallback(self._contratChoosed, with_data=True)
+        self.__score_id = host.registerCallback(self._scoreShowed, with_data=True)
+
 
     def __card_list_to_xml(self, cards_list, elt_name):
         """Convert a card list to domish element"""
@@ -380,19 +385,46 @@
         to_jid = jid.JID(room_jid.userhost() + "/" + next_player)  # FIXME: gof:
         self.send(to_jid, 'your_turn', profile=profile)
 
-    def contratChoosed(self, player, referee, contrat, profile_key='@NONE@'):
-        """Must be call by player when the contrat is selected
-        @param player: player's name
-        @param referee: arbiter jid
-        @contrat: contrat choosed (must be the exact same string than in the give list options)
-        @profile_key: profile
+    def _contratChoosed(self, raw_data, profile):
+        """Will be called when the contrat is selected
+        @param raw_data: contains the choosed session id and the chosen contrat
+        @param profile_key: profile
         """
-        profile = self.host.memory.getProfileName(profile_key)
-        if not profile:
-            error(_("profile %s is unknown") % profile_key)
-            return
+        try:
+            session_data = self._sessions.profileGet(raw_data["session_id"], profile)
+        except KeyError:
+            warning(_("session id doesn't exist, session has probably expired"))
+            # TODO: send error dialog
+            return defer.succeed({})
+
+        room_jid_s = session_data['room_jid'].userhost()
+        referee = self.games[room_jid_s]['referee']
+        player = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
+        data = xml_tools.XMLUIResult2DataFormResult(raw_data)
+        contrat = data['contrat']
         debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile})
-        self.send(jid.JID(referee), ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile)
+        d = self.send(jid.JID(referee), ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile)
+        d.addCallback(lambda ignore: {})
+        del self._sessions[raw_data["session_id"]]
+        return d
+
+    def _scoreShowed(self, raw_data, profile):
+        """Will be called when the player closes the score dialog
+        @param raw_data: nothing to retrieve from here but the session id
+        @param profile_key: profile
+        """
+        try:
+            session_data = self._sessions.profileGet(raw_data["session_id"], profile)
+        except KeyError:
+            warning(_("session id doesn't exist, session has probably expired"))
+            # TODO: send error dialog
+            return defer.succeed({})
+
+        room_jid_s = session_data['room_jid'].userhost()
+        # XXX: empty hand means to the frontend "reset the display"...
+        self.host.bridge.tarotGameNew(room_jid_s, [], profile)
+        del self._sessions[raw_data["session_id"]]
+        return defer.succeed({})
 
     def play_cards(self, player, referee, cards, profile_key='@NONE@'):
         """Must be call by player when the contrat is selected
@@ -480,7 +512,9 @@
 
             elif elt.name == 'contrat':  # it's time to choose contrat
                 form = data_form.Form.fromElement(elt.firstChildElement())
-                xml_data = dataForm2XMLUI(form, "").toXml()
+                session_id, session_data = self._sessions.newSession(profile=profile)
+                session_data["room_jid"] = room_jid
+                xml_data = xml_tools.dataForm2XMLUI(form, self.__choose_contrat_id, session_id).toXml()
                 self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile)
 
             elif elt.name == 'contrat_choosed':
@@ -619,7 +653,9 @@
                 for looser in elt.elements(name='looser', uri=NS_CG):
                     loosers.append(unicode(looser))
                 form = data_form.Form.fromElement(form_elt)
-                xml_data = dataForm2XMLUI(form, "").toXml()
+                session_id, session_data = self._sessions.newSession(profile=profile)
+                session_data["room_jid"] = room_jid
+                xml_data = xml_tools.dataForm2XMLUI(form, self.__score_id, session_id).toXml()
                 self.host.bridge.tarotGameScore(room_jid.userhost(), xml_data, winners, loosers, profile)
             elif elt.name == 'error':
                 if elt['type'] == 'invalid_cards':