/usr/share/kde4/apps/kajongg/meld.py is in kajongg 4:4.13.0-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 35 36 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 237 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 340 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 | # -*- 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.
Read the user manual for a description of the interface to this scoring engine
"""
from itertools import chain
from log import m18nc
from tile import Tile, TileList, elements
class Meld(TileList):
"""represents a meld. Can be empty. Many Meld methods will
raise exceptions if the meld is empty. But we do not care,
those methods are not supposed to be called on empty melds.
Meld is essentially a list of Tile with added methods.
A Meld is immutable, not from the view of python but for
its user
for melds with 3 tiles:
isDeclared == isExposed : 3 exposed tiles
not isDeclared == isConcealed: 3 concealed Tiles
exposed: aaa
exposedClaimed: aaa
for melds with 4 tiles:
isKong = aAAa or aaaa or aaaA but NOT AAAA
isDeclared = aAAa or aaaa or aaaA
isExposed = aaaa or aaaA
isConcealed: aAAa or AAAA
exposedClaimed: aaaA
exposed: aaaa
"""
# pylint: disable=too-many-instance-attributes
__hash__ = None
cache = {}
def __new__(cls, newContent=None):
"""try to use cache"""
if isinstance(newContent, str):
if newContent in cls.cache:
return cls.cache[newContent]
elif isinstance(newContent, Meld):
return newContent
tiles = TileList(newContent)
cacheKey = tiles.key()
if cacheKey in cls.cache:
return cls.cache[cacheKey]
return TileList.__new__(cls, tiles)
@classmethod
def check(cls):
"""check cache consistency"""
for key, value in cls.cache.items():
assert key == value.key or key == str(value), 'cache wrong: cachekey=%s realkey=%s value=%s' % (
key, value.key, value)
assert value.key == 1 + value.hashTable.index(value) / 2
assert value.key == TileList.key(value), \
'static key:%s current key:%s, static value:%s, current value:%s ' % (
value.key, TileList.key(value), value.original, value)
def __init__(self, newContent=None):
"""init the meld: content can be either
- a single string with 2 chars for every tile
- a list containing such strings
- another meld. Its tiles are not passed.
- a list of Tile objects"""
if not hasattr(self, '_fixed'): # already defined if I am from cache
TileList.__init__(self, newContent)
self.case = ''.join('a' if x.islower() else 'A' for x in self)
self.key = TileList.key(self)
if self.key not in self.cache:
self.cache[self.key] = self
self.cache[str(self)] = self
self.isExposed = self.__isExposed()
self.isConcealed = not self.isExposed
self.isSingle = self.isPair = self.isChow = self.isPung = False
self.isKong = self.isClaimedKong = self.isKnitted = False
self.isDragonMeld = len(self) and self[0].isDragon
self.isWindMeld = len(self) and self[0].isWind
self.isHonorMeld = self.isDragonMeld or self.isWindMeld
self.isBonus = len(self) == 1 and self[0].isBonus
self.isKnown = len(self) and self[0].isKnown
self.__setMeldType()
self.isPungKong = self.isPung or self.isKong
self.isDeclared = self.isExposed or self.isKong
groups = set(x.group.lower() for x in self)
if len(groups) == 1:
self.group = self[0].group
self.lowerGroup = self.group.lower()
else:
self.group = 'X'
self.lowerGroup = 'x'
self.isRest = False
self.__staticRules = {} # ruleset is key
self.__dynamicRules = {} # ruleset is key
self.__staticDoublingRules = {} # ruleset is key
self.__dynamicDoublingRules = {} # ruleset is key
self.__hasRules = None # unknown yet
self.__hasDoublingRules = None # unknown yet
self.concealed = self.exposed = self.declared = self.exposedClaimed = None # to satisfy pylint
self._fixed = True
if len(self) < 4:
TileList.__setattr__(self, 'concealed', Meld(TileList(x.concealed for x in self)))
TileList.__setattr__(self, 'declared', self.concealed)
TileList.__setattr__(self, 'exposed', Meld(TileList(x.exposed for x in self)))
TileList.__setattr__(self, 'exposedClaimed', self.exposed)
else:
TileList.__setattr__(self, 'concealed', Meld(TileList(x.concealed for x in self)))
TileList.__setattr__(self, 'declared',
Meld(TileList([self[0].exposed, self[1].concealed, self[2].concealed, self[3].exposed])))
TileList.__setattr__(self, 'exposed', Meld(TileList(x.exposed for x in self)))
TileList.__setattr__(self, 'exposedClaimed',
Meld(TileList([self[0].exposed, self[1].exposed, self[2].exposed, self[3].concealed])))
def __setattr__(self, name, value):
if (hasattr(self, '_fixed')
and not name.endswith('__hasRules')
and not name.endswith('__hasDoublingRules')):
raise TypeError
TileList.__setattr__(self, name, value)
def __prepareRules(self, ruleset):
"""prepare rules from ruleset"""
rulesetId = id(ruleset)
self.__staticRules[rulesetId] = list(x for x in ruleset.meldRules
if not hasattr(x, 'mayApplyToMeld') and x.appliesToMeld(None, self))
self.__dynamicRules[rulesetId] = list(x for x in ruleset.meldRules
if hasattr(x, 'mayApplyToMeld') and x.mayApplyToMeld(self))
self.__hasRules = any(len(x) for x in chain(
self.__staticRules.values(), self.__dynamicRules.values()))
self.__staticDoublingRules[rulesetId] = list(x for x in ruleset.doublingMeldRules
if not hasattr(x, 'mayApplyToMeld') and x.appliesToMeld(None, self))
self.__dynamicDoublingRules[rulesetId] = list(x for x in ruleset.doublingMeldRules
if hasattr(x, 'mayApplyToMeld') and x.mayApplyToMeld(self))
self.__hasDoublingRules = any(len(x) for x in chain(
self.__staticDoublingRules.values(), self.__dynamicDoublingRules.values()))
def rules(self, hand):
"""all applicable rules for this meld being part of hand"""
if self.__hasRules is False:
return []
ruleset = hand.ruleset
rulesetId = id(ruleset)
if rulesetId not in self.__staticRules:
self.__prepareRules(ruleset)
result = self.__staticRules[rulesetId][:]
result.extend(x for x in self.__dynamicRules[rulesetId] if x.appliesToMeld(hand, self))
return result
def doublingRules(self, hand):
"""all applicable doubling rules for this meld being part of hand"""
ruleset = hand.ruleset
rulesetId = id(ruleset)
if rulesetId not in self.__staticRules:
self.__prepareRules(ruleset)
result = self.__staticDoublingRules[rulesetId][:]
result.extend(x for x in self.__dynamicDoublingRules[rulesetId] if x.appliesToMeld(hand, self))
return result
def append(self, dummy):
"""we want to be immutable"""
raise TypeError
def extend(self, dummy):
"""we want to be immutable"""
raise TypeError
def insert(self, dummy):
"""we want to be immutable"""
raise TypeError
def pop(self, dummy):
"""we want to be immutable"""
raise TypeError
def remove(self, dummy):
"""we want to be immutable"""
raise TypeError
def without(self, remove):
"""self without tile. The rest will be uppercased."""
tiles = TileList()
for tile in self:
if tile is remove:
remove = None
else:
tiles.append(tile.concealed)
return tiles
def __setitem__(self, index, value):
"""sets a tile in the meld"""
raise TypeError
def __delitem__(self, index):
"""removes a tile from the meld"""
raise TypeError
def __isExposed(self):
"""meld state: exposed or not"""
if self.case.islower():
return True
elif len(self) == 4:
return self.case[1:3].islower()
else:
return False
def __setMeldType(self):
"""compute meld type. Except knitting melds."""
# pylint: disable=too-many-branches,too-many-return-statements
length = len(self)
if length == 0:
return
if length > 4:
raise UserWarning('Meld %s is too long' % self)
if any(not x.isKnown for x in self):
if len(set(self)) != 1:
raise UserWarning('Meld %s: Cannot mix known and unknown tiles')
self.isKnown = False
return
if length == 1:
self.isSingle = True
return
if length == 2:
if self[0] == self[1]:
self.isPair = True
elif self[0].value == self[1].value and self.case[0] == self.case[1] \
and all(x.lowerGroup in Tile.colors for x in self):
self.isKnitted = True
else:
raise UserWarning('Meld %s is malformed' % self)
return
# now length is 3 or 4
tiles = set(self)
if len(tiles) == 1:
if length == 3:
self.isPung = True
else:
self.isKong = True
return
if len(tiles) == 3 and length == 3:
if len(set(x.value for x in tiles)) == 1:
if self.case in ('aaa', 'AAA'):
if len(set(x.group for x in tiles)) == 3:
if all(x.lowerGroup in Tile.colors for x in tiles):
self.isKnitted = True
return
groups = set(x.group for x in self)
if len(groups) > 2 or len(set(x.lower() for x in groups)) > 1:
raise UserWarning('Meld %s is malformed' % self)
values = set(x.value for x in self)
if length == 4:
if len(values) > 1:
raise UserWarning('Meld %s is malformed' % self)
if self.case == 'aaaA':
self.isKong = self.isClaimedKong = True
elif self.case == 'aAAa':
self.isKong = True
else:
raise UserWarning('Meld %s is malformed' % self)
return
# only possibilities left are CHOW and REST
# length is 3
if len(groups) == 1:
if groups.pop().lower() in Tile.colors:
if self[0].nextForChow is self[1] and self[1].nextForChow is self[2]:
self.isChow = True
return
raise UserWarning('Meld %s is malformed' % self)
def __lt__(self, other):
"""used for sorting. Smaller value is shown first."""
if len(other) == 0:
return False
if len(self) == 0:
return True
if self.isDeclared and not other.isDeclared:
return True
if not self.isDeclared and other.isDeclared:
return False
if self[0].key == other[0].key:
return len(self) > len(other)
return self[0].key < other[0].key
def __repr__(self):
"""the default representation"""
return 'Meld(%s)' % str(self)
def typeName(self):
"""convert int to speaking name with shortcut. ATTENTION: UNTRANSLATED!"""
# pylint: disable=too-many-return-statements
if self.isBonus:
return m18nc('kajongg meld type', 'Bonus')
elif self.isSingle:
return m18nc('kajongg meld type', '&single')
elif self.isPair:
return m18nc('kajongg meld type', '&pair')
elif self.isChow:
return m18nc('kajongg meld type', '&chow')
elif self.isPung:
return m18nc('kajongg meld type', 'p&ung')
elif self.isClaimedKong:
return m18nc('kajongg meld type', 'c&laimed kong')
elif self.isKong:
return m18nc('kajongg meld type', 'k&ong')
else:
return m18nc('kajongg meld type', 'rest of tiles')
def __stateName(self):
"""the translated name of the state"""
if self.isBonus or self.isClaimedKong:
return ''
elif self.isExposed:
return m18nc('kajongg meld state', 'Exposed')
else:
return m18nc('kajongg meld state', 'Concealed')
def name(self):
"""the long name"""
result = m18nc('kajongg meld name, do not translate parameter names', '{state} {meldType} {name}')
return result.format(
state=self.__stateName(),
meldType=self.typeName(),
name=self[0].name()).replace(' ', ' ').strip()
@staticmethod
def cacheMeldsInTiles():
"""define all usual melds as Tile attributes"""
Tile.unknown.single = Meld(Tile.unknown)
Tile.unknown.pung = Meld(Tile.unknown * 3)
for tile, occ in elements.occurrence.items():
tile.single = Meld(tile)
tile.concealed.single = Meld(tile.concealed)
if occ > 1:
tile.pair = Meld(tile * 2)
tile.concealed.pair = Meld(tile.concealed * 2)
if occ > 2:
tile.pung = Meld(tile * 3)
tile.concealed.pung = Meld(tile.concealed * 3)
if tile.value in range(1, 8):
tile.chow = Meld([tile, tile.nextForChow, tile.nextForChow.nextForChow])
tile.concealed.chow = Meld([tile.concealed, tile.nextForChow.concealed,
tile.nextForChow.nextForChow.concealed])
if tile.value in range(1, 10):
tile.knitted3 = Meld([Tile(x, tile.value) for x in Tile.colors])
tile.concealed.knitted3 = Meld([Tile(x, tile.value).concealed for x in Tile.colors])
if occ > 3:
tile.kong = Meld(tile * 4)
tile.claimedKong = Meld([tile, tile, tile, tile.concealed])
tile.concealed.kong = Meld(tile.concealed * 4)
class MeldList(list):
"""a list of melds"""
def __init__(self, newContent=None):
list.__init__(self)
if newContent is None:
return
if isinstance(newContent, Meld):
list.append(self, newContent)
elif isinstance(newContent, str):
list.extend(self, [Meld(x) for x in newContent.split()]) # pylint: disable=maybe-no-member
else:
list.extend(self, [Meld(x) for x in newContent])
self.sort()
def extend(self, values):
list.extend(self, values)
self.sort()
def append(self, value):
list.append(self, value)
self.sort()
def tiles(self):
"""flat view of all tiles in all melds"""
return TileList(sum(self, []))
def __str__(self):
if len(self):
return ' '.join(str(x) for x in self)
else:
return ''
Meld.cacheMeldsInTiles()
|