《付録》TetrisCenter.py

# -*- coding: utf-8 -*-
#===============================================================================
#    Copyright (C) 2000-2008, 小泉ひよ子とタマゴ倶楽部
#
# Change History: Games
#    1988/05, Smalltalk
#    2004/09, Java
#    2005/02, C#
#    2005/03, Jython
# History: WPF examples
#    2008/01/25, IronPython 1.1.1 (download)
#    2008/08/22, IronPython 1.1.2 (download)
#    2008/03/16, ver.2.0, WPF
#    2008/00/00, ver.2.1, IronPython 1.1.2 
#===============================================================================

from TetrisContext import *
from TetrisWorld import *

## --------------------
class Tetris:
    def __init__(self, client):
        self.client = client
        for item, mino in self.client.testCase:
            tray = Tray()
            mino.tray = tray
            mino.dispatch = self._cases(mino)
            self.client.addItem(item, mino)
            self._addTray(tray, item)
            self._addMino(mino, item)

    def _cases(self, mino):
        return {
            Key_Right: mino.shiftRight,
            Key_Left : mino.shiftLeft ,
            Key_Up   : mino.counterClockwise,
            Key_Down : mino.rotateClockwise ,
            }

    def _addTray(self, tray, item):
        targets = "leftEdge", "rightEdge", "bottomEnd", "tiles",
        for e in targets:
            for stone in getattr(tray, e).values():
                self.client.addShape(stone.shape, item)

    def _addMino(self, mino, item):
        for e in mino.shape:
            self.client.addShape(e, item)

    ## --------------------               
    def keyDown(self, sender, e):
        KeyHolder(e.Key).switch(self.client.cases())
        self.client.update()

## --------------------               
class KeyHolder:
    def __init__(self, value):
        self.value = value

    def switch(self, cases):
        for key, f in cases.items():
            if key == self.value:
                f()

## --------------------