Esempio n. 1
0
    def test_count_gaps(self):
        """
        Test that gap counting works as expected with filled/non-filled columns.
        """
        field = Field.create()
        self.assertEqual(field.count_gaps(), 0)

        field = Field.create(
            generate_valid_state(
                np.array([
                    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [1, 0, 1, 0, 1, 1, 1, 1, 1, 1],
                ])))
        self.assertEqual(field.count_gaps(), 0)

        field = Field.create(
            generate_valid_state(
                np.array([
                    [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                ])))
        self.assertEqual(field.count_gaps(), 1)

        field = Field.create(
            generate_valid_state(
                np.array([
                    [1, 0, 0, 0, 0, 0, 0, 0, 1, 0],
                    [0, 1, 1, 0, 0, 0, 0, 0, 1, 0],
                    [1, 0, 0, 1, 0, 0, 0, 0, 1, 0],
                    [0, 0, 0, 1, 0, 0, 0, 1, 1, 1],
                ])))
        self.assertEqual(field.count_gaps(), 6)
Esempio n. 2
0
	def createitemlocations( self, numOfItems ) :
		field = Field()
		locations = field.getItemLocations()
		count = 0
		for i in range( len( locations ) ) :
			count += 1
		self.assertEqual( count, numOfItems )
Esempio n. 3
0
 def _get_fitness_(self):
     """
     Helper method to perform a single simulation to evaluate the performance
     of the chromosome. This will be called multiple times and the overall
     performance of the chromosome is the average of all the runs.
     """
     tetrominos = [
         Tetromino.ITetromino(),
         Tetromino.OTetromino(),
         Tetromino.TTetromino(),
         Tetromino.STetromino(),
         Tetromino.ZTetromino(),
         Tetromino.JTetromino(),
         Tetromino.LTetromino()
     ]
     field = Field()
     field_score = -1
     for length in range(self.max_simulation_length):
         tetromino = random.choice(tetrominos)
         _, __, _field, _field_score = field.get_optimal_drop(
             tetromino, self.genes)
         if _field_score == math.inf:
             return length, field_score
         else:
             field = _field
             field_score = _field_score
     return length, field_score
Esempio n. 4
0
    def test_drop(self):
        """
        Test various drop sequences and line clears.
        """
        state = generate_valid_state(
            np.array([
                [1, 1, 0, 1, 1, 0, 1, 1, 0, 0],
                [1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
            ],
                     dtype=np.uint8))
        field = Field.create(state)
        self.assertIsNotNone(field)

        lines_cleared = field.drop(Tetromino.JTetromino(), 0)
        self.assertEqual(lines_cleared, 0)
        expected_field = Field.create(
            generate_valid_state(
                np.array([
                    [6, 6, 6, 0, 0, 0, 0, 0, 0, 0],
                    [1, 1, 6, 1, 1, 0, 1, 1, 0, 0],
                    [1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
                ])))
        self.assertFieldsEqual(field, expected_field)

        lines_cleared = field.drop(Tetromino.TTetromino().rotate_right(), 8)
        self.assertEqual(lines_cleared, 1)
        expected_field = Field.create(
            generate_valid_state(
                np.array([
                    [6, 6, 6, 0, 0, 0, 0, 0, 0, 3],
                    [1, 1, 6, 1, 1, 0, 1, 1, 3, 3],
                ])))
        self.assertFieldsEqual(field, expected_field)

        field.drop(Tetromino.OTetromino(), 3)
        field.drop(Tetromino.ZTetromino(), 6)
        field.drop(Tetromino.JTetromino().flip(), 0)
        field.drop(Tetromino.OTetromino(), 8)
        expected_field = Field.create(
            generate_valid_state(
                np.array([
                    [6, 0, 0, 0, 0, 0, 0, 0, 2, 2],
                    [6, 6, 6, 2, 2, 0, 5, 5, 2, 2],
                    [6, 6, 6, 2, 2, 0, 0, 5, 5, 3],
                    [1, 1, 6, 1, 1, 0, 1, 1, 3, 3],
                ])))
        self.assertFieldsEqual(field, expected_field)
        lines_cleared = field.drop(Tetromino.ITetromino().rotate_right(), 5)
        self.assertEqual(lines_cleared, 2)
        expected_field = Field.create(
            generate_valid_state(
                np.array([
                    [6, 0, 0, 0, 0, 1, 0, 0, 2, 2],
                    [6, 6, 6, 2, 2, 1, 0, 5, 5, 3],
                ])))
Esempio n. 5
0
 def generate_fields(self):
     x = 0
     while x < len(self.wordlist):
         word = self.wordlist[x].replace("\"",
                                         "&quot;").replace("\'", "&#39;")
         field = Field(word=word, word_id=x, Game=self)
         self.fields.append(field)
         x += 1
Esempio n. 6
0
    def test_heights(self):  # pylint: disable=no-self-use
        """
        Test that height calculation works as expected with filled/non-filled
        columns.
        """
        field = Field.create()
        expected_heights = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
        np.testing.assert_array_equal(field.heights(), expected_heights)

        field = Field.create(
            generate_valid_state(
                np.array([
                    [1, 0, 0, 0, 0, 0, 0, 0, 1, 0],
                    [0, 1, 1, 0, 0, 0, 0, 0, 1, 0],
                    [1, 0, 0, 1, 0, 0, 0, 0, 1, 0],
                    [0, 0, 1, 1, 0, 0, 0, 1, 1, 1],
                ])))
        expected_heights = np.array([4, 3, 3, 2, 0, 0, 0, 1, 4, 1])
        np.testing.assert_array_equal(field.heights(), expected_heights)
Esempio n. 7
0
 def fromString(s, field=Field(2)):
     lines = list(
         map(lambda line: list(map(lambda n: int(n),
                                   line.strip().split())),
             s.strip().splitlines()))
     output = Matrix(len(lines), len(lines[0]), field)
     for (i, line) in enumerate(lines):
         for (j, v) in enumerate(line):
             output.set(i, j, v)
     return output
Esempio n. 8
0
def show(chromosome):
    tetrominos = [
        Tetromino.ITetromino(),
        Tetromino.OTetromino(),
        Tetromino.TTetromino(),
        Tetromino.STetromino(),
        Tetromino.ZTetromino(),
        Tetromino.JTetromino(),
        Tetromino.LTetromino()
    ]
    field = Field()
    pieces = 0
    while True:
        tetromino = random.choice(tetrominos)
        _, __, field, ___ = field.get_optimal_drop(tetromino, chromosome.genes)
        if field == None:
            break
        print(field)
        pieces += 1
        time.sleep(0.1)
    print('Performance: {}'.format(pieces))
Esempio n. 9
0
    def __init__(self, rows, cols, field=Field(2), fill=None):
        """Constructs a blank matrix with the given number of rows and columns,
        with operations from the given field. All the elements are initially None."""
        if rows <= 0 or cols <= 0:
            raise ValueError("Invalid number of rows or columns")
        if not isinstance(field, Field):
            raise TypeError()

        # The field used to operate on the values in the matrix.
        self.f = field
        # The values of the matrix stored in row-major order, with each element initially None.
        self.values = [[fill] * cols for _ in range(rows)]
Esempio n. 10
0
    def test_init(self):
        # Test that a newly initialized field object is empty.
        field = Field.create()
        self.assertIsNotNone(field)
        self.assertFalse(field.state.any())

        # Test that a valid state results in a properly initialized Field
        state = generate_valid_state(
            np.array([
                [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            ], dtype=np.uint8))
        field = Field.create(state)
        self.assertIsNotNone(field)
        self.assertTrue((field.state == state).all())

        # Ensure that a copy was made of the input state.
        state[10, 1] = 2
        self.assertFalse((field.state == state).all())

        # Test that a invalid state returns None
        state = np.ones((2, 3))
        self.assertIsNone(Field.create(state))
Esempio n. 11
0
 def get_syndrome_table(self):
     p = 2**self.column_count()
     table = Matrix(p, self.column_count() + self.row_count(), Field(2), 0)
     for i in range(p):
         bin_form = tobin(i).zfill(self.column_count())
         for (j, c) in enumerate(bin_form):
             table.set(i, j, c)
         for subset in all_combinations(self.values):
             sum = reduce(lambda x, y: xor_vectors(x, y[1]), subset,
                          [0] * self.column_count())
             num = int("".join(list(map(str, sum))), 2)
             if num == i:
                 for v in subset:
                     table.set(i, self.column_count() + v[0], 1)
                 break
     return table
Esempio n. 12
0
print("profile: " + str(tuple(map(lambda num: "2^%d" % num, span_straight.span_profile()))))

print("")

print('=== generating minimal span form for dual code ===')
span_dual = H.to_minimal_span_form()
print(str(span_dual))
print("profile: " + str(tuple(map(lambda num: "2^%d" % num, span_straight.span_profile()))))

print("")

print('=== computing field ===')
oct_parsed = int(str(input_polynom), 8)
modulus = oct_parsed if rtl else int(tobin(oct_parsed).zfill(len(str(input_polynom)) * 3)[::-1], 2)
binary_modulus = tobin(modulus)
print("modulus = %s" % binary_modulus)
mod_length = len(binary_modulus)
field = Field(modulus)
elements = field.get_all_elems()
bin_elements = list(map(lambda it: tobin(it).zfill(mod_length - 1), elements))
for i, item in enumerate(bin_elements):
    print("%s: %s" % (str(i).zfill(2), item))
print("")
upper = Sum(Mult(Num(input_a), Var(1)), Num(input_b)).calc({"x": input_x0}, field)
bottom = Sum(Mult(Num(input_c), Var(1)), Num(input_d)).calc({"x": input_x0}, field)
bottom_inverted = field.reciprocal(bottom)
upper_div_bottom = field.multiply(upper, bottom_inverted)
print('f(x) = ( %d * x + %d ) / ( %d * x + %d )' % (input_a, input_b, input_c, input_d))
print('f(%d) = %d / %d = %d * %d = %d' % (input_x0, upper, bottom, upper, bottom_inverted, upper_div_bottom))

Esempio n. 13
0
	def test_createoneitemlocation( self ) :
		field = Field()
		item = Item()
		item.addRandomStartLocation(field)
		self.assertTrue( item.getStartLocation() != ( 0, 0, 0 ) )
Esempio n. 14
0
    time.sleep(5)
    name_changer_button = driver.find_element_by_class_name('name')
    button = name_changer_button.find_element_by_id('playername_button')
    name_fild = name_changer_button.find_element_by_id('playername')
    button.click()
    name_fild.send_keys("Botti")
    button_start_game = driver.find_element_by_id('start_game')
    button_start_game.click()

    block_to_index = {'j': 1, 'l': 2, 'z': 3, 'i': 4, 't': 5, 'o': 6, 's': 7}
    first_rows = driver.find_element_by_xpath(
        '//*[@id="player"]').find_elements_by_tag_name("tr")
    next_rows = driver.find_element_by_xpath(
        '/html/body/div[2]/div/div/div[1]/div[2]/div[1]/div[2]/div/table/tbody'
    ).find_elements_by_tag_name("tr")
    field = Field()
    current_tetromino = get_t(first_rows)()
    print(current_tetromino)
    next_tetromino = None
    while True:
        time.sleep(1)
        try:
            next_tetromino = get_next_t(next_rows)()
        except Exception as e:
            driver.quit()
            quit()
            print(str(e))
        print(next_tetromino)
        opt = field.get_optimal_drop(current_tetromino)
        rotation = opt[-1]
        column = opt[1]
Esempio n. 15
0
 def create(field=None):
     """
     Factory method to create a TetrisDriver, taking an optional Field with
     which to initialize the game with.
     """
     return TetrisDriver(Field.create() if field is None else field)
Esempio n. 16
0
def task1():
    print("=== TASK 1 ===")
    print("")

    oct_parsed = int(str(task1_input), 8)

    # wheter to interpret 1011 as 1 + x2 + x^3 or 1 + x + x^3
    # else clause: takes parsed number, converts to binary, adds zeroes to the left, reverses, parses as binary
    # (it's the same as reversing number's binary form)
    # e.g. 101001 -> 100101
    modulus = oct_parsed if rtl else int(
        tobin(oct_parsed).zfill(len(str(task1_input)) * 3)[::-1], 2)

    binary_modulus = tobin(modulus)
    mod_length = len(binary_modulus)
    M = mod_length - 1
    print("modulus = %s" % binary_modulus)
    print("GF(2^%s)" % M)
    print("")

    d = task1_errors * 2 + 1

    field = Field(modulus)
    elements = field.get_all_elems()
    bin_elements = list(
        map(lambda it: tobin(it).zfill(mod_length - 1), elements))
    for i, item in enumerate(bin_elements):
        print("%s: %s" % (str(i).zfill(2), item))

    print("")

    if task1_is_rc_code:

        def gen_brackets():
            for i in range(1, d):
                yield Polynomial([Alpha(i), Num(1)])

        brackets = MultList(list(gen_brackets()))
        print("g(x) = %s" % str(brackets))
        print("")

        steps = brackets.toPolynomialCalc(field)
        for step in steps:
            print(str(step))
        print("")

        print("g(x) = %s" % str(steps[-1]))
        print("")
        n = 2**M - 1
        k = n - d + 1
        print("d = %d, n = %d, k = %d" % (d, n, k))
    else:
        print('classes: ')
        classes = get_cyclic_classes(2**M - 1)
        for c in classes:
            print("C_%d = %s" % (c[0], c))
        include_classes_nums = {}
        include_classes = []
        for i in range(1, d):
            for c in classes:
                if not (c[0] in include_classes_nums) and i in c:
                    include_classes_nums[c[0]] = True
                    include_classes.append(c)
        print('classes that include numbers 1..%d: %s' %
              (d - 1, list(include_classes_nums.keys())))
        print('list of M_i:')

        def gen_brackets(c):
            for i in c:
                yield Polynomial([Alpha(i), Num(1)])

        m_array = [MultList(list(gen_brackets(c))) for c in include_classes]
        m_array_reduced = list(map(lambda x: x.toPolynomial(field), m_array))
        for i in range(len(m_array)):
            print("M_%d = %s = %s" % (include_classes[i][0], str(
                m_array[i]), str(m_array_reduced[i])))
        gx = reduce(lambda x, y: x.mult(y, field), m_array)
        print("g(x) = %s" % str(gx))
        poly = gx.toPolynomial(field)
        print("g(x) = %s" % poly)
        n = 2**M - 1
        h = poly.max_power()
        k = n - h
        print("d = %d, n = %d, k = %d" % (d, n, k))
Esempio n. 17
0
def task2():
    print("=== TASK 2 ===")
    print("")

    oct_parsed = int(str(task2_input), 8)

    # wheter to interpret 1011 as 1 + x2 + x^3 or 1 + x + x^3
    # else clause: takes parsed number, converts to binary, adds zeroes to the left, reverses, parses as binary
    # (it's the same as reversing number's binary form)
    # e.g. 101001 -> 100101
    modulus = oct_parsed if rtl else int(
        tobin(oct_parsed).zfill(len(str(task2_input)) * 3)[::-1], 2)

    binary_modulus = tobin(modulus)
    mod_length = len(binary_modulus)
    print("modulus = %s" % binary_modulus)
    print("GF(2^%s)" % (mod_length - 1))
    print("")

    field = Field(modulus)
    elements = field.get_all_elems()
    bin_elements = map(lambda it: tobin(it).zfill(mod_length - 1), elements)
    for i, item in enumerate(bin_elements):
        print("%s: %s" % (str(i).zfill(2), item))

    print("")

    code_polynomial = binaryToPolynomial(
        task2_code) if task2_code_is_binary else octToPolynomial(
            task2_code, field)
    print("g(x) = %s" % str(code_polynomial))

    syndrome_len = task2_errors * 2
    syndrome_values_show = [(i, code_polynomial.calc({"x": field.get(i)},
                                                     field))
                            for i in range(1, syndrome_len + 1)]
    for (i, val) in syndrome_values_show:
        if val == 0:
            print("g(a^%d) = 0" % i)
        else:
            p = field.powerOf(val)
            print("g(a^%d) = a^%d" % (i, p))
    syndrome_values = list(
        map(lambda tuple: numToAlpha(tuple[1], field), syndrome_values_show))
    syndrome_values_raw = list(
        map(lambda a: a.calc({}, field), syndrome_values))
    syndrome = Polynomial(syndrome_values)
    print("syndrome(x) = %s" % str(syndrome))
    v = task2_errors + 1
    D = 0
    M = None
    while D == 0:
        v = v - 1
        print(syndrome_values_raw[0:v + 1])
        M = get_m_matrix(syndrome_values_raw[0:v + 1], field)
        print("with M = ")
        print(M.str_field())
        D = M.determinant_and_ref()
        print("v = %d, D = %d" % (v, D))
    M = get_m_matrix(syndrome_values_raw[0:v + 1], field)
    MSolve = M.append_col(syndrome_values_raw[len(syndrome_values_raw) - v:])
    print(MSolve.str_field())
    lambdas = MSolve.solve()
    print(MSolve.str_field())
    lambdas_coef = list(map(lambda it: numToAlpha(it, field), lambdas))
    lambda_poly = Polynomial(lambdas_coef + [1])
    print(lambda_poly)
    roots = lambda_poly.find_roots(field)
    print("roots: %s" %
          list(map(lambda it: str(numToAlpha(it, field)), roots)))
    inverse_roots = list(map(lambda it: field.reciprocal(it), roots))
    print("inverse_roots (locators): %s" %
          list(map(lambda it: str(numToAlpha(it, field)), inverse_roots)))
    y_left = Matrix(len(inverse_roots), len(inverse_roots), field)
    y_left.values = [
        list(map(lambda it: field.power(it, i), inverse_roots))
        for i in range(1,
                       len(inverse_roots) + 1)
    ]
    system = y_left.append_col(syndrome_values_raw[:len(inverse_roots)])
    print("values system: ")
    print(system.str_field())
    y_arr = system.solve()
    print("solved: ")
    print(system.str_field())