Example #1
0
    def __init__(self):
        self.t = Tetris()

        state_num = 2**(
            4 * 8
        ) * 4 * 4 * 9 * 5  # 4x8 board [filled or not], 4*9 active-shape locations, 4 rotation positions, 5 shape types
        action_num = 4  # rotate, left, right, step
        #P = {s : {a : [] for a in range(action_num)} for s in range(state_num)}

        init_state_dist = []
        for x in range(4):
            for rot in range(4):
                for shape_type in range(5):
                    init_state_dist.append(encode([0, 0, x, rot, shape_type]))

        init_state_dist = np.array(init_state_dist)
        #init_state_dist /= init_state_dist.sum()

        #super(TetrisEnv, self).__init__(state_num, action_num, P, init_state_dist)

        self.action_space = spaces.Discrete(5)

        self.observation_space = spaces.Tuple(
            (spaces.Discrete(2**(4 * 8)), spaces.Discrete(4 * 9),
             spaces.Discrete(4), spaces.Discrete(5)))
        size = 2**(4 * 8) * 4 * 4 * 9 * 5
        #-int(-np.log(2**(4*8)*4*4*9*5)/np.log(2))
        self.observation_space.shape = np.zeros(size, dtype=int)
Example #2
0
 def run(self):
     """Run this game."""
     clock = pygame.time.Clock()
     count = 0
     while True:
         for event in pygame.event.get():
             if event.type == pygame.QUIT:
                 pygame.quit()
                 if self.mode == 1:
                     with open('data.json', 'w') as f:
                         json.dump({'record': self.record}, f)
                 exit()
             elif event.type == pygame.KEYDOWN:
                 if event.key == pygame.K_RETURN:
                     if self.game.state == 0:
                         if self.game.score.points > self.record and self.mode == 1:
                             self.record = self.game.score.points
                         self.game = Tetris(WIDTH, HEIGHT, self.level,
                                            self.mode == 1, None)
                     else:
                         self.paused = not self.paused
         pressed = pygame.key.get_pressed()
         if not self.paused:
             if self.game.state == 1:
                 if self.mode == 0:
                     if self.timer.tick() == 0:
                         self.agent.play(self.game.current_tetromino,
                                         self.game.grid)(self.game)
                 elif self.mode == 1:
                     self.interact(pressed)
             self.game.update()
         self.pressed = pressed
         self.render()
         clock.tick(60)
Example #3
0
def run():
    game = Tetris()
    episodes = 2000
    discount=0.9 
    epsilon=.99
    nuerons=[32, 32, 32]
    activation_functions=['relu', 'relu', 'relu', 'linear']
    batchSize = 32
    epoch = 5
    trainIteration = 1

    dqn = Agent(4, discount, epsilon, nuerons, activation_functions)
    episodes = 2000
    scores = []
    for episode in range(episodes):
        current = game.newGame()
        gameOver, step = False, 0
        renderEpisode = episode % 50 == 0

        while not gameOver:
            actions = game.getLegalActions()
            bestAction, bestState = dqn.best_state(list(actions.keys()), list(actions.values()))

            reward, gameOver = game.play(xLoc=bestAction[0], degrees=bestAction[1], render=renderEpisode)
            dqn.add_sample(current, bestState, reward, gameOver)
            current = bestState
            scores.append(reward)
        
        if episode % trainIteration == 0:
            dqn.train(batch_size=batchSize, epoch=epoch)
Example #4
0
    def __init__(self, cfg):
        self.num_states = cfg.MODEL.SIZE_STATE
        self.num_actions = cfg.MODEL.SIZE_ACTION
        self.num_episodes = cfg.SOLVER.NUM_EPISODES

        self.tetris = Tetris(cfg)
        self.agent = Agent(cfg,self.tetris)
