Esempio n. 1
0
    def __init__(self):
        self.pawn_color = (255, 25, 25)
        self.pawn_radius = 25

        #stworzenie wszystkich pol (poza polami docelowymi graczy)
        self.fields = [Field(0, 0, (255, 255, 255), 20) for _ in range(40)]

        #stworzenie pol docelowych dla graczy
        self.red_target_fields = [
            Field(0, 0, (255, 128, 128), 20) for _ in range(4)
        ]
        self.green_target_fields = [
            Field(0, 0, (128, 255, 128), 20) for _ in range(4)
        ]
        self.blue_target_fields = [
            Field(0, 0, (128, 128, 255), 20) for _ in range(4)
        ]
        self.yellow_target_fields = [
            Field(0, 0, (255, 255, 128), 20) for _ in range(4)
        ]

        #nadanie specjalnego koloru dla startowych pozycji
        self.fields[0].set_color((255, 255, 128))
        self.fields[10].set_color((255, 128, 128))
        self.fields[20].set_color((128, 255, 128))
        self.fields[30].set_color((128, 128, 255))

        #nadanie odpowiednich pozycji dla wszystkich pol
        self.set_fields_position()

        #stworzenie indywidualnych sciezek dla graczy
        self.routes = self.create_routes()  # {green, blue, yellow, red}
Esempio n. 2
0
def test_reach_end_field():
    board = Board("rgby")
    piece = PIECES["green1"]
    board.move_piece(piece, Field("40"))
    suggested_moves = board.suggest_moves(piece, 4)
    assert 2 == len(suggested_moves)
    assert (Field("B4", color="g"), "reach end field") in suggested_moves
Esempio n. 3
0
    def test_convert_to_short_weierstrass(self):

        # Test with Curve41417
        field = Field(2**414 - 17)
        curve41417 = EdwardsCurve(1, 3617, Field(2**414 - 17))
        curve41417_bp = (
            17319886477121189177719202498822615443556957307604340815256226171904769976866975908866528699294134494857887698432266169206165,
            34)

        # this is tested in the Montgomery test case.
        curve41417monty, P_to_monty, P_from_monty = curve41417.to_montgomery()
        curve41417monty_bp = P_to_monty(curve41417_bp)

        # now finally convert to short weierstrass

        weiss, P_to_weiss, P_from_weiss = curve41417monty.to_short_weierstrass(
        )

        self.assertEquals(
            42307582002575910332922579714097346549017899709713998034217522897561970639123926132812109468141778230245837569601494931198756,
            weiss.a)
        self.assertEquals(
            42307582002575910332922579714097346549017899709713998034217522897561970639123926132812109468141778230245837569601494877203573,
            weiss.b)

        self.assertEquals((
            33333246426271929353211729471713060917408042195532240875444108949594279897491578165245904429445037393527023539686026309646457,
            2236671449683305925398969480507433209994648385971289644656272082874689574321388075188206152980709096399807140440181156775230
        ), P_to_weiss(curve41417monty_bp))

        self.assertEquals(curve41417monty_bp,
                          P_from_monty(P_to_monty(curve41417monty_bp)))
Esempio n. 4
0
def main():
    "Play the game."
    name1 = input('1st player, enter your name: ')
    name2 = input('2nd player, enter your name: ')
    path1, path2 = '{}.txt'.format(name1), '{}.txt'.format(name2)
    player1 = Player(name1)
    player2 = Player(name2)
    ships1 = generate_field()
    field1 = Field(ships1)
    ships2 = generate_field()
    field2 = Field(ships2)
    game = Game(fields=[field1, field2], players=[player1, player2])
    write(path1=path1, path2=path2, game=game)

    print('New game.')
    while not winner(field1.field_with_ships(), field2.field_with_ships()):
        write(path1=path1, path2=path2, game=game)
        # making move.
        move = (game._players[game.current_player]).read_position()
        # if shot in the ship.
        if game.shot_at(move, game.current_player - 1):
            print('Yeah!')
            write(path1=path1, path2=path2, game=game)
        # if didn;t change the player.
        else:
            if game.current_player == 1:
                game.current_player = 0
            else:
                game.current_player = 1

    print('The end!')
    if '@' in field2.field_with_ships():
        print('Winner is {}'.format(player2._name))
    else:
        print('Winner is {}'.format(player1._name))
