def __init__(self, name, size): self.name = name self.ships = [] self.field_size = size self.my_field = Field(size, is_enemy=False) self.enemy_field = Field(size, is_enemy=True) self.verbose = True
class FieldTests(unittest.TestCase): def setUp(self): self.__x = random.randint(2, 128) self.__y = random.randint(2, 128) self.__field = Field(self.__y, self.__x) def test_zero(self): self.assertFalse(Field(0, 0).is_correct(0, 0)) def test_size(self): self.assertEqual(self.__field.x, self.__x) self.assertEqual(self.__field.y, self.__y) def test_basic(self): n = random.random() x = random.randint(0, self.__x - 1) y = random.randint(0, self.__y - 1) self.__field[y][x] = n self.assertEqual(self.__field[y][x], n) def test_border(self): self.__field[0][0] = 0 self.__field[self.__y - 1][self.__x - 1] = 0 def test_method_is_correct(self): x = random.randint(0, self.__x - 1) y = random.randint(0, self.__y - 1) self.assertTrue(self.__field.is_correct(0, 0)) self.assertTrue(self.__field.is_correct(y, x)) self.assertTrue(not self.__field.is_correct(-1, 0)) self.assertTrue(not self.__field.is_correct(0, -1)) self.assertTrue(not self.__field.is_correct(self.__y, 0)) self.assertTrue(not self.__field.is_correct(0, self.__x))
def __init__(self,name,type_byte_nr=1,length_byte_nr=1,length_compensation=0,type_=0,value=''): Field.__init__(self, name, value) self._type_byte_nr = type_byte_nr self._length_byte_nr = length_byte_nr self._type = type_ self._length_compensation = length_compensation self._length = len(value) + length_compensation
def __init__(self, fdir, fname, parallel_run=None): Raw = OpenFOAM_RawData(fdir, fname, self.nperbin, parallel_run=parallel_run) Field.__init__(self, Raw) self.axislabels = ['x','y','z'] self.plotfreq = self.Raw.Nave
def tick(self, time_diff): """Some time has passed; decide what to do next.""" mytanks, othertanks, flags, shots = self.bzrc.get_lots_o_stuff() self.mytanks = mytanks self.flags = flags # We only care about our enemy's flag enemy_flag = None for flag in self.flags: # print("flag color: %s x: %f y: %f" % (flag.color, flag.x, flag.y)) if flag.color == self.enemy: # print("enemy found, and it is %s" % flag.color) enemy_flag = flag # Flag is the goal, so it creates an attractive field obstacles = self.bzrc.get_obstacles() fields = self.repulsive_and_tangential_fields_from_obstacles(obstacles) # fields = [] attractive_field = Field(enemy_flag.x, enemy_flag.y, 5, 300) attractive_field.kind = 'attractive' for tank in self.mytanks: # print("tank angle is %f x is %f y is %f" % (tank.angle, tank.x, tank.y)) #if this tank has the flag, then its attractive field is the home base if tank.flag == self.enemy: attractive_field = Field((self.base.corner1_x + self.base.corner3_x) / 2.0, (self.base.corner1_y + self.base.corner3_y) / 2.0, 5, 300) attractive_field.kind = 'attractive' fields.append(attractive_field) self.bzrc.angvel(tank.index, self.calculate_angvel(tank, fields)) #speed depends on how far away we are? #just ignore that for now, see if it works. self.bzrc.speed(tank.index, self.calculate_speed(tank, fields)) self.bzrc.shoot(tank.index)
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
def generate_matrix(q, number_processes = 35): field = Field(q) two_powers = [2 ** (q - i) for i in xrange(q + 1)] with Manager() as manager: A = manager.dict() # where we store the row integers amount = lambda : len(A) # I use this to print out how many rows we have generated periodically def append(x): if x in A: return 0 A[x] = True return 1 #append = lambda x : A.__setitem__(x, True) is_new = lambda x : not A.__contains__(x) # to avoid duplicate entries # we don't need the a = 0, b = q - 1 case because it requires setting the 0th column (0 * (q-1)) which has already been chosen a = q - 1 # generate all the numerators quickly numerators = [[field.add(field.multiply(a, t), c) for t in field.trace()] for c in field] bs = range(q - 3) + [q - 1] # all the b values we need _distribute(lambda bs : _make_and_start_process(bs, a, field, numerators, append, is_new, two_powers, amount), bs, number_processes) # start all the processes and then wait for them to finish # the keys of the dictionary represent the row integers for the problem return A.keys()
def parseJsonPage(self, site, doc, listurl): try: doc = json.loads(doc, encoding=site.getCharset()) item = self.listRule.getEntryItem() if item and item in doc: data = doc[item] else: data = doc urlParent = self.listRule.getContentUrl() extrarules = self.listRule.extrarules if isinstance(data, list) and urlParent: for _data in data: if urlParent in _data: link = urlparse.urljoin(listurl, _data[urlParent]) guid = md5(link).hexdigest() _item = Item({ "type" : self.seed_type, "images" : [] }) #取出需要的key数据 for field_name, _rule, fetch_all, page_type in extrarules: field = Field(name = field_name, rule=_rule) if _rule in _data: value = _data[_rule] if is_image(value): _item["images"].append(value) field.value = value _item[field["name"]] = field if (link is not None): _item['url'] = link # get item guid if self.guid_rule: guid = self.getItemGUID(_item) elif self.seed["dont_craw_content"]: self.guid_rule = [] for f in _item.fields: self.guid_rule.append(_item[f]["id"]) guid = self.getItemGUID(_item) self.guid_rule = None else: self.guid_rule = "url" guid = self.getItemGUID(_item) self.guid_rule = None self.items[guid] = _item else: if isinstance(self.items, dict): self.items = []; self.items.append(data) except: raise "Cant parse json file"
class Saver(): def __init__(self, balls=int(random.random() * 100), trail=" "): self.field = Field(title="Term Saver") self.balls = [Ball(x=int(random.random() * self.field.x-1)+1, y=int(random.random() * self.field.y-1)+1) for x in range(balls)] self.speed = 0.009 self.trail = trail return def update(self): for ball in self.balls: hitWall = self.walled(ball) if hitWall: # wall collision ball.bounce(hitWall) # ball collision self.clearTrail(ball, self.trail, True) ball.move() self.field.write_at(item=ball.image, coords=ball.getPosition()) # clear the field randomly (.1% chance) if random.choice(range(1000)) == 1: self.field.clear() self.field.deploy() return def walled(self, ball): direction = [] if ball.x < 1: direction.append('right') elif ball.x >= self.field.x-1: direction.append('left') if ball.y < 1: direction.append('down') elif ball.y >= self.field.y-1: direction.append('up') if len(direction): return ' '.join(direction) return None def run(self): run = 1 while run: c = self.field.display.getch() if c == ord('q'): run = 0 self.update() time.sleep(self.speed) self.field.destroy() return def clearTrail(self, obj, remains=" ", centered=False): for i in range(len(obj.image)): self.field.write_at(item=remains, coords=[obj.x+i, obj.y], centered=centered) return
def frame_paint(self,dt): """Clear the current OpenGL context, calls actor's paint_all method """ if not self.paused: self.gl_clear() Field.paint() if self.show_fps: self.pcd.draw()
def __init__(self, settings, name, data, allowed_range=None): """Set the allowed range if specified.""" self.start = None self.end = None if allowed_range is not None: self.start, self.end = allowed_range Field.__init__(self, settings, name, data)
def __init__(self,fdir,rectype='bins'): self.vField = Channelflow_vField(fdir) self.strainField = Channelflow_strainField(fdir) Field.__init__(self,self.vField.Raw) self.inherit_parameters(self.strainField) self.labels = ["mag"] self.nperbin = 1
def __init__(self, settings, name, data, first_name_list=None): """Get a first name list if necessary and call parent constructor.""" if first_name_list: first_name_list = settings.resolve_path(first_name_list) with open(first_name_list, 'r') as f: self._first_name_list = f.read().splitlines() else: self._first_name_list = [] Field.__init__(self, settings, name, data)
def __init__(self,fdir,rectype='bins'): self.vField = Channelflow_vField(fdir) Field.__init__(self,self.vField.Raw) self.inherit_parameters(self.vField) self.labels = ["dudx","dudy","dudz", "dvdx","dvdy","dvdz", "dwdx","dwdy","dwdz"] self.nperbin = 9
def __init__(self): """ EXAMPLES:: sage: ContinuedFractionField() Field of all continued fractions """ Field.__init__(self, self) self._assign_names(('x'),normalize=False)
def __init__(self): field = Field(2**255 - 19) ed25519 = TwistedEdwardsCurve(-1, field.div(-121665, 121666), field) base_point = (15112221349535400772501151409588531511454012693041857206046113283949847762202L, 46316835694926478169428394003475163141307993866256225615783033603165251855960L) self.curve = ed25519 self.bp = base_point
def test_domain_centre(self): cmin = (-18.5, 5, 0) cmax = (10, 10, 10) d = (0.1, 0.25, 2) name = 'test_field' f = Field(cmin, cmax, d, dim=2, name=name) assert f.domain_centre() == (-4.25, 7.5, 5)
def create_enum_field(): """Create a Protocol instance with some fields.""" proto, diss = dissector.Protocol.create_dissector('test') field = Field('enum', 'int32', 4, 0, Platform.big) field.set_list_validation(dict(enumerate('ABCDE'))) diss.add_field(field) diss.push_modifiers() yield diss.children[0] dissector.Protocol.protocols = {} del proto, diss
def tick(self,dt): """Calls the actors update_all method until time out """ if not self.paused: self.chrono += dt if self.chrono > DURATION: exit() Field.tick(dt) else: pass
def test_index2coord(self): cmin = (-1, -4, 11) cmax = (15, 10.1, 12.5) d = (1, 0.1, 0.5) name = 'test_field' f = Field(cmin, cmax, d, dim=2, name=name) assert f.index2coord((0, 0, 0)) == (-0.5, -3.95, 11.25) assert f.index2coord((5, 10, 1)) == (4.5, -2.95, 11.75)
def _create_enum(self, name, enum): """Create a new enum field.""" if enum not in self.enums.keys(): raise ParseError('Unknown enum: %s' % enum) type = self.map_type('enum') size = self.size_of('enum') alignment = self.alignment('enum') field = Field(name, type, size, alignment, self.platform.endian) field.set_list_validation(self.enums[enum]) return field
def generate_schematic(self, circuit_raw=None, circuit_id=None, options=None): """ Generate a schematic for the given raw circuit data. circuit_raw: list-dict like [{"name":.. ,"type":.. , "conns":.. , "groups":..}, ..] circuit_id: of the circuit as a tuple of strings ("foo", "bar") options: a {} to set various config options, see __init__() """ # allow to pre-set target circuit as object-attr, # instead of passing as argument self.cur_circ = circuit_id or self.cur_circ self.cur_circ_raw = circuit_raw or self.cur_circ_raw # make sure both contain something useful assert self.cur_circ assert self.cur_circ_raw # apply available OPTIONS here options = self.options = options or {} xsize = options.get("xsize") or 40 ysize = options.get("ysize") or 40 optimizer = "deterministic" if "optimizer" in options: optimizer = options["optimizer"] try: # max field size is critical... # DETERMINISTIC -> can be biiig, makes no difference # EVOLUTIONARY -> small approx 14x14 for 4block+bias print "\n".join(str(x) for x in self.cur_circ_raw) field = Field(self.cur_circ, xsize, ysize) #if optimizer == "deterministic": # o = Deterministic(field) #elif optimizer == "evolution": # o = GeneticAlgorithm(field) #else: # print "[ERR] Unknown optimizer!" # sys.exit(1) o = FakeOptimizer(field, self.cur_circ_raw) field = o.run() field.optimize_size() self.plot(field) return True except (OptimizerError, FieldException) as e: print "[-] failed to create schematic for circ {}".format(self.cur_circ) print e.message return False return None # never reached
def shuffle_from_field(self, field): f = Field(field.circuit_id, field.nx, field.ny) blocks = field.get_blocks() shuffle(blocks) for blk in blocks: ypos = choice(range(2, f.ny-4+1, 2)) if not f.add_in_row(ypos, blk): raise FieldBlockCouldNotBePlaced((ypos, -1), blk) return out
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
def setUp(self): # Test with Ed25519 field = Field(2**255 - 19) ed25519 = TwistedEdwardsCurve(-1, field.div(-121665, 121666), field) base_point = (15112221349535400772501151409588531511454012693041857206046113283949847762202L, 46316835694926478169428394003475163141307993866256225615783033603165251855960L) self.curve = ed25519 self.bp = base_point self.bp_order = 2**252 + 27742317777372353535851937790883648493
def postsimilar(self,sessionuserid): newf = [] for fld in self.fields: f = Field(sessionuserid,fld.decoration,fld.label) newf.append(f) cPickle.dump(f, open(f.getid()+".obj",'wb')) newp = Pagelet(sessionuserid,self.views,newf) self.leaves.append(newp.getid()) cPickle.dump(self, open(self.getid()+".obj",'wb')) cPickle.dump(self, open(newp.getid()+".obj",'wb')) return newp
def __init__(self, fdir): # Get mean velocity and density field self.fdir = fdir self.vField = Channelflow_vField(fdir) Field.__init__(self,self.vField.Raw) self.inherit_parameters(self.vField) self.labels = ['uu','uv','uw', 'vu','vv','vw', 'wu','wv','ww'] self.nperbin = 9
def repulsive_and_tangential_fields_from_obstacles(self, obstacles): fields = [] for obstacle in obstacles: centroid = self.calculate_centroid(obstacle) radius = self.calculate_radius_from_centroid(centroid, obstacle) field = Field(centroid['x'], centroid['y'], radius, 100) field.kind = 'repulsive' fields.append(field) tan_field = Field(centroid['x'], centroid['y'], radius, 100) tan_field.kind = 'tangential' fields.append(tan_field) return fields
def test_random_coord(self): cmin = (-18.5, 5, 0) cmax = (10, 10, 10) d = (0.1, 0.25, 2) name = 'test_field' f = Field(cmin, cmax, d, dim=2, name=name) for j in range(500): c = f.random_coord() assert f.cmin[0] <= c[0] <= f.cmax[0] assert f.cmin[1] <= c[1] <= f.cmax[1] assert f.cmin[2] <= c[2] <= f.cmax[2]
def test_coord2index(self): cmin = (-10, -5, 0) cmax = (10, 5, 10) d = (1, 5, 1) name = 'test_field' f = Field(cmin, cmax, d, dim=2, name=name) assert f.coord2index((-10, -5, 0)) == (0, 0, 0) assert f.n[0] == 20 assert f.coord2index((10, 5, 10)) == (19, 1, 9) assert f.coord2index((0.0001, 0.0001, 5.0001)) == (10, 1, 5) assert f.coord2index((-0.0001, -0.0001, 4.9999)) == (9, 0, 4)
def initializeFields(self): self.fields = [] self.fields.append( Field(name="Start", isSpecial=True, specialFunction=self.startField, imagePath="res/start.png")) #Start self.fields.append( Field(name="Współczesne stosunki międzynarodowe", color=(102, 51, 0), financial=(12, 4, 6, 18, 50, 10)) ) # 1.1 -financial cena,opłata bazowa,opłata 1 poziom,opłata 2 poziom,opłata 3 poziom,cena upgradu self.fields.append( Field(name="Szansa", isSpecial=True, specialFunction=self.chanceField, imagePath="res/questionmark.png")) # Szansa self.fields.append( Field(name="Historia Filozofii", color=(102, 51, 0), financial=(12, 4, 12, 36, 90, 10))) # 1.2 self.fields.append( Field(name="DUUUŻY grzyb", isSpecial=True, specialFunction=self.bigMushroom, imagePath="res/bigmush.png")) # Grzyb duży self.fields.append( Field(name="Wstęp do informatyki", color=(204, 229, 255), financial=(20, 6, 18, 54, 110, 10))) # 2.1 self.fields.append( Field(name="Szansa", isSpecial=True, specialFunction=self.chanceField, imagePath="res/questionmark.png")) # Szansa self.fields.append( Field(name="Wstęp do programowania w języku Python", color=(204, 229, 255), financial=(20, 6, 18, 54, 110, 10))) # 2.2 self.fields.append( Field(name="Wstęp do programowania w języku C", color=(204, 229, 255), financial=(24, 8, 20, 60, 120, 10))) # 2.3 self.fields.append( Field(name="Naprawa komputera", isSpecial=True, specialFunction=self.prisonField, imagePath="res/jail.png")) # Więzienie self.fields.append( Field(name="Kurs: Podstawowy warsztat informatyka", color=(153, 0, 153), financial=(28, 10, 30, 90, 150, 20))) # 3.1 self.fields.append( Field(name="Praktyka zawodowa w Nokii", isSpecial=True, specialFunction=self.practiseField, financial=(45, 30, 0, 0, 0, 0), imagePath="res/nokia.png")) self.fields.append( Field(name="Komunikacja człowiek-komputer", color=(153, 0, 153), financial=(28, 10, 30, 90, 150, 20))) # 3.2 self.fields.append( Field(name="Systemy wbudowane", color=(153, 0, 153), financial=(32, 12, 36, 100, 180, 20))) # 3.3 self.fields.append( Field(name="Rozwój systemu zapisów", color=(255, 128, 0), financial=(36, 14, 40, 110, 190, 20))) #4.1 self.fields.append( Field(name="Szansa", isSpecial=True, specialFunction=self.chanceField, imagePath="res/questionmark.png")) # Szansa self.fields.append( Field(name="Kurs: Praktyczne aspekty sieci komputerowych", color=(255, 128, 0), financial=(36, 14, 40, 110, 190, 20))) # 4.2 self.fields.append( Field(name="Kurs: WWW", color=(225, 128, 0), financial=(40, 16, 44, 120, 200, 20))) # 4.3 self.fields.append( Field(name="Tramwaj", isSpecial=True, specialFunction=self.tramField, imagePath="res/tram.png")) # Tramwaj self.fields.append( Field(name="Podstawy grafiki komputerowej", color=(255, 0, 0), financial=(44, 18, 50, 140, 210, 30))) # 5.1 self.fields.append( Field(name="Szansa", isSpecial=True, specialFunction=self.chanceField, imagePath="res/questionmark.png")) # Szansa self.fields.append( Field(name="Kurs programowania gier w silniku Unity3D", color=(255, 0, 0), financial=(44, 18, 50, 140, 210, 30))) # 5.2 self.fields.append( Field(name="Artificial Intelligence for Games", color=(255, 0, 0), financial=(48, 20, 60, 150, 220, 30))) # 5.3 self.fields.append( Field(name="Kurs języka Java", color=(255, 255, 0), financial=(52, 22, 66, 160, 230, 30))) # 6.1 self.fields.append( Field(name="Kurs języka Rust", color=(255, 255, 0), financial=(52, 22, 66, 160, 230, 30))) # 6.2 self.fields.append( Field(name="Praktyka zawodowa w Comarch", isSpecial=True, specialFunction=self.practiseField, financial=(45, 30, 0, 0, 0, 0), imagePath="res/comarch.png")) self.fields.append( Field(name="Języki programowania", color=(255, 255, 0), financial=(56, 24, 72, 170, 240, 30))) # 6.3 self.fields.append( Field(name="Zepsułeś komputer", isSpecial=True, specialFunction=self.goToPrison, imagePath="res/gotojail.png")) # Idź do więzienia self.fields.append( Field(name="Analiza numeryczna", color=(0, 153, 0), financial=(60, 26, 78, 190, 255, 40))) # 7.1 self.fields.append( Field(name="Matematyka dyskretna", color=(0, 153, 0), financial=(60, 26, 78, 190, 255, 40))) # 7.2 self.fields.append( Field(name="Szansa", isSpecial=True, specialFunction=self.chanceField, imagePath="res/questionmark.png")) # Szansa self.fields.append( Field(name="Algebra", color=(0, 153, 0), financial=(64, 30, 90, 200, 280, 40))) # 7.3 self.fields.append( Field(name="Szansa", isSpecial=True, specialFunction=self.chanceField, imagePath="res/questionmark.png")) # Szansa self.fields.append( Field(name="Analiza matematyczna", color=(3, 177, 252), financial=(70, 35, 100, 220, 300, 40))) # 8.1 self.fields.append( Field(name="Mały grzyb", isSpecial=True, specialFunction=self.littleMushroom, imagePath="res/smallmush.png")) # Grzyb mały self.fields.append( Field(name="Logika dla informatyków", color=(3, 177, 252), financial=(80, 40, 120, 280, 400, 40))) # 8.1
def request_field(self) -> Field: """ Сервер запрашивает поле :return: int[][] """ return Field.generate_random_field(self.client_id)
elif rotation == 2: keys.append(keymap['rotate_right']) keys.append(keymap['rotate_right']) elif rotation == 3: keys.append(keymap['rotate_left']) # Then we move it all the way to the the left that we are guaranteed # that it is at column 0. The main reason for doing this is that when # the tetromino is rotated, the bottom-leftmost piece in the tetromino # may not be in the 3rd column due to the way Tetris rotates the piece # about a specific point. There are too many edge cases so instead of # implementing tetromino rotation on the board, it's easier to just # flush all the pieces to the left after orienting them. for i in range(4): keys.append(keymap['move_left']) # Now we can move it back to the correct column. Since pyautogui's # typewrite is instantaneous, we don't have to worry about the delay # from moving it all the way to the left. for i in range(column): keys.append(keymap['move_right']) keys.append(keymap['drop']) return keys if __name__ == '__main__': f = Field() f.drop(Tetromino.TTetromino(), 3) opt = Optimizer.get_optimal_drop(f['tetromino_rotation'], f['tetromino_column'], Tetromino.ITetromino()) print(opt['field'])
class Foo(Model): foo_field = Field('text')
class Solution: # data structure : numpy 2D array # [[x, y], --> alphabet a (index = 0) and x, y are floats # [x, y], --> alphabet b (index = 1) # . # . # . # [x, y], --> alphabet z (index = 25) # ] num_alphabet = 32 field = Field() # constructor def __init__(self, seed=None): # generate solution with seed list if seed is not None: self.positions = np.array(seed) num_alphabet = len(seed) # generate random solution else: # auxiliary random function which never returns 0 def rand_nonzero(): temp = np.random.rand() while temp == 0.0: temp = np.random.rand() return temp # random generate self.positions = np.array([[ rand_nonzero() * CONFIG['keyboard_width'], rand_nonzero() * CONFIG['keyboard_height'] ] for i in range(Solution.num_alphabet)]) # calculate necessary values # calculate area of polygon using showlace formula def poly_area(x, y): return 0.5 * np.abs( np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) # expand voronoi diagram for 4-directions under = self.positions * np.array([1, -1]) right = self.positions * np.array([-1, 1]) + np.array( [2 * CONFIG['keyboard_width'], 0]) upper = self.positions * np.array([1, -1]) + np.array( [0, 2 * CONFIG['keyboard_height']]) left = self.positions * np.array([-1, 1]) points = np.concatenate((self.positions, under, right, upper, left), axis=0) # make voronoi diagram vor = Voronoi(points) # list of areas of each voronoi cells areas = [] # list of rectangular areas of each voronoi cells areas_rect = [] # list of central points of each voronoi cells central_points = [] # list of number of fingers correponding to alphabets which_finger = [] # list of coordinates of vertices of each voronoi regions voronoi_edges = [] # for each cells from a to spacebar, calculate area of cells for i in range(Solution.num_alphabet): index_region = vor.point_region[i] index_vertices = vor.regions[index_region] # coordinate of each vertices x_coord = [] y_coord = [] # calculate areas for j in index_vertices: x_coord.append(vor.vertices[j][0]) y_coord.append(vor.vertices[j][1]) areas.append(poly_area(x_coord, y_coord)) # calculate vertices of voronoi region edge_vertices = [] for j in index_vertices: edge_vertices.append(vor.vertices[j]) voronoi_edges.append(edge_vertices) # calculate min and max of x, y coord min_x = min(x_coord) max_x = max(x_coord) min_y = min(y_coord) max_y = max(y_coord) # calculate rectangular areas rect_width = abs(max_x - min_x) rect_height = abs(max_y - min_y) areas_rect.append(rect_width * rect_height) # calculate central point of each voronoi cells cent_x = (min_x + max_x) / 2 cent_y = (min_y + max_y) / 2 central_points.append([cent_x, cent_y]) # calculate which finger will push the key which_finger.append(Solution.field.which_finger([cent_x, cent_y])) # add attributes self.areas = areas self.areas_rect = areas_rect self.central_points = central_points self.which_finger = which_finger self.voronoi_edges = voronoi_edges self.vor = vor # get coordinate of key by name # ex) # sol.get_loc_by_name('a') def get_loc_by_name(self, keyname): return self.positions[ord(keyname) - 97] # get coordinate of key def get_loc(self, index): return self.positions[index] # plot voronoi diagram def plot(self): # labels for labeling points labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' labels = 'qwertyuiop!asdfghjkl@#zxcvbnm$%^' # plot voronoi_plot_2d(self.vor, show_vertices=False, show_points=False) colors = [ '#ffb3b3', '#ffd9b3', '#ffffb3', '#d9ffb3', '#b3ffff', '#b3d9ff', '#b3b3ff', '#d9b3ff' ] for i in range(Solution.num_alphabet): index_region = self.vor.point_region[i] index_vertices = self.vor.regions[index_region] polygon = [self.vor.vertices[j] for j in index_vertices] #plt.fill(*zip(*polygon), colors[self.which_finger[i]]) # draw points and labels plt.scatter(self.positions[:, 0], self.positions[:, 1], s=10, zorder=100) for i, txt in enumerate(labels): plt.annotate(txt, (self.positions[:, 0][i], self.positions[:, 1][i])) # config plt plt.xlim(0, CONFIG['keyboard_width']) plt.ylim(0, CONFIG['keyboard_height']) plt.gca().set_aspect('equal', adjustable='box') plt.show()
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 if __name__ == "__main__": back = Field(10, 20) fore = Field(10, 20) rainbowclock = Field(10, 20) rgb_field_painter = RGB_Field_Painter() clock = Clock(fore, Field(32, 8), rgb_field_painter, Led_Matrix_Painter()) COLORS = 60 r = rainbowcolors(COLORS) currentrainbowstart = 0 while True: currentrainbowstart += 1 currentrainbowstart %= COLORS - 20 for x in range(10): for y in range(20): back.set_pixel(x, y, r[y + currentrainbowstart]) clock.draw_clock([255, 255, 255])
from intcomp import IntComp from intcomp import Status from field import Field from field import coord filename = "11day-input.txt" output_file = "output.txt" if os.path.exists(output_file): os.remove(output_file) if len(sys.argv) > 1: filename = sys.argv[1] comp = IntComp(filename) hull = Field() status = Status.INPUT_REQUIRED pos = coord(0, 0) rot = 0 #0 = up, increasing clockwise count = set() # Day 11.2 hull.set_val(1, pos) while status == Status.INPUT_REQUIRED: paint = hull.get_val(pos) outs = comp.execute_tape(paint) status = outs[0]
def load_fields(self, fields): for name, attr in fields.iteritems(): field = Field.get_field(attr['type']) attr['name'] = name self.fields[name] = field(attr)
# # .. set index for begining & end of film times, groups = run.getTimeGroups(time) times.sort() # for index, time in enumerate(times) : text = ['$N_e \mathrm{~@~} t = \mathrm{~}$'+'${:6.1f}$'.format(time)] print('time : '+str(time)+' / '+str(times[-1])) data = run.getN(time, 'a') flux = run.getA(time, 'z', 'fftw') filename = basename+str(index) # .. load the data for image im0 = Field(limit = limit, data = data, domain = domain, shifts = shifts) # # .. load the data for contours im1 = Field(limit = limit, data = flux, domain = domain, stride = None, section = None, shifts = shifts, labels = None) # # .. draw the plot plo = Colp(coloraxis = im0.axis, colordata = im0.data, bounds = bounds,
def start_game(self): while True: print() print("Chose the game mode: ") print("[1] 1 Player vs Bot") print("[2] 2 Players") print() command = input("Enter command: ") if command.isdigit() and command == "1": while True: print("Enter size of grid (between 3 to 10): ") print() size = input("Enter size: ") if size.isdigit() and 3 <= int(size) <= 10: break else: print("Please enter correct size!") field = Field(int(size)) player = Player("X") bot = Bot("O") checker = Checker(field.grid) first_player = randint(0, 1) if first_player == 0: field.display() not_finished = True while not_finished: y, x = player.make_move(field.grid) field.fill_cell(player.symbol, x, y) field.display() flag = checker.do_win_the_game(player) if flag: print("You won the game!") not_finished = False no_empty = checker.no_empty_cell() if no_empty: print("It's a draw!") break if not flag: y, x = bot.make_move(field.grid) field.fill_cell(bot.symbol, x, y) field.display() flag = checker.do_win_the_game(bot) if flag: print("Bot won the game!") break no_empty = checker.no_empty_cell() if no_empty: print("It's a draw!") break else: field.display() not_finished = True while not_finished: y, x = bot.make_move(field.grid) field.fill_cell(bot.symbol, x, y) field.display() flag = checker.do_win_the_game(bot) if flag: print("Bot won the game!") not_finished = False no_empty = checker.no_empty_cell() if no_empty: print("It's a draw!") break if not flag: y, x = player.make_move(field.grid) field.fill_cell(player.symbol, x, y) field.display() flag = checker.do_win_the_game(player) if flag: print("You won the game!") break no_empty = checker.no_empty_cell() if no_empty: print("It's a draw!") break elif command.isdigit() and command == "2": while True: print("Enter size of grid (between 3 to 10): ") print() size = input("Enter size: ") if size.isdigit() and 3 <= int(size) <= 10: break else: print("Please enter correct size!") field = Field(int(size)) player_1 = Player("X") player_2 = Player("O") checker = Checker(field.grid) first_player = randint(0, 1) if first_player == 0: field.display() not_finished = True while not_finished: print("Player #1 turn:") y, x = player_1.make_move(field.grid) field.fill_cell(player_1.symbol, x, y) flag = checker.do_win_the_game(player_1) if flag: print("Player #1 won the game!") not_finished = False no_empty = checker.no_empty_cell() if no_empty: print("It's a draw!") break if not flag: print("Player #2 turn:") y, x = player_2.make_move(field.grid) field.fill_cell(player_2.symbol, x, y) field.display() flag = checker.do_win_the_game(player_2) if flag: print("Player #2 won the game!") break no_empty = checker.no_empty_cell() if no_empty: print("It's a draw!") break else: field.display() not_finished = True while not_finished: print("Player #2 turn:") y, x = player_2.make_move(field.grid) field.fill_cell(player_2.symbol, x, y) field.display() flag = checker.do_win_the_game(player_2) if flag: print("Player #2 won the game!") not_finished = False no_empty = checker.no_empty_cell() if no_empty: print("It's a draw!") break if not flag: print("Player #1 turn:") y, x = player_1.make_move(field.grid) field.fill_cell(player_1.symbol, x, y) field.display() flag = checker.do_win_the_game(player_1) if flag: print("Player #1 won the game!") break no_empty = checker.no_empty_cell() if no_empty: print("It's a draw!") break else: print("Please enter correct command!") while True: print() print("Do you want to play again?") print("[1] YES") print("[2] EXIT") command = input("Enter command: ") if command.isdigit() and command == "1": break elif command == "2": exit(1) else: print("Please enter correct command!")
__author__ = 'Thomas Scheinecker' from field import Field from base_entity import BaseEntity fieldSize = eval(input('Field size: ')) entryPoint = eval(input('Entry point: ')) basePoint = eval(input('Base point: ')) path = eval(input('Path: ')) print( "fieldSize: {fieldSize}; entryPoint {entryPoint}; basePoint; path {path}". format(**locals())) base = BaseEntity(100, 0, "BASE", "Your base", basePoint, 2, 3, 5, (2, 2)) print(base) field = Field(path, fieldSize, entryPoint, base) print(field)
def test_fieldtype_query_string_generation(self): expected_query_string = '[field_name] text' field = Field('text', name='field_name') self.assertEqual(field.query_string, expected_query_string)
def interpose(ball_info, robot_info, control_target): # ボールが動いていると判断するしきい値[m/s] MOVE_BALL_VELOCITY_THRESHOLD = 0.5 # ロボットがボールを持っていると判断するしきい値[m] DIST_ROBOT_TO_BALL_THRESHOLD = 0.2 # ゴールライン上ではなく一定距離[m]前を守るための変数 MARGIN_DIST_X = 0.1 # ゴールの位置(自陣のゴールのx座標は絶対負になる) OUR_GOAL_POSE = Field.goal_pose('our', 'center') OUR_GOAL_UPPER = Field.goal_pose('our', 'upper') OUR_GOAL_LOWER = Field.goal_pose('our', 'lower') # ボールの位置 ball_pose = ball_info.pose # 敵のロボットの情報 robot_info_their = robot_info['their'] # 敵ロボットとボールの距離 dist = [] for their_info in robot_info_their: if their_info.disappeared is False: dist.append(tool.distance_2_poses(their_info.pose, ball_pose)) else: dist.append(100) # 一番近い敵ロボットのID min_dist_id = dist.index(min(dist)) # 一番近い敵ロボットの座標 robot_pose = robot_info_their[min_dist_id].pose # ボールの速度 ball_velocity_x = ball_info.velocity.x ball_velocity_y = ball_info.velocity.y ball_velocity = math.hypot(ball_velocity_x, ball_velocity_y) # ボールの進む角度 angle_ball = math.atan2(ball_velocity_y, ball_velocity_x) # ボールの進む変化量を計算(方向を考慮した単位量) var_ball_velocity_x = math.cos(angle_ball) var_ball_velocity_y = math.sin(angle_ball) # ボールの次の予測位置を取得 ball_pose_next = Pose2D(ball_pose.x + var_ball_velocity_x, ball_pose.y + var_ball_velocity_y, 0) # 敵ロボットとボールの距離が近い場合は敵の向いている直線を使う if dist[min_dist_id] < DIST_ROBOT_TO_BALL_THRESHOLD and robot_pose.x < 0: slope = math.tan(robot_pose.theta) intercept = robot_pose.y - slope * robot_pose.x # ボールの速度がある場合かつ近づいてくる場合はボールの向かう直線を使う elif MOVE_BALL_VELOCITY_THRESHOLD < ball_velocity and ball_velocity_x < 0: slope, intercept = _get_line_parameters(ball_pose, ball_pose_next) # その他はゴール中心とボールを結ぶ直線を使う else: slope, intercept = _get_line_parameters(ball_pose, OUR_GOAL_POSE) # ゴーリの新しい座標 goalie_pose_x = OUR_GOAL_POSE.x + MARGIN_DIST_X goalie_pose_y = slope * goalie_pose_x + intercept # ゴールから飛び出さないようる上下限を設ける if OUR_GOAL_UPPER.y < goalie_pose_y: goalie_pose_y = OUR_GOAL_UPPER.y elif goalie_pose_y < OUR_GOAL_LOWER.y: goalie_pose_y = OUR_GOAL_LOWER.y # ゴーリの新しい座標 new_goalie_pose = Pose2D(goalie_pose_x, goalie_pose_y, 0) # --------------------------------------------------------- remake_path = False # pathが設定されてなければpathを新規作成 if control_target.path is None or len(control_target.path) == 0: remake_path = True # 現在のpathゴール姿勢と、新しいpathゴール姿勢を比較し、path再生成の必要を判断する if remake_path is False: current_goalie_pose = control_target.path[-1] if not tool.is_close(current_goalie_pose, new_goalie_pose, Pose2D(0.1, 0.1, math.radians(10))): remake_path = True # remake_path is Trueならpathを再生成する # pathを再生成すると衝突回避用に作られた経路もリセットされる if remake_path: control_target.path = [] control_target.path.append(new_goalie_pose) return control_target
F2.rowconfigure(i, weight=1) F2.grid(sticky='NEWS') return F2 def new(self): self.field.generateNew() self.drawField() def drawField(self): for (r, c), lab in self.field.get().items(): real_lab = str(lab) if lab == 16: real_lab = "" B = tk.Button(self.cellFrame, text=real_lab, command=lambda x=(r, c): self.moveCell(x)) B.grid(row=r, column=c, sticky='NEWS') self.cellFrame.grid(sticky='NEWS') def moveCell(self, c): self.field.move(c) self.drawField() if self.field.isWin(): mb.showinfo("Поздравление", "Вы победили!") self.new() f = Field() app = Application(f) app.mainloop()
def __init__(self, conf): Field.__init__(self, conf) for fieldConf in conf['fields']: field = Helper.createField(fieldConf['type'], fieldConf) self.fields.append(field)
def __init__(self, dictobj): self.Typename = dictobj["Typename"] self.FieldsAsDicts = dictobj["Fields"] self.FieldsList = [ Field(dictionary) for dictionary in self.FieldsAsDicts ]
from field import Field from player import Player from render import create_image, render_map player = Player(6, 6, 3.14159 / 4, 3.14159 / 3) field = Field() # show image img = create_image(field, player) img.show() map = render_map(field, player) map.show()
def start(): print("Welcome to the game Battlefirst_ship") name1 = input("Write the name of the first player: ") name2 = input("Write the name of the second player: ") player1 = Player(name1) player2 = Player(name2) def place_ship(field, length): x = random.randint(1, 11) y = random.randint(1, 11) horizontal = random.choice([True, False]) return Ship((x, y), horizontal, length) # first_ship_4 = Ship((1,1), True, 4) # first_ship_3_1 = Ship((6,1), False, 3) # first_ship_3_2 = Ship((2,3), True, 3) # first_ship_2_1 = Ship((8,2), True, 2) # first_ship_2_2 = Ship((2,5), False, 2) # first_ship_2_3 = Ship((4,5), False, 2) # first_ship_1_1 = Ship((3,8), True, 1) # first_ship_1_2 = Ship((7,6), True, 1) # first_ship_1_3 = Ship((8,8), True, 1) # first_ship_1_4 = Ship((5,9), True, 1) # # second_ship_4 = Ship((7,7), False, 4) # second_ship_3_1 = Ship((2,2), True, 3) # second_ship_3_2 = Ship((8,5), True, 3) # second_ship_2_1 = Ship((6,2), True, 2) # second_ship_2_2 = Ship((9,1), False, 2) # second_ship_2_3 = Ship((3,4), False, 2) # second_ship_1_1 = Ship((3,7), True, 1) # second_ship_1_2 = Ship((5,4), True, 1) # second_ship_1_3 = Ship((2,9), True, 1) # second_ship_1_4 = Ship((9,8), True, 1) # # # # first_ships = [first_ship_2_1, first_ship_2_2, first_ship_2_3, first_ship_3_1, first_ship_3_2, first_ship_4, # first_ship_1_1, first_ship_1_2, first_ship_1_3, first_ship_1_4] # second_ships = [second_ship_1_1, second_ship_1_2, second_ship_1_3, second_ship_1_4, second_ship_2_1, second_ship_2_2, # second_ship_2_3, second_ship_3_1, second_ship_3_2, second_ship_4] current_player = player1 field1 = Field([]) field2 = Field([]) def place_ship(field, length): x = random.randint(1, 10) y = random.randint(1, 10) horizontal = random.choice([True, False]) ship = Ship((x, y), horizontal, length) # print(ship.coords) x_coords = [] y_coords = [] for (x_1, y_1) in ship.coords: # print(x_1, y_1) x_coords.append(x_1) y_coords.append(y_1) # print(x_coords) for i in x_coords: if i > 10: return place_ship(field, length) for j in y_coords: if j > 10: return place_ship(field, length) for (x1, y1) in ship.coords: # print("Hello", x1, y1) if field.water[x1 - 1][y1 - 1] == "+" or field.water[x1 - 1][y1 - 1] == "*": return place_ship(field, length) field._Field__ships.append(ship) field.set_ships() place_ship(field1, 4) place_ship(field1, 3) place_ship(field1, 3) place_ship(field1, 2) place_ship(field1, 2) place_ship(field1, 2) place_ship(field1, 1) place_ship(field1, 1) place_ship(field1, 1) place_ship(field1, 1) place_ship(field2, 4) place_ship(field2, 3) place_ship(field2, 3) place_ship(field2, 2) place_ship(field2, 2) place_ship(field2, 2) place_ship(field2, 1) place_ship(field2, 1) place_ship(field2, 1) place_ship(field2, 1) def output1(name, field): print("Field of player {}".format(name)) print(" a b c d e f g h i j".upper()) for digit, line in enumerate(field.water, 1): print("{:<3}".format(digit) + " ".join(line).replace("*", "~")) def hiden_output(name, field): print("Field of player {}".format(name)) print(" a b c d e f g h i j".upper()) for digit, line in enumerate(field.field_without_ships(), 1): print("{:<3}".format(digit) + " ".join(line)) running = True while running: if current_player == player1: output1(name1, field1) hiden_output(name2, field2) hits_count = field2.combo field2.shoot_at(player1.read_position()) current_hits = field2.combo hiden_output(name2, field2) else: output1(name2, field2) hiden_output(name1, field1) hits_count = field1.combo field1.shoot_at(player1.read_position()) current_hits = field1.combo hiden_output(name1, field1) if current_hits > hits_count: current_player = current_player else: if input("Next player? (y/n): ") == "y": if current_player == player1: current_player = player2 else: current_player = player1 print("\n\n===========================\n\n") print("\n\n===========================\n\n") if field1.combo == 20: print("{} wins!".format(name2)) running = False elif field2.combo == 20: print("{} wins!".format(name1)) running = False
def start_game(): """Запуск игры""" game_start.play() base, player, level_x, level_y = generate_level(load_level(map_name)) pygame.time.set_timer(pygame.USEREVENT, 2000) enemy_shoot = pygame.USEREVENT + 0 spawn_enemies = pygame.USEREVENT + 1 random_rotate_enemies = pygame.USEREVENT + 2 spawn_bonus = pygame.USEREVENT + 3 bg_music_on = pygame.USEREVENT + 4 pygame.time.set_timer(enemy_shoot, 2000) pygame.time.set_timer(spawn_enemies, 4000) pygame.time.set_timer(random_rotate_enemies, 5000) pygame.time.set_timer(spawn_bonus, 20000) pygame.time.set_timer(bg_music_on, 4200, True) spawn_enemy = SpawnEnemy(spawn_points) field = Field(width, height) field.render(player, screen) last_shoot = 0 volume1 = 0.2 volume2 = 0.1 while True: now = pygame.time.get_ticks() for event in pygame.event.get(): if event.type == pygame.QUIT: terminate() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if now - last_shoot > player.shoot_delay: last_shoot = now x, y = player.get_position() fire.play() bullet = Bullet(x, y, player.last_direction, player) elif event.key == 61: volume1 += 0.1 volume2 += 0.1 for sound in sounds: if sound != bg: sound.set_volume(volume1) else: sound.set_volume(volume2) elif event.key == 45: volume1 -= 0.1 volume2 -= 0.1 for sound in sounds: if sound != bg: sound.set_volume(volume1) else: sound.set_volume(volume2) elif event.type == enemy_shoot: for enemy in enemies: if not enemy.died: x, y = enemy.get_position() bullet = Bullet(x, y, enemy.last_direction, enemy) else: enemies.remove(enemy) elif event.type == spawn_enemies: spawn_enemy.spawn() elif event.type == random_rotate_enemies: for enemy in enemies: enemy.collision = True elif event.type == spawn_bonus: if len(bonuses) != 0: bonuses[0].kill() bonuses.clear() bonus = Bonus() bonuses.append(bonus) elif event.type == bg_music_on: bg.play(-1) statistic(player.hp, player.kills, player.damage, player.shoot_delay) spawn_enemy.level_up() all_sprites.draw(screen) all_sprites.update() pygame.display.flip() clock.tick(FPS) if now > 300000: end_screen(True) if player.died or not base.game: player.freeze() end_screen(False)
def _callback_geometry(self, msg): Field.update(msg)
import keyboard keyboard.is_pressed("a") except: print("no keyboard library or no sudo! Showing demo") keyboard = None HEIGHT = 480 WIDTH = 640 root = Tk() root.geometry('{}x{}'.format(WIDTH, HEIGHT)) canvas = Canvas(root, width=WIDTH, height=HEIGHT) canvas.pack(fill=BOTH) player = Player(1.5, 1.5, 3.14159 / 4, 3.14159 / 3) myMap = Field() k = 0 while 1: k += 1 if (keyboard): #moving or exiting if some keys pressed if is_pressed(keyboard.is_pressed("ESC")): print(k) sys.exit(-1) if is_pressed('w'): player.x -= 0.05 * cos(player.v_dir) player.y -= 0.05 * sin(player.v_dir) if is_pressed("s"): player.x += 0.05 * cos(player.v_dir) player.y += 0.05 * sin(player.v_dir) if is_pressed("d"):
class Game: def __init__(self, player_no=0): self.field = Field() self.queue = MinoQueue() self.score = Score() self.__holding = Holding() self.layout = Layout(self.field, self.queue, self.score, self.__holding, player_no) self.mino = self.queue.get_next() self.state = GameState.PLAYING self.__reset_counter() self.player_no = player_no def update(self): removed_lines = self.field.remove_complete_lines() if len(removed_lines) > 0: self.score.count_removed(removed_lines) return if self.__is_game_over(): pyxel.stop(0) self.state = GameState.GAME_OVER self.layout.reduce_drawable_line() return self.advance_counter -= self.reduce_count if self.advance_counter <= 0: self.__advance() def draw(self): self.layout.draw(self.mino) def move(self, direction): if self.mino.can_move(self.field, direction): pyxel.play(1, 3) self.mino.move(direction) def rotate(self, direction): if self.mino.can_rotate(self.field, direction): pyxel.play(1, 5) self.mino.rotate(direction) def drop(self): while self.mino.can_move(self.field, MoveDirection.DOWN): self.mino.move(MoveDirection.DOWN) self.__put_on() def hold(self): if self.__holding.can_hold(): self.mino = self.__holding.hold(self.mino) if self.mino == None: self.mino = self.queue.get_next() def __is_game_over(self): if not self.mino.is_initial_position(): return False if self.mino.can_move(self.field, C.MoveDirection.DOWN): return False return True def __advance(self): if self.mino.can_move(self.field, MoveDirection.DOWN): self.mino.move(MoveDirection.DOWN) self.__reset_counter() else: self.__put_on() def __put_on(self): self.field.store(self.mino.blocks, self.mino.position) pyxel.play(1, 4) self.mino = self.queue.get_next() self.advance_counter += 1 self.__holding.unlock() def __reset_counter(self): self.advance_counter = C.ADVANCE_COUNTER self.reduce_count = C.REDUCE_COUNT
class DummyModel(Model): field_a = Field('text') field_b = Field('text')
def __init__(self, ast): # reset ids and lists of meta-classes: Field, Method, and Clazz fields_reset() methods_reset() classes_reset() self._frozen = False # class declarations in this template self._classes = [] # [ Clazz... ] # event involved in this template self._events = {} # [ event_kind0 : 0, ... ] self._evt_annotated = False # aux types for observer patterns self._obs_auxs = {} # { Aux...1 : [ C1, D1 ], ... } # aux types for accessor patterns self._acc_auxs = [] # [ Aux...1, ... ] # aux types for singleton pattern self._sng_auxs = [] # [ Aux...1, ... ] # primitive classes cls_obj = Clazz(pkg=u"java.lang", name=C.J.OBJ) cls_obj.sup = None # Object is the root self._classes.append(cls_obj) find_obs = lambda anno: anno.by_name(C.A.OBS) annos = [] pkg = None mods = [] events = [] for _ast in ast.getChildren(): tag = _ast.getText() if tag in [C.T.CLS, C.T.ITF, C.T.ENUM]: clazz = parse_class(_ast) clazz.annos = annos if pkg: for cls in util.flatten_classes([clazz], "inners"): cls.pkg = pkg clazz.mods = mods self._classes.append(clazz) # collect event kinds for cls in util.flatten_classes([clazz], "inners"): # 1) class itself is sort of event if cls.is_event: events.append(repr(cls)) # 2) might be annotated with explicit event sorts elif util.exists(find_obs, annos): _anno = util.find(find_obs, annos) events.extend(_anno.events) self._evt_annotated = True annos = [] pkg = None mods = [] elif tag == C.T.ANNO: annos.append(parse_anno(_ast)) elif tag == C.T.PKG: p_node = util.mk_v_node_w_children(_ast.getChildren()) pkg = util.implode_id(p_node) else: # modifiers mods.append(tag) ## parsing done ## post manipulations go below logging.debug("# class(es): {}".format(len(classes()))) logging.debug("# method(s): {}".format(len(methods()))) logging.debug("# field(s): {}".format(len(fields()))) self.consist() # remove duplicates in events events = util.rm_dup(events) if events: logging.debug("event(s) in the template: {}: {}".format( len(events), events)) # numbering the event kinds for i, event in enumerate(events): self._events[event] = i # if there exists java.util.EventObject (i.e., cmd == "gui") # no additional class is required to represent events evt_obj = class_lookup(C.GUI.EVT) if evt_obj: # artificial field to record subtype events' kinds fld = Field(clazz=evt_obj, mods=[C.mod.PB], typ=C.J.i, name=u"kind") evt_obj.flds.append(fld) else: # if there exists android.os.Message (i.e., cmd == "android") # no additional class is required, too msg = class_lookup(C.ADR.MSG) if msg: pass # o.w. introduce artificial class Event that implodes all event kinds # class Event { int kind; E_kind$n$ evt$n$; } elif events: cls_e = merge_layer(u"Event", map(class_lookup, events)) cls_e.add_default_init() self._classes.append(cls_e) add_artifacts([u"Event"])
def center_back(my_pose, ball_info, control_target, my_role, defense_num): # ゴール前ディフェンスは、ペナルティエリアに沿って守備を行う # ボールとゴールを結ぶ直線と、ペナルティエリアのラインの交点を基準に移動 # ボールの位置によって、ライン左、ライン正面、ライン右のどのラインの前に移動するか変わる # ペナルティエリアからどれだけ離れるか MARGIN_LINE = 0.2 # 2台でディフェンスする時のお互いの距離 MARGIN_ROBOT = 0 # ライン左からライン正面に移動する時等に、 # 一時的にスピードアップするための数値 MARGIN_FOR_SPEED = 0.5 # ディフェンスが2台以上いる時はMARGIN_ROBOTを変更 if defense_num > 1: if my_role == role.ROLE_ID["ROLE_CENTER_BACK_1"]: MARGIN_ROBOT = 0.15 else: MARGIN_ROBOT = -0.15 # ボール位置 ball_pose = ball_info.pose # ボールの位置判定用フラグ ball_is_center = False ball_is_left = False ball_is_right = False # 自分の位置判定用フラグ my_pose_is_left = False my_pose_is_right = False # 移動すべき場所判定用フラグ target_is_center = False target_is_left = False target_is_right = False # Field情報からペナルティエリアの情報を取得 # ペナルティエリアの左角 left_penalty_corner = Field.penalty_pose('our', 'upper_front') # ペナルティエリアの右角 right_penalty_corner = Field.penalty_pose('our', 'lower_front') # ペナルティエリアの左側のゴールラインとの交点 left_penalty_goalside = Field.penalty_pose('our', 'upper_back') # ペナルティエリアの右側のゴールラインとの交点 right_penalty_goalside = Field.penalty_pose('our', 'lower_back') # ゴールの中心 goal_center = Field.goal_pose('our', 'center') # ゴール中心からペナルティエリア左角への角度 angle_to_left_penalty_corner = tool.get_angle(goal_center, left_penalty_corner) # ゴール中心からペナルティエリア右角への角度 angle_to_right_penalty_corner = tool.get_angle(goal_center, right_penalty_corner) # 自分からボールへの角度(ボールの方向を向くため) angle_to_ball = tool.get_angle(my_pose, ball_pose) # ゴールを背にした左角を中心とした座標軸へ変換 trans_left = tool.Trans(left_penalty_corner, angle_to_left_penalty_corner) tr_left_ball_pose = trans_left.transform(ball_pose) # ゴールを背にした右角を中心とした座標軸へ変換 trans_right = tool.Trans(right_penalty_corner, angle_to_right_penalty_corner) tr_right_ball_pose = trans_right.transform(ball_pose) # ボールの位置を判定 if tr_left_ball_pose.y > 0: ball_is_left = True elif tr_right_ball_pose.y < 0: ball_is_right = True else: ball_is_center = True # --------------------------------------------------------- # キックとドリブルはOFF control_target.kick_power = 0.0 control_target.dribble_power = 0.0 # ボールは真ん中にある if ball_is_center: # ペナルティエリアの左角と右角の線分(正面の線)と、ゴール中心とボールの線分の交点 target_pose = tool.get_intersection(left_penalty_corner, right_penalty_corner, goal_center, ball_pose) if target_pose is not None: # ペナルティエリアに侵入しないように+MARGIN_LINE target_pose.x += MARGIN_LINE # ロボットが正面の線より後ろにいる if my_pose.x < left_penalty_corner.x: # ダッシュで正面に移動 target_pose.x += MARGIN_FOR_SPEED # ペナルティエリアを沿って移動 if my_pose.y > 0: target_pose.y = left_penalty_corner.y + MARGIN_LINE else: target_pose.y = right_penalty_corner.y - MARGIN_LINE else: target_pose.y += MARGIN_ROBOT else: target_pose = Pose2D() # ボールは左側にある elif ball_is_left: # ペナルティエリアの左側の線分と、ゴール中心とボールの線分の交点 target_pose = tool.get_intersection(left_penalty_corner, left_penalty_goalside, goal_center, ball_pose) if target_pose is not None: # ペナルティエリアに侵入しないように+MARGIN_LINE target_pose.y += MARGIN_LINE # ロボットが左側にいない if my_pose.y < left_penalty_corner.y: # 左側にいないかつ後ろにいる場合は右側を沿う if my_pose.x < left_penalty_corner.x and my_pose.y < 0: target_pose.x = left_penalty_corner.x + MARGIN_FOR_SPEED target_pose.y = right_penalty_corner.y - MARGIN_LINE # 左側にダッシュで移動 else: target_pose.x = left_penalty_corner.x + MARGIN_LINE target_pose.y += MARGIN_FOR_SPEED else: target_pose.x -= MARGIN_ROBOT else: target_pose = Pose2D() # ボールは右側にある elif ball_is_right: target_pose = tool.get_intersection(right_penalty_corner, right_penalty_goalside, goal_center, ball_pose) if target_pose is not None: # ペナルティエリアに侵入しないように-MARGIN_LINE target_pose.y -= MARGIN_LINE # ロボットが右側にいない if my_pose.y > right_penalty_corner.y: # 右側にいないかつ後ろにいる場合は左側を沿う if my_pose.x < left_penalty_corner.x and my_pose.y > 0: target_pose.x = left_penalty_corner.x + MARGIN_FOR_SPEED target_pose.y = left_penalty_corner.y + MARGIN_LINE # 右側にダッシュで移動 else: target_pose.x = right_penalty_corner.x + MARGIN_LINE target_pose.y -= MARGIN_FOR_SPEED else: target_pose.x += MARGIN_ROBOT else: target_pose = Pose2D() # フィールドから出ないように if target_pose.x < goal_center.x: target_pose.x = goal_center.x # 向きはボールの方向 target_pose.theta = angle_to_ball control_target.path = [] control_target.path.append(target_pose) return control_target
def get_action(self, referee, obstacle_avoidance, ball_info, robot_info=None, defense_num=0): self._control_target.control_enable = True remake_path = False # 経路再生成のフラグ TODO:remake_pathを活用する avoid_obstacle = True # 障害物回避の経路追加フラグ avoid_ball = False # ボール回避の経路追加フラグ zone_enable = False # パラメータ初期化 self._control_target.dribble_power = 0.0 self._control_target.kick_power = 0.0 if referee.can_move_robot is False or ball_info.disappeared: # 移動禁止 or ボールの消失で制御を停止する rospy.logdebug("HALT") self._control_target, remake_path= normal.stop(self._control_target) avoid_obstacle = False # 障害物回避しない elif referee.is_inplay: rospy.logdebug("IN-PLAY") zone_enable = True if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: if tool.is_in_defense_area(ball_info.pose, 'our'): self._control_target = offense.outside_shoot( self._my_pose, ball_info, self._control_target) else: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: if tool.is_in_defense_area(ball_info.pose, 'our'): # ボールが自チームのディフェンスエリアにある場合は行動を変える self._control_target = normal.move_to( self._control_target, Pose2D(0,0,0), ball_info, look_ball=True) elif tool.is_in_defense_area(ball_info.pose, 'their'): # ボールが相手チームのディフェンスエリアにある場合は行動を変える self._control_target = normal.keep_x( self._control_target, Field.penalty_pose('their', 'upper_front').x - 1.0, ball_info) else: self._control_target = offense.inplay_shoot( self._my_pose, ball_info, self._control_target) else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info, zone_enable) else: if referee.referee_id == ref.REFEREE_ID["STOP"]: rospy.logdebug("STOP") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target = offense.interpose(ball_info, self._control_target, dist_from_target=0.7) avoid_ball = True else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info) elif referee.referee_id == ref.REFEREE_ID["OUR_KICKOFF_PREPARATION"]: rospy.logdebug("OUR_KICKOFF_PREPARATION") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target, avoid_ball = offense.setplay_shoot( self._my_pose, ball_info, self._control_target, kick_enable=False) else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info) elif referee.referee_id == ref.REFEREE_ID["OUR_KICKOFF_START"]: rospy.logdebug("OUR_KICKOFF_START") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target, avoid_ball = offense.setplay_shoot( self._my_pose, ball_info, self._control_target, kick_enable=True) else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info) elif referee.referee_id == ref.REFEREE_ID["OUR_PENALTY_PREPARATION"]: rospy.logdebug("OUR_PENALTY_PREPARATION") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target, avoid_ball = offense.setplay_shoot( self._my_pose, ball_info, self._control_target, kick_enable=False) else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info) elif referee.referee_id == ref.REFEREE_ID["OUR_PENALTY_START"]: rospy.logdebug("OUR_PENALTY_START") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target, avoid_ball = offense.setplay_shoot( self._my_pose, ball_info, self._control_target, kick_enable=True, penalty=True) else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info) elif referee.referee_id == ref.REFEREE_ID["OUR_DIRECT_FREE"]: rospy.logdebug("OUR_DIRECT_FREE") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target, avoid_ball = offense.setplay_pass( self._my_pose, ball_info, self._control_target, Pose2D(Field.field('length')*0.25, 0, 0), receive_enable=True, receiver_role_exist=Observer.role_is_exist(role.ROLE_ID["ROLE_ZONE_1"]), robot_info=robot_info, direct=True) elif self._my_role == role.ROLE_ID["ROLE_ZONE_1"]: self._control_target = normal.move_to( self._control_target, Pose2D(Field.field('length')*0.25,0,0), ball_info, look_ball=True) else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info) elif referee.referee_id == ref.REFEREE_ID["OUR_INDIRECT_FREE"]: rospy.logdebug("OUR_INDIRECT_FREE") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target, avoid_ball = offense.setplay_pass( self._my_pose, ball_info, self._control_target, Pose2D(Field.field('length')*0.25, 0, 0), receive_enable=True, receiver_role_exist=Observer.role_is_exist(role.ROLE_ID["ROLE_ZONE_1"]), robot_info=robot_info) elif self._my_role == role.ROLE_ID["ROLE_ZONE_1"]: self._control_target = normal.move_to( self._control_target, Pose2D(Field.field('length')*0.25,0,0), ball_info, look_ball=True) else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info) elif referee.referee_id == ref.REFEREE_ID["OUR_TIMEOUT"]: rospy.logdebug("OUR_TIMEOUT") # 自チームのタイムアウトではロボットを停止させる self._control_target, remake_path= normal.stop(self._control_target) avoid_obstacle = False # 障害物回避しない elif referee.referee_id == ref.REFEREE_ID["OUR_BALL_PLACEMENT"]: rospy.logdebug("OUR_BALL_PLACEMENT") replace_pose = referee.placement_position if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target, avoid_ball = ball_placement.basic_ball_placement(self._control_target, replace_pose, ball_info, robot_info, self._MY_ID, 'atk', [Field.field('length'), Field.field('width')]) elif self._my_role == role.ROLE_ID["ROLE_CENTER_BACK_1"]: self._control_target, avoid_ball = ball_placement.basic_ball_placement(self._control_target, replace_pose, ball_info, robot_info, self._MY_ID, 'recv', [Field.field('length'), Field.field('width')]) else: self._control_target, avoid_ball = ball_placement.avoid_ball_place_line( self._my_pose, ball_info, replace_pose, self._control_target) elif referee.referee_id == ref.REFEREE_ID["THEIR_KICKOFF_PREPARATION"] \ or referee.referee_id == ref.REFEREE_ID["THEIR_KICKOFF_START"]: rospy.logdebug("THEIR_KICKOFF") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target = offense.interpose(ball_info, self._control_target, dist_from_target=0.6) avoid_ball = True else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info) elif referee.referee_id == ref.REFEREE_ID["THEIR_PENALTY_PREPARATION"] \ or referee.referee_id == ref.REFEREE_ID["THEIR_PENALTY_START"]: rospy.logdebug("THEIR_PENALTY") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない else: self._control_target, remake_path = normal.make_line( self._my_role, ball_info, self._control_target, start_x=-Field.field("length")*0.5, start_y=Field.field("width")*0.4, add_x=0.4, add_y=0) elif referee.referee_id == ref.REFEREE_ID["THEIR_DIRECT_FREE"]: rospy.logdebug("THEIR_DIRECT") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target = offense.interpose(ball_info, self._control_target, dist_from_target=0.6) avoid_ball = True else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info,zone_enable=True) elif referee.referee_id == ref.REFEREE_ID["THEIR_INDIRECT_FREE"]: rospy.logdebug("THEIR_INDIRECT") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target = offense.interpose(ball_info, self._control_target, dist_from_target=0.6) avoid_ball = True else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info, zone_enable=True) elif referee.referee_id == ref.REFEREE_ID["THEIR_TIMEOUT"]: rospy.logdebug("THEIR_TIMEOUT") if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: self._control_target = offense.interpose(ball_info, self._control_target, dist_from_target=0.6) avoid_ball = True else: self._control_target = assign.assign( self._my_role, ball_info, self._control_target, self._my_pose, defense_num, robot_info) elif referee.referee_id == ref.REFEREE_ID["THEIR_BALL_PLACEMENT"]: rospy.logdebug("THEIR_BALL_PLACEMENT") replace_pose = referee.placement_position if self._my_role == role.ROLE_ID["ROLE_GOALIE"]: self._control_target = goalie.interpose( ball_info, robot_info, self._control_target) avoid_obstacle = False # 障害物回避しない # elif self._my_role == role.ROLE_ID["ROLE_ATTACKER"]: # self._control_target = offense.interpose(ball_info, # self._control_target, dist_from_target=0.6) # avoid_ball = True else: self._control_target, avoid_ball = ball_placement.avoid_ball_place_line( self._my_pose, ball_info, replace_pose, self._control_target, force_avoid=True) # self._control_target = assign.assign( # self._my_role, ball_info, self._control_target, # self._my_pose, defense_num, robot_info) # 障害物回避の経路作成 if avoid_obstacle: self._control_target.path = obstacle_avoidance.add_path( self._control_target.path, self._my_pose, avoid_ball) return self._control_target
import time import traceback import transforms3d import random import numpy as np import csv from scipy.spatial import ConvexHull from types import SimpleNamespace # start the webots supervisor supervisor = Supervisor() time_step = int(supervisor.getBasicTimeStep()) field = Field("kid") children = supervisor.getRoot().getField('children') children.importMFNodeFromString(-1, f'RobocupSoccerField {{ size "kid" }}') children.importMFNodeFromString( -1, f'DEF BALL RobocupSoccerBall {{ translation 0 0 0.1 size 1 }}') children.importMFNodeFromString( -1, f'DEF PLAYER RoboCup_GankenKun {{translation -0.3 0 0.450 rotation 0 0 1 0 controller "play_motion" controllerArgs "./kick_motion0.csv"}}' ) player = supervisor.getFromDef('PLAYER') ball = supervisor.getFromDef('BALL') player_translation = supervisor.getFromDef('PLAYER').getField('translation') player_rotation = supervisor.getFromDef('PLAYER').getField('rotation') player_controller = supervisor.getFromDef('PLAYER').getField('controller') ball_translation = supervisor.getFromDef('BALL').getField('translation') ball_rotation = supervisor.getFromDef('BALL').getField('rotation')
def main(): bewd = Monster( "Blue-Eyes White Dragon", "This legendary dragon is a " "powerful engine of destruction. Virtually invincible, very few have " "faced this awesome creature and lived to tell the tale.", 8, 3000, 2500) dm = Monster("Dark Magician", "The ultimate wizard in terms of attack and " "defense.", 7, 2500, 2100) rebd = Monster("Red-Eyes Black Dragon", "", 7, 2400, 2000) bls = Monster("Black Luster Soldier", "", 8, 3000, 2500) ss = Monster("Summoned Skull", "", 6, 2500, 1200) dmg = Monster("Dark Magician Girl", "", 6, 2000, 1700) fgd = Monster("Five Headed Dragon", "", 12, 5000, 5000) cg = Monster("Celtic Guardian", "", 4, 1400, 1200) cod = Monster("Curse of Dragon", "", 5, 2000, 1500) gtfk = Monster("Gaia the Fierce Knight", "", 7, 2300, 2100) obelisk = Monster("Obelisk the Tormentor", "", 12, 4000, 4000) slifer = Monster("Slifer the Sky Dragon", "", 12, 4000, 4000) ra = Monster("The Winged Dragon of Ra", "", 12, 4000, 4000) kuriboh = Monster("Kuriboh", "", 1, 300, 200) cardlist = [ bewd, dm, rebd, bls, ss, dmg, fgd, cg, cod, gtfk, obelisk, slifer, ra, kuriboh ] deck_list1 = DeckList() for monster in cardlist: for i in range(3): deck_list1.add_card(monster) deck_list2 = DeckList() for monster in cardlist: for i in range(3): deck_list2.add_card(monster) # These variables initialize the classes need to set up the Duel. deck1 = Deck(deck_list1) deck2 = Deck(deck_list2) hand1 = [] hand2 = [] field1 = Field() field2 = Field() gy1 = [] gy2 = [] lp1 = 8000 lp2 = 8000 turn_count = 0 phase = "DP" turn_player_idx = 0 player1 = Player(1, hand1, gy1, deck1, field1, lp1) player2 = Player(2, hand2, gy2, deck2, field2, lp2) players = [player1, player2] winner = None # These functions start the Duel using the variables defined above. # Both decks are shuffled and both players draw 5 cards. deck1.shuffle() deck2.shuffle() player1.draw(5) player2.draw(5) print("DUEL START") # This while loop contols the actions that the players can take in the # Duel. It will not close until the Duel is over (i.e. a Player's # LifePoints hit 0, a Player can't draw any more cards, etc...) while player1.get_lp() > 0 and player2.get_lp() > 0 and not winner: # This section prints out the visualtion of the current state of # of the Duel (i.e. Turn Count, Each Player's Hand, Field, LP, etc...) print("\n\n=====================================================") print("TURN: {}".format(turn_count + 1)) turn_player = players[turn_player_idx] opposite_player_idx = abs(turn_player_idx - 1) opposite_player = players[abs(turn_player_idx - 1)] # This section handles the logic of the Draw Phase. # If the player can draw a card, they draw it. If not the game is over # and the opponent wins. Also, in this phase all action locks are # reset. (i.e. Monsters not being able to Attack or change their # Positions) phase = "DP" if turn_player.can_draw(): print("Player {player_id_1} draws a card".format( player_id_1=turn_player.get_id())) turn_player.draw(1) else: print("Player {player_id_1} cannot draw.".format( player_id_1=turn_player.get_id(), player_id_2=opposite_player.get_id())) winner = opposite_player.get_id() for monster in turn_player.get_field().monster_zones: if monster != None: monster.unlock_attack() monster.unlock_position() turn_player.set_can_summon(True) # This section adds the intial actions the Player can take during # the Main Phase. After choosing from the selections the user enters # the actions while loop and choose from those choices until their # turn is over. phase = "MP" possible_moves = [] if turn_player.get_can_summon(): possible_moves.append("Summon") possible_moves.append("Set") if turn_player.can_change_pos(): possible_moves.append("Change Battle Position") if turn_player.can_battle() and turn_count > 0: possible_moves.append("Go to Battle Phase") possible_moves.append("End Turn") # This loop tells the Player what actions they can currently take. # It uses an input prompt so the Player can select an action. while possible_moves: print("OPPONENT'S FIELD:") print("{} LP".format(opposite_player.get_lp())) print("HAND: {}".format(["x"] * len(opposite_player.get_hand()))) print("DECK: {}".format(len(opposite_player.get_deck()))) print(opposite_player.get_field().hidden()) print("YOUR FIELD:") print("{} LP".format(turn_player.get_lp())) print("DECK: {}".format(len(turn_player.get_deck()))) print(turn_player.get_field()) print("HAND: {}".format(turn_player.get_hand())) print("You can do the following moves:") for i in range(len(possible_moves)): print("[{idx}] {action}".format(idx=i, action=possible_moves[i])) choice = try_int_input("What would you like to do: ") while choice >= len(possible_moves) or choice < 0: choice = try_int_input("Please enter a valid choice: ") # This section handles the logic for actions the Player can take # during their Main Phase. # Summon: If able, summon a monster from your hand in Face-up # Attack Position. # Set: If able, set a monster from your hand in Face-down Defense # Position. # Change Battle Position: If able, change the Position of a # monster you control. (i.e. Attack to Defense, Face-down Defense # to Face-up Attack, etc...) # Go to Battle Phase: Go to Battle Phase. if (possible_moves[choice] == "Summon" or possible_moves[choice] == "Set"): possible_monsters = [] possible_monsters = turn_player.get_hand() for i in range(len(possible_monsters)): print("[{idx}] {monster} " "[{attack} ATK / {defense} DEF]".format( idx=i, monster=possible_monsters[i].get_name(), attack=possible_monsters[i].get_atk(), defense=possible_monsters[i].get_def())) monster_choice = try_int_input( "Which card would you like to {}: ".format( possible_moves[choice])) while (monster_choice >= len(possible_monsters) or monster_choice < 0): monster_choice = try_int_input( "Please enter a valid choice: ") open_idx = turn_player.get_field().get_open_zones()[0] summon_monster = turn_player.get_hand().pop(monster_choice) if possible_moves[choice] == "Summon": turn_player.get_field().summon(summon_monster, open_idx) turn_player.set_can_summon(False) print("{monster} has been Summoned".format( monster=summon_monster.get_name())) if possible_moves[choice] == "Set": turn_player.get_field().set(summon_monster, open_idx) turn_player.set_can_summon(False) print("{monster} has been Set".format( monster=summon_monster.get_name())) elif possible_moves[choice] == "Change Battle Position": possible_monsters = [] possible_monsters = turn_player.get_field()\ .get_can_change_pos() monster_zones = turn_player.get_field().monster_zones for i in range(len(possible_monsters)): print("[{idx}] {monster} [{attack} ATK / {defense} DEF]"\ .format( idx=i, monster=monster_zones[possible_monsters[i]]\ .get_name(), attack=monster_zones[possible_monsters[i]]\ .get_atk(), defense=monster_zones[possible_monsters[i]]\ .get_def())) monster_choice = try_int_input( "Which card would you like to change position: ") while (monster_choice >= len(possible_monsters) or monster_choice < 0): monster_choice = try_int_input( "Please enter a valid choice: ") pos_change_monster = \ monster_zones[possible_monsters[monster_choice]] pos_change_monster.change_pos() elif possible_moves[choice] == "Go to Battle Phase": phase = "BP" # This section handles the logic for actions the Player can take # during their Battle Phase. # Attack: If able, the Player's monster can either attack the # opponent's monster or the opponent directly if they have no # monsters. elif possible_moves[choice] == "Attack": possible_monsters = [] possible_monsters = turn_player.get_field().get_can_attack() monster_zones = turn_player.get_field().monster_zones for i in range(len(possible_monsters)): print("[{idx}] {monster} {stat} {pos}".format( idx=i, monster=monster_zones[possible_monsters[i]].get_name(), stat=monster_zones[possible_monsters[i]].get_stat(), pos=monster_zones[ possible_monsters[i]].get_position())) monster_choice = try_int_input( "Which card would you like to attack with: ") while (monster_choice >= len(possible_monsters) or monster_choice < 0): monster_choice = try_int_input( "Please enter a valid choice: ") attacker = monster_zones[possible_monsters[monster_choice]] attacker_idx = possible_monsters[monster_choice] possible_targets = [] possible_targets = opposite_player.get_field().get_monsters() opp_monster_zones = opposite_player.get_field().monster_zones if len(possible_targets): for i in range(len(possible_targets)): print("[{idx}] {monster} {stat} {pos}".format( idx=i, monster=( "???" if opp_monster_zones[possible_targets[i]]\ .get_is_set() else opp_monster_zones[possible_targets[i]]\ .get_name() ), stat=( "SET" if opp_monster_zones[possible_targets[i]]\ .get_is_set() else opp_monster_zones[possible_targets[i]]\ .get_stat() ), pos=( opp_monster_zones[possible_targets[i]].\ get_position() ) )) target_choice = try_int_input( "Which card would you like to attack: ") while (target_choice >= len(possible_targets) or target_choice < 0): target_choice = try_int_input( "Please enter a valid choice: ") target = opp_monster_zones[possible_targets[target_choice]] target_idx = possible_targets[target_choice] battle_result = battle(attacker, target) print( "{attacker} [{attacker_stat} ATTACK] " "ATTACKS {target} [{target_stat} {target_pos}]"\ .format( attacker=attacker.get_name(), attacker_stat=attacker.get_atk(), target=target.get_name(), target_stat=target.get_stat(), target_pos=target.get_position() ) ) # The following sections handle the logic of battle and # its result. Depending on the result of battle a monster # may be destroyed, LifePoints may be lost, etc... # This section handles the logic for the battle scenario # in which the attacker wins against an Attack Position # target. if battle_result[0] and battle_result[1] > 0: print( "{attacker} WINS. {target} DESTROYED"\ .format( attacker=attacker.get_name(), target=target.get_name() ) ) opposite_player.get_gy().append(opposite_player\ .get_field()\ .remove(attacker_idx) ) opposite_player.change_lp(-1 * battle_result[1]) attacker.lock_attack() # This section handles the logic for the battle scenario # in which the attacker loses against an Attack Position # target. elif battle_result[0] and battle_result[1] < 0: print( "{target} WINS. {attacker} DESTROYED"\ .format( attacker=attacker.get_name(), target=target.get_name() ) ) turn_player.get_gy().append(turn_player.get_field()\ .remove(target_idx) ) turn_player.change_lp(battle_result[1]) # This section handles the logic for the battle scenario # in which the attacker ties with an Attack Position # target. elif battle_result[0] and battle_result[1] == 0: print( "BATTLE TIE. {attacker} and {target} DESTROYED"\ .format( attacker=attacker.get_name(), target=target.get_name() ) ) turn_player.get_gy().append(turn_player.get_field()\ .remove(attacker_idx) ) opposite_player.get_gy().append(opposite_player\ .get_field()\ .remove(target_idx) ) # This section handles the logic for the battle scenario # in which the attacker loses to a Defense Position # target. elif not battle_result[0] and battle_result[1] < 0: print( "{attacker} LOSES. {target} NOT DESTROYED"\ .format( attacker=attacker.get_name(), target=target.get_name() ) ) turn_player.change_lp(battle_result[1]) attacker.lock_attack() if target.get_is_set(): target.flip() # This section handles the logic for the battle scenario # in which the attacker wins against a Defense Position # target. elif not battle_result[0] and battle_result[1] > 0: print( "{attacker} WINS. {target} DESTROYED"\ .format( attacker=attacker.get_name(), target=target.get_name() ) ) opposite_player.get_gy().append(opposite_player\ .get_field()\ .remove(target_idx) ) attacker.lock_attack() # This section handles the logic for the battle scenario # in which the attacker ties with a Defense Position # target. else: print("NO MONSTERS DESTROYED") if target.get_is_set(): target.flip() attacker.lock_attack() else: # This section handles the logic for the battle scenario # in which the opponent has no monsters and the attacker # attacks directly. print( "{attacker} attacks Player {player} directly"\ .format( attacker=attacker.get_name(), player=opposite_player.get_id() ) ) damage = -1 * attacker.get_atk() opposite_player.change_lp(damage) attacker.lock_attack() # This section checks if either Players' LifePoints are 0 # after battle. If one of the Players' LifePoints is 0 the # Duel ends and the other Player wins. if turn_player.get_lp() <= 0: turn_player.set_lp(0) winner = opposite_player.get_id() break elif opposite_player.get_lp() <= 0: opposite_player.set_lp(0) winner = turn_player.get_id() break # This section handles the logic for actions the Player can take # at any Phase in the Duel. # End Turn: Go to End Phase and start opponent's turn. elif possible_moves[choice] == "End Turn": phase = "EP" # This section clears the Player's possible actions and then adds # new possible actions based on the game state. # i.e. Game Phase, Turn Count, actions already taken, etc... possible_moves = [] if phase == "MP": if turn_player.get_can_summon(): possible_moves.append("Summon") possible_moves.append("Set") if turn_player.can_change_pos(): possible_moves.append("Change Battle Position") if turn_player.can_battle() and turn_count > 0: possible_moves.append("Go to Battle Phase") possible_moves.append("End Turn") elif phase == "BP": if turn_player.can_battle(): possible_moves.append("Attack") possible_moves.append("End Turn") elif phase == "EP": # This section handles the logic of the End Phase. # If players have more than 6 cards they must discard down to # 6. The turn count is incremented and then the turn player # is changed the opposite player. while len(turn_player.get_hand()) > 6: current_hand = turn_player.get_hand() for i in range(len(current_hand)): print( "[{idx}] {card} [{attack} ATK / {defense} DEF]"\ .format( idx=i, card=current_hand[i].get_name(), attack=current_hand[i].get_atk(), defense=current_hand[i].get_def() ) ) choice = try_int_input( "Too many cards in your hand. You have {}, you can " "only have up to 6. Which card will you discard: ".\ format(len(current_hand)) ) while choice > len(current_hand) or choice < 0: choice = try_int_input("Please enter a valid choice: ") current_hand.pop(choice) turn_count += 1 turn_player_idx = opposite_player_idx else: print("You shouldn't be here.") # After the Duel loop ends, the name of the winner is printed. print("PLAYER {} WINS!".format(winner))
def defense_zone(my_pose, ball_info, control_target, my_role, defense_num, their_robot_info, zone_enable): # ゴールディフェンスに割り当てる台数 GOAL_DEFENSE_NUM = 2 # 現在のディフェンス数 - ゴールディフェンス数 = ゾーンディフェンスに割り当てられる台数 ZONE_DEFENSE_NUM = defense_num - GOAL_DEFENSE_NUM # ゾーンディフェンスが始まるROLE_ID ZONE_START_ROLE_ID = role.ROLE_ID["ROLE_ZONE_1"] # ゾーンオフェンス用の待機場所 ZONE_OFFENCE_POSE = Pose2D(Field.field('length') * 0.25, 0, 0) # センターライン用のマージン MARGIN_CENTER = 0.6 # ちょっと前進用のマージン MARGIN_LITTLE_FORWARD = 1.0 # ドリブルパワー DRIBBLE_POWER = 0.6 # ボール位置 ball_pose = ball_info.pose # Field情報からペナルティエリアの情報を取得 # フィールド幅 field_width = Field.field('width') # フィールド幅の半分 half_field_width = float(field_width) / 2 # フィールド幅の1/4 quarter_field_width = float(field_width) / 4 # フィールド長さ field_length = Field.field('length') # フィールド長さの1/4 → 自陣側の長さの半分 half_our_field_length = -float(field_length) / 4 # ゴール中心 goal_center = Field.goal_pose('our', 'center') # ペナルティエリアの角 left_penalty_corner = Field.penalty_pose('our', 'upper_front') right_penalty_corner = Field.penalty_pose('our', 'lower_front') # 自分からボールへの角度(ボールの方向を向くため) angle_to_ball = tool.get_angle(my_pose, ball_pose) # ゴール中心からボールへの角度 angle_to_ball_from_goal = tool.get_angle(goal_center, ball_pose) # ゾーンディフェンス用のID zone_id = None # 移動目標点の初期化 target_pose = Pose2D() # --------------------------------------------------------- # キックとドリブルはOFF control_target.kick_power = 0.0 control_target.dribble_power = 0.0 # ゾーンオフェンス判定用フラグ my_role_is_offence = False # ボールが相手フィールドにあるとき # ゾーンから1台ゾーンオフェンスに出す # 相手キックオフ時などに前に出ないように # マージンを持って相手フィールド側かを判断している if ZONE_DEFENSE_NUM > 1 and ball_pose.x > MARGIN_CENTER: # 1台ディフェンスが減る ZONE_DEFENSE_NUM -= 1 # ゾーンディフェンスが始まるROLE_IDをずらす ZONE_START_ROLE_ID = role.ROLE_ID["ROLE_ZONE_2"] # ROLE_ZONE_1をゾーンオフェンスとして出す if my_role is role.ROLE_ID["ROLE_ZONE_1"]: my_role_is_offence = True # 私はゾーンオフェンスです if my_role_is_offence: zone_id = 0 target_pose = ZONE_OFFENCE_POSE # 基本的にアタッカーがボールを取りに行くので # ボールが無い方向に移動してこぼれ球が取れるようにする if ball_pose.y > 0: target_pose.y = -quarter_field_width else: target_pose.y = quarter_field_width # ボールを向く target_pose.theta = angle_to_ball # ゾーンオフェンス以外 if ZONE_DEFENSE_NUM > 0 and not my_role_is_offence: step = float(field_width) / (ZONE_DEFENSE_NUM * 2) # ゾーンディフェンスの数でフィールド幅を等分した配列を作る split_field = [ i * step - half_field_width for i in range(0, (ZONE_DEFENSE_NUM * 2 + 1)) ] # ゾーンディフェンスの数でフィールド幅を等分した時の # それぞれのゾーンの中心の配列を作る split_field_center = [i * step - half_field_width for i in range(0,(ZONE_DEFENSE_NUM * 2)) \ if i % 2 != 0] # 参照エラー対策のtry try: # ゾーンIDの計算 # ロボットが8台生きていてゾーンオフェンスがいなければ # ゾーンIDは0~3 zone_id = my_role - ZONE_START_ROLE_ID # ゾーンの中心を目標位置とする target_pose.y = split_field_center[zone_id] # 自分のゾーンに入っている敵チェック # their_robot_infoのposeを抜き出してそれぞれチェック # 敵が自陣側にいる、かつ、自分のゾーンの幅の中にいる、を確認 # 当てはまらない場合配列は空っぽ invader_pose = [i.pose for i in their_robot_info \ if split_field[zone_id * 2] < i.pose.y < split_field[(zone_id + 1) * 2] and \ i.pose.x < 0] # ボールが自分のゾーンの中に入っている, かつzone_enable if(zone_enable and \ ball_pose.x < 0 and \ split_field[zone_id * 2] < ball_pose.y < split_field[(zone_id + 1) * 2]): trans = tool.Trans(ball_pose, angle_to_ball_from_goal) target_pose = trans.inverted_transform(Pose2D(-0.9, 0, 0)) # 自分のゾーンにボールはないけど敵がいる場合は割り込む elif zone_enable and invader_pose != []: # 敵とボールの間に割り込む angle_to_ball_from_invader = tool.get_angle( invader_pose[0], ball_pose) trans = tool.Trans(invader_pose[0], angle_to_ball_from_invader) target_pose = trans.inverted_transform(Pose2D(0.5, 0, 0)) else: # ボールが敵陣の時はディフェンスちょっと前進 if ball_pose.x > MARGIN_CENTER: target_pose.x = half_our_field_length + MARGIN_LITTLE_FORWARD else: target_pose.x = half_our_field_length except IndexError: target_pose = my_pose target_pose.theta = angle_to_ball # ボールが来てたらボールを受け取る if zone_id != None: receive_ball_result, receive_target_pose = defense.update_receive_ball( ball_info, my_pose, zone_id) if receive_ball_result: # ドリブラー回す control_target.dribble_power = DRIBBLE_POWER target_pose = receive_target_pose else: # ボールに近づいてたら離れる target_pose = defense.get_avoid_ball_pose(ball_pose, target_pose) # ペナルティエリアには入らない if((left_penalty_corner.y + 0.2 > target_pose.y > right_penalty_corner.y - 0.2) and \ target_pose.x < left_penalty_corner.x + 0.3): target_pose.x = half_our_field_length control_target.path = [] control_target.path.append(target_pose) return control_target
h, w, _ = array.shape array = np.flip(array, 0) img = pyglet.image.ImageData(width=w, height=h, format="RGB", data=bytes(array)) text = img.get_texture() gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST) text.width = int(size[0]) text.height = int(size[1]) return text t = Template('GLIDER', figures.gliderDiagonalNE) f = Field((160, 90)) f.fillRandom() f.placeTemplate(t, (2, 2)) def update(dt): f.update() g = GUI(f) pyglet.clock.schedule_interval(update, 1.0 / 100.0) g.run() #------- #------- #--#----