class Keyboard:
    def __init__(self):
        self.T = Tetris(action_type='single', is_display=True)

    def run(self):
        while True:
            state = self.T.reset()
            done = False
            while not done:
                flag = False
                for evt in pygame.event.get():
                    if evt.type == pygame.QUIT:
                        exit()
                    if evt.type == pygame.KEYDOWN:
                        for idx, key in enumerate(key_actions):
                            if evt.key == eval("pygame.K_" + key):
                                state, _, done, _, _ = self.T.step(idx)
                                flag = True
                                pygame.time.wait(delay_time[idx])
                keys_pressed = pygame.key.get_pressed()
                if not flag:
                    for idx, key in enumerate(key_actions):
                        key = eval("pygame.K_" + key)
                        if keys_pressed[key]:
                            state, _, done, _, _ = self.T.step(idx)
                            if idx == [3, 4, 5, 6]:
                                pygame.time.wait(delay_time[idx])
                pygame.time.wait(10)
    def __init__(self):
        self.t = Tetris()
        self.action_space = spaces.Discrete(5)

        self.observation_space = spaces.Tuple(
            (spaces.Discrete(32), spaces.Discrete(4)))
        self.seed()
    def consumer(self, msg):
        if self.game is None:
            if 'snake' in msg:
                self.game = Snake(20, 25)
                self.run_thread()
            if 'tetris' in msg:
                self.game = Tetris(20, 25)
                self.run_thread()
        else:
            # fire all of the events
            if len(msg) > 0:
                #with self.lock:

                if 'left' in msg:
                    self.eventwatcher += self.game.on_left
                elif 'right' in msg:
                    self.eventwatcher += self.game.on_right
                elif 'up' in msg:
                    self.eventwatcher += self.game.on_up
                elif 'down' in msg:
                    self.eventwatcher += self.game.on_down
                elif 'abutton' in msg:
                    self.eventwatcher += self.game.on_a
                elif 'bbutton' in msg:
                    self.eventwatcher += self.game.on_b
Example #8
0
def main():
    game = Tetris()
    try:
        game.start_game()
    except Exception:
        pass
    curses.endwin()
Example #9
0
    def start_tetris(self):
        self.tetris = Tetris(self.app.ipcon)

        if self.tetris.okay:
            self.tetris.run_game_loop()

        self.tetris = None
Example #10
0
def main():
    game = Tetris(width=10, height=12)

    while not game.isFinished:
        # One game update
        game.update()
        print(game)
        time.sleep(0.2)
Example #11
0
 def get_fitness(self, chromosome, seed):
     """Return the fitness of a given chromosome."""
     agent = Agent(chromosome.chromosome)
     game = Tetris(WIDTH, HEIGHT, 0, 0, seed)  # simulate a game of Tetris
     while game.state != 0:
         agent.play(game.current_tetromino, game.grid)(game)
         game.update()
     chromosome.fitness = game.score.score
     print(f'Fitness: {chromosome.fitness}')
     return chromosome
Example #12
0
def playTetris(screen):
    graphics = TetrisGraphicsCurses(screen)
    controls = TetrisControlsCurses(screen)
    tetris = Tetris()
    while (tetris.state != Tetris.State.END):
        action = controls.readTetrisAction(tetris.state)
        actionOutput = tetris.action(action)
        tetrisOutput = tetris.update()
        for out in actionOutput, tetrisOutput:
            graphics.update(out)
Example #13
0
def start_game():
    global game

    game = Tetris()
    game.start()

    global action_report
    action_report = game.move_piece('up')

    return json.dumps(action_report.state)
Example #14
0
	def __init__(self):
		self.game = Tetris()
		self.led_display = LED_Module()
		self.led = MAX7219()
		self.to_show_led = ""
		self.showed_led = ""
		self.to_show_matrix = []
		self.showed_matrix = []
		self.state = ""
		self.change_state("PLAY")
		self.num = 0
