servertable.py 36.2 KB
Newer Older
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Copyright (C) 2009-2014 Wolfgang Rohdewald <wolfgang@rohdewald.de>

Kajongg is free software you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

The DBPasswordChecker is based on an example from the book
Twisted Network Programming Essentials by Abe Fettig, 2006
O'Reilly Media, Inc., ISBN 0-596-10032-9
"""

import os
import random
import traceback
if os.name != 'nt':
    import resource
from itertools import chain

from twisted.spread import pb

35
36
from common import Debug, Internal
from wind import Wind
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
from util import Duration
from message import Message, ChatMessage
from log import logDebug, logError, m18nE, m18n, m18ncE
from deferredutil import DeferredBlock
from tile import Tile, TileList, elements
from meld import Meld, MeldList
from query import Query
from client import Client, Table
from wall import WallEmpty
from sound import Voice
from servercommon import srvError
from user import User
from game import PlayingGame

class ServerGame(PlayingGame):

    """the central game instance on the server"""
    # pylint: disable=too-many-arguments, too-many-public-methods

    def __init__(self, names, ruleset, gameid=None, wantedGame=None,
                 client=None, playOpen=False, autoPlay=False):
        PlayingGame.__init__(
            self,
            names,
            ruleset,
            gameid,
            wantedGame,
            client,
            playOpen,
            autoPlay)
        self.shouldSave = True

    def throwDices(self):
        """sets random living and kongBox
        sets divideAt: an index for the wall break"""
        self.wall.tiles.sort()
        self.randomGenerator.shuffle(self.wall.tiles)
        PlayingGame.throwDices(self)

    def initHand(self):
        """Happens only on server: every player gets 13 tiles (including east)"""
        self.throwDices()
        self.wall.divide()
        for player in self.players:
            player.clearHand()
            # 13 tiles at least, with names as given by wall
            # compensate boni
            while len(player.concealedTiles) != 13:
                player.addConcealedTiles(self.wall.deal())
        PlayingGame.initHand(self)


class ServerTable(Table):

    """a table on the game server"""
    # pylint: disable=too-many-arguments

    def __init__(self, server, owner, ruleset, suspendedAt,
                 playOpen, autoPlay, wantedGame, tableId=None):
        if tableId is None:
            tableId = server.generateTableId()
        Table.__init__(
            self,
            tableId,
            ruleset,
            suspendedAt,
            False,
            playOpen,
            autoPlay,
            wantedGame)
        self.server = server
        self.owner = owner
        self.users = [owner] if owner else []
        self.remotes = {}   # maps client connections to users
        self.game = None
        self.client = None
        server.tables[self.tableid] = self
        if Debug.table:
            logDebug(u'new table %s' % self)

    def hasName(self, name):
        """returns True if one of the players in the game is named 'name'"""
        return bool(self.game) and any(x.name == name for x in self.game.players)

    def asSimpleList(self, withFullRuleset=False):
        """return the table attributes to be sent to the client"""
        game = self.game
        onlineNames = [x.name for x in self.users]
        if self.suspendedAt:
            names = tuple(x.name for x in game.players)
        else:
            names = tuple(x.name for x in self.users)
        online = tuple(bool(x in onlineNames) for x in names)
        if game:
            endValues = game.handctr, dict(
                (x.wind, x.balance) for x in game.players)
        else:
            endValues = None
        if withFullRuleset:
            ruleset = self.ruleset.toList()
        else:
            ruleset = self.ruleset.hash
        return list(
            [self.tableid, ruleset, game.gameid if game else None, self.suspendedAt, self.running,
             self.playOpen, self.autoPlay, self.wantedGame, names, online, endValues])

    def maxSeats(self):
        """for a new game: 4. For a suspended game: The
        number of humans before suspending"""
        result = 4
        if self.suspendedAt:
            result -= sum(x.name.startswith(u'Robot ')
                          for x in self.game.players)
        return result

    def sendChatMessage(self, chatLine):
        """sends a chat messages to all clients"""
        if Debug.chat:
            logDebug(u'server sends chat msg %s' % chatLine)
        if self.suspendedAt:
            chatters = []
            for player in self.game.players:
                chatters.extend(
                    x for x in self.server.srvUsers if x.name == player.name)
        else:
            chatters = self.users
        for other in chatters:
            self.server.callRemote(other, 'chat', chatLine.asList())

    def addUser(self, user):
        """add user to this table"""
        if user.name in list(x.name for x in self.users):
            raise srvError(pb.Error, m18nE('You already joined this table'))
        if len(self.users) == self.maxSeats():
            raise srvError(pb.Error, m18nE('All seats are already taken'))
        self.users.append(user)
        if Debug.table:
            logDebug(u'%s seated on table %s' % (user.name, self))
        self.sendChatMessage(ChatMessage(self.tableid, user.name,
                                         m18nE('takes a seat'), isStatusMessage=True))

    def delUser(self, user):
        """remove user from this table"""
        if user in self.users:
            self.running = False
            self.users.remove(user)
            self.sendChatMessage(ChatMessage(self.tableid, user.name,
                                             m18nE('leaves the table'), isStatusMessage=True))
            if user is self.owner:
                # silently pass ownership
                if self.users:
                    self.owner = self.users[0]
                    if Debug.table:
                        logDebug(u'%s leaves table %d, %s is the new owner' % (
                            user.name, self.tableid, self.owner))
                else:
                    if Debug.table:
                        logDebug(u'%s leaves table %d, table is now empty' % (
                            user.name, self.tableid))
            else:
                if Debug.table:
                    logDebug(u'%s leaves table %d, %s stays owner' % (
                        user.name, self.tableid, self.owner))

    def __unicode__(self):
        """for debugging output"""
        onlineNames = list(x.name + (u'(Owner)' if x == self.owner.name else u'')
                           for x in self.users)
        offlineString = u''
        if self.game:
            offlineNames = list(x.name for x in self.game.players if x.name not in onlineNames
                                and not x.name.startswith(u'Robot'))
            if offlineNames:
                offlineString = u' offline:' + u','.join(offlineNames)
        return u'%d(%s%s)' % (self.tableid, u','.join(onlineNames), offlineString)

    def calcGameId(self):
        """based upon the max gameids we got from the clients, propose
        a new one, we want to use the same gameid in all data bases"""
        serverMaxGameId = Query('select max(id) from game').records[0][0]
        serverMaxGameId = int(serverMaxGameId) if serverMaxGameId else 0
        gameIds = [x.maxGameId for x in self.users]
        gameIds.append(serverMaxGameId)
        return max(gameIds) + 1

    def __prepareNewGame(self):
        """returns a new game object"""
        names = list(x.name for x in self.users)
        # the server and all databases save the english name but we
        # want to make sure a translation exists for the client GUI
        robotNames = [
            m18ncE(
                'kajongg, name of robot player, to be translated',
                u'Robot 1'),
            m18ncE(
                'kajongg, name of robot player, to be translated',
                u'Robot 2'),
            m18ncE('kajongg, name of robot player, to be translated', u'Robot 3')]
        while len(names) < 4:
            names.append(robotNames[3 - len(names)])
237
        names = list(tuple([Wind.all4[idx], name])
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
                     for idx, name in enumerate(names))
        self.client = Client()
                             # Game has a weakref to client, so we must keep
                             # it!
        return ServerGame(names, self.ruleset, client=self.client,
                          playOpen=self.playOpen, autoPlay=self.autoPlay, wantedGame=self.wantedGame)

    def userForPlayer(self, player):
        """finds the table user corresponding to player"""
        for result in self.users:
            if result.name == player.name:
                return result

    def __connectPlayers(self):
        """connects client instances with the game players"""
        game = self.game
        for player in game.players:
            remote = self.userForPlayer(player)
            if not remote:
                # we found a robot player, its client runs in this server
                # process
                remote = Client(player.name)
                remote.table = self
            self.remotes[player] = remote

    def __checkDbIdents(self):
        """for 4 players, we have up to 4 data bases:
        more than one player might use the same data base.
        However the server always needs to use its own data base.
        If a data base is used by more than one client, only one of
        them should update. Here we set shouldSave for all players,
        while the server always saves"""
        serverIdent = Internal.db.identifier
        dbIdents = set()
        game = self.game
        for player in game.players:
            player.shouldSave = False
            if isinstance(self.remotes[player], User):
                dbIdent = self.remotes[player].dbIdent
                assert dbIdent != serverIdent, \
                    'client and server try to use the same database:%s' % \
                    Internal.db.path
                player.shouldSave = dbIdent not in dbIdents
                dbIdents.add(dbIdent)

    def readyForGameStart(self, user):
        """the table initiator told us he wants to start the game"""
        if len(self.users) < self.maxSeats() and self.owner != user:
            raise srvError(pb.Error,
                           m18nE(
                               'Only the initiator %1 can start this game, you are %2'),
                           self.owner.name, user.name)
        if self.suspendedAt:
            self.__connectPlayers()
            self.__checkDbIdents()
            self.initGame()
        else:
            self.game = self.__prepareNewGame()
            self.__connectPlayers()
            self.__checkDbIdents()
            self.proposeGameId(self.calcGameId())
        # TODO: remove table for all other srvUsers out of sight

    def proposeGameId(self, gameid):
        """server proposes an id to the clients ands waits for answers"""
        while True:
            query = Query('insert into game(id,seed) values(?,?)',
                          (gameid, 'proposed'), mayFail=True, failSilent=True)
            if not query.failure:
                break
            gameid += random.randrange(1, 100)
        block = DeferredBlock(self)
        for player in self.game.players:
            if player.shouldSave and isinstance(self.remotes[player], User):
                # do not ask robot players, they use the server data base
                block.tellPlayer(player, Message.ProposeGameId, gameid=gameid)
        block.callback(self.collectGameIdAnswers, gameid)

    def collectGameIdAnswers(self, requests, gameid):
        """clients answered if the proposed game id is free"""
        if requests:
            # when errors happen, there might be no requests left
            for msg in requests:
                if msg.answer == Message.NO:
                    self.proposeGameId(gameid + 1)
                    return
                elif msg.answer != Message.OK:
                    raise srvError(
                        pb.Error,
                        'collectGameIdAnswers got neither NO nor OK')
            self.game.gameid = gameid
            self.initGame()

    def initGame(self):
        """ask clients if they are ready to start"""
        game = self.game
        game.saveStartTime()
        block = DeferredBlock(self)
        for player in game.players:
            block.tellPlayer(
                player, Message.ReadyForGameStart, tableid=self.tableid,
                gameid=game.gameid, shouldSave=player.shouldSave,
340
                wantedGame=game.wantedGame, playerNames=list((x.wind, x.name) for x in game.players))
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
        block.callback(self.startGame)

    def startGame(self, requests):
        """if all players said ready, start the game"""
        for user in self.users:
            userRequests = list(x for x in requests if x.user == user)
            if not userRequests or userRequests[0].answer == Message.NoGameStart:
                if Debug.table:
                    if not userRequests:
                        logDebug(
                            u'Server.startGame: found no request for user %s' %
                            user.name)
                    else:
                        logDebug(
                            u'Server.startGame: %s said NoGameStart' %
                            user.name)
                self.game = None
                return
        if Debug.table:
            logDebug(u'Game starts on table %s' % self)
        elementIter = iter(elements.all(self.game.ruleset))
        wallSize = len(self.game.wall.tiles)
        self.game.wall.tiles = []
        for _ in range(wallSize):
            self.game.wall.tiles.append(next(elementIter).concealed)
        assert isinstance(self.game, ServerGame), self.game
        self.running = True
        self.__adaptOtherTables()
        self.sendVoiceIds()

    def __adaptOtherTables(self):
        """if the players on this table also reserved seats on other tables, clear them
        make running table invisible for other users"""
        for user in self.users:
            for tableid in self.server.tablesWith(user):
                if tableid != self.tableid:
                    self.server.leaveTable(user, tableid)
        foreigners = list(
            x for x in self.server.srvUsers if x not in self.users)
        if foreigners:
            if Debug.table:
                logDebug(
                    u'make running table %s invisible for %s' %
                    (self, ','.join(str(x) for x in foreigners)))
            for srvUser in foreigners:
                self.server.callRemote(
                    srvUser,
                    'tableRemoved',
                    self.tableid,
                    '')

    def sendVoiceIds(self):
        """tell each player what voice ids the others have. By now the client has a Game instance!"""
        humanPlayers = [
            x for x in self.game.players if isinstance(self.remotes[x], User)]
        if len(humanPlayers) < 2 or not any(self.remotes[x].voiceId for x in humanPlayers):
            # no need to pass around voice data
            self.assignVoices()
            return
        block = DeferredBlock(self)
        for player in humanPlayers:
            remote = self.remotes[player]
            if remote.voiceId:
                # send it to other human players:
                others = [x for x in humanPlayers if x != player]
                if Debug.sound:
                    logDebug(u'telling other human players that %s has voiceId %s' % (
                        player.name, remote.voiceId))
                block.tell(
                    player,
                    others,
                    Message.VoiceId,
                    source=remote.voiceId)
        block.callback(self.collectVoiceData)

    def collectVoiceData(self, requests):
        """collect voices of other players"""
        if not self.running:
            return
        block = DeferredBlock(self)
        voiceDataRequests = []
        for request in requests:
            if request.answer == Message.ClientWantsVoiceData:
                # another human player requests sounds for voiceId
                voiceId = request.args[0]
                voiceFor = [x for x in self.game.players if isinstance(self.remotes[x], User)
                            and self.remotes[x].voiceId == voiceId][0]
                voiceFor.voice = Voice(voiceId)
                if Debug.sound:
                    logDebug(
                        u'client %s wants voice data %s for %s' %
                        (request.user.name, request.args[0], voiceFor))
                voiceDataRequests.append((request.user, voiceFor))
                if not voiceFor.voice.oggFiles():
                    # the server does not have it, ask the client with that
                    # voice
                    block.tell(
                        voiceFor,
                        voiceFor,
                        Message.ServerWantsVoiceData)
        block.callback(self.sendVoiceData, voiceDataRequests)

    def sendVoiceData(self, requests, voiceDataRequests):
        """sends voice sounds to other human players"""
        self.processAnswers(requests)
        block = DeferredBlock(self)
        for voiceDataRequester, voiceFor in voiceDataRequests:
            # this player requested sounds for voiceFor
            voice = voiceFor.voice
            content = voice.archiveContent
            if content:
                if Debug.sound:
                    logDebug(
                        u'server got voice data %s for %s from client' %
                        (voiceFor.voice, voiceFor.name))
                block.tell(
                    voiceFor,
                    voiceDataRequester,
                    Message.VoiceData,
                    md5sum=voice.md5sum,
                    source=content)
            elif Debug.sound:
                logDebug(u'server got empty voice data %s for %s from client' % (
                    voice, voiceFor.name))
        block.callback(self.assignVoices)

    def assignVoices(self, dummyResults=None):
        """now all human players have all voice data needed"""
        humanPlayers = [
            x for x in self.game.players if isinstance(self.remotes[x], User)]
        block = DeferredBlock(self)
        block.tell(None, humanPlayers, Message.AssignVoices)
        block.callback(self.startHand)

    def pickTile(self, dummyResults=None, deadEnd=False):
        """the active player gets a tile from wall. Tell all clients."""
        if not self.running:
            return
        player = self.game.activePlayer
        try:
            tile = player.pickedTile(deadEnd)
        except WallEmpty:
            self.endHand()
        else:
            self.game.lastDiscard = None
            block = DeferredBlock(self)
            block.tellPlayer(
                player,
                Message.PickedTile,
                tile=tile,
                deadEnd=deadEnd)
            showTile = tile if tile.isBonus or self.game.playOpen else Tile.unknown
            block.tellOthers(
                player,
                Message.PickedTile,
                tile=showTile,
                deadEnd=deadEnd)
            block.callback(self.moved)

    def pickKongReplacement(self, requests=None):
        """the active player gets a tile from the dead end. Tell all clients."""
        requests = self.prioritize(requests)
        if requests and requests[0].answer == Message.MahJongg:
            # somebody robs my kong
            requests[0].answer.serverAction(self, requests[0])
        else:
            self.pickTile(requests, deadEnd=True)

    def clientDiscarded(self, msg):
        """client told us he discarded a tile. Check for consistency and tell others."""
        if not self.running:
            return
        player = msg.player
        assert player == self.game.activePlayer
        tile = Tile(msg.args[0])
        if tile not in player.concealedTiles:
            self.abort(
                u'player %s discarded %s but does not have it' %
                (player, tile))
            return
        dangerousText = self.game.dangerousFor(player, tile)
        mustPlayDangerous = player.mustPlayDangerous()
        violates = player.violatesOriginalCall(tile)
        self.game.hasDiscarded(player, tile)
        block = DeferredBlock(self)
        block.tellAll(player, Message.Discard, tile=tile)
        block.callback(self._clientDiscarded2, msg, dangerousText, mustPlayDangerous, violates)

    def _clientDiscarded2(self, dummyResults, msg, dangerousText, mustPlayDangerous, violates):
Wolfgang Rohdewald's avatar
Wolfgang Rohdewald committed
530
        """client told us he discarded a tile. Continue, check for violating original call"""
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
        block = DeferredBlock(self)
        player = msg.player
        if violates:
            if Debug.originalCall:
                tile = Tile(msg.args[0])
                logDebug(u'%s just violated OC with %s' % (player, tile))
            player.mayWin = False
            block.tellAll(player, Message.ViolatesOriginalCall)
        block.callback(self._clientDiscarded3, msg, dangerousText, mustPlayDangerous)

    def _clientDiscarded3(self, dummyResults, msg, dangerousText, mustPlayDangerous):
        """client told us he discarded a tile. Continue, check for calling"""
        block = DeferredBlock(self)
        player = msg.player
        if self.game.ruleset.mustDeclareCallingHand and not player.isCalling:
            if player.hand.callingHands:
                player.isCalling = True
                block.tellAll(player, Message.Calling)
        block.callback(self._clientDiscarded4, msg, dangerousText, mustPlayDangerous)

    def _clientDiscarded4(self, dummyResults, msg, dangerousText, mustPlayDangerous):
        """client told us he discarded a tile. Continue, check for dangerous game"""
        block = DeferredBlock(self)
        player = msg.player
        if dangerousText:
            if mustPlayDangerous and player.lastSource not in 'dZ':
                if Debug.dangerousGame:
                    tile = Tile(msg.args[0])
                    logDebug(u'%s claims no choice. Discarded %s, keeping %s. %s' %
                             (player, tile, ''.join(player.concealedTiles), ' / '.join(dangerousText)))
                player.claimedNoChoice = True
                block.tellAll(
                    player,
                    Message.NoChoice,
                    tiles=TileList(player.concealedTiles))
            else:
                player.playedDangerous = True
                if Debug.dangerousGame:
                    tile = Tile(msg.args[0])
                    logDebug(u'%s played dangerous. Discarded %s, keeping %s. %s' %
                             (player, tile, ''.join(player.concealedTiles), ' / '.join(dangerousText)))
                block.tellAll(
                    player,
                    Message.DangerousGame,
                    tiles=TileList(player.concealedTiles))
        if msg.answer == Message.OriginalCall:
            player.isCalling = True
            block.callback(self.clientMadeOriginalCall, msg)
        else:
            block.callback(self._askForClaims, msg)

    def clientMadeOriginalCall(self, dummyResults, msg):
        """first tell everybody about original call
        and then treat the implicit discard"""
        msg.player.originalCall = True
        if Debug.originalCall:
            logDebug(u'server.clientMadeOriginalCall: %s' % msg.player)
        block = DeferredBlock(self)
        block.tellAll(msg.player, Message.OriginalCall)
        block.callback(self._askForClaims, msg)

    def startHand(self, dummyResults=None):
        """all players are ready to start a hand, so do it"""
        if self.running:
            self.game.prepareHand()
            self.game.initHand()
            block = self.tellAll(None, Message.InitHand,
                                 divideAt=self.game.divideAt)
            block.callback(self.divided)

    def divided(self, dummyResults=None):
        """the wall is now divided for all clients"""
        if not self.running:
            return
        block = DeferredBlock(self)
        for clientPlayer in self.game.players:
            for player in self.game.players:
                if player == clientPlayer or self.game.playOpen:
                    tiles = player.concealedTiles
                else:
                    tiles = TileList(Tile.unknown * 13)
                block.tell(player, clientPlayer, Message.SetConcealedTiles,
                           tiles=TileList(chain(tiles, player.bonusTiles)))
        block.callback(self.dealt)

    def endHand(self, dummyResults=None):
        """hand is over, show all concealed tiles to all players"""
        if not self.running:
            return
        if self.game.playOpen:
            self.saveHand()
        else:
            block = DeferredBlock(self)
            for player in self.game.players:
                # there might be no winner, winner.others() would be wrong
                if player != self.game.winner:
                    # the winner tiles are already shown in claimMahJongg
                    block.tellOthers(
                        player, Message.ShowConcealedTiles, show=True,
                        tiles=TileList(player.concealedTiles))
            block.callback(self.saveHand)

    def saveHand(self, dummyResults=None):
        """save the hand to the database and proceed to next hand"""
        if not self.running:
            return
        self.tellAll(None, Message.SaveHand, self.nextHand)
        self.game.saveHand()

    def nextHand(self, dummyResults):
        """next hand: maybe rotate"""
        if not self.running:
            return
        DeferredBlock.garbageCollection()
        for block in DeferredBlock.blocks:
            if block.table == self:
                logError(
                    u'request left from previous hand: %s' %
                    block.outstandingUnicode())
        token = self.game.handId.prompt(
            withAI=False)  # we need to send the old token until the
                                   # clients started the new hand
        rotateWinds = self.game.maybeRotateWinds()
        if self.game.finished():
            self.server.removeTable(
                self,
                'gameOver',
                m18nE('Game <numid>%1</numid> is over!'),
                self.game.seed)
            if Debug.process and os.name != 'nt':
                logDebug(
                    u'MEM:%s' %
                    resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
            return
        self.game.sortPlayers()
        playerNames = list((x.wind, x.name) for x in self.game.players)
        self.tellAll(None, Message.ReadyForHandStart, self.startHand,
668
                     playerNames=playerNames, rotateWinds=rotateWinds, token=token)
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896

    def abort(self, message, *args):
        """abort the table. Reason: message/args"""
        self.server.removeTable(self, 'abort', message, *args)

    def claimTile(self, player, claim, meldTiles, nextMessage):
        """a player claims a tile for pung, kong or chow.
        meldTiles contains the claimed tile, concealed"""
        if not self.running:
            return
        lastDiscard = self.game.lastDiscard
        # if we rob a tile, self.game.lastDiscard has already been set to the
        # robbed tile
        hasTiles = Meld(meldTiles[:])
        discardingPlayer = self.game.activePlayer
        hasTiles = hasTiles.without(lastDiscard)
        meld = Meld(meldTiles)
        if len(meld) != 4 and not (meld.isPair or meld.isPungKong or meld.isChow):
            msg = m18nE('%1 wrongly said %2 for meld %3')
            self.abort(msg, player.name, claim.name, str(meld))
            return
        if not player.hasConcealedTiles(hasTiles):
            msg = m18nE(
                '%1 wrongly said %2: claims to have concealed tiles %3 but only has %4')
            self.abort(
                msg,
                player.name,
                claim.name,
                ' '.join(hasTiles),
                ''.join(player.concealedTiles))
            return
        # update our internal state before we listen to the clients again
        self.game.discardedTiles[lastDiscard.exposed] -= 1
        self.game.activePlayer = player
        if lastDiscard:
            player.lastTile = lastDiscard.exposed
            player.lastSource = 'd'
        player.exposeMeld(hasTiles, lastDiscard)
        self.game.lastDiscard = None
        block = DeferredBlock(self)
        if (nextMessage != Message.Kong
                and self.game.dangerousFor(discardingPlayer, lastDiscard)
                and discardingPlayer.playedDangerous):
            player.usedDangerousFrom = discardingPlayer
            if Debug.dangerousGame:
                logDebug(u'%s claims dangerous tile %s discarded by %s' %
                         (player, lastDiscard, discardingPlayer))
            block.tellAll(
                player,
                Message.UsedDangerousFrom,
                source=discardingPlayer.name)
        block.tellAll(player, nextMessage, meld=meld)
        if claim == Message.Kong:
            block.callback(self.pickKongReplacement)
        else:
            block.callback(self.moved)

    def declareKong(self, player, meldTiles):
        """player declares a Kong, meldTiles is a list"""
        kongMeld = Meld(meldTiles)
        if not player.hasConcealedTiles(kongMeld) and kongMeld[0].exposed.pung not in player.exposedMelds:
            msg = m18nE('declareKong:%1 wrongly said Kong for meld %2')
            args = (player.name, str(kongMeld))
            logDebug(m18n(msg, *args))
            logDebug(
                u'declareKong:concealedTiles:%s' %
                ''.join(player.concealedTiles))
            logDebug(u'declareKong:concealedMelds:%s' %
                     ' '.join(str(x) for x in player.concealedMelds))
            logDebug(u'declareKong:exposedMelds:%s' %
                     ' '.join(str(x) for x in player.exposedMelds))
            self.abort(msg, *args)
            return
        player.exposeMeld(kongMeld)
        self.tellAll(
            player,
            Message.DeclaredKong,
            self.pickKongReplacement,
            meld=kongMeld)

    def claimMahJongg(self, msg):
        """a player claims mah jongg. Check this and
        if correct, tell all. Otherwise abort game,  kajongg client is faulty"""
        if not self.running:
            return
        player = msg.player
        concealedMelds = MeldList(msg.args[0])
        withDiscard = Tile(msg.args[1]) if msg.args[1] else None
        lastMeld = Meld(msg.args[2])
        if self.game.ruleset.mustDeclareCallingHand:
            assert player.isCalling, '%s %s %s says MJ but never claimed: concmelds:%s withdiscard:%s lastmeld:%s' % (
                self.game.handId, player.hand, player, concealedMelds, withDiscard, lastMeld)
        discardingPlayer = self.game.activePlayer
        lastMove = next(self.game.lastMoves(withoutNotifications=True))
        robbedTheKong = lastMove.message == Message.DeclaredKong
        if robbedTheKong:
            player.robsTile()
            withDiscard = lastMove.meld[0].concealed
            lastMove.player.robTileFrom(withDiscard)
        msgArgs = player.showConcealedMelds(concealedMelds, withDiscard)
        if msgArgs:
            self.abort(*msgArgs)
            return
        player.declaredMahJongg(
            concealedMelds,
            withDiscard,
            player.lastTile,
            lastMeld)
        if not player.hand.won:
            msg = m18nE('%1 claiming MahJongg: This is not a winning hand: %2')
            self.abort(msg, player.name, player.hand.string)
            return
        block = DeferredBlock(self)
        if robbedTheKong:
            block.tellAll(player, Message.RobbedTheKong, tile=withDiscard)
        if (player.lastSource == 'd'
                and self.game.dangerousFor(discardingPlayer, player.lastTile)
                and discardingPlayer.playedDangerous):
            player.usedDangerousFrom = discardingPlayer
            if Debug.dangerousGame:
                logDebug(u'%s wins with dangerous tile %s from %s' %
                         (player, self.game.lastDiscard, discardingPlayer))
            block.tellAll(
                player,
                Message.UsedDangerousFrom,
                source=discardingPlayer.name)
        block.tellAll(
            player, Message.MahJongg, melds=concealedMelds, lastTile=player.lastTile,
            lastMeld=lastMeld, withDiscardTile=withDiscard)
        block.callback(self.endHand)

    def dealt(self, dummyResults):
        """all tiles are dealt, ask east to discard a tile"""
        if self.running:
            self.tellAll(
                self.game.activePlayer,
                Message.ActivePlayer,
                self.pickTile)

    def nextTurn(self):
        """the next player becomes active"""
        if self.running:
            # the player might just have disconnected
            self.game.nextTurn()
            self.tellAll(
                self.game.activePlayer,
                Message.ActivePlayer,
                self.pickTile)

    def prioritize(self, requests):
        """returns only requests we want to execute"""
        if not self.running:
            return
        answers = [
            x for x in requests if x.answer not in [
                Message.NoClaim,
                Message.OK,
                None]]
        if len(answers) > 1:
            claims = [
                Message.MahJongg,
                Message.Kong,
                Message.Pung,
                Message.Chow]
            for claim in claims:
                if claim in [x.answer for x in answers]:
                    # ignore claims with lower priority:
                    answers = [
                        x for x in answers if x.answer == claim or x.answer not in claims]
                    break
        mjAnswers = [x for x in answers if x.answer == Message.MahJongg]
        if len(mjAnswers) > 1:
            mjPlayers = [x.player for x in mjAnswers]
            nextPlayer = self.game.nextPlayer()
            while nextPlayer not in mjPlayers:
                nextPlayer = self.game.nextPlayer(nextPlayer)
            answers = [
                x for x in answers if x.player == nextPlayer or x.answer != Message.MahJongg]
        return answers

    def _askForClaims(self, dummyRequests, dummyMsg):
        """ask all players if they want to claim"""
        if self.running:
            self.tellOthers(
                self.game.activePlayer,
                Message.AskForClaims,
                self.moved)

    def processAnswers(self, requests):
        """a player did something"""
        if not self.running:
            return
        answers = self.prioritize(requests)
        if not answers:
            return
        for answer in answers:
            msg = u'<-  %s' % answer
            if Debug.traffic:
                logDebug(msg)
            with Duration(msg):
                answer.answer.serverAction(self, answer)
        return answers

    def moved(self, requests):
        """a player did something"""
        if Debug.stack:
            stck = traceback.extract_stack()
            if len(stck) > 30:
                logDebug(u'stack size:%d' % len(stck))
                logDebug(stck)
        answers = self.processAnswers(requests)
        if not answers:
            self.nextTurn()

    def tellAll(self, player, command, callback=None, **kwargs):
        """tell something about player to all players"""
        block = DeferredBlock(self)
        block.tellAll(player, command, **kwargs)
        block.callback(callback)
        return block

    def tellOthers(self, player, command, callback=None, **kwargs):
        """tell something about player to all other players"""
        block = DeferredBlock(self)
        block.tellOthers(player, command, **kwargs)
        block.callback(callback)
        return block