Esempio n. 5
0
    def __init__(self, platforms):
        """Create a new delegator instance.

        'platforms' is a set of all platforms to support
        """
        super().__init__('luastructs', Platform.mappings['default'], None)
        self.platforms = platforms
        self.field_var = 'f.'
        self.description = 'Lua C Structs'
        self.dissectors = {self.platform.name: self}

        self.var = create_lua_var('delegator')
        self.table_var = create_lua_var('dissector_table')
        self.id_table = create_lua_var('message_ids')
        self.sizes_table = create_lua_var('dissector_sizes')
        self.msg_var = create_lua_var('msg_node')

        # Add fields, don't change sizes!
        endian = Platform.big
        self.add_field(Field('Version', 'uint8', 1, 0, endian))
        values = {p.flag: p.name for name, p in self.platforms.items()}
        field = Field('Flags', 'uint8', 1, 0, endian)
        field.set_list_validation(values)
        self.add_field(field)
        self.add_field(Field('Message', 'uint16', 2, 0, endian))
        self.add_field(Field('Message length', 'uint32', 4, 0, endian))

        self.version, self.flags, self.msg_id, self.length = self.children
Esempio n. 6
0
 def __init__(self, name, queue, s_z):
     self.player_name = name
     self.queue = queue
     self.field = Field(s_z)
     self.field_enemy = Field(s_z)
     self.killed = 0
     self.log = []
Esempio n. 7
0
def create_field():
    """Create a Protocol instance with some fields."""
    proto, diss = dissector.Protocol.create_dissector('test')
    diss.add_field(Field('one', 'float', 4, 0, Platform.big))
    diss.add_field(Field('two', 'string', 12, 0, Platform.big))
    diss.push_modifiers()
    yield diss.children[0], diss.children[1]
    dissector.Protocol.protocols = {}
    del proto, diss
Esempio n. 8
0
 def __init__(self):
     super(EmptyEntry, self).__init__()
     self.entryType = ''
     self.requiredFields = dict()
     self.optionalFields = dict()
     self.additionalFields = {
         FieldName.Paper: Field(FieldName.Paper),
         FieldName.Comment: Field(FieldName.Comment)
     }
Esempio n. 9
0
def initGame(height, width):
    global botField, playerField, botShips, playerShips, bot
    botField = Field(height, width)
    playerField = Field(height, width)

    playerShips = initShips()
    botShips = initShips()

    bot = Bot(botField, playerField, botShips)
    bot.initShips()
Esempio n. 10
0
 def calculate_one_tick(self):
     print("Cache has {} entrys,".format(len(self.queue)))
     if self.queue == []:
         f = Field(copy_field=self.field)
         f.update()
         self.queue.append(f)
     elif len(self.queue) < 5:
         f = Field(copy_field=self.queue[-1])
         f.update()
         self.queue.append(f)
Esempio n. 11
0
 def __init__(self):
     super(Inproceedings, self).__init__()
     self.entryType = 'INPROCEEDINGS'
     self.requiredFields = {
         FieldName.Author: Author(),
         FieldName.Title: Field(FieldName.Title),
         FieldName.BookTitle: Field(FieldName.BookTitle),
         FieldName.Year: Year()
     }
     self.optionalFields.update({
         FieldName.Editor:
         Editor(),
         FieldName.Volume:
         Field(FieldName.Volume),
         FieldName.Number:
         Field(FieldName.Number),
         FieldName.Series:
         Field(FieldName.Series),
         FieldName.Pages:
         Pages(),
         FieldName.Organization:
         Organization(),
         FieldName.Publisher:
         Field(FieldName.Publisher),
         FieldName.Address:
         Field(FieldName.Address),
         FieldName.Month:
         Field(FieldName.Month),
         FieldName.Note:
         Field(FieldName.Note)
     })