Example #15
0
def lineClearIntegrationTest():
    height = 5
    width = 4
    tetris = Tetris(height, width)
    tetris.tetro = Tetromino(height - 1, 0, Tetris.TetrominoKind.I)
    tetris.state = Tetris.State.PLACE

    out = tetris.update()

    assert (out != None and Tetris.Output.LINE_CLEAR in out)
    _, clearedLines = out
    assert (clearedLines == [4])
Example #16
0
class Game:
    def __init__(self, p):
        self.die = False
        self.tetris = Tetris(20, 2, 20)
        self.bot = Bot(self.tetris, p)

    def draw(self):
        if not self.die:
            self.bot.run()
        self.tetris.run()
        if self.tetris.die:
            self.die = True
Example #17
0
def fallActuallyFalls():
    tetris = Tetris(20, 10)
    tetris.state == Tetris.State.FALLING
    tetro0 = Tetromino(0, 0, Tetris.TetrominoKind.O)
    tetris.tetro = copy.copy(tetro0)
    tetro1 = tetris.tetro

    tetris.moveDown(1)

    assert (tetro0.tetroKind == tetro1.tetroKind)
    assert (tetro0.col == tetro1.col)
    assert (tetro0.row + 1 == tetro1.row)
Example #18
0
 def __init__(self):
     super(TetrisEnv, self).__init__()
     self.game = Tetris()
     self.action_list = [
         self.game.left, self.game.right, self.game.up, self.game.down,
         self.rotatel, self.rotater, self.game.hold
     ]
     # up down left right hold rotateleft rotateright
     self.action_space = spaces.Discrete(7)
     self.observation_space = spaces.MultiDiscrete([2] * Tetris.width *
                                                   Tetris.height + [8] * 7 +
                                                   [8] + [2] + [8] + [4] +
                                                   [10] + [20])
     self.reset()
Example #19
0
def materializeNewTetrominoAfterPlace():
    tetris = Tetris(10, 10)
    tetris.state = Tetris.State.PLACE
    tetris.tetro = Tetromino(0, 5, Tetris.TetrominoKind.O)
    tetris.place()
    assert (tetris.state == Tetris.State.MATERIALIZE)
    tetris.materialize()
    assert (tetris.tetro.row == 0)
Example #20
0
def placeAfterFallingEnough():
    tetris = Tetris()
    tetris.state = Tetris.State.FALLING
    tetris.tetro = Tetromino(0, 0, Tetris.TetrominoKind.Z)
    tetris.moveDown(tetris.height)
    assert (tetris.state == Tetris.State.FALLING)
    tetris.moveDown(1)
    assert (tetris.state == Tetris.State.PLACE)
Example #21
0
    def __init__(self, stdscr):
        self.stdscr = stdscr
        self.init_curses()

        self.game_win = curses.newwin(visible_rows, block_width * num_cols, 0,
                                      0)
        self.info_win = curses.newwin(10, 20, 0, block_width * num_cols)
        self.debug_win = curses.newwin(10, 20, 10, block_width * num_cols)
        self.tetris = Tetris()

        self.pause = False
        self.debug = False

        self.fps_counter = 0
        self.frames_this_second = 0
        self.start_fps_timer = 0
    def getSimulator(self, simulator):
        if simulator == "logistics":
            return Logistics(start=True)

        elif simulator == "pong":
            return Pong(start=True)

        elif simulator == "tetris":
            return Tetris(start=True)

        elif simulator == "wumpus":
            return Wumpus(start=True)

        elif simulator == "blocks":
            return Blocks_world(start=True)

        elif simulator == "blackjack":
            return Game(start=True)

        elif simulator == "50chain":
            return Chain(start=True)

        elif simulator == "net_admin":
            return Admin(start=True)
        else:
            print('{} is not a supported simulation'.format(simulator))
            raise NameError()
