コード例 #1
0
ファイル: rnn_models.py プロジェクト: wanboyang/BRIMs
    def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, n_out=10, dropout=0.5, tie_weights=False, use_cudnn_version=True,
                 use_adaptive_softmax=False, cutoffs=None, discrete_input=True, num_blocks=[6], topk=[4], do_gru=False,
                 use_inactive=False, blocked_grad=False, layer_dilation = -1, block_dilation = -1, num_modules_read_input=2):
        super(RNNModel, self).__init__()

        self.topk = topk
        self.use_cudnn_version = use_cudnn_version
        self.drop = nn.Dropout(dropout)
        if discrete_input:
            self.encoder1 = nn.Embedding(ntoken, ninp//3)
            self.encoder2 = nn.Embedding(ntoken, ninp//3)
            self.encoder3 = nn.Embedding(ntoken, ninp//3)
        else:
            self.encoder1 = nn.Linear(ntoken, ninp//3)
            self.encoder2 = nn.Linear(ntoken, ninp//3)
            self.encoder3 = nn.Linear(ntoken, ninp//3)
        self.num_blocks = num_blocks
        self.nhid = nhid
        self.discrete_input = discrete_input
        self.sigmoid = nn.Sigmoid()
        self.sm = nn.Softmax(dim=1)
        self.use_inactive = use_inactive
        self.blocked_grad = blocked_grad
        self.rnn_type = rnn_type
        self.nlayers = nlayers
        self.use_adaptive_softmax = use_adaptive_softmax

        print("Dropout rate", dropout)

        self.decoder = nn.Linear(nhid[-1], n_out)

        self.init_weights()

        self.model = Blocks(ninp, nhid, nlayers, num_blocks, topk, use_inactive, blocked_grad)
コード例 #2
0
ファイル: rnn_models_new.py プロジェクト: zhangzx-sjtu/RIMs
    def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False, use_cudnn_version=True,
                 use_adaptive_softmax=False, cutoffs=None, discrete_input=True, num_blocks=[6], topk=[4], do_gru=False,
                 use_inactive=False, blocked_grad=False, layer_dilation = -1, block_dilation = -1):
        super(RNNModel, self).__init__()

        self.topk = topk
        self.use_cudnn_version = use_cudnn_version
        self.drop = nn.Dropout(dropout)
        if discrete_input:
            self.encoder = nn.Embedding(ntoken, ninp)
        else:
            self.encoder = nn.Linear(ntoken, ninp)
        self.num_blocks = num_blocks
        self.nhid = nhid
        self.discrete_input = discrete_input
        self.sigmoid = nn.Sigmoid()
        self.sm = nn.Softmax(dim=1)
        self.use_inactive = use_inactive
        self.blocked_grad = blocked_grad
        self.rnn_type = rnn_type
        self.nlayers = nlayers
        self.use_adaptive_softmax = use_adaptive_softmax

        print("Dropout rate", dropout)

        self.decoder = nn.Linear(nhid[-1], ntoken)
        if tie_weights:
            print('Tying Weights!')
            if nhid[-1] != ninp:
                raise ValueError('When using the tied flag, nhid must be equal to emsize')
            self.decoder.weight = self.encoder.weight

        self.init_weights()

        self.model = Blocks(ninp, nhid, nlayers, num_blocks, topk, use_inactive, blocked_grad)
コード例 #3
0
 def __init__(self, x, y, group):
     Blocks.__init__(self,
                     x,
                     y,
                     where_image='images\Blocks\spike.png',
                     group=group)
     self.type = 'spike'
コード例 #4
0
 def makeMap(self, blocks, dots, powerPills):
     size = self.settings.rectSize
     for row in self.lines:
         for chars in row:
             if chars == "X":
                 newBlock = Blocks(self.screen)
                 newBlock.rect.x, newBlock.rect.y = self.xShift, self.yShift
                 self.xShift += size
                 blocks.add(newBlock)
             elif chars == ".":
                 newDot = Dot(self.screen, self.settings)
                 newDot.rect.x, newDot.rect.y = self.xShift +size/4, self.yShift +size/4
                 self.xShift += size
                 dots.add(newDot)
             elif chars ==" ":
                 self.xShift += size
             elif chars == "o":
                 newPill = PowerPill(self.screen, self.settings)
                 newPill.rect.x, newPill.rect.y = self.xShift +size/4, self.yShift +size/4
                 powerPills.add(newPill)
                 self.xShift += size
             elif chars == "x":
                 newBlock = Blocks(self.screen)
                 newBlock.rect.x, newBlock.rect.y = self.xShift, self.yShift
                 newBlock.type = 1
                 self.xShift += size
                 blocks.add(newBlock)
         self.xShift = 0
         self.yShift += size
コード例 #5
0
ファイル: model.py プロジェクト: xarion/kaggle-tf-speech
    def __init__(self, data, parameters):
        self.parameters = parameters
        self.input = data.inputs
        self.labels = data.labels
        self.input_file_names = data.file_names
        self.blocks = Blocks()
        self.data = data

        self.models = {"default_mfcc_model": self.default_mfcc_model,
                       "unfinished_model": self.unfinished_model}
        self.models[self.parameters['model']]()
コード例 #6
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_pile_8_onto_2_same_column(self):
     self.blocks = Blocks(10)
     self.blocks.move_onto(8, 5)
     self.blocks.move_over(2, 8)
     self.blocks.move_over(7, 8)
     self.blocks.pile_onto(8, 2)
     self.assertEqual(self.blocks.blocks[5], [5, 8, 2, 7])
コード例 #7
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_pile_8_over_1(self):
     self.blocks = Blocks(10)
     self.blocks.move_onto(8, 5)
     self.blocks.move_over(6, 5)
     self.blocks.move_over(7, 5)
     self.blocks.pile_over(8, 1)
     self.assertEqual(self.blocks.blocks[1], [1, 8, 6, 7])
コード例 #8
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def setUp(self):
     self.blocks = Blocks()
     self.result = [
         [0],
         [1, 9, 2, 4],
         [],
         [3],
         [],
         [5, 8, 7, 6],
         [],
         [],
         [],
         []
     ]
     self.example = [
         [0],
         [1, 2, 3, 4],
         [],
         [],
         [],
         [5, 6, 7, 8],
         [],
         [],
         [],
         [9]
     ]
コード例 #9
0
ファイル: dematik.py プロジェクト: laniauj/dematik
    def __init__(self, backend, debug=False):
        # Debug mode means printing stack trace on errors
        self.debug = debug
        
        self.env = Environment(
            loader=PrefixLoader({
                'blocks-'+backend:   PackageLoader('dematik', 'blocks-'+backend),
                'macros-'+backend:   PackageLoader('dematik', 'macros-'+backend)
            }),
            autoescape=select_autoescape(['j2']),
            undefined=StrictUndefined
        )

        self.env.globals = {
            "now": datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
            "get_text" : self.get_text,
            "get_md_text" : self.get_md_text,
            "get_items" : self.get_items,
            "get_rows" : self.get_rows,
            "get_columns" : self.get_columns,
            "get_varname" : self.get_varname,
            "get_id" : self.get_id,
            "get_date_min" : self.get_date_min,
            "get_date_is_futur" : self.get_date_is_futur,
            "get_date_max" : self.get_date_max,
            "get_date_in_past" : self.get_date_in_past,
            "get_date_can_be_today" : self.get_date_can_be_today,
            "is_in_listing" : self.is_in_listing,
            "is_in_filters" : self.is_in_filters,
        }

        self.fields_data = FieldData()
        self.blocks = Blocks(self.env, ['blocks-'+backend])
        self.reset()
コード例 #10
0
ファイル: GameFunc.py プロジェクト: ramhue/Pacman
def makeMap(screen, maze, MyShield):

    line = ""
    allLines = []
    deltaX = 0
    deltaY = 0
    file = open("pacmanportalmaze.txt", "r")

    if file.mode == 'r':
        contents = file.read()
    for chars in contents:
        if chars != '\n':
            line += chars
        else:
            allLines.append(line)
            line = ""
    for line in allLines:
        for char in line:
            if char == 'X':
                newBlock = Blocks(screen)
                newBlock.rect.x, newBlock.rect.y = deltaX, deltaY
                maze.add(newBlock)
            elif char == 'o':
                newShield = Shield(screen)
                newShield.rect.x, newShield.rect.y = deltaX, (deltaY)
                MyShield.add(newShield)

            deltaX += 13
        deltaX = 0
        deltaY += 13
コード例 #11
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_pile_8_onto_1_with_9(self):
     self.blocks = Blocks(10)
     self.blocks.move_onto(8, 5)
     self.blocks.move_onto(9, 1)
     self.blocks.move_over(6, 5)
     self.blocks.move_over(7, 5)
     self.blocks.pile_onto(8, 1)
     self.assertEqual(self.blocks.blocks[1], [1, 8, 6, 7, 9])
コード例 #12
0
    def __init__(self, row, column, block_input, init_list=None):
        if row == None or column == None or block_input == None:
            print('argument : row, col, block_list, init_list.')
        else:
            # self.dimension = (row, column)
            self.blocks = Blocks(block_input)
            self.table_row = row
            self.table_col = column
            length = row * column
            self.table = {n: 'x' for n in range(1, length + 1)}
            if init_list == None:
                self.init_list = []
            else:
                self.init_list = init_list
                print("init_list :", self.init_list)
                self.load_block_init()

            print('table created. row:', row, ' x col:', column)
コード例 #13
0
ファイル: command.py プロジェクト: phinpho/SolvingUVa
 def read(self, line):
     if self.blocks is None:
         self.blocks = Blocks(int(line))
     else:
         if line == "quit":
             self.finish = True
             self.output()
         else:
             self.parse(line)
コード例 #14
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_final(self):
     self.blocks = Blocks(10)
     self.blocks.move_onto(9, 1)
     self.blocks.move_over(8, 1)
     self.blocks.move_over(7, 1)
     self.blocks.move_over(6, 1)
     self.blocks.pile_over(8, 6)
     self.blocks.pile_over(8, 5)
     self.blocks.move_over(2, 1)
     self.blocks.move_over(4, 9)
     self.assertEqual(self.blocks.blocks, self.result)
コード例 #15
0
    def __init__(self):
        pygame.init()  #初始化背景设置
        self.blocks_right = c * (block_size + 1)  #计算方格区右边界
        height = r * (block_size + 1)
        if height < 300:
            height = 300  #保证按键显示完全
        self.screen = pygame.display.set_mode(
            (self.blocks_right + 100, height))
        pygame.display.set_caption("Game Of Life")  #设置标题
        self.screen.fill(bg_color)
        self.core = Core(r, c)
        self.__init_lives()
        self.blocks = Blocks(r, c, block_size, self.screen,
                             self.core.get_now_state())
        self.blocks.draw_board()
        self.running = False
        self.time = time.time()
        self.__add_buttons()
        self.speed = 1

        return
コード例 #16
0
    def __init__(self, data, parameters):
        """
        :param training: If this is true some update ops and input pipeline will be created.
        The update ops are not necessarily used because training is True.
        """
        self.batch_size = parameters['batch_size']
        self.training = parameters["training"]
        self.label_on_value = parameters["label_on_value"]
        self.label_off_value = parameters["label_off_value"]
        self.decay_rate = parameters["decay_rate"]
        self.filter_size = parameters["filter_size"]
        self.stride_length = parameters["stride_length"]
        self.bigram_model = parameters["bigram_model"]
        self.num_bigrams = parameters["num_bigrams"]
        self.max_model_width = parameters["max_model_width"]
        self.global_avg_pooling = parameters["global_avg_pooling"]
        self.use_adam = parameters["use_adam"]
        self.sigmoid_unknown = parameters["sigmoid_unknown"]
        self.accuracy_regulated_decay = parameters["accuracy_regulated_decay"]
        self.loss_regulated_decay = parameters["loss_regulated_decay"]
        self.blocks = Blocks(self.training, parameters)
        self.model_width = parameters["model_width"]  # 32
        self.model_setup = map(
            lambda x: int(x.strip()),
            parameters["model_setup"].split(','))  # [0, 4, 4]
        self.input = data.inputs
        self.labels = data.labels
        self.input_file_names = data.file_names

        self.learning_rate = None
        self.logits = self.inference(self.input)

        self.top_1_accuracy = None
        self.loss = None
        self.train_step = None
        self.global_step = None
        self.one_hot_truth = None
        self.optimizer = None
        self.evaluation()
        self.optimize()
コード例 #17
0
ファイル: classes.py プロジェクト: bradur/pytetris
 def __init__(self, xy, text, action, size):
     super(MenuItem, self).__init__(size)
     from blocks import Blocks
     self.b = Blocks(size)
     self.action = action
     self.hovered = False
     self.text = text
     self.w, self.h = self.font.size(text)
     x, y = xy[0] - self.w / 2, xy[1]
     self.rect = pygame.Rect(x, y, self.w, self.h)
     self.s = pygame.Surface((self.b.size * 1.5 + self.w, self.h),
                             pygame.SRCALPHA, 32)
     self.s.convert_alpha()
     self.image = self.font.render(self.text, True, self.normalc)
     self.s.blit(self.image, (self.b.size * 1.5, 0))
     self.image = self.s
コード例 #18
0
ファイル: command.py プロジェクト: phinpho/SolvingUVa
class Command(object):

    blocks = None
    finish = False

    def read(self, line):
        if self.blocks is None:
            self.blocks = Blocks(int(line))
        else:
            if line == "quit":
                self.finish = True
                self.output()
            else:
                self.parse(line)

    def parse(self, line):
        action, block, pos, des = line.split(" ")
        if action == "move":
            if pos == "onto":
                self.blocks.move_onto(int(block), int(des))
            elif pos == "over":
                self.blocks.move_over(int(block), int(des))
        elif action == "pile":
            if pos == "onto":
                self.blocks.pile_onto(int(block), int(des))
            elif pos == "over":
                self.blocks.pile_over(int(block), int(des))

    def output(self):
        for i, blocks in enumerate(self.blocks.blocks):
            print "%d:" % i,
            for block in blocks:
                print "%d" % block,
            print

    def start(self):
        while not self.finish:
            self.read(raw_input())
コード例 #19
0
def readFile(screen, blocks, shield, powerpills, intersections):
    file = open("images/otherpacmanportalmaze.txt", "r")
    contents = file.read()
    line = ''
    all_lines = []
    for chars in contents:
        if chars != '\n':
            line += chars
        else:
            all_lines.append(line)
            line = ''
    i = 0
    j = 0
    intersection_num = 0
    for rows in all_lines:
        for chars in rows:
            if chars == 'X':
                new = Blocks(screen)
                new.rect.x, new.rect.y = 13 * i, 13 * j
                blocks.add(new)
            elif chars == 'd':
                thepowerpill = Powerpills(screen)
                thepowerpill.rect.x, thepowerpill.rect.y = 13 * i, 13 * j
                powerpills.add(thepowerpill)
            elif chars == 'b':
                thepowerpill = Powerpills(screen, 'big')
                thepowerpill.rect.x, thepowerpill.rect.y = 13 * i, 13 * j
                powerpills.add(thepowerpill)
            elif chars == 'i':
                intersection = Intersections(screen, intersection_num)
                intersection_num += 1
                intersection.rect.x, intersection.rect.y = 13 * i, 13 * j
                intersections.add(intersection)
            elif chars == 'o':
                theshield = Shield(screen)
                theshield.rect.x, theshield.rect.y = 13 * i, 13 * j
                shield.add(theshield)
            i += 1
        i = 0
        j += 1
コード例 #20
0
    def __init__(self, k, parameters):
        '''
        \fn Level(u, parameters)
        
        \brief Constructor default
    
        \param k - Level of fovea
        \param parameters - Parameters of fovea structure
        '''
        self.k = k  # Save level

        # Updating the image size parameter ( U ) was done in configuration of fovea

        if (parameters.typeShape == 0):  # Blocks
            self.boundingBox = []  # Clear boundingBox
            self.shapeLevel = []  # Clear shapeLevel
            self.boundingBox.append(self.getDelta(parameters))
            self.boundingBox.append(self.getSize(parameters))
            block = Blocks(self.boundingBox)
            self.shapeLevel.append(block)
        else:  # Polygons
            print("Shape wasn't configured")
コード例 #21
0
def readFile(screen, blocks, shield, powerpills, portal):
    file = open("images/otherpacmanportalmaze.txt", "r")
    contents = file.read()
    line = ''
    all_lines = []
    for chars in contents:
        if chars != '\n':
            line += chars
        else:
            all_lines.append(line)
            line = ''
    i = 0
    j = 0
    for rows in all_lines:
        for chars in rows:
            if chars == 'X':
                new = Blocks(screen)
                new.rect.x, new.rect.y = 13 * i, 13 * j
                blocks.add(new)
            elif chars == 'd':
                thepowerpill = Powerpills(screen)
                thepowerpill.rect.x, thepowerpill.rect.y = 13 * i, 13 * j
                powerpills.add(thepowerpill)
            elif chars == 'o':
                theshield = Shield(screen)
                theshield.rect.x, theshield.rect.y = 13 * i, 13 * j
                shield.add(theshield)
            # This is where the horizontal portal is supposed to be
            elif chars == 'h':
                pass
            # Vertical portal?
            elif chars == 'P':
                theportal = Portal(screen)
                theportal.rect.x, theportal.rect.y = 13 * i, 13 * j
                portal.add(theportal)
                pass
            i += 1
        i = 0
        j += 1
コード例 #22
0
def main():
    if len(sys.argv) != 2:
        print('usage:', sys.argv[0], '<filename>')
        exit(1)
    filename = sys.argv[1]
    try:
        stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        #stdscr.keypad(True)
        blocks = Blocks(stdscr)
        blocks.add_stdout('Stdout/Stderr', 8)
        manager = JupyterManager(blocks, sys.argv[1])
        manager.launch()
        manager.load(filename)
        stdscr.clear()
        print('Ctrl-J: Move block down')
        print('Ctrl-K: Move block up')
        print('Ctrl-P t: Create terminal')
        print('Ctrl-P e: Run external python')
        print('Ctrl-P o/O: Create new cell')
        print('         -> Press u for history')
        print('         -> Press Tab for eval')
        while True:
            try:
                blocks.render()
                blocks.wait()
                manager.clear_buffers()
                manager.save(filename)
            except KeyboardInterrupt:
                break
    finally:
        curses.nocbreak()
        stdscr.keypad(False)
        curses.echo()
        curses.endwin()
コード例 #23
0
class BlocksTests(TestCase):
    def setUp(self):
        self.blocks = Blocks()
        
    def test_get_set(self):
        self.blocks.set(box)
        self.assertEqual(self.blocks.get(), box)

    def test_get_set_with_moving(self):
        self.blocks.set(box_drop_after)
        self.assertEqual(self.blocks.get(), box_drop_after)

    def test_insert_new(self):
        self.blocks.set(box)
        self.blocks.insert_block("AE")
        self.assertEqual(self.blocks.get(), box_new_block)

    def test_insert_diamond(self):
        self.blocks.set(box)
        self.blocks.insert_diamond(1)
        self.assertEqual(self.blocks.get(), box_new_diamond)

    def test_drop(self):
        self.blocks.set(box_drop_before)
        self.blocks.drop()
        self.assertEqual(self.blocks.get(), box_drop_after)

    def test_drop_partial(self):
        self.blocks.set(box_drop_independent_before)
        self.blocks.drop()
        self.assertEqual(self.blocks.get(), box_drop_independent_after)

    def test_drop_result(self):
        self.blocks.set(box_drop_before)
        r = self.blocks.drop()
        self.assertEqual(r,[(3,0,'a',DOWN),(4,0,'e',DOWN)])
    
    def test_settle(self):
        self.blocks.set(box_settle_before)
        self.blocks.drop()
        self.assertEqual(self.blocks.get(), box_settle_after)

    def test_leftshift(self):
        self.blocks.set(box_shift_before)
        result = self.blocks.left_shift()
        self.assertEqual(self.blocks.get(), box_leftshift)
        self.assertTrue(result)
        
    def test_rightshift(self):
        self.blocks.set(box_shift_before)
        result = self.blocks.right_shift()
        self.assertEqual(self.blocks.get(), box_rightshift)
        self.assertTrue(result)

    def test_leftshift_return(self):
        self.blocks.set(box_shift_before)
        result = self.blocks.left_shift()
        self.assertEqual(result,[(3,1,'a',LEFT),(4,1,'e',LEFT)])

    def test_rightshift_return(self):
        self.blocks.set(box_shift_before)
        result = self.blocks.right_shift()
        self.assertEqual(result,[(3,1,'a',RIGHT),(4,1,'e',RIGHT)])

    def test_cannot_shift_without_moving(self):
        self.blocks.set(box)
        result = self.blocks.left_shift()
        self.assertFalse(result)
        self.assertEqual(self.blocks.get(), box)
        result = self.blocks.right_shift()
        self.assertFalse(result)
        self.assertEqual(self.blocks.get(), box)

    def test_cannot_leftshift(self):
        self.blocks.set(box_cannot_leftshift)
        result = self.blocks.left_shift()
        self.assertEqual(self.blocks.get(), box_cannot_leftshift)
        self.assertFalse(result)

    def test_cannot_rightshift(self):
        self.blocks.set(box_cannot_rightshift1)
        result = self.blocks.right_shift()
        self.assertEqual(self.blocks.get(), box_cannot_rightshift1)
        self.assertFalse(result)
        self.blocks.set(box_cannot_rightshift2)
        result = self.blocks.right_shift()
        self.assertFalse(result)
        self.assertEqual(self.blocks.get(), box_cannot_rightshift2)

    def test_rotate(self):
        self.blocks.set(box_rotate_1)
        for after in [box_rotate_2, box_rotate_3, box_rotate_4]:
            self.blocks.rotate()
            self.assertEqual(self.blocks.get(), after)

    def test_rotate_return(self):
        self.blocks.set(box_rotate_1)
        result = self.blocks.rotate()
        self.assertEqual(result, [(4,1,'e',DOWNLEFT)])

    def test_cannot_rotate(self):
        self.blocks.set(box_cannot_rotate)
        self.blocks.rotate()
        self.assertEqual(self.blocks.get(), box_cannot_rotate)

    def test_remove_single(self):
        self.blocks.set(box_remove_single_before)
        self.blocks.remove_multiplets()
        self.assertEqual(self.blocks.get(), box_remove_single_after)

    def test_remove_multi(self):
        self.blocks.set(box_remove_multi_before)
        self.blocks.remove_multiplets()
        self.assertEqual(self.blocks.get(), box_remove_multi_after)

    def test_drop_bricks(self):
        self.blocks.set(box_drop_bricks_before)
        result = self.blocks.drop_bricks()
        expected = [(2,2,'a',DOWN*2),(4,3,'b',DOWN*1),
                    (5,1,'e',DOWN*4),(5,0,'e',DOWN*4),
                    (6,4,'c',DOWN*1),(6,3,'d',DOWN*1)]
        self.assertEqual(self.blocks.get(), box_drop_bricks_after)
        for r,e in zip(result,expected):
            self.assertEqual(r[0],e[0])
            self.assertEqual(r[1],e[1])
            self.assertEqual(r[2],e[2])
            self.assertEqual(sum(r[3]==e[3]),2)
            

    def test_remove_and_drop(self):
        self.blocks.set(box_drop_remove_before)
        self.blocks.remove_multiplets()
        self.blocks.drop_bricks()
        self.assertEqual(self.blocks.get(), box_drop_remove_after)

    def test_remove_consecutive(self):
        self.blocks.set(box_remove_consecutive_before)
        self.blocks.remove_consecutive()
        self.assertEqual(self.blocks.get(), box_remove_consecutive_after)

    def test_box_overflow(self):
        self.blocks.set(box_game_over)
        self.assertTrue(self.blocks.box_overflow())
        self.blocks.set(box_not_game_over)
        self.assertFalse(self.blocks.box_overflow())

    def test_get_stack_size(self):
        """returns height of the pile"""
        self.blocks.set(box)
        self.assertEqual(self.blocks.get_stack_size(),5)
        self.blocks.set(box_drop_after)
        self.assertEqual(self.blocks.get_stack_size(),5)
        self.blocks.set(box_remove_multi_after)
        self.assertEqual(self.blocks.get_stack_size(),3)
コード例 #24
0
from blocks import Blocks, block_dataset

blocks = Blocks(block_dataset) 

# print("test", block.block_list)
print("test", blocks.block_used)
print("mark #2 block used")
blocks.show_blocks()
blocks.mark_used(2)
blocks.show_blocks()
コード例 #25
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_pile_8_onto_1(self):
     self.blocks = Blocks(10)
     self.blocks.pile_onto(8, 1)
     self.assertEqual(self.blocks.blocks[1], [1, 8])
コード例 #26
0
class Model:
    def __init__(self, data, parameters):
        """
        :param training: If this is true some update ops and input pipeline will be created.
        The update ops are not necessarily used because training is True.
        """
        self.batch_size = parameters['batch_size']
        self.training = parameters["training"]
        self.label_on_value = parameters["label_on_value"]
        self.label_off_value = parameters["label_off_value"]
        self.decay_rate = parameters["decay_rate"]
        self.filter_size = parameters["filter_size"]
        self.stride_length = parameters["stride_length"]
        self.bigram_model = parameters["bigram_model"]
        self.num_bigrams = parameters["num_bigrams"]
        self.max_model_width = parameters["max_model_width"]
        self.global_avg_pooling = parameters["global_avg_pooling"]
        self.use_adam = parameters["use_adam"]
        self.sigmoid_unknown = parameters["sigmoid_unknown"]
        self.accuracy_regulated_decay = parameters["accuracy_regulated_decay"]
        self.loss_regulated_decay = parameters["loss_regulated_decay"]
        self.blocks = Blocks(self.training, parameters)
        self.model_width = parameters["model_width"]  # 32
        self.model_setup = map(lambda x: int(x.strip()), parameters["model_setup"].split(','))  # [0, 4, 4]
        self.input = data.inputs
        self.labels = data.labels
        self.input_file_names = data.file_names

        self.learning_rate = None
        self.logits = self.inference(self.input)

        self.top_1_accuracy = None
        self.loss = None
        self.train_step = None
        self.global_step = None
        self.one_hot_truth = None
        self.optimizer = None
        self.evaluation()
        self.optimize()
        # dummy variable that is temporarily ignored

    def inference(self, preprocessed_input):

        channels = self.model_width

        with tf.variable_scope("conv_1_1"):
            conv_1_1 = self.blocks.conv2d_with_filter(preprocessed_input,
                                                      filter_size=[20, 8],
                                                      input_channels=1,
                                                      output_channels=channels,
                                                      strides=1,
                                                      padding="VALID")
        residual_layer = conv_1_1
        input_channels = channels

        for residual_block_set in range(0, len(self.model_setup)):
            output_channels = input_channels * 2
            if self.max_model_width < output_channels:
                output_channels = self.max_model_width

            if self.model_setup[residual_block_set] == 0:
                residual_layer = tf.nn.max_pool(residual_layer, ksize=[1, self.filter_size, 1, 1],
                                                strides=[1, self.stride_length, 1, 1],
                                                padding="SAME")

            for residual_block in range(0, self.model_setup[residual_block_set]):
                with tf.variable_scope("conv_%d_%d" % (residual_block_set + 2, residual_block + 1)):
                    residual_layer = self.blocks.residual_separable(residual_layer,
                                                                    input_channels=input_channels,
                                                                    output_channels=output_channels,
                                                                    strides=self.stride_length if residual_block == 0 else 1,
                                                                    activate_before_residual=residual_block == 0)
                    input_channels = output_channels

        if self.bigram_model:
            with tf.variable_scope("bigram"):
                output_channels = self.num_bigrams
                residual_layer = self.blocks.conv2d(residual_layer,
                                                    filter_size=2,
                                                    input_channels=input_channels,
                                                    output_channels=output_channels,
                                                    strides=1)
                input_channels = output_channels

        if self.global_avg_pooling:
            with tf.variable_scope("global_pooling"):
                # global average pooling
                residual_layer = tf.reduce_max(residual_layer, [1, 2])
                residual_layer = self.blocks.batch_normalization(residual_layer)
                residual_layer = self.blocks.relu(residual_layer)
                # residual_layer = self.blocks.biased_fc(residual_layer,
                #                                                input_channels=input_channels,
                #                                                output_channels=input_channels)
                # residual_layer = self.blocks.batch_normalization(residual_layer)
                # residual_layer = self.blocks.relu(residual_layer)
        else:
            with tf.variable_scope("flatten"):
                shape = residual_layer.shape
                dims = shape[1].value * shape[2].value * shape[3].value
                residual_layer = tf.reshape(residual_layer, shape=[-1, dims])
                output_channels = dims
                input_channels = output_channels
                residual_layer = self.blocks.batch_normalization(residual_layer)
                residual_layer = self.blocks.relu(residual_layer)

        with tf.variable_scope("output"):
            logits = self.blocks.biased_fc(residual_layer,
                                           input_channels=input_channels,
                                           output_channels=12)
            self.freeze_layer = logits
        return logits

    def optimize(self):
        with tf.variable_scope('loss'):
            if not self.sigmoid_unknown:
                self.one_hot_truth = tf.squeeze(tf.one_hot(self.labels, 12,
                                                           on_value=self.label_on_value,
                                                           off_value=self.label_off_value))
                cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits, labels=self.one_hot_truth)
                self.loss = tf.reduce_mean(cross_entropy)
            else:
                self.one_hot_truth = tf.squeeze(tf.one_hot(self.labels, 12,
                                                           on_value=self.label_on_value,
                                                           off_value=self.label_off_value))
                class_cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits[:, :11],
                                                                              labels=self.one_hot_truth[:, :11])
                class_results = tf.reduce_max(self.one_hot_truth[:, :11], axis=1)
                sigmoid_labels = (self.one_hot_truth[:, 11:]) * 0.97
                silent_unknown_cross_entropy = \
                    tf.nn.sigmoid_cross_entropy_with_logits(logits=self.logits[:, 11:],
                                                            labels=sigmoid_labels)

                self.loss = tf.reduce_mean(class_cross_entropy * class_results)
                self.loss += tf.reduce_mean(silent_unknown_cross_entropy)
                self.loss += (1. - self.accuracy)

            if self.accuracy_regulated_decay:
                self.loss = self.loss + (1 - self.accuracy) * self.decay()
            elif self.loss_regulated_decay:
                self.loss = self.loss + self.loss * self.decay()
            else:
                self.loss = self.loss + self.decay()
            tf.add_to_collection('losses', self.loss)
            tf.summary.scalar('loss_total', self.loss)

        with tf.variable_scope('train'):
            self.global_step = tf.Variable(0, name='global_step', trainable=False)
            self.probabilities = tf.nn.softmax(self.logits)

            if self.use_adam:
                self.optimizer = tf.train.AdamOptimizer()
            else:
                boundaries = [25000, 35000]
                values = [0.1, 0.01, 0.001]

                self.learning_rate = tf.train.piecewise_constant(self.global_step, boundaries, values)
                tf.summary.scalar('learning_rate', self.learning_rate)

                self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)

            update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
            with tf.control_dependencies(update_ops):
                self.training_step = self.optimizer.minimize(self.loss, global_step=self.global_step)

    def evaluation(self):
        with tf.variable_scope('accuracy'):
            if not self.sigmoid_unknown:
                self.prediction = tf.cast(tf.argmax(self.logits, 1), tf.int32)
            else:
                class_predictions = tf.cast(tf.argmax(self.logits[:, :11], 1), tf.int32)
                silent_unknown_sigmoids = tf.nn.sigmoid(self.logits[:, 11:])
                silent_unknown_labels = tf.cast(tf.argmax(silent_unknown_sigmoids, 1), tf.int32) + 11
                accepted_silent_unknown_labels = tf.cast(
                    tf.greater_equal(tf.reduce_max(silent_unknown_sigmoids, axis=1), 0.2), tf.int32)
                self.prediction = \
                    class_predictions - (class_predictions * accepted_silent_unknown_labels) \
                    + silent_unknown_labels * accepted_silent_unknown_labels

            correct_prediction = tf.equal(self.prediction, self.labels)
            self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

            tf.summary.scalar('accuracy_top1', self.accuracy)
        with tf.variable_scope("confusion_matrix"):
            self.confusion_matrix = tf.confusion_matrix(self.labels, self.prediction)

    def decay(self):
        """L2 weight decay loss."""
        costs = list()
        for var in self.blocks.get_decayed_variables():
            costs.append(tf.nn.l2_loss(var))

        decay = tf.reduce_sum(costs)
        tf.summary.scalar('decay', decay)

        return tf.multiply(self.decay_rate, decay)
コード例 #27
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_constructor_settings_size(self):
     self.blocks = Blocks(10)
     self.assertEqual(len(self.blocks.blocks), 10)
コード例 #28
0
ファイル: rnn_models_new.py プロジェクト: zhangzx-sjtu/RIMs
class RNNModel(nn.Module):
    """Container module with an encoder, a recurrent module, and a decoder."""

    def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, tie_weights=False, use_cudnn_version=True,
                 use_adaptive_softmax=False, cutoffs=None, discrete_input=True, num_blocks=[6], topk=[4], do_gru=False,
                 use_inactive=False, blocked_grad=False, layer_dilation = -1, block_dilation = -1):
        super(RNNModel, self).__init__()

        self.topk = topk
        self.use_cudnn_version = use_cudnn_version
        self.drop = nn.Dropout(dropout)
        if discrete_input:
            self.encoder = nn.Embedding(ntoken, ninp)
        else:
            self.encoder = nn.Linear(ntoken, ninp)
        self.num_blocks = num_blocks
        self.nhid = nhid
        self.discrete_input = discrete_input
        self.sigmoid = nn.Sigmoid()
        self.sm = nn.Softmax(dim=1)
        self.use_inactive = use_inactive
        self.blocked_grad = blocked_grad
        self.rnn_type = rnn_type
        self.nlayers = nlayers
        self.use_adaptive_softmax = use_adaptive_softmax

        print("Dropout rate", dropout)

        self.decoder = nn.Linear(nhid[-1], ntoken)
        if tie_weights:
            print('Tying Weights!')
            if nhid[-1] != ninp:
                raise ValueError('When using the tied flag, nhid must be equal to emsize')
            self.decoder.weight = self.encoder.weight

        self.init_weights()

        self.model = Blocks(ninp, nhid, nlayers, num_blocks, topk, use_inactive, blocked_grad)

    def init_weights(self):
        initrange = 0.1
        self.encoder.weight.data.uniform_(-initrange, initrange)
        if not self.use_adaptive_softmax:
            self.decoder.bias.data.zero_()
            self.decoder.weight.data.uniform_(-initrange, initrange)

    def forward(self, input, hidden, calc_mask=False):
        extra_loss = 0.0

        emb = self.drop(self.encoder(input))

        hx, cx = hidden
        masks = []
        output = []

        self.model.blockify_params()

        for idx_step in range(input.shape[0]):
            hx, cx, mask = self.model(emb[idx_step], hx, cx, idx_step)
            masks.append(mask)
            output.append(hx[-1])

        hidden = (hx,cx)
        output = torch.stack(output)
        output = self.drop(output)

        dec = output.view(output.size(0) * output.size(1), self.nhid[-1])
        dec = self.decoder(dec)

        average_masks = [[] for _ in range(self.nlayers)]
        sample_masks = [[] for _ in range(self.nlayers)]

        if calc_mask:
            for idx_step, layer_mask in enumerate(masks):
                for idx_layer, mask in enumerate(layer_mask):
                    mk = mask.view(mask.size()[0], self.num_blocks[idx_layer], self.nhid[idx_layer] // self.num_blocks[idx_layer])
                    mk = torch.mean(mk, dim=2)
                    sample_masks[idx_layer].append(mk[0])
                    mk = torch.mean(mk, dim=0)
                    average_masks[idx_layer].append(mk)

        if calc_mask:
            for idx_layer in range(self.nlayers):
                average_masks[idx_layer] = torch.stack(average_masks[idx_layer]).view(input.shape[0],self.num_blocks[idx_layer]).transpose(1,0)
                sample_masks[idx_layer] = torch.stack(sample_masks[idx_layer]).view(input.shape[0],self.num_blocks[idx_layer]).transpose(1,0)

        if calc_mask:
            return dec.view(output.size(0), output.size(1), dec.size(1)), hidden, extra_loss, average_masks, sample_masks
        else:
            return dec.view(output.size(0), output.size(1), dec.size(1)), hidden, extra_loss, None, None

    def init_hidden(self, bsz):
        hx, cx = [],[]
        weight = next(self.model.bc_lst[0].block_lstm.parameters())
        for i in range(self.nlayers):
            hx.append(weight.new_zeros(bsz, self.nhid[i]))
            cx.append(weight.new_zeros(bsz, self.nhid[i]))

        return (hx,cx)
コード例 #29
0
ファイル: schem2bp.py プロジェクト: thepaka/StarMade
def schem2bp(fileName, opt_expand = False):

    # Load NBT

    nbtfile = nbt.NBTFile(fileName, 'rb')

    # Compute values

    height = nbtfile['Height'].value
    length = nbtfile['Length'].value
    width = nbtfile['Width'].value

    b = Blocks(width, height, length)
    b.datas = nbtfile['Data'].value
    b.ids = nbtfile['Blocks'].value

    # Expand
    if opt_expand:
        expand(b, 2)

    # The ship core will be the bedrock block (id 7)
    b.set_orig_on_blockid(7)

    pos = b.index_to_pos(len(b.datas)-1)
    print "Last block : x=%2d, y=%2d, z=%2d" % pos

    datas = {}
    blocks_counter = {}
    for i in xrange(0, len(b.datas)):
        pos = b.index_to_pos(i)
        id, data = b.get(pos)

        if id:
            chunk_pos = ( pos[0] / 16 * 16,  pos[1] / 16 * 16,  pos[2] / 16 * 16 )

            data_pos = ( (chunk_pos[0] + 128) / 255 ,
                         (chunk_pos[1] + 128) / 255 ,
                         (chunk_pos[2] + 128) / 255 )

            if not data_pos in datas:
                print "New data (%2d, %2d, %2d)" % data_pos
                datas[data_pos] = {}

            if not chunk_pos in datas[data_pos]:
                print "New chunk (%2d, %2d, %2d)" % chunk_pos
                datas[data_pos][chunk_pos] = {}

            x_off = chunk_pos[0]
            y_off = chunk_pos[1]
            z_off = chunk_pos[2]

            id, hp, active, orient = resolver.minecraft_to_starmade( id, data )

            block_pos = (pos[0] - x_off, pos[1] - y_off, pos[2] - z_off)
            datas[data_pos][chunk_pos][block_pos] = {
                'id': id,
                'hp': hp,
                'active': active,
                'orient': orient
            }

            if not id in blocks_counter:
                blocks_counter[id]=1
            else:
                blocks_counter[id]+=1

    # Create blueprint

    basename = os.path.basename(fileName)
    bpname = os.path.splitext(basename)[0]

    bp = {
        'datas': {},
        'header': {
                'blocks': blocks_counter,
                'bounds_a': ( b.orig[0] - 1.0,
                              b.orig[1] - 1.0,
                              b.orig[2] - 1.0),
                'bounds_b': ( b.orig[0] + b.width + 0.0,
                              b.orig[1] + b.height + 0.0,
                              b.orig[2] + b.length + 0.0),
                'int_a': 0,
                'int_b': 0},
        'logic': {'controllers': [], 'int_a': 0},
        'meta': {'byte_a': 1, 'int_a': 0}
    }

    for data in datas:

        data_filename = "ENTITY_SHIP_%s.%d.%d.%d.smd2" %  ((bpname, ) + data)

        bp_d = bp['datas'][data_filename] = {
                'chunk_index': {},
                'chunk_timestamps': {},
                'chunks': [],
                'filelen': 0,
                'int_a': 0,
                'pos': data
        }

        ci = 0
        for chunk in datas[data]:

            pos_index = blueprint.indexed_pos( chunk, data )

            bp_d['chunk_index'][pos_index] = {
                'id' : ci,
                'len' : 0
            }
            bp_d['chunk_timestamps'][pos_index] = int(time.time()* 1000)
            bp_d['chunks'].append({
                'blocks': datas[data][chunk],
                'pos': chunk,
                'timestamp': int(time.time()* 1000),
                'type': 1
            })
            ci += 1

    blueprint.writeBlueprint(bpname, bp)
コード例 #30
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_remove_block_9(self):
     self.blocks = Blocks(10)
     self.blocks.blocks = self.result
     self.blocks.remove_block(1, 1)
     self.assertEqual(self.blocks.blocks[1][1], 2)
コード例 #31
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_position_index(self):
     self.blocks = Blocks(10)
     self.blocks.blocks = self.result
     positions = self.blocks.position(9)
     self.assertEqual(positions, (1, 1))
コード例 #32
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_update_blocks_structure(self):
     self.blocks = Blocks(10)
     self.assertEqual(type(self.blocks.blocks[0]), type([]))
コード例 #33
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
class TestBlocks(unittest.TestCase):

    def setUp(self):
        self.blocks = Blocks()
        self.result = [
            [0],
            [1, 9, 2, 4],
            [],
            [3],
            [],
            [5, 8, 7, 6],
            [],
            [],
            [],
            []
        ]
        self.example = [
            [0],
            [1, 2, 3, 4],
            [],
            [],
            [],
            [5, 6, 7, 8],
            [],
            [],
            [],
            [9]
        ]

    def test_amount_blocks(self):
        self.blocks.set_size(10)
        self.assertEqual(len(self.blocks.blocks), 10)

    def test_constructor_settings_size(self):
        self.blocks = Blocks(10)
        self.assertEqual(len(self.blocks.blocks), 10)

    def test_update_blocks_structure(self):
        self.blocks = Blocks(10)
        self.assertEqual(type(self.blocks.blocks[0]), type([]))

    def test_position_index(self):
        self.blocks = Blocks(10)
        self.blocks.blocks = self.result
        positions = self.blocks.position(9)
        self.assertEqual(positions, (1, 1))

    def test_remove_block_9(self):
        self.blocks = Blocks(10)
        self.blocks.blocks = self.result
        self.blocks.remove_block(1, 1)
        self.assertEqual(self.blocks.blocks[1][1], 2)

    def test_remove_block_4(self):
        self.blocks = Blocks(10)
        self.blocks.blocks = self.result
        self.blocks.remove_block(1, 3)
        with self.assertRaises(IndexError):
            self.blocks.blocks[1][3]

    def test_check_pile_movement_same_pile(self):
        self.blocks = Blocks(10)
        self.blocks.blocks = self.example
        check = self.blocks.check_pile_movement(2, 3)
        self.assertFalse(check)

    def test_check_pile_movement_different_pile(self):
        self.blocks = Blocks(10)
        self.blocks.blocks = self.example
        check = self.blocks.check_pile_movement(6, 2)
        self.assertTrue(check)

    def test_remove_pile_2(self):
        self.blocks = Blocks(10)
        self.blocks.blocks = self.example
        pile = self.blocks.remove_pile(2)
        self.assertEqual(self.blocks.blocks[1], [1])
        self.assertEqual(pile, [2, 3, 4])

    def test_remove_pile_4(self):
        self.blocks = Blocks(10)
        self.blocks.blocks = self.example
        pile = self.blocks.remove_pile(4)
        self.assertEqual(self.blocks.blocks[1], [1, 2, 3])
        self.assertEqual(pile, [4])

    def test_move_9_onto_1(self):
        self.blocks = Blocks(10)
        self.blocks.move_onto(9, 1)
        self.assertEqual(self.blocks.blocks[1], [1, 9])

    def test_move_9_over_1(self):
        self.blocks = Blocks(10)
        self.blocks.move_over(9, 1)
        self.blocks.move_over(2, 1)
        self.assertEqual(self.blocks.blocks[1], [1, 9, 2])

    def test_pile_8_onto_1(self):
        self.blocks = Blocks(10)
        self.blocks.pile_onto(8, 1)
        self.assertEqual(self.blocks.blocks[1], [1, 8])

    def test_pile_8_onto_1(self):
        self.blocks = Blocks(10)
        self.blocks.move_onto(8, 5)
        self.blocks.move_over(6, 5)
        self.blocks.move_over(7, 5)
        self.blocks.pile_onto(8, 1)
        self.assertEqual(self.blocks.blocks[1], [1, 8, 6, 7])

    def test_pile_8_onto_2_same_column(self):
        self.blocks = Blocks(10)
        self.blocks.move_onto(8, 5)
        self.blocks.move_over(2, 8)
        self.blocks.move_over(7, 8)
        self.blocks.pile_onto(8, 2)
        self.assertEqual(self.blocks.blocks[5], [5, 8, 2, 7])

    def test_pile_8_onto_1_with_9(self):
        self.blocks = Blocks(10)
        self.blocks.move_onto(8, 5)
        self.blocks.move_onto(9, 1)
        self.blocks.move_over(6, 5)
        self.blocks.move_over(7, 5)
        self.blocks.pile_onto(8, 1)
        self.assertEqual(self.blocks.blocks[1], [1, 8, 6, 7, 9])

    def test_pile_8_over_1(self):
        self.blocks = Blocks(10)
        self.blocks.move_onto(8, 5)
        self.blocks.move_over(6, 5)
        self.blocks.move_over(7, 5)
        self.blocks.pile_over(8, 1)
        self.assertEqual(self.blocks.blocks[1], [1, 8, 6, 7])

    def test_pile_8_over_1_with_9(self):
        self.blocks = Blocks(10)
        self.blocks.move_onto(8, 5)
        self.blocks.move_onto(9, 1)
        self.blocks.move_over(6, 5)
        self.blocks.move_over(7, 5)
        self.blocks.pile_onto(8, 1)
        self.assertEqual(self.blocks.blocks[1], [1, 8, 6, 7, 9])

    def test_final(self):
        self.blocks = Blocks(10)
        self.blocks.move_onto(9, 1)
        self.blocks.move_over(8, 1)
        self.blocks.move_over(7, 1)
        self.blocks.move_over(6, 1)
        self.blocks.pile_over(8, 6)
        self.blocks.pile_over(8, 5)
        self.blocks.move_over(2, 1)
        self.blocks.move_over(4, 9)
        self.assertEqual(self.blocks.blocks, self.result)
コード例 #34
0
 def setUp(self):
     self.blocks = Blocks()
コード例 #35
0
 def setUp(self):
     self.tetris = Tetris()
     self.display = pygame.display.set_mode((800, 700))
     self.gameloop = GameLoop(self.display)
     self.blocks = Blocks()
コード例 #36
0
ファイル: rnn_models.py プロジェクト: wanboyang/BRIMs
class RNNModel(nn.Module):
    """Container module with an encoder, a recurrent module, and a decoder."""

    def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, n_out=10, dropout=0.5, tie_weights=False, use_cudnn_version=True,
                 use_adaptive_softmax=False, cutoffs=None, discrete_input=True, num_blocks=[6], topk=[4], do_gru=False,
                 use_inactive=False, blocked_grad=False, layer_dilation = -1, block_dilation = -1, num_modules_read_input=2):
        super(RNNModel, self).__init__()

        self.topk = topk
        self.use_cudnn_version = use_cudnn_version
        self.drop = nn.Dropout(dropout)
        if discrete_input:
            self.encoder1 = nn.Embedding(ntoken, ninp//3)
            self.encoder2 = nn.Embedding(ntoken, ninp//3)
            self.encoder3 = nn.Embedding(ntoken, ninp//3)
        else:
            self.encoder1 = nn.Linear(ntoken, ninp//3)
            self.encoder2 = nn.Linear(ntoken, ninp//3)
            self.encoder3 = nn.Linear(ntoken, ninp//3)
        self.num_blocks = num_blocks
        self.nhid = nhid
        self.discrete_input = discrete_input
        self.sigmoid = nn.Sigmoid()
        self.sm = nn.Softmax(dim=1)
        self.use_inactive = use_inactive
        self.blocked_grad = blocked_grad
        self.rnn_type = rnn_type
        self.nlayers = nlayers
        self.use_adaptive_softmax = use_adaptive_softmax

        print("Dropout rate", dropout)

        self.decoder = nn.Linear(nhid[-1], n_out)

        self.init_weights()

        self.model = Blocks(ninp, nhid, nlayers, num_blocks, topk, use_inactive, blocked_grad)

    def init_weights(self):
        initrange = 0.1
        self.encoder1.weight.data.uniform_(-initrange, initrange)
        self.encoder2.weight.data.uniform_(-initrange, initrange)
        self.encoder3.weight.data.uniform_(-initrange, initrange)
        if not self.use_adaptive_softmax:
            self.decoder.bias.data.zero_()
            self.decoder.weight.data.uniform_(-initrange, initrange)

    def forward(self, input, hidden, calc_mask=False):
        extra_loss = 0.0

        emb1 = self.drop(self.encoder1(input[:,:,0]))
        emb2 = self.drop(self.encoder2(input[:,:,1]))
        emb3 = self.drop(self.encoder3(input[:,:,2]))

        emb = torch.cat([emb1, emb2, emb3], dim=2)

        hx, cx = hidden
        masks = []
        output = []

        self.model.blockify_params()

        for idx_step in range(input.shape[0]):
            hx, cx = self.model(emb[idx_step], hx, cx, idx_step)
            output.append(hx[-1])

        hidden = (hx,cx)
        output = torch.stack(output)
        output = self.drop(output)

        dec = output.view(output.size(0) * output.size(1), self.nhid[-1])
        dec = self.decoder(dec)

        if calc_mask:
            return dec.view(output.size(0), output.size(1), dec.size(1)), hidden
        else:
            return dec.view(output.size(0), output.size(1), dec.size(1)), hidden

    def init_hidden(self, bsz):
        hx, cx = [],[]
        weight = next(self.model.bc_lst[0].block_lstm.parameters())
        for i in range(self.nlayers):
            hx.append(weight.new_zeros(bsz, self.nhid[i]))
            cx.append(weight.new_zeros(bsz, self.nhid[i]))

        return (hx,cx)
コード例 #37
0
    def plansza2(self):
        """Rysuje drugą planszę."""

        j = self.screen_height / 2 - 50
        while j > 30:

            block = Blocks(10, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            j = j - 60

        j = self.screen_height / 2 - 25
        while j > 30:

            block = Blocks(90, j, 'data/wood_brick.png')
            self.BlocksSprite.add(block)
            j = j - 60

        j = self.screen_height / 2 - 50
        while j > 30:

            block = Blocks(170, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            j = j - 60

        ####

        j = self.screen_height / 2 - 50
        while j > 30:

            block = Blocks(self.screen_width - 90, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            j = j - 60

        j = self.screen_height / 2 - 25
        while j > 30:

            block = Blocks(self.screen_width - 170, j, 'data/wood_brick.png')
            self.BlocksSprite.add(block)
            j = j - 60

        j = self.screen_height / 2 - 50
        while j > 30:

            block = Blocks(self.screen_width - 250, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            j = j - 60

        ###

        j = self.screen_height / 2 - 50
        for k in range(8):
            block = Blocks(270, j, 'data/light_wood_brick.png')
            self.BlocksSprite.add(block)
            j = j - 30

        j = self.screen_height / 2 - 50
        for k in range(8):
            block = Blocks(450, j, 'data/light_wood_brick.png')
            self.BlocksSprite.add(block)
            j = j - 30

        block = Blocks(360, 40, 'data/light_wood_brick.png')
        self.BlocksSprite.add(block)
        block = Blocks(360, 250, 'data/light_wood_brick.png')
        self.BlocksSprite.add(block)

        i = 10
        while i < self.screen_width:
            block = Blocks(i, self.screen_height / 2 + 20,
                           'data/light_wood_brick.png')
            self.BlocksSprite.add(block)
            i = i + 175

        i = 100
        while i < self.screen_width:
            block = Blocks(i, self.screen_height / 2 + 55,
                           'data/light_wood_brick.png')
            self.BlocksSprite.add(block)
            i = i + 175

        self.counter = len(self.BlocksSprite)
コード例 #38
0
ファイル: model.py プロジェクト: xarion/kaggle-tf-speech
class Model:
    def __init__(self, data, parameters):
        self.parameters = parameters
        self.input = data.inputs
        self.labels = data.labels
        self.input_file_names = data.file_names
        self.blocks = Blocks()
        self.data = data

        self.models = {"default_mfcc_model": self.default_mfcc_model,
                       "unfinished_model": self.unfinished_model}
        self.models[self.parameters['model']]()

    def default_mfcc_model(self):

        assert self.parameters['mfcc_inputs']

        with tf.variable_scope("conv_1"):
            conv_1 = self.blocks.conv2d(self.input, [20, 8, 1, 64])
            conv_1 = tf.nn.max_pool(conv_1, [1, 2, 2, 1], [1, 2, 2, 1], padding="VALID")
            conv_1 = self.blocks.normalized_relu_activation(conv_1)

        # with tf.variable_scope("conv_1_2"):
        #     conv_1 = self.blocks.conv2d(conv_1, [8, 20, 64, 64])
        #     conv_1 = tf.nn.max_pool(conv_1, [1, 2, 2, 1], [1, 2, 2, 1], padding="VALID")
        #     conv_1 = self.blocks.normalized_relu_activation(conv_1)

        with tf.variable_scope("conv_2"):
            conv_2 = self.blocks.conv2d(conv_1, [10, 4, 64, 128])
            conv_2 = tf.nn.max_pool(conv_2, [1, 2, 2, 1], [1, 2, 2, 1], padding="VALID")
            conv_2 = self.blocks.normalized_relu_activation(conv_2)
        # with tf.variable_scope("conv_2_2"):
        #     conv_2 = self.blocks.conv2d(conv_2, [4, 10, 128, 256])
        #     conv_2 = tf.nn.max_pool(conv_2, [1, 2, 2, 1], [1, 2, 2, 1], padding="VALID")
        #     conv_2 = self.blocks.normalized_relu_activation(conv_2)

        with tf.variable_scope("fc"):
            final_fc = self.blocks.fc(conv_2, 30720, self.data.number_of_labels)

        with tf.variable_scope("accuracy"):
            self.logits = final_fc
            self.prediction = tf.cast(tf.argmax(self.logits, axis=1), tf.int32)
            self.accuracy = tf.reduce_mean(tf.cast(tf.equal(self.labels, self.prediction), dtype=tf.float32))
            dense_labels = tf.one_hot(self.labels, 12)
            classification_loss = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits,
                                                                          labels=dense_labels)

            self.classification_loss = tf.reduce_mean(classification_loss)

        with tf.variable_scope("confusion_matrix"):
            self.confusion_matrix = tf.confusion_matrix(self.labels, self.prediction)

        with tf.variable_scope("decay"):
            cost = []
            for weight in self.blocks.weights:
                cost.append(tf.nn.l2_loss(weight))
            decay = 0.0001 * tf.reduce_sum(cost)

        with tf.variable_scope("all_losses"):
            self.loss = self.classification_loss + decay
            tf.summary.scalar("decay", decay)
            tf.summary.scalar("classification_loss", self.classification_loss)
            tf.summary.scalar("total_loss", self.loss)
            tf.summary.scalar("accuracy", self.accuracy)

        with tf.variable_scope('classification_gradient'):
            boundaries = [20000]
            values = [0.001, 0.0001]

            self.global_step = tf.Variable(0, name='global_step', trainable=False)
            self.learning_rate = tf.train.piecewise_constant(self.global_step, boundaries, values)
            tf.summary.scalar('learning_rate', self.learning_rate)

            self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)
            update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)

            with tf.control_dependencies(update_ops):
                self.training_step = self.optimizer.minimize(self.loss, global_step=self.global_step)

    def unfinished_model(self):

        assert not self.parameters['mfcc_inputs']

        with tf.variable_scope("conv_1"):
            conv_1 = self.blocks.conv2d(self.input, [9, 1, 1, 32])
            conv_1 = self.blocks.normalized_relu_activation(conv_1)
            conv_1 = tf.nn.max_pool(conv_1, [1, 2, 1, 1], [1, 2, 1, 1], padding="VALID")

        with tf.variable_scope("conv_1_2"):
            conv_1 = self.blocks.conv2d(conv_1, [9, 1, 32, 64])
            conv_1 = self.blocks.normalized_relu_activation(conv_1)
            conv_1 = tf.nn.max_pool(conv_1, [1, 2, 2, 1], [1, 2, 2, 1], padding="VALID")

        with tf.variable_scope("conv_2"):
            conv_2 = self.blocks.conv2d(conv_1, [9, 1, 64, 128])
            conv_2 = self.blocks.normalized_relu_activation(conv_2)
            conv_2 = tf.nn.max_pool(conv_2, [1, 2, 1, 1], [1, 2, 1, 1], padding="VALID")

        with tf.variable_scope("conv_2_2"):
            conv_2 = self.blocks.conv2d(conv_2, [4, 10, 128, 256])
            conv_2 = self.blocks.normalized_relu_activation(conv_2)
            conv_2 = tf.nn.max_pool(conv_2, [1, 2, 1, 1], [1, 2, 1, 1], padding="VALID")

        with tf.variable_scope("fc"):
            final_fc = self.blocks.fc(conv_2, 61440, self.data.number_of_labels)

        with tf.variable_scope("accuracy"):
            self.logits = final_fc
            self.prediction = tf.cast(tf.argmax(self.logits, axis=1), tf.int32)
            self.accuracy = tf.reduce_mean(tf.cast(tf.equal(self.labels, self.prediction), dtype=tf.float32))
            dense_labels = tf.one_hot(self.labels, 12, on_value=0.9, off_value=0.0091)
            classification_loss = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits,
                                                                          labels=dense_labels)

            self.classification_loss = tf.reduce_mean(classification_loss)

        with tf.variable_scope("confusion_matrix"):
            self.confusion_matrix = tf.confusion_matrix(self.labels, self.prediction)

        with tf.variable_scope("decay"):
            cost = []
            for weight in self.blocks.weights:
                cost.append(tf.nn.l2_loss(weight))
            decay = 0.01 * tf.reduce_sum(cost)

        with tf.variable_scope("all_losses"):
            self.loss = self.classification_loss + decay
            tf.summary.scalar("decay", decay)
            tf.summary.scalar("classification_loss", self.classification_loss)
            tf.summary.scalar("total_loss", self.loss)
            tf.summary.scalar("accuracy", self.accuracy)

        with tf.variable_scope('classification_gradient'):
            boundaries = [20000]
            values = [0.1, 0.01]

            self.global_step = tf.Variable(0, name='global_step', trainable=False)
            self.learning_rate = tf.train.piecewise_constant(self.global_step, boundaries, values)
            tf.summary.scalar('learning_rate', self.learning_rate)

            self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate)
            update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)

            with tf.control_dependencies(update_ops):
                self.training_step = self.optimizer.minimize(self.loss, global_step=self.global_step)
コード例 #39
0
def create_bg_blocks(ai_settings, screen, image, bg_blocks, rx, ry, xx, type_):
    block = Blocks(ai_settings, screen, image, rx, ry, 0, type_)
    block.rect.y = ry
    block.rect.x = rx
    block.x = xx
    bg_blocks.add(block)
コード例 #40
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_check_pile_movement_same_pile(self):
     self.blocks = Blocks(10)
     self.blocks.blocks = self.example
     check = self.blocks.check_pile_movement(2, 3)
     self.assertFalse(check)
コード例 #41
0
class Puzzle:
    def __init__(self, row, column, block_input, init_list=None):
        if row == None or column == None or block_input == None:
            print('argument : row, col, block_list, init_list.')
        else:
            # self.dimension = (row, column)
            self.blocks = Blocks(block_input)
            self.table_row = row
            self.table_col = column
            length = row * column
            self.table = {n: 'x' for n in range(1, length + 1)}
            if init_list == None:
                self.init_list = []
            else:
                self.init_list = init_list
                print("init_list :", self.init_list)
                self.load_block_init()

            print('table created. row:', row, ' x col:', column)

    def load_block_init(self):
        print('fn called')
        for n, b in self.init_list:
            if self.isLoadable(n, self.blocks.block_list[b]):
                self.load_block(n, self.blocks.block_list[b])
            else:
                print("load not possible. place :", n, b, " th block")

    def table_init(self):
        self.table = {n: 'x' for n in range(1, len(self.table) + 1)}
        return self

    def show_list(self):
        result = ''
        for _, v in self.table.items():
            result += str(v)
        print(result)
        return self

    def show_table(self):
        result = ''
        for k, v in self.table.items():
            if v == 'x':
                result += '.x'
            else:
                result += v.zfill(2)

            if k % self.table_col == 0:
                result += '\n'
        print(result)
        return self

    def isLoadable(self, n, block, offset_trigger=False):
        loadable = True

        offset = 0
        if offset_trigger == True and n != 1:
            offset = block.offset

        if (n - 1) % 8 + block.col > 8:
            loadable = False
        elif (n - 1) // 8 + block.row > 6:
            loadable = False
        else:
            for e in block.data:
                if self.table[e + n - 1 - offset] == 'x':
                    pass
                else:
                    loadable = False
                    break
        # print(loadable, block.offset)
        return loadable

    def isLoadableAny(self, block: Block):
        loadable = False
        for i, v in self.table.items():
            if self.isLoadable(i, block):
                loadable = i
                break
        return loadable

    def load_block(self, n: int, block: Block, offset_trigger=False):

        offset = 0
        if offset_trigger == True and n != 1:
            offset = block.offset

        # print("load_block() called", n, block.id)
        for e in block.data:
            self.table[e + n - 1 - offset] = str(block.id)
        # print("block loaded")
        self.blocks.mark_used(block.id)
        return self

    # def load_block_front(self, block : Block):
    #     check = self.isLoadableAny(block)
    #     if check != False:
    #         self.load_block(check, block)
    #         return self
    #     else:
    #         print("no space for block ", block.id)
    #         return None

    def isFull(self):
        result = True
        for _, v in self.table.items():
            if v == "x":
                result = False
        # print(result)
        return result
コード例 #42
0
ファイル: main.py プロジェクト: stepheneller/Breakout
from turtle import Screen
from paddle import Paddle
from ball import Ball
from scoreboard import ScoreBoard
from blocks import Blocks
import time

screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.title("Breakout!")
screen.tracer(0)

paddle = Paddle((0, -250))
scoreboard = ScoreBoard()
blocks = Blocks()
ball = Ball()

screen.listen()
screen.onkey(paddle.go_left, "Left")
screen.onkey(paddle.go_right, "Right")

game_is_on = True
red_contact_first_time = False
orange_contact_first_time = False
red_contact = False
orange_contact = False
hits = 0
lives = 3

while game_is_on:
コード例 #43
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_check_pile_movement_different_pile(self):
     self.blocks = Blocks(10)
     self.blocks.blocks = self.example
     check = self.blocks.check_pile_movement(6, 2)
     self.assertTrue(check)
コード例 #44
0
    def plansza1(self):
        """Rysuje pierwszą planszę."""

        i = 5
        j = self.screen_height / 2 - 50

        while j > 0:

            block = Blocks(i, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            i = i + 33.75
            j = j - 30

        i = 90
        j = self.screen_height / 2 - 50
        while j > 70:

            block = Blocks(i, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            i = i + 33.75
            j = j - 30

        i = self.screen_width - 85
        j = self.screen_height / 2 - 50
        while j > 0:

            block = Blocks(i, j, 'data/wood_brick.png')
            self.BlocksSprite.add(block)
            i = i - 33.75
            j = j - 30

        i = self.screen_width - 2 * 85
        j = self.screen_height / 2 - 50
        while j > 70:

            block = Blocks(i, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            i = i - 33.75
            j = j - 30

        j = self.screen_height / 2 + 50
        while j > 0:

            block = Blocks(360, j, 'data/wood_brick.png')
            self.BlocksSprite.add(block)
            j = j - 30

        j = self.screen_height / 2 + 50
        while j > 150:

            block = Blocks(275, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            j = j - 30

        j = self.screen_height / 2 + 50

        while j > 150:

            block = Blocks(445, j, 'data/wood_brick.png')
            self.BlocksSprite.add(block)
            j = j - 30

        self.counter = len(self.BlocksSprite)
コード例 #45
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_remove_pile_2(self):
     self.blocks = Blocks(10)
     self.blocks.blocks = self.example
     pile = self.blocks.remove_pile(2)
     self.assertEqual(self.blocks.blocks[1], [1])
     self.assertEqual(pile, [2, 3, 4])
コード例 #46
0
    def plansza3(self):
        """Rysuje trzecią planszę."""

        for i in range(2):
            self.add_speed = Extensions(
                random.randrange(30, self.screen_width - 30),
                random.randrange(30, self.screen_height / 2),
                "data/add_speed.png")
            self.AddSpeedSprite.add(self.add_speed)

        for i in range(2):
            self.add_speed = Extensions(
                random.randrange(30, self.screen_width - 30),
                random.randrange(30, self.screen_height / 2),
                "data/substract_speed.png")
            self.SubstractSpeedSprite.add(self.add_speed)

        i = 10
        j = 35
        while i < self.screen_width - 10:
            block = Blocks(i, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            i = i + 87.5

        i = 97.5
        j = 70
        while i < self.screen_width - 97.5:
            block = Blocks(i, j, 'data/wood_brick.png')
            self.BlocksSprite.add(block)
            i = i + 87.5

        i = 185
        j = 105
        while i < self.screen_width - 185:
            block = Blocks(i, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            i = i + 87.5

        i = 272.5
        j = 140
        while i < self.screen_width - 272.5:
            block = Blocks(i, j, 'data/wood_brick.png')
            self.BlocksSprite.add(block)
            i = i + 87.5

        ####

        block = Blocks(360, 175, 'data/gray_brick.png')
        self.BlocksSprite.add(block)

        ####

        i = 272.5
        j = 210
        while i < self.screen_width - 272.5:
            block = Blocks(i, j, 'data/wood_brick.png')
            self.BlocksSprite.add(block)
            i = i + 175

        i = 185
        j = 245
        while i < self.screen_width - 185:
            block = Blocks(i, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            i = i + 175

        i = 97.5
        j = 280
        while i < self.screen_width - 97.5:
            block = Blocks(i, j, 'data/wood_brick.png')
            self.BlocksSprite.add(block)
            i = i + 175

        i = 10
        j = 315
        while i < self.screen_width - 10:
            block = Blocks(i, j, 'data/gray_brick.png')
            self.BlocksSprite.add(block)
            i = i + 175

        ####

        i = 10
        for k in range(3):
            block = Blocks(i, 175, 'data/light_wood_brick.png')
            self.BlocksSprite.add(block)
            i = i + 87.5

        j = 140
        for k in range(2):
            block = Blocks(97.5, j, 'data/light_wood_brick.png')
            self.BlocksSprite.add(block)
            j = j + 70

        i = 535
        for k in range(3):
            block = Blocks(i, 175, 'data/light_wood_brick.png')
            self.BlocksSprite.add(block)
            i = i + 87.5

        j = 140
        for k in range(2):
            block = Blocks(622.5, j, 'data/light_wood_brick.png')
            self.BlocksSprite.add(block)
            j = j + 70

        self.counter = len(self.BlocksSprite)
コード例 #47
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_remove_pile_4(self):
     self.blocks = Blocks(10)
     self.blocks.blocks = self.example
     pile = self.blocks.remove_pile(4)
     self.assertEqual(self.blocks.blocks[1], [1, 2, 3])
     self.assertEqual(pile, [4])
コード例 #48
0
ファイル: bp2schem.py プロジェクト: thepaka/StarMade
def bp2schem(dirName):

    # Load blueprint

    bp = blueprint.readBlueprint(dirName)

    # Compute values

    width =  int( abs(bp['header']['bounds_a'][0] - bp['header']['bounds_b'][0] ) - 1 )
    height = int( abs(bp['header']['bounds_a'][1] - bp['header']['bounds_b'][1] ) - 1 )
    length = int( abs(bp['header']['bounds_a'][2] - bp['header']['bounds_b'][2] ) - 1 )

    orig = ( bp['header']['bounds_a'][0] + 1,
             bp['header']['bounds_a'][1] + 1,
             bp['header']['bounds_a'][2] + 1)

    b = Blocks(width, height, length, orig)

    for data in bp['datas'].values():
        chunks = data['chunks']
        chunk_index = data['chunk_index']
        data_pos = data['pos']

        for chunk in chunks:
            x_off = chunk['pos'][0]
            y_off = chunk['pos'][1]
            z_off = chunk['pos'][2]

            print "Chunk pos : x=%d y=%d z=%d" % ( x_off, y_off, z_off )

            for pos, data in chunk['blocks'].items():
                block_info = resolver.starmade_to_minecraft( data['id'], data['orient'] )
                block_pos = (pos[0] + x_off, pos[1] + y_off , pos[2] + z_off)

                b.add(block_pos, block_info[0], block_info[1])

    # Create NBT

    nbtfile = nbt.NBTFile()
    nbtfile.name = "Schematic"

    nbtfile.tags.extend([
        TAG_String(name='Materials', value = 'Alpha'),

        TAG_List(name='Entities', type=TAG_Compound),
        TAG_List(name='TileEntities', type=TAG_Compound),

        TAG_Byte_Array(name='Data'),
        TAG_Byte_Array(name='Blocks'),

        TAG_Int(name='WEOffsetX', value = 0),
        TAG_Int(name='WEOffsetY', value = 0),
        TAG_Int(name='WEOffsetZ', value = 0),

        TAG_Int(name='WEOriginX', value = 0),
        TAG_Int(name='WEOriginY', value = 0),
        TAG_Int(name='WEOriginZ', value = 0),

        TAG_Short(name='Height', value = height),
        TAG_Short(name='Length', value = length),
        TAG_Short(name='Width', value = width)
    ])

    nbtfile['Data'].value = b.datas
    nbtfile['Blocks'].value = b.ids

    outfile = "%s.schematic" % os.path.basename(dirName)
    print 'Writing %s' % outfile
    nbtfile.write_file(outfile)
コード例 #49
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_move_9_onto_1(self):
     self.blocks = Blocks(10)
     self.blocks.move_onto(9, 1)
     self.assertEqual(self.blocks.blocks[1], [1, 9])
コード例 #50
0
from ball import Ball
from blocks import Blocks
from scoreboard import ScoreBoard

# setting up the game screen
game_screen = Screen()
game_screen.setup(width=600, height=650)
game_screen.bgcolor("black")
game_screen.title("Breakout Game")
game_screen.tracer(0)
game_screen.listen()

# setup and display each game component
user_paddle = Paddle()
game_ball = Ball()
game_blocks = Blocks()
scores = ScoreBoard()
game_on = True


def end_game():
    """A function that ends the game abruptly"""

    global game_on
    game_on = False


# move the paddle up and down on key presses
game_screen.onkey(user_paddle.move_up, "Up")
game_screen.onkey(user_paddle.move_down, "Down")
コード例 #51
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_move_9_over_1(self):
     self.blocks = Blocks(10)
     self.blocks.move_over(9, 1)
     self.blocks.move_over(2, 1)
     self.assertEqual(self.blocks.blocks[1], [1, 9, 2])
コード例 #52
0
ファイル: blocks_spec.py プロジェクト: phinpho/SolvingUVa
 def test_remove_block_4(self):
     self.blocks = Blocks(10)
     self.blocks.blocks = self.result
     self.blocks.remove_block(1, 3)
     with self.assertRaises(IndexError):
         self.blocks.blocks[1][3]
コード例 #53
0
class GameOfLife:
    def __init__(self):
        pygame.init()  #初始化背景设置
        self.blocks_right = c * (block_size + 1)  #计算方格区右边界
        height = r * (block_size + 1)
        if height < 300:
            height = 300  #保证按键显示完全
        self.screen = pygame.display.set_mode(
            (self.blocks_right + 100, height))
        pygame.display.set_caption("Game Of Life")  #设置标题
        self.screen.fill(bg_color)
        self.core = Core(r, c)
        self.__init_lives()
        self.blocks = Blocks(r, c, block_size, self.screen,
                             self.core.get_now_state())
        self.blocks.draw_board()
        self.running = False
        self.time = time.time()
        self.__add_buttons()
        self.speed = 1

        return

    #添加初始生命
    def __init_lives(self):
        self.core.add_life(1, 1, rle.glider)
        self.core.add_life(15, 10, rle.blinker)
        self.core.add_life(20, 10, rle.toad)
        self.core.add_life(10, 80, rle.HWSS)
        self.core.add_life(30, 0, rle.glider_generater)
        self.core.add_life(30, 40, rle.glider_generater)

    #添加按键
    def __add_buttons(self):
        self.next_button = Button(self.blocks_right + 10, 20, self.screen,
                                  'next')
        self.start_button = Button(self.blocks_right + 10, 80, self.screen,
                                   'start')
        self.stop_button = Button(self.blocks_right + 10, 140, self.screen,
                                  'stop')
        self.speed_up_button = Button(self.blocks_right + 10, 200, self.screen,
                                      'speed up')
        self.speed_down_button = Button(self.blocks_right + 10, 260,
                                        self.screen, 'speed down')
        self.next_button.draw_button()
        self.start_button.draw_button()
        self.stop_button.draw_button()
        self.speed_up_button.draw_button()
        self.speed_down_button.draw_button()

    #点击方格区
    def click_block(self, mouse_x, mouse_y):
        r = int(mouse_y / (block_size + 1))
        c = int(mouse_x / (block_size + 1))
        self.core.change_block(r, c)
        self.blocks.click(r, c)

    #点击按键区
    def click_button(self, mouse_x, mouse_y):
        if self.next_button.rect.collidepoint(mouse_x, mouse_y):
            self.blocks.set_status(self.core.get_next_state())
        if self.start_button.rect.collidepoint(mouse_x, mouse_y):
            self.running = True
        if self.stop_button.rect.collidepoint(mouse_x, mouse_y):
            self.running = False
        if self.speed_up_button.rect.collidepoint(mouse_x, mouse_y):
            if self.speed < 20:
                self.speed += 1
        if self.speed_down_button.rect.collidepoint(mouse_x, mouse_y):
            if self.speed > 1:
                self.speed -= 1
        return

    #添加按键
    def draw(self):
        self.blocks.draw_board()
        pygame.display.flip()

    #运行游戏
    def run_game(self):
        while True:
            for event in pygame.event.get():  #检测键盘鼠标事件
                if event.type == pygame.QUIT:
                    sys.exit()  #退出程序
                elif event.type == pygame.MOUSEBUTTONDOWN:  #检测鼠标点击事件
                    mouse_x, mouse_y = pygame.mouse.get_pos(
                    )  #get_pos()返回一个单击时鼠标的xy坐标
                    if (mouse_x < self.blocks_right):
                        self.click_block(mouse_x, mouse_y)
                    else:
                        self.click_button(mouse_x, mouse_y)
            if self.running:
                nowtime = time.time()
                if nowtime - self.time > (1 / self.speed):
                    self.time = nowtime
                    self.blocks.set_status(self.core.get_next_state())
            self.draw()