Esempio n. 12
0
def simulate(in_runs, in_pairs, in_visitors):
	target = [ [2,2,0],[2,2,1],[2,2,2] ]
	genes  = [ [1,1,0],[1,2,0],[2,0,0],[2,1,0] ] # simulating t110 x t110
	probs  = [ 4/9,    2/9,    1/9,    2/9     ] # 25/12.5/6.25/12.5
	genemap = len(probs)
	pairs_results = []
	turtle_results = []

	for run in range(in_runs):
		turtle_day = -1
		pairs_day = -1
		turtle = Field("turtle", turtle_layout)
		pairs  = Field("pairs", pairs_layout)
		pairer = PairBreeder()
		feeder = Feeder(genes, probs, visit=in_visitors, pairs=in_pairs)
		for day in range(1, 365):
			# get the days flowers
			feed = feeder.feed()
			# print("day",day,feed)

			# check for output from the pairer, put them into the pairs field
			for new_pair in pairer.breed():
				pairs.place(new_pair[0], new_pair[1])

			# add the day's feed into the pairer and the turtle
			for new_flower in feed:
				pairer.place(new_flower)
				turtle.place(new_flower)

			# everything above this point technically "runs" the day before
			# run the fields
			if pairs_day == -1:
				harvest  = pairs.run()
				# print("pairs:",  pairs_harvest)
				for flower in harvest:
					if flower.get_genes() in target:
						pairs_day = day
			if turtle_day == -1:
				harvest = turtle.run()
				# print("turtle:", turtle_harvest)
				for flower in harvest:
					if flower.get_genes() in target:
						turtle_day = day

			# break out if they both finish
			if turtle_day != -1 and pairs_day != -1:
				break
		if turtle_day != -1 and pairs_day != -1:
			# print("run", run, "ended on day", day, "turtle", turtle_day, "pairs", pairs_day)
			pairs_results.append(pairs_day)
			turtle_results.append(turtle_day)

	print("{}\t{}\tpairs\t{}\t{}\t{}\t{}\t{}".format(in_visitors, in_pairs, np.amin(pairs_results), np.amax(pairs_results), np.mean(pairs_results), np.median(pairs_results), np.percentile(pairs_results, 95)))
	print("{}\t{}\tturtle\t{}\t{}\t{}\t{}\t{}".format(in_visitors, in_pairs, np.amin(turtle_results), np.amax(turtle_results), np.mean(turtle_results), np.median(turtle_results), np.percentile(turtle_results, 95)))
	return
Esempio n. 13
0
 def __init__(self):
     self._id = None
     self.entryType = ''
     self.key = ''
     self.requiredFields = dict()
     self.optionalFields = {FieldName.Key: Field(FieldName.Key)}
     self.additionalFields = {
         FieldName.Annote: Field(FieldName.Annote),
         FieldName.Paper: Field(FieldName.Paper),
         FieldName.Comment: Field(FieldName.Comment)
     }
Esempio n. 14
0
    def __init__(self, name, settings):
        super().__init__(name, settings)
        self.name(name)
        self.description = ""
        # self.number_of_fifos = 1
        self.fifo_fields = []
        if self.access_mode() not in ['RO', 'WO']:
            logger.error(
                "'{}' not a valid access mode for slaves of type FIFO. Valid modes include 'RO' and 'WO'"
                .format(self.access_mode()))
            raise ARGSModeError

        self.tx_fifo_vacancy = Field(
            name="fifo_status",
            settings={
                'width':
                32,
                'access_mode':
                "RO",
                'address_offset':
                0x8,
                'reset_value':
                0,
                'field_description':
                "Transmit Data FIFO Vacancy (TDFV). Width N equal to C_S_AXI_DATA_WIDTH"
            })
        self.rx_fifo_occupancy = Field(
            name="fifo_status",
            settings={
                'width':
                16,
                'access_mode':
                "RO",
                'address_offset':
                0x1C,
                'reset_value':
                0,
                'field_description':
                "Receive Data FIFO Occupancy (RDFO). Number of locations in use for data storage"
            })
        self.rx_length = Field(
            name="fifo_status",
            settings={
                'width':
                23,
                'access_mode':
                "RO",
                'address_offset':
                0x24,
                'reset_value':
                0,
                'field_description':
                "Receive Length Register (RLR). The number of bytes of the corresponding receive data stored in the receive data FIFO"
            })
Esempio n. 15
0
def create_array_field():
    """Create a Protocol instance with some fields."""
    proto, diss = dissector.Protocol.create_dissector('test')
    field = Field('arr', 'float', 4, 0, Platform.big)
    diss.add_field(ArrayField.create([2, 3], field))
    field = Field('str', 'string', 30, 0, Platform.big)
    diss.add_field(ArrayField.create([2], field))
    diss.push_modifiers()
    yield diss.children[0], diss.children[1]
    dissector.Protocol.protocols = {}
    del proto, diss
Esempio n. 16
0
    def start_game(self):
        field1 = Field()
        field2 = Field()

        client1, client2 = self._server.get_clients()
        print(client1, client2)

        player1 = Player(client1[0], client1[1], field1, 'player1')
        player2 = Player(client2[0], client2[1], field2, 'player2')

        self._game_process(player1, player2)