Example #23
0
File: FATD.py Project: kkroy36/NIPS
 def __init__(self,FA="LSReg",domain="50chain",N=100,loss="ls",trees=500,type="max",depth=2):
     '''class constructor'''
     self.domain = domain
     if domain == "50chain":
         self.domObj = Chain()
     elif domain == "blackjack":
         self.domObj = Game()
     elif domain == "wumpus":
         self.domObj = Grid(4)
     elif domain == "blocksworld":
         self.domObj = BW(4)
     elif domain == "traffic":
         self.domObj = TrafficSignal()
     elif domain == "pong":
         self.domObj = Pong()
     elif domain == "tetris":
         self.domObj = Tetris()
     if FA == "LSReg":
         self.FA = LSReg()
     elif FA == "NN":
         self.FA = NeuralNetwork()
     elif FA == "GB":
         self.FA = GradientBooster(loss=loss,trees=trees,depth=depth)
     self.value,self.count = {},{}
     self.values = [{} for i in range(N)]
     self.approxValues = [{} for i in range(N)]
     self.BE = []
     self.type = type
     self.TD(self.FA,N)
Example #24
0
def new_client(client, server):
	global tetris, command, first_run
	id = client['id']
	print("New client(%d) connected" % id)
	tetris.insert(id, Tetris())
	command.insert(id, "")
	print("Game created")
Example #25
0
def make_env():
  #env = gym.envs.make(FLAGS.env)
  # remove the timelimitwrapper
  #env = env.env
  #if wrap:
   # env = atari_helpers.AtariEnvWrapper(env)
  return Tetris(action_type = FLAGS.action_type,use_fitness=True)
Example #26
0
File: FATD.py Project: kkroy36/NIPS
 def getSample(self):
     '''gets a sample trajectory from
        the specified domain
     '''
     d = Chain()
     if self.domain == "blackjack":
         d = Game()
     elif self.domain == "wumpus":
         d = Grid(4)
     elif self.domain == "blocksworld":
         d = BW(4)
     elif self.domain == "traffic":
         d = TrafficSignal()
     elif self.domain == "pong":
         d = Pong()
     elif self.domain == "tetris":
         d = Tetris()
     #elif wumpus
     sample = []
     state = d
     actions = d.actions
     while True:
         if state == "winner" or state == "loser":
             sample += [deepcopy(state)]
             break
         sample += [deepcopy(str(state))]
         action = actions[randint(0,len(actions)-1)]
         state = d.takeAction(state,action)
     return sample
Example #27
0
    def __init__(self, shadowsEnabled=True, automated=False):
        self.game = Tetris()

        Tk.__init__(self)
        self.canvas = Canvas(self,
                             width=TetrisWindow.DEFAULT_WIDTH,
                             height=TetrisWindow.DEFAULT_HEIGHT)
        self.canvas.pack(fill=BOTH, expand=1)
        self.needToRedraw = False
        self.shadowsEnabled = shadowsEnabled

        if not automated:
            self.refreshTimerFired()
            self.canvas.after(1000, self.gameTimerFired)
            self.bind("<Button-1>", self.mousePressed)
            self.bind("<Key>", self.keyPressed)
        self.canvas.bind("<Configure>", self.onResize)
Example #28
0
	def __init__(self):
		self.t = Tetris()

		state_num = 2**(4*8)*4*4*9*5  # 4x8 board [filled or not], 4*9 active-shape locations, 4 rotation positions, 5 shape types
		action_num = 4 # rotate, left, right, step
		P = {s : {a : [] for a in range(action_num)} for s in range(state_num)}

		init_state_dist = []
		for x in range(4):
			for rot in range(4):
				for shape_type in range(5):
					init_state_dist.append( encode([0, 0, x, rot, shape_type]) )

		init_state_dist = np.array(init_state_dist)
		init_state_dist /= init_state_dist.sum()

		super(TetrisEnv, self).__init__(state_num, action_num, P, init_state_dist)
Example #29
0
def hand_crafted():
    env = Tetris()
    current_state = env.reset()
    done = False
    steps = 0

    agent = Handcrafted_agent(env.get_state_size())

    # Game
    while not done:
        next_states = env.get_next_states_handcrafted()
        best_state = agent.best_state(next_states.values())
        
        best_action = None
        for action, state in next_states.items():
            if state == best_state:
                best_action = action
                break

        reward, done = env.play(best_action[0], best_action[1], render=True,
                                render_delay=None)
        
        current_state = next_states[best_action]
        steps += 1
    
    return env.get_game_score()
Example #30
0
    def __init__(self, d):
        display.App.__init__(self, d)

        self.menu_items = [('Clock', Clock(d)), ('Tetris', Tetris(d)),
                           ('Snake', Snake(d)), ('Off', Blank(d))]

        self.selected = 0

        self.font = pygame.font.Font("fonts/5x7.pcf", 7)
class TetrisWidget(QWidget, Ui_Tetris):
    tetris = None
    thread = None

    def __init__(self, parent, app):
        super(QWidget, self).__init__()
        self.app = app

        self.setupUi(self)

        self.button_a.pressed.connect(lambda: self.button_press('a'))
        self.button_s.pressed.connect(lambda: self.button_press('s'))
        self.button_d.pressed.connect(lambda: self.button_press('d'))
        self.button_k.pressed.connect(lambda: self.button_press('k'))
        self.button_l.pressed.connect(lambda: self.button_press('l'))
        self.button_r.pressed.connect(lambda: self.button_press('r'))

    def start_tetris(self):
        self.tetris = Tetris(self.app.ipcon)

        if self.tetris.okay:
            self.tetris.run_game_loop()

        self.tetris = None

    def button_press(self, button):
        if self.tetris:
            self.tetris.kp.key_queue.put(button)

    def start(self):
        self.thread = Thread(target=self.start_tetris)
        self.thread.daemon = True
        self.thread.start()

    def stop(self):
        if self.tetris:
            self.tetris.loop = False
            self.tetris.kp.key_queue.put('q')