Esempio n. 17
0
def create_lua_keywords_field():
    """Create a Protocol instance with some fields."""
    proto, diss = dissector.Protocol.create_dissector('test')
    field = Field('elseif', 'int32', 4, 0, Platform.big)
    field.set_list_validation(dict(enumerate('VWXYZ')))
    diss.add_field(field)
    diss.add_field(Field('in', 'float', 4, 0, Platform.big))
    diss.push_modifiers()
    yield diss.children[0], diss.children[1]
    dissector.Protocol.protocols = {}
    del proto, diss
Esempio n. 18
0
    def init_fields(self):
        for i in range(8):
            for j in range(0, 8, 2):
                if i % 2 == 0:
                    light_field = Field(i, j, 50, "light")
                    dark_field = Field(i, j + 1, 50, "dark")
                else:
                    dark_field = Field(i, j, 50, "dark")
                    light_field = Field(i, j + 1, 50, "light")

                self.fields.append(light_field)
                self.fields.append(dark_field)
Esempio n. 19
0
 def __init__(self):
     super(Unpublished, self).__init__()
     self.entryType = 'UNPUBLISHED'
     self.requiredFields = {
         FieldName.Author: Author(),
         FieldName.Title: Field(FieldName.Title),
         FieldName.Note: Field(FieldName.Note)
     }
     self.optionalFields.update({
         FieldName.Year: Year(),
         FieldName.Month: Field(FieldName.Month)
     })
Esempio n. 20
0
 def __init__(self):
     """
     This method initializes a Game class.
     field: - list of Fields for the game
     players: - list of Players for the game
     """
     field1, field2 = Field(), Field()
     self.__field = [field1, field2]
     name1 = str(input("Please enter name:"))
     name2 = str(input("Please enter name:"))
     self.__players = [Player(name1), Player(name2)]
     self.__current_player = 1
Esempio n. 21
0
 def test_plow_sow_action(self):
     player = init_player()
     player.set_next_space(Field())
     player.set_next_space(Field())
     player.add_supply(VEGETABLE)
     player.add_supply(GRAIN, 2)
     args = {VEGETABLE: 1, GRAIN: 2}
     if not PLOW_SOW_ACTION.apply_action(player, args):
         self.assertTrue(False, 'Action not completed.')
     expected = 3
     self.assertEqual(len(player.get_fields()), expected)
     self.assertEqual(sum([len(f.sown) for f in player.get_fields()]), 8)
Esempio n. 22
0
def multiply(background: Field, foreground: Field):
    white = Field(10, 20)
    for x in range(10):
        for y in range(20):
            white.set_pixel(x, y, [255, 255, 255])

    bg = numpy.array(background.field)
    fg = numpy.array(foreground.field)
    multi = numpy.multiply(bg, fg)
    multi = numpy.divide(multi, white.field)
    combined = Field(10, 20)
    combined.field = multi.astype(int).tolist()
    return combined
Esempio n. 23
0
 def __init__(self):
     super(Manual, self).__init__()
     self.entryType = 'MANUAL'
     self.requiredFields = {FieldName.Title: Field(FieldName.Title)}
     self.optionalFields.update({
         FieldName.Author: Author(),
         FieldName.Organization: Organization(),
         FieldName.Edition: Field(FieldName.Edition),
         FieldName.Address: Field(FieldName.Address),
         FieldName.Year: Year(),
         FieldName.Month: Field(FieldName.Month),
         FieldName.Note: Field(FieldName.Note)
     })
Esempio n. 24
0
def main():
    setrecursionlimit(10000)

    game_field = Field()

    while True:
        command = Menu.get_command()

        if command.startswith(Commands.EXIT):
            return
        elif command.startswith(Commands.START):
            result = do_start_command(command, game_field)
            if result is True:
                game_field = Field()
Esempio n. 25
0
    def _init_fields(self) -> None:
        """
        method for placing ships on both players' fields
        """
        # set player.my_field
        self.players[0].set_and_fill_field(
            field=Field(height=self.map_height, width=self.map_width))
        self.players[1].set_and_fill_field(
            field=Field(height=self.map_height, width=self.map_width))

        # set player.enemy_field
        self.players[0].enemy_field = Field(height=self.map_height,
                                            width=self.map_width)
        self.players[1].enemy_field = Field(height=self.map_height,
                                            width=self.map_width)