Example #32
0
class QTetris(QWidget):

    class QTile(QGraphicsObject):
        colorMap = {Tetris.I: QColor("#53bbf4"), Tetris.J: QColor("#e25fb8"),
                    Tetris.L: QColor("#ffac00"), Tetris.O: QColor("#ecff2e"),
                    Tetris.S: QColor("#97eb00"), Tetris.T: QColor("#ff85cb"),
                    Tetris.Z: QColor("#ff5a48")}

        def __init__(self, qTetris: 'QTetris', tetrimino: Tetris.Tetrimino, tile: Tetris.Tile):
            super(QTetris.QTile, self).__init__()
            tile.delegate = self
            self.color = self.colorMap[type(tetrimino)]
            self.qTetris = qTetris
            self.moveAnimation = QParallelAnimationGroup()
            self.dropAnimation = QPropertyAnimation(self, b'pos')
            self.collapseAnimation = QPropertyAnimation(self, b'pos')
            self.shiftAnimation = QPropertyAnimation(self, b'pos')
            self.collapseAnimation.finished.connect(lambda tl=tile: tile.delegate.disappeared(tl))
            self.qTetris.scene.addItem(self)
            self.setPos(QPointF(0, 4))
            self.moved(tile)

        def moved(self, tile: Tetris.Tile):
            translation = QPropertyAnimation(self, b'pos')
            start, end = self.pos(), QPointF(tile.row, tile.column)
            curve, speed, delay = QEasingCurve.OutBack, 1 / 50, -1
            self.animate(translation, start, end, curve, speed, delay)

            rotation = QPropertyAnimation(self, b'rotation')
            start, end = self.rotation(), tile.rotation
            curve, speed, delay = QEasingCurve.OutBack, 1, -1
            self.animate(rotation, start, end, curve, speed, delay)
            rotation.setDuration(translation.duration())

            self.moveAnimation.clear()
            self.moveAnimation.addAnimation(translation)
            self.moveAnimation.addAnimation(rotation)
            self.moveAnimation.start()

        def dropped(self, tile: Tetris.Tile):
            start, end = self.pos(), QPointF(tile.row, tile.column)
            curve, speed, delay = QEasingCurve.OutBounce, 1 / 50, 0
            self.animate(self.dropAnimation, start, end, curve, speed, delay)

        def collapsed(self, tile: Tetris.Tile):
            start, end = self.pos(), QPointF(tile.row, tile.column + 2 * tile.tetris.num_columns)
            curve, speed, delay = QEasingCurve.InOutExpo, 1 / 50, 800
            if self.dropAnimation.state() == QAbstractAnimation.Running:
                start = self.dropAnimation.endValue()
            self.animate(self.collapseAnimation, start, end, curve, speed, delay)

        def shifted(self, tile: Tetris.Tile):
            start, end = self.pos(), QPointF(tile.row, tile.column)
            curve, speed, delay = QEasingCurve.OutBounce, 1 / 100, 1200
            if self.dropAnimation.state() == QAbstractAnimation.Running:
                start = self.dropAnimation.endValue()
            self.animate(self.shiftAnimation, start, end, curve, speed, delay)

        def disappeared(self, tile: Tetris.Tile):
            self.qTetris.scene.removeItem(self)

        def paint(self, painter: QPainter, styleOption: QStyleOptionGraphicsItem, widget: QWidget=None):
            pen = QPen()
            pen.setWidthF(0.05)
            pen.setColor(Qt.darkGray)
            painter.setPen(pen)
            brush = QBrush()
            brush.setColor(self.color)
            brush.setStyle(Qt.SolidPattern)
            painter.setBrush(brush)
            topLeft = QPointF(0, 0)
            bottomRight = QPointF(1, 1)
            rectangle = QRectF(topLeft, bottomRight)
            rectangle.translate(-0.5, -0.5)
            painter.drawRect(rectangle)

        @staticmethod
        def animate(animation: QPropertyAnimation, start: Union[QPointF, int, float], end: Union[QPointF, int, float],
                    curve: QEasingCurve=QEasingCurve.Linear, speed: float=1 / 50, delay: int=-1):
            animation.setStartValue(start)
            animation.setEndValue(end)
            animation.setEasingCurve(curve)
            if type(start) == type(end) == QPointF:
                distance = (end - start).manhattanLength()
            else:
                distance = abs(end - start)
            animation.setDuration(round(distance / speed))
            if delay == 0:
                animation.start()
            if delay > 0:
                QTimer.singleShot(delay, animation.start)

        def boundingRect(self):
            topLeft = QPointF(0, 0)
            bottomRight = QPointF(1, 1)
            rectangle = QRectF(topLeft, bottomRight)
            rectangle.translate(-0.5, -0.5)
            return rectangle

    class QScene(QGraphicsScene):
        def __init__(self, tetris: Tetris):
            super(QTetris.QScene, self).__init__()
            self.tetris = tetris

            pen = QPen()
            pen.setWidthF(0.05)
            pen.setColor(Qt.lightGray)
            brush = QBrush(Qt.NoBrush)
            rect = QRectF(0, 0, tetris.num_rows, tetris.num_columns)
            rect.translate(-0.5, -0.5)
            self.setSceneRect(rect)
            self.addRect(rect, pen, brush)
            self.setBackgroundBrush(self.palette().window())

            for column in range(0, tetris.num_columns, 2):
                pen = QPen(Qt.NoPen)
                brush = QBrush(Qt.SolidPattern)
                brush.setColor(Qt.lightGray)
                topLeft = QPointF(0, column)
                bottomRight = QPointF(tetris.num_rows, column + 1)
                rectangle = QRectF(topLeft, bottomRight)
                rectangle.translate(-0.5, -0.5)
                self.addRect(rectangle, pen, brush)

        def mouseMoveEvent(self, sceneMouseEvent: QGraphicsSceneMouseEvent):
            mousePoint = sceneMouseEvent.scenePos()
            mouseRow, mouseColumn = round(mousePoint.x()), round(mousePoint.y())
            row, column = self.tetris.falling_tetrimino.row, self.tetris.falling_tetrimino.column
            if mouseColumn - column > 0:
                self.tetris.move_right()
            if mouseColumn - column < 0:
                self.tetris.move_left()

        def mouseReleaseEvent(self, sceneMouseEvent: QGraphicsSceneMouseEvent):
            if sceneMouseEvent.button() == Qt.LeftButton:
                self.tetris.drop()
            if sceneMouseEvent.button() == Qt.RightButton:
                self.tetris.rotate()

        def wheelEvent(self, sceneWheelEvent: QGraphicsSceneWheelEvent):
            if sceneWheelEvent.delta() > 10:
                self.tetris.move_down()

        def keyReleaseEvent(self, sceneKeyEvent: QKeyEvent):
            if sceneKeyEvent.key() == Qt.Key_Left:
                self.tetris.move_left()
            if sceneKeyEvent.key() == Qt.Key_Right:
                self.tetris.move_right()
            if sceneKeyEvent.key() == Qt.Key_Down:
                self.tetris.move_down()
            if sceneKeyEvent.key() == Qt.Key_Up:
                self.tetris.rotate()

    class QView(QGraphicsView):
        def __init__(self, scene: 'QTetris.QScene'):
            super(QTetris.QView, self).__init__()
            self.setTransform(QTransform().rotate(+90).scale(+1, -1))
            self.setMinimumSize(100, 200)
            self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
            self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
            self.setRenderHints(QPainter.Antialiasing)
            self.setFrameStyle(QFrame.NoFrame)
            self.setMouseTracking(True)
            self.setScene(scene)

    def __init__(self):
        super(QTetris, self).__init__()
        self.tetris = None
        self.timer = None
        self.initGame()

        self.view = None
        self.scene = None
        self.initUI()

        self.show()
        self.tetris.spawn()
        self.timer.start()

    def initGame(self):
        self.tetris = Tetris()
        self.tetris.delegate = self
        self.timer = QTimer(self)
        self.timer.setInterval(350)
        self.timer.timeout.connect(lambda: self.tetris.tick())

    def initUI(self):
        self.setLayout(QGridLayout())
        self.layout().setSpacing(0)
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.scene = QTetris.QScene(self.tetris)
        self.view = QTetris.QView(self.scene)
        self.layout().addWidget(self.view)
        self.scored(0)

    def appeared(self, tetrimino: Tetris.Tetrimino):
        for tile in tetrimino:
            QTetris.QTile(self, tetrimino, tile)

    def scored(self, score: int):
        self.setWindowTitle(self.tr("Tetris - {score}").format(score=score))

    def terminated(self):
        QMessageBox.critical(self, self.tr("Game Over!"), self.tr("You toppped out."), QMessageBox.Ok)
        self.tetris.restart()

    def resizeEvent(self, resizeEvent: QResizeEvent):
        boundingRect = self.scene.itemsBoundingRect()
        self.view.fitInView(boundingRect, Qt.KeepAspectRatio)
        self.view.centerOn(boundingRect.center())

    def sizeHint(self) -> QSize:
        return QSize(self.tetris.num_columns * 22, self.tetris.num_rows * 22)
Example #33
0
from tetris import Tetris

game = Tetris()
game.initialize_game()
game.start()
Example #34
0
 def initGame(self):
     self.tetris = Tetris()
     self.tetris.delegate = self
     self.timer = QTimer(self)
     self.timer.setInterval(350)
     self.timer.timeout.connect(lambda: self.tetris.tick())