Esempio n. 26
0
    def __parse_board(self, matrix: List[List[str]]) -> List[List[Field]]:
        """
        Parses input matrix into list of lists of fields imitating chessboard\n
        :param matrix: Input containing matrix of encoded pieces
        :return: List of lists of fields
        """
        def create_fields(color: str, y: int, x: int) -> dict:
            """
            Creates field dictionary matching code, color and coordinates with pieces\n
            :param color: Color of piece
            :param y: Vertical coordinate (0 starts at top of imaginary chessboard)
            :param x: Horizontal coordinate (0 starts at left of imaginary chessboard)
            :return: Dictionary of string, Field pairs
            """
            return {
                'p': Field(WPawn(), x, y, Statuses.PIECE),
                'r': Field(Rook(color), x, y, Statuses.PIECE),
                'k': Field(Knight(color), x, y, Statuses.PIECE),
                'b': Field(Bishop(color), x, y, Statuses.PIECE),
                'q': Field(Queen(color), x, y, Statuses.PIECE),
                'W': Field(King(color), x, y, Statuses.PIECE)
            }

        board = []
        for _ in matrix:
            board.append([])
        i = 0
        colors = ("white", "black")
        for row in matrix:
            j = 0
            for field in row:
                if field == '--':
                    board[i].append(Field(Piece(), j, i, Statuses.NULL))
                else:
                    color, piece = field[0], field[1]
                    if color == 'w':
                        fields = create_fields(colors[0], i, j)
                        if piece == 'W':
                            self.white_king_position = (j, i)
                    else:
                        fields = create_fields(colors[1], i, j)
                        fields['p'] = Field(BPawn(), j, i, Statuses.PIECE)
                        if piece == 'W':
                            self.black_king_position = (j, i)
                    board[i].append(fields[piece])
                j += 1
            i += 1
        return board
Esempio n. 27
0
 def __init__(self, u, F):
     self.t = 0
     self.iter = 0
     self.u = u
     self.RHS = Field(u.grid)
     self.F = F
     self.I = Average3(u)
Esempio n. 28
0
 def __init__(self,
              field_size,
              food_fill_factor,
              num_initial_creatures,
              creature_mutation="NORMAL",
              creature_reproduction_mutation_prob=0,
              creatures_randomly_teleport=False,
              field_has_boundaries=False,
              food_spoils=False,
              creature_meat_value=2):
     self.field = Field(field_size, has_boundaries=field_has_boundaries)
     self.field.sprout(food_fill_factor)
     self.creatures = []
     self.creatures_by_loc = [[[] for x in range(field_size)]
                              for y in range(field_size)]
     self.create_creatures(
         num_initial_creatures,
         creature_mutation=creature_mutation,
         creature_reproduction_mutation_prob=
         creature_reproduction_mutation_prob,
         creatures_randomly_teleport=creatures_randomly_teleport,
         creature_meat_value=creature_meat_value)
     self.days_passed = 0
     self.history = []
     self.food_fill_factor = food_fill_factor
     self.food_spoils = food_spoils
Esempio n. 29
0
 def create_entry(filename):
     entryid = str(uuid.uuid1)
     self.instance[entryid] = {}
     self.instance[entryid]["FILE"] = filename
     self.instance[entryid]["STATE"] = FileState.UNLOADED
     self.instance[entryid]["DATA"] = Field()
     return entryid
Esempio n. 30
0
def get_time_dependent_circular_flow_fields():
    x = np.linspace(-5, 5, 100)
    y = np.linspace(-2, 2, 100)
    a = 1
    U_inf = 10
    K = 0
    X, Y = np.meshgrid(x, y, indexing='ij')
    R_sq = X**2 + Y**2
    space = Space([x, y])
    space.set_elements_names(['x', 'y'])

    K_coeffs = np.linspace(0, 2 * U_inf * a, 100)
    fields = []
    for K in K_coeffs:
        u = U_inf * (
            1 - (a**2 * R_sq - 2 * a**2 * Y**2) / R_sq**2) - K * a * Y / R_sq
        v = -2 * U_inf * a**2 * X * Y / R_sq**2 + K * a * X / R_sq
        for xi in range(len(x)):
            for yi in range(len(y)):
                if x[xi]**2 + y[yi]**2 < a**2:
                    u[xi, yi] = 0.
                    v[xi, yi] = 0.

        circ_field = Field([u, v], space)
        circ_field.set_elements_names(['u', 'v'])
        fields.append(circ_field)
    return fields